Loving Cube Engine API documentation

Introduction and table of contents - The init file - The Main object - Importing new textures - Importing 3D meshes - New data types - List of instantiable objects - List of static objects


Static objects

"This" special keyword

For each active object type lua_class_name (see ActiveObjects), the methods of the table lua_class_name set up its behavior, and are called for each active object instance. Within these methods, the keyword This is a static object which actually represents the current active object instance. It has the following methods:

MethodDescription
Number3 position([Number3 pos])Set or get the world-coordinates (x,y,z) position of the instance.
void setVariable(string type_and_name, argument(s) ...)Set the value of an instance variable, creating it if it not yet defined.
type_and_name is a-colon separated string. The first part must be either "bool","int","number","pos","str". The second part is the variable name.
argument(s) is the new value.
Example: setVariable("pos:mvtVector", Number3.new(2.0,3.5,1.0)) set the value of the variable "mvtVector" of type "pos" to be (2.0,3.5,1.0).
value getVariable(string type_and_name)Get the value of an instance variable (1 or 3 elements are returned, depending of the type). The variable shall already have been defined (you can check it with isVariableDefined()).
type_and_name is a-colon separated string like above.
Example: local mynumber = getVariable("number:myobjectnumber")
bool isVariableDefined(string type_and_name)Return true if the instance variable has been defined (i.e. setVariable() was called on it at least once).
void disable()"Disable" the instance until the next ActiveObjects.resetActiveObjects() call. The instance will no more be present in-game, but it will be still available in the 3D editor as a small cube.
number distanceTo(Number3 pos)Get the world-coordinates distance between the instance position and another position.
void drop()Destroy the instance. When called, this MUST be the last "This" function called in the object (otherwise the game would crash since the instance does not exist any more).

Player - Controls the main character, for example in a platform game

MethodDescriptionLimitations
void load(bool load_or_unload)If true, loads the Player static object. This MUST be called prior to calling any other method of Player. If false, unloads the Player static object.
void enable(bool enable_or_disable)Show or hide the player (and everything associated with it likes its buttons).
number distanceTo(Number3 pos)Get the distance between the Player and a given coordinate.
(number, number, number) position([number x, number y, number z])Set or get the world-coordinates of the Player.
Number3 speed([Number3 s])Set or get the speed vector of the Player.
void movementType(string movement_type)Set or get the movement type of the Player. Can be "NONE","WALK","CAR","FLY".TODO: CODE AND TEST
void setGameOver(bool yes_or_no)Set the Player in the "game over" state. setGameOver(true) is like enable(false), except that when "game over", it's still possible to rotate the camera.
bool isGameOver()Is the Player in the "game over" state.
bool setModel3D(
number mesh_scale,
number mesh_weld,
Number3 ground_position_modifier,
string frame_file_static
string frame_file_walk1[, string frame_file_walk2, [...]],
string frame_file_jumping)
Load a new Player 3D model, discarding the previous one.
  • mesh_scale is the relative scale of the meshes.
  • mesh_weld is the simplication factor of the mesh, for optimization. -1 disable mesh simplification (often advised)
  • ground_position_modifier define the mesh relative position of the ground, for collision.
  • frame_file... are the meshes files. The mesh used to the "static" frame is the first one. The mesh used to the "jump" frame is the last one. All other meshes are used for "walk" animation. There must be at least 3 frames.
number cameraDistance([number dist])Set or get the distance of the camera to the player model.
void setup(bool enable_2D_buttons, bool enable_3d_render, bool enable_camera_follow, bool enable_drag_and_drop_camera, bool enable_scroll_zoom_camera)Respectively enable or disable some features in the Player object:
  • Enable or disable displaying the 2D buttons used to move the Player with the mouse.
  • Enable or disable displaying the player 3D mesh.
  • Enable or disable the fact that the camera follows the Player.
  • Enable or disable the fact that this is possible to rotate the camera with a mouse drag and drop.
  • Enable or disable the fact that this is possible to zoom/unzoom with the mouse scroll and the zoom buttons.
void selectCubesEngineForCollision(CubesEngine cubes_engine_instance)Select the CubesEngine instance which will be used for collision detection (by default it is CubesEngine.get()).
number angleY([number angle])Set or get the player model angle (= the camera angle)

Editor3D - Utilities for the 3D editor

MethodDescriptionLimitations
void load(bool load_or_unload)If true, loads the Editor3D static object. This MUST be called prior to calling any other method of Editor3D. If false, unloads the Editor3D static object.
void enable(bool enable_or_disable)Show or hide the 3D editor (and everything associated with it).
Number3 getInitialPosition()Get the position of the blue "INIT" box, in world coordinates.
Int3 initialPosition([Int3 pos]) Get or set the position of the blue "INIT" box, this time in cube coordinates. Also reset the red cursor box position to the one of the blue box.
Int3 cursorPosition([Int3 pos])Get or set the position of the red cursor box, in cube coordinates.
void setup(bool enable_2D_buttons, bool enable_keyboard_layout_french, bool enable_auto_select_a_cube)Respectively enable or disable some features in the Editor3D object.

Input - Keyboard and mouse control

MethodDescriptionLimitations
bool getKey(string key)Return true if the keyboard key is pressed. key may be:
- the character of the key from A to Z, for example getKey("a"). Beware that getKey("a") and getKey("A") are different and depends of whether caps lock is enabled.
- the string "ASCII:X", X being the numerical decimal ascii code, for example getKey("ASCII:9") for tabulation
- the string "FX", X being the function key between 1 and 12, for example getKey("F5") for F5 key
- "RIGHT", "LEFT", "UP", "DOWN" being each of the arrow keys
bool getKeyNoCase(string key)Same than getKey, but when using for example getKeyNoCase("a"), return true whenever "a" or "A" is pressed, i.e. whenever caps lock is enabled or not.
bool getKeyNoRepeat(string key)Same than getKey, but avoid repetition i.e. wait for the key to be released before returning true again. Note that this is roughly equivalent to use the callback Main.onKeyPressed() function, which may be more advised.
(bool is_pressed_left, bool is_pressed_middle, bool is_pressed_right, int x, int y) getMouseInfos()
Int2 getMousePosition()
bool getJoystickButton(int player_id, string button)Return true if the Microsoft XBox 360 usb joypad in plugged and the button button is pressed.
player_id must be an integer between 1 and 4.
button may be: LEFT, RIGHT, UP, DOWN, X, Y, A, B, START, BACK, LEFT_SHOULDER, RIGHT_SHOULDER, LEFT_TRIGGER, RIGHT_TRIGGER.

Also are supported: LEFT_STICK_LEFT_AS_BUTTON, LEFT_STICK_RIGHT_AS_BUTTON, LEFT_STICK_UP_AS_BUTTON, LEFT_STICK_DOWN_AS_BUTTON and RIGHT_STICK_LEFT_AS_BUTTON, RIGHT_STICK_RIGHT_AS_BUTTON, RIGHT_STICK_UP_AS_BUTTON, RIGHT_STICK_DOWN_AS_BUTTON as a way to simplify getJoystickLeftStickState()/getJoystickRightStickState() and checking that a stick axis is greater than 0.5 or smaller than -0.5, which would mean it is "pressed".
bool getJoystickButtonNoRepeat(int player_id, string button)Same than getJoystickButton, but avoid repetition i.e. wait for the button to be released before returning true again.
Number2 getJoystickLeftStickState(int player_id)Get the left stick state (between -1 and 1) for horizontal and vertical axis
Number2 getJoystickRightStickState(int player_id)Get the right stick state (between -1 and 1) for horizontal and vertical axis

Misc - Miscellaneous utility functions

MethodDescriptionLimitations
Int2 getWindowSize()Get window size (or device size if fullscreen) in pixel units
void printConsole(thing[, ...])Print something in the console (in some devices, the console may not be available). thing may be a string, a number, an int, or a bool, or anything else (in this latter case, it shows the hexadecimal memory address). Can take several arguments.TODO: no console on most devices
void assert(bool condition)Abort the program if the condition is false. Note that you may want to use assert(condition) instead of Misc.assert(condition)
int getTime()Time in miliseconds since the program started (or the system started). Very useful to compute elapsed times.
int getFrameDuration()Time in miliseconds of the last displayed frame.
You should use this value for any operation which depends of time, to keep the same behaviour on every computer (i.e. whatever the framerate).
Example: position_x_player = position_x_player + Misc.getFrameDuration() / 30000.0
void drawPleaseWait()Draw a black screen with written "Please wait". This is the only draw function which can be called almost everywhere (outside a draw callback), and is intended to be used before calling some code which would take a long time to achieve, in order to warn the user.
void selectCubeEngineAndActiveObjects(CubesEngine cubes_engine_instance, ActiveObjects active_objects_instance).Select a new default cube engine and active objects (note: currently active_objects_instance can only be ActiveObjects.get(). They will be used for CubesAndActiveObjects, for BufferOfCubesAndActiveObjects, and for the Editor3D.
void quitApplication()Send a signal for the application to quit. Do nothing if getRunningEnvironment() is "ENVIRONMENT_WINDOWS_STORE" or "ENVIRONMENT_WINDOWS_STORE_WITH_ADS", since store applications do not "stop".
void getRunningEnvironment()Get the following string, depending of the executable and the environment:
  • ENVIRONMENT_LINUX: The operating system is Linux, and the executable uses OpenGL for rendering.
  • ENVIRONMENT_WINDOWS_DESKTOP_OPENGL: The operating system is Windows, the application is an ordinary desktop application, and the executable uses OpenGL for rendering.
  • ENVIRONMENT_WINDOWS_DESKTOP_DIRECTX: The operating system is Windows, the application is an ordinary desktop application, and the executable uses Direct3D for rendering.
  • ENVIRONMENT_WINDOWS_STORE: The operating system is Windows (at least Windows 8), and this is a Windows Store application, designed both for computers and tablets. The executable uses Direct3D for rendering.
  • ENVIRONMENT_WINDOWS_STORE_WITH_ADS: Same than ENVIRONMENT_WINDOWS_STORE, but an ad is displayed.

CubesAndActiveObjects - Special functions which concern both CubeEngine and ActiveObjects

Important note: a loaded world must be compatible with the same size_one_region and size_one_cube than the current default CubesEngine instance, otherwise it will crash. (TODO fix or warn)
MethodDescriptionLimitations
void loadWorldInAppData(string filepath)Load a world file from a path in the application data ("%AppData%/LovingCubeEngine/") directory.
void saveWorldInAppData(string filepath)Save a world file to a path in the application data ("%AppData%/LovingCubeEngine/") directory.
void loadWorldInAppFolder(string filepath)Load a world file from a path in the directory (or a subdirectory) of the application.
void clearAllWorld()Delete all cubes and active objects.
void finalizeCubeTypesAndActiveObjectTypes()Must be called after calling a bunch of the functions CubesEngine.addCubeType,CubesEngine.ClearCubeTypes,ActiveObjects.addType,ActiveObjects.clearTypes, in order to update the world and the 3D editor accordingly.

FileUtil - File utility functions

Note: the application data directory is "%AppData%/LovingCubeEngine/" i.e. most of the time "C:\Users\username;\AppData\Roaming\LovingCubeEngine"

MethodDescriptionLimitations
bool fileExistsInAppFolder(string file_path)Return true if the path exists in the directory of the application
bool fileExistsInAppData(string file_path)Return true if the path exists in the application data directory
void writeTextFileInAppData(string file_path, string contents)Write a text file in the application data directory
string readTextFileInAppData(string file_path)Read a text file in the application data directory
string getAppDataFullPath()Return the full path to the application data directory
void copyFileFromAppFolderToAppData(string src_file, string desc_file)Copy a file from the application directory to the application data directory

Maths - Mathematics functions

MethodDescriptionLimitations
Number3 getNormalizedVector(Number3 v1, Number3 v2)Return the normalized version of the vector (v1:x()-v2:x() , v1:y()-v2:y() , v1:z()-v2:z()).
number getDistanceBetween(Number3 pos1, Number pos2)Get the distance between the points of coordinates pos1 and pos2.
Number3 cartesianCoordFromSphericalCoord(number angle_x, number angle_y, number radius)Get the 3D coordinates from spherical coordinatesTODO: TEST

Scene2D - Utilities to control the 2D text/drawing

MethodDescription
void scheduleDraw2DSprite(string image_filepath, int duration_ms, [Int2 pos])Draw a 2D sprite during duration_ms miliseconds. Contrarily to an ordinary sprite, you don't need to deal with a drawing function, and unallocation, etc. If pos is not provided, draw in the center of the window.
void drawText(string text, Int2 pos[, int font_size = 18[, Color c[, bool smooth[, int automatic_line_return]]])Draw the text text at pixel coordinates pos. Text size and font color (including transparency) may be specified. The text string supports "\n" for line returns. If smooth is defined and true, make the text rendering more blurry/smooth, this can render a little better in the text is small. If automatic_line_return is defined, make a line return after automatic_line_return pixels of width.TODO: smooth on DirectX has no effect
void drawRectangle(Int2 pos1, Int2 pos2, Color c[, int border_width = 0[, bool fill = true]])Draw the rectangle between pixel coordinates pos1 and pos2, with a given color and border width in pixel units, and whether the rectangle is filled with color or only the border is drawn.
void drawLine(Int2 pos1, Int2 pos2, Color c, int thickness)Draw a line between pixel coordinates pos1 and pos2, with a given color and thickness in pixel units.
void setMessageOnScreen(string text, int duration_seconds[, Color text_color, Color back_color)Draw a message in the center of the screen for duration_seconds seconds. The text string supports "\n" for line returns. Optional arguments 3 and 4 are text color and background color.

Scene3D - Utilities to control the 3D scene

MethodDescriptionLimitations
Color fogColor([Color c])Set or get the fog color (alpha value is ignored here).
number fogDistance([number distance])Set or get the fog distance to the camera. Changing the fog distance can greatly impact performances, because what's over the fog is not drawn nor computed.
Number3 cameraPosition([Number3 pos])Set or get the camera position. Note that if the Player and/or the Editor3D are enabled, changing the camera position can, depending of where this function is called, have strange results, because the Player and/or the Editor3D also control the camera.
(number, number) cameraAngle([number angle_x, number angle_y])Set or get the camera (pitch and yaw) angles in degree units.TODO: TEST
TODO: roll axis
number cameraFOV([number fov])Set or get the (vertical) camera field of view in degrees, for example 90. Default is 110. Return the current (or new) camera field of view.
void setCameraLookAt(Number3 target,number angle_x,number angle_y, number distance)Set the camera position to look at the point target from a given distance and a given angle.
void setSkyBox(string file_top, string file_bottom, string file_front, string file_back, string file_left, string file_right)Set up a new Skybox from the given pictures files (for each of the 6 faces), dropping the previous one if it exists.
Int2 get2DPosFrom3D(Number3 pos)Get the window pixel coordinates of a 3D point.TODO: TEST
TODO: code DirectX version
void enableGet3DPosFrom2D(bool yesNo)Enable or disable the usage of the 3D picking function get3DPosFrom2D(). This must be called before creating your object/scene, for example at the initialization of the app. Note that enabling this in DirectX environment might use a lot of memory.
Number3 get3DPosFrom2D(Int2 pos)Get the 3D coordinates of a window 2D point. Note: you shall can enableGet3DPosFrom2D(true) before using the function for the first time.
void setShaderForFilenameTexture(string filename, int id)Affect an identifier to a given texture file. In the shader program, you will be able to get this value (see userDefinedTextureId) and decide what shaders apply to this specific texture.
void removeShaderForFilenameTexture(string filename)Unaffect the shader identifier associated with this given texture file.
Color shadowsColor([Color c])Set or get the colors of shadows (default is (128,128,128,255) i.e. gray). Each RGB component is multiplied with the corresponding component of the actual texture color to retrieve the final color. Note that you must call this before adding cubes to display. Alpha value is ignored here.

Pathfinding - Very basic pathfinding algorithms

MethodDescriptionLimitations
void addSegmentInGraph(Number3 pos1, Number3 pos2)Add a segment in the graph, creating nodes if they don't exist.
void removeSegmentFromGraph(Number3 pos1, Number3 pos2)Remove a segment from the graph, removing nodes if they are no more used.TODO: TEST
int findPathLengthInGraph(Number3 start, Number3 end)Find a way from node start to node end, if any (this may not be the shortest way).
Return the number of nodes used to reach end, or -1 if not found.
(bool,integer,number x,number y,number z[,...]) findPathInGraph(Number3 start, Number3 end)Find a way from node start to node end, if any (this may not be the shortest way).
Return:
- A bool indicating whether a path was found
- The number of nodes in the path
- For each node in the path, the x,y,z coordinates of this node.
void clearGraph()Cleanup all nodes in the graph.TODO: TEST

Example:

Pathfinding.addSegmentInGraph(Number3.new(0,0,0),Number3.new(10,10,10))
Pathfinding.addSegmentInGraph(Number3.new(10,10,10),Number3.new(20,20,20))
Pathfinding.addSegmentInGraph(Number3.new(30,30,30),Number3.new(20,20,20))
Pathfinding.addSegmentInGraph(Number3.new(10,10,10),Number3.new(40,40,40))
local array = {Pathfinding.findPathInGraph(Number3.new(0,0,0),Number3.new(30,30,30)}
local found_path = table.remove(array, 1)
local nb_elements = table.remove(array, 1)
Misc.printConsole(found_path, nb_elements, unpack(array))
(pathfinding example)

Results with:

Prints: lua print: true, 4, 0, 0, 0, 10, 10, 10, 20, 20, 20, 30, 30, 30

Network - Internet/network access utilities

MethodDescriptionLimitations
string doHttpRequest(string url, bool verbose, string method[, string argument1, string value1[, string argument2, string value2[, ...]]])Interact with a page from a web server using an HTTP method. If verbose, print some things in the console for debug.
method should be "GET","POST","PUT", or "DELETE". The optional arguments and their values are passed as Content-Type: application/x-www-form-urlencoded. For example, you can use set method to "GET" and choose an url to download some web page on the Internet.
TODO: Add authentication and encryption (i.e. does not work with https yet)

ConfigFile - Utilities for basic XML files used to store variables

Note: if the functions xxxxValue are called with only one argument, the variable should already be defined, otherwise it will return empty string / 0 / false.

void loadFile(string path)Load the variables in the XML config file in "%AppData%/LovingCubeEngine/" into memory.
void saveFile(string path)Save the variables in memory into an XML config file in "%AppData%/LovingCubeEngine/".
string stringValue(string variable_name[, string new_value])Set or get a value from a variable name
number numberValue(string variable_name[, number new_value])Set or get a value from a variable name
int integerValue(string variable_name[, int new_value])Set or get a value from a variable name
bool booleanValue(string variable_name[, bool new_value])Set or get a value from a variable name