3. Table mbm

The engine provides a global table (mbm ) to access some useful functions.
Let’s start explaining how is organized the renderization through the worlds.

3.1. World

my_substituition Explaining how orientation and world works.


World is the way that scene sorts renderizable to be render.

Here the table shows the order to be render:

Order to render

world

z order

Example

1st

3D

1st -2
2nd -1
3th 0
4th 1
5th 2
tMesh = mesh:new('3D',0,0,-2)
tMesh = mesh:new('3D',0,0,-1)
tMesh = mesh:new('3D',0,0,0)
tMesh = mesh:new('3D',0,0,1)
tMesh = mesh:new('3D',0,0,2)

2nd

2DW

1st -2
2nd -1
3th 0
4th 1
5th 2
tSprite = sprite:new('2DW',0,0,-2)
tSprite = sprite:new('2DW',0,0,-1)
tSprite = sprite:new('2DW',0,0,0)
tSprite = sprite:new('2DW',0,0,1)
tSprite = sprite:new('2DW',0,0,2)

3th

2DS

1st -2
2nd -1
3th 0
4th 1
5th 2
tTexture = texture:new('2DS',0,0,-2)
tTexture = texture:new('2DS',0,0,-1)
tTexture = texture:new('2DS',0,0,0)
tTexture = texture:new('2DS',0,0,1)
tTexture = texture:new('2DS',0,0,2)
Follow the explanation of how each world works.

The engine provides 3 type of worlds.
Each renderizable only can belong to one world.
You can specify the world in the renderizable ‘s constructor.
The default world is 2DW if not specified.
All renderizable has the same option in constructor which is the world and initial position.
The position is composed by x, y and z. The z position is what determines the order to render as described on table above.
The world is independent on orientation.
See below how portrait orientation and landscape orientation are:
_images/phone.png

Figure 3.1 Portrait orientation

_images/phone-landscape.png

Figure 3.2 Landscape orientation

Note

Regardless the orientation, the coordinates will be according to the world chosen.

For the explanation of world, we will use the following image:

_images/crate.png

Figure 3.3 crate.png

download crate.png


Next, an explanation about the coordinates and cameras.

  • A 2DS renderizable is for X,Y coordinates at main screen and do not has camera.
    • The origin for 2DS is on top-left screen.

    • The axis X increment to the right.

    • The axis Y increment down.

2D screen coordinates (portrait orientation)

_images/phone-2ds.png

Figure 3.4 Portrait orientation

Example:

tTexture = texture:new('2DS')
if tTexture:load('crate.png') then
   tTexture:setSize(100,100)
end
_images/phone-crate.png

Figure 3.5 Texture crate.png, 2DS, at 0,0 position and portrait orientation.

2D screen coordinates (landscape orientation)

_images/phone-2ds-landscape.png

Figure 3.6 Landscape orientation

Example:

tTexture = texture:new('2DS')
if tTexture:load('crate.png') then
   tTexture:setSize(100,100)
end
_images/phone-crate-landscape.png

Figure 3.7 Texture crate.png, 2DS, at 0,0 position and landscape orientation.

  • A 2DW renderizable is for X,Y coordinates in the world and has its own camera.
    • The origin for 2dw is on center of screen.

    • The axis X increment to the right.

    • The axis Y axis increment up.

_images/phone-2dw.png

Figure 3.8 2D world coordinates (landscape orientation)

Example:

tTexture = texture:new('2DW')
if tTexture:load('crate.png') then
   tTexture:setSize(100,100)
end
_images/phone-crate-2dw.png

Figure 3.9 Texture crate.png, 2DW, at 0,0 position and portrait orientation.

  • A 3D renderizable is for 3d coordinates world and has its own camera (independent from 2D).
    • The origin for 3D is on center of screen.

    • The axis X increment to the right.

    • The axis Y increment up.

    • The axis Z increment in direction to inside the screen.

_images/phone-3d.png

Figure 3.10 3D world coordinates (landscape orientation)

Example:

tTexture = texture:new('3D')
if tTexture:load('crate.png') then
   tTexture:setSize(100,100)
end

3.2. mbm

The engine provides a global table (mbm ) to access some useful functions as explained.
These functions are described below.

3.2.1. addPath

addPath(string newPath)

Add a path to search files.

This command will feed an internal path list in the engine. The path is used to search file on registered folder.

Parameters

stringFull path or partial path folder path.

Example:

if mbm.get("Windows") then
  mbm.addPath("C:\\my_folder_images")
elseif mbm.get("Linux") then
  mbm.addPath("/var/opt/my_folder_images")
elseif mbm.get("Android") then
  mbm.addPath("my_folder_images")
end

3.2.2. allPaths

getAllPaths

Retrieve all path known by the engine.

return

table - tPaths with all paths

Example:

local tPaths = mbm.getAllPaths()
for i=1, #tPaths do
    print(tPaths[i])
end

3.2.3. Callback

3.2.3.1. addOnTouch

addOnTouch(table renderizable, function callback)

Add a call back function to a renderizable object to be called when it is touched.

Parameters
  • tablerenderizable object.

  • functioncallback function. Also can be as string.

Example:

--The function has to be the following signature:
function onTouchSprite (self, x, y,key)
  --here we set anim 'break' when is touched. This is an example.
  self:setAnim('break')
end
--
--
--
--  it works informing the function name as string:
--
mbm.addOnTouch(tMySprite,'onTouchSprite')
--
--
--
-- it works informing the literal function:
mbm.addOnTouch(tMySprite,onTouchSprite)
--
--
--
-- it works informing the anonymous function:
--
mbm.addOnTouch(tMySprite,
  function (self, x, y,key) -- anonymous
     self:setAnim('break')
  end)

3.2.4. Dialogs

3.2.4.1. openFile

openFile(string defaultFileName*, string extension*, ...)

Call a native dialog box to get a file (full path) pointing the defaultFileName and extension allowed. This method does not work on Android.

Parameters
  • stringdefault file name as input.

  • stringextension filter to be applied. Can be 0 or more extensions.

Returns

string - fileName for success or nil to canceled

Example:

local filename = mbm.openFile('mario.png','*.png','*.jpeg')
if filename then
    print("File ",filename)
end

3.2.4.2. openMultiFile

openMultiFile(string defaultFileName*, string extension*, ...)

Call a native dialog box to get one or more files (full path) pointing the defaultFileName and extension allowed. This method does not work on Android.

Parameters
  • stringdefault file name as input.

  • stringextension filter to be applied. Can be 0 or more extensions.

Returns

table - allFiles for success or nil to canceled

Example:

local tFiles = mbm.openMultiFile('mario.png','*.png','*.jpeg')
if tFiles and #tFiles > 0 then
    for i=1, #tFiles do
        print("File ",i,tFiles[i])
    end
end

3.2.4.3. saveFile

saveFile(string defaultFileName*, string extension*, ...)

Call a native dialog box to save a file (it will retrieve a full path) pointing the defaultFileName and extension allowed. This method does not work on Android.

Parameters
  • stringdefault file name as input.

  • stringextension filter to be applied. Can be 0 or more extensions.

Returns

string - fileName for success or nil to canceled

Example:

local filename = mbm.saveFile('test.txt','*.txt','*.lua')
if filename then
    print("File ",filename)
end

3.2.4.4. openFolder

openFolder(string title*, string* defaultPath)

Call a native dialog box to get a folder path pointing the default path optionally. This method does not work on Android.

Parameters
  • stringtitle default to be showed on dialog box.

  • stringdefault path to folder start.

Returns

string - folderName for success or nil to canceled

Example:

local folderPath = mbm.openFolder('Please choose a folder','C://') --for windows for example.
if folderPath then
    print("folder ",folderPath)
end

3.2.4.5. messageBox

messageBox(string title*, string message*, string dialogType*, string iconType*)

Call a native message box dialog. This method does not work on Android.

Parameters
  • stringtitle to be showed on message box.

  • stringmessage to be showed on message box.

  • stringdialog Type one of the valid type as string ok, okcancel, yesno.

  • stringicon Type one of the valid icon type as string info, warning, error, question.

Returns

boolean - true for yes/ok or false to no/canceled

Example:

local ret = mbm.messageBox( 'My Application title',
                            'There is no connection! \n Continue?',
                            'yesno',
                            'info')
if ret then
    print('yes')
else
    print('no')
end

3.2.4.6. inputBox

inputBox(string title*, string message*, string defaultInput*)

Call a native input box dialog. This method does not work on Android.

Parameters
  • stringtitle to be showed on input box.

  • stringmessage to be showed on input box.

  • stringdefault Input a default value as input.

Returns

string - value for the input or nil if canceled

Example:

local name = mbm.inputBox( 'My Application title',
                            'Please enter your name:',
                            'my_name')
if name then
    print('name:',name)
end

3.2.4.7. inputPassword

inputPassword(string title*, string message*, string defaultInput*)

Call a native input box dialog for password. This method does not work on Android.

Parameters
  • stringtitle to be showed on input box.

  • stringmessage to be showed on input box.

  • stringdefault Input a default value as input.

Returns

string - value for the input or nil if canceled

Example:

local password = mbm.inputPassword( 'My Application title',
                            'Please enter your password:')
if password then
    print('password:',password)
end

3.2.5. FPS

3.2.5.1. getFps

getFps(boolean * b_real)

Retrieve the current frames per second. Normally the engine work at 60 fps. The fps can be affected by fakeFps if it is set. In that case pass true to the function that it will be recoveried the real FPS.

Returns

number - fps

Example:

local fps = mbm.getFps()
print('Fps:',fps) -- this could be fake FPS if is set

local b_real = true -- request the real FPS (true)

local fps = mbm.getFps(b_real)
print('Real Fps:',fps) -- This is real FPS

3.2.5.2. setFakeFps

setFakeFps(number cycles, number fps)

Set a fake FPS rate. A fake FPS rate is useful, for example, when we have to do a massive physics calculate for a short period of time.

Also, this is a way to simulate a “slow motion” scene. You just must to put a high FPS for that.

After the end of cycle the FPS come back to normal.

Parameters
  • numbercycles making the fake fps.

  • number – the new value of fake fps.

Example:

local iFakeFps = 60
local iSeconds = 5
mbm.setFakeFps(iFakeFps * iSeconds,iFakeFps)

Hint

  • 180 cycles by 60 fps will fake simulate 3 seconds.

  • 180 cycles by 45 fps will fake simulate 4 seconds.

  • 300 cycles by 50 fps will fake simulate 6 seconds.

3.2.6. Global

3.2.6.1. setGlobal

setGlobal(string key,[string,number,boolean] value)

Set a global value. This allows exchange information among scenes using get and set. The value is permanent among scenes. You can use getGlobal to retrieve values.

Parameters
  • numberkey to the map

  • variable – the value can be any of: string, number or boolean

Example:

mbm.setGlobal('key','something')
mbm.setGlobal('level',10)
mbm.setGlobal('life','100')
mbm.setGlobal('super',true)

3.2.6.2. getGlobal

getGlobal(string name)

Get a global value. This allows retrieving a value previously set using setGlobal in another scene.

Parameters

numberkey to the map

Returns

number, string or boolean. depends on setGlobal

Example:

local key   = mbm.getGlobal('key')
local level = mbm.getGlobal('level')
local life  = mbm.getGlobal('life')
local super = mbm.getGlobal('super)

3.2.6.3. clearGlobals

clearGlobals

Clear all global variables. The variable are set by setGlobal and get by getGlobal. They are called global because remains among scenes.

Example:

mbm.setGlobal('life',100)
mbm.clearGlobals()
local life = mbm.getGlobal('life')
print(life) --nil

3.2.7. getCamera

getCamera(string * world)

Get a camera which gives you the control to the scene. See camera for more information.

Parameters

stringworld can be '2d' or '3d'. default is '2d'.

Returns

camera table reference.

Example:

camera   = mbm.getCamera()     --Get camera 2DW
camera2d = mbm.getCamera('2d') --Get camera 2DW
camera3d = mbm.getCamera('3d') --Get camera 3D

Note

2d represent 2DW since 2DS has no camera

3.2.8. get

get(string what)

Check operation system (OS), compilation flags (versions from libs).

Parameters

stringwhat question as string.

Returns

string or boolean or nil

The following table shows the parameters available for the engine until now:

Parameter

Explanation

Result as

Windows

true if is running on Windows

boolean

Android

true if is running on Android

boolean

Linux

true if is running on Linux

boolean

Version

Get all version used

string

Mbm

Get the current engine version

string

Box-2d

Box 2d version or nil if is not available

string

Opengl

Opengl version or nil if is not available

string

LUA

LUA version or nil if is not available

string

Audiere

Audiere version or nil if is not available

string

Mini-z

Mini-z version or nil if is not available

string

Exe Name

Executable name

string

USE_EDITOR_FEATURES

true if is built with editor features

Useful for editor

boolean

USE_SQLITE3

true if is built with sqlite3 compiled

boolean

USE_DEPRECATED_2_MINOR

true if the version is compatible < 2

boolean

USE_VR

true if is built using virtual reality class beta

boolean

USE_OPENGL_ES

true if is using opengles

boolean

USE_VULKAN

true if is using vulkan

boolean

USE_TILE_MAP_PARSER

true if is built with Tiled Map

boolean

Example:

if mbm.get('Windows') then
    print('Running on windows')
elseif mbm.get('Linux') then
    print('Running on Linux')
elseif mbm.get('Android') then
    print('Running on Linux')
end
print('LUA version'   ,mbm.get('LUA'))
print('Using sqlite3:',mbm.get('USE_SQLITE3') or 'false')

3.2.9. getSplash

getSplash

Retrieve a splash previously set using the method loadScene.

Returns

renderizable - the type is dynamic, depend on loadScene second parameter of course.

Example: scene_1.lua

-- scene_1.lua
tSplash = texture:new('2ds')
tSplash:load('mario.png',50,50)

if mbm.loadScene('scene_2.lua',tSplash) then
   print('scene loaded successfully')
else
   print('Failed to load scene')
end

Example: scene_2.lua

-- scene_2.lua
--retrieve the splash set in the previous scene
tSplash = mbm.getSplash()
tSplash:setPos(100,100)

3.2.10. include

include(string fileName)

Try to include a LUA script file. Return false on error.

Parameters

stringfileName to be loaded.

Returns

boolean - result

The main difference between the command include, dofile or require from LUA is that the command will use an internal list (see addPath.), to search the file. Also in case of fail, it will return false (will not throw an exception).

Is useful when we wish to continue the main script even some dependencies are not found.

Example:

if mbm.include('saved-data.lua') then
  print('loading game...')
  --do something ...
else
  print('There is no saved data...')
  print('New game then...')
end

3.2.11. loadScene

loadScene(string fileNameScene, *renderizable splash)

Load a new scene.

Parameters
  • stringfileNameScene file name scene to be loaded.

  • renderizablesplash table for splash that shows between scenes (optional).

Returns

boolean - true for success.

Example:

if mbm.loadScene('other_Scene.lua') then
   print('scene loaded successfully')
else
   print('Failed to load scene')
end

--passing splash texture as parameter
--
tSplash = texture:new('2ds')
tSplash:load('mario.png',50,50)
if mbm.loadScene('other_Scene.lua',tSplash) then
   print('scene loaded successfully')
else
   print('Failed to load scene')
end

--passing splash file name for texture as parameter
--
if mbm.loadScene('other_Scene.lua','loading.png') then
   print('scene loaded successfully')
else
   print('Failed to load scene')
end

Note

The load method will search in all known path.
You can add a path to search by the method addPath.

The renderizable as splash parameter can be texture, sprite, mesh, gif or particle.
To retrieve the splash in the other scene use getSplash method.

3.2.12. print

print(...)

Overload the native print from LUA getting information from current line.

Parameters
  • var-args – accept the same parameter as native print from LUA.

  • var-argsline if passed will print the line number from LUA file.

  • var-argswarn, error, info if passed will print the colored tag in the output.

  • var-argscolor if passed will print color in the output.

the colors accepted are: red, green, blue, cian, yellow, magenta, white.

Example:

Listing 3.1 overload_print.lua
 1 print('Normal print') 	
 2 
 3 print('line','Hello from print')
 4 
 5 print('error', 'An error ocurred')
 6 
 7 print('error','line','An error ocurred at this line')
 8 
 9 print('green','line','An importatnt thing ocurred at this line')
10 
11 print('magenta','line','This color is magenta')
12 
13 print('magenta','line','info', 'This color is magenta?')
14 
15 print('warn','line','info', 'This is an warning?')
16 
17 print('warn','line', 'No, this is an warning!')
18 
19 print('info','this is an information!')
20   
_images/print_overload.png

Figure 3.11 Print from engine

3.2.13. pause

pause

Pause the application.

It means to stop any physic, timer, and animation. the main loop and callback function are still called by the engine. However, the delta time and fps are set to zero.

Example:

mbm.pause()

3.2.14. resume

resume

Resume the application previously paused (see pause).

Example:

mbm.resume()

3.2.15. pauseAudioOnPauseGame

pauseAudioOnPauseGame(boolean value)

When the application is paused (see pause), all audios are paused automatically, If it is not desired to pause them, it is possible to set this flag to false and all audios are not going to be paused automatically.

Example:

mbm.pauseAudioOnPauseGame(false)

3.2.16. Screen

3.2.16.1. enableClearScreen

enableClearScreen(boolean enable)

Enable or disable clear screen. It is normal any engine clear the screen before starting to render. Some case we may wish to disable this process (enabled by default).

Parameters

booleanvalue to enable or disable clear screen.

Example:

mbm.enableClearScreen(false)

3.2.16.2. getSizeScreen

getSizeScreen

Get the back-buffer size. It considers the current camera’s scale.

Returns

number, number - width, height

Example:

local iW, iH = mbm.getSizeScreen()

3.2.16.3. getRealSizeScreen

getRealSizeScreen

Get the real back-buffer size. It does not consider the current camera’s scale.

Returns

number, number - width, height

Example:

local iW, iH = mbm.getRealSizeScreen()

3.2.16.4. getDisplayMetrics

getDisplayMetrics

Get native size windows.

Returns

number, number - width, height

Example:

local iW, iH = mbm.getDisplayMetrics()

3.2.17. setColor

setColor(number red, number green, number blue)

Change the clear color background. You can disable clear color through enableClearScreen function.

Parameters
  • numberred color. Values between 0.0 and 1.0

  • numbergreen color. Values between 0.0 and 1.0

  • number

    blue color. Values between 0.0 and 1.0

    Example:

local r,g,b = 1.0, 0.0, 1.0
mbm.setColor(r,g,b) --set background color

3.2.18. Transform

3.2.18.1. to2dw

to2dw(number x, number y)

Transform a 2D screen coordinate to 2D world.

Parameters
  • numberx 2D screen coordinate.

  • numbery 2D screen coordinate.

Returns

number, number - x, y

Example:

function onTouchDown(key,x,y)
   local X, Y = mbm.to2dw(x,y)
end

3.2.18.2. to2ds

to2ds(number x, number y)

Transform a 2D world coordinate to 2D screen.

Parameters
  • numberx 2D world coordinate.

  • numbery 2D world coordinate.

Returns

number, number - x, y

Example:

local X, Y = mbm.to2ds(100,200)

3.2.18.3. to3d

to3d(number x, number y, number howFar)

Transform a 2D screen coordinate to 3D world.

Parameters
  • numberx 2D screen coordinate.

  • numbery 2D screen coordinate.

  • numberhow far will be in 3D world.

Returns

number, number, number - x, y, z

Example:

local x, y, z = mbm.to3d(300,100,200)

3.2.19. showConsole

showConsole(boolean enable)

Show console on Windows platform.

Parameters

booleanenable show or hide the screen console on Windows platform.

Example:

mbm.showConsole(true)

3.2.20. getObjectsRendered

getObjectsRendered(string * word)

Retrieve the total objects renderized at the moment.

param string

world 2d, 3d or all.

return

number - total objects renderized

Example:

local iTotalObjRendered   = mbm.getObjectsRendered()
local iTotalObj2DRendered = mbm.getObjectsRendered('2d')
local iTotalObj3DRendered = mbm.getObjectsRendered('3d')

3.2.21. quit

quit

Quit the application. (The application will call onEndScene if exists)

Example:

mbm.quit()

3.3. Texture

The engine uses LodePNG as default to decode and encoder an image.

3.3.1. Supported image types

The engine use some libraries to load textures and the currently supported extension are: .png .jpeg .jpg .bmp .gif .psd .pic .pnm .hdr .tga .tif.

3.3.2. createTexture

createTexture(table pixel, number width, number height, number channel, string *nickName, string *fileNamePng2Save)
This method allow to create texture at runtime.
The texture can have alpha channel or not.
It is also possible to save to as png file.

Note

The pixels for this function are expected in range 0 to 255.

Parameters
  • tablepixel. Can have 3 or 4 pixel per channel. R G B or R G B A sequential.

  • numberwidth texture.

  • numberheight texture.

  • numberchannel texture. Must be 3 or 4.

  • stringnick name. This will be the name applied to texture (optional).

  • stringfile name. if not nil, the texture will be saved as png (optional).

Returns

string - nick name for the texture created or nil has failed.

Attention

If the nick name exists (could be a real name for texture) then the function does nothing. It won’t try to replace pixels instead of. You can check if the texture exists calling the function existTexture

Example:

function write_pixel(tPixel, width, height, x,y, channel, r,g,b)
   index = ((y-1) * width * channel) + ((x-1) * channel) --find the index on the table to be filled
   tPixel[index+1] = r
   tPixel[index+2] = g
   tPixel[index+3] = b
end

local tPixel = {} --our table to store the pixels
local widthTexture  = 4
local heightTexture = 4
local channel       = 3 -- no alpha channel
local r,g,b = 0x00, 0x00, 0xff --blue

--fill the texture table with gradient color (blue to green)
for y = 1, heightTexture do

   for x = 1, widthTexture do
      write_pixel(tPixel,widthTexture, heightTexture, x,y, channel, r,g,b)
   end
end

--Our texture
local sTextureFileName = 'blue-texture.png'

--is important to check if the texture already exists,
--If the texture exists the createTexture method will return ok and do not overwrite the texture.
if not mbm.existTexture(sTextureFileName) then

   print(string.format("texture [%s] does not exist! let's create it then!",sTextureFileName))

   sTextureFileName = mbm.createTexture(tPixel,
                                       widthTexture,
                                       heightTexture,
                                       channel,
                                       sTextureFileName)
end
if sTextureFileName ~= nil then
   print('Successfully created texture:', sTextureFileName)
   --now the texture exist and can be loaded for example from a textureView object:
   tex_view = texture:new()
   tex_view:load(sTextureFileName) --load the texture previously created
   tex_view:setSize(100,100) --our texture only has 4x4 pixel, lets make the frame big to be visible
else
   print('Something goes wrong!')
end
_images/create_blue_texture.png

Figure 3.12 Simple blue texture created at runtime.

Now an example creating a gradient color:

function write_pixel(tPixel, width, height, x,y, channel, r,g,b,a)
   index = ((y-1) * width * channel) + ((x-1) * channel) --find the index on the table to be filled
   tPixel[index+1] = r
   tPixel[index+2] = g
   tPixel[index+3] = b
   tPixel[index+4] = a
end

local tPixel = {} --our table to store the pixels
local widthTexture  = 100
local heightTexture = 100
local channel       = 4

--fill the texture table with gradient color (blue to green)
for y = 1, heightTexture do
   --each column has a gradient collor
   --blue starts from 255 to 0
   --green starts from 0 to 255
   local r = 0x00
   local g = math.ceil((0xff / heightTexture) * (y))
   local b = math.ceil((0xff / heightTexture) * (heightTexture - y))
   local a = 0xff
   for x = 1, widthTexture do
      write_pixel(tPixel,widthTexture, heightTexture, x,y, channel, r,g,b,a)
   end
end

--Our texture
local sTextureFileName = 'blue-to-green-gradient-texture.png'

--is important to check if the texture already exists,
--If the texture exists the createTexture method will return ok and do not overwrite the texture.
if not mbm.existTexture(sTextureFileName) then

   print(string.format("texture [%s] does not exist! let's create it then!",sTextureFileName))

   sTextureFileName = mbm.createTexture(tPixel,
                                       widthTexture,
                                       heightTexture,
                                       channel,
                                       sTextureFileName,
                                       sTextureFileName)
end
if sTextureFileName ~= nil then
   print('Successfully created texture:', sTextureFileName)
   --now the texture exist and can be loaded for example from a textureView object:
   tex_view = texture:new()
   tex_view:load(sTextureFileName) --load the texture previously created
else
   print('Something goes wrong!')
end
_images/blue-to-green-gradient-texture.png

3.3.3. existTexture

existTexture(string name)

This method verify if a texture exist internally. Exist means that it was loaded sometime during the execution the application and it is on memory.

Parameters

stringname. the name can be also a nickname.

Returns

boolean - true if the texture exist and was loaded.

Example:

local ret = mbm.existTexture('Mario.png')
print('Mario.png is loaded in memory:',ret)

3.3.4. loadTexture

loadTexture(string file_name_texture, boolean * alpha)

Load a texture indicating the file name and if it should have alpha (true by default).

This function just load the texture an retrieve details about it. It does not show the texture in the screen. It kept in memory. The next object that will use that texture will get from memory.

Parameters
  • stringname. the name can be also a nickname.

  • booleanalpha. Force or instruct to have alpha (true by default).

Returns

number - width, number - height, number - id from engine . (the id is zero if has failed to load the texture), boolean - has alpha

Example:

local width,height,id, has_alpha = mbm.loadTexture('mario.png')
if id ~= 0 then
    print('Texture loaded, width:',width,'height:',height,'has_alpha:',has_alpha)
else
    print('Could not load the texture!')
end

Note

If the texture is already loaded the function just return the information. It does not reload the texture.

3.4. Shader

3.4.1. getShaderList

getShaderList(boolean returnDetails*, string filter*, boolean bMin*, boolean bMax*, boolean bCode*)

This method retrieve one or more existent shader in a table.

Parameters
  • booleanreturn details flag refers to code and variables. Default is false

  • stringfilter can be ps for pixel shader, vs for vertex shader or nil for both.

  • booleanbMin flag refers to include the min value.

  • booleanbMax flag refers to include the max value.

  • booleanbCode flag refers to include the code.

Returns

table - list of shader detail or list of name (without detail flag).

The following table represent a shader with all flags enabled:

{   name = 'gradient_horizontal.ps',
    code = [[
    precision mediump float;
    uniform sampler2D sample0;
    uniform vec4 right;
    uniform vec4 left;
    varying vec2 vTexCoord;

    void main()
    {
        vec4 c1 = mix(left,right,vTexCoord.x);
        c1.a = min(texture2D(sample0, vTexCoord).a,c1.a);
        gl_FragColor = c1;
    }
    ]],
    var = {right = {0.5,0.5,0.5,0.5}, left = {1,1,1,1}},
    min = {right = {0.0,0.0,0.0,0.0}, left = {0,0,0,0}},
    max = {right = {1.0,1.0,1.0,1.0}, left = {1,1,1,1}}
}

The following table represent a return of getShaderList with detail flag disable:

{
    [1] = 'bloom.ps',
    [2] = 'brightness.ps',
    [3] = 'gradient_horizontal.ps',
    ...
}

Here one example printing all shader name available:

local tShaders = mbm.getShaderList(false,nil)

table.sort(tShaders)

for i=1, # tShaders do
    local name = tShaders[i]
    print(string.format('Shader:[%s]', name))
end

The output:

Shader:[bloom.ps]
Shader:[blur directional.ps]
Shader:[blur zoom.ps]
Shader:[bright extract.ps]
Shader:[brightness.ps]
Shader:[color it.ps]
Shader:[color keying.ps]
Shader:[color tone.ps]
Shader:[edge gradient magnitude.ps]
Shader:[embossed.ps]
Shader:[explosion gaussian.ps]
Shader:[fade radial.ps]
Shader:[fade ripple.ps]
Shader:[fade saturate.ps]
Shader:[fade twist grid.ps]
Shader:[fade twist.ps]
Shader:[fade wave.ps]
Shader:[fade.ps]
Shader:[font.ps]
Shader:[frosty out line.ps]
Shader:[glass tile.ps]
Shader:[invert color.ps]
Shader:[luminance.ps]
Shader:[magnifying glass.ps]
Shader:[multi textura.ps]
Shader:[night vision blur.ps]
Shader:[night vision.ps]
Shader:[old movie.ps]
Shader:[out of bounds.ps]
Shader:[pinch mouse.ps]
Shader:[pinch.ps]
Shader:[poisson.ps]
Shader:[ripple.ps]
Shader:[saturate.ps]
Shader:[scale.vs]
Shader:[sharpen.ps]
Shader:[simple texture.vs]
Shader:[sketch.ps]
Shader:[smooth magnify.ps]
Shader:[spiral.ps]
Shader:[texture map.ps]
Shader:[tiled map.ps]
Shader:[tone mapping.ps]
Shader:[toon.ps]
Shader:[transparent.ps]
Shader:[wave.ps]

Here other example printing all detail available in the shader brightness.ps:

local bVariables = true --enable all variables
local filter     = 'brightness.ps' --put nil to print them all
local bMin       = true --enable min values
local bMax       = true --enable max values
local bCode      = true --enable code

local tShaders   = mbm.getShaderList(bVariables,filter,bMin,bMax,bCode)

function print_recursive_table(t,indent)
    if not indent then indent = 0 end
    if type(t) ~= "table" then
        formatting = string.rep("\t", indent) .. tostring(t)
        print(formatting)
    else
        for k, v in pairs(t) do
            formatting = string.rep("\t", indent) .. k .. ": "
            if type(v) == "table" then
                print(formatting)
                print_recursive_table(v, indent+1)
            else
                print(formatting .. tostring(v))
            end
        end
    end
end

for i=1, # tShaders do
    local tShader = tShaders[i]
    print_recursive_table(tShader)
end

Output:

name: brightness.ps
min:
    brightness:
        1: 0
    contrast:
        1: 0
max:
    brightness:
        1: 1
    contrast:
        1: 2
var:
    brightness:
        1: 0.5
    contrast:
        1: 1.5
code:
precision mediump float;
uniform float brightness;
uniform float contrast;
uniform sampler2D sample0;
varying vec2 vTexCoord;

vec4 xlat_main(in vec2 uv,in vec4 pixelColor)
{
    pixelColor.xyz /= pixelColor.w;
    pixelColor.xyz = (((pixelColor.xyz - 0.500000) * max(contrast, 0.000000)) + 0.500000);
    pixelColor.xyz += brightness;
    pixelColor.xyz *= pixelColor.w;
    return pixelColor;
}

void main()
{
    vec4 color = texture2D(sample0, vTexCoord);
    if (color.a == 0.0)
        discard;
    else
        gl_FragColor = xlat_main(vTexCoord,color);
}

All shader code are described at shader code.

3.4.2. existShader

existShader(string name)

This method verify if a shader exists.

Parameters

stringname for both type of shader ps or vs.

Returns

boolean - result of query.

Example:

if mbm.existShader('blend.ps') then
    print('blend.ps found!')
else
    print('blend.ps not exists!')
end

3.4.3. addShader

addShader(table tShader)

Add a new shader to the engine. Note that you must verify if the shader already exist before try to add it using th function existShader. A shader table is described here at shader table.

Parameters

tabletShader is a table with information for both type of shader ps or vs.

Returns

boolean - result of insert.

Example:

if not mbm.existShader('gradient_horizontal.ps') then
    local tShaderGradient_horizontal =
    {   name = 'gradient_horizontal.ps',
        code = [[
        precision mediump float;
        uniform sampler2D sample0;
        uniform vec4 right;
        uniform vec4 left;
        varying vec2 vTexCoord;

        void main()
        {
            vec4 c1 = mix(left,right,vTexCoord.x);
            c1.a = min(texture2D(sample0, vTexCoord).a,c1.a);
            gl_FragColor = c1;
        }
        ]],
        var = {right = {0.5,0.5,0.5,0.5}, left = {1,1,1,1}},
        min = {right = {0.0,0.0,0.0,0.0}, left = {0,0,0,0}},
        max = {right = {1.0,1.0,1.0,1.0}, left = {1,1,1,1}}
    }

    if not mbm.addShader(tShaderGradient_horizontal) then
        print("Error on add shader:",tShaderGradient_horizontal.name)
    end
else
    print('gradient_horizontal.ps already exists!')
end

More about shader can be found at shader table reference.

3.5. Miniz

3.5.1. compress

compress(string fileIn, string fileOut*, number level*)

Compress a file using the MiniZ library.

Parameters
  • stringfile in is the file that will be compressed.

  • stringfile out is the file name output. If not supplied will overwrite the file in.

  • numberlevel of compression. Valid values are between 0 (do not compress) and 10 (max compression by MiniZ lib).

Returns

boolean - result of compression.

Example:

if mbm.compress('/tmp/my_data.txt') then
    print('Successfully compressed')
else
    print('Failed to compress file')
end

3.5.2. decompress

decompress(string fileIn, string fileOut*)

Decompress a file previously compressed using the method compress which works with the MiniZ library.

Parameters
  • stringfile in is the file that will be decompressed.

  • stringfile out is the file name output. If not supplied will overwrite the file in.

Returns

boolean - result of decompression.

Example:

if mbm.decompress('/tmp/my_data.txt') then
    print('Successfully decompressed')
else
    print('Failed to decompress file')
end

3.6. Aes

3.6.1. encrypt

encrypt(string fileIn, string fileOut*, string password*)

Encrypt a file using the AESCrypt library.

Parameters
  • stringfile in is the file that will be encrypted.

  • stringfile out is the file name output. If not supplied or nil will overwrite the file in.

  • stringpassword to be used. If not informed the engine will use the default one which change each release.

Returns

boolean - result of encrypt.

Example:

if mbm.encrypt('/tmp/my_data.txt',nil,'12345') then
    print('Successfully encrypted')
else
    print('Failed to encrypt')
end

3.6.2. decrypt

decrypt(string fileIn, string fileOut*, string password*)

Decrypt a file previously encrypted using the encrypt method.

Parameters
  • stringfile in is the file that will be decrypted.

  • stringfile out is the file name output. If not supplied or nil will overwrite the file in.

  • stringpassword to be used. If not informed the engine will use the default one which change each release.

Returns

boolean - result of decrypt.

Example:

if mbm.decrypt('/tmp/my_data.txt',nil,'12345') then
    print('Successfully decrypted')
else
    print('Failed to decrypt')
end

3.7. Useful

3.7.1. shuffle

shuffle(string message, string key)

Encrypt alphabetic text by using a series of interwoven Caesar ciphers, based on the letters of a keyword. See Vigenère cipher for more information how it works.

Parameters
  • stringmessage is the text to be encrypted.

  • stringkey is the keyword to shuffle.

Returns

string - text encrypted.

Example:

local original = 'Hello World using Vigenere algorithm'
local key = 'myKeyIsSomethingLikeThis'
local msg = mbm.shuffle(original,key)
local decryptedMsg = mbm.undoShuffle(msg,key)
print('original:',original)      --Hello World using Vigenere algorithm
print('msg:',msg)                --Tcvpm Ogfxh bavtr Fmzlvwdc ejogjwflf
print('decrypted:', decryptedMsg)--Hello World using Vigenere algorithm

3.7.2. undoShuffle

undoShuffle(string message, string key)

Undo a encrypt alphabetic text previously encrypted by the method shuffle .

Parameters
  • stringmessage is the text to be decrypted.

  • stringkey is the keyword to undo the shuffle.

Returns

string - text decrypted.

Example:

local original = 'Hello World using Vigenere algorithm'
local key = '123456What'
local msg = mbm.shuffle(original,key)
local decryptedMsg = mbm.undoShuffle(msg,key)
print('original:',original)      --Hello World using Vigenere algorithm
print('msg:',msg)                --Dllek Whnsd qzigc Vbclnxnl thnokeahf
print('decrypted:', decryptedMsg)--Hello World using Vigenere algorithm

3.7.3. existFile

existFile(string name)

This method verify if a file exist by trying to open it. If the name has not the full path, the engine will try all path known. See addPath.

Parameters

stringname. the file name.

Returns

boolean - true if the file exist.

Example:

local ret = mbm.existFile('test.txt')
print('Test.txt exists:',ret)

3.7.4. getPathEngine

getPathEngine(string* fileName)

This method retrieve the path where the engine is running for Linux and Windows. For Android will retrieve a default path to read and write files runtime.

Parameters

stringfileName to be concatenated at the end of path.

Returns

string - full file name or path engine.

Example:

local fileName = mbm.getPathEngine('test.data')
print('fileName:',fileName)

3.7.5. getFullPath

getFullPath(string* fileName)

This method will try to retrieve the full path from a file. If could not retrieve, will return the same file name.

Parameters

stringfileName to get the full path.

Returns

string - full file name or file name.

Example:

local fileName = mbm.getFullPath('test.data')
print('full path:',fileName)

3.7.6. onErrorStop

onErrorStop(boolean value)

This method inform the engine to stop calling loop method if an error occurred.

Parameters

booleanvalue enabling or disabling calling loop method.

Example:

mbm.onErrorStop(true)

3.7.7. getKeyName

getKeyName(number code)

Recover the correspondent name from a value. This change according to the SO. On Windows for example the 27 code is ESC keyboard. It can be used with the methods onKeyDown and onKeyUp.

Parameters

numbercode number.

Returns

string - key name.

Note

There is an attempt to standardize this method for all SO however is still on progress.

Example:

--example 1
local keyName = mbm.getKeyName(27)
print('keyName:',keyName) -- On Windows the output is 'ESC'

--example 2
function onKeyDown(key)
    if mbm.getKeyName(key) == 'A' then
        print('A pessed')
    elseif mbm.getKeyName(key) == 'left' then
        print('go left')
    elseif mbm.getKeyName(key) == 'right' then
        print('go right')
    elseif mbm.getKeyName(key) == 'space' then
        print('Jump!')
    end
end

3.7.8. getKeyCode

getKeyCode(number key)

Recover the correspondent code from a key (as string). This change according to the SO. On Windows for example the 27 code is ESC keyboard. It can be used with the methods onKeyDown and onKeyUp.

Parameters

numberkey as string.

Returns

number - code for the input key.

Note

There is an attempt to standardize this method for all SO however is still on progress.

Example:

--example 1
local keyCode = mbm.getKeyCode('ESC')
print('keyCode:',keyCode) -- On Windows the output is 27

--example 2
function onKeyDown(key)
    if mbm.getKeyCode('A') == key then
        print('A pressed')
    elseif mbm.getKeyCode('left') == key then
        print('go left')
    elseif mbm.getKeyCode('right') == key then
        print('go right')
    elseif mbm.getKeyCode('space') == key then
        print('Jump!')
    end
end

3.7.9. isCapitalKeyOn

isCapitalKeyOn

Recover the state of Caps Lock on or off.

Example:

function onKeyDown(key)
    if mbm.getKeyCode('A') == key then
        if mbm.isCapitalKeyOn() then
            print('Key A is uppercase')
        else
            print('Key a is lowercase')
        end
    end
end

3.7.10. getIdiom

getIdiom

Recover the language (region) from the system. The return string is according to the SO.

Returns

string - idiom for the SO.

Example:

local idiom = mbm.getIdiom()
print('idiom:',idiom)
--a possible output could be:
--pt-BR
--American English

3.7.11. getUserName

getUserName

Recover the user name form current SO.

Returns

string - user name for the currently SO.

Example:

local user = mbm.getUserName()
print('Welcome ',user)

3.7.12. getSceneName

getSceneName

Recover the currently scene name.

Returns

string - scene name.

Example:

local scene = mbm.getSceneName()
print('Scene:',scene)

3.7.13. refresh

refresh

Force to reload all renderizables object. This is a way to test a lost device graph.

Note

Is not recommend to use this method frequently.

Example:

mbm.refresh()

3.7.14. windowSize

setMinMaxWindowSize(number * min_x, number * min_y, number * max_x, number * max_y)

Set min/max size for the window allowed. Zero means “allowed”.

Note

This method has no effect on Android.

Example:

local min_x,min_y = 800,  600
local max_x,max_y = 1024, 768
mbm.setMinMaxWindowSize(min_x,min_y,max_x,max_y)

3.7.15. listFiles

listFiles(string folder, boolean * recursive)

List files in folder

Parameters

booleanrecursive indicate to list recursive folders.

Returns

table - files listed {separator = '/' or '\\', path = 'folder', [1] = file, [2] ...}.

Example:

local recursive = true -- if recursive is false it will add a empty table with the folder name (path). It will not list the files inside.
local tFolders = mbm.listFiles('/home/jose/project', recursive)

print('separator', tFolders.separator)

for i=1, #tFolders do
    local files = tFolders[i]
    print('Folder:',files.path)
    print('Files:')
    for j=1, #files do
        print(files[j])
    end
    print('')
end

3.8. Android

3.8.1. doCommands

doCommands(string command, string parameter)

Execute a custom native command on Android platform. For example if we want to do a custom command using Java class, this is the way to that.

Parameters
  • stringcommand to be interpreted in native side.

  • stringparameter is a optional parameter to be used in native side.

There are some registered commands in Android. Here they are:

Command

parameter

explanation

API-level

Retrieve the current API level on Android

vibrate

milliseconds

  • Call vibration method during x milliseconds.

  • You have to add permission on manifest for this.

Following some examples calling the methods above:

local apiAndroidLevel = mbm.doCommands('API-level')
print('The current API on Android is:',apiAndroidLevel)

local ms = 500
mbm.doCommands('vibrate',500) --vibrate for 500 milliseconds

Now a simple implementation:

Lua side:

local result = mbm.doCommands('key-command-1','my parameter')
print(result) -- prints "OKAY from Java"

Java side:

@Override
public String OnDoCommands(String key, String param)
{
    if(key== "key-command-1")
    {
        Log.d("java", "my command is :" + key +" parameter:" + param);
        //we can do some specific command here
        return "OKAY from Java";
    }
    else
    {
        return "NOKAY from java!, Command not implemented:" + key;
    }
}

3.8.2. luaFunction

luaFunction(string function, string parameter)

Call a LUA function from Java (Android).

Example:

/*Call Lua native function*/
luaFunction("print","Hello from Java!");

/*Call my personal defined function*/
luaFunction("some_lua_function","execute");
function some_lua_function(param)
    --Do something
    if param == 'execute' then
        print('param is execute. we will execute some command ...')
    end
end