bitty

Reference Manual

Manual Physics Operations Others

Table of Content

TOP

Fundamental

Specifications

TOP

Project Structure

A new created project consists of a meta info asset (“info.json”) and an entry source (“main.lua”). The meta info indicates basic information of the project in JSON. The entry is where the project starts to execute. You can add supported existing file or create new blank assets into a project. All text-based assets use Unix LF (‘\n’) for line ending.

Note that it requires external programs to open file dialogs on Linux for opening, saving, exporting, etc. Make sure that at least one of the following is available: “zenity”, “kdialog”, “matedialog”, “qarma”.

In Directory

All assets are stored as raw files under a specific directory in this format.

Text-based Archive

A text-based project archive is a plain text file with the “*.bit” extension, with all assets encoded in printable UTF-8 characters or Base64 string. This format uses Unix LF (‘\n’) for line ending.

Binary-based Archive

A binary-based project archive is just a compressed ZIP package replaced with the “*.bit” extension.

TOP

Backup

Bitty Engine makes backup once you save an asset or a project, click “Project”, “Browse Data Directory…” to locate it.

TOP

Capturing

There are shortcuts to capture canvas during running.

Screenshot

GIF

TOP

Programming

Lua

Bitty project is programmable in the Lua programming language.

Syntax

Lua is widely used and validated in the software industry, there are a lot of learning materials about the language on the internet. Click to see on the Wikipedia or read the official documentations.

Lua is 1-based for list accessing, Bitty Engine follows the same convention for sequenced structures, like Bytes, File, etc. Otherwise it is 0-based for coordinates and graphical units, like Noiser, Pathfinder, Image, Sprite, Palette, Map, etc.

This document uses a meta method form to describe operators. Eg. foo:__len() denotes #foo, foo:__add(bar) denotes foo + bar, foo:__unm() denotes -foo, etc. Just write the symbol form #, +, -, etc. in your calculation.

Additionally, this is not about the syntax, but for description convenience in this document, optional parameter is described between square brackets [optional]; default value is appended after an equal sign foo = 42; variadic list is described as ....

Memory Management

Lua uses GC to free unused memory automatically, thus you don’t have to do so manually most of the time. However resources loaded by Resources.load(...) are not, consider unloading them properly. See Resources for details.

Standard Libraries

The ready to use modules, package, coroutine, math, table, string, utf8, debug are reserved from the original language.

The trivial modules, io, os are removed. Bitty Engine offers alternatives.

Bitty Engine offers some handy built-in functions, some are reserved from the original but the behaviour is improved, some are extended.

Functions

TOP

Program Structure

A conventional entry program of Bitty project is made up of a setup function which is called once program starts, and an update which is called periodically:

function setup()
end

function update(delta)
end

Define another quit function to run code on execution termination:

function quit()
end

Define focusLost, focusGained functions to run code on focus changed:

function focusLost()
end

function focusGained()
end

Define a fileDropped function to run code on file dropped:

function fileDropped(paths) -- For desktop only.
end

Define a rendererReset function to run code on renderer reset:

function rendererReset()
end

Define a call function for callback from JavaScript to Lua (for HTML build only). See Invoking for details.

function call()
end

Generally setup is used to initial game variables, states, update is where gameplay logic and rendering goes, and quit is for persisting necessary data on disk. All these entries above are optional.

Bitty Engine uses a timeout mechanism to avoid unexpected infinite loops, it raises an error when any invoking to the entries takes more than 10 seconds by default. The timeout value can be changed by Debug.setTimeout(…).

TOP

Libraries

Algorithms

Noiser

This module generates 2D or 3D noise values.

Constructors

Methods

Available options:

Key Value Note
“frequency” Real number Defaults to 0.01
“noise_type” Can be one in “open_simplex2”, “open_simplex2s”, “cellular”, “perlin”, “value_cubic”, “value” Defaults to “open_simplex2”
“rotation_type_3d” Can be one in “none”, “improve_xy_planes”, “improve_xz_planes” Defaults to “none”
“fractal_type” Can be one in “none”, “fbm”, “ridged”, “pingpong”, “domain_warp_progressive”, “domain_warp_independent” Defaults to “none”
“fractal_octaves” Integer Defaults to 3
“fractal_lacunarity” Real number Defaults to 2.0
“fractal_gain” Real number Defaults to 0.5
“fractal_weighted_strength” Real number Defaults to 0.0
“fractal_pingpong_strength” Real number Defaults to 2.0
“cellular_distance_function” Can be one in “euclidean”, “euclidean_sq”, “manhattan”, “hybrid” Defaults to “euclidean_sq”
“cellular_return_type” Can be one in “cell_value”, “distance”, “distance2”, “distance2_add”, “distance2_sub”, “distance2_mul”, “distance2_div” Defaults to “distance”
“cellular_jitter” Real number Defaults to 1.0
“domain_warp_type” Can be one in “open_simplex2”, “open_simplex2_reduced”, “basic_grid” Defaults to “open_simplex2”
“domain_warp_amplitude” Real number Defaults to 1.0

Pathfinder

This module performs a pathfinding algorithm on 2D grids.

Constructors

Object Fields

Methods

Grid coordinates can be any integer, with range of values from -32,767 to 32,767. A cost matrix will be prefilled once calling the pathfinder:set(...) function; this data exists until calling pathfinder:clear(). The pathfinder:solve(...) function prefers to use invokable to get grid cost, and falls to use prefilled matrix if no evaluator provided. Call pathfinder:clear() before solving in either way, if any grid data has been changed.

Walking cost is combined with two parts by multiplicative: neighbor cost and map cost. Neighbor cost stands for how much does it cost to walk from the current grid to its neighbor directions as following, in which D defaults to 1.414:

 _________________
|     |     |     |
|  D  |  1  |  D  |
|_____|_____|_____|
|     |     |     |
|  1  |     |  1  |
|_____|_____|_____|
|     |     |     |
|  D  |  1  |  D  |
|_____|_____|_____|

Pathfinder retrieves grid cost from either an evaluator or prefilled matrix. All cost states must be immutable during calling the pathfinder:solve(...) function. It’s not walkable if either part of the cost combination results -1; positive cost means walkable, and the pathfinder prefers lower cost grids.

Randomizer

This module provides a random algorithm organized by object, other than the built-in random function in Lua.

Constructors

Methods

Raycaster

This module performs a raycasting algorithm on 2D grids.

Constructors

Object Fields

Methods

Walker

This module performs a smooth walking algorithm on 2D grids.

Constants

Constructors

Object Fields

Methods

Archive

This module offers manipulations of ZIP package.

Constructors

Methods

Bytes

Being the same as Lua list, a Bytes’ index starts from 1. Implements a Stream protocol as memory buffer.

Constructors

Operators

Methods

Color

Constructors

Operators

Object Fields

Methods

Date Time

Static Functions

Encoding

Base64

Static Functions

LZ4

Static Functions

File

Being the same as Lua list, a File’s index starts from 1. Implements a Stream protocol as file on disk.

Constructors

Operators

Methods

Note that when open a file as Stream.Append, it always writes data at the end of the file, expanding it, and file:poke(...) are ignored.

Filesystem

Static Functions

Static Variables

Constructors

Methods

Image

Constructors

Object Fields

Methods

JSON

Constants

Constructors

Methods

Math

Structures

Constants

Static Functions

Constructors

Operators

Object Fields

Methods

Intersection Detection

Static Functions

Both shape parameters can be:

Network

Constants

Constructors

The callback of received event is an invokable in form of function (data, size, addr) end, which accepts three parameters respectively represent for the data has been just received, the data size corresponding to specific types, and the remote adress string. The type of the first parameter is determined by the “data_type” option.

The callback of connection established is an invokable in form of function (addr) end, which accepts a parameter represents for the remote address string; nil for failure for outcoming connection. It’s invoked when either incoming or outcoming connection established; ignored by UDP.

The callback of disconnected is an invokable in form of function (addr) end, which accepts a parameter represents for the remote address string. It’s invoked when either incoming or outcoming connection disconnected; ignored by UDP.

Object Fields

Methods

Currently there is only one available option:

Key Value Note
“data_type” Can be one in “stream”, “bytes”, “string”, “json”, defaults to “json” Data type for transmission/datagram

An addr argument is combined with four parts, direction, protocol, address and port:

Part Value
Direction > for connecting, < for listening
Protocol udp://, tcp://
Address IP address
Port Port number

For example:

Address string Connectivity
“>tcp://192.168.0.1:12000” As client, connects to 192.168.0.1 port 12000 via TCP
“<udp://127.0.0.1:12000” As server, listens from local host port 12000 via UDP
“udp://192.168.0.1:12000” As client, sends to 192.168.0.1 port 12000 via UDP
“tcp://12000” As server, listens from port 12000 via TCP
“192.168.0.1:12000” As client, connects to 192.168.0.1 port 12000, protocal determined by the explicit protocal parameter
“12000” As server, listens from port 12000, protocal determined by the explicit protocal parameter

A single transmission or datagram cannot be longer than 512KB.

Consider closing and setting a Network object to nil as soon as it’s no longer in use.

For “stream”, it sends and receives raw Bytes, you are free parsing and serializing for your own protocol.

For “bytes”, an extra 32-bit unsigned integer will be automatically packed at head of Bytes before sending, the size head itself also counts; Bytes parameter in the received callback doesn’t contain that head. In short words, it’s transparent between Bitty Engine projects, but it’s helpful to communicate with other endpoints to distinguish different messages, and you have to adapt the rule for other Network endpoints.

For both “string” and “json”, the underneath data flow always end up with a zero byte, vice versa, received string and Json must end up with a terminal zero byte.

Platform

Static Functions

Static Variables

Promise

This module declares a minimal protocol to handle asynchronization.

Constants

Object Fields

Methods

Stream

This module contains constants indicating accessibilities for other modules.

Constants

Web

Experimental feature. This module offers fetching via HTTP.

Functions

Implements a Promise protocol for HTTP accessing and manipulating.

The thus handler of the returned Promise object takes an invokable object in form of function (rsp) end which accepts the responded content. The catch handler of the returned Promise object takes an invokable object in form of function (err) end. The finally handler of the returned Promise object takes an invokable object in form of function () end.

For example:

fetch('https://github.com', {
    method = 'GET',
    headers = {
      ['Content-Type'] = 'text/html',
      ['User-Agent'] = 'Mozilla/5.0 Gecko/20100101 Firefox/83.0'
    }
  })
  :thus(function (rsp)
    print(rsp)
  end)
  :catch(function (err)
    print('Error.')
  end)
  :finally(function ()
    print('Finished.')
  end)
Option Values Description
method “GET”, “POST”, “PUT”, “DELETE”, etc. Specific method to perform HTTP request
headers Valid HTTP headers Optional. Header data
body Request body Optional. Body data
hint “bytes”, “string”, “json” Optional, defaults to “string”. Prefers how to interpret respond data
allow_insecure_connection_for_https true, false Optional, defaults to false, for desktop only. Specifies whether to allow insecure connection for HTTPS

TOP

Assets and Resources

Resources

Static Functions

The hint can be one in Palette, Texture, Sprite, Map, Sfx, Music. Bitty Engine can infer asset types from extension or content most of the time. However hint is necessary if there is yet insufficient information to tell a type, or to distinguish as either Sfx or Music when loading an audio asset.

For example:

foo = Resources.load('bar.pal') -- Load a palette.
foo = Resources.load({ width = 128, height = 128 }) -- Load a blank texture.
local data = {
  width = 8, height = 8,
  count = 2,
  data = {
    {
      x = 16, y = 0, width = 8, height = 8,
      interval = 0.25,
      key = 'idle'
    },
    {
      x = 24, y = 0, width = 8, height = 8,
      interval = 0.25,
      key = ''
    }
  },
  ref = baz -- Ref by object.
}
foo = Resources.load(data) -- Load a sprite.
local data = {
  tiles = {
    count = { 8, 8 }
  },
  width = 60, height = 40,
  data = { ... },
  ref = 'baz.png' -- Ref by asset name.
}
foo = Resources.load(data) -- Load a map.
foo = Resources.load('bar.mp3', Sfx) -- Load an SFX.
foo = Resources.load('bar.mp3', Music) -- Load a piece of music.

The asynchronous Resources.load(...) returns a resource handle immediately. It is lazy evaluated, loading is deferred until specific reading and writing access happens. The synchronous Resources.wait(...) also loads it, it returns immediately if the specific resource is already loaded, otherwise it waits until loaded or timeout.

Consider using Resources.unload(...) or Resources.collect() to unload unused resources (loaded by Resources.load(...)) periodically and properly, or there would be memory leak. One possible practice is to call Lua’s GC then collect resources after loading a new level, since the old one is no longer in use:

collectgarbage()
Resources.collect()

Asset

Can be loaded by Resources.load(...), only happens when Bitty Engine cannot determine specific sub asset type.

Palette Asset

Can be loaded by Resources.load(...).

Font Asset

Constructors

Font is constructed like regular object and managed by GC, do not need to unload it manually. The permeation parameter indicates how to handle font transparency, zero means using values from a font file, while non-zero means a specified threshold for whether a pixel shall pass (non-transparent) or be blocked (transparent).

Texture Asset

Can be loaded by Resources.load(...).

Object Fields

Methods

Sprite Asset

Can be loaded by Resources.load(...).

Object Fields

Methods

It communicates across internal threads when play a sprite animation synchronously, this might take lots of time if there are lots of sprites. Consider playing it asynchronously if this matters in your actual project.

Map Asset

Can be loaded by Resources.load(...).

Object Fields

SFX Asset

Can be loaded by Resources.load(...).

Music Asset

Can be loaded by Resources.load(...).

TOP

Primitives

The coordinate definition in Bitty Engine is as follow:

The zero point is to the top-left corner, the x, y axises increase in right, bottom respectively.

Basics

Functions

Shapes

Functions

Palette

Functions

Font

Functions

Texture

Functions

Sprite

Functions

Map

Functions

Audio

Functions

SFX

Functions

Music

Functions

Gamepad

A gamepad is a virtual entity, its buttons are binded to a keyboard or an actual gamepad hardware.

Functions

For the button parameter, 0, 1, 2, 3, 4, 5 are for Left, Right, Up, Down, A, B respectively. Seealso the “Gamepad” example under the “Primitives” category.

Keyboard

Functions

See keycodes for more readable presentation. Seealso the “Keyboard” example under the “Primitives” category.

Mouse

Functions

Seealso the “Mouse” example under the “Primitives” category.

Camera

Functions

Clip

Functions

Blend

Functions

TOP

Physics

Due to space limitation in the page, read Physics for details.

TOP

Invoking

The Invoke.call(func, ...) invokes from Lua to the host environment (for HTML build only). It supports up to 16 parameters.

Bitty Engine supports callback from the host environment to Lua (for HTML build only). To use this feature, you need to define a function on the Lua side with the name call, and the function will be called when the host environment invokes the callback. The function accepts variadic arguments, and the arguments are passed as strings. In JavaScript, call Module.call(arg1, arg2, ..., arg16) to invoke the callback with up to 16 arguments.

To call from JavaScript to Lua, make a “ccall” to call1, call2, etc. i.e.

Module.ccall(
	'call2',
	'number',
	[ 'number', 'number' ],
	[ stringToNewUTF8('Hello'), stringToNewUTF8('World') ]
);

TOP

Application

Static Functions

Available options:

Key Value Note  
“title” String, title Sets the title of the application window  
“minimum_size” Integers, width, height Sets the minimum size of the application window  
“maximum_size” Integers, width, height Sets the maximum size of the application window  
“bordered” Boolean, bordered Sets whether the application window is bordered  
“resizable” Boolean, resizable Sets whether the application window is resizable  
“position” Integers, x, y Sets the position of the application window  
“display_index” Integers, index Sets the index where the application window will be displayed on that device  
“transparent_color” Color nil, color Experimental, sets the transparent color key of the application window

The “transparent_color” option is an experimental feature, it supports Windows 10 and above. Note that it affects the whole application window.

Canvas

Constants

Static Functions

Static Variables

Object Fields

Methods

Project

Project accepts strategies, add a “strategies” field in “info.json” to enable specific options, eg.

{
  ...
  "strategies": [
    "batch_map"
  ]
}

Currently there is only one available strategy, change and try if it’s needed:

Strategy Description Note
“batch_map” Hints to batch map for better rendering performance, but occupies more memory Always on for HTML build
“linear_canvas” Hints to set canvas filtering as linear  
“anisotropic_canvas” Hints to set canvas filtering as anisotropic  

Constants

Static Variables

Methods

Debug

This module is used for debugging purposes.

Static Functions

TOP

Import and Export

Import

Click “Project”, “Import…” to browse and import some assets from a “.bit”, “.txt”, “*.zip” archive. This operation doesn’t overwrite conflictions in your editing project.

TOP

Export

Click “Project”, “Export…” to select and export some assets to a “.bit”, “.txt”, “*.zip” archive.

TOP

Building

Building for Desktop

Click “Project”, “Build”, then “Windows”/”MacOS”/”Linux” to make an executable for Windows/MacOS/Linux respectively with the current opened project.

It might require execution permission to launch an exported desktop binary, to apply that permission:

TOP

Building for HTML

Click “Project”, “Build”, then “HTML” to make an executable for browser with the current opened project. It requires a WebAssembly capable browser.

You can upload it to cloud or host it on your own server for others to play.

TOP