.. contents:: Table of Contents 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. .. _explaining_2ds_2dw_3d: World ----- .. container:: hatnote hatnote-gray |my_substituition| Explaining how orientation and world works. .. |my_substituition| image:: /_static/phone.png :class: hatnote-icon | .. rubric:: World is the way that :ref:`scene ` sorts :ref:`renderizable ` to be render. | Here the table shows the order to be render: .. _table_order_render: +-------------------+---------+-------------------+---------------------------------------------+ | Order to render | world | ``z`` order | Example | +===================+=========+===================+=============================================+ | 1st | ``3D`` | | 1st ``-2`` | | ``tMesh = mesh:new('3D',0,0,-2)`` | | | | | 2nd ``-1`` | | ``tMesh = mesh:new('3D',0,0,-1)`` | | | | | 3th ``0`` | | ``tMesh = mesh:new('3D',0,0,0)`` | | | | | 4th ``1`` | | ``tMesh = mesh:new('3D',0,0,1)`` | | | | | 5th ``2`` | | ``tMesh = mesh:new('3D',0,0,2)`` | +-------------------+---------+-------------------+---------------------------------------------+ | 2nd | ``2DW`` | | 1st ``-2`` | | ``tSprite = sprite:new('2DW',0,0,-2)`` | | | | | 2nd ``-1`` | | ``tSprite = sprite:new('2DW',0,0,-1)`` | | | | | 3th ``0`` | | ``tSprite = sprite:new('2DW',0,0,0)`` | | | | | 4th ``1`` | | ``tSprite = sprite:new('2DW',0,0,1)`` | | | | | 5th ``2`` | | ``tSprite = sprite:new('2DW',0,0,2)`` | +-------------------+---------+-------------------+---------------------------------------------+ | 3th | ``2DS`` | | 1st ``-2`` | | ``tTexture = texture:new('2DS',0,0,-2)`` | | | | | 2nd ``-1`` | | ``tTexture = texture:new('2DS',0,0,-1)`` | | | | | 3th ``0`` | | ``tTexture = texture:new('2DS',0,0,0)`` | | | | | 4th ``1`` | | ``tTexture = texture:new('2DS',0,0,1)`` | | | | | 5th ``2`` | | ``tTexture = texture:new('2DS',0,0,2)`` | +-------------------+---------+-------------------+---------------------------------------------+ | Follow the explanation of how each ``world`` works. | | The engine provides 3 type of ``worlds``. | Each :ref:`renderizable ` only can belong to one ``world``. | You can specify the world in the :ref:`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 :ref:`table ` above. | The ``world`` is independent on orientation. | See below how portrait orientation and landscape orientation are: .. figure:: _static/phone.png :align: center :figclass: align-center Portrait orientation .. figure:: _static/phone-landscape.png :align: center :figclass: align-center Landscape orientation .. Note:: Regardless the orientation, the coordinates will be according to the ``world`` chosen. .. rubric:: For the explanation of ``world``, we will use the following image: .. figure:: _static/crate.png :align: center :width: 200px :height: 200px :figclass: align-center crate.png :download:`download crate.png <_static/crate.png>` | | Next, an explanation about the coordinates and :ref:`cameras `. | - A ``2DS`` :ref:`renderizable ` is for ``X,Y`` coordinates at main **screen** and do not has :ref:`camera `. * The origin for ``2DS`` is on **top-left screen**. * The axis ``X`` increment to the **right**. * The axis ``Y`` increment **down**. .. rubric:: 2D screen coordinates (portrait orientation) .. figure:: _static/phone-2ds.png :align: center :figclass: align-center Portrait orientation *Example:* .. code-block:: lua :emphasize-lines: 1 tTexture = texture:new('2DS') if tTexture:load('crate.png') then tTexture:setSize(100,100) end .. figure:: _static/phone-crate.png :align: center :figclass: align-center Texture `crate.png`, ``2DS``, at ``0,0`` position and ``portrait`` orientation. .. rubric:: 2D screen coordinates (landscape orientation) .. figure:: _static/phone-2ds-landscape.png :align: center :figclass: align-center Landscape orientation *Example:* .. code-block:: lua :emphasize-lines: 1 tTexture = texture:new('2DS') if tTexture:load('crate.png') then tTexture:setSize(100,100) end .. figure:: _static/phone-crate-landscape.png :align: center :figclass: align-center Texture `crate.png`, ``2DS``, at ``0,0`` position and ``landscape`` orientation. - A ``2DW`` :ref:`renderizable ` is for ``X,Y`` coordinates in the **world** and has its own :ref:`camera `. * The origin for ``2dw`` is on **center** of screen. * The axis ``X`` increment to the **right**. * The axis ``Y`` axis increment **up**. .. figure:: _static/phone-2dw.png :align: center :figclass: align-center 2D world coordinates (landscape orientation) *Example:* .. code-block:: lua :emphasize-lines: 1 tTexture = texture:new('2DW') if tTexture:load('crate.png') then tTexture:setSize(100,100) end .. figure:: _static/phone-crate-2dw.png :align: center :figclass: align-center Texture `crate.png`, ``2DW``, at ``0,0`` position and ``portrait`` orientation. - A ``3D`` :ref:`renderizable ` is for 3d coordinates **world** and has its own :ref:`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. .. figure:: _static/phone-3d.png :align: center :figclass: align-center 3D world coordinates (landscape orientation) *Example:* .. code-block:: lua :emphasize-lines: 1 tTexture = texture:new('3D') if tTexture:load('crate.png') then tTexture:setSize(100,100) end mbm --- | The engine provides a global table (**mbm** ) to access some useful functions as explained. | These functions are described below. addPath ^^^^^^^ .. _addPath: .. data:: 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. :param string: **Full path** or **partial path** folder path. *Example:* .. code-block:: lua 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 allPaths ^^^^^^^^ .. data:: getAllPaths() Retrieve all path known by the engine. :return: :literal:`table` - *tPaths with all paths* *Example:* .. code-block:: lua local tPaths = mbm.getAllPaths() for i=1, #tPaths do print(tPaths[i]) end Callback ^^^^^^^^ addOnTouch """""""""" .. data:: addOnTouch(table renderizable, function callback) Add a call back function to a renderizable object to be called when it is touched. :param table: **renderizable** object. :param function: **callback function**. Also can be as string. *Example:* .. code-block:: lua --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) Dialogs ^^^^^^^ openFile """""""" .. data:: 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. :param string: **default file name** as input. :param string: **extension** filter to be applied. Can be 0 or more extensions. :return: :literal:`string` - *fileName for success or nil to canceled* *Example:* .. code-block:: lua local filename = mbm.openFile('mario.png','*.png','*.jpeg') if filename then print("File ",filename) end openMultiFile """"""""""""" .. data:: 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. :param string: **default file name** as input. :param string: **extension** filter to be applied. Can be 0 or more extensions. :return: :literal:`table` - *allFiles for success or nil to canceled* *Example:* .. code-block:: lua 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 saveFile """""""" .. data:: 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. :param string: **default file name** as input. :param string: **extension** filter to be applied. Can be 0 or more extensions. :return: :literal:`string` - *fileName for success or nil to canceled* *Example:* .. code-block:: lua local filename = mbm.saveFile('test.txt','*.txt','*.lua') if filename then print("File ",filename) end openFolder """""""""" .. data:: 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. :param string: **title** default to be showed on dialog box. :param string: **default path** to folder start. :return: :literal:`string` - *folderName for success or nil to canceled* *Example:* .. code-block:: lua local folderPath = mbm.openFolder('Please choose a folder','C://') --for windows for example. if folderPath then print("folder ",folderPath) end messageBox """""""""" .. data:: messageBox(string title*, string message*, string dialogType*, string iconType*) Call a native message box dialog. This method does not work on Android. :param string: **title** to be showed on message box. :param string: **message** to be showed on message box. :param string: **dialog Type** one of the valid type as string :literal:`ok`, :literal:`okcancel`, :literal:`yesno`. :param string: **icon Type** one of the valid icon type as string :literal:`info`, :literal:`warning`, :literal:`error`, :literal:`question`. :return: :literal:`boolean` - *true* for yes/ok or *false* to no/canceled *Example:* .. code-block:: lua local ret = mbm.messageBox( 'My Application title', 'There is no connection! \n Continue?', 'yesno', 'info') if ret then print('yes') else print('no') end inputBox """""""" .. data:: inputBox(string title*, string message*, string defaultInput*) Call a native input box dialog. This method does not work on Android. :param string: **title** to be showed on input box. :param string: **message** to be showed on input box. :param string: **default Input** a default value as input. :return: :literal:`string` - *value* for the input or *nil* if canceled *Example:* .. code-block:: lua local name = mbm.inputBox( 'My Application title', 'Please enter your name:', 'my_name') if name then print('name:',name) end inputPassword """"""""""""" .. data:: inputPassword(string title*, string message*, string defaultInput*) Call a native input box dialog for password. This method does not work on Android. :param string: **title** to be showed on input box. :param string: **message** to be showed on input box. :param string: **default Input** a default value as input. :return: :literal:`string` - *value* for the input or *nil* if canceled *Example:* .. code-block:: lua local password = mbm.inputPassword( 'My Application title', 'Please enter your password:') if password then print('password:',password) end FPS ^^^ getFps """""" .. data:: getFps(boolean * b_real) Retrieve the current frames per second. Normally the engine work at 60 fps. The fps can be affected by :ref:`fakeFps ` if it is set. In that case pass ``true`` to the function that it will be recoveried the real FPS. :return: ``number`` *- fps* *Example:* .. code-block:: lua 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 setFakeFps """""""""" .. _fake_fps: .. data:: 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. :param number: **cycles** making the fake fps. :param number: the new value of fake **fps**. *Example:* .. code-block:: lua 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. Global ^^^^^^ setGlobal """"""""" .. _setGlobal: .. data:: 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 :ref:`getGlobal ` to retrieve values. :param number: **key** to the map :param variable: the **value** can be any of: ``string``, ``number`` or ``boolean`` *Example:* .. code-block:: lua mbm.setGlobal('key','something') mbm.setGlobal('level',10) mbm.setGlobal('life','100') mbm.setGlobal('super',true) getGlobal """"""""" .. _getGlobal: .. data:: getGlobal(string name) Get a global value. This allows retrieving a value previously set using :ref:`setGlobal ` in another scene. :param number: *key* to the map :return: :literal:`number`, :literal:`string` or :literal:`boolean`. depends on :ref:`setGlobal ` *Example:* .. code-block:: lua local key = mbm.getGlobal('key') local level = mbm.getGlobal('level') local life = mbm.getGlobal('life') local super = mbm.getGlobal('super) clearGlobals """""""""""" .. data:: clearGlobals() Clear all global variables. The variable are set by :ref:`setGlobal ` and get by :ref:`getGlobal `. They are called global because remains among scenes. *Example:* .. code-block:: lua mbm.setGlobal('life',100) mbm.clearGlobals() local life = mbm.getGlobal('life') print(life) --nil .. _getCamera: getCamera ^^^^^^^^^ .. data:: getCamera(string * world) Get a camera which gives you the control to the scene. See :ref:`camera ` for more information. :param string: **world** can be ``'2d'`` or ``'3d'``. default is ``'2d'``. :return: :ref:`camera ` *table* reference. *Example:* .. code-block:: lua 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 :ref:`camera ` get ^^^ .. data:: get(string what) Check operation system (OS), compilation flags (versions from libs). :param string: **what** question as string. :return: ``string`` or ``boolean`` or ``nil`` .. _flag_compilation: 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_SQLITE3` | ``true`` if is built with sqlite3 compiled | ``boolean`` | +----------------------------+------------------------------------------------------------------+-------------------------------------------+ | `MBM_ENABLE_MESH_LEGACY_V7`| ``true`` if legacy mesh v7 support is enabled | ``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 | ``boolean`` | | | `Tiled Map `__ | | +----------------------------+------------------------------------------------------------------+-------------------------------------------+ *Example:* .. code-block:: lua 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') .. _getSplash: getSplash ^^^^^^^^^ .. data:: getSplash() Retrieve a splash previously set using the method :ref:`loadScene `. :return: :literal:`renderizable` - the type is dynamic, depend on :ref:`loadScene ` second parameter of course. *Example: scene_1.lua* .. code-block:: 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* .. code-block:: lua -- scene_2.lua --retrieve the splash set in the previous scene tSplash = mbm.getSplash() tSplash:setPos(100,100) include ^^^^^^^ .. data:: include(string fileName) Try to include a LUA script file. Return ``false`` on error. :param string: **fileName** to be loaded. :return: ``boolean`` *- result* The main difference between the command ``include``, ``dofile`` or ``require`` from LUA is that the command will use an internal list (see :ref:`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:* .. code-block:: lua if mbm.include('saved-data.lua') then print('loading game...') --do something ... else print('There is no saved data...') print('New game then...') end loadScene ^^^^^^^^^ .. _loadScene: .. data:: loadScene (string fileNameScene,*renderizable splash) Load a new scene. :param string: **fileNameScene** file name scene to be loaded. :param renderizable: **splash** table for splash that shows between scenes (optional). :return: :literal:`boolean` - *true* for success. *Example:* .. code-block:: lua 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 :guilabel:`load` method will search in all known path. | You can add a path to search by the method :ref:`addPath `. | | The :ref:`renderizable ` as splash parameter can be :ref:`texture `, :ref:`sprite `, :ref:`mesh `, :ref:`gif ` or :ref:`particle `. | To retrieve the splash in the other scene use :ref:`getSplash ` method. print ^^^^^ .. data:: print(...) Overload the native print from LUA getting information from current line. :param var-args: accept the same parameter as native print from LUA. :param var-args: ``line`` if passed will print the line number from LUA file. :param var-args: ``warn``, ``error``, ``info`` if passed will print the colored tag in the output. :param var-args: ``color`` if passed will print color in the output. the colors accepted are: ``red``, ``green``, ``blue``, ``cian``, ``yellow``, ``magenta``, ``white``. *Example:* .. literalinclude:: example_modules/overload_print.lua :language: lua :linenos: :emphasize-lines: 3,7,9,11,13,15,17 :caption: overload_print.lua :name: overload_print.lua .. figure:: _static/print_overload.png :align: center :figclass: align-center Print from engine pause ^^^^^ .. _pause: .. data:: pause() :noindex: 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:* .. code-block:: lua mbm.pause() resume ^^^^^^ .. data:: resume() Resume the application previously paused (see :ref:`pause `). *Example:* .. code-block:: lua mbm.resume() pauseAudioOnPauseGame ^^^^^^^^^^^^^^^^^^^^^ .. data:: pauseAudioOnPauseGame(boolean value) When the application is paused (see :ref:`pause `), all audios are paused automatically, If it is not desired to pause them, it is possible to set this flag to :literal:`false` and all audios are not going to be paused automatically. *Example:* .. code-block:: lua mbm.pauseAudioOnPauseGame(false) Screen ^^^^^^ enableClearScreen """"""""""""""""" .. _enableClearScreen: .. data:: 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). :param boolean: **value** to enable or disable clear screen. *Example:* .. code-block:: lua mbm.enableClearScreen(false) getSizeScreen """"""""""""" .. _getSizeScreen: .. data:: getSizeScreen() Get the back-buffer size. It considers the current camera's scale. :return: :literal:`number`, :literal:`number` - *width, height* *Example:* .. code-block:: lua local iW, iH = mbm.getSizeScreen() getRealSizeScreen """"""""""""""""" .. data:: getRealSizeScreen() Get the real back-buffer size. It does not consider the current camera's scale. :return: :literal:`number`, :literal:`number` - *width, height* *Example:* .. code-block:: lua local iW, iH = mbm.getRealSizeScreen() getDisplayMetrics """"""""""""""""" .. data:: getDisplayMetrics() Get native size windows. :return: ``number``, ``number`` *- width, height* *Example:* .. code-block:: lua local iW, iH = mbm.getDisplayMetrics() setColor ^^^^^^^^ .. data:: setColor(number red,number green,number blue) :noindex: Change the clear color background. You can disable clear color through :ref:`enableClearScreen ` function. :param number: **red** color. Values between 0.0 and 1.0 :param number: **green** color. Values between 0.0 and 1.0 :param number: **blue** color. Values between 0.0 and 1.0 *Example:* .. code-block:: lua local r,g,b = 1.0, 0.0, 1.0 mbm.setColor(r,g,b) --set background color Transform ^^^^^^^^^ to2dw """"" .. data:: to2dw(number x,number y) Transform a 2D screen coordinate to 2D world. :param number: **x** 2D screen coordinate. :param number: **y** 2D screen coordinate. :return: ``number``, ``number`` - *x, y* *Example:* .. code-block:: lua function onTouchDown(key,x,y) local X, Y = mbm.to2dw(x,y) end to2ds """"" .. data:: to2ds (number x,number y) Transform a 2D world coordinate to 2D screen. :param number: **x** 2D world coordinate. :param number: **y** 2D world coordinate. :return: ``number``, ``number`` - *x, y* *Example:* .. code-block:: lua local X, Y = mbm.to2ds(100,200) to3d """" .. data:: to3d (number x,number y,number howFar) Transform a 2D screen coordinate to 3D world. :param number: **x** 2D screen coordinate. :param number: **y** 2D screen coordinate. :param number: **how far** will be in 3D world. :return: ``number``, ``number``, ``number`` - *x, y, z* *Example:* .. code-block:: lua local x, y, z = mbm.to3d(300,100,200) showConsole ^^^^^^^^^^^ .. data:: showConsole (boolean enable) Show console on Windows platform. :param boolean: **enable** show or hide the screen console on Windows platform. *Example:* .. code-block:: lua mbm.showConsole(true) getObjectsRendered ^^^^^^^^^^^^^^^^^^ .. data:: getObjectsRendered (string * word) Retrieve the total objects renderized at the moment. :param string: **world** ``2d``, ``3d`` or ``all``. :return: :literal:`number` - *total objects renderized* *Example:* .. code-block:: lua local iTotalObjRendered = mbm.getObjectsRendered() local iTotalObj2DRendered = mbm.getObjectsRendered('2d') local iTotalObj3DRendered = mbm.getObjectsRendered('3d') quit ^^^^ .. data:: quit () Quit the application. (The application will call :ref:`onEndScene ` if exists) *Example:* .. code-block:: lua mbm.quit() .. _images_supported_types: Texture ------- The engine uses `LodePNG `__ as default to decode and encoder an image. 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``. .. _creating_texture: createTexture ^^^^^^^^^^^^^ .. data:: 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``. :param table: **pixel**. Can have 3 or 4 pixel per channel. :literal:`R G B` or :literal:`R G B A` sequential. :param number: **width** texture. :param number: **height** texture. :param number: **channel** texture. Must be 3 or 4. :param string: **nick name**. This will be the name applied to texture (optional). :param string: **file name**. if not ``nil``, the texture will be saved as ``png`` (optional). :return: :literal:`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 :ref:`existTexture ` *Example:* .. code-block:: lua 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 .. figure:: _static/create_blue_texture.png :align: center :figclass: align-center Simple blue texture created at runtime. Now an example creating a gradient color: .. code-block:: lua 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 .. figure:: _static/blue-to-green-gradient-texture.png :align: center :figclass: align-center existTexture ^^^^^^^^^^^^ .. _existTexture: .. data:: 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. :param string: **name**. the name can be also a nickname. :return: :literal:`boolean` - ``true`` if the texture exist and was loaded. *Example:* .. code-block:: lua local ret = mbm.existTexture('Mario.png') print('Mario.png is loaded in memory:',ret) loadTexture ^^^^^^^^^^^ .. data:: 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. :param string: **name**. the name can be also a nickname. :param boolean: **alpha**. Force or instruct to have alpha (``true`` by default). :return: ``number`` - *width*, ``number`` - *height*, ``number`` - *id* from engine . (the id is ``zero`` if has failed to load the texture), ``boolean`` - *has alpha* *Example:* .. code-block:: lua 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. Shader ------ getShaderList ^^^^^^^^^^^^^ .. _getShaderList: .. data:: getShaderList(boolean returnDetails*, string filter*, boolean bMin*, boolean bMax*, boolean bCode*) This method retrieve one or more existent shader in a table. :param boolean: **return details** flag refers to code and variables. Default is :literal:`false` :param string: **filter** can be :literal:`ps` for *pixel shader*, :literal:`vs` for *vertex shader* or :literal:`nil` for both. :param boolean: **bMin** flag refers to include the *min* value. :param boolean: **bMax** flag refers to include the *max* value. :param boolean: **bCode** flag refers to include the *code*. :return: ``table`` - *list* of shader detail or *list* of name (without detail flag). The following table represent a shader with all flags enabled: .. code-block:: lua { 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 :ref:`getShaderList ` with detail flag disable: .. code-block:: lua { [1] = 'bloom.ps', [2] = 'brightness.ps', [3] = 'gradient_horizontal.ps', ... } Here one example printing all shader name available: .. code-block:: lua 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: .. code-block:: console 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: .. code-block:: lua 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*: .. code-block:: text 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 :ref:`shader code `. existShader ^^^^^^^^^^^ .. _existShader: .. data:: existShader(string name) This method verify if a shader exists. :param string: **name** for both type of shader :literal:`ps` or :literal:`vs`. :return: :literal:`boolean` - *result* of query. *Example:* .. code-block:: lua if mbm.existShader('blend.ps') then print('blend.ps found!') else print('blend.ps not exists!') end addShader ^^^^^^^^^ .. data:: 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 :ref:`existShader `. A shader table is described here at :ref:`shader table `. :param table: **tShader** is a table with information for both type of shader :literal:`ps` or :literal:`vs`. :return: :literal:`boolean` - *result* of insert. *Example:* .. code-block:: lua 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 :ref:`shader table ` reference. Miniz ----- compress ^^^^^^^^ .. _compress: .. data:: compress(string fileIn, string fileOut*, number level*) Compress a file using the `MiniZ `__ library. :param string: **file in** is the file that will be compressed. :param string: **file out** is the file name output. If not supplied will overwrite the file in. :param number: **level** of compression. Valid values are between 0 (do not compress) and 10 (max compression by MiniZ lib). :return: :literal:`boolean` - *result* of compression. *Example:* .. code-block:: lua if mbm.compress('/tmp/my_data.txt') then print('Successfully compressed') else print('Failed to compress file') end decompress ^^^^^^^^^^ .. data:: decompress(string fileIn, string fileOut*) Decompress a file previously compressed using the method :ref:`compress ` which works with the `MiniZ `__ library. :param string: **file in** is the file that will be decompressed. :param string: **file out** is the file name output. If not supplied will overwrite the file in. :return: :literal:`boolean` - *result* of decompression. *Example:* .. code-block:: lua if mbm.decompress('/tmp/my_data.txt') then print('Successfully decompressed') else print('Failed to decompress file') end Aes --- encrypt ^^^^^^^ .. _encrypt: .. data:: encrypt(string fileIn, string fileOut*, string password*) Encrypt a file using the `AESCrypt `__ library. :param string: **file in** is the file that will be encrypted. :param string: **file out** is the file name output. If not supplied or *nil* will overwrite the file in. :param string: **password** to be used. If not informed the engine will use the default one which change each release. :return: :literal:`boolean` - *result* of encrypt. *Example:* .. code-block:: lua if mbm.encrypt('/tmp/my_data.txt',nil,'12345') then print('Successfully encrypted') else print('Failed to encrypt') end decrypt ^^^^^^^ .. data:: decrypt(string fileIn, string fileOut*, string password*) Decrypt a file previously encrypted using the :ref:`encrypt ` method. :param string: **file in** is the file that will be decrypted. :param string: **file out** is the file name output. If not supplied or *nil* will overwrite the file in. :param string: **password** to be used. If not informed the engine will use the default one which change each release. :return: :literal:`boolean` - *result* of decrypt. *Example:* .. code-block:: lua if mbm.decrypt('/tmp/my_data.txt',nil,'12345') then print('Successfully decrypted') else print('Failed to decrypt') end Useful ------ shuffle ^^^^^^^ .. _shuffle: .. data:: 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. :param string: **message** is the text to be encrypted. :param string: **key** is the keyword to shuffle. :return: :literal:`string` - *text* encrypted. *Example:* .. code-block:: lua 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 undoShuffle ^^^^^^^^^^^ .. data:: undoShuffle(string message, string key) Undo a encrypt alphabetic text previously encrypted by the method :ref:`shuffle ` . :param string: **message** is the text to be decrypted. :param string: **key** is the keyword to undo the shuffle. :return: :literal:`string` - *text* decrypted. *Example:* .. code-block:: lua 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 existFile ^^^^^^^^^ .. _existFile: .. data:: 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 :ref:`addPath `. :param string: **name**. the file name. :return: :literal:`boolean` - *true* if the file exist. *Example:* .. code-block:: lua local ret = mbm.existFile('test.txt') print('Test.txt exists:',ret) getPathEngine ^^^^^^^^^^^^^ .. TODO: review on linux .. _getPathEngine: .. data:: 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. :param string: **fileName** to be concatenated at the end of path. :return: :literal:`string` - *full file name* or path engine. *Example:* .. code-block:: lua local fileName = mbm.getPathEngine('test.data') print('fileName:',fileName) getFullPath ^^^^^^^^^^^ .. _getFullPath: .. data:: 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. :param string: **fileName** to get the full path. :return: :literal:`string` - *full file name* or file name. *Example:* .. code-block:: lua local fileName = mbm.getFullPath('test.data') print('full path:',fileName) onErrorStop ^^^^^^^^^^^ .. data:: onErrorStop(boolean value) This method inform the engine to stop calling :ref:`loop ` method if an error occurred. :param boolean: **value** enabling or disabling calling :ref:`loop ` method. *Example:* .. code-block:: lua mbm.onErrorStop(true) getKeyName ^^^^^^^^^^ .. TODO: fix for linux .. data:: getKeyName(number code) Recover the correspondent name from a value. This change according to the SO. On Windows for example the 27 code is :literal:`ESC` keyboard. It can be used with the methods :ref:`onKeyDown ` and :ref:`onKeyUp `. :param number: **code** number. :return: :literal:`string` - *key* name. .. Note:: There is an attempt to standardize this method for all SO however is still on progress. *Example:* .. code-block:: lua --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 getKeyCode ^^^^^^^^^^ .. data:: 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 :literal:`ESC` keyboard. It can be used with the methods :ref:`onKeyDown ` and :ref:`onKeyUp `. :param number: **key** as :literal:`string`. :return: :literal:`number` - *code* for the input key. .. Note:: There is an attempt to standardize this method for all SO however is still on progress. *Example:* .. code-block:: lua --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 isCapitalKeyOn ^^^^^^^^^^^^^^ .. data:: isCapitalKeyOn() Recover the state of :guilabel:`Caps Lock` *on* or *off*. *Example:* .. code-block:: lua 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 getIdiom ^^^^^^^^ .. data:: getIdiom() Recover the language (region) from the system. The return string is according to the SO. :return: :literal:`string` - *idiom* for the SO. *Example:* .. code-block:: lua local idiom = mbm.getIdiom() print('idiom:',idiom) --a possible output could be: --pt-BR --American English getUserName ^^^^^^^^^^^ .. data:: getUserName() Recover the user name form current SO. :return: :literal:`string` - *user name* for the currently SO. *Example:* .. code-block:: lua local user = mbm.getUserName() print('Welcome ',user) getSceneName ^^^^^^^^^^^^ .. data:: getSceneName() Recover the currently scene name. :return: :literal:`string` - *scene* name. *Example:* .. code-block:: lua local scene = mbm.getSceneName() print('Scene:',scene) refresh ^^^^^^^ .. data:: 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:* .. code-block:: lua mbm.refresh() windowSize ^^^^^^^^^^ .. data:: 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:* .. code-block:: lua local min_x,min_y = 800, 600 local max_x,max_y = 1024, 768 mbm.setMinMaxWindowSize(min_x,min_y,max_x,max_y) listFiles ^^^^^^^^^ .. data:: listFiles(string folder, boolean * recursive) List files in folder :param boolean: **recursive** indicate to list recursive folders. :return: :literal:`table` - *files* listed ``{separator = '/' or '\\', path = 'folder', [1] = file, [2] ...}``. *Example:* .. code-block:: lua 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 Android ------- doCommands ^^^^^^^^^^ .. data:: 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. :param string: **command** to be interpreted in native side. :param string: **parameter** 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:* .. code-block:: lua 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 .. _doCommands_java: Now a simple implementation: *Lua side:* .. code-block:: lua local result = mbm.doCommands('key-command-1','my parameter') print(result) -- prints "OKAY from Java" *Java side:* .. code-block:: java @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; } } luaFunction ^^^^^^^^^^^ .. data:: luaFunction(string function, string parameter) Call a LUA function from Java (Android). *Example:* .. code-block:: java /*Call Lua native function*/ luaFunction("print","Hello from Java!"); /*Call my personal defined function*/ luaFunction("some_lua_function","execute"); .. code-block:: lua function some_lua_function(param) --Do something if param == 'execute' then print('param is execute. we will execute some command ...') end end