Skip to content

LUA API Reference

mika edited this page Dec 20, 2017 · 29 revisions

Contents


Example Script

b = BinooAPI
b:CreateSphere("red",1,3,0,0)
b:AddGazeTarget("red")
b:AddEvent("red","CLICK","ClickCorrect")
function ClickCorrect()
    b:ShowMessage("Clicked Object")
    b:ClearObjects()
end

More examples: https://github.com/NTUSPMS/BinooAPI

LUA Unity API reference

Interactive Objects

  • void CreateButton(string id, string buttonText, float x, float y, float z)
    • creates button
  • void CreateButton(string id, string buttonText)
    • creates button
  • void SetButtonText(string id, string buttonText)
    • sets button text
  • void CreateToggleButton(string id, string buttonText, float x, float y, float z)
    • creates button with checkbox toggle
  • void CreateToggleButton(string id, string buttonText)
    • creates button with checkbox toggle
  • void SetToggleButton(string id, bool state)
    • sets checkbox state

Using External Objects

  • void Instantiate(string prefabPath)
    • instantiates pre-made prefab (must be already inside the app Resources/ folder)
  • void Instantiate(string prefabPath, string name)
    • instantiates pre-made prefab (must be already inside the app Resources/ folder)
    • and assigns name to the gameobject
  • void LoadBundle(string bundleURL)
    • loads assetbundle from server url and instantiates to scene
  • void LoadBundle(string bundleURL, string name)
    • loads assetbundle from server url and instantiates to scene and sets name
    • example: b:LoadBundle("https://binoo.edu2vr.com/public/asset-bundle/$PLATFORM$/Fossils%20and%20Skeletons/Dinosaur%20skull","skull")
    • NOTE: $PLATFORM$-string is required to allow different platforms to load their own bundle
    • NOTE: loading is asynchronous, so the object wont be available until loading has finished
  • void CleanBundleCache()
    • clears asset bundle cache (to force loading new version from server)
    • NOTE: in current version cleancache is called on every loadbundle
  • string GetAssetURL(string modelRelativePath)
    • example b:LoadBundle(b:GetAssetURL("Plants%20and%20Animals/Spider_walk"),"1")
    • returns full assetbundle url, with correct platform (android/ios)
  • void LoadStringFromURL(string url, string key = null)
    • load string from url, string is saved to internal 'lastLoadedString'-variable
    • key is optional, if given, loaded text is assigned into internal string dictionary with that key
    • if key is not given, string is loaded into internal lastLoadedString variable
    • in lua script, you can then wait until given key exists, that means data is loaded or use the waitForMe bool
  • void ParseBVHFromLastLoadedString(string targetObj, bool drawDebugOnly = false, bool zIsUp = true)
    • parses BVH mocap data from internal internal 'lastLoadedString'-variable and assigns animation to targetObj
    • Note: Bone names are renamed "hip", "Hips", "abdomen", "lowerBack", "rToe", "RightToes"..and more
    • Note: Z is up is default on
    • Note: drawDebugOnly wont show mesh to the user, because its at 0,0,0
  • void ParseBVHFromString(string targetObj, string key, bool drawDebugOnly = false, bool zIsUp = true)
    • Same as above, but takes string from internal string dictionary, with given string 'key'

Animation Component

  • void StopAnimation(string target)
  • void PlayAnimation(string target)
    • Stops or Plays Animation component for all Animation components founded in children of target gameobject
  • float GetAnimationLength(string target)
    • returns length of first animation component
    • if no animation component is founded, returns -1
  • float GetAnimationTimeNormalized(string target)
    • same as above, but using normalized time 0-1
  • bool JumpToAnimationTime(string target, float time, bool stopPlaying = false)
    • jumps to animation time, in the first animation component
    • if no animation component is founded, returns false bool JumpToAnimationTimeNormalized(string target, float time, bool stopPlaying = false)
    • same as above, but using normalized time 0-1
  • bool SetAnimationSpeed(string target, float speed)
    • sets animation speed in the first animation component
    • if no animation component is founded, returns false

Internal Variables

  • string GetInternalString(string key)
    • Get string from internal string dictionary, returns null/nil if not existing
  • void SetInternalString(string key, string val)
    • Set string to internal dictionary
    • returns null if not found
  • bool InteralStringExists(string key)
    • returns true if key exists in internal string dictionary
  • void ClearInternalStrings()
    • Clears internal string dictionary
  • bool WaitForMe()
    • checks if internal variable 'waitForMe' is true or false
    • currently only CallLoadText() and TerrainHeightmapLoadersets() it back to false after loading finished
  • void SetWaitForMe(bool state)
    • sets internal variable 'waitForMe' to true or false
    • currently only CallLoadText() and TerrainHeightmapLoadersets() sets it back to false after loading finished
  • 'lastLoadedString'
    • CallLoadText() loads string into this variable
    • currently only used in ParseBVHFromLastLoadedString()

Using CommandServer Commands

  • void SendCommand(string command)
    • executes CommandServer commands on client
    • list of available commands: link-missing
    • example to show message: b:SendCommand("MESSAGE|HelloWorld!")
  • void Cmd(string command)
    • short version of SendCommand

Controlling Modes & Scripts

  • void SwitchMode(string newMode)
    • switches to another mode, without deleting LUA generated objects
    • modes: D, O, S, 360, PC, G, 3D, T, PHOTOSPHERE, EMPTY
    • you can call b:ClearObjects() manually to clear them
    • NOTE: previous script loops get stopped/destroyed

Creating GameObjects

  • void CreateLine(float x1, float y1, float z1, float x2, float y2, float z2)
    • creates line object between two positions x,y,z to x,y,z
  • void CreateLine(string name, float x1, float y1, float z1, float x2, float y2, float z2)
    • creates line object between two positions x,y,z to x,y,z and assigns name to the gameobject
  • void CreateCube(string target, float width, float height, float depth, float x, float y, float z)
    • creates cube primitive
    • note: has collider by default
  • void CreateQuad(string target, float width, float height, float x, float y, float z)
    • creates quad primitive
    • note: has collider by default
  • void CreateSphere(string target, float radius, float x, float y, float z)
    • creates sphere primitive
    • note: has collider by default
  • void void CreateLightSource(string name, float x, float y, float z, int r, int g, int b)
    • creates point at light given location with color set to RGB (0-255)
  • void CreateLightSource(string name, float x, float y, float z
    • creates point at light given location
  • void Clone(string source, string target)
    • clones gameobject (to same position and rotation)
    • wont clone if target gameobject already exists
  • void CreateGameObject(string newName)
    • creates new empty gameobject
    • this could be used as an invisible collider (use AddBoxCollider(..))
  • void CreateGameObject(string newName, float x, float y, float z)
    • creates new empty gameobject at position
    • this could be used as an invisible collider (use AddBoxCollider(..))

Procedural meshes

  • void CreateSphere(string newName, float radius, int segments)
  • void CreateBox(string newName, float sizeX, float sizeY, float sizeZ, int segmentsX, int segmentsY, int segmentsZ)
  • void CreateCone(string newName, float height, float lowerRadius, float upperRadius, int segments, int sectors)
  • void CreatePlane(string newName, float sizeX, float sizeZ, int segmentsX, int segmentsZ)
  • void CreateSlope(string newName, float sizeX, float sizeY, float sizeZ)
  • void CreateStairs(string newName, int stairs, float sizeX, float sizeY, float sizeZ)
  • void CreateTorus(string newName, float flipAngle, float phaseAngle, float radius, float width, int segments, int sectors)

Working with GameObjects

  • void ClearObjects()
    • erases all LUA generated objects
    • this gets called when switching modes or photospheres
  • void AddEvent(string target, string eventType, string functionName)
    • attaches event script to target gameobject
    • note: You must add AddGazeTarget() first, otherwise event function does not get registered
  • void AddEvent(string target, string eventType, string functionName, string parameter)
    • attaches event script to target gameobject with parameter to send for that function
  • void RemoveEvent(string target, string eventType)
    • removes specific event from gameobject
  • void SetLayer(string target, string layer)
    • sets object layer
    • for now, adding AddGazeTarget() automatically also sets correct layer "UI", so that gaze hits it
  • void AddGazeTarget(string target)
    • makes object as a gaze target
    • Collider is required on the object
  • void AddDragTarget(string target)
    • makes object draggable by adding GazeTargetEmpty script to it (same way like duck)
    • note: layer must be also set with: b:SetLayer(id,"Pickable")
  • void AddDragTarget(string target, string onStartDragFunction, string onReleaseFunction)
    • makes object draggable by adding GazeTargetEmpty script to it (same way like duck)
    • also adds lua scripts to run when dragging starts and ends
  • void RemoveDragTarget(string target)
    • removes GazeTargetEmpty from the object
  • void RemoveGazeTarget(string target)
    • removes gazetarget script
  • void SetColor(string target, int red, int green, int blue)
    • sets object material (note: for now only first object, not multimesh)
  • void AddRigidbody(string target, float mass)
    • adds physics to object (so by default, the object would fall down with gravity)
  • void SetVelocity(string target, float x, float y, float z)
    • sets physics object velocity
  • void AddCollider(string target, string type)
    • adds collider to object
    • available collider types: "SPHERE", "BOX", "MESH"
    • NOTE: if there is not meshfilter in the root gameobject, box collider is added instead (and fit to child objects)
  • void AddBoxCollider(string target, float cx, float cy, float cz, float width, float height, float depth)
    • Adds box collider with params
    • collider center: cx,cy,xz (in gameobject local space)
    • collider size: width, height, depth (in gameobject local space)
  • void RemoveCollider(string target)
    • removes collider from target
    • note: only removes first one (not all, if there are multiple same colliders)
    • colliders checked: SphereCollider, MeshCollider, BoxCollider, CapsuleCollider
  • void SetActive(string target, bool state)
    • activate/deactivate gameobject
    • when deactivated, it wont interact with anything and scripts attached to the gameobject wont run
  • void Rename(string target, string newName)
    • renames gameobject
  • void SetParent(string child, string parent)
    • set parent for this child gameobject (child becomes parented under parent)

Moving & Scaling Objects

  • void MoveObject(string name, float x, float y, float z)
    • moves target object to x,y,z position
  • void SetPosition(string name, float x, float y, float z)
    • moves target object to x,y,z position
  • void TweenMove(string target, float x, float y, float z, float duration)
    • animates object position from current position to target position
    • duration in seconds
  • void TweenMoveX(string target, float distance, float duration)
  • void TweenMoveY(string target, float distance, float duration)
  • void TweenMoveZ(string target, float distance, float duration)
  • void TweenScale(string target, float newScale, float duration)
    • animates object scale from current scale to target scale
    • duration in seconds
  • void TweenRotate(string target, float rx, float ry, float rz, float duration)
    • animates object scale from current rotation to target rotation (eulerangles)
    • duration in seconds
  • void SetRotation(string target, float rx, float ry, float rz)
    • set gameobject euler rotation angles
  • void Rotate(string target, float rx, float ry, float rz)
    • set gameobject euler rotation angles
    • same as SetRotation()
  • void ScaleObject(string target, float scaleX, float scaleY, float scaleZ)
    • sets object scale
  • void PlaceObjectOnSphere(string target, float u, float v, float radius = 1500 / 2)
    • moves object to photosphere
  • void RotateTowardsPlayer(string target)
    • calls "go.transform.LookAt(go.transform.position - PlayerControls.instance.transform.position);"
  • void RotateAround(string target, float angle, float px, float py, float pz, float ax, float ay, float az)
    • Rotates the transform about axis passing through point in world coordinates by angle degrees
  • void MoveX(string id, float distance)
  • void MoveY(string id, float distance)
  • void MoveZ(string id, float distance)
    • move towards z-axis in local space (forward)
  • void RotateX(string id, float angle)
  • void RotateY(string id, float angle)
  • void RotateZ(string id, float angle)
    • rotate single axis in local space
  • void LookTowards(string id, string targetID)
    • rotate id-gameobject to look at towards targetid-gameobject (z axis towards target)

Working with Lines

  • void SetLineVertexPosition(string target, int index, float x, float y, float z)
    • sets line vertex position
    • CreateLine() object has 2 vertices by default, so use index 0 or 1 for now

Queries

  • vector3 GetPosition(string target)
    • get gameobject position
    • result string is in format: x,y,z
  • bool FindObject(string target)
    • returns true if gameobject can be founded, or false if not found
  • float TimeSinceLastTap()
    • returns time in seconds since last tap event (accelerometer tap detection)
    • returns negative value if no tap events yet
  • int TouchCount()
    • returns touch count (how many fingers touching screen)
  • string GetUserName()
    • returns username that has been set in character customizer
    • note: this is not unique username, can be anything.
    • Returns "Unknown" if not set

Text

  • void CreateText(string id, string text, int fontSize, float x, float y, float z)
    • creates text object with id, text string, font size and position
    • text object is rotated facing towards player after its created (but it wont update if player moves)

Videos

  • void PlayVideoYoutube360(string id)
    • shows sphere and plays youtube 360 video on it (can use in any mode)
    • id is youtube video_id
  • void PlayVideoYoutube2D(string id)
    • shows quad plane and plays 2D video on it (can use in any mode)
    • id is youtube video_id
  • void PlayLocalVideo360(string filename)
    • shows sphere and plays 360 video on it (can use in any mode)
    • video should be in sdcard, at binoo folder: "This PC\Galaxy S4\Card\binoo"
  • void PlayLocalVideo2D(string filename)
    • shows quad plane and plays 2D video on it (can use in any mode)
    • video should be in sdcard, at binoo folder: "This PC\Galaxy S4\Card\binoo"
  • void HideVideoPlayers()
    • hides and stops video players
  • bool VideoExists(string url)
    • Checks if locally download video exists
    • TODO: to be renamed..
  • bool VideoExistsSDCard(string filePath)
    • Checks if video file exists on SDCard *android
    • on editor its: 'd:/data/binoo/' *to be changed..
  • void SeekVideoTo(int timems)
    • rewinds to time in current video player
  • int VideoLength()
    • returns current video duration
    • returns -1 if no active video
  • int VideoSeekPosition()
    • returns current video seek position
    • returns -1 if no active video

Photospheres

  • void PhotoSphere_ClearAllObjects()
    • removes created objects from the current photospheres, including portals, buttons and all
  • string PhotoSphere_GetCurrentRoomID()
    • returns current room localid
  • void PhotoSphere_Goto(string id)
    • go to room with this localid
  • void PhotoSphere_ShowPortals()
    • shows portals (if were hidden)
  • void PhotoSphere_HidePortals()
    • hides portals (if were visible)
  • void PhotoSphere_SetPointer(float u, float v)
    • sets pointer in sphere uv coordinate (so target arrow is then visible too)
  • Vector2 PhotoSphere_GetUVCoordinateForObject(string target)
    • returns uv coordinate for object (raycasted from center of sphere to against sphere)
    • returns -1,-1 if invalid
  • void PhotoSphere_SetPointerToObject(string target)
    • sets pointer to object (using the GetUVCoordinateForObject())
  • void PhotoSphere_HideSpheres()
    • hides photospheres
  • void PhotoSphere_ShowSpheres()
    • shows photospheres

Sending Data To Server

  • void ServerLog(string msg)
    • sends data to logging server, commandserver appends unique user id to the message

Debugging

  • void Log(string msg)
    • prints message into debug log (not visible to user yet)
  • void DebugMode(bool state)
    • state = true, enable debugging console
    • user need to click small button at top left to show/hide debug log window

Audio & Sounds

  • void PlaySynth(string soundString)
    • play procedural audio effects using https://github.com/zeh/usfxr
    • example soundStrings:
      • pickup coin "0,.5,,.0763,.4372,.2188,.3,.5305,,,,,,,,,.5,.6701,,,,,,,,1,,,,,,"
      • laser "0,.5,,.111,.1587,.3237,.3,.6699,.2,-.3305,,,,,,,,,,,.7683,-.5274,,,,1,,,.2155,,,"
      • explosion "3,.5,,.1525,.7683,.3475,.3,.6844,,-.3436,,,,,,,.1537,.6979,,,,,,,,1,,,,,,"
      • blip "0,.5,,.1526,,.1299,.3,.581,,,,,,,,,,,,,.3828,,,,,1,,,.1,,,"
  • void PlaySound(string soundName)
    • plays sound from built-in library
  • void StopAllSounds()
    • stops currently playing sound clips (including AUDIO command sound loaded from url)

Saving / Loading local data

  • void SaveString(string key, string data)
  • void LoadString(string key)
    • load string from unity PlayerPrefs
  • void SaveInt(string key, int val)
    • saves into temporary dictionary
    • data is cleared on mode change
  • int? GetInt(string key)
    • queries from temporary dictionary
    • returns null if key doesnt exists
    • data is cleared on mode change
  • bool KeyExists(string key)
    • checks from temporary dictionary
    • data is cleared on mode change
  • void ClearAllKeys()
    • clears temporary dictionary
  • void RemoveInt(string key)
    • removes key from temporary dictionary

Working with Textures

  • void CreateTexture(string id, int width, int height)
    • creates bitmap texture with given widht/height
    • use id to access it later
    • textures are stored in scene gameobject (so if mode changes, or you call ClearObjects(), also textures are destroyed)
  • void ClearTexture(string target, int r, int g, int b)
    • clears texture with given color
  • void AssignTexture(string target, string id)
    • assign texture to target gameobject material
  • AssignLibraryTexture(string target, string textureName)
    • assigns texture from library, list: link missing
  • void SetPixel(string id, int x, int y, int r, int g, int b)
    • draw pixel to texture
  • string GetPixel(string id, int x, int y)
    • get pixel color from texture
    • result string is in format: r,g,b,a

Multiplayer

  • void ShowOtherPlayers()
    • draw other players (their avatars), if any are connected
    • note: in photosphere, all players are in 0,0,0 position, so they wont be visible unless moving
  • void HideOtherPlayers()
    • hide other players (their avatars)
  • float GetMultiplayerUpdateSpeed()
    • Default update value is 15 secs
  • void SetMultiplayerUpdateSpeed(float delay)
    • Set update speed (clamped to 0.16f - 9999f)
    • Note: low values might cause heavy traffic on the server with many players online (and there is no automatic way to restart server if it crashes)

Notifications

  • void ShowMessage(string message)
    • displays message on screen
    • Same as doing b:SendCommand("MESSAGE|You Win!")
  • void ShowStaticMessage(string msg)
    • displays static message on screen bottom
  • void HideStaticMessage()
    • hides static message on screen bottom

FlowFields

  • void CreateFlowField(string id, int arraySize, float worldSize)
    • Creates flowfield particle array, pivot is in the middle of the gameobject
    • id is name of the created gameobject
    • int 3D array size (value of 2 would create 222 array)
    • float worldSize: gameobject width/height/depth in unity world units (meters) *not current in use yet
  • void SetFlowFieldCellLength(string id, int nx, int ny, int nz, float length)
    • set single array cell arrow length
  • void SetFlowFieldCellLengths(string id, float length)
    • set all arrow lengths
  • void SetFlowFieldCellColor(string id, int nx, int ny, int nz, int r, int g, int b, int a = 255)
    • set single array cell arrow color
  • void SetFlowFieldCellColors(string id, int r, int g, int b, int a = 255)
    • set all arrow colors
  • void SetFlowFieldCellRotation(string id, int nx, int ny, int nz, float ax, float ay, float az)
    • set single array cell arrow rotation angle (in euler angles)
  • void SetFlowFieldCellRotations(string id, float ax, float ay, float az)
    • set all arrow rotation angles (in euler angles)
  • void SetFlowFieldCellsTowards(string id, string target, bool invert = false)
    • set all arrow directions towards target object
    • invert can be used to flip arrow directions, by default its set to false
  • void SetFlowFieldLengthsFromDistance(string id, string target, float scale, bool invert = false)
    • set all arrow lengths based on distance to target object
    • invert can be used to flip arrow length, by default its set to false
  • void SetFlowFieldColorsFromDistance(string id, string target, int[] startColor, int[] endColor)
    • set all arrow colors based on distance to target object (interpolate color from startcolor to endcolor based on min-max distances)
  • void SetCellColorFromDistanceToObject(string id, string target, int x, int y, int z, int[] startColor, int[] endColor)
    • sets single cell color from distance to object
  • void SetFlowFieldCellRotationTowards(string id, string target, int x, int y, int z, bool invert = false)
    • sets single cell color from distance to object

Terrain

  • void CreateTerrain(string id, int size, float x = 0, float y = 0, float z = 0, int terrainMaxHeight = 300, int heightmapResolution = 512, int baseMapResolution = 512, int detailResolution = 512, int resolutionPerPath = 8)
    • creates terrain object, with default grass texture
    • size is world size in meters, default position is at 0,0,0 (pivot at the bottom left corner of the terrain)
    • other parameters are optional (resolutions should be kept low <1024 on mobile)
  • float GetTerrainWorldHeight(string id, float x, float z)
    • Gets world Y position from terrain in given world x, z coordinate
  • void DropObjectToTerrain(string target, string terrainid, float x, float z, bool align = true)
    • Moves, drops and aligns object to terrain normal in world x, z position
    • Optional param to align to surface normal
  • void SetTerrainHeightmapFromPerlinNoise(string id, float noiseScale, float heightScale, float noiseOffsetX = 0, float noiseOffsetZ = 0)
    • Sets terrainheightmap using perlinnoise
    • try low noiseScale values, like 0.007
    • heightscale is value between 0-1. 1 means full terrainMaxHeight
  • void SetTerrainHeightmap(string id, string url, float heightScale = 1, bool invert = false)
    • loads grayscale heightmap and assigns to terrain
    • after loading and processing, WaitForMe bool is set to false
  • void SetTerrainTextureFromLibrary(string id, string libraryTexture)
    • assign texture from library to terrain
    • Available library textures: "asphalt,bark_black_pine,base_wood,blue_plastic,ceramic,church_tiles,cobblestone,concrete_tiles,fabric_suit_vintage,flooring_board,forest_ground,grass,ground_beach,ground_moss,ground_mud,hexagon_path,macro_hull,marble,metalplate,metropolian_street,moss,paving_stone,sand1,sand2,stylised_brick,stylised_ice,stylised_rock,wood_planks"

Player

  • void TogglePlayerMovement(bool toggle)
    • enable player movement (as in terrain level)
  • Vector3 GetPlayerPosition()
    • returns (this) player position
    • result string is in format: x,y,z
  • void SetPlayerPosition(float x, float y, float z)
    • sets players position
  • void TweenMovePlayer(float x, float y, float z, float duration)
    • animates player position movement

Math

  • float GetDistance(float sx, float sy, float sz, float tx, float ty, float tz)
    • returns distance of 2 points (same as Vector3.Distance() in Unity)

Common Errors

  • "ScriptRuntimeException: attempt to call a nil value", maybe you missed "b:" in front of the method? or "math." in front of "random()"
Clone this wiki locally