.. highlightlang:: lua :linenothreshold: 5 .. lua:module:: drystal .. role:: lua(code) :language: lua API Reference ============= .. warning:: Drystal API is not stable yet. It is still changing and as it matures some parts are more and more reliable than others. Unfortunately, it has not sufficient testing in real games, so the API is changing where we think a change is worth an API break. .. contents:: :local: :depth: 3 Engine ------ .. lua:function:: stop() Stops the execution of drystal. .. lua:function:: reload() Reloads the current game. This can be useful during the development on your desktop. .. note:: F3 also reloads the game. Callbacks ^^^^^^^^^ .. lua:function:: init() This function is called after script loading, before the first frame. You may want to load your assets from here but you can load them before if you prefer. .. code:: print '1' function drystal.init() print '3' end print '2' .. lua:function:: update(dt: float) This functions is called at each frame. The ``dt`` parameter represents the time elapsed since the last update (in seconds). Use this function to update the game state. .. lua:function:: draw() This function is called after the :lua:func:`drystal.update` function. .. lua:function:: atexit() This function is called when the window is closed or when :lua:func:`drystal.stop` is called. .. lua:function:: prereload() Called before the game is reloaded (by :lua:func:`drystal.reload`, by pressing F3 or with livereloading). You can use it to save the current state of the game inside a global variable, so it will still be accessible after the reload. .. lua:function:: postreload() Called after the game was reloaded. You can use it to restore the state of the game. .. include that in a tutorial .. .. literalinclude:: ../examples/red_background.lua .. :language: lua .. :linenos: Event ----- The event module allows you to know when the mouse is moved, a key or a button is pressed or released, or when the screen is resized. .. lua:function:: set_relative_mode(relative: boolean) Sets the relative mode. Relative mode is when the mouse is hidden and can't leave the window/canvas. Callbacks ^^^^^^^^^ To receive events, you have to defined some of the following functions. .. lua:function:: mouse_motion(x, y, dx, dy) Called when the mouse is moved. ``dx`` and ``dy`` are difference between the current position and the last one. .. lua:function:: mouse_press(x, y, button: integer) Called when a button (or mouse wheel) is pressed. :param int x: X coordinate of the mouse when the button was pressed :param int y: Y coordinate of the mouse when the button was pressed :param int button: - ``drystal.buttons.left`` (= 1), - ``drystal.buttons.right`` (= 2), - ``drystal.buttons.middle`` (= 3), - ``drystal.buttons.wheel_up`` (= 4), - or ``drystal.buttons.wheel_down`` (= 5). .. lua:function:: mouse_release(x, y, button: integer) Called when a button (or mouse wheel) is released. :param: button is the same as in :lua:func:`drystal.mouse_press`. .. lua:function:: key_press(key) Called when a key is pressed. Depending on key repeat system configuration of the player, :lua:func:`drystal.key_press` can be called multiple times even if the user did not released the key. :lua:func:`drystal.key_release` will be called too. .. lua:function:: key_release(key) Same as :lua:func:`drystal.key_press` but when a key is released. .. lua:function:: key_text(unicode_key) Called when a key is pressed, ``unicode_key`` is the character generated by the key and the current modifiers. For example, if *shift* and *d* are pressed, :lua:func:`drystal.key_text` will be called with the parameter **'D'**. .. lua:function:: page_resize(w, h) Called when the browser page is resized. Use this callback to resize the canvas in the fullscreen mode (see :lua:func:`drystal.set_fullscreen`). :param: see `inner window width and height `_ Graphics -------- Window ^^^^^^ .. lua:data:: screen :lua:data:`drystal.screen` is the surface representing the window/canvas, which will be blit after execution of the :lua:func:`drystal.draw` callback. .. lua:data:: current_draw_on :lua:meth:`.Surface:draw_on` .. lua:data:: current_draw_from :lua:meth:`.Surface:draw_from` .. lua:function:: resize(width: integer, height: integer) Resizes the window (or the canvas in the browser) to the specified dimensions. .. note:: Unlike some engines, you can resize the window without having to recreate your surfaces or shaders. .. code-block:: lua :linenos: drystal.resize(200, 300) assert(drystal.screen.w == 200) assert(drystal.screen.h == 300) .. lua:function:: set_fullscreen(fullscreen: boolean) Enables or disables the fullscreen mode. .. note:: It will make the game fits the whole page in a browser and not use the true fullscreen mode. We choose this behavior because the escape key will not be available anymore and it makes less sense to play a game in fullscreen with a browser. You also need to ensure that there is no border or margin for the canvas in your index.html. .. code-block:: css html,body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; } .. note:: When the browser is resized, the canvas is not resized. Call ``drystal.set_fullscreen(true)`` from the callback :lua:func:`drystal.page_resize` to update it. .. lua:function:: set_title(title: str) Changes the title of the window. In the browser, the title of the document is changed. .. lua:function:: show_cursor(show: boolean) Decides if the mouse cursor should be hidden or not. Surface ^^^^^^^ .. lua:class:: Surface Object representing a surface. Surfaces can be drawn on other surfaces (screen included). .. lua:data:: w Width of the surface. .. lua:data:: h Height of the surface. .. lua:method:: draw_on() -> Surface Use this surface as destination/backbuffer (draw method be redirected to this surface instead of screen) for future draws. :return: the old surface which was used .. lua:method:: draw_from() -> Surface Use this surface as source for future textured draws (like :lua:func:`drystal.draw_sprite`). :return: the old surface which was used .. lua:method:: set_filter(filter) :param filter: - ``drystal.filters.nearest``, - ``drystal.filters.linear`` (= ``drystal.filters.default``), - ``drystal.filters.bilinear`` - or ``drystal.filters.trilinear``. .. warning:: A surface is limited to 2048x2048 pixels. We follow the `WebGL Stats `_ and we use the highest texture size at 100%. .. lua:method:: get_pixel(x, y) -> r, g, b, a Returns red/green/blue/alpha components at given pixel position. Top-left is at (1, 1) and bottom-right is at (surface.w, surface.h) included. .. lua:function:: new_surface(width, height) Creates a new surface of dimensions (``width``, ``height``). By default, the surface is transparent. .. code:: local surf = drystal.new_surface(200, 200) surf:draw_on() -- the following draw function will act on this surface drystal.set_color('white') drystal.draw_circle(surf.w / 2, surf.h / 2, 100) -- draw a white circle inside the surface drystal.screen:draw_on() ... .. lua:function:: load_surface(filename) Loads a surface from a file. If the file does not exist or is invalid, :lua:func:`drystal.load_surface` returns (`nil`, error). .. note:: Use :lua:`assert(drystal.load_surface 'test.png')` to make sure the surface is loaded. Drawing primitives ^^^^^^^^^^^^^^^^^^ .. lua:function:: set_color(red: float [0-255], green: float [0-255], blue: float [0-255]) Sets current color used by ``draw_*`` functions. .. lua:function:: set_color(color: table) Sets current color used by ``draw_*`` functions. ``color`` should contains 3 values at keys 1, 2 and 3. For example, ``{128, 128, 128}`` represents gray. .. lua:function:: set_color(color: string) Sets current color used by ``draw_*`` functions. ``color`` should be either a color name from the :lua:data:`colors` table or a '#rgb' or '#rrggbb' CSS-like string. .. lua:function:: set_alpha(alpha: float [0-255]) Sets the current alpha used by ``draw_*`` functions. .. lua:function:: draw_background() Clears the current :lua:data:`current_draw_on` surface. .. note:: In the following function, ``x``, ``y``, ``w`` (width) and ``h`` (height) are floats. Angle are expressed in radians. ``x`` and ``y`` are screen coordinates. .. lua:function:: draw_point(x, y, size) Draws a point at the given coordinate and with given size. .. lua:function:: draw_point_tex(sourcex, sourcey, x, y, size) Draws a textured point at the given coordinate and with given size. The point will be textured with the surface bound to :lua:data:`current_draw_from`, starting from ``sourcex, sourcey`` to ``sourcex+64, sourcey+64``. .. lua:function:: draw_line(x1, y1, x2, y2, width=1: float) Draws a line between the two given points. .. lua:function:: draw_triangle(x1, y1, x2, y2, x3, y3) Draws a filled triangle between the three given points. .. lua:function:: draw_surface(ix1, iy1, ix2, iy2, ix3, iy3, ox1, oy1, ox2, oy2, ox3, oy3) Draws a surface (set as :lua:data:`current_draw_from`). The first 6 parameters represent a triangle in the source texture, the last 6 represent the destination triangle. They can have different sizes to create deformations. Tinting is possible by using :lua:func:`drystal.set_color` (255, 255, 255 for no modification). .. lua:function:: draw_quad(ix1, iy1, ix2, iy2, ix3, iy3, ix4, iy4, ox1, oy1, ox2, oy2, ox3, oy3, ox4, oy4) Same as :lua:func:`drystal.draw_surface` but with quadrilaterals instead of triangles. .. lua:function:: draw_rect(x, y, w, h) Draws a filled rectangle. .. lua:function:: draw_rect_rotated(x, y, w, h, angle: float) Draws a filled rotated rectangle. .. lua:function:: draw_square(x, y, w, h, width) Draws a non-filled rectangle. .. lua:function:: draw_circle(x, y, radius: float) Draws a circle. The coordinate is the position of the center. ``radius`` is expressed in pixel. .. note:: This function draws a lot of triangles. If possible, include a circle in your spritesheet and draw it with :lua:func:`drystal.draw_sprite`. .. lua:function:: draw_polygon(x1, y1, x2, y2, ...) Draws a filled polygon. .. lua:function:: draw_polyline(loop, width, x1, y1, x2, y2, ...) Draws a non-filled polygon. .. lua:function:: draw_image(x, y, w, h, destx, desty[, destw=w[, desth=h]]) Draws an image. It can be resized if ``destw`` or ``desth`` are different than ``w`` and ``h`` .. lua:function:: draw_sprite(sprite: table, x, y[, transform: table]) Draws a sprite, from the current :lua:meth:`.Surface:draw_from` surface. Use :lua:class:`Sprite` for easier sprite drawing. :param table sprite: must have the fields: x, y, w and h :param table transform: must have the fields: angle, wfactor and hfactor .. code:: local sprite = { -- the first image of a 32x32 spritesheet x = 0, y = 0, w = 32, h = 32, } function drystal.draw() ... drystal.draw_sprite(sprite, 200, 300) end .. lua:function:: draw_sprite_simple(sprite: table, x, y) .. lua:function:: draw_sprite_rotated(sprite: table, x, y, angle: float) .. lua:function:: draw_sprite_resized(sprite: table, x, y, w, h) Blending ^^^^^^^^ .. todo:: Images to show the differences .. lua:function:: set_blend_mode(blend_mode) Sets the current blend mode. :param blend_mode: - ``drystal.blends.alpha`` (= ``drystal.blends.default``), - ``drystal.blends.add`` - or ``drystal.blends.mult``. Camera ^^^^^^ The camera can be used the modify position and size of the following draws. .. lua:data:: drystal.camera.x (=0) Position of the camera (x coordinate). .. lua:data:: drystal.camera.y (=0) Position of the camera (y coordinate). .. lua:data:: drystal.camera.zoom (=1) Zoom of the camera. Values greater than 1 mean zoom in, less than 1 mean zoom out. .. lua:data:: drystal.camera.angle (=0) Angle of the camera. You can easily apply a tilt effect with this field. .. lua:function:: drystal.camera.reset() Resets the camera fields to default values. .. lua:function:: drystal.camera.push() Saves the current camera state. You can then restore it with :lua:func:`drystal.camera.pop`. .. lua:function:: drystal.camera.pop() Restores the camera to the previous state. .. lua:function:: drystal.screen2scene(x: float, y: float) -> float, float Computes the position of screen coordinates ``(x, y)`` to scene/camera coordinates. Buffer ^^^^^^ A buffer can **only contain one type of shape** (point, textured point, line, triangle, textured triangle). .. lua:class:: Buffer .. lua:method:: use() Use this buffer as current buffer. .. lua:method:: draw([dx=0: float[, dy=0: float]]) Draw this buffer. ``dx`` and ``dy`` can be used to offset the draw. .. lua:method:: reset() Removes all elements from the buffer. .. lua:method:: upload_and_free() Sends the buffer to the graphic card and free memory. If a buffer is freed, you cannot call :lua:meth:`.Buffer:reset`, :lua:meth:`.Buffer:use` or :lua:func:`.Buffer.upload_and_free` anymore or errors will be thrown. .. lua:function:: new_buffer([initial_size: integer]) -> Buffer Creates a buffer of the specified ``initial_size``. Once the buffer is full, it is resized. .. lua:function:: use_default_buffer() Tells drystal to use the default buffer. Shader ^^^^^^ .. lua:class:: Shader .. lua:method:: use() Use this shader for the following draws. .. lua:method:: feed(uniform: str, value: float) .. lua:function:: new_shader([vertex: str[, fragment_color: str[, fragment_texture: str]]]) -> Shader Creates a shader with code specified. If one of the code is :lua:`nil`, code of the default shader is used. .. lua:function:: use_default_shader() Tells drystal to use the default shader. Post processing """"""""""""""" .. lua:function:: add_postfx(name: str, code: str[, uniforms: table]) -> function | (nil, error) Creates a post processing effect. The ``code`` parameter must contain a *effect* function. Additional uniforms can be declared by the ``uniforms`` parameter. .. code:: assert(drystal.add_postfx('gray', [[ vec3 effect(sampler2D tex, vec2 coord) { vec3 texval = texture2D(tex, coord).rgb; return mix(texval, vec3((texval.r + texval.g + texval.b) / 3.0), scale); } ]], {'scale'})) .. lua:function:: postfx(name: str, uniforms...: floats) Applies a post processing effect on the current *draw on* surface. The uniform list must have the same order than in the declaration of the effect. .. code:: function drystal.draw() ... drystal.postfx('gray', 0.8) end Colors ^^^^^^ .. lua:class:: Color .. lua:method:: rgb() -> r, g, b Gets the RGB values of the color. You can also use ``.r``, ``.g`` and ``.b``. .. lua:method:: hsl() -> h, s, l Gets the HSL values of the color. You can also use ``.h``, ``.s`` and ``.l``. .. lua:method:: cmyk() -> c, m, y, k Gets the CMYK values of the color. You can also use ``.c``, ``.m``, ``.y`` and ``.k``. .. lua:method:: add(color) -> Color Creates a new Color which is the combination of the two colors using the CMYK subtractive color model. .. note:: You can also use the ``+`` operator. .. lua:method:: sub(color) -> Color Creates a new Color which is the substraction of the two colors using the CMYK subtractive color model. .. note:: You can also use the ``-`` operator. .. lua:method:: mul(color) -> Color Creates a new Color which is the multiplication of the two colors. .. note:: You can also use the ``*`` operator. .. lua:method:: darker() -> Color Creates a darker color. .. lua:method:: lighter() -> Color Creates a lighter color. .. lua:function:: new_color(table) -> Color Creates a color with the RGB color model. :param table table: must contains the three components: r, g and b. .. lua:function:: new_color('rgb', r, g, b) -> Color Creates a color with the RGB color model. .. lua:function:: new_color('hsl', h, s, l) -> Color Creates a color with the HSL color model. .. lua:function:: new_color('cmyk', c, m, y, k) -> Color Creates a color with the CMYK color model. .. lua:data:: colors This table contains all of the `W3C colors `_. You can also create colors from the #rgb or #rrggbb syntax by indexing this table, like so: ``drystal.colors['#F0F']``. .. code:: local drystal = require 'drystal' local color = drystal.colors.green function drystal.init() drystal.resize(600, 400) print('press d or l or m or a') end function drystal.draw() drystal.set_color(color) drystal.draw_background() end function drystal.key_press(key) if key == 'd' then color = color:darker() end if key == 'l' then color = color:lighter() end if key == 'm' then color = color * drystal.colors.steelblue end if key == 'a' then color = color + drystal.colors.red end end Sprite ^^^^^^ .. lua:class:: Sprite .. lua:data:: source Source table of the sprite. It must contain ``x``, ``y``, ``w`` and ``h`` fields. .. lua:data:: color (={255,255,255}) Tint of the sprite. .. lua:data:: alpha (=255) Alpha of the sprite. .. lua:data:: x, y Coordinates on the screen (or any destination surface). .. lua:data:: w, h Width and height of the sprite. If this is different than values from *source*, the sprite will be resized. .. lua:data:: angle (=0) Rotation of the sprite. .. lua:method:: draw() Draws the sprite on the current *draw on* surface. You have to set the correct sprite sheet as *draw from* surface before use this function. .. lua:function:: new_sprite(source: table[, x=0, y=0[, w=source.w, h=source.h]]) -> Sprite Creates a sprite. :param table source: must contain the following fields: - x, y : coordinates where the sprite is located in the *draw_from* image - w, h : size of the sprite in the *draw_from* image .. code:: local surface = assert(drystal.load_surface('spritesheet.png')) local source = { x=0, y=0, w=32, h=32 } local sprite = drystal.new_sprite(source, 350, 200) sprite.update=function(self, dt) -- custom field self.angle = self.angle + dt * math.pi * 2 end function drystal.update(dt) sprite:update(dt) end function drystal.draw() ... -- draw background, etc surface:draw_from() sprite:draw() end Font rendering -------------- .. lua:class:: Font .. lua:method:: draw(text: str, x, y[, alignment=drystal.aligns.left]) Draws ``text`` at the given coordinates. Supports '\\n'. A particular syntax can be used to create some text effects, for example: - :lua:`"test {r:255|g:0|b:0|!}"` will print the ``!`` in red, - :lua:`"{outline|outg:255|t{nooutline|e}st}"` will print ``test`` with a green outline, except the ``e``. :param integer alignement: - if alignment is ``drystal.aligns.left`` (= 1), text is left aligned (default) - if alignment is ``drystal.aligns.center`` (= 2), text is centered around ``x``. - if alignment is ``drystal.aligns.right`` (= 3), text is right aligned. .. lua:method:: draw_plain(text: str, x, y) Same as :lua:meth:`.Font:draw`, except it doesn't align nor accept formating. Use this function for faster text drawing. .. lua:method:: sizeof(text) -> float, float Returns width and height the text would use if it was drawn on the screen. .. lua:method:: sizeof_plain(text) Returns width and height the text would use if it was drawn on the screen by :lua:meth:`.Font:draw_plain`. .. lua:function:: load_font(filename: str, size: float) -> Font | (nil, error) Loads a truetype font (.ttf file) at desired size. Particle System --------------- .. lua:class:: System .. lua:method:: start() Starts emitting over time. .. lua:method:: emit([amount=1: integer]) Emits ``n`` particle(s). This function is useful when the system is paused and you want a fixed number of particle emission at one particular frame. You still need to call *update* so the particles get updated. .. lua:method:: stop() Stops emitting over time. .. lua:method:: reset() Removes all existing particles. .. lua:method:: clone() -> System Returns an exact copy of the system. .. lua:method:: draw([x=0: float[, y=0: float])) Draws the particles of the system. ``x`` and ``y`` can be used as offset. .. lua:method:: update(dt: float) Updates the system and emits some particles according to the emission rate if the system is started. .. lua:method:: add_size(at_lifetime, size) Adds a size at a desired particle's lifetime. `at_lifetime` is a float between 0 and 1 which indicate when the specified size has to be the current particle size. .. lua:method:: add_size(at_lifetime, minsize, maxsize) Adds a random size at a desired particle's lifetime. .. lua:method:: add_color(at_lifetime, r, g, b) Adds a color at a desired particle's lifetime. `at_lifetime` is a float between 0 and 1 which indicate when the specified color has to be the current particle color. .. lua:method:: add_color(at_lifetime, minr, maxr, ming, maxg, minb, maxg) Adds a random color at a desired particle's lifetime. .. lua:method:: set_texture(tex: Surface, sourcex, sourcey) Sets the texture of the particles. See :lua:func:`drystal.draw_point_tex` for details about ``sourcex`` and ``sourcey``. By default, the system doesn't have texture, particles will be represented by colored squares. .. lua:method:: set_position(x: float, y: float) Sets the position of the system. .. lua:method:: get_position() -> float, float Returns the position of the system. .. lua:method:: set_offset(x: float, y: float) Sets the maximum position offset of a particle when emitted. .. lua:method:: get_offset() -> float, float Returns the position offset of a particle when emitted. .. lua:method:: set_emission_rate(frequency: float) Sets the emission rate of the system (in Hertz). .. lua:method:: get_emission_rate() -> float Returns the emission rate of the system (in Hertz). .. lua:method:: set_lifetime(min: float[, max=min: float]) Sets the lifetime of the particles. .. lua:method:: get_lifetime() -> float, float Returns the lifetime of the particles. .. .. lua:method:: set_min_lifetime(min: float) .. .. lua:method:: get_min_lifetime() -> float .. .. lua:method:: set_max_lifetime(max: float) .. .. lua:method:: get_max_lifetime() -> float .. lua:method:: set_direction(min: float[, max=min: float]) Sets the direction of the particles (in radian). .. lua:method:: get_direction() -> float, float Returns the direction of the particles (in radian). .. .. lua:method:: set_min_direction(min: float) .. .. lua:method:: get_min_direction() -> float .. .. lua:method:: set_max_direction(max: float) .. .. lua:method:: get_max_direction() -> float .. lua:method:: set_initial_acceleration(min: float[, max=min: float]) Sets the initial acceleration of the particles. .. lua:method:: get_initial_acceleration() -> float, float Returns the initial acceleration of the particles. .. .. lua:method:: set_min_initial_acceleration(min: float) .. .. lua:method:: get_min_initial_acceleration() -> float .. .. lua:method:: set_max_initial_acceleration(max: float) .. .. lua:method:: get_max_initial_acceleration() -> float .. lua:method:: set_initial_velocity(min: float[, max=min: float]) Sets the initial velocity of the particles. .. lua:method:: get_initial_velocity() -> float, float Returns the initial velocity of particles. .. .. lua:method:: set_min_initial_velocity(min: float) .. .. lua:method:: get_min_initial_velocity() -> float .. .. lua:method:: set_max_initial_velocity(max: float) .. .. lua:method:: get_max_initial_velocity() -> float .. lua:function:: new_system(x, y[, size=256]) -> System Creates a new particle system at given position. You can specify the default number of particles held by the system with the ``size`` parameter. If the system need to hold more particles, it resizes automatically. .. warning:: By default, attributes are initialized with random values. Make sure to call appropriate setters to obtain the desired particle effect. Physics ------- Learning how to use Box2D_ will help to better understand Drystal's physics module. .. lua:function:: init_physics(gravity_x: float, gravity_y: float[, pixels_per_meter]) See :lua:func:`drystal.set_pixels_per_meter`. .. warning:: If :lua:func:`init_physics` is not called before other physics functions, errors will occur. .. lua:function:: update_physics(dt: float[, timestep=0.01]) Updates the world. .. lua:function:: get_gravity() -> float, float Returns the gravity of the world. .. lua:function:: set_gravity(x, y) Sets the gravity of the world. .. lua:function:: get_pixels_per_meter() -> float Returns the ratio used to convert coordinates and forces to/from Box2D. .. lua:function:: set_pixels_per_meter(pixels_per_meter: float) Sets the ratio used to convert coordinates and forces to/from Box2D. For example, if you set the ratio to ``64``, this means a circle with a radius of 64 will have a radius of 1 meter in the Box2d world. .. lua:function:: on_collision(on_begin, on_end, on_presolve, on_postsolve) Hooks some callbacks to the collision listener. - :lua:`on_begin(body1, body2, x, y, normalx, normaly)` - :lua:`on_end(body1, body2)` - :lua:`on_presolve(body1, body2, x, y, normalx, normaly) -> boolean` - :lua:`on_postsolve(body1, body2)` .. lua:function:: raycast(x1, y1, x2, y2, 'any' | 'closest' | 'farthest') -> body, x, y Returns any body, the closest or the farthest found during a raycast from ``(x1, y1)`` to ``(x2, y2)``. It also returns the point of collision. .. lua:function:: raycast(x1, y1, x2, y2, 'all') -> bodies, points Returns all the bodies found during a raycast from ``(x1, y1)`` to ``(x2, y2)``. It also returns the points of collision. .. lua:function:: raycast(x1, y1, x2, y2, callback) -> body, x, y :lua:`callback(body, fraction, x, y) -> float, boolean` The callback should returns a float and a boolean. The float works like described `here `_. If the boolean is `false` then the body and position is not kept for the returned values of `raycast`, which means you can select which values you want to return. .. lua:function:: query(x1, y1, x2, y2) -> table Returns a table with all bodies contained inside the area defined by ``x1``, ``y1``, ``x2`` and ``y2``. .. lua:function:: new_shape('box', width, height[, x=0, y=0]) -> Shape Creates a *box* shape. The box is centered on x,y which means you have to add an offset of width/2,height/2 during your draws. .. lua:function:: new_shape('circle', radius[, x=0, y=0]) -> Shape Creates a *circle* shape. .. lua:function:: new_shape('chain', x1, y1, x2, y2, ...) -> Shape Creates a *chain* shape. The last point will be linked to the first one. .. lua:function:: new_body(is_dynamic: boolean, [x, y], shape1, shape2, ...) -> Body Creates a body at the given position (or 0, 0) with the given shapes. If ``is_dynamic`` is false, the body will be static. .. lua:function:: new_joint('mouse', body1, body2, max_force[, collide_connected]) -> MouseJoint Creates a mouse joint. .. lua:function:: new_joint('distance', body1, body2[, collide_connected]) -> DistanceJoint Creates a distance joint. .. lua:function:: new_joint('rope', body1, body2[, collide_connected]) -> RopeJoint Creates a rope joint. .. lua:function:: new_joint('revolute', body1, body2, anchor1x, anchor1y, anchor2x, anchor2y, [, collide_connected]) -> RevoluteJoint Creates a revolute joint. .. lua:function:: new_joint('gear', body1, body2, joint1, joint2, ratio, [, collide_connected]) -> GearJoint Creates a gear joint. ``joint1`` and ``joint2`` must be either revolute joints or prismatic joints. .. lua:function:: new_joint('prismatic', body1, body2, anchor1x, anchor1y, anchor2x, anchor2y, axisx, axisy[, collide_connected]) -> PrismaticJoint Creates a prismatic joint. Shape ^^^^^ .. lua:class:: Shape .. lua:method:: set_density(density: float) Sets the density of the shape. .. lua:method:: get_density() -> float Returns the density of the shape. .. lua:method:: set_restitution(restitution float) Sets the restitution of the shape. .. lua:method:: get_restitution() -> float Returns the restitution of the shape. .. lua:method:: set_friction(friction float) Sets the friction of the shape. .. lua:method:: get_friction() -> float Returns the friction of the shape. .. lua:method:: set_sensor(sensor: boolean) If ``sensor`` is ``true``, the shape will not collide but the ``on_collision`` callback will be called. Body ^^^^ .. lua:class:: Body .. lua:method:: set_position(x: float, y: float) Sets the position of the body. .. lua:method:: get_position() -> float, float Returns the position of the body. .. lua:method:: set_angle(angle: float) Sets the angle of the body. .. lua:method:: get_angle() -> float Returns the angle of the body. .. lua:method:: set_linear_velocity(x: float, y: float) Sets the linear velocity of the body. .. lua:method:: get_linear_velocity() -> float, float Returns the linear velocity of the body. .. lua:method:: set_angular_velocity(x: float, y: float) Sets the angular velocity of the body. .. lua:method:: get_angular_velocity() -> float, float Returns the angular velocity of the body. .. lua:method:: set_linear_damping(damping: float) Sets the linear damping of the body. .. lua:method:: get_linear_damping() -> float Returns the linear damping of the body. .. lua:method:: set_angular_damping(damping: float) Sets the angular damping of the body. .. lua:method:: get_angular_damping() -> float Returns the angular damping of the body. .. lua:method:: set_fixed_rotation(fixed: boolean) Fixes the rotation of the body. .. lua:method:: get_fixed_rotation() -> boolean Returns ``true`` if the body has fixed rotation. .. lua:method:: set_active(active: boolean) Enables or disables a body. .. lua:method:: set_bullet(bullet: boolean) Marks the body as a fast moving object. .. lua:method:: get_mass() -> float Returns the mass of the body. .. lua:method:: set_mass_center(x, y) Sets the mass center. .. lua:method:: apply_force(x, y[, x, y]) Applies a force (by default, x, y are the body's center). .. lua:method:: apply_linear_impulse(x, y) Applies a linear impulse (by default, x, y are the body's center). .. lua:method:: apply_angular_impulse(angle) Applies a angular impulse. .. lua:method:: apply_torque(torque) Applies a torque. .. lua:method:: dump() Prints Box2D attributes of the body. .. lua:method:: destroy() Destroys the body. .. warning:: Once the body is destroy, you cannot call any of its functions anymore. Make sure to remove references (:lua:`my_body = nil`). .. warning:: Associated joints are destroyed too. Calling functions on those joints will throw an error, make sure to remove references (:lua:`my_joint = nil`). MouseJoint ^^^^^^^^^^ .. lua:class:: MouseJoint .. lua:method:: set_target(x, y) Sets the target position of the joint. .. lua:method:: destroy() Destroys the joint. RopeJoint ^^^^^^^^^ .. lua:class:: RopeJoint .. lua:method:: set_max_length(max_length: float) Sets the maximum length of the joint .. lua:method:: destroy() Destroys the joint. DistanceJoint ^^^^^^^^^^^^^ .. lua:class:: DistanceJoint .. lua:method:: set_length(length: float) Sets the length of the joint .. lua:method:: set_frequency(frequency: float) Sets the frequency of the joint. .. lua:method:: destroy() Destroys the joint. RevoluteJoint ^^^^^^^^^^^^^ .. lua:class:: RevoluteJoint .. lua:method:: set_angle_limits(min, max) Sets the angle limits of the joint. If ``min`` equals ``max``, limits are disabled. .. lua:method:: set_motor_speed(speed: float[, maxtorque=20: float]) Set the motor speed. If ``speed`` is 0, motor is disabled. .. lua:method:: destroy() Destroys the joint. PrismaticJoint ^^^^^^^^^^^^^^ .. lua:class:: PrismaticJoint .. lua:method:: set_motor_speed(speed: float) Sets the motor speed. .. lua:method:: set_max_motor_force(force: float) Sets the maximum motor force. .. lua:method:: set_enable_motor(enable: boolean) Enables or disables the motor. .. lua:method:: set_enable_limit(enable: boolean) Enables or disables the limit. .. lua:method:: is_limit_enabled() -> boolean Returns ``true`` if the joint has limit. .. lua:method:: is_motor_enabled() -> boolean Returns ``true`` if the motor is enabled. .. lua:method:: destroy() Destroys the joint. Audio ----- The audio module allows you to play short sounds with the :lua:class:`Sound` class and stream ambiance music with the :lua:class:`Music` class. For each class you can either load the audio data from a file or generate it with a callback function. Music ^^^^^ .. lua:class:: Music Musics are for large audio files, mainly for ambiance musics during the game. .. lua:method:: play([loop=false: bool[, onend_callback: function]]) Plays the music (from the beginning). If ``loop`` is true, the music will loop forever. ``onend_callback`` is called when the music finishes (and is not called by :stop()). .. lua:method:: set_pitch(pitch: float) Sets the pitch of the music. ``pitch`` must be > 0. .. lua:method:: set_volume(volume: float) Sets the volume of the music. ``volume`` must be >= 0. .. lua:method:: pause() Pauses the music. .. lua:method:: stop() Stops the music. .. lua:function:: load_music(filename: str) -> Music | (nil, error) Loads a music from a file. .. warning:: Only the Ogg_ format is available. .. lua:function:: load_music(callback: function[, samplesrate=44100: integer]) -> Music | (nil, error) Loads a music according to a callback function generating the music. .. lua:function:: set_music_volume(volume: float [0-1]) Sets the global music volume. Sound ^^^^^ .. lua:class:: Sound Sounds are for short audio files like special effects (e.g. a jump, a shot fired or an explosion). They are loaded directly into memory. So if you want to play longer audio files it is recommended to use :lua:class:`Music` objects which stream the music instead of playing it directly. .. lua:method:: play([volume=1[, x=0[, y=0[, pitch=1]]]) Plays the sound at given volume, position and pitch. :param float volume: between 0 and 1 :param float x: between -1 and 1 (-1 is full left, 1 is full right) :param float y: between -1 and 1 :param float pitch: greater than 0 .. lua:function:: load_sound(filename: str) -> Sound | (nil, error) Loads a sound from a file. It has to be in WAV_ format. Only 44100Hz, 8 bits or 16 bits are supported. If you want to use positional audio, it has to be mono audio. .. lua:function:: load_sound(callback: function, numsamples: integer) -> Sound | (nil, error) Loads a sound according to a callback function generating the sound. .. lua:function:: load_sound(data: table) -> Sound | (nil, error) .. lua:function:: set_sound_volume(volume: float [0-1]) Sets the global sound volume. Storage ------- In browser, this module uses Javascript's localStorage feature. In desktop, it uses files. Storage is a way to store data for future executions. .. lua:function:: store(key: str, value: table) Stores a table in the storage. .. lua:function:: fetch(key: str) -> table | nil Retrieves the table associated with the given key. .. code:: drystal.store('test', {text='wow'}) assert(drystal.fetch('test').text == 'wow') .. note:: Serialization of the table is done by a JSON module. In the browser, data are stored in the ``localStorage`` from Javascript. Web --- .. lua:data:: is_web: boolean Equals ``true`` if the game is executed inside a browser. .. lua:function:: wget(url: string, filename: string, onload: function, onerror: function) .. warning:: :lua:func:`drystal.wget` is not available on the desktop and will throw an error if it is used on the desktop. .. lua:function:: run_js(script: str) .. warning:: :lua:func:`drystal.run_js` is not available on the desktop and will throw an error if it is used on the desktop. Timer ----- .. lua:class:: Timer .. lua:method:: update(dt: float) Updates the timer. ``dt`` is the time elapsed expressed in second, as in :lua:func:`drystal.update`. If the timer finishes, :lua:data:`finished` is set to `true`. If ``callback`` is not :lua:`nil`, it is called. .. lua:data:: finished: boolean Indicates if the timer is finished or not. .. lua:function:: new_timer(duration: float[, callback]) -> Timer Creates a new timer with specified duration and callback. .. warning:: *You* have to update the timer, otherwise it won't finish and the callback won't be called. Utils ----- .. lua:function:: tojson(table) -> string Serializes a Lua table into JSON_ formatted string. .. lua:function:: fromjson(json: string) -> table Converts a JSON_ formatted string back into a Lua table. .. lua:function:: file_exists(filename: str) -> boolean Returns ``true`` if the file exists. .. _Ogg: https://en.wikipedia.org/wiki/Ogg .. _WAV: https://en.wikipedia.org/wiki/WAV .. _Box2D: http://box2d.org/ .. _JSON: http://json.org/ .. _InnerWindow: http://www.w3schools.com/jsref/prop_win_innerheight.asp