GIANTS Game Engine v4 Documentation



Table of Contents

  1. Chapter 01: Overview
  2. Chapter 02: SDK
    1. Runtime development key short-cuts
    2. Console Command Reference
    3. Function Reference
      1. General
      2. Entity
      3. Node
      4. Scenegraph
      5. Lighting
      6. Camera
      7. Shape
      8. Physics
      9. Spline
      10. Animation
      11. Overlays
      12. Sound
      13. Input
      14. XML
      15. Network
      16. Callbacks
    4. Foundation Reference
      1. Scenegraph
      2. Input
  3. Chapter 03: Tutorials
    1. Tutorial 1 - Load i3d files and basics
    2. Tutorial 2 - Light functions, global time and rendering text
    3. Tutorial 3 - User Attributes
    4. Tutorial 4 - Timers
    5. Tutorial 5 - Physics
    6. Tutorial 6 - Overlays
    7. Tutorial 7 - Audio
  4. Chapter 04: Editor
    1. Viewport
    2. Scenegraph
    3. Attributes
    4. Toolbar
    5. Terrain
    6. User Attributes
    7. Scripting
    8. Terrain Editing
    9. Replace Dialog
    10. Interactive Placement
    11. Other functionality
    12. Key short-cuts
  5. Chapter 05: Debugger
    1. Overview
    2. Interface
      1. Menu and Toolbars
      2. Main text editor panel
      3. File browser panel
      4. Variable overview panel
      5. Additional information panel
    3. Tutorial
      1. Setup
      2. Debugging
      3. Stepping
    4. Keyboard short-cuts
  6. Chapter 06: Exporter
    1. Autodesk Maya1 i3d exporter
      1. Material export options
    2. Autodesk 3ds MAX2 i3d exporter
    3. Blender i3d exporter
  7. Chapter 07: Content Creation - Artwork Guide
    1. Autodesk Maya
    2. Autodesk 3DS MAX
    3. Texturing
  8. Chapter 08: I3D Format
    1. Introduction
    2. Features
    3. Overview
    4. Specification
      1. General Layout
      2. Materials
      3. Shapes
      4. Dynamics
      5. Scenegraph
      6. Animation
    5. Example file
    6. Test Scenes


Overview



Introduction


GIANTS Engine is a real-time 3D game engine with corresponding content pipeline tools. Its flexible and modular design supports multiple platforms and game genres.



Key features

Graphics

  • Flexible culling, sorting and rendering
  • Particle systems
  • Level-of-detail (hierarchy, geometry and shader)
  • Dynamic shader generation
  • Dynamic directional, point, spot and ambient lights
  • Dynamic shadows
  • Reflections and refractions
  • Customizable shaders
  • Multi layered terrain
  • Scene graph representation
  • Flexible foliage system

Physics

  • Rigid Body physics
  • Advanced character control
  • Articulated vehicle dynamics
  • Ragdoll dynamics
  • Customizable joints
  • Triggers
  • Contact reports
  • Automated collision geometry generation

Animations

  • Hierarchical scene graph animation
  • Skeleton animation
  • Animation sequence blending and interpolation
  • Animation sequence instancing

Artificial Intelligence

  • Automated navigation mesh generation
  • Path finding
  • Containment queries

Tools

  • Flexible and powerful content pipeline tool chain
  • Full featured editor
  • 3D modeling tool exporters (including animation, hierarchy, physics, materials, shaders and user attributes)
    • Autodesk Maya
    • Autodesk 3ds MAX
    • Blender
  • Remote runtime target debugger
    • Connection via TCP/IP
    • Script debugger
    • Physics debugger

Miscellaneous

  • Streaming support
  • Generic scripting support (LUA, Small, Python, ...)
  • Unicode support
  • Networking support
    • Peer-to-peer or Client/Server
    • NAT Traversal
  • Flexible XML-based file formats
  • Multi-Threading support
  • Multi-platform
  • 3D audio support
  • Detailed runtime stats and profiling system
  • Extensive documentation and tutorials



Runtime development key short-cuts



Key Function
~ or ` Toggle console
F2 Show frame rate
F3 Toggle frame rate limiter
F4 Wireframe mode
F5 Toggle debug rendering
F7 Toggle camera
F8 Toggle stats
F9 Connect to physics visual remote debugger (VRD)
F10 Connect to remote debugger


Console Command Reference


enableFramerateLimit

Description
Enable/disable frame per second limiter

exit, quit or q

Description
Quits application

framerateLimitFPS

Description
Frame per second limit attribute

globalClipDistance

Description
Global clipping distance. Additional distance clipping per object (at center of object).

globalCullOverride

Description
Global cull override. If true no visibility culling is used.

listEntities

Description
Print detailed entity list

listResources

Description
Print detailed resource list

reload

Description
Reloads resource with given name

reloadAll

Description
Reload all resources with given type

showDebugAudioSource

Description
Show debug audio sources

showDebugLightSources

Description
Show debug lights

showDebugRendering

Description
Show debug rendering. Global switch for all debug rendering.

showShapeBoundingVolume

Description
Show shape bounding volumes

showTransformGroupFrames

Description
Show debug transform group frames

showFps

Description
Show frames per second

sortGeometry

Description
Sort render queue by material sort id

parallelRenderingAndPhysics

Description
Enable parallel rendering and physics




Function Reference

General Function Reference


print

Description
Print to console

Definition
function print(arg1, ...)

Arguments
any typearg1variable to print
any type...variable to print




source

Description
Source script file

Definition
function source(filename)

Arguments
stringfilenamename of script file




requestExit

Description
Request application to exit at the end of this frame

Definition
function requestExit()




renderText

Description
Render text to viewport
See asciiToUtf8 to convert to utf8

Definition
function renderText(float x, float y, float size, string str)

Arguments
floatxx position [0, 1]
floatyy position [0, 1]
floatsizefont size
stringstrutf8 encoded string to print




setTextColor

Description
Set the text color to be used for the following renderText calls

Definition
function setTextColor(float r, float g, float b, float a)

Arguments
floatrred color component [0, 1]
floatggreen color component [0, 1]
floatbblue color component [0, 1]
floataalpha (opacity) [0, 1]




setTextBold

Description
Set the text boldness to be used for the following renderText calls

Definition
function setTextBold(boolean isBold)

Arguments
booleanisBoldbold state




setTextAlignment

Description
Set the text alignment to be used for the following renderText calls

Definition
function setTextAlignment(integer alignment)

Arguments
integeralignmentalignment (RenderText.ALIGN_LEFT, RenderText.ALIGN_CENTER or RenderText.ALIGN_RIGHT)




setTextWrapWidth

Description
Set the text wrap width to be used for the following renderText calls

Definition
function setTextWrapWidth(float wrapWidth)

Arguments
floatwrapWidthwrap width

Notes
since v4.1.5




drawDebugPoint

Description
Render a point. Only use for debug rendering

Definition
function drawDebugPoint(float x, float y, float z, float r, float g, float b, float a)

Arguments
floatxx position
floatyy position
floatzz position
floatrred color component [0, 1]
floatggreen color component [0, 1]
floatbblue color component [0, 1]
floataalpha color component [0, 1]

Notes
since v4.1.5




drawDebugLine

Description
Render a line. Only use for debug rendering

Definition
function drawDebugLine(float x0, float y0, float z0, float r0, float g0, float b0, float x1, float y1, float z1, float r1, float g1, float b1)

Arguments
floatx0start x position
floaty0start y position
floatz0start z position
floatr0start red color component [0, 1]
floatg0start green color component [0, 1]
floatb0start blue color component [0, 1]
floatx1end x position
floaty1end y position
floatz1end z position
floatr1end red color component [0, 1]
floatg1end green color component [0, 1]
floatb1end blue color component [0, 1]

Notes
since v4.1.5




drawDebugArrow

Description
Render an arrow. Only use for debug rendering

Definition
function drawDebugArrow(float x, float y, float z, float dirX, float dirY, float dirZ, float tangX, float tangY, float tangZ, float r, float g, float b)

Arguments
floatxx position
floatyy position
floatzz position
floatdirXdirection x coordinate
floatdirYdirection y coordinate
floatdirZdirection z coordinate
floattangXtangential x direction
floattangYtangential y direction
floattangZtangential z direction
floatrred color component [0, 1]
floatggreen color component [0, 1]
floatbblue color component [0, 1]

Notes
since v4.1.5




asciiToUtf8

Description
Converts an ascii latin1 (ISO 88859-1) encoded string to an utf8 string

Definition
function asciiToUtf8(string asciiString)

Arguments
stringasciiStringascii string
Return Values
stringutf8stringutf8 encoded string

Notes
since v4.1.5




unicodeToUtf8

Description
Converts an unicode value to an utf8 string

Definition
function unicodeToUtf8(integer unicode)

Arguments
integerunicodeunicode value
Return Values
stringutf8stringutf8 encoded string representing the unicode

Notes
since v4.1.5




utf8Strlen

Description
Returns the length of an utf8 formated string

Definition
function utf8Strlen(string utf8string)

Arguments
stringutf8stringutf8 formated string
Return Values
integerlengthlength of the given string

Notes
since v4.1.5




utf8Substr

Description
Returns a sub string of an utf8 formated string

Definition
function utf8Substr(string utf8string, integer startIndex, integer length)

Arguments
stringutf8stringutf8 formated string
integerstartIndexzero based start index
integerlengthmaximal length of the sub string (optional)
Return Values
stringsubStringutf8 formated sub string

Notes
since v4.1.5




setFog

Description
Set fog properties

Definition
function setFog(string fogType, float startDistanceOrDensity, float endDistance, float r, float g, float b)

Arguments
stringfogTypefog type ("none", "linear", "exp" or "exp2")
floatstartDistanceOrDensitystart distance (linear) or density (exp and exp2)
floatendDistanceend distance (linear)
floatrcolor r
floatgcolor g
floatbcolor b




setVolumeFog

Description
Set volume fog properties

Definition
function setVolumeFog(string fogType, float startDistanceOrDensity, float endDistance, float yPlane, float r, float g, float b)

Arguments
stringfogTypefog type ("none", "linear", "exp" or "exp2")
floatstartDistanceOrDensitystart distance (linear) or density (exp and exp2)
floatendDistanceend distance (linear)
floatyPlaney plane value
floatrcolor r
floatgcolor g
floatbcolor b




wrapMousePosition

Description
Wrap mouse position

Definition
function wrapMousePosition(float x, float y)

Arguments
floatxx coord [0, 1]
floatyy coord [0, 1]




setShowMouseCursor

Description
Set show mouse cursor

Definition
function setShowMouseCursor(boolean state)

Arguments
booleanstateenable state




setCaption

Description
Set caption

Definition
function setCaption(string caption)

Arguments
stringcaptionapplication caption




loadI3DFile

Description
Load I3D file

Definition
function loadI3DFile(string filename)

Arguments
stringfilenamei3d filename
Return Values
integerrootNodeIdid of root node




project

Description
Transform vector from world space into screen space

Definition
function project(float wx, float wy, float wz)

Arguments
floatwxworld space x coordinate
floatwyworld space y coordinate
floatwzworld space z coordinate

Return Values
floatsxscreen space x coordinate
floatsyscreen space y coordinate
floatszscreen space z coordinate




unProject

Description
Transform vector from screen space into world space

Definition
function unProject(float sx, float sy, float sz)

Arguments
floatsxscreen space x coordinate
floatsyscreen space y coordinate
floatszscreen space z coordinate

Return Values
floatwxworld space x coordinate
floatwyworld space y coordinate
floatwzworld space z coordinate




addTimer

Description
Adds timer callback function

Definition
function addTimer(float time, string timerFunctionCallback, object instance)

Arguments
floattimetime in milliseconds
stringtriggerFunctionCallbacktrigger function callback
objectinstanceinstance object (optional)

Return Values
integertimerIdtimer id




setTimerTime

Description
Set timer interval time

Definition
function setTimerTime(integer timerId, float time)

Arguments
integertimerIdtimer id
floattimetime in milliseconds




saveScreenshot

Description
Save screenshot

Definition
function saveScreenshot(string filename)

Arguments
stringfilenamefilename




getAppBasePath

Description
Get application base path

Definition
function getAppBasePath()

Return Values
stringappBasePathapplication base path




getUserProfileAppPath

Description
Get user profile application path

Definition
function getUserProfileAppPath()

Return Values
stringgetUserProfileAppPathuser profile application path




copyFile

Description
Get copy file

Definition
function copyFile(string sourceFile, string destinationFile, boolean overwrite)

Arguments
stringsourceFilesource filename
stringdestinationFiledestination filename
booleanoverwriteoverwrite file if it already exists




getFiles

Description
Get all files of a directory

Definition
function getFiles(string path, string fileFunctionCallback, object instance)

Arguments
stringpathpath
stringfileFunctionCallbackfile function callback
objectinstanceinstance object (optional)

Return Values
integernumFilesnumber of files




Entity Function Reference


delete

Description
Delete Entity/Object

Definition
function delete(integer objectId)

Arguments
integerobjectIdobject id



getClassName

Description
Get class name of object

Definition
function getClassName(integer objectId)

Arguments
integerobjectIdobject id

Return Values
stringclassNameclass name of object




addDeleteListener

Description
Add a delete listener

Definition
function addDeleteListener(integer objectId, string deleteFunctionCallback, object targetObject)

Arguments
integerobjectIdobject id
stringdeleteFunctionCallbackdelete listener function callback, is called when the entity is deleted
objecttargetObjecttarget object (optional), the callback function is called as a member function of targetObject

Return Values
integerlistenerIdid to the created callback, must be given to removeDeleteListener




removeDeleteListener

Description
Remove a delete listener. Note: it is important to call removeDeleteListener for each addDeleteListener call to avoid memory leaks

Definition
function removeDeleteListener(integer objectId, integer listenerId)

Arguments
integerobjectIdobject id
integerlistenerIdid of the delete listener




Node Function Reference


getParent

Description
Get parent id

Definition
function getParent(integer objectId)

Arguments
integerobjectIdobject id

Return Values
integerparentIdparent id




link

Description
Link node to another node

Definition
function link(integer parentNodeId, integer childNodeId)

Arguments
integerparentNodeIdid of parent node
integerchildNodeIdid of child node




unlink

Description
Unlink node from parent

Definition
function unlink(integer objectId)

Arguments
integerobjectIdobject id




getNumOfChildren

Description
Get number of children

Definition
function getNumOfChildren(integer objectId)

Arguments
integerobjectIdobject id

Return Values
integernumOfChildrennumber of children




getChildAt

Description
Get child id at given index

Definition
function getChildAt(integer objectId, integer index)

Arguments
integerobjectIdobject id
integerindexindex of child

Return Values
integerchildIdid of child node




getChild

Description
Get child id

Definition
function getChild(integer objectId, string childName)

Arguments
integerobjectIdobject id
stringchildNamechild name

Return Values
integerchildIdid of child node




getName

Description
Get object name

Definition
function getName(integer objectId)

Arguments
integerobjectIdobject id

Return Values
stringobjectNameobject name




setName

Description
Set object name

Definition
function setName(integer objectId, string objectName)

Arguments
integerobjectIdobject id
stringobjectNamenew object name




removeChildAt

Description
Remove child at given index

Definition
function removeChildAt(integer objectId, integer index)

Arguments
integerobjectIdobject id
integerindexindex of child




Scenegraph Function Reference


createTransformGroup

Description
Create transform group

Definition
function createTransformGroup(string transformName)

Arguments
stringtransformNamename of transform object

Return Values
integertransformIdid of transform object




setTranslation

Description
Set translation of a transform object

Definition
function setTranslation(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of translation
floatyy value of translation
floatzz value of translation




getTranslation

Description
Get translation of a transform object

Definition
function getTranslation(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatxx value of translation
floatyy value of translation
floatzz value of translation




getWorldTranslation

Description
Get world translation of a transform object

Definition
function getWorldTranslation(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatxx value of world translation
floatyy value of world translation
floatzz value of world translation




setRotation

Description
Set euler rotation of a transform object. Order ZY'X''

Definition
function setRotation(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of rotation (radian units)
floatyy value of rotation (radian units)
floatzz value of rotation (radian units)




getRotation

Description
Get rotation of a transform object

Definition
function getRotation(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatxx value of rotation (radian units)
floatyy value of rotation (radian units)
floatzz value of rotation (radian units)




getWorldRotation

Description
Get world rotation of a transform object

Definition
function getWorldRotation(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatxx value of world rotation (radian units)
floatyy value of world rotation (radian units)
floatzz value of world rotation (radian units)




setDirection

Description
Set the direction of an object, the positive z-axis points towards the given direction. The y-axis lies in the direction-up-plane.

Definition
function setDirection(integer transformId, float x, float y, float z, float upX, float upY, float upZ)

Arguments
integertransformIdid of transform object
floatxx value of direction
floatyy value of direction
floatzz value of direction
floatupXx value of up vector
floatupYy value of up vector
floatupYz value of up vector




setScale

Description
Set scale of a transform object

Definition
function setScale(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of scale
floatyy value of scale
floatzz value of scale




getScale

Description
Get scale of a transform object

Definition
function getScale(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatxx value of scale
floatyy value of scale
floatzz value of scale




setVisibility

Description
Set transform object visibility

Definition
function setVisibility(integer transformId, boolean visibility)

Arguments
integertransformIdid of transform object
booleanvisibilityvisibility state




getVisibility

Description
Get transform object visibility

Definition
function getVisibility(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
booleanvisibilityvisibility state




clone

Description
Clone scenegraph object

Definition
function clone(integer objectId, boolean groupUnderParent)

Arguments
idobjectIdid of scenegraph object
booleangroupUnderParentif true the clone will be linked to the the same parent as objectId, otherwise it is not linked to the scenegraph

Return Values
idcloneIdid of clone object




setRootNode

Description
Set scenegraph root node used by the given viewport

Definition
function setRootNode(integer rootNodeId, integer viewportIndex)

Arguments
integerrootNodeIdid of new root node
integerviewportIndexthe index of the viewport [0-7]




getRootNode

Description
Get scenegraph root node used by the given viewport

Definition
function getRootNode(integer viewportIndex)

Arguments
integerviewportIndexthe index of the viewport [0-7]

Return Values
integerrootNodeIdid of the root node




localToWorld

Description
Local space to world space transformation

Definition
function localToWorld(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of local position
floatyy value of local position
floatzz value of local position

Return Values
floatxx value of world position
floatyy value of world position
floatzz value of world position




localDirectionToWorld

Description
Local space to world space transformation, only direction without translation

Definition
function localDirectionToWorld(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of local direction
floatyy value of local direction
floatzz value of local direction

Return Values
floatxx value of world direction
floatyy value of world direction
floatzz value of world direction




worldToLocal

Description
World space to local space transformation

Definition
function worldToLocal(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of world position
floatyy value of world position
floatzz value of world position

Return Values
floatxx value of local position
floatyy value of local position
floatzz value of local position




worldDirectionToLocal

Description
World space to local space transformation, only direction without translation

Definition
function worldDirectionToLocal(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx value of world direction
floatyy value of world direction
floatzz value of world direction

Return Values
floatxx value of local direction
floatyy value of local direction
floatzz value of local direction




getAnimCharacterSet

Description
Get animation character set id

Definition
function getAnimCharacterSet(integer objectId)

Arguments
integerobjectIdobject id

Return Values
integeranimIdanimation character set id




setUserAttribute

Description
Set user attribute value

Definition
function setUserAttribute(integer objectId, string attributeName, string typeName, integer/float/boolean/string value)

Arguments
integerobjectIdobject id
stringattributeNamename of the user attribute
stringtypeNamename of the type ("Integer", "Float", "String", "Boolean")
integer/float/boolean/stringvaluevalue of the user attribute, must match typeName




getUserAttribute

Description
Get user attribute value

Definition
function getUserAttribute(integer objectId, string attributeName)

Arguments
integerobjectIdobject id
stringattributeNamename of the user attribute

Return Values
integer/float/boolean/stringattributeValuevalue of the user attribute, return type is the type of the attribute. Returns nil if attributeName doest not exist




setObjectMask

Description
Set object mask

Definition
function setObjectMask(integer objectId, integer mask)

Arguments
integerobjectIdobject id
integermaskthe object mask to set




getObjectMask

Description
Get object mask

Definition
function getObjectMask(integer objectId)

Arguments
integerobjectIdobject id

Return Values
integermaskthe object mask




getTerrainHeightAtWorldPos

Description
get the terrain height at the given position

Definition
function getTerrainHeightAtWorldPos(integer terrainId, float x, float y, float z)

Arguments
integerterrainIdterrain id
floatxx value of the world position
floatyy value of the world position
floatzz value of the world position

Return Values
floatheightValueheight of the terrain at the given position



Lighting Function Reference


setAmbientColor

Description
Set global ambient color

Definition
function setAmbientColor(float r, float g, float b)

Arguments
floatrred value of ambient color
floatggreen value of ambient color
floatbblue value of ambient color




getLightDiffuseColor

Description
Get diffuse color of a light

Definition
function getLightDiffuseColor(integer lightId)

Arguments
integerlightIdid of light

Return Values
floatrred value of diffuse color
floatggreen value of diffuse color
floatbblue value of diffuse color




setLightDiffuseColor

Description
Set diffuse color of a light

Definition
function setLightDiffuseColor(integer lightId, float r, float g, float b)

Arguments
integerlightIdid of light
floatrred value of diffuse color
floatggreen value of diffuse color
floatbblue value of diffuse color




getLightSpecularColor

Description
Get specular color of a light

Definition
function getLightSpecularColor(integer lightId)

Arguments
integerlightIdid of light

Return Values
floatrred value of specular color
floatggreen value of specular color
floatbblue value of specular color




setLightSpecularColor

Description
Set specular color of a light

Definition
function setLightSpecularColor(integer lightId, float r, float g, float b)

Arguments
integerlightIdid of light
floatrred value of specular color
floatggreen value of specular color
floatbblue value of specular color




getLightRange

Description
Get range of a light

Definition
function getLightRange(integer lightId)

Arguments
integerlightIdid of light

Return Values
floatrangelight range




setLightRange

Description
Set range of a light

Definition
function setLightRange(integer lightId, float range)

Arguments
integerlightIdid of light
floatrangelight range




Camera Function Reference


createCamera

Description
Create camera

Definition
function createCamera(string cameraName, float fovy, float nearClip, float farClip)

Arguments
stringcameraNamecamera name
floatfovyfield of view (degree)
floatnearClipnear clip
floatfarClipfar clip




setCamera

Description
Set currently used camera by the given viewport

Definition
function setCamera(integer cameraId, integer viewportIndex)

Arguments
integercameraIdnew camera id
integerviewportIndexthe index of the viewport [0-7]




getCamera

Description
Get currently used camera by the given viewport

Definition
function getCamera(integer viewportIndex)

Arguments
integerviewportIndexthe index of the viewport [0-7]

Return Values
integercurrentCameraIdcurrent camera id




setViewport

Description
Set the dimensions of the given viewport

Definition
function setViewport(integer viewportIndex, float left, float top, float width, float height)

Arguments
integerviewportIndexthe index of the viewport [0-7]
floatleftthe start position from the left side [0-1]
floattopthe start position from the top side [0-1]
floatwidththe width of the viewport [0-1]
floatheightthe height of the viewport [0-1]

Notes
since v4.1.5




setFovy

Description
Set the field of view angle

Definition
function setFovy(integer cameraId, float fovy)

Arguments
integercameraIdcamera id
floatfovyfield of view angle (degree)




getFovy

Description
Get the field of view angle

Definition
function getFovy(integer cameraId)

Arguments
integercameraIdcamera id

Return Values
floatfovyfield of view angle (degree)




setNearClip

Description
Set the near clip distance

Definition
function setNearClip(integer cameraId, float nearClip)

Arguments
integercameraIdcamera id
floatnearClipnear clip distance




getNearClip

Description
Get the near clip distance

Definition
function getNearClip(integer cameraId)

Arguments
integercameraIdcamera id

Return Values
floatnearClipnear clip distance




setFarClip

Description
Set the far clip distance

Definition
function setFarClip(integer cameraId, float farClip)

Arguments
integercameraIdcamera id
floatfarClipfar clip distance




getFarClip

Description
Get the far clip distance

Definition
function getFarClip(integer cameraId)

Arguments
integercameraIdcamera id

Return Values
floatfarClipfar clip distance




aimCamera

Description
Aim camera (spring/damper)

Definition
function aimCamera(integer cameraId, float x, float y, float z, float distance, float dt, float springStrength)

Arguments
integercameraIdcamera id
floatxtarget x coordinate
floatytarget y coordinate
floatztarget z coordinate
floatdistancedistance from target
floatdtdelta time
floatspringStrengthspring strength




Shape Function Reference


setShaderParameter

Description
Set shader parameter

Definition
function setShaderParameter(integer shapeId, string parameterName, float x, float y, float z, float w, boolean shared)

Arguments
integershapeIdshape id
stringparameterNamethe name of the parameter
floatxx value
floatyy value
floatzz value
floatww value
booleansharedif true, the value is applied to all shapes with the same material



Particle System Function Reference


setEmittingState

Description
Set whether the particle system should emit new particles

Definition
function setEmittingState(integer particleSystemId, boolean state)

Arguments
integerparticleSystemIdparticle system id
booleanstateif true, new particles are emitted




resetNumOfEmittedParticles

Description
Resets the counter of emitted particles. This is used if the maxEmit attribute is set for the particle system.

Definition
function resetNumOfEmittedParticles(integer particleSystemId)

Arguments
integerparticleSystemIdparticle system id

Notes
since v4.1.5




setParticleSystemTimeScale

Description
Sets the time scale for the particle simulation.

Definition
function setParticleSystemTimeScale(integer particleSystemId, float timeScale)

Arguments
integerparticleSystemIdparticle system id
floattimeScaletime scale for the particle simulation




getEmitterShape

Description
Returns the emitter shape of the particle system

Definition
function getEmitterShape(integer particleSystemId)

Arguments
integerparticleSystemIdparticle system id

Return Values
integershapeIdid of the emitter shape




setEmitterShape

Description
Sets the emitter shape of the particle system

Definition
function setEmitterShape(integer particleSystemId, integer shapeId)

Arguments
integerparticleSystemIdparticle system id
integershapeIdid of the emitter shape




Physics Function Reference


simulatePhysics

Description
Enable/disable physics simulation

Definition
function simulatePhysics(boolean state)

Arguments
booleanstateenable simulation state




simulatePhysicsTimeScale

Description
Time scale of physics simulation

Definition
function simulatePhysicsTimeScale(float scale)

Arguments
floatscalephysics time scale




createCCT

Description
Create character controller (y axis capsule based)

Definition
function createCCT(integer transformId, float radius, float height, float stepOffset, float slopeLimit, float skinWidth, float collisionMask, float mass)

Arguments
integertransformIdid of transform object
floatradiusradius
floatheightheight
floatstepOffsetstep offset
floatslopeLimitslope limit
floatskinWidthskin width
integercollisionMaskcollision mask
floatmasscharacter mass [kg]

Return Values
integercharacterIndexcharacter index number




moveCCT

Description
Enqueue character movement

Definition
function moveCCT(integer characterIndex, float x, float y, float z, float collisionMasks)

Arguments
integercharacterIndexcharacter index number
floatxx value
floatyy value
floatzz value
floatcollisionMaskscollision masks




removeCCT

Description
Remove character controller

Definition
function removeCCT(integer characterIndex)

Arguments
integercharacterIndexcharacter index number




getCCTCollisionFlags

Description
Get character controller collision flags

Definition
function getCCTCollisionFlags(integer characterIndex)

Arguments
integercharacterIndexcharacter index number

Return Values
booleansideside flag
booleanupup flag
booleandowndown flag




raycastAll

Description
Raycast objects

Definition
function raycastAll(float x, float y, float z, float nx, float ny, float nz, string raycastFunctionCallback, float maxDistance)

Arguments
floatxorigin x
floatyorigin y
floatzorigin z
floatnxdirection x
floatnydirection y
floatnzdirection z
stringraycastFunctionCallbackraycast function callback
floatmaxDistancemax distance

Return Values
integernumShapesnumber of shapes hit




raycastClosest

Description
Raycast closest object

Definition
function raycastClosest(float x, float y, float z, float nx, float ny, float nz, string raycastFunctionCallback, float maxDistance)

Arguments
floatxorigin x
floatyorigin y
floatzorigin z
floatnxdirection x
floatnydirection y
floatnzdirection z
stringraycastFunctionCallbackraycast function callback
floatmaxDistancemax distance

Return Values
integernumShapesnumber of shapes hit




overlapSphere

Description
Overlap sphere objects

Definition
function overlapSphere(float x, float y, float z, float radius, string overlapFunctionCallback, object targetObject)

Arguments
floatxcenter x
floatycenter y
floatzcenter z
floatradiusradius
stringoverlapFunctionCallbackoverlap function callback
objecttargetObjecttarget object (optional), the callback function is called as a member function of targetObject

Return Values
integernumShapesnumber of shape overlaps




overlapBox

Description
Overlap box objects

Definition
function overlapBox(float x, float y, float z, float rx, float ry, float rz, float ex, float ey, float ez, string overlapFunctionCallback, object targetObject)

Arguments
floatxcenter x
floatycenter y
floatzcenter z
floatrxrotation x
floatryrotation y
floatrzrotation z
floatexextent x
floateyextent y
floatezextent z
stringoverlapFunctionCallbackoverlap function callback
objecttargetObjecttarget object (optional), the callback function is called as a member function of targetObject

Return Values
integernumShapesnumber of shape overlaps




addForce

Description
Add force to object

Definition
function addForce(integer transformId, float forceX, float forceY, float forceZ, float positionX, float positionY, float positionZ, boolean isPositionLocal)

Arguments
integertransformIdid of transform object
floatforceXforce x
floatforceYforce y
floatforceZforce z
floatpositionXposition x
floatpositionYposition y
floatpositionZposition z
booleanisPositionLocalis position local




addImpulse

Description
Add impulse to object

Definition
function addImpulse(integer transformId, float impulseX, float impulseY, float impulseZ, float positionX, float positionY, float positionZ, boolean isPositionLocal)

Arguments
integertransformIdid of transform object
floatimpulseXimpulse x
floatimpulseYimpulse y
floatimpulseZimpulse z
floatpositionXposition x
floatpositionYposition y
floatpositionZposition z
booleanisPositionLocalis position local




setJointDrive

Description
Set joint drive. Drives orientation if position drive or angular velocity if velocity drive.

Definition
function setJointDrive(integer transformId, float angle, float valueX, float valueY, float valueZ)

Arguments
integertransformIdid of transform object
floatangleorientation angle
floatvalueXorientation axis x or angular velocity x
floatvalueYorientation axis y or angular velocity y
floatvalueZorientation axis z or angular velocity z




createWheelShape

Description
Create wheel shape

Definition
function createWheelShape(integer transformId, float positionX, float positionY, float positionZ, float radius, float suspensionTravel, float spring, float damper, float mass)

Arguments
integertransformIdid of transform object
floatpositionXposition x
floatpositionYposition y
floatpositionZposition z
floatradiusradius
floatsuspensionTravelsuspension travel
floatspringspring
floatdamperdamper
floatmassmass

Return Values
integerwheelShapeIndexwheel shape index




setWheelShapeProps

Description
Set wheel shape properties

Definition
function setWheelShapeProps(integer transformId, integer wheelShapeIndex, float motorTorque, float brakeTorque, float steerAngle)

Arguments
integertransformIdid of transform object
integerwheelShapeIndexwheel shape index
floatmotorTorquemotor torque
floatbrakeTorquebrake torque
floatsteerAnglesteer angle




getWheelShapeAxleSpeed

Description
Get wheel shape axle speed

Definition
function getWheelShapeAxleSpeed(integer transformId, integer wheelShapeIndex)

Arguments
integertransformIdid of transform object
integerwheelShapeIndexwheelShapeIndex

Return Values
floataxleSpeedaxle speed




getWheelShapeContactPoint

Description
Get wheel shape contact point

Definition
function getWheelShapeContactPoint(integer transformId, integer wheelShapeIndex)

Arguments
integertransformIdid of transform object
integerwheelShapeIndexwheelShapeIndex

Return Values
floatxx position
floatyy position
floatzz position




getWheelShapePosition

Description
Get wheel shape position

Definition
function getWheelShapePosition(integer transformId, integer wheelShapeIndex)

Arguments
integertransformIdid of transform object
integerwheelShapeIndexwheelShapeIndex

Return Values
floatxx position
floatyy position
floatzz position




addTrigger

Description
Adds a trigger callback function

The transformId must have set the trigger flag and must be a static or a kinematic rigid body.
The given triggerFunctionCallback is called, whenever a dynamic or kinematic body enters or leaves the region defined by the trigger geometry. Static objects do not trigger an event.
See "trigger callback" in section "Custom callbacks"

Definition
function addTrigger(integer transformId, string triggerFunctionCallback, object targetObject)

Arguments
integertransformIdid of transform object
stringtriggerFunctionCallbacktrigger function callback
objecttargetObjecttarget object (optional), the callback function is called as a member function of targetObject




removeTrigger

Description
Removes trigger callback function

Definition
function removeTrigger(integer transformId)

Arguments
integertransformIdid of transform object




addContactReport

Description
Adds contact report callback function
See contact callback function

Definition
function addContactReport(integer transformId, float forceThreshold, string contactReportFunctionCallback, object targetObject)

Arguments
integertransformIdid of transform object
floatforceThresholdforce threshold
stringcontactFunctionCallbackcontact report function callback
objecttargetObjecttarget object (optional), the callback function is called as a member function of targetObject




removeContactReport

Description
Removes contact report callback function

Definition
function removeContactReport(integer transformId)

Arguments
integertransformIdid of transform object




getRigidBodyType

Description
Get rigid body type

Definition
function getRigidBodyType(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
stringtyperigid body type ("Static", "Dynamic", "Kinematic" or "NoRigidBody")




setRigidBodyType

Description
Set rigid body type

Definition
function setRigidBodyType(integer transformId, string type)

Arguments
integertransformIdid of transform object
stringtyperigid body type ("Static", "Dynamic", "Kinematic" or "NoRigidBody")




getCollisionMask

Description
Get collision mask

Definition
function getCollisionMask(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
integermaskcollision mask




setCollisionMask

Description
Set collision mask

Definition
function setCollisionMask(integer transformId, integer mask)

Arguments
integertransformIdid of transform object
integermaskcollision mask




getCenterOfMass

Description
Get center of mass

Definition
function getCenterOfMass(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatxx position
floatyy position
floatzz position




setCenterOfMass

Description
Set center of mass

Definition
function setCenterOfMass(integer transformId, float x, float y, float z)

Arguments
integertransformIdid of transform object
floatxx position
floatyy position
floatzz position




getMass

Description
Get mass

Definition
function getMass(integer transformId)

Arguments
integertransformIdid of transform object

Return Values
floatmassmass




setMass

Description
Set mass

Definition
function setMass(integer transformId, float mass)

Arguments
integertransformIdid of transform object
floatmassmass



Destruction Function Reference


getHasDestructionShape

Description
Returns if the given destruction shape index exists

Definition
function getHasDestructionShape(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
booleanhasShapetrue if a shape with the given index exists, otherwise false




getDestructionShapeWorldTranslation

Description
Get world translation of the given destruction shape

Definition
function getDestructionShapeWorldTranslation(integer shapeId, integer destructionShapeIndex, boolean physicalPosition)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
booleanphysicalPositionif true, the translation of the physics object is returned, otherwise the translation of the visual representation

Return Values
floatxx world coordinate
floatyy world coordinate
floatzz world coordinate




destructionShapeLocalToWorld

Description
Destruction shape local space to world space transformation

Definition
function destructionShapeLocalToWorld(integer shapeId, integer destructionShapeIndex, boolean physicalPosition, float x, float y, float z)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
booleanphysicalPositionif true, the translation of the physics object is returned, otherwise the translation of the visual representation
floatxx value of local position
floatyy value of local position
floatzz value of local position

Return Values
floatxx world coordinate
floatyy world coordinate
floatzz world coordinate




destructionShapeWorldToLocal

Description
Destruction shape world space to local space transformation

Definition
function destructionShapeWorldToLocal(integer shapeId, integer destructionShapeIndex, boolean physicalPosition, float x, float y, float z)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
booleanphysicalPositionif true, the translation of the physics object is returned, otherwise the translation of the visual representation
floatxx value of world position
floatyy value of world position
floatzz value of world position

Return Values
floatxx value of local position
floatyy value of local position
floatzz value of local position




destructionShapeLocalDirectionToWorld

Description
Destruction shape local space to world space transformation, only direction without translation

Definition
function destructionShapeLocalDirectionToWorld(integer shapeId, integer destructionShapeIndex, boolean physicalPosition, float x, float y, float z)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
booleanphysicalPositionif true, the direction of the physics object is returned, otherwise the direction of the visual representation
floatxx value of world direction
floatyy value of world direction
floatzz value of world direction

Return Values
floatxx value of local direction
floatyy value of local direction
floatzz value of local direction




destructionShapeWorldDirectionToLocal

Description
Destruction shape world space to local space transformation, only direction without translation

Definition
function destructionShapeWorldDirectionToLocal(integer shapeId, integer destructionShapeIndex, boolean physicalPosition, float x, float y, float z)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
booleanphysicalPositionif true, the direction of the physics object is returned, otherwise the direction of the visual representation
floatxx value of world direction
floatyy value of world direction
floatzz value of world direction

Return Values
floatxx value of local direction
floatyy value of local direction
floatzz value of local direction




getDestructionShapeCenterOfMass

Description
Get the destruction shape center of mass

Definition
function getDestructionShapeCenterOfMass(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
floatxx value of local position of the center of mass
floatyy value of local position of the center of mass
floatzz value of local position of the center of mass




getDestructionShapeMass

Description
Get the destruction shape mass

Definition
function getDestructionShapeMass(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
floatmassmass of the destruction shape




getDestructionShapeLinearVelocity

Description
Get world space destruction shape linear velocity

Definition
function getDestructionShapeLinearVelocity(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
floatxx value of velocity
floatyy value of velocity
floatzz value of velocity




getDestructionShapeAngularVelocity

Description
Get world space destruction shape angular velocity

Definition
function getDestructionShapeAngularVelocity(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
floatxx value of angular velocity
floatyy value of angular velocity
floatzz value of angular velocity




getDestructionMaxDamage

Description
Get the maximal damage each destruction shape of the shape can receive until it breaks

Definition
function getDestructionMaxDamage(integer shapeId)

Arguments
integershapeIdid of the shape

Return Values
floatmaxDamagemaximal damage




getDestructionShapeDamage

Description
Get the current damage value of the given destruction shape

Definition
function getDestructionShapeDamage(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
floatdamagedamage of the destruction shape




getDestructionShapeDamageRatio

Description
Get the current damage ratio [0,1] of the given destruction shape

Definition
function getDestructionShapeDamageRatio(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape

Return Values
floatdamageRatiodamageRatio [0,1] of the destruction shape




addDestructionShapeDamage

Description
Add damage to the given destruction shape

Definition
function addDestructionShapeDamage(integer shapeId, integer destructionShapeIndex, float damage)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
floatdamageamount of damage




deleteDestructionShape

Description
Delete the given destruction shape

Definition
function deleteDestructionShape(integer shapeId, integer destructionShapeIndex)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape




getNumDestructionJoints

Description
Get the number of joints the given shape has

Definition
function getNumDestructionJoints(integer shapeId)

Arguments
integershapeIdid of the shape

Return Values
integernumJointsnumber of joints between the destruction shapes




getNumRemainingDestructionJoints

Description
Get the number of unbroken joints, the given shape currently has

Definition
function getNumRemainingDestructionJoints(integer shapeId)

Arguments
integershapeIdid of the shape

Return Values
integernumRemainingJointsnumber of unbroken joints between the destruction shapes




addDestructionShapeForce

Description
Add force to the given destruction shape

Definition
function addDestructionShapeForce(integer shapeId, integer destructionShapeIndex, float x, float y, float z)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
floatxx value of world space force
floatyy value of world space force
floatzz value of world space force




addDestructionShapeImpulse

Description
Add impulse to the given destruction shape

Definition
function addDestructionShapeImpulse(integer shapeId, integer destructionShapeIndex, float x, float y, float z)

Arguments
integershapeIdid of the shape
integerdestructionShapeIndexindex of the destruction shape
floatxx value of world space impulse
floatyy value of world space impulse
floatzz value of world space impulse




Spline Function Reference


getSplinePosition

Description
Get spline position

Definition
function getSplinePosition(integer shapeId, float time)

Arguments
integershapeIdid of curve shape object
floattimetime [0,1]

Return Values
floatxx coordinate
floatyy coordinate
floatzz coordinate




getSplineOrientation

Description
Get spline orientation

Definition
function getSplineOrientation(integer shapeId, float time, float upDirX, float upDirY, float upDirZ)

Arguments
integershapeIdid of curve shape object
floattimetime [0,1]
floatupDirXup direction x coordinate
floatupDirYup direction y coordinate
floatupDirZup direction z coordinate

Return Values
floatrxx rotation
floatryy rotation
floatrzz rotation




getSplineLength

Description
Get spline length

Definition
function getSplineLength(integer shapeId)

Arguments
integershapeIdid of curve shape object

Return Values
floatlengthlength of spline




getSplineNumOfCV

Description
Get number of spline control vertices

Definition
function getSplineNumOfCV(integer shapeId)

Arguments
integershapeIdid of curve shape object

Return Values
integernumnumber of spline control vertices




getSplineCV

Description
Get spline control vertex

Definition
function getSplineCV(integer shapeId, float time)

Arguments
integershapeIdid of curve shape object
integerindexcontrol vertex index

Return Values
floatxcontrol vertex x coordinate
floatycontrol vertex y coordinate
floatzcontrol vertex z coordinate




Animation Function Reference


getAnimCharacterSet

Description
Returns the character set driving the transform group

Definition
function getAnimCharacterSet(integer transformId)

Arguments
integertransformIdid of transform group

Return Values
integeridid of character set object, 0 if no character set is assigned to the transform group




enableAnimTrack

Description
Enable animation track

Definition
function enableAnimTrack(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number




disableAnimTrack

Description
Disable animation track

Definition
function disableAnimTrack(string characterSetId, integer track)

Arguments
stringcharacterSetIdname of CharacterSet object
integertracktrack number




isAnimTrackEnabled

Description
Is animation track enabled

Definition
function isAnimTrackEnabled(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number

Return Values
boolstateenable state




setAnimTrackSpeedScale

Description
Set animation track speed scale

Definition
function setAnimTrackSpeedScale(integer characterSetId, integer track, float speedScale)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number
floatspeedScalespeed scale




setAnimTrackLoopState

Description
Set animation track loop state

Definition
function setAnimTrackLoopState(integer characterSetId, integer track, bool loopState)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number
boolloopStateloop scale




setAnimTrackTime

Description
Set animation track time

Definition
function setAnimTrackTime(integer characterSetId, integer track, float time)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number
floattimetime
boolimmediateUpdate (optional)if set to true, the animation is updated immediately, otherwise it is only updated the next frame. For performance reasons, only set this to true if you really need the immediate update.




getAnimTrackTime

Description
Get animation track time

Definition
function getAnimTrackTime(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number

Return Values
floattimecurrent time




getAnimClipDuration

Description
Get the duration of the clip at the given index

Definition
function getAnimClipDuration(integer characterSetId, integer index)

Arguments
integercharacterSetIdid of CharacterSet object
integerindexclip index

Return Values
floatdurationclip duration




setAnimTrackBlendWeight

Description
Set animation track blend weight

Definition
function setAnimTrackBlendWeight(integer characterSetId, integer track, float weight)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number
floatweightblend weight




getAnimTrackBlendWeight

Description
Get animation track blend weight

Definition
function getAnimTrackBlendWeight(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number

Return Values
floatweightblend weight




getAnimClipIndex

Description
Returns the index of the clip with the given name

Definition
function getAnimClipIndex(integer characterSetId, string clipName)

Arguments
integercharacterSetIdid of CharacterSet object
stringclipNamethe name of the clip to find

Return Values
integerindexindex of the clip, -1 if clip was not found




assignAnimTrackClip

Description
Assign clip to animation track

Definition
function assignAnimTrackClip(integer characterSetId, integer track, float clipIndex)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number
floatclipIndexclip index number




isAnimTrackClipAssigned

Description
Is clip assigned to animation track

Definition
function isAnimTrackClipAssigned(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number

Return Values
boolstateassigned state




getAnimTrackAssignedClip

Description
Get animation track assigned clip index number

Definition
function getAnimTrackAssignedClip(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number

Return Values
floatclipIndexclip index number




clearAnimTrackClip

Description
Clear animation track clip assignment

Definition
function clearAnimTrackClip(integer characterSetId, integer track)

Arguments
integercharacterSetIdid of CharacterSet object
integertracktrack number




getAnimNumOfClips

Description
Get number of clips

Definition
function getAnimNumOfClips(integer characterSetId)

Arguments
integercharacterSetIdid of CharacterSet object

Return Values
floatclipsnumber of clips




Overlays Function Reference


createOverlay

Description
Create image overlay object

Definition
function createOverlay(string overlayName, string textureFilename)

Arguments
stringoverlayNameoverlay name
stringtextureFilenametexture file name

Notes
deprecated, use createImageOverlay




createImageOverlay

Description
Create overlay object

Definition
function createImageOverlay(string textureFilename)

Arguments
stringtextureFilenametexture file name

Notes
since v4.1.3




setOverlayColor

Description
Set overlay color

Definition
function setOverlayColor(integer overlayId, float red, float green, float blue, float alpha)

Arguments
integeroverlayIdoverlay id
floatredred value
floatgreengreen value
floatblueblue value
floatalphaalpha value




setOverlayUVs

Description
Set overlay uv coordinates

Definition
function setOverlayUVs(integer overlayId, float u0, float v0, float u1, float v1, float u2, float v2, float u3, float v3)

Arguments
integeroverlayIdoverlay id
floatv0v0 texture coodinate
floatu0u0 texture coodinate
floatv1v1 texture coodinate
floatu1u1 texture coodinate
floatv2v2 texture coodinate
floatu2u2 texture coodinate
floatv3v3 texture coodinate
floatu3u3 texture coodinate




renderOverlay

Description
Render overlay

Definition
function renderOverlay(integer overlayId, float x1, float y1, float width, float height)

Arguments
integeroverlayIdoverlay id
floatxx position [0,1]
floatyy position [0,1]
floatwidthwidth [0,1]
floatheightheight [0,1]




createVideoOverlay

Description
Create video overlay object

Definition
function createVideoOverlay(string videoFilename, bool loopVideo, float soundVolume)

Arguments
stringvideoFilenamevideo file name
boolloopVideoloop video
floatsoundVolumesound volume [0,1]

Notes
since v4.1.3




playVideoOverlay

Description
Play video overlay object

Definition
function playVideoOverlay(integer videoOverlayId)

Arguments
integervideoOverlayIdoverlay id

Notes
since v4.1.3




stopVideoOverlay

Description
Stop video overlay object

Definition
function stopVideoOverlay(integer videoOverlayId)

Arguments
integervideoOverlayIdoverlay id

Notes
since v4.1.3




updateVideoOverlay

Description
Update video overlay object

Definition
function updateVideoOverlay(integer videoOverlayId)

Arguments
integervideoOverlayIdoverlay id

Notes
since v4.1.3




getVideoOverlayDuration

Description
Get video overlay duration

Definition
function getVideoOverlayDuration(integer videoOverlayId)

Arguments
integervideoOverlayIdoverlay id

Return Values
floatvideoDurationvideo duration in milliseconds

Notes
since v4.1.3




getVideoOverlayCurrentTime

Description
Get video overlay current time

Definition
function getVideoOverlayCurrentTime(integer videoOverlayId)

Arguments
integervideoOverlayIdoverlay id

Return Values
floatvideoCurrentTimevideo current time in milliseconds

Notes
since v4.1.5




isVideoOverlayPlaying

Description
Get is video overlay playing

Definition
function isVideoOverlayPlaying(integer videoOverlayId)

Arguments
integervideoOverlayIdoverlay id

Return Values
boolisVideoOverlayPlayingis video overlay playing

Notes
since v4.1.3




Sound Function Reference


createSample

Description
Create sample object

Definition
function createSample(string objectName)

Arguments
stringobjectNamesample object name

Return Values
integersampleIdid of the created sample




loadSample

Description
Load sample object

Definition
function loadSample(integer objectId, string sampleFilename, bool b3DSound)

Arguments
integerobjectIdid of sample object
stringsampleFilenameSample filename (.wav)
boolb3DSoundtrue=enables 3D Sound-Rendering, false=disables 3D Sound-Rendering




playSample

Description
Play sample object

Definition
function playSample(integer objectId, integer loops, float volume, float offset)

Arguments
integerobjectIdid of sample object
integerloopsnumber of loops [0,n] 0 = endless looping
floatvolumevolume [0,1]
floatoffsetoffset in milliseconds




stopSample

Description
Stop sample object

Definition
function stopSample(integer objectId)

Arguments
integerobjectIdid of sample object




setSamplePitch

Description
Set sample pitch

Definition
function setSamplePitch(integer objectId, float pitch)

Arguments
integerobjectIdid of sample object
floatpitchpitch value [0.5-2.0]




getSamplePitch

Description
Get sample pitch

Definition
function getSamplePitch(integer objectId)

Arguments
integerobjectIdid of sample object

Return Values
floatpitchpitch of sample object




setSampleVolume

Description
Set sample volume

Definition
function setSampleVolume(integer objectId, float volume)

Arguments
integerobjectIdid of sample object
floatvolumevolume value




getSampleVolume

Description
Get sample volume

Definition
function getSampleVolume(integer objectId)

Arguments
integerobjectIdid of sample object

Return Values
floatvolumevolume of sample object




getSampleDuration

Description
Get sample duration

Definition
function getSampleDuration(integer objectId)

Arguments
integerobjectIdid of sample object

Return Values
floatdurationduration in milliseconds




setSampleVelocity

Description
Set velocity of a sample object

Definition
function setSampleVelocity(int sampleId, float x, float y, float z)

Arguments
integersampleIdid of transform object
floatxvelocity value towards x
floatyvelocity value towards y
floatzvelocity value towards z




getSampleVelocity

Description
Get velocity of a sample object

Definition
function getSampleVelocity(integer sampleId)

Arguments
integersampleIdid of transform object

Return Values
floatxx value of velocity towards x
floatyy value of velocity towards y
floatzz value of velocity towards z




enableSampleFX

Description
enable audio effects - Reverberation

Definition
function enableSampleFX(integer objectId, int reverbPresetType)

Arguments
integerobjectIdid of sample object
intreverbPresetTypereverberation preset id [1, 68]




disableSampleFX

Description
disable audio effects - Reverberation

Definition
function disableSampleFX(integer objectId)

Arguments
integerobjectIdid of sample object




enableSampleFilter

Description
enable audio filters

Definition
function enableSampleFilter(integer objectId, int filterType, float gain, float gainLF, float gainHF)

Arguments
integerobjectIdid of sample object
intreverbPresetTypefilter type id [0, 3]
floatgaingain [0, 1]
floatgainLFgain low frequency [0, 1]
floatgainHFgain high frequency [0, 1]




disableSampleFilter

Description
disable audio filter

Definition
function disableSampleFilter(integer objectId)

Arguments
integerobjectIdid of sample object




createStreamedSample

Description
Create streamed sample object

Definition
function createStreamedSample(string objectName)

Arguments
stringobjectNamestreamed sample object name

Return Values
integersampleIdid of the created sample




loadStreamedSample

Description
Load streamed sample object

Definition
function loadStreamedSample(integer objectId, string bgmusicFilename)

Arguments
integerobjectIdid of streamed sample object
stringbgmusicFilenamestreamed sample filename (.ogg)




playStreamedSample

Description
Play streamed sample music object

Definition
function playStreamedSample(integer objectId, integer repeat)

Arguments
integerobjectIdid of streamed sample object
integerrepeatamount of recurrences. 0 means endless loop.




pauseStreamedSample

Description
Pause streamed sample object

Definition
function pauseStreamedSample(integer objectId)

Arguments
integerobjectIdid of streamed sample object




resumeStreamedSample

Description
Resume streamed sample

Definition
function resumeStreamedSample(integer objectId

Arguments
integerobjectIdid of streamed sample object




stopStreamedSample

Description
Stop streamed sample object

Definition
function stopStreamedSample(integer objectId

Arguments
integerobjectIdid of streamed sample object




setStreamedSampleVolume

Description
Set streamed sample volume

Definition
function setStreamedSampleVolume(integer objectId, float volume)

Arguments
integer objectId id of sample object
float volume volume value




getStreamedSampleVolume

Description
Get streamed sample volume

Definition
function getStreamedSampleVolume(integer objectId)

Arguments
integer objectId id of sample object

Return Values
float volume volume of sample object




createAudioSource

Description
Create audio source object for 3D sounds

Definition
function createAudioSource(string audioSourceName, string sampleFilename, float radius, float innerRadius, float volume, integer loops)

Arguments
stringaudioSourceNameaudio source name
stringsampleFilenamesample file name (.wav or .ogg)
floatradiusradius
floatinnerRadiusinner radius
floatvolumevolume [0,1]
integerloopsloops




getAudioSourceSample

Description
Gets the sample id of an audio source

Definition
function getAudioSourceSample(integer objectId)

Arguments
idobjectIdid of the audio source

Return Values
integersampleIdid of the sample



Input Function Reference


getNumOfGamepads

Description
Get number of joysticks/gampads

Definition
function getNumOfGamepads()

Return Values
integernumOfGamepadsnumber of joysticks/gampads

Notes
since v4.1.5




getInputAxis

Description
Get joystick/gampad axis value

Definition
function getInputAxis(integer axisNumber, integer gamepadIndex)

Arguments
integeraxisNumberaxis number [0=Input.AXIS_1, 5=Input.AXIS_6],
integergamepadIndexjoystick/gampad index

Return Values
floataxisValueaxis value [-1, 1]




getInputButton

Description
Get joystick/gampad button value

Definition
function getInputButton(integer buttonNumber, integer gamepadIndex)

Arguments
integerbuttonNumberbutton number [0=Input.BUTTON_1, 15==Input.BUTTON_16]
integergamepadIndexjoystick/gampad index

Return Values
floatbuttonValuebutton value [0, 1]




keyEvent and mouseEvent callbacks




XML Function Reference

XML Path

XML paths used in the getXML... and setXML... functions have the following format:
node1.node2.....nodeN
or
node1.node2.....nodeN#attribute.

Example:
<test>
   <test1 attr="test">
      This is some text
   </test1>
</test>

To get the attribute "attr", use the path test.test1#attr.
To get the content of test1, use the path test.test1.

createXMLFile

Description
Create an empty XML file

Definition
function createXMLFile(string objectName, string filename, string rootNodeName)

Arguments
stringobjectNameinternal name for the object created
stringfilenamefilename (full path)
stringrootNodeNamename of the root node

Return Values
integerobjectIdobject id




loadXMLFile

Description
Load XML file

Definition
function loadXMLFile(string objectName, string filename)

Arguments
stringobjectNameinternal name for the object created
stringfilenamefilename (full path)

Return Values
integerobjectIdobject id




saveXMLFile

Description
Save XML file

Definition
function saveXMLFile(integer objectId)

Arguments
integerobjectIdobject id




getXMLInt

Description
Get XML file integer attribute
See XML Path

Definition
function getXMLInt(integer objectId, string attributePath)

Arguments
integerobjectIdobject id
stringattributePathattribute path

Return Values
integervalueattribute value




getXMLFloat

Description
Get XML file float attribute
See XML Path

Definition
function getXMLFloat(integer objectId, string attributePath)

Arguments
integerobjectIdobject id
stringattributePathattribute path

Return Values
floatvalueattribute value




getXMLBool

Description
Get XML file boolean attribute
See XML Path

Definition
function getXMLBool(integer objectId, string attributePath)

Arguments
integerobjectIdobject id
stringattributePathattribute path

Return Values
booleanvalueattribute value




getXMLString

Description
Get XML file string attribute
See XML Path

Definition
function getXMLString(integer objectId, string attributePath)

Arguments
integerobjectIdobject id
stringattributePathattribute path

Return Values
stringvalueattribute value




setXMLInt

Description
Set XML file integer attribute
See XML Path

Definition
function setXMLInt(integer objectId, string attributePath, integer value)

Arguments
integerobjectIdobject id
stringattributePathattribute path
integervalueattribute value




setXMLFloat

Description
Set XML file float attribute
See XML Path

Definition
function setXMLFloat(integer objectId, string attributePath, float value)

Arguments
integerobjectIdobject id
stringattributePathattribute path
floatvalueattribute value




setXMLBool

Description
Set XML file boolean attribute
See XML Path

Definition
function setXMLBool(integer objectId, string attributePath, boolean value)

Arguments
integerobjectIdobject id
stringattributePathattribute path
booleanvalueattribute value




setXMLString

Description
Set XML file string attribute
See XML Path

Definition
function setXMLString(integer objectId, string attributePath, string value)

Arguments
integerobjectIdobject id
stringattributePathattribute path
stringvalueattribute value




hasXMLProperty

Description
Returns if an XML path is available in the file
See XML Path

Definition
function hasXMLProperty(integer objectId, string propertyPath)

Arguments
integerobjectIdobject id
stringpropertyPathpath to a node or an attribute

Return Values
booleanvalueis the given property available in the xml file




Network Function Reference


netStartup

Description
Startup network subsystem

Definition
function netStartup(integer maxConnections, integer threadSleepTimer, string localHostAddress, integer port, string packetReceivedCallback, object targetObject)

Arguments
integermaxConnectionsmax connections
integerthreadSleepTimerthread sleep timer (milliseconds)
stringlocalHostAddresslocal listen host address. Leave empty to disable listen port.
integerportlisten port number
stringpacketReceivedCallbackcallback function which is called when a packet was received
objecttargetObjecttarget object (optional), the callback function is called as a member function of targetObject

Return Values
booleanresulttrue if successful false otherwise




netSetMaximumIncomingConnections

Description
Set maximum incoming connections

Definition
function netSetMaximumIncomingConnections(integer maximumIncomingConnections)

Arguments
integermaximumIncomingConnectionsmaximum incoming connections




netSetIncomingPassword

Description
Set incoming password

Definition
function netSetIncomingPassword(string incomingPassword)

Arguments
stringincomingPasswordincoming password




netConnect

Description
Connect

Definition
function netConnect(string host, integer port, string password)

Arguments
stringhostremote host address
integerportremote post address
stringpasswordconnection password

Return Values
integerstreamIdstream id (zero if failed)




netCloseConnection

Description
Close network connection

Definition
function netCloseConnection(integer streamId, boolean sendDisconnectionNotification, integer orderingChannel)

Arguments
booleansendDisconnectionNotificationsend disconnection notification
integerorderingChannelordering channel




netShutdown

Description
Network shutdown

Definition
function netShutdown(integer maxBlockDurationTime, integer orderingChannel)

Arguments
integerstreamIdstream id
integermaxBlockDurationTimemaximum blocking duration time
integerorderingChannelordering channel




netSendStream

Description
Network send stream

Definition
function netSendStream(integer streamId, string priority, string reliability, integer orderingChannel, boolean flushStream)

Arguments
integerstreamIdstream id
stringprioritypriority (low, medium or high)
stringreliabilityreliability (unreliable, unreliable_sequenced, reliable, reliable_sequenced or reliable_ordered)
integerorderingChannelordering channel
booleanflushStreamflush stream




streamWriteBool

Description
Stream write boolean

Definition
function streamWriteBool(integer streamId, boolean value)

Arguments
integerstreamIdstream id
booleanvaluevalue




streamWriteInt8

Description
Stream write 8bit sigend integer

Definition
function streamWriteInt8(integer value)

Arguments
integerstreamIdstream id
integervaluevalue [-127, 127]




streamWriteInt16

Description
Stream write 16bit signed integer

Definition
function streamWriteInt16(integer value)

Arguments
integerstreamIdstream id
integervaluevalue [-32768, 32768]




streamWriteInt32

Description
Stream write 32bit signed integer

Definition
function streamWriteInt32(integer value)

Arguments
integerstreamIdstream id
integervaluevalue




streamWriteIntN

Description
Stream write N bit signed integer. 0>N>32.

Definition
function streamWriteIntN(integer value)

Arguments
integerstreamIdstream id
integervaluevalue [-2^(N-1), 2^(N-1)]




streamWriteFloat32

Description
Stream write 32bit float

Definition
function streamWriteFloat32(float value)

Arguments
integerstreamIdstream id
floatvaluevalue




streamWriteString

Description
Stream write string

Definition
function streamWriteString(string value)

Arguments
integerstreamIdstream id
stringvaluevalue, max 64k characters




streamReadBool

Description
Stream read boolean

Definition
function streamReadBool(integer streamId)

Arguments
integerstreamIdstream id

Return Values
booleanvaluevalue




streamReadInt8

Description
Stream read 8bit signed integer

Definition
function streamReadInt8(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integervaluevalue




streamReadInt16

Description
Stream read 16bit signed integer

Definition
function streamReadInt16(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integervaluevalue




streamReadInt32

Description
Stream read 32bit signed integer

Definition
function streamReadInt32(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integervaluevalue




streamReadIntN

Description
Stream read N bit signed integer

Definition
function streamReadIntN(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integervaluevalue




streamReadFloat32

Description
Stream read 32bit float

Definition
function streamReadFloat32(integer streamId)

Arguments
integerstreamIdstream id

Return Values
floatvaluevalue




streamReadString

Description
Stream read string

Definition
function streamReadString(integer streamId)

Arguments
integerstreamIdstream id

Return Values
stringvaluevalue




streamGetNumOfUnreadBits

Description
Stream get number of unread bits

Definition
function streamGetNumOfUnreadBits(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integervaluenumber of unread bit




streamGetReadOffset

Description
Stream get read offset

Definition
function streamGetReadOffset(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integeroffsetRead offset




streamSetReadOffset

Description
Sets the read pointer to the given offset in bytes

Definition
function streamSetReadOffset(integer streamId, integer offset)

Arguments
integerstreamIdstream id
integeroffsetread offset in bytes




streamGetWriteOffset

Description
Returns the write pointer offset in bytes

Definition
function streamGetWriteOffset(integer streamId)

Arguments
integerstreamIdstream id

Return Values
integeroffsetWrite offset




streamSetWriteOffset

Description
Sets the write pointer to the given offset in bytes

Definition
function streamSetWriteOffset(integer streamId, integer offset)

Arguments
integerstreamIdstream id
integeroffsetwrite offset in bytes




Network defines

Description
Network message types

Definition
VariableDescription
Network.TYPE_APPLICATIONApplication
Network.TYPE_CONNECTION_REQUEST_ACCEPTEDConnection request accepted
Network.TYPE_CONNECTION_ATTEMPT_FAILEDConnection attempt failed
Network.TYPE_ALREADY_CONNECTEDAlready connected
Network.TYPE_NEW_INCOMING_CONNECTIONNew incoming connection
Network.TYPE_NO_FREE_INCOMING_CONNECTIONSNo free incoming connections
Network.TYPE_DISCONNECTION_NOTIFICATIONDisconnection notification
Network.TYPE_CONNECTION_LOSTConnection lost
Network.TYPE_RSA_PUBLIC_KEY_MISMATCHRSA public key mismatch
Network.TYPE_CONNECTION_BANNEDConnection banned
Network.TYPE_INVALID_PASSWORDInvalid password
Network.TYPE_MODIFIED_PACKETModified packet
Network.TYPE_PONGPong
Network.TYPE_ADVERTISE_SYSTEMAdvertise system
Network.TYPE_REMOTE_DISCONNECTION_NOTIFICATIONRemote disconnection notification
Network.TYPE_REMOTE_CONNECTION_LOSTRemote connection lost
Network.TYPE_REMOTE_NEW_INCOMING_CONNECTIONRemote new incoming connection




Callbacks Function Reference


Default callbacks

init

Description
This function is called once on startup. Create and load objects here.

Definition
function init(string args)

Arguments
stringargscommand line arguments

Return Values
booleansuccessreturn true if successful




keyEvent

Description
This function is called when a key event occurs.

Definition
function keyEvent(float unicode, float sym, float modifier, boolean isDown)

Arguments
floatunicodeunicode value
floatsymsym key
floatmodifierkey modifier
booleanisDownis down state



mouseEvent

Description
This function is called when a mouse event occurs.

Definition
function mouseEvent(float posX, float posY, boolean isDown, boolean isUp, float button)

Arguments
floatposXx position [0,1]
floatposYy position [0,1]
booleanisDownis down state
booleanisUpis up state
floatbuttonbutton number



update

Description
This function is called once per frame to update game state.

Definition
function update(float dt)

Arguments
floatdttime between this frame and last frame in milliseconds



draw

Description
This function is called once per frame to draw game objects. Call render functions here.

Definition
function draw()

Custom callbacks

trigger callback

Description
This function is called when a trigger event occurs.

Definition
function triggerFunctionName(integer triggerId, string otherId, boolean onEnter, boolean onLeave, boolean onStay)

Arguments
integertriggerIdid of the trigger node
integerotherIdid of the other node
booleanonEnteron enter state
booleanonLeaveon leave state
booleanonStayon stay state



contact callback

Description
This function is called when a contact event occurs.

Definition
function onContact(integer objectId, integer otherObjectId, boolean isStart, float normalForce, float tangentialForce)

Arguments
integerobjectIdid of the object
integerotherObjectIdid of the other object
booleanisStartis start touch
floatnormalForcenormal contact force
floattangentialForcetangential contact force



raycast callback

Description
This function is called when a raycast hit event occurs.

Definition
function raycastFunctionName(integer hitObjectId, float x, float y, float z, float distance)

Arguments
integerhitObjectIdid of the hit node
floatxworld impact x
floatyworld impact y
floatzworld impact z
floatdistancedistance

Return Values
booleancontinuecontinue raycasting




create callback

Description
Create callbacks are called during i3d loads.

Definition
function createFunctionName(integer objectId)

Arguments
integerobjectIdid of the object




timer callback

Description
This function is called when a timer event occurs.

Definition
function timerFunctionName()

Return Values
booleankeepTimerreturn false if the timer should be removed




packet received callback

Description
This function is called when a network packet was received.

Definition
function packetReceived(packetType, timestamp, streamId)

Arguments
integerpacketTypetype of the packet. All available types are stored in the Network table
integertimestamptimestamp of when the packet was sent
integerstreamIdid of the stream containing the packet data




Foundation Reference

Scenegraph


translate

Description
Translate object (transform)

Definition
function translate(integer objectId, float dx, float dy, float dz)

Arguments
integerobjectIdobject id (transform)
floatdxx relative translation value
floatdyy relative translation value
floatdzz relative translation value

Source file
shared/foundation/scenegraph.lua




rotate

Description
Rotate object (transform)

Definition
function rotate(integer objectId, float dx, float dy, float dz)

Arguments
integerobjectIdobject id (transform)
floatdxx relative rotation value
floatdyy relative rotation value
floatdzz relative rotation value

Source file
shared/foundation/scenegraph.lua




toggleVisibility

Description
Toggle visibility of a scenegraph object

Definition
function toggleVisibility(integer objectId)

Arguments
integerobjectIdid of scenegraph object

Source file
shared/foundation/scenegraph.lua




printScenegraph

Description
Prints scenegraph object

Definition
function printScenegraph(integer objectId)

Arguments
integerobjectIdid of scenegraph object

Source file
shared/foundation/scenegraph.lua




Input




Key values

Description
Key values used by keyEvent function

Definition
VariableValueDescription
Input.KEY_a97Value of key a
Input.KEY_b98Value of key b
........
Input.KEY_z122Value of key z
Input.KEY_esc27Value of escape key

Source file
shared/foundation/input.lua




Mouse values

Description
Mouse values used by mouseEvent function

Definition
VariableValueDescription
Input.MOUSE_BUTTON_NONE0none mouse button
Input.MOUSE_BUTTON_LEFT1left mouse button
Input.MOUSE_BUTTON_MIDDLE2middle mouse button
Input.MOUSE_BUTTON_RIGHT3right mouse button

Source file
shared/foundation/input.lua




Gamepad/Joystick values

Description
Gamepad/Joystick axis values used by getInputAxis function

Definition
VariableValueDescription
Input.AXIS_X0x axis
Input.AXIS_Y1y axis
Input.AXIS_Z2z axis
Input.AXIS_W3w axis

Source file
shared/foundation/input.lua




Reverberation Preset values

Description
Reverberation preset values used by enableSampleFX function

Definition
VariableValueDescription
Audio.REVERB_PRESET_DEFAULT1Value of default reverberation preset
Audio.REVERB_PRESET_GENERIC2Value of generic reverberation preset
........
Audio.REVERB_PRESET_SPORT_FULLSTADIUM67Preset values of a full sport stadium
Audio.REVERB_PRESET_SPORT_STADIUMTANNOY68Preset values of a statium tannoy

Source file
shared/foundation/audio.lua




Filter types

Description
Filter types values used by enableSampleFilter function

Definition
VariableValueDescription
Audio.FILTER_NULL0Value of a NULL filter type. A filter that has no parameters and does nothing.
Audio.FILTER_LOWPASS1Value of a lowpass filter type. It is used to remove high frequency content from a signal. Not currently implemented
Audio.FILTER_HIGHPASS2Value of a hightpass filter type. It is used to remove low frequency content from a signal. Not currently implemented
Audio.FILTER_BANDPASS35Value of a bandpass filter type. It is used to remove high and low frequency content from a signal. Not currently implemented

Source file
shared/foundation/audio.lua




Tutorials



Tutorial 1 – Load i3d files and basics


The goal of this tutorial is to teach you the very basics of the GIANTS engine. You simply load an i3d with a cube in it and then rotate the cube by using LUA script.

Sample name: SampleI3DLoading
Script source code file: sample/i3dLoading/main.lua

The goal of this tutorial is to show you
  • how the engine uses ids
  • how to load i3d files
  • how to access objects within a loaded i3d
  • what the base callback functions of the engine are
  • how to access keyboard commands
New functions in this tutorial

init()
keyEvent()
update()
rotate()
getRootNode()
loadI3DFile()
link()
getChildAt()
print()
requestExit()

The most important script file is your main.lua. It is a lua file that is loaded and executed when your exe file is started.

The first thing you need to know is how the engine exactly knows where your main.lua is. Well there has to be an xml file in the same folder as your exe with exactly the same name as your exe. In this case it is named SampleI3DLoading.xml. Open it with a text editor.

<?xml version="1.0" encoding="iso-8859-1" standalone="no" ?>
<startup>
 <cmdline>game.exe -script sample/i3dLoading/main.lua</cmdline>
</startup>

In the third line you see where your main.lua is located. If you want to move your main.lua, you have to change the path in this xml as well.

So, let's have a look at this main.lua, open it with any text editor. There are 5 essential functions: init(), mouseEvent(), keyEvent(), update() and draw(). Let's look at these functions in detail:

init()


init() is executed once when you start your exe. Let’s go through the function line by line:

 local worldRootNode = getRootNode();

The variable worldRootNode is defined and assigned with the result of a function called getRootNode();

If you meet a new function and you don’t exactly know what it does, simply look here and search for the function. Then you get detailed information about the function. In the tutorials those function descriptions are always blue.
Here is what you find if you search for the getRootNode function:

getRootNode

Description
Get scenegraph root node

Definition
function getRootNode()

Return Values
integerrootNodeIdid of the root node

The descriptions of the functions are quite self-explanatory and can be really helpful.

It's important to see that the GIANTS engine works with ids also called handles. This function returns the id from the root node of your root scene graph.

Your entire world is attached to this root node. Each object you want to see later on must be a child of this root node.

Now we need to load the i3d that contains the cube we want to rotate later on.

 local sceneToLoad = loadI3DFile("sample/i3dLoading/cube.i3d");

With this function, you load an i3d file, and its id (which is an integer) is returned. Now that we’ve got both things, the worldRootNode and the i3d we want to load, we have to link them together, which is the next line of code.

 link(getRootNode(), sceneToLoad);

Now we want the cube's id to rotate. Be aware that the i3d we've already loaded is the whole scene which contains not only the cube, but also a light and the camera. So now we need to know which id the cube has. Since the cube is a child of the i3d we can use the following function:

 cubeId = getChildAt(sceneToLoad, 0);

First you name the i3d that you want the child from and then you say which child you want. 0 is the first child, 1 is the second. You need to know which child is your cube. Just open the cube .i3d with the Editor and you can see that the cube is the first position in your scenegraph (reading from top down)

Scenegraph

A very important thing you need in programming are prints. The function needed here is simply called print(). The thing you want to print are the parameters. Be careful with strings, they always need quotes. You can link strings and variables by using .. as shown in the example.

 print("this is a print: cube id: " .. cubeId);

You can see the printed text in the in game console. Just press tilde '~' to make the console visible.

Now we have all the information we need, but one thing remains to be done. Since the camera is located right in the center (inside the cube actually) we won’t be able to see anything. So we grab the camera and move it a bit. With the getCamera() function we first get the id of the camera, because the setTranslation function needs to know which id has to be translated. The next parameters are the desired x, y, z values.

 setTranslation(getCamera(), 5, 10.0, 10.0);

Then we rotate the camera so that we can see our cube nicely. The function is similar to the setTranslation but you define the rotations around the three axes of course. You need a radian value, that’s why the functions math.rad() are used. They convert a degree value into a radian value.

setRotation(getCamera(), math.rad(-45), math.rad(20), 0);

mouseEvent()

We don’t use this function right now, but of course you can access the mouse commands with it.

function mouseEvent(posX, posY, isDown, isUp, button)
end;

keyEvent()

This function is used to access any keyboard commands. In this case, we only want to know if the escape key is pressed. If this is the case, then the program closes with the command requestExit();

function keyEvent(unicode, sym, modifier, isDown)
 -- Check for escape key
 if sym == Input.KEY_esc and isDown == true then
  -- Request quit
  requestExit();
 end;
end;

update(dt)

The update function is a function that is called after every frame. The parameter dt is the time that has passed since the last update call in milliseconds.

So, this is the place where we can finally make our cube rotate. For this we use the rotate(dt) function. It needs the id of the object that should rotate, in this case the cubeId, and also the rate of rotation on the x, y and z-axis. We just let it rotate on the x-axis with the value of 0.08 degree per millisecond.

function update(dt)
 rotate(cubeId, math.rad(0.08)*dt, 0, 0);
end;

draw()

The draw function is needed to draw something onto the screen. This will be discussed later on.

function draw()
end;

Tutorial 2 – Light functions, global time and rendering text


Sample name: SampleLighting
Script source code file: sample/lighting/main.lua

The goal of this tutorial is to show you
  • how to manipulate lights in your scene
  • how to handle time
  • how to print a text on the screen
New functions in this tutorial

setLightDiffuseColor()
getLightDiffuseColor()
setLightRange()
getLightRange()
renderText()

The first thing you might notice is that there are two new additional variables that we’re going to use:
 local globalTime = 0;
 local lightRadius = 7;

In this, and also in further tutorials, we will just cover the new functions and variables. So, if there is anything you don’t understand, have a look at Tutorial 1.

init()

In the init() function we additionally store the id of the point light in the variable pointLightId.

 pointLightId = getChildAt(id, 2);

When you open the i3d file cubeWithPointLight.i3d, you can see that the light is in third position. Since the function getChildAt()starts counting from 0, the argument 2 points to the third child.

Set the light radius to an initial value of 7.

 setLightRange(pointLightId, lightRadius);

keyEvent()

Here are two more keys: Key 1 and Key 2. When they are pressed, the functions decreaseLightRadius and increaseLightRadius are called.

if sym == Input.KEY_1 and isDown == true then
 decreaseLightRadius();
end;

if sym == Input.KEY_2 and isDown == true then
 increaseLightRadius();
end;

increase- decreaseLightRadius()
These two functions change the variable lightRadius by 0.5 and then call the lightRadius function with the new value.

function increaseLightRadius()
 lightRadius = lightRadius + 0.5
 setLightRange(pointLightId,lightRadius);
end;

update(dt)

Two variables are new here:

Why do we need a globalTime here? Well, we want the light to rotate around the cube. Therefore, we need a value that constantly changes in corrrespondence with time. Of course you could also increase a number every frame, but since the framerate isn’t constant we also use the time which has passed since the last frame and thus get an exact and constantly growing number that isn’t affected by the different framerates. Remember that dt is the time passed between the last and the actual frame in milliseconds. So, if dt is multiplied by 0.001 you get seconds. We also need a distance to the center which is stored in the variable radius.

 globalTime = globalTime+dt*0.001;
 local radius = 2;

This function handles the translation of the pointLight using the globalTime and the radius 2.

 setTranslation(pointLightId, math.sin(globalTime)*radius, 3, math.cos(globalTime)*radius);

We also change the color of the diffuse color of the light. This is done with the setLightDiffuseColor() function. As arguments it uses the id, and then the three values for red, green and blue as floats between 0 and 1. As r we use the sinus of the globalTime.

 setLightDiffuseColor(pointLightId, math.sin(globalTime), 0.4, 0.2);

When you execute the program, you see that there is a white box where the point light is. This may seem a bit odd since you probably don’t want this cube to be visible at all. When you open the file cubeWithPointLight.i3d and click on the plus left of the light in the scene graph, you see that we have attached a little cube to the light. We have done this to to give you a better visual feedback on where the pointLight is. On top of that, it shows also another important thing: as a child it inherits the translations of the parent and thus also moves with it.

draw()

Like the update function, the draw function is executed after every frame.

First we store the rgb values of the pointLight using the getLightDiffuseColor() function. It returns three different values. So be careful, you need to separate the different variables by commas!

 local r, g, b = getLightDiffuseColor(pointLightId);

Then we use the function renderText() to render the result directly onto the screen.

renderText

Description
Render text to viewport

Definition
function renderText(float x, float y, float size, string str)

Arguments
floatxx position [0, 1]
floatyy position [0, 1]
floatsizefont size
stringstrstring to print

When using renderText you can also weld parts together with the .. operator to concatenate variables and strings like in the example.

 renderText(0,0.95,0.05,"r value: " .. r);
 renderText(0,0.90,0.05,"g value: " .. g);
 renderText(0,0.85,0.05,"b value: " .. b);

The next line stores the value of the getLightRange() function in the lightRadius variable

 local lightRadius = getLightRange(pointLightId);

and then the variable is rendered onto the screen:

 renderText(0,0.75,0.05,"LightRadius: " .. lightRadius);

With the last line we simply render the globalTime. Since it is a float we use math.floor to get an integer.

 renderText(0,0.65,0.05,"seconds: " .. math.floor(globalTime));

Tutorial 3 - User Attributes


Sample name: SampleUserAttributes
Script source code file: sample/userAttributes/main.lua

The goal of this tutorial is to show you
  • how to create user attributes
  • how to access user attributes from script
  • how to use the onCreate script callback
New functions in this tutorial

getUserAttribute()
setUserAttribute()
setScale()
translate()

Open sceneWithUserAttributes.i3d and main.lua which are located in \sample\userAttributes.

Run the sample SampleUserAttributes.exe. You see three cubes with different scales and one cube that is rotating. If you press 1,2 or 3, the related cube is translated onto the y-axis and the number of translations is also displayed.

If you look at sceneWithUserAttributes.i3d in the editor, you will see, that all three cubes in the back have the same size. Open the User Attributes window.

Editor

In the User Attributes window you see the name of your object, followed by the user attributes and at the bottom there is the possibility to create new attributes. Select the different objects to see what kind of user attributes they have.

You’ll notice that both cubes in the back have two user attributes labeled count and size. The bigger cube in the front only has an onCreate script callback.

How to create new user attributes
To create your own attributes, just enter the name of your attribute and then choose the according type of your attribute. You can choose whether your attribute is a boolean, integer, float, a string or a script callback. Then hit add and your attribute will appear.

Let’s have a look at the LUA code in main.lua. The very first line of code is the creation of an empty array called cubeIdArray.

init()


You should be familiar with the first two lines, otherwise have a look at Tutorial 1.
What follows is a for loop from 0 to 2 where the array cubeIdArray is filled up with three new arrays containing the cubeIds of the three cubes.

Then the variable size gets filled with the result of the getUserAttributes function. The getUserAttributes function needs the id of the object and the name of the attribute as arguments. Be careful here, the name has to be exactly the same as you have specified in the editor.

Finally, there is a check whether size has a value and then the function setScale is used to scale the cube accordingly. Try to enter new size values in the i3d and then see the result by running the program.

for index=0, 2 do
-- Get current cube id and store it for later
local cubeId = getChildAt(i3dRoot, index);
   cubeIdArray[index] = {};
   cubeIdArray[index].id = cubeId;

   -- Get scale value from user attributes
   local size = getUserAttribute(cubeId, "size");
   if size ~= nil then
     -- Set scale of current cube
     setScale(cubeId, size, size, size);
   end;
end;

keyEvent()


First we check if esc is pressed.

Then, if the keys 1,2 or 3 are pressed, the rest of the code is executed. The id of the corresponding cube is stored within the variable cubeId. Then the count of the cube is stored in the variable count by using the return value of the function getUserAttribute. If the count isn’t nil, the count is increased by one using the setUserAttribute function.

The setUserAttribute function can either be used to create new attributes or to overwrite values of existing attributes. It uses the id of the object (cubeId), the name of the attribute("count"), the data type(Integer) and the new value as arguments(count+1). Finally, the corresponding cube is translated onto the y-axis with the value 0.1 using the translate function.

if isDown == true then

  -- Check for escape key
  if sym == Input.KEY_esc then
   -- Request quit
   requestExit();
  end;

  -- Check for key 1 to 3
  if sym >= Input.KEY_1 and sym <= Input.KEY_3 then

    -- Get id of current cube
    local cubeId = cubeIdArray[sym-Input.KEY_1].id;

    -- Get count user attribute
    local count = getUserAttribute(cubeId, "count");
    if count ~= nil then
      -- Set count user attribute
      setUserAttribute(cubeId, "count", "Integer", count+1);
      -- Translate cube a bit
      translate(cubeId, 0, 0.1, 0);
    end;

  end;

end;

cubeOnCreate(id)


This function isn't called anywhere in the LUA code. So what is it used for? As soon as the cube in the front gets loaded, its attribute script callback causes the function cubeOnCreate to run once. The script also provides the id of the object that caused the script callback. Be careful with the spelling, the function in your LUA script has to be exactly the same as your ScriptCallback in the i3d. What we do in the cubeOnCreate function is quite simple: we store the id in the new variable rotatingCubeId.

function cubeOnCreate(id)
  -- Store the id for later
  rotatingCubeId = id;
end;

update(dt)


Here we first check if rotatingCubeId exists and then we rotate the cube using the rotate function with the id we stored in the variable rotatingCubeId.

function update(dt)

  -- Rotate cube3
  if rotatingCubeId ~= nil then
    rotate(rotatingCubeId, 0, 0.05, 0);
  end;

end;

draw()


Here you can see how flexibly you can use the renderText function: using it within a for loop, for welding text and variables as well as for calling functions like the getUserAttributes in this case.

function draw()

  for index=0, 2 do
    renderText(0,0.95-index*0.05, 0.04,"Cube " .. index .. ": "
    .. getUserAttribute(cubeIdArray[index].id, "count") .. " press key " .. index+1);
  end;

end;

Tutorial 4 - Timers


Sample name: SampleTimer
Script source code file: sample/timer/main.lua

The goal of this tutorial is to show you
  • how to create and use timers
New functions in this tutorial

addTimer()
setTimerTime()
removeTimer()

Run the sample SampleTimer.exe. Only three lines of text are rendered. The first shows you a random timer interval, the second is a string that says that you can remove the timer with the space key and finally, there is a line showing a flashing text :"Timer called".

Before we start looking at the code we should get a rough idea about what a timer is, and what functionalities it has.

A timer is a simple object that has a certain set time and the name of the callback function. As soon as the timer is activated, the defined time is counted down to zero. When this happens, the timer calls the callback function. This behavior can be used in various situations, for instance if a trigger shouldn’t react immediately but only after a certain delay.

Open the the main.lua which is located in the directory /sample/timer.

At first, four variables are defined:

timerId = 0;
timerInterval = 0;
renderCount = 0;
timerRemoved = false;

init()


In the init function the first line calls the function setRandomTimerInterval. This function simply generates a random value between 1000 and 5000 for the variable timerInterval.

function setRandomTimerInterval()
  timerInterval = math.random(1000, 5000);
end;

The variable timerInterval is used immediately because a new timer is created with the line:

 timerId = addTimer(timerInterval, "onTimer");

The variable timerId stores the Id of the new timer which is returned by the function addTimer. Here is how this function is described in the documentation:

addTimer

Description
Adds timer callback function

Definition
function addTimer(float time, string timerFunctionCallback, object instance)

Arguments
floattimetime in milliseconds
stringtriggerFunctionCallbacktrigger function callback
objectinstanceinstance object (optional)

Return Values
integertimerIdtimer id

The first argument is the time in milliseconds and the second argument is the function that is called when the time reaches zero. In this case, the variable timerInterval defines how long the timer will wait, until it calls its callback function. After this time, the function onTimer is called.

keyEvent()


If you hit the space key the timer is removed and the boolean timerRemoved is switched to true.

if sym == Input.KEY_space then
  -- Remove timer
  removeTimer(timerId);
  timerRemoved = true;
end;

onTimer()


This function is called as soon as the timer reaches zero.

The first line defines the variable renderCount to be 100. This defines the number of frames the line "timer called" is rendered in the draw function later on.

The second line defines a new timerInterval by calling the setRandomTimerInterval function again.

The third line sets a new timer time with the new timerInterval time. The setTimerTime function needs the id of the timer (timerId) and the new time (timerInterval). After the timer reaches zero again, the onTimer function is called again. You can remove a timer within the callback function by returning false.

-- Timer callback
function onTimer()
  renderCount = 100;
  setRandomTimerInterval();
  setTimerTime(timerId, timerInterval);
  return true;
end;

draw()


First we have an if-else construct that handles the two states, i.e. whether the timer is removed or not. Depending on the state of the boolean timerRemoved, the different renderText functions are executed.

The string "timer called" is only called if the variable renderCount is not zero. Remember that we set the renderCount to 100 in the onTimer function which is the trigger callback of the timer. With each frame the renderCount is decreased by 1.

Tutorial 5 - Physics


Sample name: SamplePhysics
Script source code file: sample/physics/main.lua

The goal of this tutorial is to show you
  • the difference between rigid body and no rigid body
  • the difference between static, kinematic and dynamic objects
  • how to create objects with physical behavior

Basically, there are two different types of objects available. Objects with rigid body and objects without rigid body.

No rigid body


Objects with no rigid body are only rendered. They can be moved freely and they don’t cause any collision, thus other objects can move through them. These objects only use a minimum of the engine's performance. If you export a new object from Maya without having changed the attributes, the rigid body is activated by default. You should turn it off in the editor, when you don’t need it.

Rigid body


Objects with rigid body behave like real objects. If another object with rigid body tries to go trough it, there will be a collosion. Since the used up power of this behavior has to be calculated, it should only be used when necessary. There are three rigid body types:

Static

These objects offer collision, but they can’t be moved, nor do they react to gravity.

Kinematic

These objects offer collisions with dynamic objects and can be moved in a predefined way. E.g. if you have a train that goes from A to B along a predefined path and a collision occurs with a kinematic object, the train will simply continue its movement, while the dynamic object will be pushed away. If the same train hits a static or another kinematic object, nothing will happen.

Dynamic

This kind of objects react dynamically to collisions and can't be moved manually. The movement of dynamic objects is a result of external forces and isn’t predefined.

Run SamplePhysics.exe.

Since it is self-explanatory, just open the sceneWithPhysics.i3d which is located in /sample/physics to see how it is done.

Editor

You probably need to zoom out a bit to see the whole scene.

Select the different objects and look at the Rigid Body Type in the red marked area. In this scene all objects are rigid bodies, but the Rigid Body Type is different, depending on how their physics should react.

If you want to select a cube which is within the sphere of the multi-selection-tool, you’ll first have to select something that is a bit further away.

Try to change the Rigid Body Type of the different objects and see what happens, when you run the program. To change it, simply open the dropdown menu and select the desired Rigid Body Type. Hit enter, and don’t forget to save your scene.

Instead of defining the physical behavior of an object in the editor, you could specify these settings directly in Maya. Launch the i3d exporter and open the attributes panel where you can see all the Rigid Body options available. Just select the desired mesh, click Load Current and then set the Rigid Body settings as you wish. Don’t forget to click Save Current when you've done it. If you export the mesh as an i3d file, the rigid body settings are already included. This method has the advantage that attributes defined in Maya remain in the saved scene file. If you export the same scene more than once, you might save time by defining it once in Maya instead of redoing it every time in the editor.

Maya

Tutorial 6 - Overlays


Sample name: SampleOverlay
Script source code file: sample/overlay/main.lua

The goal of this tutorial is to show you
  • how overlays work
  • how to create overlays
New functions in this tutorial:

createOverlay()
setOverlayColor()
renderOverlay()

When you run sampleOverlay.exe you see an overlay displayed on the screen. If you click on it, its position changes randomly.

Open main.lua which is in /sample/overlay to take a look at the code.

First there are three variables: overlayId holds the id of the overlay, overlayX and overlayY are used to define the position of the overlay.

init()


In the first line, the variable overlayId is filled with the result of the function createOverlay which returns the id of the newly created overlay. The documentation describes the createOverlay functions as follows:

createOverlay

Description
Create overlay object

Definition
function createOverlay(string overlayName, string textureFilename)

Arguments
stringoverlayNameoverlay name
stringtextureFilenametexture file name

Take note that you have to use the relative path to your file.

 overlayId = createOverlay("overlay", "sample/overlay/overlay.png");

The second line consists of the setOverlayColor function.
Try to comment it out by adding -- in front of the line. Save the script and run the program. You see that this sample also works without the setOverlayColor function. It isn’t needed to display an overlay, but it gives you the possibility to change its appearance. Here is how it is described in the documentation:

setOverlayColor

Description
Set overlay color

Definition
function setOverlayColor(integer overlayId, float red, float green, float blue, float alpha)

Arguments
integeroverlayIdoverlay id
floatredred value
floatgreengreen value
floatblueblue value
floatalphaalpha value

The used arguments in the example result in white with an opacity of 0.75.

 setOverlayColor(overlayId, 1, 1, 1, 0.75);

Try the arguments 1, 0, 0, 0.75, to see the difference.

mouseEvent()


This function runs every time you move the mouse or click on it. If the mouse is inactive this function isn’t executed. It provides the position of the cursor, and the state of the buttons which can be used within the function.
We first check, if the state of a mouse button is down, which is done by the isDown part of the if-construct. The rest of the if-construct is a simple hit test, it checks whether the cursor is within the overlay or not. If the if-construct returns true, you have clicked on the button. Then the overlayX and overlayY values are overwritten with a random number between 0.05 and 0.8.

function mouseEvent(posX, posY, isDown, isUp, button)
  -- Check if overlay has been clicked
  if isDown and posX > overlayX and posX < overlayX+0.16 and
    posY > overlayY and posY < overlayY+0.04 then
    overlayX = math.random(50, 800)/1000;
    overlayY = math.random(50, 900)/1000;
  end; end;

draw()


What happens here is essential : try commenting out the renderOverlay function once. If you run the sample now, nothing will be rendered at all. This function is needed to render an overlay. This allows you to display or hide components (e.g. menu options) depending on the state of your program.

Here is how the function is described in the documentation:

renderOverlay

Description
Render overlay

Definition
function renderOverlay(integer overlayId, float x1, float y1, float width, float height)

Arguments
integeroverlayIdoverlay id
floatxx position [0,1]
floatyy position [0,1]
floatwidthwidth [0,1]
floatheightheight [0,1]

A width and height of 1 means that the overlay has exactly the size of the screen.

Since overlayX and overlayY change when you click on the overlay, it is instantly rendered in the new position.

function draw()
  -- Render overlay
  renderOverlay(overlayId, overlayX, overlayY, 0.16, 0.04);
end;

Tutorial 7 - Audio


Sample name: SampleAudio
Script source code file: sample/audio/main.lua

The goal of this tutorial is to show you
  • how to use audio samples
  • the difference between 2d and 3d sounds
New functions in this tutorial

createSample()
loadSample()
playSample()

Run sampleAudio.exe. Every two seconds you should hear a "pling" and if you press space you should hear a water splash.

Open main.lua which is in /sample/audio to see the code of this example.

First there are three variables: time, sample1Id and sample2Id

init()


The first line creates a sample using the createSample function and stores the id in the variable sample1Id. The only argument here is the name of the sample.

 sample1Id = createSample("sample1");

The sample is like an empty shell which needs filling with an audio file. That’s what the second line does. It needs the id of the sample and the filename as arguments. The last argument is a boolean and defines whether your sound is 3D or not.

3D sounds can be placed in your scene. They are surrounded by a sphere which defines the distance over which the sound can be heard. The closer you get to the sound the louder it is.

A 2D sound simply plays at full volume when it is triggered.

For the filename you need to indicate the relative path.

 loadSample(sample1Id, "sample/audio/sample1.wav", false);

keyEvent()


If you press the space key, the sample2 is played via the playSample function. Here is how this function is described in the documentation:

playSample

Description
Play sample object

Definition
function playSample(integer objectId, integer loops, float volume, float offset)

Arguments
integerobjectIdid of sample object
integerloopsnumber of loops [0,n] 0 = endless looping
floatvolumevolume [0,1]
floatoffsetoffset in milliseconds

The offset defines from which position within the sample it starts playing. E.g. if you define an offset of 3000, the first three seconds of your sample are cut off the first time the sample gets played.

if sym == Input.KEY_space then
  playSample(sample2Id, 1, 1, 0);
end;

update()


First the time is increased and if it is larger than 2000 milliseconds the sample1 is played and the time is reset to 0.

function update(dt)

  time = time + dt;

  if time > 2000 then
    playSample(sample1Id, 1, 1, 0);
    time = 0;
  end;
end;



Editor

  1. Viewport
  2. Scenegraph Panel
  3. Attributes Panel
  4. Toolbar
  5. Terrain Editing
  6. User Attributes
  7. Animation Panel
  8. Particle System Panel
  9. Spline Editing
  10. Scripting
  11. Replace Dialog
  12. Interactive Placement
  13. Other functionality
  14. Keyboard short-cuts



If you start up the Editor, you might not have all the panel windows open. To open other panel windows open the menu option window and enable the panel you want. You can adjust the width and height of the panels by dragging the outlines and if you want to close a window you can simply press the cross right of the panel name.


Viewport




Navigation

The navigation is quite like in Maya. If you have nothing open in your editor I suggest you quickly open a simple i3d file otherwise you won’t see much of an effect. If its to dark in your scene just create a light by going to Create–>Light.
Some shortcuts:
LMB = Left Mouse Button
RMB = Right Mouse Button
MMB = Middle Mouse Button
Alt + LMB = Press and hold the Alt-Key and the left mouse button.

Alt + LMB is rotating the camera.
Alt + RMB moves the camera forward and backward.
Alt + MMB causes the camera to pan.

If you don’t have a middle mouse button, you can press LMB and RMB instead.

View Options

By simply right-clicking into the viewport panel you get the View Options. Sometimes it’s useful too use different cameras in a scene. You can create them once and then with the View Options you can choose the camera to view at your scene from different angles quickly.

You might notice that if you rotate, the camera is rotated. If you have a big level this behaviour is very useful, but if you want to look at one particular object this can be quite awkward. To change the rotation to Framed Rotate you first have to select your object either by clicking on it directly or by choosing it from the scene-graph and the framing the selected object by pressing the F key. Now you can simply click (RMB) on the screen to open the View Options and choose Framed Rotate. Now the camera is rotating around your the last framed object.

With solid or wireframe you can choose if you want the view shaded.

If you have large scenes, you can toggle the visibility of lights, audio sources, physics and the cameras by checking them on the show submenu.

You can also use the Selectable submenu to toggle whether you can select lights, audio sources or cameras.

Furthermore you can toggle the grid and the polycount on and off.


Scenegraph Panel

A very useful feature of the GIANTS Editor is the scenegraph. If you don’t have it on the screen, just go to menu window and hit scenegraph. It is basically the same you have in Maya. It shows all objects you have in your scene and also the parent-child relationship between your objects.



Let’s just make a little scene with some Transform Groups. The Transform Group is the basic building block of your scene. You can use a TransformGroup to move all the attached objects just by moving the Transform Group since the children inherit the transformations of the parent. To create a new Transform Group go to Create and hit TransformGroup. Now you can see it in the Scenegraph, its name is transform. To change the name just select it and go to the attributes panel. At the very top of the panel you can choose the name of your object. Make two TransformGroups and name them Parent and Child. If you move them around you see that their transformations are independent, the movement of the parent doesn’t affect the child. Now let’s make the appropriate relationship between the two. Select the child in the scenegraph panel and go to Edit->Cut. Now select your parent and hit Edit->Paste.

As you can see now, the child is now connected to the parent. If you now move around the parent, the transformation of the child is affected too whereas the child can be moved around without affecting the parent.




There can be 6 types of objects in your scene: Triangle Meshes, Splines, Cameras, Transform Groups, Lights, Terrains and Audio Sources.

It is also possible to use CTRL+C to copy objets, CTRL+X to cut objects and CTRL+V to paste objects. Notice that pasted objects are always children of the currently selected object. If you want to paste an object on the highest hierarchy level of the scenegraph be sure that nothing is selected in the scenegraph. This can be achieved by clicking at an empty space in the scenegraph panel.


Attributes Panel

If you don’t see the attributes panel go to Windows->Attributes then select an object in the scenegraph or the viewport. One important thing to notice is, that if the background color of an attribute turns red, you entered a value that isn’t allowed. (eg scale values other than 1 for a dynamic rigid body object) The background color of animated attributes is yellow.




Toolbar




The toolbar looks like this. If your pointing on the icons with your mouse, a text with the functionality of the tool is displayed.

Let’s quickly go through them from left to right.

File Operations
  • Create a new i3d-File
  • Open a i3d-File
  • Open i3d in text editor (4.1.4 or later)
  • Reload i3d (4.1.4 or later)
  • Save the i3d-File
  • Save the i3d-File as
  • Import an i3d-file
History
  • Undo last action
  • Redo last action
Physics
  • Play/Stop
If you hit the play icon, the physics will simulate.

Toggle Local- World Mode
A handy tool is the toggle Local- World Mode, it changes the orientation of the viewport transform gizmo from the local space of your object to world space.

Grid Snapping (4.1.5 or later)
Use this option to snap objects to a predefined grid.

Terrain and Terrain Foliage
  • Terrain Sculpt Mode
  • Terrain Detail Texture Paint Mode
  • Terrain Foliage Paint Mode
  • Save Terrain Data
Texture Reload
  • Reload all Textures
  • Reload Textures of selected objects


Terrain Editing




To test the terrain sculpting, just open the terrain test scene. Now you have a terrain to play with. Open the terrain editing panel with window->Terrain Editing. (If the scenegraph panel is still open it might cut off a bit, just close it to get more space.)



If the terrain sculpt mode is active now, you can rise or lower the surface of your terrain by using RMB and LMB. MMB can be used to smooth and the value defines the force with which you pull or push. What happens here is, that you are painting a height map, that defines the height of each point of your terrain by giving it a grey-value. The attributes Opacity, Hardness and the Value are defining the “brush” you are painting the height map with. Just play around with the setting.With the shortcuts "V" and "B" you can change size of the brush and with "N" and "M" you can change the opacity of the brush quickly.

In the terrain texture paint mode next to the terrain sculpt icon you can colorize your terrain with different textures.
The used texture layers are defined in the i3d-file. (If you want to change the texture layers, you have to open the i3d with a text editor and change the layers there) Just choose your texture and paint onto your terrain. With the Chunk vis checkbox on, you can see exactly which texture layers you used in a chunk by what amout. You can use as many texture layers as you want, but you are limited to a maximum of four texture layers per chunk.

With the Terrain Foliage Paint Mode active, you can paint your foliage onto your terrain, it`s the same thing as if you would paint onto your terrain - not with a texture but with foliage. LMB adds foliage, RMB removes foliage.


User Attributes




The user attributes panel is typically not visible if you open the editor for the first time. So go to Windows->User Attributes. Select an object in the scenegraph to see its user attributes.

User Attributes can be defined in the editor and then be used in the engine (eg. within a script). This enables you to define object specific attributes for every object in the scene.


Animation Panel (4.1.5 or later)




You can preview animation sets with the animation panel.

Particle System Panel (4.1.5 or later)




The particle system panel allows you to edit particle systems with real time preview.

Spline Editing (4.1.5 or later)




You can edit splines by picking a control vertex (CV) of a spline an moving it around. Delete or insert new control vertices with the keys delete and insert.

Scripting

Here you can execute script snippets. With ENTER, you can add new lines. SHIFT+ENTER will execute the code in the text field.

Type in the following:

print("hello world from the GIANTS Editor");

Then hit SHIFT+ENTER and the string is printed out above.


The scripting can be useful for many things. For example you can run this script snippet to test the fog settings in an i3d scene:

setFog("exp2", 0.002, 0, 0.8, 0.81, 0.97);


Replace Dialog




If you want to replace an object in your scene, you can go to Edit->Replace to open the replace panel. Select the object you want to replace, then hit load. Do likewise with the object you want to replace with and choose whether you want to keep the User Attributes or not. Now you can replace one single object by hitting replace or you can replace all objects that are similar to the one you selected by hitting replace all.

Note: replace all does only work with single objects, but not with hierarchies of objects, however the single replace function works.
This feature is quite useful because you can use it to substitute an object reference feature within your i3d scene file.


Interactive Placement

This is a really nice feature of the editor, so you should try it at least once!
To place an object on the surface of another object, you can simply select the object you want to place and then press CTRL + B + LMB, while pointing at your desired location. The selected object will then instantly be set to the location you’ve chosen.

Hint: you can do this with all your objects within your scenegraph and also with the camera or light sources. E.g. you can select the current camera and then place the camera at a location far away, allowing for fast relocation of the camera.

If you keep the LMB pressed and hit CRTL or SHIFT you can clone the selected object at the currect mouse position. CRTL will just clone the object while SHIFT will add a random rotation in the y-axis. (Very useful feature if you want to create a forest with hundreds of randomly rotated trees for instance)

Other functionality


Edit->Clear History: This clears the undo/redo history.

Edit->Move to Camera: Moves the selected object in front of the current camera

Navigation Speed: Moves the camera faster or slower. Use - and + to ajust the speed.


Keyboard short-cuts

Key Function
Alt + LMB Rotate camera
Alt + MMB Pan camera
Alt + RMB Zoom camera
Alt + LMB + RMB Move camera up or down and left or right camera
F Frame selected object
- Decrease navigation speed
+ Increase navigation speed
4 Wireframe mode
6 Shaded mode
Ctrl-S Save
Ctrl-Z Undo
Ctrl-W Replace Dialog (4.1.6 or later)
Ctrl-X Cut
Ctrl-C Copy
Ctrl-V Paste
Delete Delete
Ctrl-D Duplicate
Ctrl-F Move to Camera
Ctrl-B Interactive placement (hold left mouse button to move around)
Shift Interactive placement paint
Ctrl Interactive placement paint with random rotation around y axis
Ctrl-R Pick replace value in viewport (Terrain edit modes)
V Decrease brush radius
B Increase brush radius
N Decrease brush opacity
M Increase brush opacity
F8 Toggle stats
Shift + Enter Execute Script (Script Window)
X Grid Snapping (4.1.5 or later)
Delete Delete spline control vertex (4.1.5 or later)
Insert Insert new spline control vertex (4.1.5 or later)




Debugger

  1. Overview
  2. Interface
    1. Menu and Toolbars
    2. Main text editor panel
    3. File browser panel
    4. Variable overview panel
    5. Additional information panel
  3. Tutorial
    1. Setup
    2. Debugging
    3. Stepping
  4. Keyboard short-cuts



Overview

The debugger lets you test and run your scripts by setting break points inside your code and analyzing the situation once reaching them. With its help you can avoid adding custom debug print calls to check for the assignment of variables or if a certain part of the code got reached. It is easy to use and follows known conventions for debugging environments.

The user interface is divided in the following sections:

You can move around each panel by dragging and dropping the corresponding title bar. You can resize the panel by pulling its borders. You can close panels you don't need by using the cross symbol on the upper right corner and make them reappear again through the View-menu.

To actually use the remote debugger's functionality see section Tutorial.

Most actions described here require use of the left mouse button, for the remainder of the text clicking a button means using the left mouse button.
In the last section the available keyboard short-cuts are listed.

User Interface

Menu and Toolbars

The file menu lets you open and save files, create and switch between projects and exit the application. The view menu lets you show hidden parts of the user interface. There is also the option to reset the complete window layout. With the debug menu you can control your debugging sessions (see section Debugging for details). The help menu finally directs you to further information on our website.
The most common operations are directly accessible in the toolbars.

Main text editor panel

The text editor panel shows you all currently opened source code files. You can toggle between different source files by clicking on the tabs at the top of the panel. To close a specific source file press the cross in this row on the right edge of the panel.
If you have opened many files you can use the arrows on the left and right side to move the currently shown tabs or use the small down arrow to directly jump to a specific file.
The editor behaves like a regular text editor that in addition automatically highlights script commands. You can use it to directly write your source code.

The most important part in conjunction with debugging is the setup of breakpoints. To set a break point press the left mouse button on the grey vertical bar to the right of the line numbers. A red dot will appear and signal the presence of the break point. Click on it again to remove it. Please be aware that you can only set breakpoints in source code lines that represent a script statement.

File browser panel

The file browser shows you the project directory tree. It only shows files with the following extensions: .lua, .xml and .i3d files. In the file browser you can open files for editing.
If you made changes to files outside of the debugger you have to refresh this view in the context menu. You can access the context menu with a right mouse button click.

Variable overview panel

This panel shows you all variables and its assigned values in the current state.
There are two tabs with global and local variables. Global variables are accessible from any code part. Whenever you create a new variable that is not directly stored inside a table or specified as local, a new global variable is generated. Local variables are either parameters passed to a function or newly created variables with the local keyword.
Both tabs show a list with the variable name, its assigned value and its type. The contents of tables can be opened by using the + symbol in the variable list. For these contents a string representation of each key is used as name. If the key is a table its content is not visible.

Additional information panel

Callstack tab

While debugging, the callstack tab shows you the stack of functions called, that result in the current position in the code. The topmost list item specifies the current position in the code.
Each item in the list states the source code file and the position inside this file where the function call happened. Double clicking on an item results in opening this source code file at the specified position inside the text editor panel, the line is also marked by a green arrow on the left side.

Breakpoint tab

This tab shows a list of all set breakpoints. Double clicking on an item results in opening this source code file at the specified position inside the text editor panel, the line is also marked by a green arrow on the left side.

Output tab

The output tab shows the engine logging output. The output of your print commands is also shown there.
Script error messages are printed in this log as well. Double clicking on an item results in opening this source code file at the specified position inside the text editor panel, the line is also marked by a green arrow on the left side.

Tutorial

Setup

To create a new remote debugger project use the file menu with File / New Project.... In the window that appears you have to specify the project settings.
  • Name: Name of the project
  • Location: Location where the project file is saved
  • Source Base: Directory that is used as the root for all source files in the project
  • Debug Port: TCP/IP port number
  • Command line: Command to run the application
  • Working Directory: Directory where to run the application
  • In most cases the fields for Location, Source Base and Working Directory will show the same value.

To be able to debug your program the debugger has to connect to the running application. The easiest way to manage this is by specifying the -autoConnectDebugger command line option in the XML-file for your application. The XML-entry should look similar to this line:
<cmdline>game.exe -script scripts/main.lua -name test -autoConnectDebugger</cmdline>
The mentioned command line option is added by default if you start the application within the debugger. You can still use the debugger without the autoConnectDebugger command line option by pressing F10 in the engine application. The status line at the bottom of the debugger will indicate the status of the connection to the game application.

Debugging

An important part of debugging are breakpoints. Whenever the script code execution reaches a code line with a breakpoint the execution paused. You can set breakpoints inside the text editor panel by clicking next to the code line number. A red dot will appear to show the position of the breakpoint. The code will be stopped before execution of the script statement in the current line. Please note that only lines with script statements can be used for breakpoints. To remove a breakpoint you can click on the red dot again.
To control a debugging session you can use the Debug-toolbar, the corresponding menu items or keyboard shortcuts.
To start a debugging session you need to launch the engine application. You can do this with the Start and Stop-commands.
Once a breakpoint is reached during execution of the script code the engine application pauses. Now you can inspect the current engine state with the help of the variable, the callstack and the output panel.

You can also pause the engine application at any point in time without a breakpoint with the Break all-command. This command is useful when you need to know what the engine application currently does.

To let the program continue use the Continue-command.

Stepping

To further analyze the control flow of the script code and the change of variables you can also step the application on a line by line basis with the help of the Step into, Step over, and Step out commands.
The functionality provided is, in short words:
  • Step out - stop at the next script statement after the statement that called the current function
  • Step into - stop at the first script statement of the function to be called
  • Step over - stop at the next script statement in the current function
The current position in your code is always highlighted by a yellow arrow next to the line numbers. If you opened other files and don't know where the engine execution stopped you can always use the callstack and double click on its first entry and the code file will open in the text editor panel with the current line marked with a green arrow.

The following screenshots show an example situation.
The program is stopped at line 19 of the test.lua file. In the local variables panel we see that the two parameters of the function and the newly set variable with the parameter z are available. The callstack tells us, that we are currently in line 19, but also that the current function was called in line 9 from the current file. And again this function was called from line 52 of the main.lua source file.

If we want to continue debugging we could use the Step into command which would lead us to line 27, the first line with a statement of the called function third(). The Step over command would result the engine application to pause at line 21. And the Step out command would finally run the same code but stop at line 11.
Please note that line number 20 and 26 are no script statements and therefore you cannot set breakpoints on such lines.

Keyboard short-cuts

Key Function
Ctrl-S Save
Ctrl-Alt-S Save all
F5 Start/Continue debugging
Ctrl-F5 Start without debugging
F6 Stop debugging
F7 Break all
F10 Step over
F11 Step into
Shift-F11 Step out

Exporter



Autodesk Maya1 i3d exporter



To generate i3d files of your 3d-models you can use the exporter plugin for Autodesk Maya. The GIANTS Editor and the GIANTS Engine can only load i3d files. This section of the documentation will show you, how to export i3d files with the I3D exporter plugins in Autodesk Maya. The first thing you probably want to do is to install the exporter plugins in Autodesk Maya.

Installing I3D exporter plugin

Step 1
Place the files I3DExportUI.mel, I3DExportValidate.mel and I3DExporter2008.mll into the folder "C:/Documents and Settings/<USERNAME>/My Documents/maya/scripts".

Step 2
Start Maya and open the Script Editor window.



Step 3
Select custom shelf tab

Step 4
Type the following commands in the lower portion of the Script Editor:

loadPlugin -qt "C:/Documents and Settings/<USERNAME>/My Documents/maya/scripts/I3DExporter2008.mll";
source I3DExportUI;
source I3DExportValidate;
I3DExport;

Highlight the commands, then use the middle mouse button, to drag the highlighted MEL commands to the shelf.

Note:
  • Maya don't like backslashes so replace them with slashes.
  • Replace <USERNAME> with your username.
  • The file path can be different depending on the language of your operating system (eg. C:/Dokumente und Einstellungen/<USERNAME>/Eigene Dateien/maya/scripts/I3DExporter2008.mll)

Step 5
Copy the I3D_icon.bmp into the folder "C:/Documents and Settings/<USERNAME>/My Documents/maya/2008/prefs/icons". Edit shelf to replace the default icon with the one enclosed.


Preparing your 3d-model for export

Before you can actually use the exporter, it’s wise to check certain things with your 3d-model in Maya which can cause issues later in the editor or the engine.

In the Channel-Box you see the transformations of your selected object.



The ScaleX, ScaleY and ScaleZ of your object should be 1 1 1.
If you just plan to use this object as a static mesh or with no physics at all you could export it with any scale you want, but if you want to simulate your object in the engine (as a dynamic or kinematic rigid body object) the scale must be 1 1 1 otherwise the physics simulation will produce incorrect results.



If you have an object with scale, you can easily get rid of the scale. Go to the Modify-Panel, and select the option box right of the Freeze Transformations. The Freeze Transformations dialog window opens. You can select the checkbox scale and hit apply.

Note: Please refer to the artwork guide for further information about asset conditioning for the engine.


I3D exporter usage

Start the exporter dialog with a click on the I3D exporter icon you have created on your custom shelf (see Installing I3D exporter plugins)



Export Panel
The export panel is quite self-explanatory. In the export options part you can include and exclude parts from exporting (IK, Animation, Shapes, Nurbs Curves, Lights, Cameras, Particle Systems and/or Default Cameras). The Shape Export Subparts section allows you to control which subshape attributes are exported (Normals, vertex Colors, Texture Coordinates and/or Skin Weights).

The miscellaneous section has this options:
  • Verbose, display verbose information in output window during the export
  • Relative Paths, generate relative paths for texture files
  • Float Epsilon, truncate values within epsilon range to zero. Epsilon: [-1e-5, 1e-5]

Buttons
  • Preview, exports whole scene to a temporary file and starts the editor
  • Export All, exports the whole scene
  • Export, exports only currently selected objects

Attributes Panel
In the attributes panel you can load and save attributes of your objects those attributes will be saved into the Maya file and are translated into the correct i3d attributes when you export to a i3d file.



The first thing you have to do here is, that you must press the "Load Current" button at the bottom in order to load the attibutes of your object. Otherwise everything is unchecked and is not showing the attributes that are currently active on you object. So be sure, to hit this button first.

Current Node
Here you can see the name of your current working object.

Rigid Body
This section handles all the attributes regarding to physics rigid bodies.

Joint
Here you can define your joint-attributes in detail. One thing you might miss here are the joint limits, they must be defined within Maya, since your object can have many joints with different limits. You can define the limit of a joint angle by the limit informations of your transform-object.

Rendering
  • Occlusion Culling, Objects that are entirely covered by other objects may be culled and thus not rendered at all. This option can increase the rendering performace in the engine if you have big objects containing much smaller objects, for instance a house. If you activate the occlusion culling on the root-node of the house all its childs are also not rendered, if the house is complete covered behind other objects. However, you should not apply this attribute on too many small objects because it is one more task for the engine.
  • Non Renderable, With this option a objects will not be rendered at any time. Use this option for collision geometry. If you have complex objects with sub-objects attached, be careful with this checkbox since this attribute is also going to affect all the attached children.
  • Clip Distance, This value defines how far the object is still going to be rendered. If you have a large scene and tons of objects this is a powerful method to keep your framerate high.
After you have defined all your attributes, you have to hit the "Save Current" button to save your attributes. If you have lots of objects with the same attributes, you can select them all, and then use apply selected to apply the current settings to all the selected objects. Remove current resets the attributes to the default values and if you want do reset multiple objects, you can select them all and hit "Remove Selected"

Validate Panel
With this panel you can validate if one of your objects have an incorrect pivot. In Maya your pivot can have a local and a world space attribute which you can find in the attribute editor on the right side. The x y and z values of both, local and world-space have to be 0 0 0 otherwise you will get a warning. You can fix incorrect pivots with the FreeezeToPivot option in the tools panel.

Tools
If you have validated your objects and a local pivot was not set to 0 0 0, you can quickly fix affected objects with the FreeezeToPivot button.


Known issues

Issue Solution
place2dTexture node information is ignored Don't modify place2dTexture nodes and operate directly on the texture coordinates
Polygons with more than 4 sides and/or holes are ignored Triangulate affected polygons (Modeling->Polygons->Triangulate)

Material export options

Mapping between Maya and i3d material attributes



Material Attributes
  • Custom Shader: Use the attribute name 'customShader' with a string type to add a custom shader to the material.
    The value specifies the path of the custom shader xml file relative to the maya file.
  • Custom Shader Parameter: Use the attribute name 'customParameter_<parameterName>' with a string type to specify the value of a custom shader parameter. The values should be space separated.
    <parameterName> is the name of the parameter as specified in the custom shader.
  • Custom Shader Texture:: Use the attribute 'customTexture_<textureName>' with a string type to specify the texture of a custom shader texture.
    The value specifies the path of the texture file relative to the maya file.
    <textureName> is the name of the texture as specified in the custom shader.

Autodesk 3ds MAX2 i3d exporter

Installing I3D exporter plugin

Copy the plugin file I3DExporter2008.dle or I3DExporter2009.dle into this directory:

%3DSMAX installation path%/plugins/

On a Windows XP (english version) this would be this path:

C:\Program Files\Autodesk\3ds Max 2009\plugins

for example.


Blender i3d exporter

Installing I3D exporter plugin (Windows)

  1. Install Python Runtime 2.6
  2. Setup the environment variable PYTHONPATH to the python installation path. Also add DLLs and LIB directory.
    Example: PYTHONPATH = C:\Python26;C:\Python26\DLLs;C:\Python26\Lib
  3. Copy blenderI3DExport.py to Blenders scripts directory.
    (eg. C:\Documents and Settings\\Application Data\Blender Foundation\Blender\.blender\scripts)

Installing I3D exporter plugin (Linux)

You'll find a hidden directory called ".blender" in your home directory. Inside there's a sub-directory called "scripts", place the file blenderI3DExport.py there. Restart Blender.




1,2 Autodesk 3ds MAX and Autodesk Maya are registered trademarks of the Autodesk Corp.



Content Creation - Artwork Guide



Autodesk Maya

Set correct normals

Adjust normals to match topology. Use hard edges for cubic and soft edges for curved surfaces.

fixNormals1

fixNormals2



Disable double sided option

doubleSided



Remove zero area polygons

zero_area_poly



Eliminate T-Injunction

t-injunction



Autodesk 3DS MAX



Remove useless polygons

Remove useless polygons



Generate normalmaps for details

Generate Normalmaps for appropriate details in the geometry.

Generate Normalmaps



Flip edges

Flip/turn edges to match topology of the polygon mesh.

Retriangulation of the polygon mesh is a good starting point. This works only with Editable Polys

retriangulate

Convert to a Editable Mesh

convertToMesh

Flip/Turn individual edges manually

Flip edges 1
Flip edges 2



Disable two sided material option

Two sided materials are not supported in the engine and have to be replaced by an inverted copy of the affected polygons.

2sided1

2sided2

Used operations

  • Disable 2-Sided checkbox material property
  • Select Mesh
  • Clone
  • Select clone
  • Modifier: Polygon mode, select affected polygons and flip normals
  • Delete unused faces from cloned mesh
  • Attach cloned mesh to original mesh
  • Modifier: Vertex mode and weld vertices

2sided3



Set correct normals

Adjust normals to match topology. Use hard edges for cubic and soft edges for curved surfaces.

fixNormals1

Used operations

  • Select Mesh
  • Normal Modifier
  • Select affected normals and break them
  • Fine tune normals manually (optional)

fixNormals1b

fixNormals2



Merge to single polygon mesh

Merge groups of objects to a single mesh for optimal in-game performance.

mergeToSingleMesh1

Used operations

  • Select one object
  • Modifier: Object mode and attach list
  • Select objects to merge

mergeToSingleMesh2



Texturing

JPEG compression artifacts

Never use the JPG format to store textures. Each time a jpg file is stored the quality of the image decreases. Even if the compression quality is set to 100%.

jpg_artifacts1 jpg_artifacts2
Saved once as png from orignal texture (left), saved multiple times as jpg (right)

Non-Power-of-Two textures

Use power-of-two textures but you can use non-squared textures. As a general rule you should make your textures as big as they are in pixels when beeing projected onto the screen in the game.
Eg. if you want to texture a fullscreen squad, you probably want to use a 1024x1024px to 2048x1024px sized texture.
Normalmap textures should be at least as big as the diffuse textures or even twice as big.

Texture size

Texture size must be 2048x2048 pixels or smaller. Bigger textures are not supported on older graphics cards (eg. GeforceFX, Radeon9xxx, Radeon8xx and Intel onboard graphic chips).


Generate maps for parallaxmapping

Requirements
The Nvidia Photoshop Normal Map Filter plug-in from Nvidia. This plug-in can be downloaded from developer.nvidia.com

Description
  • First, you need a greyscale image or a bump map as the base for the Parallax Map. Please note that most of the time, you will have to convert this greyscale image to a RGB image. You can do this with select Image > Mode > RGB Color (menu bar).
  • Go to the "Window" tab and select "Show Channels". In the channel window, click the 'Create New Channel' icon on the bottom right, just left of the Trash Icon. A new channel "Alpha 1" will appear.

  • NV_Settings


  • Click one of the Color channels, press CTRL-A then CTRL-C to copy the channel informations to the clipboard for later use.
  • In the channel window select the RGB channel with shift and the left mouse button. All channel tabs should now be marked or accordingly selected.
  • Go now to the "Filter" menu and select "nvTools/NormalMapFilter...". In the Height Generation section, select InvertY. To create a Parallax Map you also have to select Height in the Alpha Field Section. With the "Scale" setting you can alter the intensity (depth) of the normal map. The "Filter Type" setting, defines how precise the normal map has to be. "4 sample" means precise, whereas 9x9 means rough. Click "OK" to proceed.

  • NV_Settings


  • You should now have a normal map, combined with a bump map in the Alpha Channel.
  • Now you have to insert the previous saved channel information to the "Alpha 1" channel. Select the alpha channel with your left mouse button and then press CTRL-V to paste the Heightmap image into the channel.
  • To increase the quality of your Parallax Map you can try also to apply a low gaussian filter to the alpha channel. Further you can reduce the contrast to get better results.
  • Save the Image as png with transparency (RGBA 32 bit).




I3D Format



Introduction

I3D is an open eXtensible Markup Language (XML) file format.

The purpose of i3D is to interchange 3D assets between applications and platforms without loss of information.

Workflow

A vaild I3D file can have up to seven parts: Textures, Materials, Shapes, Dynamics, Scene graph, Animation and Userdata. Dependent on application each part can be omitted.

The XML Schema language is used to describe the I3D feature set. Download: I3D 1.6 Schema

Features

  • Scenegraph hierarchy with
    • TransformGroups/Bones: translation, rotation, scale and visibility
    • Lights: ambient, point, directional and spot lights
    • Cameras: field of view, near and far clipping plane
    • Shapes: meshes and nurbs curves (supports geometry instancing)
    • Particle Systems
  • Animation
    • Animation sets
    • Clips
    • Keyframes: translation, rotation, scale and visibility
    • Morph Targets
  • User Attributes
  • Dynamics
    • Particle Systems (Sprite based)
      • Surface Emitter
      • Gravity Fields
      • Air Fields
  • Meshes
    • Vertices
    • Normals
    • Vertex colors
    • Skin weights
    • Texture coordinates (including multiple uv sets)
    • Faces (vertex color, normals and texture coordinates per face)
  • Curves
    • Nurbscurves
  • Shader/Materials
    • Multitextures (arbitrary layered textures)
    • Lightmaps
    • Bumpmaps/Normalmaps
    • Environmentmaps
    • Specularmaps

Overview



Overview

Specification

General Layout

  <?xml version="1.0" encoding="iso-8859-1"?>
  <i3D name="MyScene" version="1.6" xsi:noNamespaceSchemaLocation="http://i3d.giants.ch/schema/i3d-1.6.xsd">
    <Files>..</Files>
    <Materials>..</Materials>
    <Shapes>..</Shapes>
    <Dynamics>..</Dynamics>
    <Scene>..</Scene>
    <Animation>..</Animation>
    <UserAttributes>..</UserAttributes>
  </i3D>

Coordinate Systems

I3D uses a right-handed coordinate system.


Files


All used file references are defined here. File handles are mapped to the corresponding filenames.

  <Files>
    <File fileId="1" filename="myTexture1.png" relativePath="true"/>
    ...
  </Files>

Materials


Materials used in the materials attribute of Shape nodes within the scenegraph section are defined in this section.

  <Materials>
    <Material name="myShader_001" materialId="12">
      <Texture fileId="1"/>
    </Material>
    ...
  </Materials>

Shapes


Shapes are defined here and referenced from the Scene graph section. This mechanism allows multiple instancing of shapes.
  <Shapes>
    <IndexedTriangleSet name="myMesh01" shapeId="1">
      ...
    </IndexedTriangleSet>
    ...
  </Shapes>

Shape node types


IndexedTriangleSet

Attribute Description Type Optional
name Name of Shape string no
shapeId Shape id integer no

Element Description Type Cardinality
Vertices List of vertices complex 1
Triangles List of triangles complex 1
Subsets List of Subsets complex 1

Vertices
Attribute Description Type Optional
count Number of vertices integer no
normal Normal boolean yes
uv0 UV set 0 boolean yes
uv1 UV set 1 boolean yes
uv2 UV set 2 boolean yes
uv3 UV set 3 boolean yes
color Vertex color boolean yes
blendweights Blend weights boolean yes

Element Description Type Cardinality
v Vertex complex 1..n

v

Attribute Description Type Optional
p Vertex position string no
n Vertex normals string yes
t0 to t16 Texture coordinate string yes
c Vertex colors string yes
bw Bone weights string yes
bi Bone indices string yes


Triangles
Attribute Description Type Optional
count Number of triangles integer no

Element Description Type Cardinality
t Triangle complex 1..n

t

Attribute Description Type Optional
vi Vertices index string no


Subsets
Element Description Type Cardinality
Subset Subset complex 1..n

Subset

Attribute Description Type Optional
firstVertex First vertex integer no
numVertices Number of vertices integer no
firstIndex First index integer no
numIndices Number of indices integer no


Example
<IndexedTriangleSet name="myMesh01" shapeId="1">
  <Vertices count="30" uv0="true">
    <v c="-0.50 -0.5 0.50" t0="0 0.1 0.3 0.3 0.2 0 0.1 1"/>
    <v c="0.49 -0.5 0.50" t0="1 0.9 0.3 0.3 0.6 0 0.1 1"/>
    <v c="-0.50 0.49 0.50" t0="0 0.1 0.9 0.3 0.2 0 0 1"/>
    ...
  </Vertices>
  <Triangles count="40">
    <t vi="0 1 3"/>
    <t vi="2 3 5"/>
    <t vi="4 5 7"/>
    ...
  </Triangles>
  <Subsets count="1">
    <Subset firstVertex="0" numVertices="30" firstIndex="0" numIndices="40"/>
  </Subsets>
</IndexedTriangleSet>


NurbsCurve

Attribute Description Type Optional
name Name of Shape string no
shapeId Shape id integer no
degree Degree integer no
form Form (stored as: "open", "close" or "periodic") string no

Element Description Type Cardinality
cv List of contol vertices complex 3..n


cv

Attribute Description Type Optional
c Contol vertex (stored as "x y z") string no


Example
<NurbsCurve name="cameraPathShape" shapeId="1" degree="3" form="periodic">
  <cv c="-160.4501888 7.53270339 82.4246445"/>
  <cv c="-72.07301868 2.962592169 111.1353409"/>
  <cv c="-14.67712792 3.470019386 126.2614971"/>
  <cv c="15.12607817 8.251274441 47.11430616"/>
  <cv c="30.05244121 12.88635426 26.06245926"/>
  <cv c="34.16515005 11.5454009 -1.548135874"/>
  <cv c="-86.27624814 11.50889609 -65.1259517"/>
  <cv c="-88.5073931 11.67542369 -86.80101523"/>
  <cv c="-174.5511508 8.575730303 -67.03592031"/>
  <cv c="-189.2139061 8.539901228 -43.65303468"/>
  <cv c="-199.9735277 8.470538543 63.31385212"/>
  <cv c="-191.3309447 8.438562697 75.55727406"/>
  <cv c="-176.8774992 8.259085125 81.87273025"/>
</NurbsCurve>

Dynamics


Dynamic objects are defined in this part and referenced from the Scene graph section.

  <Dynamics>
    <ParticleSystem name="emitter1" dynamicId="1" type="sprite" rate="0.004" lifespanInfinite="false"
    speed="0.01" speedRandom="0" tangentSpeed="0" normalSpeed="1" lifespan="10000" maxCount="1000"
    spriteScaleX="50" spriteScaleY="50" depthSort="false" emitterShape="pCubeShape1" shader="lambert2">
      <Gravity force="0 -3 0"/>
      <Air velocity="2 0 0"/>
    </ParticleSystem>
  </Dynamics>

Scenegraph


The Scene graph hierarchy (transformations, bones, joints, shapes, lights, cameras and particle systems) are stored in this section. Shapes, materials and particle systems are stored as references.

  <Scene>
    <TransformGroup name="myGroup1" translation="1.25 0 -9" nodeId="47">
      <Shape name="mySphere" materialIds="1" shapeId="1" nodeId="48"/>
      <TransformGroup name="myGroup2" rotation="90 0 270" nodeId="49">
        <Shape name="mySphere2" materialIds="1" shapeId="2" nodeId="50"/>
      </TransformGroup>
      ...
    </TransformGroup>
    ...
  </Scene>

Scene graph node types


TransformGroup

Attribute Description Type Optional
name Name of TransformGroup string no
translation Translation complex yes
rotation Rotation, euler order ZY'X'' complex yes
scale Scale complex yes
visibility Visibility boolean yes
kinematic Kinematic object boolean yes
dynamic Dynamic object boolean yes
static Static object boolean yes
compound Compound parent boolean yes
compoundChild Compound child boolean yes
collision Enable collision boolean yes
ccd Continuous collision detection boolean yes
trigger Trigger boolean yes
cloth Cloth boolean yes
restitution Restitution float yes
staticFriction Static friction float yes
dynamicFriction Dynamic friction float yes
skinWidth Skin width float yes
density Density float yes
collisionMask Collision mask integer yes
joint Joint boolean yes
breakableJoint Breakable joint boolean yes
jointBreakForce Joint break force double yes
jointBreakTorque Joint break torque double yes
projection Enable joint projection boolean yes
xAxisDrive Enable x axis drive boolean yes
yAxisDrive Enable y axis drive boolean yes
zAxisDrive Enable z axis drive boolean yes
drivePos Enable drive position boolean yes
projDistance Projection distance double yes
driveForceLimit Drive force limit double yes
driveSpring Drive spring double yes
driveSpring Drive spring double yes
solverIterationCount Solver iteration count integer yes
rotMinX Rotation minimum x double yes
rotMinY Rotation minimum y double yes
rotMinZ Rotation minimum z double yes
rotMaxX Rotation maximum x double yes
rotMaxY Rotation maximum y double yes
rotMaxZ Rotation maximum z double yes
transMinX Translation minimum x double yes
transMinY Translation minimum y double yes
transMinZ Translation minimum z double yes
transMaxX Translation maximum x double yes
transMaxY Translation maximum y double yes
transMaxZ Translation maximum z double yes
objectMask Object mask integer yes
nodeId Node reference id, used for Animation and UserAttributes section integer no

Element Description Type Cardinality
TransformGroup Transform group node complex 0..N
Shape Shape node complex 0..N
Camera Camera node complex 0..N
Light Light node complex 0..N
Dynamic Dynamic node (eg. particle system) complex 0..N

Shape

Attribute Description Type Optional
shapeId Shape reference id (reference to shapes section) string no
materialIds List of used material ids (reference to materials section) string no
skinBindNodeIds Skin bind node ids string yes
castsShadows Casts shadows boolean yes
receiveShadows Receive shadows boolean yes
clipDistance Clip distance double yes
nonRenderable Non renderable boolean yes


Camera

Attribute Description Type Optional
fov Field of view double no
nearClip Near clipping plane double no
farClip Far clipping plane double no

Light

Attribute Description Type Optional
type Light type string no
diffuseColor Diffuse color complex yes
emitDiffuse Emit diffuse string yes
specularColor Specular color complex yes
emitSpecular Emit specular string yes
castShadowMap Cast shadow Map boolean yes
depthMapBias Depth map bias double yes
depthMapResolution Depth map resolution integer yes
shadowFarDistance Shadow far fistance double yes
shadowTextureOffset Shadow texture offset double yes
shadowExtrusionDistance Shadow extrusion distance double yes
decayRate Decay rate integer yes
coneAngle coneAngle double yes
dropOff dropOff integer yes
projTexture Projective texture name string yes
range Range double no

5 Dynamic

Attribute Description Type Optional
dynamicId Dynamic id (reference to dynamics section) string no



Example

<Scene>
  <Camera name="camera1" translation="0 2.00 6.47" rotation="-13.07 0 0" fov="54.43" nearClip="0.01" farClip="1000" nodeId="34"/>
  <Light name="pointLight1" translation="6.56 5.76 4.04" type="point" diffuseColor="1 1 1" range="10" nodeId="35"/>
  <TransformGroup name="group1" translation="1.35 0.96 0.81" nodeId="36">
      <Shape name="pCubeShape1" rotation="-23.94 6.49 14.29" materialIds="1 2" shapeId="1" nodeId="37"/>
  </TransformGroup>
</Scene>

Animation


Motions are defined in this part. Clips are the basic building block and allow Non-Linear Animation by composing multiple clips.

  <Animation>
    <AnimationSets>
      <AnimationSet name="walk_crouched">
        <Clip name="walk_crouched1Source" duration="1000">
          <Keyframes nodeId="Hips">
            <Keyframe time="0" translation="-0.467 13.504 39.842"/>
            <Keyframe time="333" translation="-0.559 12.915 39.370"/>
            <Keyframe time="1000" translation="-2.610 11.917 35.462"/>
          </Keyframes>
          <Keyframes node="Chest">
            <Keyframe time="0" rotation="-1.013 -4.465 0.890"/>
            <Keyframe time="666" rotation="10.009 -6.667 4.381"/>
            <Keyframe time="1000" rotation="11.638 -3.906 4.115"/>
          </Keyframes>
        </Clip>
      </AnimationSet>
    </AnimationSets>
  </Animation>

I3D Example: Quad

<?xml version="1.0" encoding="iso-8859-1"?>

<i3D name="myScene" version="1.6" xsi:noNamespaceSchemaLocation="http://i3d.giants.ch/schema/i3d-1.6.xsd">
  <Files>
    <File fileId="1" filename="myTexture1.png"/>
  </Files>

  <Materials>
    <Material name="myShader_001" materialId="1">
      <Texture fileId="1"/>
    </Material>
  </Materials>

  <Shapes>
    <IndexedTriangleSet name="myPolyObject" shapeId="1">
      <Vertices count="3" uv0="true">
        <v c="-0.50 -0.5 0.50" t0="0 0.1 0.3 0.3 0.2 0 0.1 1"/>
        <v c="0.49 -0.5 0.50" t0="1 0.9 0.3 0.3 0.6 0 0.1 1"/>
        <v c="-0.50 0.49 0.50" t0="0 0.1 0.9 0.3 0.2 0 0 1"/>
      </Vertices>
      <Triangles count="3">
        <t vi="0 1 3"/>
        <t vi="2 3 5"/>
        <t vi="4 5 7"/>
      </Triangles>
      <Subsets count="1">
        <Subset firstVertex="0" numVertices="3" firstIndex="0" numIndices="3"/>
      </Subsets>
    </IndexedTriangleSet>
  </Shapes>

  <Scene>
    <TransformGroup name="myGroup1" translation="1.25 0 -9">
      <Shape name="myPolyObject" shapeId="1" materialIds="1"/>
      <TransformGroup name="myGroup2" translation="2.0 1.0 1.5" rotation="90 0 270">
        <Shape name="polyObject" shapeId="1" materialIds="1"/>
      </TransformGroup>
    </TransformGroup>
  </Scene>
</i3D>

Test Scenes


Note: Test scenes are bundled with the editor.

terrain_test
Terrain and Foliage (terrain_test.i3d)
water_test
Water Shader (terrain_test.i3d)
physics_test
Physics (physics_test.i3d)
custom_shader_test
Custom Shader (custom_shader_test_scene.i3d)
character_animation_test
Character Animation (character_animation_test.i3d)
parallax_mapping_test
Parallax Mapping (parallax_mapping_test.i3d)
level_of_detail_test
Level of Detail (level_of_detail_test.i3d)
particle_system_test
Particle System (particle_system_test.i3d)