Resource API documentation

Version: alpha

FUNCTION
resource.material() reference to material resource
resource.font() reference to font resource
resource.texture() reference to texture resource
resource.atlas() reference to atlas resource
resource.buffer() reference to buffer resource
resource.tile_source() reference to tile source resource
resource.set() Set a resource
resource.load() load a resource
resource.create_texture() create a texture
resource.release() release a resource
resource.set_texture() set a texture
resource.set_atlas() set atlas data
resource.get_atlas() Get atlas data
resource.set_sound() Update internal sound resource
resource.get_buffer() get resource buffer
resource.set_buffer() set resource buffer
resource.get_text_metrics() gets the text metrics for a font
resource.get_current_manifest() return a reference to the Manifest that is currently loaded
resource.store_resource() add a resource to the data archive and runtime index
resource.store_manifest() create, verify, and store a manifest to device
resource.store_archive() register and store a live update zip file
resource.is_using_liveupdate_data() is any liveupdate data mounted and currently in use
CONSTANT
resource.TEXTURE_TYPE_2D 2D texture type
resource.TEXTURE_TYPE_CUBE_MAP Cube map texture type
resource.TEXTURE_FORMAT_LUMINANCE luminance type texture format
resource.TEXTURE_FORMAT_RGB RGB type texture format
resource.TEXTURE_FORMAT_RGBA RGBA type texture format
resource.LIVEUPDATE_OK LIVEUPDATE_OK
resource.LIVEUPDATE_INVALID_RESOURCE LIVEUPDATE_INVALID_RESOURCE
resource.LIVEUPDATE_VERSION_MISMATCH LIVEUPDATE_VERSION_MISMATCH
resource.LIVEUPDATE_ENGINE_VERSION_MISMATCH LIVEUPDATE_ENGINE_VERSION_MISMATCH
resource.LIVEUPDATE_SIGNATURE_MISMATCH LIVEUPDATE_SIGNATURE_MISMATCH
resource.LIVEUPDATE_SCHEME_MISMATCH LIVEUPDATE_SCHEME_MISMATCH
resource.LIVEUPDATE_BUNDLED_RESOURCE_MISMATCH LIVEUPDATE_BUNDLED_RESOURCE_MISMATCH
resource.LIVEUPDATE_FORMAT_ERROR LIVEUPDATE_FORMAT_ERROR

Functions

resource.material()

resource.material([path])

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Return a hash to the run-time version of the resource
This function can only be called within go.property function calls.

PARAMETERS

[path] string optional resource path string to the resource

RETURNS

path hash a path hash to the binary version of the resource

EXAMPLES

Load a material and set it to a sprite:
go.property("my_material", resource.material("/material.material"))
function init(self)
  go.set("#sprite", "material", self.my_material)
end

resource.font()

resource.font([path])

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Return a hash to the run-time version of the resource
This function can only be called within go.property function calls.

PARAMETERS

[path] string optional resource path string to the resource

RETURNS

path hash a path hash to the binary version of the resource

EXAMPLES

Load a font and set it to a label:
go.property("my_font", resource.font("/font.font"))
function init(self)
  go.set("#label", "font", self.my_font)
end
Load a font and set it to a gui:
go.property("my_font", resource.font("/font.font"))
function init(self)
  go.set("#gui", "fonts", self.my_font, {key = "my_font"})
end

resource.texture()

resource.texture([path])

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Return a hash to the run-time version of the resource
This function can only be called within go.property function calls.

PARAMETERS

[path] string optional resource path string to the resource

RETURNS

path hash a path hash to the binary version of the resource

EXAMPLES

Load a texture and set it to a model:
go.property("my_texture", resource.texture("/texture.png"))
function init(self)
  go.set("#model", "texture0", self.my_texture)
end

resource.atlas()

resource.atlas([path])

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Return a hash to the run-time version of the resource
This function can only be called within go.property function calls.

PARAMETERS

[path] string optional resource path string to the resource

RETURNS

path hash a path hash to the binary version of the resource

EXAMPLES

Load an atlas and set it to a sprite:
go.property("my_atlas", resource.atlas("/atlas.atlas"))
function init(self)
  go.set("#sprite", "image", self.my_atlas)
end
Load an atlas and set it to a gui:
go.property("my_atlas", resource.atlas("/atlas.atlas"))
function init(self)
  go.set("#gui", "textures", self.my_atlas, {key = "my_atlas"})
end

resource.buffer()

resource.buffer([path])

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Return a hash to the run-time version of the resource
This function can only be called within go.property function calls.

PARAMETERS

[path] string optional resource path string to the resource

RETURNS

path hash a path hash to the binary version of the resource

EXAMPLES

Set a unique buffer it to a sprite:
go.property("my_buffer", resource.buffer("/cube.buffer"))
function init(self)
  go.set("#mesh", "vertices", self.my_buffer)
end

resource.tile_source()

resource.tile_source([path])

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Return a hash to the run-time version of the resource
This function can only be called within go.property function calls.

PARAMETERS

[path] string optional resource path string to the resource

RETURNS

path hash a path hash to the binary version of the resource

EXAMPLES

Load tile source and set it to a tile map:
go.property("my_tile_source", resource.tile_source("/tilesource.tilesource"))
function init(self)
  go.set("#tilemap", "tile_source", self.my_tile_source)
end

resource.set()

resource.set(path,buffer)

Sets the resource data for a specific resource

PARAMETERS

path string, hash The path to the resource
buffer buffer The buffer of precreated data, suitable for the intended resource type

EXAMPLES

Assuming the folder "/res" is added to the project custom resources:
-- load a texture resource and set it on a sprite
local buffer = resource.load("/res/new.texturec")
resource.set(go.get("#sprite", "texture0"), buffer)

resource.load()

resource.load(path)

Loads the resource data for a specific resource.

PARAMETERS

path string The path to the resource

RETURNS

buffer buffer Returns the buffer stored on disc

EXAMPLES

-- read custom resource data into buffer
local buffer = resource.load("/resources/datafile")
In order for the engine to include custom resources in the build process, you need to specify them in the "game.project" settings file:
[project]
title = My project
version = 0.1
custom_resources = resources/,assets/level_data.json

resource.create_texture()

resource.create_texture(path,table)

Creates a new texture resource that can be used in the same way as any texture created during build time. The path used for creating the texture must be unique, trying to create a resource at a path that is already registered will trigger an error. If the intention is to instead modify an existing texture, use the resource.set_texture function. Also note that the path to the new texture resource must have a '.texturec' extension, meaning "/path/my_texture" is not a valid path but "/path/my_texture.texturec" is.

PARAMETERS

path string The path to the resource.
table table A table containing info about how to create the texture. Supported entries:
type
number The texture type. Supported values:
  • resource.TEXTURE_TYPE_2D
  • resource.TEXTURE_TYPE_CUBE_MAP
width
number The width of the texture (in pixels)
height
number The width of the texture (in pixels)
format
number The texture format. Supported values:
  • resource.TEXTURE_FORMAT_LUMINANCE
  • resource.TEXTURE_FORMAT_RGB
  • resource.TEXTURE_FORMAT_RGBA
max_mipmaps
number optional max number of mipmaps. Defaults to zero, i.e no mipmap support

RETURNS

path hash The path to the resource.

EXAMPLES

How to create an 128x128 RGBA texture resource and assign it to a model
function init(self)
    local tparams = {
       width          = 128,
       height         = 128,
       type           = resource.TEXTURE_TYPE_2D,
       format         = resource.TEXTURE_FORMAT_RGBA,
   }
   local my_texture_id = resource.create_texture("/my_custom_texture.texturec", tparams)
   go.set("#model", "texture0", my_texture_id)
end

resource.release()

resource.release(path)

Release a resource.

PARAMETERS

path hash, string The path to the resource.

resource.set_texture()

resource.set_texture(path,table,buffer)

Sets the pixel data for a specific texture.

PARAMETERS

path hash, string The path to the resource
table table A table containing info about the texture. Supported entries:
type
number The texture type. Supported values:
  • resource.TEXTURE_TYPE_2D
  • resource.TEXTURE_TYPE_CUBE_MAP
width
number The width of the texture (in pixels)
height
number The width of the texture (in pixels)
format
number The texture format. Supported values:
  • resource.TEXTURE_FORMAT_LUMINANCE
  • resource.TEXTURE_FORMAT_RGB
  • resource.TEXTURE_FORMAT_RGBA
x
number optional x offset of the texture (in pixels)
y
number optional y offset of the texture (in pixels)
mipmap
number optional mipmap to upload the data to
buffer buffer The buffer of precreated pixel data To update a cube map texture you need to pass in six times the amount of data via the buffer, since a cube map has six sides!

EXAMPLES

How to update a specific region of an atlas by using the x,y values. Assumes the already set atlas is a 128x128 texture.
function init(self)
  self.x = 16
  self.y = 16
  self.height = 128 - self.x * 2
  self.width = 128 - self.y * 2
  self.buffer = buffer.create(self.width * self.height, { {name=hash("rgb"), type=buffer.VALUE_TYPE_UINT8, count=3} } )
  self.stream = buffer.get_stream(self.buffer, hash("rgb"))

  for y=1,self.height do
      for x=1,self.width do
          local index = (y-1) * self.width * 3 + (x-1) * 3 + 1
          self.stream[index + 0] = 0xff
          self.stream[index + 1] = 0x80
          self.stream[index + 2] = 0x10
      end
  end

  local resource_path = go.get("#sprite", "texture0")
  local args = { width=self.width, height=self.height, x=self.x, y=self.y, type=resource.TEXTURE_TYPE_2D, format=resource.TEXTURE_FORMAT_RGB, num_mip_maps=1 }
  resource.set_texture( resource_path, args, self.buffer )
end

resource.set_atlas()

resource.set_atlas(path,table)

Sets the data for a specific atlas resource. Setting new atlas data is specified by passing in a texture path for the backing texture of the atlas, a list of geometries and a list of animations that map to the entries in the geometry list. The geometry entries are represented by three lists: vertices, uvs and indices that together represent triangles that are used in other parts of the engine to produce render objects from. Vertex and uv coordinates for the geometries are expected to be in pixel coordinates where 0,0 is the top left corner of the texture. Note that there is no automatic padding or margin support when setting custom data, which could potentially cause filtering artifacts if used with a material sampler that has linear filtering. If that is an issue, you need to calculate padding and margins manually before passing in the geometry data to this function.

PARAMETERS

path hash, string The path to the atlas resource
table table A table containing info about the atlas. Supported entries:
  • texture
    string the path to the texture resource, e.g "/main/my_texture.texturec"
  • animations
    table a list of the animations in the atlas. Supports the following fields:
  • id
    string the id of the animation, used in e.g sprite.play_animation
  • width
    integer the width of the animation
  • height
    integer the height of the animation
  • frame_start
    integer index to the first geometry of the animation. Indices are lua based and must be in the range of 1 .. in atlas.
  • frame_end
    integer index to the last geometry of the animation (non-inclusive). Indices are lua based and must be in the range of 1 .. in atlas.
  • playback
    constant optional playback mode of the animation, the default value is go.PLAYBACK_ONCE_FORWARD
  • fps
    integer optional fps of the animation, the default value is 30
  • flip_vertical
    boolean optional flip the animation vertically, the default value is false
  • flip_horizontal
    boolean optional flip the animation horizontally, the default value is false
  • geometries
    table A list of the geometries that should map to the texture data. Supports the following fields:
  • vertices
    table a list of the vertices in texture space of the geometry in the form {px0, py0, px1, py1, ..., pxn, pyn}
  • uvs
    table a list of the uv coordinates in texture space of the geometry in the form of {u0, v0, u1, v1, ..., un, vn}
  • indices
    table a list of the indices of the geometry in the form {i0, i1, i2, ..., in}. Each tripe in the list represents a triangle.

EXAMPLES

Sets atlas data for a 256x256 texture with a single animation being rendered as a quad
function init(self)
    local params = {
        texture = "/main/my_256x256_texture.texturec",
        animations = {
            {
                id          = "my_animation",
                width       = 256,
                height      = 256,
                frame_start = 1,
                frame_end   = 2,
            }
        },
        geometries = {
            {
                vertices = {
                    0,   0,
                    0,   256,
                    256, 256,
                    256, 0
                },
                uvs = {
                    0, 0,
                    0, 256,
                    256, 256,
                    256, 0
                },
                indices = { 0,1,2,0,2,3 }
            }
        }
    }
    resource.set_atlas("/main/test.a.texturesetc", params)
end

resource.get_atlas()

resource.get_atlas(path)

Returns the atlas data for an atlas

PARAMETERS

path hash, string The path to the atlas resource

RETURNS

data table A table with the following entries:
  • texture
  • geometries
  • animations
See resource.set_atlas for a detailed description of each field

resource.set_sound()

resource.set_sound(path,buffer)

Update internal sound resource (wavc/oggc) with new data

PARAMETERS

path hash, string The path to the resource
buffer string A lua string containing the binary sound data

resource.get_buffer()

resource.get_buffer(path)

gets the buffer from a resource

PARAMETERS

path hash, string The path to the resource

RETURNS

buffer buffer The resource buffer

EXAMPLES

How to get the data from a buffer
function init(self)

    local res_path = go.get("#mesh", "vertices")
    local buf = resource.get_buffer(res_path)
    local stream_positions = buffer.get_stream(self.buffer, "position")

    for i=1,#stream_positions do
        print(i, stream_positions[i])
    end
end

resource.set_buffer()

resource.set_buffer(path,buffer)

sets the buffer of a resource

PARAMETERS

path hash, string The path to the resource
buffer buffer The resource buffer

EXAMPLES

How to set the data from a buffer
local function fill_stream(stream, verts)
    for key, value in ipairs(verts) do
        stream[key] = verts[key]
    end
end

function init(self)

    local res_path = go.get("#mesh", "vertices")

    local positions = {
         1, -1, 0,
         1,  1, 0,
         -1, -1, 0
    }

    local num_verts = #positions / 3

    -- create a new buffer
    local buf = buffer.create(num_verts, {
        { name = hash("position"), type=buffer.VALUE_TYPE_FLOAT32, count = 3 }
    })

    local buf = resource.get_buffer(res_path)
    local stream_positions = buffer.get_stream(buf, "position")

    fill_stream(stream_positions, positions)

    resource.set_buffer(res_path, buf)
end

resource.get_text_metrics()

resource.get_text_metrics(url,text,[options])

Gets the text metrics from a font

PARAMETERS

url hash the font to get the (unscaled) metrics from
text string text to measure
[options] table A table containing parameters for the text. Supported entries:
width
integer The width of the text field. Not used if line_break is false.
leading
number The leading (default 1.0)
tracking
number The leading (default 0.0)
line_break
boolean If the calculation should consider line breaks (default false)

RETURNS

metrics table a table with the following fields:
  • width
  • height
  • max_ascent
  • max_descent

EXAMPLES

function init(self)
    local font = go.get("#label", "font")
    local metrics = resource.get_text_metrics(font, "The quick brown fox\n jumps over the lazy dog")
    pprint(metrics)
end

resource.get_current_manifest()

resource.get_current_manifest()

Return a reference to the Manifest that is currently loaded.

PARAMETERS

None

RETURNS

manifest_reference number reference to the Manifest that is currently loaded

resource.store_resource()

resource.store_resource(manifest_reference,data,hexdigest,callback)

add a resource to the data archive and runtime index. The resource will be verified internally before being added to the data archive.

PARAMETERS

manifest_reference number The manifest to check against.
data string The resource data that should be stored.
hexdigest string The expected hash for the resource, retrieved through collectionproxy.missing_resources.
callback function(self, hexdigest, status) The callback function that is executed once the engine has been attempted to store the resource.
self
object The current object.
hexdigest
string The hexdigest of the resource.
status
boolean Whether or not the resource was successfully stored.

EXAMPLES

function init(self)
    self.manifest = resource.get_current_manifest()
end

local function callback_store_resource(self, hexdigest, status)
     if status == true then
          print("Successfully stored resource: " .. hexdigest)
     else
          print("Failed to store resource: " .. hexdigest)
     end
end

local function load_resources(self, target)
     local resources = collectionproxy.missing_resources(target)
     for _, resource_hash in ipairs(resources) do
          local baseurl = "http://example.defold.com:8000/"
          http.request(baseurl .. resource_hash, "GET", function(self, id, response)
               if response.status == 200 then
                    resource.store_resource(self.manifest, response.response, resource_hash, callback_store_resource)
               else
                    print("Failed to download resource: " .. resource_hash)
               end
          end)
     end
end

resource.store_manifest()

resource.store_manifest(manifest_buffer,callback)

Create a new manifest from a buffer. The created manifest is verified by ensuring that the manifest was signed using the bundled public/private key-pair during the bundle process and that the manifest supports the current running engine version. Once the manifest is verified it is stored on device. The next time the engine starts (or is rebooted) it will look for the stored manifest before loading resources. Storing a new manifest allows the developer to update the game, modify existing resources, or add new resources to the game through LiveUpdate.

PARAMETERS

manifest_buffer string the binary data that represents the manifest
callback function(self, status) the callback function executed once the engine has attempted to store the manifest.
self
object The current object.
status
constant the status of the store operation:
  • resource.LIVEUPATE_OK
  • resource.LIVEUPATE_INVALID_RESOURCE
  • resource.LIVEUPATE_VERSION_MISMATCH
  • resource.LIVEUPATE_ENGINE_VERSION_MISMATCH
  • resource.LIVEUPATE_SIGNATURE_MISMATCH
  • resource.LIVEUPDATE_BUNDLED_RESOURCE_MISMATCH
  • resource.LIVEUPDATE_FORMAT_ERROR

EXAMPLES

How to download a manifest with HTTP and store it on device.
local function store_manifest_cb(self, status)
  if status == resource.LIVEUPATE_OK then
    pprint("Successfully stored manifest. This manifest will be loaded instead of the bundled manifest the next time the engine starts.")
  else
    pprint("Failed to store manifest")
  end
end

local function download_and_store_manifest(self)
  http.request(MANIFEST_URL, "GET", function(self, id, response)
      if response.status == 200 then
        resource.store_manifest(response.response, store_manifest_cb)
      end
    end)
end

resource.store_archive()

resource.store_archive(path,callback,[options])

Stores a zip file and uses it for live update content. The contents of the zip file will be verified against the manifest to ensure file integrity. It is possible to opt out of the resource verification using an option passed to this function. The path is stored in the (internal) live update location.

PARAMETERS

path string the path to the original file on disc
callback function(self, status) the callback function executed after the storage has completed
self
object The current object.
status
constant the status of the store operation (See resource.store_manifest)
[options] table optional table with extra parameters. Supported entries:
  • boolean verify: if archive should be verified as well as stored (defaults to true)

EXAMPLES

How to download an archive with HTTP and store it on device.
local LIVEUPDATE_URL = <a file server url>

-- This can be anything, but you should keep the platform bundles apart
local ZIP_FILENAME = 'defold.resourcepack.zip'

local APP_SAVE_DIR = "LiveUpdateDemo"

function init(self)
    self.proxy = "levels#level1"

    print("INIT: is_using_liveupdate_data:", resource.is_using_liveupdate_data())
    -- let's download the archive
    msg.post("#", "attempt_download_archive")
end

-- helper function to store headers from the http request (e.g. the ETag)
local function store_http_response_headers(name, data)
    local path = sys.get_save_file(APP_SAVE_DIR, name)
    sys.save(path, data)
end

local function load_http_response_headers(name)
    local path = sys.get_save_file(APP_SAVE_DIR, name)
    return sys.load(path)
end

-- returns headers that can potentially generate a 304
-- without redownloading the file again
local function get_http_request_headers(name)
    local data = load_http_response_headers(name)
    local headers = {}
    for k, v in pairs(data) do
        if string.lower(k) == 'etag' then
            headers['If-None-Match'] = v
        elseif string.lower(k) == 'last-modified' then
            headers['If-Modified-Since'] = v
        end
    end
    return headers
end

local function store_archive_cb(self, path, status)
    if status == true then
        print("Successfully stored live update archive!", path)
        sys.reboot()
    else
        print("Failed to store live update archive, ", path)
        -- remove the path
    end
end

function on_message(self, message_id, message, sender)
    if message_id == hash("attempt_download_archive") then

        -- by supplying the ETag, we don't have to redownload the file again
        -- if we already have downloaded it.
        local headers = get_http_request_headers(ZIP_FILENAME .. '.json')
        if not resource.is_using_liveupdate_data() then
            headers = {} -- live update data has been purged, and we need do a fresh download
        end

        local path = sys.get_save_file(APP_SAVE_DIR, ZIP_FILENAME)
        local options = {
            path = path,        -- a temporary file on disc. will be removed upon successful liveupdate storage
            ignore_cache = true -- we don't want to store a (potentially large) duplicate in our http cache
        }

        local url = LIVEUPDATE_URL .. ZIP_FILENAME
        print("Downloading", url)
        http.request(url, "GET", function(self, id, response)
            if response.status == 304 then
                print(string.format("%d: Archive zip file up-to-date", response.status))
            elseif response.status == 200 and response.error == nil then
                -- register the path to the live update system
                resource.store_archive(response.path, store_archive_cb)
                -- at this point, the "path" has been moved internally to a different location

                -- save the ETag for the next run
                store_http_response_headers(ZIP_FILENAME .. '.json', response.headers)
            else
                print("Error when downloading", url, "to", path, ":", response.status, response.error)
            end

            -- If we got a 200, we would call store_archive_cb() then reboot
            -- Second time, if we get here, it should be after a 304, and then
            -- we can load the missing resources from the liveupdate archive
            if resource.is_using_liveupdate_data() then
                msg.post(self.proxy, "load")
            end
        end,
        headers, nil, options)

resource.is_using_liveupdate_data()

resource.is_using_liveupdate_data()

Is any liveupdate data mounted and currently in use? This can be used to determine if a new manifest or zip file should be downloaded.

PARAMETERS

None

RETURNS

bool bool true if a liveupdate archive (any format) has been loaded

Constants

resource.TEXTURE_TYPE_2D

2D texture type


resource.TEXTURE_TYPE_CUBE_MAP

Cube map texture type


resource.TEXTURE_FORMAT_LUMINANCE

luminance type texture format


resource.TEXTURE_FORMAT_RGB

RGB type texture format


resource.TEXTURE_FORMAT_RGBA

RGBA type texture format


resource.LIVEUPDATE_OK

LIVEUPDATE_OK


resource.LIVEUPDATE_INVALID_RESOURCE

The handled resource is invalid.


resource.LIVEUPDATE_VERSION_MISMATCH

Mismatch between manifest expected version and actual version.


resource.LIVEUPDATE_ENGINE_VERSION_MISMATCH

Mismatch between running engine version and engine versions supported by manifest.


resource.LIVEUPDATE_SIGNATURE_MISMATCH

Mismatch between manifest expected signature and actual signature.


resource.LIVEUPDATE_SCHEME_MISMATCH

Mismatch between scheme used to load resources. Resources are loaded with a different scheme than from manifest, for example over HTTP or directly from file. This is typically the case when running the game directly from the editor instead of from a bundle.


resource.LIVEUPDATE_BUNDLED_RESOURCE_MISMATCH

Mismatch between between expected bundled resources and actual bundled resources. The manifest expects a resource to be in the bundle, but it was not found in the bundle. This is typically the case when a non-excluded resource was modified between publishing the bundle and publishing the manifest.


resource.LIVEUPDATE_FORMAT_ERROR

Failed to parse manifest data buffer. The manifest was probably produced by a different engine version.