API reference

Generated by tools/gen_api_reference.py from the public members of the sources. Do not edit by hand. Conventions: time is counted in ticks, angles are in degrees. Guide with examples: Manual. The classes of skarph.core are the engine and are the same on every platform; the Android platform layer (skarph.android) is listed at the end. The desktop layer is described in Manual, section 14.

Loop and input

Engine

skarph.core.Engine - Platform independent engine core.

MemberDescription
static final String VERSIONThe engine version.
final InputQueue input
final Stats stats
void setAssets(Assets assets)Set by the platform layer.
void setAudio(Audio audio)Set by the platform layer.
Audio getAudio()Sound output.
void setStorage(Storage storage)Set by the platform layer.
Storage getStorage()Persistent storage for settings and saved games.
synchronized Http getHttp()HTTP and HTTPS for fetching small pieces of information in the background (see Http).
synchronized void setHttp(Http http)Replaces the network (options of a UrlHttp, or a fake in tests); null brings the default back.
synchronized void releaseHttp()Called by the platform layer when the program ends: stops the network thread, if one was ever started.
Assets getAssets()Access to the application's data files (textures, models, levels).
void setScreen(Screen s)Switch screen.
void frame(long nowNanos, Renderer r)
void pause()Call on the render thread when the app is paused (sent to the background, window minimized).
void resume()Call on the render thread when the app comes back.
long getTotalTicks()

Screen

skarph.core.Screen - One state of the application (menu, level, tool view...).

MemberDescription
void init(Engine engine, Renderer renderer)
void update()One logic tick (1/60 s).
void render(Renderer renderer)
void pause()
void resume()
void dispose()

ScreenAdapter

skarph.core.ScreenAdapter - Convenience base class: empty implementations of the optional callbacks.

MemberDescription
void init(Engine engine, Renderer renderer)
void pause()
void resume()
void dispose()

TickClock

skarph.core.TickClock - Fixed-rate tick scheduler: exactly 60 logic ticks per second.

MemberDescription
static final int TICKS_PER_SECOND
static final int MAX_CATCHUP_TICKSProtection against the "spiral of death" after long stalls.
void reset()Forget the previous timestamp (call after pause / long stalls).
int poll(long nowNanos)Returns how many ticks must be executed now (0..MAX_CATCHUP_TICKS).
long getTotalTicks()

InputEvent

skarph.core.InputEvent - Reusable input event holder (filled by InputQueue.poll).

MemberDescription
static final int DOWN
static final int UP
static final int MOVE
int type
int pointer
float x
float y

InputQueue

skarph.core.InputQueue - Fixed-size ring buffer of input events.

MemberDescription
InputQueue(int capacity)
synchronized void push(int type, int pointer, float x, float y)
synchronized boolean poll(InputEvent out)Returns false if the queue is empty.
synchronized void clear()
synchronized int size()

TouchState

skarph.core.TouchState - Tracks which fingers are down and where (up to MAX_POINTERS pointer ids), and measures pinch gestures.

MemberDescription
static final int MAX_POINTERS
void feed(InputEvent e)
int getDownCount()
boolean isDown(int id)
float getX(int id)
float getY(int id)
float getStartX(int id)
float getStartY(int id)
float getDragDistance(int id)Distance moved since the finger went down.
int getPointerId(int n)Returns the id of the n-th (0 based) finger that is down, or -1.
void reset()
float getPinchDistance()Current distance between the first two fingers, or -1 unless exactly two fingers are down.
float consumePinch()How much the two-finger distance changed since the last call (positive = fingers moved apart, in pixels).

TouchDecoder

skarph.core.TouchDecoder - Turns the raw data of a touch event (as delivered by the platform, including multi-touch) into DOWN / MOVE / UP events with pointer ids in an InputQueue.

MemberDescription
static final int ACTION_DOWN
static final int ACTION_UP
static final int ACTION_MOVE
static final int ACTION_CANCEL
static final int ACTION_POINTER_DOWN
static final int ACTION_POINTER_UP
static void decode(int action, int actionIndex, int count, int[] ids, float[] xs, float[] ys, InputQueue queue)

Stats

skarph.core.Stats - Frames-per-second and ticks-per-second counters, updated once per second.

MemberDescription
int fps
int tps
boolean changedSet to true every time fps/tps were refreshed.
long nowNanosTime stamp of the current frame (the value given to Engine.frame()), for code that needs frame times, e.g.

Math

Vec3

skarph.core.Vec3 - Mutable 3D vector.

MemberDescription
float x
float y
float z
Vec3()
Vec3(float x, float y, float z)
Vec3 set(float x, float y, float z)
Vec3 set(Vec3 v)
Vec3 add(Vec3 v)
Vec3 sub(Vec3 v)
Vec3 scale(float s)
float dot(Vec3 v)
Vec3 cross(Vec3 a, Vec3 b)this = a x b (safe if this is a or b).
float length()
Vec3 normalize()

Mat4

skarph.core.Mat4 - 4x4 float matrix, column-major (same layout as OpenGL): element at row r, column c is m[c * 4 + r].

MemberDescription
final float[] m
Mat4()
Mat4 setIdentity()
Mat4 set(Mat4 o)
Mat4 multiply(Mat4 a, Mat4 b)this = a * b (safe if this is a or b).
Mat4 translate(float x, float y, float z)this = this * Translation(x, y, z)
Mat4 scale(float x, float y, float z)this = this * Scale(x, y, z)
Mat4 rotate(float angleDeg, float x, float y, float z)this = this * Rotation(angleDegrees, axis).
Mat4 rotateX(float angleDeg)this = this * RotationX(angleDegrees).
Mat4 rotateY(float angleDeg)this = this * RotationY(angleDegrees).
Mat4 rotateZ(float angleDeg)this = this * RotationZ(angleDegrees).
Mat4 setPerspective(float fovyDeg, float aspect, float near, float far)Perspective projection (like gluPerspective).
Mat4 setOrtho(float l, float r, float b, float top, float near, float far)Orthographic projection (like glOrtho).
Mat4 setLookAt(float ex, float ey, float ez, float cx, float cy, float cz, float ux, float uy, float uz)View matrix (like gluLookAt).
boolean setInverse(Mat4 src)this = inverse of src (src may be this).
void transformPoint(Vec3 v)Transforms a point in place (affine part only, w is assumed 1).

FastMath

skarph.core.FastMath - Table based sine/cosine in DEGREES (much cheaper than Math.sin/cos on old devices).

MemberDescription
static float sin(float degrees)
static float cos(float degrees)

Aabb

skarph.core.Aabb - Axis-aligned bounding box.

MemberDescription
float minX
float minY
float minZ
float maxX
float maxY
float maxZ
Aabb set(float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
Aabb setCenterHalf(float cx, float cy, float cz, float hx, float hy, float hz)Box from its center and half extents.
boolean overlaps(Aabb o)
boolean contains(float x, float y, float z)
float centerX()
float centerY()
float centerZ()

Ray

skarph.core.Ray - Ray with a normalized direction.

MemberDescription
float ox
float oy
float oz
float dx
float dy
float dz
Ray set(float ox, float oy, float oz, float dx, float dy, float dz)Sets origin and direction (the direction is normalized here).
void pointAt(float t, Vec3 out)Writes the point at distance t into out.
float intersectSphere(float cx, float cy, float cz, float radius)
float intersectAabb(Aabb box)Slab test.
float intersectPlaneY(float planeY)Intersection with the horizontal plane y = planeY.

RayHit

skarph.core.RayHit - Result of PhysicsWorld.raycast(): the nearest body hit, the distance and the hit point.

MemberDescription
Body body
float t
float x
float y
float z

Memory tools

Pool

skarph.core.Pool - Fixed-size object pool.

MemberDescription
Pool(Factory<T> factory, int capacity)
T obtain()
void free(T obj)
int getFreeCount()
int getCapacity()

Nested: Pool.Factory

MemberDescription
E create()

Nested: Pool.Poolable - Optional: objects implementing this are reset() when returned to the pool.

MemberDescription
void reset()

IntList

skarph.core.IntList - Fixed-capacity list of ints (no boxing, no allocation after construction).

MemberDescription
IntList(int capacity)
boolean add(int value)Returns false if the list is full.
int get(int index)
void set(int index, int value)
int size()
int capacity()
void clear()
int indexOf(int value)
boolean contains(int value)
void removeAt(int index)Removes the element and keeps the order (O(n)).
void removeSwap(int index)Removes the element by moving the last one into its place (O(1), order changes).

IntIntMap

skarph.core.IntIntMap - Fixed-capacity hash map int -> int (open addressing, no boxing, no allocation after construction).

MemberDescription
IntIntMap(int capacity)
boolean put(int key, int value)Returns false if the map is full and the key is new.
int get(int key, int defaultValue)
boolean containsKey(int key)
boolean remove(int key)
int size()
void clear()

TextBuffer

skarph.core.TextBuffer - Preallocated char buffer for building text without String concatenation.

MemberDescription
TextBuffer(int capacity)
TextBuffer clear()
TextBuffer append(char c)
TextBuffer append(String s)
TextBuffer append(int value)
TextBuffer append(long value)
TextBuffer append(float value, int decimals)Appends a float with a fixed number of decimals (0..9).
int length()
char charAt(int index)
int getChars(char[] dst)Copies the text into dst (must be large enough).
String toString()Allocates a new String.

Rendering

Renderer

skarph.core.Renderer - Backend independent rendering interface (implemented by the platform layer).

MemberDescription
String getBackendName()Human readable name of the backend, for example "OpenGL ES 2.0 (shaders)".
int getWidth()
int getHeight()
int createMesh(MeshData data)Registers a mesh.
int loadTexture(String assetPath, boolean smooth)Loads a PNG from the app assets into a texture.
int loadTexture(String assetPath, boolean smooth, boolean repeat)Same, with a wrap mode: repeat = true tiles the texture (for UVs outside 0..1), false clamps at the edges.
void deleteTexture(int texture)Frees the texture.
void deleteMesh(int mesh)Frees the mesh.
void setMeshTextures(int mesh, int diffuseTexture, int lightmapTexture)Binds textures to a mesh that has texture coordinates: diffuse uses uv0, the lightmap uses uv1 and is multiplied with the diffuse color.
boolean supportsLightmaps()True if the device can draw lightmaps (needs two texture units).
void setLightmapsEnabled(boolean enabled)Turns lightmaps on/off globally (off = only the diffuse texture, handy for comparison).
int getTextureWidth(int texture)
int getTextureHeight(int texture)
void clear(float r, float g, float b)Clears color and depth buffers.
int getDrawCalls()Number of draw calls (meshes and quad batches) issued since the last clear().
int getTriangles()Number of triangles sent to the GPU since the last clear().
boolean usesBufferObjects()True if meshes are stored in GPU buffer objects (VBO, OpenGL ES 1.1+).
void setLighting(boolean enabled)Turns lighting on/off for meshes drawn afterwards (only meshes with normals are lit).
void setAmbientLight(float r, float g, float b)Ambient light color (0..1).
void setDirectionalLight(float dx, float dy, float dz, float r, float g, float b)The single directional light.
void setFog(boolean enabled, float start, float end, float r, float g, float b)Linear distance fog for the meshes drawn afterwards (sprites and quads are never fogged).
void setCamera(Mat4 projection, Mat4 view)Sets projection and view matrices for the following draw calls.
void drawSky(int mesh)Draws a sky mesh around the camera: the view translation is dropped (the sky never gets closer), and depth test, lighting and fog are off, so draw it FIRST, right after clear() and setCamera(), and everything else covers it.
void drawBillboards(int texture, float[] data, int count, boolean additive)Draws camera facing 3D sprites (smoke, sparks, flares) of one texture in a single draw call.
void drawMesh(int mesh, Mat4 model)Draws a mesh with the given model matrix.
void drawQuads(int texture, float[] vertices, int quadCount)Draws textured, tinted, alpha-blended 2D quads (depth test off).

Camera

skarph.core.Camera - Camera: projection + view matrices and the view frustum used for culling.

MemberDescription
final Mat4 projection
final Mat4 view
float eyeX
float eyeY
float eyeZ
Camera setPerspective(float fovyDeg, float aspect, float near, float far)
Camera setOrtho(float left, float right, float bottom, float top, float near, float far)
Camera lookAt(float ex, float ey, float ez, float cx, float cy, float cz, float ux, float uy, float uz)
void updateFrustum()Recomputes the frustum planes.
boolean screenToRay(float sx, float sy, int viewW, int viewH, Ray out)Converts a screen position (pixels, origin top-left, y down) into a world space ray, for picking.
boolean isSphereVisible(float x, float y, float z, float radius)Returns false only if the sphere is completely outside the frustum.

Shapes

skarph.core.Shapes - Builders for simple meshes (with normals).

MemberDescription
static MeshData cube(float size)Cube centered at the origin with a different color per face.
static MeshData cube(float size, float r, float g, float b)Cube centered at the origin, one color.
static MeshData sphere(float radius, int segments, int rings, float r, float g, float b)UV sphere centered at the origin, one color, smooth normals.

MeshData

skarph.core.MeshData - Backend independent mesh data: positions (xyz), optional normals (xyz, unit length, needed for lighting), colors (rgba, 0..1) and triangle indices.

MemberDescription
final float[] positions
final float[] normalsMay be null: such a mesh is never lit.
final float[] colors
final float[] uv0Diffuse texture coordinates (u, v per vertex), or null.
final float[] uv1Lightmap texture coordinates (u, v per vertex), or null.
final short[] indices
MeshData(float[] positions, float[] colors, short[] indices)
MeshData(float[] positions, float[] normals, float[] colors, short[] indices)
MeshData(float[] positions, float[] normals, float[] colors, float[] uv0, float[] uv1, short[] indices)
int getVertexCount()
int getIndexCount()

Sky

skarph.core.Sky - A cheap sky: a low poly dome (sphere) around the camera, colored per vertex with a gradient zenith (up) - horizon (eye level) - nadir (down).

MemberDescription
Sky(Renderer r, float radius, int segments, int rings, float zr, float zg, float zb, float hr, float hg, float hb, float nr, float ng, float nb)Builds the dome mesh in the renderer (allocates: call it during init).
int getMesh()The mesh handle in the renderer, or -1 if the mesh table was full.
void draw(Renderer r)Draws the sky (call first in the frame).
void release(Renderer r)Frees the mesh.
static MeshData dome(float radius, int segments, int rings, float zr, float zg, float zb, float hr, float hg, float hb, float nr, float ng, float nb)Dome mesh without normals (never lit): one vertex at each pole and a ring of segments vertices per latitude in between.

Billboards

skarph.core.Billboards - Turns billboard records (see Renderer.drawBillboards) into camera facing quads.

MemberDescription
static final int VERTEX_FLOATSFloats per vertex of the result: x, y, z, u, v, r, g, b, a.
static void expand(float[] src, int count, float[] view, float[] out)

BillboardBatch

skarph.core.BillboardBatch - Collects 3D billboards and sends them to the renderer in as few draw calls as possible (one per texture or blend mode change, or per Renderer.MAX_BILLBOARDS).

MemberDescription
BillboardBatch(Renderer renderer, int maxBillboards)
void begin()
void end()
void setColor(float r, float g, float b, float a)Tint and alpha for the following billboards (1,1,1,1 = unchanged).
void setAdditive(boolean additive)true = add the colors to the screen (fire, sparks), false = alpha blending (smoke).
int getDrawCalls()Number of renderer draw calls issued since the last begin().
void draw(TextureRegion reg, float x, float y, float z, float w, float h)A billboard of size w x h (world units) centered at (x, y, z), showing the whole region.
void drawFlat(TextureRegion reg, float x, float y, float z, float w, float depth)A flat quad lying on the ground (y = height of the plane): w along x, depth along z, the top of the region towards -z.

2D

SpriteBatch

skarph.core.SpriteBatch - Collects 2D sprites and sends them to the renderer in as few draw calls as possible (one per texture change).

MemberDescription
SpriteBatch(Renderer renderer, int maxSprites)
void begin(Mat4 projection)
void end()
void setColor(float r, float g, float b, float a)Tint and alpha for the following sprites (1,1,1,1 = unchanged).
int getDrawCalls()Number of renderer draw calls issued since the last begin().
void draw(TextureRegion reg, float x, float y)
void draw(TextureRegion reg, float x, float y, float w, float h)
void drawRotated(TextureRegion reg, float cx, float cy, float w, float h, float angleDeg)Draws a sprite of size w x h centered at (cx, cy), rotated by angleDeg (clockwise on a y-down screen).

TextureRegion

skarph.core.TextureRegion - A rectangle inside a texture (a sprite, a frame, a font glyph).

MemberDescription
int texture
float u0
float v0
float u1
float v1
float widthSize in pixels.
float height
TextureRegion set(int texture, int texW, int texH, int x, int y, int w, int h)Pixel rectangle (x, y from the top-left corner of the image).
static TextureRegion[] grid(int texture, int texW, int texH, int cellW, int cellH, int cols, int rows)Splits a texture into a grid of equal cells (sprite sheet).

FrameAnimation

skarph.core.FrameAnimation - Frame-by-frame animation.

MemberDescription
FrameAnimation(TextureRegion[] frames, int ticksPerFrame, boolean loop)
TextureRegion getFrame(int ticks)
boolean isFinished(int ticks)Always false for looping animations.
int getDurationTicks()

BitmapFont

skarph.core.BitmapFont - Fixed-width bitmap font.

MemberDescription
BitmapFont(TextureRegion[] glyphs, int firstChar)
void setScale(float scale)
float getLineHeight()
float getTextWidth(int chars)
void draw(SpriteBatch batch, String text, float x, float y)
void draw(SpriteBatch batch, TextBuffer text, float x, float y)

Ui

skarph.core.Ui - Small retained-mode UI: panels, labels, buttons, toggles and sliders drawn with the SpriteBatch and BitmapFont, with touch handling (multi-touch aware), anchors for different screen shapes and "pages" (groups of widgets shown one at a time).

MemberDescription
static final int LABEL
static final int BUTTON
static final int TOGGLE
static final int SLIDER
static final int PANEL
static final int LEFT
static final int CENTER
static final int RIGHT
static final int TOP
static final int MIDDLE
static final int BOTTOM
static final int ALWAYSGroup of widgets that are shown on every page.
final float[] colPanel
final float[] colBorder
final float[] colButton
final float[] colButtonDown
final float[] colDisabled
final float[] colOn
final float[] colOff
final float[] colText
final float[] colTextDisabled
final float[] colTrack
final float[] colKnob
Ui(int maxWidgets, int textCapacity, SpriteBatch batch, BitmapFont font, TextureRegion white)
void setListener(Listener listener)
void setViewport(float virtualW, float virtualH, int screenW, int screenH)Call at start-up and whenever the screen size changes.
int addPanel(float px, float py, float pw, float ph, int anchorX, int anchorY)Returns widget id, or -1 if the capacity is exhausted (same for all add methods).
int addLabel(String label, float px, float py, int anchorX, int anchorY, float textScale)
int addButton(String label, float px, float py, float pw, float ph, int anchorX, int anchorY, float textScale)
int addToggle(String label, float px, float py, float pw, float ph, int anchorX, int anchorY, float textScale, boolean isChecked)
int addSlider(float px, float py, float pw, float ph, int anchorX, int anchorY, float initial)
void clear()
int getCount()
TextBuffer text(int id)The widget's text.
void setText(int id, String s)
void setVisible(int id, boolean v)
void setEnabled(int id, boolean e)
boolean isEnabled(int id)
void setBlocking(int id, boolean b)A blocking panel swallows touches that land on it (for dialogs and backgrounds).
void setChecked(int id, boolean c)
boolean isChecked(int id)
void setValue(int id, float v)Sets a slider position (0..1) without calling the listener.
float getValue(int id)
boolean isPressed(int id)
void setGroup(int id, int g)Assigns a widget to a page.
void showGroup(int g)Shows only the widgets of this page (plus the ALWAYS ones).
int getActiveGroup()
boolean isShown(int id)
float getRectX(int id)Resolved rectangle of a widget in virtual units (labels: valid after the first draw).
float getRectY(int id)
float getRectW(int id)
float getRectH(int id)
boolean handle(InputEvent e)Feed every input event.
void draw()Draws all shown widgets.

Nested: Ui.Listener

MemberDescription
void onClick(int id)A button was released inside its bounds, or a toggle changed (see isChecked).
void onValueChanged(int id, float value)A slider was moved by the user.

Scene and content

Scene

skarph.core.Scene - Scene graph with a fixed node capacity (all nodes are created up front, so createNode()/destroyNode() never allocate).

MemberDescription
final Node root
boolean cullingEnabledSkip nodes whose bounding sphere is outside the camera frustum.
boolean lightingEnabledSimple lighting: one directional light plus ambient.
float lightDxDirection the light travels (from the light into the scene).
float lightDy
float lightDz
float lightR
float lightG
float lightB
float ambientR
float ambientG
float ambientB
int statTotalStatistics of the last render(): drawable nodes, drawn, culled.
int statDrawn
int statCulled
Scene(int maxNodes)
Node createNode(Node parent)Creates a node under the given parent (null = scene root).
void destroyNode(Node n)Destroys a node together with all its children; the slots can be reused.
int getFreeNodes()
void update()Recomputes world transforms of changed nodes.
void render(Renderer r, Camera camera)Draws all visible nodes that have a mesh.

Node

skarph.core.Node - Scene graph node: a transform, an optional mesh and a bounding sphere.

MemberDescription
int meshMesh handle from Renderer.createMesh(), or -1 for an empty (group) node.
boolean visibleLocal visibility; a hidden node hides its whole subtree.
float boundRadiusRadius of the mesh bounding sphere in local units (mesh is assumed centered at its origin).
float x
float y
float z
float rx
float ry
float rz
float sx
float sy
float sz
final Mat4 world
float worldX
float worldY
float worldZ
float worldRadius
boolean worldVisible
Node getParent()
Node setPosition(float x, float y, float z)
Node setRotation(float rx, float ry, float rz)Euler angles in degrees.
Node setScale(float sx, float sy, float sz)

Level

skarph.core.Level - A level loaded from a level file by LevelLoader: remembers what it created so that unload() can remove it again.

MemberDescription
static final int MAX_OBJECTS
static final int MAX_SPAWNS
static final int MAX_BODIES
float camTargetXCamera hints from the file: orbit target, distance and height.
float camTargetY
float camTargetZ
float camRadius
float camHeight
final float[] spawnsSpawn points, 3 floats each.
int spawnCount
int getObjectCount()
Node getNode(int i)
ResourceManager.Model getModel(int i)
int getBodyCount()
void unload(Scene scene, PhysicsWorld world, ResourceManager res)Removes the level's nodes and bodies and releases its models.

LevelLoader

skarph.core.LevelLoader - Loads a level from a text file.

MemberDescription
static Level load(byte[] data, ResourceManager res, Scene scene, PhysicsWorld world)

ModelData

skarph.core.ModelData - A model loaded from a model file: geometry plus the names of its textures.

MemberDescription
final MeshData mesh
final String diffuseTextureDiffuse texture file name, or null.
final String lightmapTextureLightmap texture file name, or null.
final float boundRadiusRadius of the sphere around the model origin that contains all vertices.
ModelData(MeshData mesh, String diffuseTexture, String lightmapTexture)

ModelFormat

skarph.core.ModelFormat - Binary model file formats.

MemberDescription
static final int FLAG_NORMALS
static final int FLAG_COLORS
static final int FLAG_UV0
static final int FLAG_UV1
static final int FLAG_PRECISEMDL2 only: positions, normals and UVs are float32 instead of 16 bit / 8 bit.
static final int FLAG_DEFLATEMDL2 only: the body after the header is a zlib stream.
static ModelData parse(byte[] data)Parses an MDL1 or MDL2 file.
static byte[] writeMdl2(ModelData m, boolean precise)Serializes a model as MDL2 (used by tests and Java based tools).
static byte[] write(ModelData m)Serializes a model as MDL1: exact, but big (used by tests and Java based tools).

ResourceManager

skarph.core.ResourceManager - Loads textures and models by file name and caches them with reference counting: asking for the same file twice returns the same GPU resource, and the resource is freed when every user has released it.

MemberDescription
ResourceManager(Assets assets, Renderer renderer, int maxTextures, int maxModels)
String getLastError()Description of the last failure, or null.
int getTextureCount()
int getModelCount()
int getTotalRefs()Sum of all reference counts (textures + models).
int getTexture(String name, boolean smooth, boolean repeat)Returns renderer texture handle (reference counted), or -1 on failure (see getLastError()).
void releaseTexture(int handle)
Model getModel(String name)Loads a model file (and its textures) or returns the cached one.
void releaseModel(Model m)

Nested: ResourceManager.Model - A loaded model: a renderer mesh handle plus its bounding radius.

MemberDescription
final String name
final int meshMesh handle for Node.mesh.
final float boundRadiusLocal bounding radius for Node.boundRadius.
final int diffuseTexture
final int lightmapTexture
boolean hasLightmap()

Assets

skarph.core.Assets - Platform independent access to the application's data files.

MemberDescription
byte[] readBytes(String path)Reads a whole file.

Physics

PhysicsWorld

skarph.core.PhysicsWorld - Small rigid body world: spheres and axis-aligned boxes (no rotation), gravity, bouncing, simple friction, a bounded arena (walls and floor) and ray casting.

MemberDescription
static final int SPHERE
static final int BOX
float gravityYAcceleration along y in units per tick^2 (negative = down).
float dampingVelocity multiplier per tick (air resistance).
float floorFrictionFraction of horizontal speed lost per tick while on the floor.
float contactFrictionFraction of relative sliding speed removed per contact between bodies.
float wallRestitutionBounciness of the arena walls and floor.
float maxSpeedPer-axis speed limit in units per tick.
int solverIterations
boolean useGridfalse = test all pairs (slow, for comparison); true = use the grid.
int statPairTestsStatistics of the last step().
int statPairs
int statContacts
int statDropped
PhysicsWorld(int maxBodies, float minX, float minY, float minZ, float maxX, float maxY, float maxZ, float cellSize)
Body createSphere(float x, float y, float z, float radius, float mass)
Body createBox(float x, float y, float z, float hx, float hy, float hz, float mass)
void destroyBody(Body b)
int getBodyCount()
int getFreeBodies()
void step()Advances the simulation by one tick.
boolean raycast(Ray ray, float maxDist, RayHit hit)Finds the nearest body hit by the ray within maxDist.

Body

skarph.core.Body - A physics body: a sphere or an axis-aligned box (boxes never rotate).

MemberDescription
float x
float y
float z
float vx
float vy
float vz
float radiusSphere radius (SPHERE bodies).
float hxBox half extents (BOX bodies).
float hy
float hz
float invMass0 = static (never moves), otherwise 1 / mass.
float restitutionBounciness 0..1.
int tagFree to use for your own purposes (for example an index into your arrays).
boolean onFloorTrue if the body touched the floor during the last step.
final Aabb boundsWorld-space box, refreshed every step.
int getType()
boolean isActive()
boolean isStatic()
void updateBounds()

Collision

skarph.core.Collision - Narrow-phase tests between spheres and axis-aligned boxes.

MemberDescription
static boolean sphereSphere(float ax, float ay, float az, float ar, float bx, float by, float bz, float br, Contact c)
static boolean sphereAabb(float cx, float cy, float cz, float r, Aabb box, Contact c)Normal points from the sphere toward the box.
static boolean aabbAabb(Aabb a, Aabb b, Contact c)Normal points from a toward b along the axis of least penetration.

Contact

skarph.core.Contact - Result of a narrow-phase test: unit normal pointing from the first shape to the second, and the penetration depth.

MemberDescription
float nx
float ny
float nz
float depth

SpatialGrid

skarph.core.SpatialGrid - Uniform 3D grid for the broad phase: finds which objects can possibly touch without testing every pair.

MemberDescription
SpatialGrid(float minX, float minY, float minZ, float cellSize, int cellsX, int cellsY, int cellsZ, int maxObjects, int maxEntries)
void clear()
boolean insert(int id, Aabb b)Returns false if the id is out of range or the entry table is full.
int findPairs(int[] out, int maxPairs)Finds all pairs of inserted objects whose boxes overlap.
int getPairTests()Number of box-vs-box tests done by the last findPairs() (for statistics).
int query(Aabb box, int[] out)Writes the ids of all inserted objects whose box overlaps the given box into out.

Effects and cutscenes

ParticleSystem

skarph.core.ParticleSystem - 3D particles on a fixed pool (sparks, smoke, dust).

MemberDescription
ParticleSystem(int capacity)
boolean emit(ParticleType type, float x, float y, float z, float vx, float vy, float vz, int lifeTicks)One particle at (x, y, z) with velocity (units per tick) living lifeTicks ticks.
int burst(ParticleType type, float x, float y, float z, int n, float speed, int lifeMin, int lifeMax)A burst of count particles flying in random directions with speed 0.5..1 x speed, life lifeMin..lifeMax ticks.
void update()One logic tick: move, apply gravity and drag, age, remove the dead.
void draw(BillboardBatch bb, Camera cam)Sends every particle to the batch (call between bb.begin() and bb.end(); the batch color/blend are changed).
void clear()Removes all particles.
int getActiveCount()
int getCapacity()
void setSeed(int seed)Seed of the random numbers used by burst() (same seed = same effect).

ParticleType

skarph.core.ParticleType - Look and physics of one kind of particle (spark, smoke, dust).

MemberDescription
final FrameAnimation animationFrames chosen by particle age in ticks (frame by frame, no interpolation).
boolean additivetrue = colors are added (fire, sparks, flares), false = alpha blending (smoke, dust).
float gravityAdded to the vertical speed every tick (world units per tick per tick).
float dragSpeed multiplier per tick, 1 = no air resistance, 0.95 = slows down quickly.
float sizeStartBillboard size (world units) at birth and at the end of life; the size follows the age.
float sizeEnd
float rTint.
float g
float b
float alphaStartAlpha at birth and at the end of life.
float alphaEnd
ParticleType(FrameAnimation animation)
ParticleType(TextureRegion region)One fixed region.

CameraTrack

skarph.core.CameraTrack - A pre-recorded camera path for cutscenes: exactly ONE pose per tick (60 per second), no interpolation at run time (the same rule as frame animation).

MemberDescription
static final int FLOATS
static final int EYE_X
static final int EYE_Y
static final int EYE_Z
static final int TARGET_X
static final int TARGET_Y
static final int TARGET_Z
static final int FOV
static final int MAX_TICKSOne hour at 60 ticks per second.
CameraTrack(float[] poses, int count)
static CameraTrack parse(byte[] data)
byte[] toBytes()
int getTickCount()
boolean isFinished(int tick)true when the tick is past the last pose (the camera then stays on the last pose).
float get(int tick, int field)One value of the pose of the tick (EYE_X ..
void apply(int tick, Camera cam)Puts the camera on the pose of the tick (view matrix and frustum).
float getFov(int tick)

Timeline

skarph.core.Timeline - A cutscene timeline: a list of scenes, each starting at a tick, all inside one tick range 0..endTick.

MemberDescription
static final int TPS
static final int MAX_SCENES
static final int MAX_NAME
Timeline(int[] starts, String[] names, int count, int endTick)
static Timeline parse(String text)
int getSceneCount()
int getStart(int scene)First tick of the scene.
int getEnd(int scene)First tick AFTER the scene (the start of the next scene, or the end of the timeline).
String getName(int scene)
int getEndTick()First tick after the whole timeline.
boolean isFinished(int tick)true when the tick is at or past the end (a negative tick is not finished, it is before the start).
int sceneAt(int tick)Index of the scene that runs at the tick, or -1 before the start and from the end on.
int getSceneTick(int tick)Ticks since the start of the scene that runs at the tick, or -1 if no scene runs.

Diagnostics and quality

Profiler

skarph.core.Profiler - Frame statistics as ready-to-draw text, without allocations.

MemberDescription
void setGcCount(int total)Total number of GC runs of the process so far.
void frame(Stats stats, Renderer r)Reads the counters of the frame that was just drawn and refreshes the text if needed.
TextBuffer getText()Three lines: FPS and TPS, draw calls and triangles, GC runs since reset.
int getDrawCalls()
int getTriangles()
int getMaxDrawCalls()
int getMaxTriangles()
int getGcCount()GC runs since the first setGcCount() after construction or reset().
void reset()Forgets the maximums and restarts the GC count from the current value.

Benchmark

skarph.core.Benchmark - Frame time benchmark: average and minimum FPS and a score for a fixed run.

MemberDescription
static final int WARMUPFrames at the start of a run that are left out of the minimum.
void start()
void stop()Aborts or ends the run; the results are computed from the frames seen so far.
void frame(long nowNanos)Call once per frame while running (ignored when not running).
boolean isRunning()
int getFrames()
float getSeconds()Seconds from the first to the last frame so far.
float getAvgFps()Valid after stop(); 0 if fewer than 2 frames were seen.
float getMinFps()
int getScore()

QualityGovernor

skarph.core.QualityGovernor - Automatic quality level for old devices.

MemberDescription
static final int WARMUP_SECONDS
int lowerBelowFps
int lowerSeconds
int raiseAtFps
int raiseSeconds
QualityGovernor(int levels, int startLevel)
int getLevel()
int getFps()Frames per second of the last full second window (0 before the first one).
int getCeiling()The highest level the governor will still try (lowered after a level turned out too slow).
void setLevel(int l)Sets the level by hand (for example from a menu); the warm up starts again.
void reset()Forget everything learned (the ceiling, the counters).
boolean frame(long nowNanos)Call once per rendered frame.

Sound, saving and network

Audio

skarph.core.Audio - Platform independent sound.

MemberDescription
int loadSound(String assetPath)Loads a short sound effect (loading may continue in the background).
void unloadSound(int sound)
int playSound(int sound, float volume, float pitch, boolean loop)Plays an effect.
void stopStream(int stream)
boolean playMusic(String assetPath, boolean loop)Starts streaming music (stops the previous track).
void stopMusic()
void setMusicVolume(float volume)
boolean isMusicPlaying()
void pauseAll()Called by the engine when the app is paused.
void resumeAll()Called by the engine when the app is resumed.
void release()Frees every native resource (call when the program ends).

NullAudio

skarph.core.NullAudio - Audio that does nothing: the default, so code never needs null checks (also used in tests).

MemberDescription
int loadSound(String assetPath)
void unloadSound(int sound)
int playSound(int sound, float volume, float pitch, boolean loop)
void stopStream(int stream)
boolean playMusic(String assetPath, boolean loop)
void stopMusic()
void setMusicVolume(float volume)
boolean isMusicPlaying()
void pauseAll()
void resumeAll()
void release()

Storage

skarph.core.Storage - Persistent private storage for small files (settings, saved games).

MemberDescription
byte[] load(String name)Returns the file contents, or null if it does not exist.
boolean save(String name, byte[] data)Writes (replaces) a file.
boolean delete(String name)

MemoryStorage

skarph.core.MemoryStorage - Storage kept in memory only: the default (and handy for tests).

MemberDescription
byte[] load(String name)
boolean save(String name, byte[] data)
boolean delete(String name)

Settings

skarph.core.Settings - Small typed key/value store (int, float, boolean, String) that can be saved to a Storage file and loaded back.

MemberDescription
Settings(int capacity)
int size()
boolean putInt(String key, int value)All put methods return false if the store is full and the key is new.
boolean putBoolean(String key, boolean value)
boolean putFloat(String key, float value)
boolean putString(String key, String value)
int getInt(String key, int def)
boolean getBoolean(String key, boolean def)
float getFloat(String key, float def)
String getString(String key, String def)
boolean contains(String key)
void clear()
byte[] toBytes()
int fromBytes(byte[] data)Parses data written by toBytes(), adding the entries.
boolean save(Storage storage, String name)
boolean load(Storage storage, String name)Returns false if the file does not exist.

Http

skarph.core.Http - Simple HTTP and HTTPS for slow but reliable fetching and sending of small pieces of information (news, a version file, a leaderboard, a configuration; GET to fetch, POST to send, for example a score).

MemberDescription
HttpRequest get(String url)Starts a GET request in the background.
HttpRequest post(String url, byte[] body, String contentType)Starts a POST request in the background: sends body (null = empty) with the given Content-Type (null = application/octet-stream) and collects the server's answer like #get does.
void release()Stops the background work: unfinished requests fail.

HttpRequest

skarph.core.HttpRequest - One HTTP request and its outcome.

MemberDescription
static final int PENDINGStill queued or running (retries included).
static final int OKFinished with a 2xx answer: #getBody() is set.
static final int FAILEDFinished without an answer or with an error status: #getError() says why.
static final int CANCELLEDStopped by #cancel().
static HttpRequest completed(String url, int statusCode, byte[] body, String contentType)A request that is already finished with a successful answer (for fakes in tests).
static HttpRequest failed(String url, int statusCode, String error)A request that is already finished and failed (statusCode 0 = no answer at all).
String getMethod()"GET" or "POST".
String getUrl()The URL that was asked for (redirects are not reflected here).
int getState()#PENDING, #OK, #FAILED or #CANCELLED.
boolean isDone()True when the request is over, whatever the outcome.
boolean isSuccess()True when the request finished with a 2xx answer.
int getStatusCode()The last HTTP status code received (404, 200, ...), 0 while there is none.
byte[] getBody()The answer, or null unless #isSuccess().
String getText()The answer as UTF-8 text (allocates), or null unless #isSuccess().
String getContentType()The Content-Type header of the answer, or null when there is none or the request did not succeed.
String getError()What went wrong, or null unless the state is #FAILED.
int getAttempts()How many times the request was tried so far (1 = no retry was needed).
int getReceivedBytes()Bytes of the answer received so far in the current attempt (for a progress bar).
int getTotalBytes()Size of the answer from its Content-Length header, -1 while unknown.
void cancel()Gives up on the request: it is over at once (state #CANCELLED, no body) and the background thread abandons the connection.

UrlHttp

skarph.core.UrlHttp - Http on java.net.HttpURLConnection: the same code on Android and on the desktop, HTTPS included (certificates are checked by the platform).

MemberDescription
UrlHttp setTimeouts(int connectMillis, int readMillis)Connect and read timeout in milliseconds (a read timeout counts the silence between two pieces of data).
UrlHttp setAttemptTimeout(int millis)Upper limit for one attempt from the start to the last byte, in milliseconds (default 60000).
UrlHttp setRetries(int maxAttempts, int retryDelayMillis)How often a request is tried in total (1 = never repeat, default 3) and the pause before the second try (default 1000 ms; before the third it is twice as long, and so on).
UrlHttp setMaxBytes(int bytes)Largest accepted answer in bytes (default 8 MiB).
UrlHttp setMaxUploadBytes(int bytes)Largest body of a POST in bytes (default 1 MiB); a bigger one fails at once.
UrlHttp setMaxRedirects(int count)How many redirects are followed (default 5).
UrlHttp setUserAgent(String agent)The User-Agent header (default "Skarph/" and the engine version).
HttpRequest get(String url)
HttpRequest post(String url, byte[] body, String contentType)
void release()

Android platform layer

EngineView

skarph.android.EngineView - GLSurfaceView hosting the engine.

MemberDescription
static final int BACKEND_AUTO
static final int BACKEND_GLES1
static final int BACKEND_GLES2
void run()
void run()
EngineView(Context context, Engine engine)
EngineView(Context context, Engine engine, int requestedBackend)
static boolean isGles2Supported(Context context)True if this device can run the OpenGL ES 2.0 backend (Android 2.3+ and ES 2.0 reported).
int getBackend()Returns BACKEND_GLES1 or BACKEND_GLES2: the backend this view really uses.
void setBackendListener(BackendListener listener)
void onPause()
void onResume()
void destroy()Call from Activity.onDestroy(): releases the sound resources and stops the network thread.
boolean onTouchEvent(MotionEvent e)

Nested: EngineView.BackendListener - Called on the UI thread when the OpenGL ES 2.0 backend cannot work on this device.

MemberDescription
void onBackendFailed(EngineView view, String reason)

AndroidVersion

skarph.android.AndroidVersion - Android version without Build.VERSION.SDK_INT (that field exists only since API 4 / Android 1.6).

MemberDescription
static final int SDKThe API level of the running device (3 for Android 1.5).

GLES1Renderer

skarph.android.GLES1Renderer - OpenGL ES 1.x backend (fixed pipeline).

MemberDescription
void setVboEnabled(boolean enabled)Disable VBOs (call before the first frame) if a device misbehaves.
GLES1Renderer(Engine engine, AssetManager assets)
void onSurfaceCreated(GL10 gl, EGLConfig config)
void onSurfaceChanged(GL10 gl, int w, int h)
void onDrawFrame(GL10 gl)
String getBackendName()
int getWidth()
int getHeight()
int createMesh(MeshData data)
void deleteMesh(int mesh)
void setMeshTextures(int mesh, int diffuseTexture, int lightmapTexture)
boolean supportsLightmaps()
void setLightmapsEnabled(boolean enabled)
int loadTexture(String assetPath, boolean smooth)
int loadTexture(String assetPath, boolean smooth, boolean repeat)
void deleteTexture(int texture)
int getTextureWidth(int texture)
int getTextureHeight(int texture)
boolean usesBufferObjects()
void setLighting(boolean enabled)
void setAmbientLight(float r, float g, float b)
void setDirectionalLight(float dx, float dy, float dz, float r, float g, float b)
void setFog(boolean enabled, float start, float end, float r, float g, float b)
int getDrawCalls()
int getTriangles()
void clear(float r, float g, float b)
void setCamera(Mat4 projection, Mat4 view)
void drawSky(int mesh)
void drawMesh(int mesh, Mat4 model)
void drawQuads(int texture, float[] vertices, int quadCount)
void drawBillboards(int texture, float[] data, int count, boolean additive)

GLES2Renderer

skarph.android.GLES2Renderer - OpenGL ES 2.0 backend (programmable pipeline), the counterpart of GLES1Renderer.

MemberDescription
GLES2Renderer(Engine engine, Gl2 gl, GlImageLoader images, GlLog log, FailureListener listener)
void onSurfaceCreated()The GL context was created (or recreated): set the state and rebuild every GL object.
void onSurfaceChanged(int w, int h)
void onDrawFrame()
boolean hasFailed()
String getBackendName()
int getWidth()
int getHeight()
boolean usesBufferObjects()
boolean supportsLightmaps()
void setLightmapsEnabled(boolean enabled)
void setLighting(boolean enabled)
void setAmbientLight(float r, float g, float b)
void setDirectionalLight(float dx, float dy, float dz, float r, float g, float b)
void setFog(boolean enabled, float start, float end, float r, float g, float b)
int getDrawCalls()
int getTriangles()
void clear(float r, float g, float b)
void setCamera(Mat4 projection, Mat4 view)
void drawSky(int mesh)
int createMesh(MeshData data)
void deleteMesh(int mesh)
void setMeshTextures(int mesh, int diffuseTexture, int lightmapTexture)
void drawMesh(int mesh, Mat4 model)
static void normalMatrix(Mat4 model, float[] out)Normal matrix = inverse transpose of the upper left 3x3 of the model matrix (column-major, written to out[0..8]).
void drawQuads(int texture, float[] vertices, int quadCount)
void drawBillboards(int texture, float[] data, int count, boolean additive)
int loadTexture(String assetPath, boolean smooth)
int loadTexture(String assetPath, boolean smooth, boolean repeat)
void deleteTexture(int texture)
int getTextureWidth(int texture)
int getTextureHeight(int texture)

Nested: GLES2Renderer.FailureListener - Told when the backend cannot work on this device.

MemberDescription
void onFailure(String reason)

AndroidAssets

skarph.android.AndroidAssets - skarph.core.Assets backed by the Android assets folder.

MemberDescription
AndroidAssets(AssetManager manager)
byte[] readBytes(String path)

AndroidAudio

skarph.android.AndroidAudio - skarph.core.Audio for Android: SoundPool for short effects (loaded asynchronously by the system, so playSound() returns -1 until a sound is ready) and MediaPlayer for streamed music.

MemberDescription
AndroidAudio(AssetManager assets)
synchronized int loadSound(String assetPath)
synchronized void unloadSound(int sound)
synchronized int playSound(int sound, float volume, float pitch, boolean loop)
synchronized void stopStream(int stream)
synchronized boolean playMusic(String assetPath, boolean loop)
synchronized void stopMusic()
synchronized void setMusicVolume(float volume)
synchronized boolean isMusicPlaying()
synchronized void pauseAll()
synchronized void resumeAll()
synchronized void release()

AndroidStorage

skarph.android.AndroidStorage - skarph.core.Storage backed by the app's private internal files (no permissions needed).

MemberDescription
AndroidStorage(Context context)
byte[] load(String name)
boolean save(String name, byte[] data)
boolean delete(String name)

AndroidGc

skarph.android.AndroidGc - Source of the GC run count for Profiler.setGcCount().

MemberDescription
static int count()

AndroidLog

skarph.android.AndroidLog - GlLog that writes to logcat with the tag "skarph".

MemberDescription
void info(String message)
void warn(String message)
void error(String message)

BitmapImageLoader

skarph.android.BitmapImageLoader - GlImageLoader for Android: decodes PNGs from assets with BitmapFactory, uploads with GLUtils.

MemberDescription
BitmapImageLoader(AssetManager assets)
GlImage load(String assetPath)

Internal and platform classes

Not meant to be called by games: AndroidGl2, BitmapOptionsCompat, GLES2Shaders, GLES2SurfaceRenderer, Gl2, GlImage, GlImageLoader, GlLog, Gles2Setup, MultiTouchHandler.