Wild Pockets API

Classes:

class AccessControl

Undocumented class.

Member functions:

AccessControl.setOwnerPrivate(filename, private)

Sets the "owner-private" flag on a resource. A resource that is marked as owner-private may only be loaded from a scene owned by the same user as the resource. A scene that is marked is owner-private may only be loaded in the builder by the user that owns it.

- filename: (string) Filename on which to change access.
- private: (boolean) True to enable the owner-private access restriction;
False to disable.


>

class Animation

Commands to bend an object, making it sway, jiggle, or dance. Animations are loaded from resources and can be played on any object with a model containing bones. The animation will move the bones, moving the object.

Member functions:

time = Animation:getEndTime()

- time: (number) Time, in seconds

Gets the end time of the animation, i.e. the last time at which the animation moves any bones.


path = Animation:getPath(boneName)

- path: (Path) The path that moves the specified bone
- boneName: (string) The name of the bone that will be moved by the path

Retrieves a path from the animation by specifying the name of the bone moved by the path.


names = Animation:getPathNames()

- names: (array) An array of name strings

Retrieves all of the path names moved by this animation.


time = Animation:getStartTime()

- time: (number) Time, in seconds

Gets the earliest time for the animation, i.e. the earliest time value at which the animation will move any bones.


animation = Animation.load(filename)

- animation: (Animation) The animation resource
- filename: (string) The filename of the animation resource to load

Loads an animation resource with a specified filename


>

class Camera

Manages the scene camera, which is the player's view into the scene. Camera commands allow for the camera to be positioned and targeted, and also allow for more complicated behaviors like following a targed object.

Member functions:

Camera.attachObject(obj,offset)

- obj: (SceneObject) The object to attach to
- offset: (vector) The vector in world space to offset the camera from looking straight at the object
(usefull for 3rd person)

Attaches an object to the camera. In 1st and 3rd person mode this is the object that the camera follows.

note: Camera.attachObject(nil) will detatch any object from the camera.


Camera.beginRotate(sensitivity)

Pushes a keymap that turns mouse movement into camera rotation. The keymap is the following:

* fpskeymap = EventMap.new()
* EventMap.setEvent(fpskeymap, "keyPress-scrollWheel",function(d) Camera.zoomIn(d/100) end)
* EventMap.setEvent(fpskeymap, "keyPress-rightMouse",function() Camera.beginRotate(150) end)
* EventMap.setEvent(fpskeymap, "keyRelease-rightMouse",function() Camera.endRotate() end)
* EventHandler.push(fpskeymap)


Camera.detachObject()

Detaches the current attached object from the camera.

THIS FUNCTION WAS DEPRECATED IN V1.5 please use Camera.attachObject(nil)


Camera.endRotate()

This should be called after the rotation map is pushed via beginRotate. It pops the rotation EventMap.


Camera.focusOnObject(obj)

- obj: (SceneObject) The object to focus on

Focuses the camera on an object. In 1st person or 3rd person mode the camera lines itself up with the attached object and the new focused object. In sky mode the camera looks at the new focused object and will rotate about it.


Camera.follow(obj,distance,heading,pitch)

- obj: (SceneObject) The object for the camera to follow
- distance: (Number) The distance at which the camera should follow the object. Can be a number or nil.
- heading: (Number) The heading that the camera should maintain. Can be a number (degrees) or nil.
- pitch: (Number) The pitch that the camera should maintain. Can be a number (degrees) or nil.

Switches the camera to 3rd person mode and attaches it to the object specified. The distance that the camera follows can be specified as well as the ideal heading and pitch. Leaving the distance, heading or pitch as nil will let the camera freely change that aspect.


offset = Camera.getAttachOffset()

- offset: (Vector) the offset from the object where the camera is

Gets the offset of the camera from the object it is attached to


facing = Camera.getBackwardVector()

Returns a unit vector in the opposite direction the camera is facing (i.e. the unit vector from the eye to the focus)


distance = Camera.getDistance()

Returns the distance (meters) between the camera eye and the camera focus.


up = Camera.getDownVector()

Returns a unit vector in the direction that is "down" for the camera (i.e. moving in this direction moves an object vertically on the screen)


location = Camera.getExactEye()

Gets the exact position of the current camera's eye, regardless of the camera's current motion.


location = Camera.getExactFocus()

Gets a coordinate that is currently centered in the camera's frame, regardless of the camera's current motion.


Camera.getExactRotation()

Returns the rotation of the camera.


location = Camera.getEye()

Gets the location at which the camera's eye is targeted. This may not be the current eye location if the camera is in motion.


location = Camera.getFocus()

Gets the coordinates the camera is currently targeting to center in the frame. The coordinates may not be currently centered in the frame if the camera is in motion.


amount = Camera.getFollowDistance()

- amount: (Number) The distance that the camera should follow behind it's attached object. Could be nil if not set.

Gets the distance that the camera tries to maintain away from the attached object.


heading = Camera.getFollowHeading()

- heading: (Number) The heading to maintain. This could return nil if not set.

Gets the heading that the camera should maintain relative to global coordinates.


pitch = Camera.getFollowPitch()

- pitch: (Number) The optimal pitch for the camera. This can return nil if not set.

Returns the optimal pitch for the camera to maintain.


Camera:getForwardRay( ? )

Undocumented method.


facing = Camera.getForwardVector()

Returns a unit vector in the direction the camera is facing (i.e. the unit vector from the eye to the focus)


heading = Camera.getHeading()

- heading: (Number) heading in degrees, as an angle from the negative X-axis

Returns the camera heading as an angle(degrees) from the negative X-axis.


Camera.getHeadingVector(rotation)

- rotation: (Number) The amount of rotation to apply to this vector clockwise in degrees - may be nil

Returns a vector that points in the direction of the camera in the XY plane. The angle passed will rotate this vector clockwise around the Z axis by that angle.


right = Camera.getLeftVector()

Returns a unit vector in the direction that to the "left" for the camera (i.e. moving in this direction moves an object horizontally on the screen)


minDistance, maxDistance = Camera.getMinMaxDistance()

- minDistance: (Number) Minimum distance (meters) allowed between the camera and the object
- maxDistance: (Number) Maximum distance (meters) allowed between the camera and the object

Gets the minimum and maximum follow distance. When following an object, the camera will not get further or closer than these limits.


minHeading, maxHeading = Camera.getMinMaxHeading()

- minHeading: (Number) Angle (degrees), low counterclockwise boundary on heading
- maxHeading: (Number) Angle (degrees), high counterclockwise boundary on heading

Gets the minimum / maximum limits on heading while following an object. The limits are angles (degrees) from the negative X-axis.


minPitch, maxPitch = Camera.getMinMaxPitch()

- minPitch: (Number) The minimum pitch (degrees), the furthest up the camera will tilt
- maxPitch: (Number) The maximum pitch (degrees), the furthest down the camera will tilt

Gets the minimum and maximum limits on the camera pitch while following an object. When following an object, the camera will tilt outside of these limits.


mode = Camera.getMode()

- mode: (string) the current mode of the camera ('1st', '3rd', 'Sky')

The camera can switch between 1st, 3rd and Sky mode. 1st mode will lock the camera to the object. 3rd will have the camera follow an object . Sky will have the camera rotate around a point or object.

'1st' mode does not currently work.


pitch = Camera.getPitch()

Retrieves the pitch expressed as an angle (degrees) relative to the XY-plane. 0 is level, while positive values are downward pitch and negative values are upward pitch.


right = Camera.getRightRay()

Returns a unit vector in the direction that to the "right" for the camera (i.e. moving in this direction moves an object horizontally on the screen)

DEPRECATED IN V1.5

please use Camera.getRightVector()


right = Camera.getRightVector()

Returns a unit vector in the direction that to the "right" for the camera (i.e. moving in this direction moves an object horizontally on the screen)


speed = Camera.getSpeed()

- speed: (Number) elasticity constant, between 0 and 1 inclusive

Gets the camera elasticity. Each frame, the camera moves this fraction of the distance towards its eye and focus positions. Setting this value closer to 1 makes the camera move faster.


up = Camera.getUpRay()

Returns a unit vector in the direction that is "up" for the camera (i.e. moving in this direction moves an object vertically on the screen)

DEPRECATED IN V1.5

please use Camera.getUpVector()


up = Camera.getUpVector()

Returns a unit vector in the direction that is "up" for the camera (i.e. moving in this direction moves an object vertically on the screen)


Camera.hold(object,offset,rotation)

- object: (SceneObject) The object to lock to the cameras frame of reference.
- offset: (Vector) The position offset to hold the object at.
- rotation: (Rotation) The rotation to keep the object at.

Will basically "glue" an object to the camera. The object will move with the camera and rotate with the camera. For example an offset of vec(0,10,0) will hold the object directly in front of the camera 10 units forward. To stop holding the object call Camera.release().


Camera.moveBackward(amount)

- amount: (Number) The distance to move the camera backwards

Moves the camera backwards in Sky mode.


Camera.moveDown(amount)

- amount: (Number) The distance to move the camera down

Moves the camera down in sky mode.


Camera.moveForward(amount)

- amount: (Number) The distance to move the camera forward

Moves the camera forward in Sky mode


Camera.moveLeft(amount)

- amount: (Number) The distance to move the camera left

Moves the camera left in Sky mode.


Camera.moveRight(amount)

- amount: (Number) The distance to move the camera right

Moves the camera right in Sky mode.


Camera.moveUp(amount)

- amount: (Number) The distance to move the camera up

Moves the camera up in Sky mode.


projectedVector = Camera.project(relativeVector)

- relativeVector: (Vector) A displacement vector in camera space
- projectedVector: (Vector) the displacement vector in world space

Transforms a vector from camera space to world space. For example, projecting the vector (3,0,0) will yield a vector that translates an object horizontally in the camera's view by three units.


Camera.release(object)

- object: (SceneObject) The object to lock to the cameras frame of reference

Will stop keeping an object in the cameras frame of reference. This is used to stop a Camera.hold().


Camera.rotateDown(angle)

Pitches the camera up the specified number of degrees while keeping the focus in the center of the frame.


Camera.rotateLeft(amount)

Rotates the camera left the specified number of degrees


Camera.rotateRight(amount)

Rotates the camera right the specified number of degrees


Camera.rotateUp(angle)

Pitches the camera upward the specified number of degrees while keeping the focus in the center of the frame.


Camera.setAngle(distance,heading, pitch)

- distance: (Number) Distance (meters) from the focus to the eye
- heading: (Number) Angle (degrees) counterclockwise from negative X-axis
- pitch: (Number) angle(degrees) between camera and XY-plane. Zero is level, negative is upward pitch

Shifts the camera's orientation to attain a specific distance, heading, and pitch relative to the camera's focus.


Camera.setAttachOffset(offset)

- offset: (Vector) The offset from the object where the camera should be.

Sets the offset of the camera from the object it is attached to.


Camera.setCallback(moveCallback)

- moveCallback: (function ()) The callback to be called on each camera move

Specifies a function to be called when the camera is moved.


Camera.setDistance(amount)

Sets the distance between the cameras focus and eye


Camera.setExactEye(location)

Sets the camera's eye immediately, jumping to the specified coordinates.


Camera.setExactFocus(location)

Immediately centers a location in the camera's frame, jumping the camera's orientation to face the coordinates.


Camera.setEye(location)

Specifies a location to place the camera's eye. The camera will pan and zoom to reach that location.


Camera.setFocus(location)

Specifies a location to place the camera's focus. The camera will pan to look at that location.


Camera.setFollowDistance(amount)

- amount: (Number) The distance that the camera should follow. Can be a number or nil.

Sets the distance that the camera tries to maintain away from the attached object. Setting this to nil will allow the camera to choose its own distance.


Camera.setFollowHeading(heading)

- heading: (Number) The heading to maintain. This can be a number(degrees) or nil.

Sets the heading that the camera should maintain relative to global coordinates. This is useful for keeping the camera facing a fixed direction regardless of the orientation of the SceneObject being followed. Setting this to nil will allow the camera to swivel around the object.


Camera.setFollowPitch(pitch)

- pitch: (Number) The optimal pitch for the camera. This can be a number(degrees) or nil.

Sets the optimal pitch for the camera to maintain. If this is set to nil, the camera will choose its own pitch.


Camera.setForwardVector(facing)

facing - (Vector) the direction to face the camera.

Keeping the camera position the same, setForwardVector rotates the camera to face the direction of the vector: facing


Camera.setHeading(amount)

Sets the heading of the cameras eye from its focus


Camera.setHeadingVector(facing)

heading - (Vector) the direction to face the camera.

Similar to Camera.setForwardVector but does not interfere with the pitch of the camera.


Camera.setMinMaxDistance(minDistance, maxDistance)

- minDistance: (Number) Minimum distance (meters) allowed between the camera and the object
- maxDistance: (Number) Maximum distance (meters) allowed between the camera and the object

Sets the minimum and maximum follow distance. When following an object, the camera will not get further or closer than these limits.


Camera.setMinMaxHeading(minHeading, maxHeading)

- minHeading: (Number) Angle (degrees), low counterclockwise boundary on heading
- maxHeading: (Number) Angle (degrees), high counterclockwise boundary on heading

Sets the minimum / maximum limits on heading while following an object. The limits are angles (degrees) from the negative X-axis.


Camera.setMinMaxPitch(minPitch, maxPitch)

- minPitch: (Number) The minimum pitch (degrees), the furthest up the camera will tilt
- maxPitch: (Number) The maximum pitch (degrees), the furthest down the camera will tilt

Sets the minimum and maximum limits on the camera pitch while following an object. When following an object, the camera will tilt outside of these limits.


Camera.setMode(mode)

- mode: (string) Sets the mode ('1st', '3rd', 'Sky')

The camera can switch between 1st, 3rd and Sky mode. 1st mode will lock the camera to the object. 3rd will have the camera follow an object . Sky will have the camera rotate around a point or object.

'1st' mode does not currently work.


Camera.setPitch(amount)

Sets the pitch of the cameras eye from its focus


Camera.setSpeed(speed)

- speed: (Number) elasticity constant, between 0 and 1 inclusive

Sets the camera elasticity. Each frame, the camera moves this fraction of the distance towards its eye and focus positions. Setting this value closer to 1 makes the camera move faster.


Camera.stopFollow()

This is just a shortcut function to Camera.detachObject() and will stop the camera from following the attach object.

DEPRECATED IN V1.5

please use Camera.follow(nil) to stop following an object.


Camera.unFocus()

Stops focusing on the current focus object.

DEPRECATED IN V1.5

please use Camera.setFocus(nil) to unfocus the camera


Camera.zoomIn(amount)

- amount: (number) The distance to zoom the camera in

Brings the camera closer to the focus.


Camera.zoomOut(amount)

- amount: (Number) The distance to zoom the camera out

Moves the camera farther from the focus.


Camera.zoomTo(distance)

- distance: (number) The distance between the eye and focus.

Sets the camera to be a certain distance from the focus

DEPRECATED IN V1.5

please use Camera.setDistance(distance)


>

class CameraBoom

The CameraBoom is the most basic camera object. It contains a Transform, which determines the position of the camera. As such, it can be manipulated using most any of the methods of class Transform.

It is unusual for the application programmer to manipulate the CameraBoom directly. Instead, the application programmer usually uses a higher-level class, Camera, which controls the CameraBoom. To manipulate the CameraBoom directly, you will need to first disable class Camera.

To obtain the CameraBoom, use SceneManager.getCamera().

Member functions:

distance = CameraBoom:distance(point)

The distance operator can compute the distance between any two objects: they can be scene objects, cameras, transforms, or just points specified as vectors.


r,f,u,l,b,d = CameraBoom:getAxes()

Get the object's local direction vectors. Returns six values:

* positive x axis (the 'right' vector)
* positive y axis (the 'forward' vector)
* positive z axis (the 'up' vector)
* negative x axis (the 'left' vector)
* negative y axis (the 'backward' vector)
* negative z axis (the 'down' vector)


vec = CameraBoom:getBackwardVector()

Returns a vector that points backward out of the rear of the character's head. The backward vector is equal to the character's local negative Y-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


direction = CameraBoom:getCompassDirection([frame_of_reference])

Get the compass direction in which the object is facing. The return value is a string, one of: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE If the object's orientation is not exactly in one of these sixteen directions, it will approximate.


vec = CameraBoom:getDownVector()

Returns a vector that points downward out of the bottom the character's feet. The down vector is equal to the character's local negative Z-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


vec = CameraBoom:getForwardVector()

Returns a vector that points forward out of the tip of the character's nose. The forward vector is equal to the character's local positive Y-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


fov = CameraBoom:getFov()

Returns the field of view, in degrees.


heading,pitch,roll = CameraBoom:getHPR([frame_of_reference])

Returns the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


heading = CameraBoom:getHeading([frame_of_reference])

Returns the object's heading, where 0 is north, 90 is west, 180 is south, and 270 is east.


vec = CameraBoom:getLeftVector()

Returns a vector that points left out of the character's left shoulder. The left vector is equal to the character's local negative X-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


near,far = CameraBoom:getNearFarPlanes()

Returns the near and far clipping distances.


position = CameraBoom:getPosition([frame_of_reference])

Get the position.


vec = CameraBoom:getRightVector()

Returns a vector that points right out of the character's right shoulder. The right vector is equal to the character's local positive X-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


position = CameraBoom:getRotation([frame_of_reference])

Get the rotation.


position = CameraBoom:getScale()

Get the scale.


sx = CameraBoom:getScaleX()

Returns the X-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


sx,sy,sz = CameraBoom.getScaleXYZ()

Returns the X, Y, Z scale of the object as three values. It is also possible to obtain the scale as a single vector object by calling getScale instead.

DEPRECATED IN V1.5

please use Transform.getScale()


sy = CameraBoom:getScaleY()

Returns the Y-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


sz = CameraBoom:getScaleZ()

Returns the Z-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


transform = CameraBoom:getTransform()

Gets a copy of the camera's transform.


vec = CameraBoom:getUpVector()

Returns a vector that points upward out of the top of the character's head. The up vector is equal to the character's local positive Z-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


X = CameraBoom:getX([frame_of_reference])

Get the X-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


x,y,z = CameraBoom.getXYZ([frame_of_reference])

Returns the X, Y, Z position of the object as three values. It is also possible to obtain the position as a single vector object by calling getPosition instead.

DEPRECATED IN V1.5

please use Transform.getPosition()


Y = CameraBoom:getY([frame_of_reference])

Get the Y-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


Z = CameraBoom:getZ([frame_of_reference])

Get the Z-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


projection = CameraBoom:guiProject(position)

Convert from world coordinates to GUI coordinates. projection is a vector containing the Gui Coordinates x and y, along with the z coordinate coorisponding to the distance from the camera to the object.


CameraBoom:pathToAxis(mode, vector)

Rotates the object to cause one axis of the object to align with the specified vector. Mode is a string, one of the following:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


CameraBoom:pathToAxisAngle(axis, angle)

Rotates an object about an arbitrary (axis) by (angle)


CameraBoom:pathToCompassDirection(direction [, frame_of_reference])

Set the compass direction in which the object is facing. The parameter must be a string, one of the following: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE.


CameraBoom:pathToForwardVector(direction [, up] [, frame_of_reference])

Look in the specified direction. The direction must be a vector. The object is also made upright, insofar as possible subject to the constraint that it be looking in the specified direction. You can specify an optional up-vector.


CameraBoom:pathToHPR(heading, pitch, roll [, frame_of_reference])

Sets the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


CameraBoom:pathToHeading(heading [, frame_of_reference])

Causes the object to face in the given heading, where 0 is north, 90 is west, 180 is south, and 270 is east. In addition, the object is made upright.


CameraBoom:pathToLookAt(otherobject)

Causes this object to look at (point toward) the other object. The other object can be a scene object, a transform, or a point in the form of a vector.


CameraBoom:pathToPosition(x,y,z [, frame_of_reference])

Sets the position. The parameter is either a vector or three numbers.


CameraBoom:pathToRotation(rotation [, frame_of_reference])

Sets the rotation. The parameter is a rotation object, typically constructed using Rotation.new or the like.


CameraBoom:pathToScale(x,y,z)

Sets the scale. The parameter is either a vector or three numbers.


CameraBoom:pathToScaleX(x)

Sets the X-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


CameraBoom:pathToScaleXYZ(x,y,z)

Sets the scale.

DEPRECATED IN V1.5

please use Transform.setScale()


CameraBoom:pathToScaleY(y)

Sets the Y-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


CameraBoom:pathToScaleZ(z)

Sets the Z-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


CameraBoom:pathToTransform(transform [, frame_of_reference])

Sets the entire transform.


CameraBoom:pathToUpright([frame_of_reference])

Causes the object to upright itself - In other words, the object's local Z-axis is aligned with the world's Z-axis. If possible, the object's heading is not lost.


CameraBoom:pathToX(x [, frame_of_reference])

Sets the X-component of the position. It may be more convenient to set all three using setXYZ.


CameraBoom:pathToXYZ(x,y,z [, frame_of_reference])

Sets the position.

DEPRECATED IN V1.5

please use Transform:setPosition()


CameraBoom:pathToY(y [, frame_of_reference])

Sets the Y-component of the position. It may be more convenient to set all three using setXYZ.


CameraBoom:pathToZ(z [, frame_of_reference])

Sets the Z-component of the position. It may be more convenient to set all three using setXYZ.


CameraBoom:rotateAboutAxis(axis, angle)

Rotates an object about an arbitrary (axis) by (angle)


CameraBoom:setAxis(mode, vector)

Rotates the object to cause one axis of the object to align with the specified vector. Mode is a string, one of the following:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


CameraBoom:setCompassDirection(direction [, frame_of_reference])

Set the compass direction in which the object is facing. The parameter must be a string, one of the following: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE.


CameraBoom:setEyeFocus(eye, focus)

Sets the camera transform using the eye/focus method


CameraBoom:setForwardVector(direction [, up] [, frame_of_reference])

Look in the specified direction. The direction must be a vector. The object is also made upright, insofar as possible subject to the constraint that it be looking in the specified direction. You can specify an optional up-vector.


CameraBoom:setFov(fov)

Sets the field of view, in degrees. The default is 45 degrees. The legal range is 1 to 89 degrees. Best results are usually obtained around 30 degrees.


CameraBoom:setHPR(heading, pitch, roll [, frame_of_reference])

Sets the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


CameraBoom:setHeading(heading [, frame_of_reference])

Causes the object to face in the given heading, where 0 is north, 90 is west, 180 is south, and 270 is east. In addition, the object is made upright.


CameraBoom:setLookAt(otherobject)

Causes this object to look at (point toward) the other object. The other object can be a scene object, a transform, or a point in the form of a vector.


CameraBoom:setNearFarPlanes(near, far)

Sets the near and far clipping distances.


CameraBoom:setPosition(x,y,z [, frame_of_reference])

Sets the position. The parameter is either a vector or three numbers.


CameraBoom:setRotation(rotation [, frame_of_reference])

Sets the rotation. The parameter is a rotation object, typically constructed using Rotation.new or the like.


CameraBoom:setScale(x,y,z)

Sets the scale. The parameter is either a vector or three numbers.


CameraBoom:setScaleX(x)

Sets the X-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


CameraBoom:setScaleXYZ(x,y,z)

Sets the scale.

DEPRECATED IN V1.5

please use Transform.setScale()


CameraBoom:setScaleY(y)

Sets the Y-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


CameraBoom:setScaleZ(z)

Sets the Z-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


CameraBoom:setTransform(transform [, frame_of_reference])

Sets the entire transform.


CameraBoom:setUpright([frame_of_reference])

Causes the object to upright itself - In other words, the object's local Z-axis is aligned with the world's Z-axis. If possible, the object's heading is not lost.


CameraBoom:setX(x [, frame_of_reference])

Sets the X-component of the position. It may be more convenient to set all three using setXYZ.


CameraBoom:setXYZ(x,y,z [, frame_of_reference])

Sets the position.

DEPRECATED IN V1.5

please use Transform:setPosition()


CameraBoom:setY(y [, frame_of_reference])

Sets the Y-component of the position. It may be more convenient to set all three using setXYZ.


CameraBoom:setZ(z [, frame_of_reference])

Sets the Z-component of the position. It may be more convenient to set all three using setXYZ.


>

class Class

Undocumented class.

Member functions:

ClassName = Class.new()

Create and return a new Class.

The Class system allows you to define your own classes, which can be instantiated on their own and used as you would in any object-oriented programming language. Additionally, classes can be attached to SceneObjects, giving you a powerful system for assigning behaviors to objects in your scene.

For more information on the Class system, please refer to the Wild Pockets manual.


>

class Collider

Collider is a container for functions that perform collision-based queries on the scene. Currently, that includes casting rays into the scene and asking which objects the rays collide with.

Member functions:

results = Collider.castMouseRay([mode])

This routine is identical to Collider.castRay, except that you do not specify a ray: it uses the mouse ray.


result = Collider:castMouseRayToMousePlane(planepoint)

- planepoint (Vector3D) - A point on the plane perpendicular to the camera

Casts a ray in the scene that will return the any collisions with a plane that is perpendicular to the camera Returns a table of results. result.point will contain the Vector3D of the intersection point.


result = Collider:castMouseRayToPlane(planepoint,planenormal)

- planepoint (Vector3D) - A point on the plane
- planenormal (Vector3D) - A unit vector perpendicular to the plane

Casts a ray in the scene that will return the any collisions with the plane specified Returns a table of results. result.point will contain the Vector3D of the intersection point.


results = Collider.castRay(from, to, [mode])

- from (Vector) - The point in space where the Ray is originating.
- to (Vector) - A point in space to define the direction of the Ray.
- mode (String) - Either 'polygons' or 'solids'... See Below

Casts a ray through the scene, checking for collisions against scene objects. Returns a table describing where the collisions occurred.

The table returned is a structure with three main fields: objects, points, and distances. These are three parallel arrays. For example, to print out all information about the first two intersection points, do this:

* local results = Collider.castRay(p1, p2)
* local objects = results.objects
* local points = results.points
* local distances = results.distances
* print(objects[1], points[1], distances[1])
* print(objects[2], points[2], distances[2])

The arrays are sorted by distance, nearest to farthest. The results table also contains fields 'object', 'point', and 'distance' which specify the first collision.

If the optional parameter 'mode' is specfied, it can be either the string 'polygons' or the string 'solids', indicating whether the ray should be tested against the polygons of the model or the collisions solids.


results = Collider.castRayToPlane(from, to, point, vec)

- from (Vector) - The point in space where the Ray is originating.
- to (Vector) - A point in space to define the direction of the Ray.
- point (Vector) - A point on the plane
- vec (Vector) - A Vector perpendicular to the plane

Casts a ray through the scene, checking for collisions against the plane specified. Returns a table describing where the collisions occurred.

The table returned is a structure with three main fields: objects, points, and distances. These are three parallel arrays. For example, to print out all information about the first two intersection points, do this:

* local results = Collider.castRayToPlane(p1, p2, v1, v2)
* local objects = results.objects
* local points = results.points
* local distances = results.distances
* print(objects[1], points[1], distances[1])
* print(objects[2], points[2], distances[2])

The arrays are sorted by distance, nearest to farthest. The results table also contains fields 'object', 'point', and 'distance' which specify the first collision.


>

class Color

Stores a single color, which is expressed as the four components (red, green, blue, alpha). The values of the components range from 0 to 1.

Member functions:

newColor = Color:__add(otherColor)

Adds two colors. Also will add a color by a scalar. Returns the new color.


newColor = Color:__div(otherColor)

Divides two colors. Also will divide a color by a scalar. Returns the new color.


isEqual = Color:__eq(otherColor)

Determines whether or not the color is equivalent to otherColor, where otherColor is of type color. Returns boolean isEqual, true if the color is equivalent, false otherwise.


newColor = Color:__mul(otherColor)

Multiplies two colors together. Also will multiply a color by a scalar. Returns the new color.


newColor = Color:__sub(otherColor)

Subtracts two colors. Also will subtract a color by a scalar. Returns the new color.


R, G, B, A = Color:get()

Returns the four channels of color information as four numbers ranging from 0 to 1. ( R=red value, G=green value, B=blue value, A=alpha value) DEPRICATED : Use Color.getRGBA() instead.


A = Color:getA()

Returns the alpha channel of color information ranging from 0 to 1.


B = Color:getB()

Returns the blue channel of color information ranging from 0 to 1.


G = Color:getG()

Returns the green channel of color information ranging from 0 to 1.


R = Color:getR()

Returns the red channel of color information ranging from 0 to 1.


R, G, B, A = Color:getRGBA()

Returns the four channels of color information as four numbers ranging from 0 to 1. ( R=red value, G=green value, B=blue value, A=alpha value)


color = Color.new(...)

Creates a new color object. The parameters can be any of the following:
- Option 1. A hexadecimal color string (eg, 'FFE03A').
- Option 2. Three numbers, red, green, blue, in the range 0-1
- Option 3. Four numbers, red, green, blue, alpha, in the range 0-1

Note that there exists a global function 'color', which is shorthand for Color.new


Color:setA(A)

Sets the values of the alpha channel, using numbers ranging from 0 to 1.


Color:setB(B)

Sets the values of the blue channel, using numbers ranging from 0 to 1.


Color:setG(G)

Sets the values of the green channel, using numbers ranging from 0 to 1.


Color:setR(R)

Sets the values of the red channel, using numbers ranging from 0 to 1.


>

class Coroutines

WildPockets allows you to execute a subroutine "in the background." The technical name for such a background job is a coroutine. Coroutines are similar to threads in other programming languages, with one important difference: a coroutine runs exclusively, getting 100% of the CPU and blocking out all other coroutines, until it explicitly sleeps. Because of this, no locking or mutexes are needed: any code that doesn't contain a sleep-command is implicitly atomic. See the manual entry on background jobs for more information.

Whenever WildPockets calls an event handler (or the like), it creates a coroutine to run the handler. Therefore, event handlers can use functions like Coroutines.yield and Coroutines.sleep.

Member functions:

coroutine = Coroutines.create(coroutineFunction)

Creates a coroutine without scheduling it. Returns the handle of the coroutine.

This is not the normal way to create a coroutine. The normal way is to use Coroutine.schedule to create a coroutine and schedule it for execution. This routine is only used when you want to create a coroutine without scheduling it for execution.


Coroutines.kill(coroutine)

The coroutine is marked dead. If any part of the system still has a handle for the coroutine, and attempts to use that handle to resume the coroutine, the attempt will return immediately having no effect.


current = Coroutines.running()

Returns the handle of the currently-executing coroutine.


Coroutines.schedule(fn, arg1, arg2, arg3...)

The engine maintains a ready-coroutines stack: a list of coroutines that need to be executed as soon as possible. Coroutines.schedule adds a coroutine to this stack. The engine processes the stack frequently. The first parameter can be handle of an existing coroutine, or it can be a function, in which case a new coroutine is created to run the function. If you supply a function, you can also supply arguments. Returns the coroutine handle.


status = Coroutines.status(coroutineHandle)

Gets the status of the specified coroutine. For more information, see The Lua manual.


Coroutines.yield()

Used by a coroutine when it wishes to sleep until manually awakened. The coroutine will never wake up again unless you explicitly awaken it using Coroutines.schedule. See also Timer.sleep, which causes a coroutine to sleep for a finite amount of time.


>

class Deque

The word 'Deque' is short for 'double-ended queue.' This is basically an array, except that you can 'push' elements (append to the array) on either end, and 'pop' elements (trim things off the array) at either end. The Deque can also be used as a stack or a queue, it is designed to be efficient to be used in either of these manners.

The Deque is implemented as a circular buffer. It is unnecessary for the lua user to understand how circular buffers work, other than to understand the performance characteristics of the Deque.

Member functions:

flag = Deque:empty()

Returns true if the deque is empty.


val = Deque:get(N)

Returns the Nth element in the deque.


val = Deque:getBack()

Returns the value at the back of the deque.


val = Deque:getFront()

Returns the value at the front of the deque.


deque = Deque.new()

Allocates a deque object.


val = Deque:popBack()

Pops a value from the back of the deque.


val = Deque:popFront()

Pops a value from the front of the deque.


Deque:pushBack(val)

Push a value onto the back of the deque.


Deque:pushFront(val)

Push a value onto the front of the deque.


Deque:set(N, val)

Sets the Nth element in the deque. Cannot create new elements, only modify existing ones.


size = Deque:size()

Returns the number of elements currently in the deque.


>

class EventHandler

Manages the stack of active EventMaps. Handles incoming events and dispatches them to functions by looking up the functions in the EventMaps.

EventMaps are kept in a stack in the order in which they are pushed. When an event is fired, the stack is searched for a handler for the event, starting with the most recently- pushed handler. The first handler found is then triggered to handle the event.

Member functions:

event, arg1, arg2, ... = EventHandler.getCurrentEvent()

Called inside an event handler, returns the name of the current event. Called anywhere else, returns "". Note that if an event handler does a coroutine yield or Timer.sleep, it ceases to classify as an event handler from that point forward. Also returns the event arguments, if any.


hasMap = EventHandler.has(evtmap)

Returns true if the specified event map is on the event handling stack.


flag = EventHandler.keyIsDown(key)

Returns true if the keyboard key or mouse button is down. Key should be a string like "tab", "a", "b", "c", or "leftMouse" as you might find in the corresponding keyPress event.


EventHandler:pop(evtmap)

Pops an EventMap off the event stack.


EventHandler:push(evtmap)

Pushes an EventMap onto the event stack.


EventHandler.synthesize()

When you enter and then exit the debugger, any keys that were being held down prior to entering the debugger are pseudo-released. This involves synthesizing fake keyRelease events.


>

class EventMap

Mechanism for mapping sets of user events (such as keypresses) to sets of functions that handle the events. EventMaps are given to the EventHandler, which uses the maps to decide what functions are called when events occur.

Member functions:

EventMap:clearEvent(name)

Clears an event handler from the map.


evt = EventMap.new()

Returns a new EventMap


EventMap:setEvent(event,function)

- event: (string) The event to listen for
- function: (function) The callback function

Sets a function to fire when an event is received. Key events are preceded with 'keyPress', 'keyRelease' or 'keyDown'. keyPress will fire when a button is depressed. keyRelease will fire when a button is released. keyDown will fire every few milliseconds while the key is depressed. mouseMove will fire when the mouse moves.

The full documentation for event handling, including the list of known events and the list of keys, are contained in the manual.


>

class Gizmo

Note - The Gizmo system is disabled by default for performance purposes. For the Gizmo system to work, you must activate the Gizmo system using Gizmo.setActive(true).

Creates lightweight "gizmo" visual objects that are drawn in the 3D scene. Unlike SceneObjects, Gizmos don't effect each other or the SceneObjects in the scene; they are intended to quickly render simple objects in the 3D view for user interface purposes, like lines connecting two objects or outlines around an object.

Gizmos are created using the Gizmo.create method, which takes in a string denoting the type ("box","sphere",or "line") and a table of property values and yields a gizmo. Gizmos look very much like tables; they have a set of properties that can be queried and set. Modifying a gizmo's properties modifies the visual appearance of the gizmo immediately; for instance, setting the 'position' property of a gizmo to vec(0,0,5) positions the gizmo's center at 0,0,5. In addition to raw values, most gizmo properties can be set to 'active' data types, as follows:

* nil: Setting a property to nil will cause it to use the default value
* function: Setting a property to a function will call that function every frame,
taking the function's return value as the value of the property (Be aware that this means passing in a full function such as "function() getInfo() end" , not just "getInfo()")
* SceneObject: Setting a property to a SceneObject will pull an appropriate value
from the SceneObject for the property. For example, setting the "rotation" property to a SceneObject will set the gizmo's rotation to the result of SceneObject:getRotation. In this way, gizmos can be made to 'track' SceneObjects in a straightforward manner. The properties position, rotation, scale, color, color1, color2, extent, radius, endpoint1, and endpoint2 can be used this way.

The following properties are shared among all gizmos:

- name: (string, default "") A unique name for the gizmo, used by Gizmo.atScreenCoordinates to
determine which gizmo is selected
- position: (Vector, default 0,0,0) The location of the center of the gizmo
- scale: (Vector, default 1,1,1) The scale of the gizmo
- rotation: (Rotation, default identity rotation) The rotation of the gizmo
- color: (Color, default 1,0,0,1) The color of the gizmo
- overlay (Boolean, default true) If true, gizmo is overlayed on top of the scene; otherwise,
the gizmo is inside the scene

Individual gizmos also have properties specific to them:
* box
- extent: (Vector, default 1,1,1) The width, height, and depth of the box

* sphere
- radius: (number, default 1) The radius of the sphere

* line
- endpoint1: (Vector, default 0,0,0) Location of the first endpoint
- endpoint2: (Vector, default 0,0,0) Location of the second endpoint
- color1: (Color) Color of endpoint 1. If nil, the 'color' property is used
- color2: (Color) Color of endpoint 2. If nil, the 'color' property is used

NOTE: Gizmos use ShapeSequences for their rendering, so the use of custom ShapeSequences will interfere with Gizmos. To use custom ShapeSequences, either disable the Gizmo system (using Gizmo.setActive(false)) or attach additional sequences onto the end of the Gizmo ShapeSequence (using Gizmo.addCustomRenderer).

Member functions:

Gizmo.addCustomRenderer(renderer)

- renderer(function): A render function, which takes one ShapeSequence as input

Adds a custom gizmo renderer, which can add additional ShapeSequences each frame. Developers who wish to use ShapeSequences and Gizmos at the same time may use this function to extend the Gizmo's ShapeSequence.


name = Gizmo.atScreenCoordinates(x,y)

- name (string): Name of the gizmo found
- x (number): x-coordinate (in screen pixels) of the search origin
- y (number): y-coordinate (in screen pixels) of the search origin

Searches for a gizmo under the specified x-y coordinate on the screen. Returns the gizmo's name if it exists, or nil if no named gizmo was found under the specified coordinate.


newGizmo = Gizmo.create(gizmoType,options)

- gizmoType (string): Type of gizmo to create. This may be "sphere", "box", or "line"
- options (table): Table of options to configure the gizmo. See the Gizmo class documentation for more information
- newGizmo (Gizmo): The created gizmo

Creates a new gizmo and begins displaying it immediately. You can modify the values in the gizmo table to change how the gizmo is displayed.


Gizmo.hide(gizmo)

Hides the specified gizmo.


Gizmo.hideAll()

Hides all visible gizmos.


Gizmo.removeCustomRenderer(renderer)

- renderer(function): A render function that was previously added with Gizmo.addCustomRenderer.

Removes a custom gizmo renderer so it will not be called every frame.


Gizmo.setActive(flag)

Enables the Gizmo system, which renders 3D shapes in the scene. Gizmos will only be rendered if Gizmo.setActive(true) is called.

Because Gizmos use ShapeSequences for their rendering, Gizmos must be disabled if another ShapeSequence-based system is desired. See Gizmo.addCustomRenderer for more information on extending the Gizmo rendering system.


Gizmo.show(gizmo)

Shows the specified gizmo


>

class Global Functions

This is a list of all the global functions that are not part of any class.

Member functions:

function assert( ? )

Undocumented function.


function color(r,g,b,a)

Creates a new Color instance. This is a shortcut for Color:new


function delete(x)

Deletes an element from the scene. The parameters can be any of the following:
- SceneObject: The object to delete
- Joint: The joint to delete
- instance of a class: Runs the class's destructor


function error( ? )

Undocumented function.


function eventMap()

Creates a new EventMap instance. This is a shortcut for EventMap.new


function getBuildTarget()

Get the build target name of the plugin


function getShaderStatus(...)

- status : (string) The status of the shader engine


Retrieves a plain-text description of the status of the shader engine.


function getShaderWarnings(...)

- warnings : (string) Warnings from shaders


Retrieves a plain-text list of all warnings generated by the shader compiler.


function getVersion([mode])

Get the version of the plugin; pass 'name', 'version', 'build, 'fullversion', or 'family' to get individual components.


function getfenv( ? )

Undocumented function.


function getmetatable( ? )

Undocumented function.


function import( ? )

Undocumented function.


function info(name)

Shows the documentation on a given function or class. Name is the function or class to look up, as a string. To look up a method in a module or class, use the format "Module.method"


function ipairs( ? )

Undocumented function.


function loadShaders(vertexShader,fragmentShader)

- vertexShader: (string) A vertex shader program, written in GLS
- fragmentShader: (string) A fragment shader program, written in GLS

Replaces all shaders on objects in the scene with the given shader program. To use the engine's built-in shaders, specify the empty string for both arguments


function loadstring(sourcecode,chunkName)

- sourcecode: (string) Lua code to compile into a function. The resulting
function is in the form 'function () [sourcecode] end'
- chunkName: (string) The name of the function, used in tracebacks if an
error occurs.

Returns: A function generated from the compiled source code.

Parses a string as Lua source code and returns a function from the string. The resulting function has an empty environment; use setfenv to specify an environment for the function. For example, setfenv(chunk,getfenv()) will set the function's environment to the current environment.


function next( ? )

Undocumented function.


function pairs( ? )

Undocumented function.


function pcall( ? )

Undocumented function.


function print( ? )

Undocumented function.


function rawget( ? )

Undocumented function.


function select(object)

This is only relevant in the builder. Selects an object in the scene, deselecting other objects.


function selected()

Returns the last selected object in the window


function setfenv( ? )

Undocumented function.


function setmetatable( ? )

Undocumented function.


function sourceForShader(...)

- vertexSource: (string) Source code for vertex shader
- fragmentSource: (string) Source code for fragment shader
- color: (Color) Color of the object
- diffuseTexture: (bool) If true, the shader should handle a diffuse texture
- normalMapping: (bool) If true, the shader should handle a normal / gloss map

Yields the source code for the shader that would be generated to handle the specified render parameters


function tonumber( ? )

Undocumented function.


function tostring( ? )

Undocumented function.


function type( ? )

Undocumented function.


function underMouse()

Returns the object that is under the mouse

DEPRECATED IN V1.5

please use Mouse.under()


function unpack( ? )

Undocumented function.


function vec( ? )

Undocumented function.


function warning( ? )

Undocumented function.


function xpcall( ? )

Undocumented function.


>

class GuiManager

The GUI is implemented through classes GuiManager and Rect.

The GUI design is extremely unconventional. It will not be possible to build GUIs until you have read the manual chapter on GUI creation.

Member functions:

GuiManager.call(name, func, level)

Asks the GuiManager to call the specified function every frame. The function you provide should draw some elements on the screen using Rect:drawPict and/or Rect:drawText.

You can specify a level, things with a higher level number will always be drawn on top of lower level numbers.

Specifying levels is know to be slightly buggy.


GuiManager.currentMouse()

Return the ID of the region that has the mouse.


GuiManager.dispatchEvent(eventName, ...)

Dispatches an event such as keyPress-leftMouse. Returns true if the event was handled, or false if the event still needs to be pushed down the EventMap stack.


rect = GuiManager.find(x, y)

- rect: (Rect) The region containing the point
- x: (number) X coordinate of the point, in pixels
- y: (number) Y coordinate of the point, in pixels

Retrieves the region in the current GUI that contains the specified point. If no user-specified regions contain the point, returns nil.


text = GuiManager.getClipboardText()

Returns the text on the system clipboard. For security reasons, this function can only be used inside a GUI event handler for "keyPress-v" with the control-key down. Without this security restriction, it would be possible for any game you run to simply monitor your clipboard.


GuiManager.getFocus()

Returns the Id of the rect that currently has keyboard focus


rect = GuiManager.getScreen()

- rect: (Rect) The screen rectangle

Returns the Rect representing the whole screen.


GuiManager.leftClickCounter()

Returns the number of times that the left mouse button has been clicked in rapid succession. On a single-click returns 1, on a double-click returns 2, and so forth.


GuiManager.leftClickInProgress()

Returns non-nil if a left-click is in progress. A left-click is when the user presses and releases the left mouse button in a single gui region, without leaving that region. If the pointer leaves the region, the left click is aborted. Returns the ID of the region. See also leftMouseIsDown, a less-strict test.


GuiManager.leftMouseIsDown()

Returns true if the left mouse button is down *and* the pointer was inside the gui at the time the left-mouse-down occurred. Mouse downs outside the gui do NOT set this flag.


GuiManager.raise(name)

If the GuiManager is calling multiple repaint functions, it must choose some order in which to call them. The 'raise' function moves a given repaint function to the end of the list. The thing at the end of the list is painted last, making it visually the thing on top.


GuiManager.rightClickCounter()

Returns the number of times that the right mouse button has been clicked in rapid succession. On a single-click returns 1, on a double-click returns 2, and so forth.


GuiManager.rightClickInProgress()

Returns non-nil if a right-click is in progress. A right-click is when the user presses and releases the right mouse button in a single gui region, without leaving that region. If the pointer leaves the region, the right click is aborted. Returns the ID of the region. See also rightMouseIsDown, a less-strict test.


GuiManager.rightMouseIsDown()

Returns true if the right mouse button is down *and* the pointer was inside the gui at the time the right-mouse-down occurred. Mouse downs outside the gui do NOT set this flag.


GuiManager.setClipboardText(text)

Sets the text on the system clipboard. For security reasons, this function can only be used inside a GUI event handler for "keyPress-c" or "keyPress-x" with the control-key down.. Without this security restriction, it would be possible for any game you run to erase your clipboard or put dangerous content onto your clipboard.


GuiManager.setFocus(targetId)

Attempts to direct the keyboard focus to the specified rectangle. Searches for any subrectangle that has used enableFocus. Of these, it selects the most-recently-used, or if none has been used, activates the first, sequentially.


GuiManager.skinResources(skin)

Returns a list of all the resources used in the specified skin.


GuiManager.standardSkin()

Returns the standard skin. A skin is a collection of drawPict/drawText styles. See the manual entry on styles and skins.


GuiManager.stop(name)

Asks the GuiManager to stop calling the specified function.


rect,chrect = GuiManager.textBoundingBoxes(pos,options,text,charindex)

Measures the size of a block of rendered text. Doesn't actually render the text, just measures how big it will be when rendered. The return values are the bounding box of the block of text as a whole, and also the bounding box of a single selected character.

When text is laid out, the actual height of the glyphs is ignored. Otherwise, the presence of unusually tall characters on some lines would force the line spacing to be irregular. Instead, the height of the glyph is taken, by definition, to be the pixel size of the text, plus the line gap above, plus the line gap below.

If the font isn't downloaded yet, returns empty rectangles.


pos = GuiManager.textMousePosition(pos,options,text,mx,my)

Determines the following: if you were to render the given block of text, where in the text would the mouse be? Returns the character index to which the mouse would point. The character index is returned as a floating-point value. The fractional part indicates how far, left-to-right, the mouse is within that character. Ie, 10.01 would mean the mouse is pointing at the left edge of the tenth character, and 10.99 would mean the mouse is pointing at the right edge of the 10th character.


>

class GuiStyle

The function Rect:drawPict accepts a table of configuration parameters that control what is drawn. Parsing such a table every frame can be expensive, so it is possible to precompile the table into a GuiStyle object. The drawing functions like Rect:drawPict accept either a raw table or a GuiStyle object.

Member functions:

style = GuiStyle.new({ options })

Creates a new gui style object. The table might contain these values:

- font: (string) file path of a font resource
- color: (color) a color specification
- size: (number) Height of a line of text, in pixels
- linegap: (number) Number of pixels between each line of text
- valign: (Vertical alignment of text) Vertical alignment of text. Default: top
- halign: (string) Horizontal alignment of text. Default: left
- wrap: (boolean) If true, text should wrap at border
- bbcursor: (boolean) If true, bounding box will include room for cursor
- behind: (boolean) If true, this GUI element is drawn behind the scene
- highlightcolor: (color) color of the highlight
- pointcolor: (color) color of the insertion-point
- foreground: (string) filename of a Texture to use as a foreground image
- background: (string) Filename of a Texture to use as a background image
- stretch: (boolean) If true, stretch the image to fill the border, otherwise tile the image
- behind: (boolean) If true, the image is rendered behind the scene.


tab = GuiStyle.tab(guistyle)

Returns the table from which the GuiStyle was originally built. This should be invoked as GuiStyle.tab(guistyle), not guistyle:tab(), in case somebody passes you a style that's already a table.


>

class Joint

Specifies a joint, which connects two SceneObjects in a scene together or one scene object to an absolute coordinate in world space.

Joints place constraints on objects, causing them to remain aligned relative to each other or to a point of reference.

Types of joints:
- Ball: Connects two objects together such that they may rotate freely around
an axis of rotation, but each maintains its relative distance from the axis of rotation. Ball joints do not support minimum and maximum angles.
- Anchor: Fixes an two objects together, 'pinning' them. These objects can't
rotate or move away from each other.
- Hinge: Like a ball joint, but additionally prevents rotation around all but
one axis. Minimum and maximum angles may be set on a hinge joint.
- Universal: Like a ball joint, but additionally prevents rotation around exactly
one axis. Minimum and maximum angles may be set on a universal joint.

Member functions:

Joint:__eq()

Equality test


force = Joint:getBreakForce()

Retrieves the force at which the joint will break. If 0, joint is unbreakable.


enabled = Joint:getEnabled()

Returns if a joint is enabled or disabled


Joint:getMax()

Returns the maximum angle/position of the joint, or nil if no limit is set

DEPRECATED IN V1.5

please use Joint:getRange()


Joint:getMin()

Returns the minimum angle/position of the joint, or nil if no limit is set

DEPRECATED IN V1.5

please use Joint:getRange()


object1 = Joint:getObject1()

Returns the first attached object or nil if the joint is affixed to an absolute coordinate in space


object2 = Joint:getObject2()

Returns the second attached object or nil if the joint is affixed to an absolute coordinate in space.


position = Joint:getPosition()

position: (Vector) coordinates of the pivot of the joint

Returns the joint's pivot position


minRange,maxRange = Joint:getRange()

Returns the minimum and maximum angle/position of the joint, or nil if no limit is set


rotation = Joint:getRotation()

- rotation: (Rotation) The joint's rotation relative to the positive Y-axis.

Returns the joint's rotation in world coordinate space


type = Joint:getType()

- type: (string) One of the joint types. See the class documentation for the types of joints.

Returns the type of the joint


newJoint = Joint.new()

Creates a new joint.


Joint:setBreakForce(force)

- force: (number) Force that must be applied to the joint to break it.

Sets the force at which a joint will break. A joint breaks by disabling itself if the force applied to the joint exceeds the break force. If 0, joint is unbreakable.


Joint:setEnabled(flag)

- flag: (boolean) If true, enable the joint

Enables or disables a joint. Enabled joints constrain the behavior of the objects to which they are connected and are moved by those objects. Disabled joints do not constrain objects to which they are connected and are not moved by those objects.


Joint:setObject1(object)

- object: (SceneObject or nil) One object to which to attach the joint

Attaches an object to the joint, or affixes one end of the joint to the scene itself. Joints affixed to the scene have position and constrain their objects, but the joint pivot does not move (meaning the object is 'attached to space')


Joint:setObject2(object)

- object: (SceneObject or nil) One object to which to attach the joint

Attaches an object to the joint, or affixes one end of the joint to the scene itself. Joints affixed to the scene have position and constrain their objects, but the joint pivot does not move (meaning the object is 'attached to space')


Joint:setPosition(position)

position: (Vector) coordinates of the pivot of the joint

Sets the position of the joint's pivot. Rotational-constraint joints will allow pivoting around this location in space


Joint:setRange(min,max)

- min: (Number or nil) Minimum angle, in degrees (deflection from initial position). Specify 'nil' for no minimum limit
- max: (Number or nil) Maximum angle, in degrees (deflection from initial position). Specify 'nil' for no maximum limit

Sets the minimum and maximum angle/position of the joint, where the zero angle is the angle of the joint when the joint was enabled


Joint:setRotation(rotation)

- rotation: (Rotation) The joint's rotation relative to the positive Y-axis.

Sets the rotation of the joint in world coordinate space. Hinge joints allow rotation around the Y-axis, while Universal joints allow rotation around the Y and Z-axes.


Joint:setType(type)

- type: (string) One of the joint types. Supported types are 'Ball', 'Hinge', 'Anchor' and 'Universal'.
See the class documentation for the description of these joints.

Sets the type of joint


>

class Lighting

Controls intensity and direction of the lights in the scene.

Currently, the Wild Pockets engine supports three directional, global lights that are shared by all objects in the scene. The direction, ambient intensity, diffuse intensity, and specular intensity of these lights can be controlled. Additionally, the 'shininess' (specular coefficient) can also be modified for all objects in the scene.

With the exception of the shininess attribute, each light property can be specified for each light independently by specifying a light index (either 0, 1, or 2). Specifying no index automatically selects light 0.

Member functions:

color = Lighting.getAmbient()

- color: (color) The current color of the ambient light

retrieves the current ambient color of the specified light


color = Lighting.getDiffuse(index)

ambient: (color) The current diffuse color of the light index: (number, optional) Index of one of the lights in the scene

retrieves the diffuse color of the light


direction = Lighting.getDirection(index)

- direction: (Vector) The direction towards which the light is shining
- index: (number, optional) Index of one of the lights in the scene

retrieves the position of the light in the scene


coefficient = Lighting.getShininess()

- coefficient: (number) The current specular coefficient

retrieves the shininess coefficient of the objects in the scene


color = Lighting.getSpecular(index)

- color: (color) The current color of the specular light
- index: (number, optional) Index of one of the lights in the scene

retrieves the specular color of the light


transform = Lighting.getTransform(index)

- transform: (Transform) transform from a vector along the positive y-axis to the direction from which the light is shining
- index: (number, optional) Index of one of the lights in the scene

Retrieves a transform describing the orientation of the light in the scene


Lighting.setAmbient(color)

- color: (Color) The color to which the ambient light should be set

sets the ambient light in the scene


Lighting.setDiffuse(color,index)

- color: (Color) Diffuse color of the light
- index: (number, optional) Index of one of the lights in the scene

sets the diffuse color of the light


Lighting.setDirection(direction,index)

- direction: (Vector) A vector pointing in the direction from which the light originates
- index: (number, optional) Index of one of the lights in the scene

sets the orientation of the light in the scene


Lighting.setShininess(coefficient)

- coefficient: (number) Specifies a specular coefficient, with higher
values corresponding to a sharper specular highlight.

sets the shininess coefficient of the light


Lighting.setSpecular(color,index)

- color: (Color) The color to use for specular highlights from the specified light
- index: (number, optional) Index of one of the lights in the scene

sets the specular color of the light


Lighting.setTransform(transform,index)

- transform: (Transform) direction towards which the light is shining
- index: (number, optional) Index of one of the lights in the scene

sets a transform describing the orientation of the light in the scene


>

class Matrix

Using Matrices is not recommended. Please read about class Transform before trying matrices: class Transform is full of convenient operators that do all kinds of useful things.

If, after reading about Transforms, you still feel that you need matrices, please report this as a bug. We feel that if you have to use trigonometry, matrix math, calculus, or any other complex mathematics in order to write WildPockets games, then we've done something wrong.

Despite that, we've provided a matrix class that you can use as a stopgap until we fix the design flaw that is forcing you to use matrices.

Member functions:

value = Matrix:__add(othermatrix)

Matrix Addition


value = Matrix:__mul(value)

Value can be a number, a matrix, or a vector.


Matrix:__sub(...)

Matrix Subtraction


value = Matrix:getValAt(x,y)

Gets an element of the matrix.


value = Matrix:inverse()

Returns the matrix inverse. Currently only works on affine matrices.


affine = Matrix:isAffine()

Returns true if the matrix is Affine.

This is usefull for checking if you can use our inverse function.


mat = Matrix.new(...)

Creates a new matrix object. The parameters can be any of the following:
- Option 1. Another matrix: the new matrix is identical to the matrix passed in
- Option 2. A rotation object.
- Option 3. A transform object.
- Option 4. A table of 16 numbers: these numbers are in order, across each row left to right, row by row top to bottom
- Option 5. 16 numbers: these numbers are in order, across each row left to right, row by row top to bottom


Matrix:setValAt(x,y,value)

Sets an element of the matrix.


>

class Mouse

Allows access to the system pointing device to retrieve information such as the x and y coordinates of the cursor. Mouse also supports raycasting and determining which object the player has clicked on.

Member functions:

Mouse.capture(callback)

- callback : This function will be passed a true or false if the player has allowed mouse capture.

Asks the player if the game can have permission to steal the mouse cursor


width = Mouse.getMaxX()

Returns the width of the rendering area.


height = Mouse.getMaxY()

Returns the height of the rendering area.


percentX = Mouse.getPercentX()

Returns the X coord of the mouse as a number between 0 and 1.


percentY = Mouse.getPercentY()

Returns the Y coord of the mouse as a number between 0 and 1.


ray = Mouse.getRay()

Returns a normalized ray as a vector from the camera to the mouse.


ray = Mouse.getRayFromXY(x,y)

Returns a normalized ray as a vector from the camera to the gui coordinates passed.


object,distance,point = Mouse.getTopObject()

Returns the object under the mouse, or NIL if none, the distance to the object, and the collision point.

There is a much more powerful version of this function called Collider.castMouseRay. There is also a global funtion 'underMouse()' that returns the first object under the mouse.

DEPRECATED IN V1.5

please use Mouse.under() for getting an object. please use Collider.castMouseRay() for all other functionality.


X = Mouse.getX()

Returns the mouses X coordinates in pixels from the left side of the plugin window.


X,Y = Mouse.getXY()

Returns the mouse X and Y coordinates in pixels from the top of the plugin window.


Y = Mouse.getY()

Returns the mouses Y coordinates in pixels from the top of the plugin window.


flag = Mouse.hasFocus()

Returns true if the WildPockets window has the keyboard/mouse focus.


Mouse.hascapture()

Returns if the game has permission to steal the mouse cursor


flag = Mouse.haveFocus()

Returns true if the WildPockets window has the keyboard/mouse focus.

DEPRECATED IN V1.5

please use Mouse.hasFocus()


Mouse.hide()

Hides the mouse cursor.


Mouse.setCursorVisible(bool)

Sets if the mouse is visible.


Mouse.setPosition(x,y)

Shows the mouse cursor. If either x or y is nil, it will center the cursor on the screen.


Mouse.show()

Shows the mouse cursor.


Mouse:under( ? )

Undocumented method.


>

class NumberSet

A sorted set of numbers.

Member functions:

value = NumberSet:greatest()

Gets the largest number in the set. If the set is empty, returns NIL.


NumberSet:insert(n)

Inserts a number into the set, if it's not already there.


value = NumberSet:least()

Gets the smallest number in the set. If the set is empty, returns NIL.


set = NumberSet.new()

Constructs a new NumberSet.


value = NumberSet:popGreatest()

Returns the largest number in the set, removing it from the set.


value = NumberSet:popLeast()

Returns the smallest number in the set, removing it from the set.


size = NumberSet:size()

Returns the number of values in the set.


>

class ParticleSystem

To create a particle system, you must write a little program in a custom language called 'ParticleScript.' ParticleScript is documented in the manual. Having created your program, you attach your particle system to a scene object using SceneObject:setParticleSystem(script). You may remove the particle effect from a scene object using SceneObject:clearParticleSystem(). When a particle system is present on a scene object, you can obtain a handle to that particle system using SceneObject:particles(). With a handle to a particle system, you may be able to tweak its behavior using methods of class ParticleSystem. What you can tweak depends greatly on the ParticleScript itself. Please see the manual entry on ParticleScript.

Member functions:

ParticleSystem:debug(...)

Prints a debugging dump.


components = ParticleSystem:getUniformComponents(attr)

Returns how many components the specified uniform variable has.


list = ParticleSystem:getUniformNames()

Returns a list of all uniforms (an array of strings).


ParticleSystem:getUniformValue(...)

Fetches the value of a uniform parameter.


ParticleSystem:setUniformValue(attr, v1 [,v2 ,v3 ,v4])

Stores a value for a uniform parameter.


>

class Path

Paths are used to store prerecorded motions. These motions are stored as a series of keyframes. It is possible to store position keyframes, rotation keyframes, scale keyframes, or any combination of these. The three tracks (position, rotation, and scale) operate independently. Keyframes can be inserted into the path in any order, they are automatically sorted by time. Keyframes do not need to be spaced evenly. Paths can be used to look up values or may drive the transform of an object directly.

If you fetch a position, rotation, or scale from a time which is in-between two keyframes, the Path will automatically interpolate. Position interpolation is linear, not splined. Rotation interpolation uses nlerp, not slerp. If you fetch a time value outside the keyframe range, the Path can either extrapolate or clamp, at your discretion. The default behavior is clamping.

Paths can only store prerecorded motion. If you need motion that responds to user input, Paths are not for you.

Member functions:

Path:apply(t)

Fetches a sample from the path and applies it to the path's target object.


Path:clearPosition([t1 , [t2]])

Deletes track keyframes. With zero arguments, deletes all track keyframes. With one argument, a time value, deletes just the track keyframe at the specified time. With two arguments, both time values, deletes all track keyframes between the two numbers inclusive. If no keyframes are present that match, returns silently without doing anything.


Path:clearRotation([t1 , [t2]])

Deletes track keyframes. With zero arguments, deletes all track keyframes. With one argument, a time value, deletes just the track keyframe at the specified time. With two arguments, both time values, deletes all track keyframes between the two numbers inclusive. If no keyframes are present that match, returns silently without doing anything.


Path:clearScale([t1 , [t2]])

Deletes track keyframes. With zero arguments, deletes all track keyframes. With one argument, a time value, deletes just the track keyframe at the specified time. With two arguments, both time values, deletes all track keyframes between the two numbers inclusive. If no keyframes are present that match, returns silently without doing anything.


Path:clearUniscale([t1 , [t2]])

Deletes track keyframes. With zero arguments, deletes all track keyframes. With one argument, a time value, deletes just the track keyframe at the specified time. With two arguments, both time values, deletes all track keyframes between the two numbers inclusive. If no keyframes are present that match, returns silently without doing anything.


path = Path:copy()

Makes a copy of a path.


Path:duration(length)

Rescales the path's length to the specified duration. This does not construct a new path: it modifies the existing one. Returns the existing path.

DEPRECATED IN V1.5

please use Path:setDuration()


time,value = Path:firstPosition()

Returns the first track keyframe.


time,value = Path:firstRotation()

Returns the first track keyframe.


time,value = Path:firstScale()

Returns the first track keyframe.


time,value = Path:firstUniscale()

Returns the first track keyframe.


Path:getBegin()

Gets the lowest timestamp


Path:getDuration()

Returns the path's duration in seconds.


Path:getEnd()

Gets the highest timestamp


flag = Path:getExtrapolatePosition()

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


flag = Path:getExtrapolateRotation()

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


flag = Path:getExtrapolateScale()

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


flag = Path:getExtrapolateUniscale()

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


track = Path:getPosition(time)

Gets the track at a given time. This value is either default (if the path has no keys or one key), interpolated (if time is between two keys), clamped (if time is outside of all keyframes and the extrapolate flag is off), or extrapolated (if time is outside of all keys and the extrapolate flag is on).


track = Path:getRotation(time)

Gets the track at a given time. This value is either default (if the path has no keys or one key), interpolated (if time is between two keys), clamped (if time is outside of all keyframes and the extrapolate flag is off), or extrapolated (if time is outside of all keys and the extrapolate flag is on).


track = Path:getScale(time)

Gets the track at a given time. This value is either default (if the path has no keys or one key), interpolated (if time is between two keys), clamped (if time is outside of all keyframes and the extrapolate flag is off), or extrapolated (if time is outside of all keys and the extrapolate flag is on).


Path:getTarget()

Returns the object that was stored using setTarget.


track = Path:getUniscale(time)

Gets the track at a given time. This value is either default (if the path has no keys or one key), interpolated (if time is between two keys), clamped (if time is outside of all keyframes and the extrapolate flag is off), or extrapolated (if time is outside of all keys and the extrapolate flag is on).


Path:go()

Starts a background job that causes an object to follow the path. The path must be associated with a particular scene object. The background job can be terminated using Path:stop().


anypresent = Path:hasPosition()

Returns true if any track keyframes have been stored in the path.


anypresent = Path:hasRotation()

Returns true if any track keyframes have been stored in the path.


anypresent = Path:hasScale()

Returns true if any track keyframes have been stored in the path.


anypresent = Path:hasUniscale()

Returns true if any track keyframes have been stored in the path.


time,track = Path:lastPosition()

Returns the last track keyframe.


time,track = Path:lastRotation()

Returns the last track keyframe.


time,track = Path:lastScale()

Returns the last track keyframe.


time,track = Path:lastUniscale()

Returns the last track keyframe.


Path:makeHop(t1,t2,p1,p2,height,steps,extrapolate)

Inserts keyframes for a hopping motion

DEPRECATED IN V1.5

Unfortunately, you're going to have to write your own bunny function now.


path = Path:new()

Creates a new Path instance. Path is a class that stores keyframes. There are four kinds of keyframes - position, rotation, uniform scale, and scale. These are stored separately - you can script a series of rotations, for instance, without scripting a series of positions.

A path can be 'targeted', meaning that it may contain a reference to a particular scene object. This indicates that the path is meant to be applied to that scene object using the 'apply' method. Paths created using 'new' are not initially targeted paths.


time,track = Path:nextPosition(t)

Returns the next track keyframe.


time,track = Path:nextRotation(t)

Returns the next track keyframe.


time,track = Path:nextScale(t)

Returns the next track keyframe.


time,track = Path:nextUniscale(t)

Returns the next track keyframe.


time,track = Path:prevPosition(t)

Returns the previous track keyframe.


time,track = Path:prevRotation(t)

Returns the previous track keyframe.


time,track = Path:prevScale(t)

Returns the previous track keyframe.


time,track = Path:prevUniscale(t)

Returns the previous track keyframe.


Path:setDuration(length)

Rescales the path's duration to the specified time. This does not construct a new path: it modifies the existing one. Returns the existing path.


Path:setExtrapolatePosition(flag)

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


Path:setExtrapolateRotation(flag)

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


Path:setExtrapolateScale(flag)

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


Path:setExtrapolateUniscale(flag)

If the flag is true, retrieving coordinates outside of the path's time-range will extrapolate. If the flag is false, values are clamped to the value at the track's endpoint.


Path:setPosition(time, track)

Adds a track-keyframe at the specified time. Keyframes do not need to be added in a consecutive order, nor do they need to have consistent spacing.


Path:setRotation(time, track)

Adds a track-keyframe at the specified time. Keyframes do not need to be added in a consecutive order, nor do they need to have consistent spacing.


Path:setScale(time, track)

Adds a track-keyframe at the specified time. Keyframes do not need to be added in a consecutive order, nor do they need to have consistent spacing.


Path:setTarget(obj)

Associates the path with a target object, which indicates that the path is meant to be applied to the specified object.


Path:setUniscale(time, track)

Adds a track-keyframe at the specified time. Keyframes do not need to be added in a consecutive order, nor do they need to have consistent spacing.


Path:sleep()

Sleep while the object follows the path. The path must be associated with a particular scene object. This function doesn't return until the object has reached its destination.

Calling 'sleep' can only be done from inside background jobs!


Path:smooth({options})

Smooths out the path by inserting additional keyframes. The new keyframes are chosen using a spline. Accepts a table full of spline configuration options.

* mode: a string, one of the splining algorithms listed below.
* steps: how many keyframes to insert per existing keyframe.
* tracks: a string indicating which tracks to smooth.

The 'tracks' string can contain the characters 'prsu' designating position, rotation, scale, and uniscale respectively.

All of these options have default values:

* mode: defaults to 'synth-bezier'
* steps: selected adaptively by the algorithm.
* tracks: defaults to 'p' - ie, position only.

Currently, the only available modes is:

'synth-bezier'. This mode accepts a 'tension' parameter which may range from 0 to 1. A tension close to 1.0 causes the smoothed curve to cling to the original path very tightly, whereas a tension of 0.0 causes it to swoop in relaxed curves. For those familiar with bezier splines, you may be aware that the bezier algorithm uses two kinds of control points - major and minor - and the resulting curve only contacts the major control points. The synth-bezier algorithm uses the keyframes from the original path as the major control points, and it synthesizes the minor ones automatically.


Path:stop()

After using Path:go to start the execution of a path, you can use Path:stop to terminate the execution. See Path:go for more information.


>

class Player

Undocumented class.

Member functions:

Player.getPlayerNumberData(game,user,key,callback)

- game : (string) The game filename to associate this data with. If nil, will default to the current game filename.
- user : (string) The user that the data was saved under. Usually nil which will use the currently logged in player.
- key : (string) The unique string that identifies the data to be retrieved.
- callback : (function) The function to be called with the server returned results.

Schedules a callback to be passed the value string that was stored with the Player.putPlayerIntData function. The callback will be passed the value and error code.

quickExample: function serverGetReturn(data,err) if not err then print(data) else print(err) end end Player.getPlayerIntData(nil,nil,"myKey",serverGetReturn)


Player.getPlayerStringData(game,user,key,callback)

- game : (string) The game filename to associate this data with. If nil, will default to the current game filename.
- user : (string) The user that you want the data associated with. Usually nil which will use the currently logged in player.
- key : (string) The unique string that identifies the data to be retrieved.
- callback : (function The function to be called when the server returns the results.

Schedules a callback to be passed the value string that was stored with the Player.putPlayerStringData function. The callback will be passed the value and error code.

quickExample: function serverGetReturn(data,err) if not err then print(data) else print(err) end end Player.getPlayerStringData(nil,nil,"myKey",serverGetReturn)


Player.getTopPlayerNumberData(game,key,number,callback)

- game (string) : The game filename to associate this data with. If nil, will default to the current game filename.
- key (string) : The unique string that identifies the data to be retrieved.
- number - (number) : The number of returns to be contained in the table (for instance the top N players)
- callback (function) : The function to be called when the server returns the results.

Returns a table of entries where each entry is a table with a user and value field. This function will only tally data that has been marked public when it was uploaded. The callback will be passed the result table and the error code.


Player.getUsername()

Returns the username of the currently logged in player. If the user is remaining Anonymous it will return nil. If the user hasn't yet completed the login process it will return nil.


Player.hasPurchased(itemKey,callback)

- itemkey : The unique string that identifies the item to be purchased.
- callback : The function to be called when the server returns the results.

Initiates a server query to see if the current player has purchased the given item. The callback function will be passed both a boolean that is true if the player has purchased the item, and a string that is nil if there were no errors. If the player has not logged in, this function will also ask the player to log in.


Player:kernelOpenSubscriptionDialog(...)

Player.kernelOpenSubscriptionDialog(user,itemKey,price,days,months,curExpire,newExpire,brief,balance,callback)


Player:offerOneTimePurchase( ? )

Undocumented method.


Player.offerSubscriptionPurchase(itemKey,days,months,userCallback)

- itemkey : The unique string that identifies the item to be purchased.
- days : The number of days to offer (can be nil)
- months : The number of months to offer (can be nil)
- callback : The function to be called when the server returns the results.

Asks the player if they would like to purchase a subscription to the given itemKey. Will call the callback with the same results as hasPurchased would return (A boolean of whether or not the player has access to that item at this point in time).


Player.putPlayerNumberData(game,private,key,value,callback)

- game (string) : The game filename to associate this data with. If nil, will default to the current game filename.
- private (boolean) : If true then this value cannot be accessed unless the current player is logged in.
- key (string) : The unique string that identifies the data to be stored.
- value (number) : The data to be stored as an integer.
- callback (function) : The function to be called when the server returns the results.

Places an integer value on the server. This can be referenced under the given key, the given game name, and the current username. All information stored is also keyed under the username of the pocket owner which cannot be changed.

If private is specified as true then only the currently logged in user can retrieve this value, otherwise the value can be accessed from any pocket or webpage owned by the same owner as the current pocket.

If game is not specified this will use the current filename of the pocket. If you want data to be shared among different pockets on your account, specify the same game filename.

The callback will be passed error code strings that detail what went wrong.

quickExample: function serverPutReturn(err) if err then print(err) end end Player.putPlayerIntData(nil,true,"myKey",myNumberValue,serverPutReturn)


Player.putPlayerStringData(game,private,key,value,callback)

- game : (string) The game filename to associate this data with. If nil, will default to the current game filename.
- private : (boolean) If true then this value cannot be accessed unless the current player is logged in.
- key : (string) The unique string that identifies the data to be stored.
- value : (string) The data to be stored
- callback : (function) The function to be called when the server returns the results.

Places a string value on the server. This can be referenced under the given key, the given game name, and the current username. All information stored is also keyed under the username of the pocket owner which cannot be changed. This information can only be accessed from pockets under the same username.

If private is specified as true then only the currently logged in user can retrieve this value, otherwise the value can be accessed from any pocket or webpage owned by the same owner as the current pocket.

If game is not specified this will use the current filename of the pocket. If you want data to be shared among different pockets on your account, specify the same game filename.

The callback will be passed error code strings that detail what went wrong.

quickExample:

function serverPutReturn(err) if err then print(err) end end Player.putPlayerStringData(nil,true,"myKey",myString,serverPutReturn)


Player.recordCheckpoint(name,numberData,callback)

- name (string) : The unique name of the checkpoint.
- numberData (number or nil) : The number of times this checkpoint should be recorded.
- callback (function) : A function to capture errors.

This function will record to the Wild Pockets servers that the player hit this point in the game. This can be used for tracking information about players such as how many players defeated the troll. (Note: You will not be able to view individual tracking information for protection of the users privacy.) The numberData argument is used if you would like to send multiple recordCheckpoints with a single call. One example of how to use the number data is to track the amount of time in a level. At the end of the level you can call recordCheckpoint("Minutes Spent in Level 1",34). From the website you can see the total number of minutes spent in the level, as well as the avg minutes per playthrough. The callback function will be called with a single argument that should be nil if no errors occured.


Player.requestLogin(callback)

- callback : The function to be called when the plugin knows who is logged in.

If the player is not logged in this function will make the plugin ask the user to log in. When the user has finished logging in or chooses to remain anonymous the callback will be called and passed the username and any errors.


>

class ProfileTimer

ProfileTimers are used to instrument your program to gather performance data. You will create one ProfileTimer object per profiling category, like this:

* timer = ProfileTimer.new("My Subroutine")

The timer should be created *once* at the start of your program. At the beginning of the subroutine you wish to measure, you must fetch the current time, like this:

* start = ProfileTimer.queryPerformanceCounter()

At the end of the subroutine you wish to measure, you need to increment the timer, like this:

* timer:addFromStart(start)

This measures the amount of time elapsed, and adds that to the timer. It also increments a counter that shows how many times the subroutine has been called.

Member functions:

ProfileTimer:add(value)

Add the specified amount of time to the ProfileTimer, and increments the timer's call-counter.


ProfileTimer:addFromStart(start)

Fetches the current time using queryPerformanceCounter, and computes an elapsed time relative to start. Adds this elapsed time to the timer, and increments the timer's call-counter.


ProfileTimer:count(value)

Add the specified integer value to a counter.


ProfileTimer.dumpFrame()

Prints out performance measurements. The four columns are:

- Number of calls (last 60 frames average)
- Time taken (last 60 frames average)
- Number of calls (last frame)
- Time taken (last frame)

If you call dumpFrame when you're not in profiling mode, the data you get is rather unreliable because of thread interactions.


ProfileTimer.dumpSteps()

Dumps the record of simulation steps. Shows the wall-clock time of the step, and whether or not a render was fired. Finally, estimates the simulation and render fps based on the simulation step data.


value = ProfileTimer.getProfilingMode()

In normal mode, the engine tries to maintain maximum speed. In profiling mode, the engine tries to maximize measurement accuracy. Mainly, the difference is that in profiling mode, the engine avoids complex multithreading. Returns true or false.


timer = ProfileTimer:new(name)

Constructs a new ProfileTimer. You will construct one ProfileTimer for each subroutine you wish to instrument.


seconds = ProfileTimer:queryPerformanceCounter()

Queries the microsecond-accuracy performance timer. This should only be used for performance instrumentation.


ProfileTimer.setProfilingMode(true/false)

In normal mode, the engine tries to maintain maximum speed. In profiling mode, the engine tries to maximize measurement accuracy. Mainly, the difference is that in profiling mode, the engine avoids complex multithreading.


ProfileTimer.startFresh()

Discards all data collected up to this point and starts gathering fresh data. This is useful if you want a clean measurement that only includes a specific time period.

This resets all the data, but it doesn't reset the profiling mode.


>

class Rect

Stores a screen-space rectangle, specified in pixels pixels from the upper-left corner of the screen. The Rect also contains an ID string.

When creating GUI elements such as windows, menus, buttons, and the like, the first step is generally to construct rectangles for each subcomponent. For example, consider a confirmation dialog containing a message, an OK button, and a cancel button. To build such a dialog, the first step would be to construct four rectangles: one for the dialog as a whole, one for the message, one for the OK button, and one for the cancel-button. This is how you lay out a GUI.

Rect ID strings should be descriptive and hierarchical. In the example above, the dialog could have ID 'screen/confirm' the text could have ID 'screen/confirm/text', the OK button could have ID 'screen/confirm/ok', and the cancel button could have ID 'screen/confirm/cancel'. The GUI system relies upon the ID strings being built in this predictable, hierarchical way.

All Rect constructors automatically create ID strings by concatenating the ID of a parent rectangle, a slash, and a sub-ID string supplied as an argument. The argument can generally be omitted, but this results in an 'unnamed' Rect. Many operations cannot be performed using unnamed Rects.

All rectangle hierarchies must start with a top-level screen rectangle, obtained by calling Rect:screen(). The rectangle returned by this function often has ID 'screen', but not always.

In a hierarchy of Rects, the child Rects do not need to be inside the parent Rects. The hierarchy is logical, not spatial.

The GUI system as a whole is unusual. Please read the manual chapter on GUI creation to learn the concepts associated with GUI-building.

Member functions:

Rect:__eq(other)

Returns true if the rect is equal to the other Rect.


Rect:activateRegion()

Enable the rectangle as a mouse-detection region. Unlike the methods leftMouseDown, and so forth, this activates the region, but doesn't install a callback.

Only works inside a GUI repaint-function.


rect = Rect:adjacent([SubID,] sizex, sizey, gap, align)

Creates a rectangle that is adjacent to the given rectangle. Align can be 'NW','NE','SW','SE','EN','ES','WN','WS'.


rect = Rect:center([SubID,] xsize,ysize)

Creates a subrectangle centered inside self.


Rect:clearMenuActive()

Clears the rect's menu-active flag.

DEPRECATED IN V1.5

please use Rect:setMenuActive(false)


rect = Rect:confine([SubID,] container)

Tries to make this rectangle fit inside the container rectangle by scooting this rectangle left, right, up, or down.


flag = Rect:contains(x,y)

Returns true if the coordinates are inside the rect.


Rect:drag()

Allows the rect to be dragged using the left mouse button. Returns a displaced version of the rectangle.


Rect:drawButton(clip, skin, label, callback)

Draws a button, and arranges a callback to occur if the button is clicked.

* Uses skin[.buttonDefault].down
* Uses skin[.buttonDefault].over
* Uses skin[.buttonDefault].normal
* Uses skin[.buttonDefault].text (optional)
* Uses skin[.buttonDefault].overlay (optional)


Rect:drawCheckBox(clip, skin, initvalue [,callback])

Draws a checkbox. The initial value you pass in should be a boolean. If you provide a callback function, then it will be called each time the checkbox's value is altered. You can alter the checkbox yourself using getCheckBoxValue and setCheckBoxValue.

* Uses skin[.checkboxDefault].selectedDown
* Uses skin[.checkboxDefault].selectedOver
* Uses skin[.checkboxDefault].selected
* Uses skin[.checkboxDefault].down
* Uses skin[.checkboxDefault].over
* Uses skin[.checkboxDefault].normal
* Uses skin[.checkboxDefault].tooltip (optional)


Rect:drawDropDownButton(clip, skin, text)

Draws a drop-down-menu button. Text is optional.

* Uses skin[.dropDownMenuDefault].over
* Uses skin[.dropDownMenuDefault].normal
* Uses skin[.dropDownMenuDefault].overlay (optional)


Rect:drawHighlight(pos,clip,options,text,lo,hi)

- pos: (Rect) The position to render the text
- clip: (Rect) Boundary rectangle against which text should be clipped
- text: (string) The text to display
- options: (table) a table containing options.
- lo: (int) the first character you want to highlight (1-based)
- hi: (int) the last character you want to highlight (1-based)

The options are the same as for addText, with these additional:

- highlightcolor: (color) color of the highlight
- pointcolor: (color) color of the insertion-point

Draws a text-highlight or text-insertion point. You should draw the highlight before you draw the text itself.


Rect:drawIconButton(clip, skin, image, callback)

Draws a button containing a picture. Arranges a callback to occur if the button is clicked. The image parameter should be an image filename. The image will be rendered on top of the button, so it should be transparent enough to let the button show through.

* Uses skin[.buttonDefault].down
* Uses skin[.buttonDefault].over
* Uses skin[.buttonDefault].normal


Rect:drawLabel(clip, skin, text)

Draws a text label

* Uses skin[.labelDefault].text


Rect:drawMenuBody(clip, skin, align, maxheight, contents, callback)

Draws a menu body.

A menu consists of two parts: the button which pops the menu up, and the menu's body. The body only appears when the button is clicked. Drawing a menu consists of drawing the button, then drawing the body.

You have to draw the button using Rect:drawButton, Rect:drawIconButton, or the equivalent. This button will contain a menu-active flag that will determine whether or not the body is drawn. The button's handler should be Rect.setMenuActive, this will cause the menu-active flag to be set and the body to appear.

After drawing the button, use this function to draw the body. The rectangle you pass into this function is the rectangle of the button. This function synthesizes a rectangle for the body. This function will draw nothing if the button's menu-active flag is not set.

The align parameter can be any of the strings used by Rect:adjacent. This determines the position of the body relative to the button. The maxheight parameter limits the size of the menu, if it's too large, a scrollbar will be created. The contents should be an array of strings. When a menu item is clicked, the callback will be invoked, passing in the name of the item as a parameter.

* Uses skin[.menuDefault].itemOver
* Uses skin[.menuDefault].itemDown
* Uses skin[.menuDefault].textOver
* Uses skin[.menuDefault].text
* Uses skin[.menuDefault].body
* Uses skin[.menuDefault].body.textsize (integer)
* Uses skin[.menuDefault].body.linegap (integer)
* Uses skin[.menuDefault].body.xmargin (integer)
* Uses skin[.menuDefault].body.ymargin (integer)
* Uses skin[.menuDefault].body.xextend (integer)
* Uses skin[.menuDefault].body.bargap (integer)
* Uses skin[.menuDefault].body.barsize (integer)


Rect.drawPict(clip,{foreground (optional), background (optional), stretch (optional), behind (optional)})

- pos: (Rect) Position of the image
- clip: (Rect) Boundaries against which the image should be clipped
- foreground: (string) filename of a Texture to use as a foreground image
- background: (string) Filename of a Texture to use as a background image
- stretch: (boolean) If true, stretch the image to fill the border, otherwise tile the image
- behind: (boolean) If true, the image is rendered behind the scene.
- color: (color) Tint the image. Caution: there are limitations, see the manual.

Fills the specified rectangle. The contents are synthesized in a complex manner from the foreground and background images. See the manual to understand how this synthesis works.


Rect:drawRadioButton(clip, skin, first, value[, callback])

Draws a radio button. When drawing a set of radio buttons, you must pass the rectangle of the first button in the set. Value is a string or number which is this radio button's value. You may provide a callback function to the first radio button in a set, you may not provide a callback to any of the others. The callback will be invoked whenever the value changes.

* Uses skin[.radioDefault].selectedDown
* Uses skin[.radioDefault].selectedOver
* Uses skin[.radioDefault].selected
* Uses skin[.radioDefault].down
* Uses skin[.radioDefault].over
* Uses skin[.radioDefault].normal
* Uses skin[.radioDefault].tooltip (optional)


Rect:drawText(clip,options,text)

- clip: (Rect) Boundary rectangle against which text should be clipped
- text: (string) The text to display
- options: (table) a table containing options.

The options can be:

- font: (string) file path of a font resource
- color: (color) a color specification
- size: (number) Height of a line of text, in pixels
- linegap: (number) Number of pixels between each line of text
- valign: (Vertical alignment of text) Vertical alignment of text. Default: top
- halign: (string) Horizontal alignment of text. Default: left
- wrap: (boolean) If true, text should wrap at border
- behind: (boolean) If true, this GUI element is drawn behind the scene

Adds a text object to the GUI for rendering. Valid valign values: top, center, bottom. Valid halign values: left, center, right.


Rect:drawTextEditor(clip, skin, init)

Draws a multiline text editor with vertical scrollbar.

* Uses skin[.drawTextEditor].text
* Uses skin[.drawTextEditor].body


Rect:drawTextInput(clip, skin, init, callback)

Draws a one-line-of-text input box. This differs from a text editor box in that it only allows one line of text: any attempt to hit enter simply triggers the callback.

* Uses skin[.drawTextEditor][.scrollDefault].barNS
* Uses skin[.drawTextEditor][.scrollDefault].buttonNDown
* Uses skin[.drawTextEditor][.scrollDefault].buttonN
* Uses skin[.drawTextEditor][.scrollDefault].buttonSDown
* Uses skin[.drawTextEditor][.scrollDefault].buttonS
* Uses skin[.drawTextEditor][.scrollDefault].thumb
* Uses skin[.drawTextEditor].text
* Uses skin[.drawTextEditor].body
* Uses skin[.drawTextEditor].body.barsize (integer)
* Uses skin[.drawTextEditor].body.bargap (integer)


Rect:drawTooltip(clip, skin, text)

If the mouse is over this rectangle for a set period of time, this function will draw a tooltip contanining the specified text.


amount = Rect:drawVScroll(clip, skin, inc, def)

Draws a vertical scrollbar. Returns a number from zero to one, where zero means the scrollbar is at the top, and one means that the scrollbar is at the bottom. Inc is the increment (default 0.1) by which the scrollbar moves when you click the arrow buttons. Def is the default value that the scrollbar is initialized with when it is first created.

* Uses skin[.scrollDefault].barNS
* Uses skin[.scrollDefault].buttonNDown
* Uses skin[.scrollDefault].buttonN
* Uses skin[.scrollDefault].buttonSDown
* Uses skin[.scrollDefault].buttonS
* Uses skin[.scrollDefault].thumb


Rect:drawWindow(clip, skin)

Draws a box on the screen.

* Uses skin[.windowDefault].normal


Rect:enableFocus(fn)

Enable this rect to get the keyboard focus. You can also specify a callback function to obtain keyboard events. The event handling function will get called whenever this rectangle has focus and the user presses a key. The callback is passed the event name as a parameter.

If you (separately) activate this region for mouse clicks, then the GuiManager will direct focus to this region whenever you click on it. If this rectangle is a subrectangle of a larger region, and that larger region is activated for mouse clicks, then clicking the larger region may under certain circumstances also direct focus to this region.


id,x1,y1,x2,y2 = Rect:get()

Fetches the id and the bounds.


x1,y1,x2,y2 = Rect:getBounds()

Fetches the data inside the rect.


Rect:getCheckBoxValue()

Returns the current value of the checkbox, true (checked) or false (unchecked).


Rect:getFocus()

Returns true if this rectangle has the keyboard focus.


id = Rect:getId()

Returns the Rect's ID string


Rect:getMenuActive()

Returns the rect's menu-active flag.


Rect:getRadioValue()

Returns the current value of the currently-selected radio button. It doesn't matter which radio button you pass to 'getRadioValue', it will return the value of the currently-selected one in the set.


Rect:getScrollPercent()

Returns the percent that the scrollbar has been scrolled


Rect:getSelectedText()

The rectangle should be the rectangle of a textInput or textEditor. Returns the current selected text contents.


Rect:getText()

The rectangle should be the rectangle of a textInput or textEditor. Returns the current text contents.


x1 = Rect:getX1()

Returns the Rect's X1 (left edge) coordinate


x2 = Rect:getX2()

Returns the Rect's X2 (right edge) coordinate


y1 = Rect:getY1()

Returns the Rect's Y1 (top edge) coordinate


y2 = Rect:getY2()

Returns the Rect's Y2 (bottom edge) coordinate


Rect:hasMouse()

Returns true if this region has the mouse.


Rect:haveFocus()

Returns true if this rectangle has the keyboard focus.


height = Rect:height()

Fetches the height of the rectangle.


Rect:initTextInput()

Initializes a text input box so that it can have different initialization parameters - designed to be used before a call to Rect:drawTextInput(). If not called, the defaults from Rect:drawTextInput() will be used.

parameters: initial, text, cursorlo, cursorhi, focalpoint, scroll


rect = Rect:inset([SubID,] addx1,addy1,subx2,suby2)

Creates a subrectangle by insetting self.


intersection = Rect:intersect(other)

Returns the intersection of two rectangles. For convenience, if other is nil, returns self.


Rect:leftClickInProgress()

Returns true if the user is in the process of left-clicking in this region, but has not released the mouse yet.


Rect:leftMouseClick(fn)

Adds a left-mouse-click handler for the specified screen region. The handler is called when the mouse-up occurs, but only if the mouse-down was in the same region.

Only works inside a GUI repaint-function.


Rect:leftMouseDown(fn)

Adds a left-mouse-down handler for the specified screen region.

Only works inside a GUI repaint-function.


Rect:leftMouseUp(fn)

Adds a left-mouse-up handler for the specified screen region.

Only works inside a GUI repaint-function.


Rect:mouseExit(fn)

Adds a mouse-exit handler to the given region. The handler is called if the user clicks outside the region. Exit handlers are called before mouse-down, mouse-up, or mouse-click handlers.


rect = Rect:named(id)

Returns a rectangle that is the same as the specified rectangle with a new name.


Rect.new(id,x1,y1,x2,y2)

Constructs a new Rect using a manually-engineered ID string.

All other Rect constructors build rectangle ID strings hierarchically, by concatenating the ID of a parent rectangle, a slash, and an explicitly-specified SubID. This 'new' constructor is the only one that does not do this: it just puts the ID you specify into the rectangle. Since the hierarchical naming method is what you want for all normal GUI creation, this constructor is only used in rare cases when you want to manipulate the ID strings manually.

You shouldn't use this to create top-level Rects: the top-level rect should always be Rect:screen().


rect = Rect:offset([SubID,] deltax, deltay)

Shifts a rectangle in a specified direction.


rect = Rect:pad([SubID,] left,right,top,bottom,width,height)

Creates a rectangle that maintains the constraints specified on each of the four sides "100" or "100px"= pad this side with 100 pixels "30%" = keep a pad of 30 percent on this side nil = does not constrain this side

When specifying left,right and width, two should be valid values and one should be nil. When specifying top,bottom and height, two should be valid values and one should be nil. The values that you leave nil will be calculated by this function. Hence you can say keep this object 10 pixels from the right and keep the width 100 pixels.


rect = Rect:rel([SubID,] x1,y1,x2,y2)

Creates a subrectangle positioned using relative coordinates, relative to the upper-left corner.


Rect:rightClickInProgress()

Returns true if the user is in the process of right-clicking in this region, but has not released the mouse yet.


Rect:rightMouseClick(fn)

Adds a right-mouse-click handler for the specified screen region. The handler is called when the mouse-up occurs, but only if the mouse-down was in the same region.

Only works inside a GUI repaint-function.


Rect:rightMouseDown(fn)

Adds a right-mouse-down handler for the specified screen region.

Only works inside a GUI repaint-function.


Rect:rightMouseUp(fn)

Adds a right-mouse-up handler for the specified screen region.

Only works inside a GUI repaint-function.


Rect.screen()

Returns a rect representing the entire GUI layer. The string you passed to GuiManager.call will be the screen Rect's ID.


Rect:selectAllText()

The rectangle should be the rectangle of a textInput or textEditor. Selects the entire text box.


Rect:setBounds(x1,y1,x2,y2)

sets the data inside the rect.


Rect:setCheckBoxValue(state)

Sets the state of the checkbox to checked (true) or unchecked (false)


Rect:setFocus()

Attempts to direct the keyboard focus to this rectangle. Searches for any subrectangle that has used enableFocus. Of these, it selects the most-recently-used, or if none has been used, activates the first, sequentially.


Rect:setMenuActive(flag)

flag - (boolean) sets menu-active

Sets the rect's menu-active flag.


Rect:setRadioValue(state)

Sets the state of the radio button set. It doesn't matter which radio button you pass to 'setRadioValue', it will activate the one whose value matches the string/integer that you specify.


Rect:setSelectedText(text)

The rectangle should be the rectangle of a textInput or textEditor. Replaces the current selection with text.


Rect:setText(text)

The rectangle should be the rectangle of a textInput or textEditor. Sets the current text contents.


Rect:setViewPort()

Sets the location of the 3D view. If you call Rect.setViewPort(nil), restores the viewport to the full window.

Since the user could resize the window at any time, programs that set the viewport need to continually monitor the screen size and adjust the viewport as necessary.


sizex = Rect:sizex()

Fetches the width of the rectangle.

DEPRECATED IN V1.5

please use Rect:width()


sizey = Rect:sizey()

Fetches the height of the rectangle.

DEPRECATED IN V1.5

please use Rect:height()


rect = Rect:sub([SubID,] x1,y1,x2,y2)

Creates a subrectangle positioned using absolute coordinates.


Rect:toggleMenuActive()

Toggles the rect's menu-active flag.

DEPRECATED IN V1.5

please use Rect:getMenuActive() and Rect:setMenuActive()


Rect:userdata()

Gets the userdata table for the specified rectangle. You can put whatever you want into the userdata table.

Userdata tables are stored according to the Rect's ID: if two rects have the same ID, they share the same userdata table. Userdata tables are persistent from frame-to-frame: if you store something in the table one frame, then fetch the same table the next frame (using a rect of the same ID), you will be able to fetch the data you stored. If an entire repaint cycle goes by and a given userdata table is not accessed, it will be garbage collected.

To attach userdata to a Rect, the rect must have been created using an ID string. If the ID string was omitted, no userdata can be stored.

The userdata table may contain some keys starting with double underscore. Do not modify such keys.


Rect.userdataOf(id)

Gets the userdata table for the specified rectangle. You can put whatever you want into the userdata table.

Userdata tables are stored according to the Rect's ID: if two rects have the same ID, they share the same userdata table. Userdata tables are persistent from frame-to-frame: if you store something in the table one frame, then fetch the same table the next frame (using a rect of the same ID), you will be able to fetch the data you stored. If an entire repaint cycle goes by and a given userdata table is not accessed, it will be garbage collected.

To attach userdata to a Rect, the rect must have been created using an ID string. If the ID string was omitted, no userdata can be stored.

The userdata table may contain some keys starting with double underscore. Do not modify such keys.


width = Rect:width()

Fetches the width of the rectangle.


>

class Rotation

Rotations represent the orientation of an object.

In WildPockets, the +Z axis is considered 'up', the +Y axis is considered 'north', and the +X axis is considered 'east.' The default orientation is an upright individual facing north. An object in this orientation is considered 'not rotated.'

Since there are so many different ways to express an orientation, there are numerous constructors for class Rotation. For example, 'newDirection' will convert an orientation-vector into a Rotation object - with the assumption that the object should be as upright as possible while still facing in the specified direction. There are also numerous operators that convert Rotation objects into the various possible representations of orientaiton.

Member functions:

Rotation:__eq(other)

Equality comparison for rotations


Rotation:compose(parent)

Returns the composition of self and parent. If you rotate an object using the composed rotation, it is as if you rotated it using self, and then rotated it using parent.


Rotation:getAxes()

Converts the rotation object into six vectors indicating the orientation of the object. The six vectors are:

* positive x axis (the 'right' vector)
* positive y axis (the 'forward' vector)
* positive z axis (the 'up' vector)
* negative x axis (the 'left' vector)
* negative y axis (the 'backward' vector)
* negative z axis (the 'down' vector)


axis, angle = Rotation.getAxisAngle()

Converts a rotation object into an axis and an angle. The angle is in degrees.


Rotation:getHPR()

Convert a rotation into a heading, pitch, and roll. Returns three values. See Rotation.newHPR for more information about the meaning of these three numbers.


Rotation:getHeading()

Convert a rotation into a heading.


Rotation:getPitch()

Convert a rotation into a pitch.


Rotation:getRoll()

Convert a rotation into a roll.


rotation = Rotation.identity()

Returns the standard orientation: an upright individual facing north.


result = Rotation:interpolate(other, amount)

- other: (Rotation) A second rotation to serve as an interpolation target
- amount: (number) An interpolation value between 0 and 1

Interpolates between two rotation values using the slerp algorithm. If amount is 0, returns self. If amount is 1, returns other. For values in between, returns a blend between the two rotations.


Rotation.inverse()

Returns the inverse of the rotation. The inverse of a rotation simply rotates the object in the opposite direction.


Rotation.new()

With no arguments, constructs a null rotation object

With a matrix as a parameter, converts a rotation matrix to a rotation object.


Rotation.newAxisAngle(axis, angle)

Converts an axis and an angle into a rotation object. The angle is in degrees.


Rotation.newDirection(direction [, up])

Convert a direction vector and optionally an up-vector into a rotation object. If the up-vector is not specified, then the up-vector is assumed to be (0,0,1).


Rotation.newHPR(heading, pitch, roll)

Converts a heading, pitch, and roll to a rotation object. All arguments are in degrees. The object starts in the default orientation, and is rolled first about the positive Y axis, then pitched around the positive X axis, then finally headed around the positive Z-axis. This yields pretty intuitive results.


Rotation.newHeading(heading)

Converts a heading to a rotation object. Zero degrees is the default orientation: an upright individual facing north. +90 degrees is facing west, -90 degrees is facing east.


Rotation.newTwoAxes(mode, axis1, axis2)

Given a pair of axes, returns a rotation object. You can pass in any two axes (X, Y, Z). Mode must be one of:

- 'XY', 'XZ', 'YX', 'YZ', 'ZX', 'ZY'

In the event that the axes aren't perpendicular, the second axis will be corrected to make it perpendicular to the first one.

Axis 2 can be omitted, in which case an arbitrary value will be used for the second axis.


result = Rotation:nlerp(other, amount)

- other: (Rotation) A second rotation to serve as an interpolation target
- amount: (number) An interpolation value between 0 and 1

Interpolates between two rotation values using the nlerp algorithm. If amount is 0, returns self. If amount is 1, returns other. For values in between, returns a blend between the two rotations.


Rotation.random()

Returns a random rotation. We plan, eventually, to make it so that the orientations are evenly distributed, but this is not implemented yet.


Rotation:rotateVector(vector)

Applies the specified rotation to the vector. Returns the rotated vector.


result = Rotation:slerp(other, amount)

- other: (Rotation) A second rotation to serve as an interpolation target
- amount: (number) An interpolation value between 0 and 1

Interpolates between two rotation values using the slerp algorithm. If amount is 0, returns self. If amount is 1, returns other. For values in between, returns a blend between the two rotations.


Rotation.snapAxis(axis, vec)

Snaps the object so that one of its axes aligns to the specified vector. The axis can be:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


Rotation:uncompose(parent)

Finds a rotation that can be composed with parent to yield self. That is to say:

r:uncompose(p):compose(p) == r


>

class SaveLoadGame

This class enables you to save the state of your game to a user's hard drive, and later have that state restored when the user loads the saved game.

Naturally, saving the state of your game is a complex process, and depends heavily on the nature of your game. Thus, this class does not pretend to "just work"; rather, it is a tool for you to implement a save/load feature that is suited for your game.

A saved game consists of two parts; a set of scene elements (SceneObjects, joints, etc.), and a table containing arbitrary data that you can define. Either of these elements can be an empty set, if it is not applicable to your game.

When a game is saved, the scene elements are stored (as they would be when saved from the builder), and the user-defined table will be serialized as well. Of course, complex data structures may not be serialized properly, but anything consisting of primitives- numbers, booleans, strings, etc.- should be fine. Additionally, references to other SceneObjects may be stored in the table, so long as the SceneObjects that are referred to are also provided in the set of scene elements.

When a game is loaded, the stored scene elements will be created and re-inserted into the scene. The stored table will also be read back and provided to you. If the table contained references to SceneObjects, then an effort will be made to preserve those references, so long as said SceneObjects were stored in the saved game or are already in the scene.

Saved games are assigned a 'description' when they are created, and are associated with a particular, named game. The 'name' of a game, as far as the saved game system is concerned, is arbitrary and NOT connected to the name of your Pocket. You may use any name you like to refer to your game. It is conceivable that multiple version of your Pocket, saved under different filenames, may all load and saved games under the same game name. This is intentional.

(It should be noted that saved games are also associated with the user ID of the creator of the Pocket, and therefore your Pockets cannot save games to other user IDs, nor read games saved by other users' Pockets. This restriction will, of course, be modified as the access control system is built out.)

Member functions:

gameList = SaveLoadGame.enumerateSavedGames(gameName)

- gameName: The name of the game to enumerate saved games for. Your pocket
should save and load games using the same gameName parameter.

Enumerates all of the saved games associated with a particular, named game. The return value will be a table, with one entry per saved game found.

Each entry in the table will itself be a table (actually an array) containing the following values:

gameList[1] ... time/date game was saved. gameList[2] ... filename of the saved game (this will be the identifier you pass to subsequently load this game). gameList[3] ... description of the saved game, as provided when the game was saved.


usertable = SaveLoadGame.loadGame(gameName, saveFile)

- gameName: The name of the game that the saved game was associated with.
This is not the same as your pocket's filename; you may choose the gameName arbitrarily, as long as your pocket saves and loads games using the same gameName parameter.
- saveFile: The filename of the saved game. This is NOT the description that
you provided when the game is saved; rather, this is the filename returned in a result from enumerateSavedGames.

Loads a saved game that was saved previously. A saved game is defined as a set of scene elements, and a table containing arbitrary user data.

As a result of loading the saved game, any scene elements (SceneObjects, Joints) that were saved will be re-inserted into your scene. Therefore, caution is advised; any object that was saved should be removed from your live scene before loading a game.

Generally, it is advisable to only save dynamic objects in your saved games, and remove all dynamic objects (leaving only the static scene structure) before loading a game. Of course, your game design will dictate exactly what is appropriate.

The usertable that was included in the saved game will be returned to you after loading the save is complete. The return value will always be a table, even if no usertable was saved (in that case, the return value will be an empty table). If this function returns Nil, then it can be assumed that the load failed. Most likely, this would be because the saveFile parameter is incorrect, or you have used a different gameName parameter between saving and loading.


SaveLoadGame.saveGame(gameName, saveDescription, objects, usertable)

- gameName: The name of the game to associate the saved game with. This is
not the same as your pocket's filename; you may choose the gameName arbitrarily. Your pocket should save and load games using the same gameName parameter.
- saveDescription: A description of the saved game. Normally, you will want
to gather this parameter from your player. This parameter has no functional effect, but will be useful later when your player wants to select a game to load.
- objects: A table of scene elements (SceneObjects, Joints) that will be
saved, to be recreated when the game is loaded. May be an empty table (or Nil, which will be treated the same as an empty table).
- usertable: A table of arbitrary user data that will be saved, and returned
to you when the game is loaded. You may store anything here that you would expect to be able to store in an object property (numbers, strings, other tables, references to SceneObjects, etc.)

Saves the current state of your game to be loaded later. A saved game is defined as a set of scene elements, and a table containing arbitrary user data.

Please see the description of the SaveLoadGame class for a better description of what constitutes a saved game. Essentially, although a saved game does not capture the exact state of your game, you may store a set of scene elements and a set of other important data for later restoration.


>

class SceneManager

Manages the scene by creating and deleting SceneObjects, allowing references to SceneObjects to be retrieved, controlling various scene display options, and controlling the loading and saving of scenes.

Member functions:

SceneManager.addJoint(newJoint)

- newJoint: (Joint) Joint to add to the scene

adds the joint to the scene

DEPRECATED IN V1.5

please use Joint.new() to add joints to the scene


objects = SceneManager.createFromBlueprint(filename)

- objects: (SceneObject array) The objects that were instantiated from the blueprint
- filename: (string) The name of the blueprint to load


newObject = SceneManager.createObject(filename,rotation,position,options...)

- newObject: (SceneObject) The object that is created
- filename: (string or ResourceID) The geometry resource to use as the object's model
- rotation: (Rotation, optional) The initial rotation of the object
- position: (Position, optional) THe initial position of the object
- options: A sequence of strings. Currently, the only option is:
--- "noclass" - Ignore the lua module filename and lua classname specified in the model file.

Instantiates a new scene object from a model. The object is automatically assigned a default name. Initial rotation and position can be specified; if they are not, the object is created at the origin of the scene with the default (axis-aligned) rotation.

If the object has no collision geometry, then the object will be created anchored.


allJoints = SceneManager.getAllJoints()

retrieves an array containing all joints in the scene


allObjects = SceneManager.getAllObjects()

Returns an array of all Scene Objects


color = SceneManager.getBackgroundColor()

Gets the background color of the scene


objects = SceneManager.getByKeyword(keyword)

- objects (SceneObject array): An object with the keyword
- keyword (string): The keyword to find

Retrieves all objects with a specified keyword


camera = SceneManager.getCamera()

- camera: (CameraBoom) The scene's camera

This function returns the current camera. In general, this function is not used; use the Camera class to manipulate the scene's camera rather than accessing the camera object directly

DEPRECATED IN V1.5

please use SceneManager.getCameraBoom()


camera = SceneManager.getCameraBoom()

- camera: (CameraBoom) The scene's camera

This function returns the current cameraBoom. This function is used to get a handle on the camera itself for overriding the Camera class which provides usefull functionality. Use this function along with Camera.setMode("manual") to allow for the direct manipulation of the cameras transform.


filename = SceneManager.getFilename()

Retrieves the filename of the currently-loaded scene, or the empty string if the currently-loaded scene has no name


userpart,filepart,versionpart = SceneManager.getFilenameParsed()

Retrieves the filename of the currently-loaded scene, parsed into its constituent components. If the currently loaded scene is not versioned, the versionpart will be nil.


fps = SceneManager.getFps()

fps: (number) The current framerate, frames per second

Retrieves the current Frames Per Second rate of the scene rendering

DEPRECATED IN V1.5

please use Simulation.getFps()


gravity = SceneManager.getGravity()

- gravity: (Vector) the acceleration due to gravity in the scene

Returns a Vector that describes the acceleration due to gravity in the scene. If using metric units, this acceleration is in meters per second squared (m/s^2). Otherwise, it is in meters per 3600th of a second squared (3600 * m/s^2). In other words, by default, multiply the result of getGravity() by 3600 in order to get the acceleration in m/s^2, unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


height = SceneManager.getGroundPlane()

- height: (number) The height of the ground plane relative to the scene origin

retrieves the z coordinate for the ground plane


object = SceneManager.getObject(name)

- object: (SceneObject) The object to return, or nil if no such object was found
- name: (string) The name of the SceneObject in which we are interested

This function returns a scene object by name


version = SceneManager.getPluginVersion()

Get the plugin version string

DEPRECATED IN V1.5

please use the global function getVersion("family")


property = SceneManager.getProperty(propertyPath)

- property: (anything) The property at that location, or a table of the properties along that branch
- propertyPath: (string) The path to the desired property or property branch

Gets a scene property


module = SceneManager.getScriptModule()

Returns the filename of the module which provides the root script for this scene.


SceneManager:getTargetVersion( ? )

Undocumented method.


username = SceneManager.getUser()

Retrieves the current username


deleted = SceneManager.isDeletedObject(object)

- deleted: (boolean) Returns true if the object has been deleted


SceneManager.removeJoint(toRemove)

- toRemove: (Joint) The joint to remove, which should already exist in the scene

removes the joint from the scene

DEPRECATED IN V1.5

please use the delete(joint) function


filename,status,details = SceneManager.saveToBlueprint(elements,filename,typecheck)

- filename: (string or nil) The filename the blueprint was saved as, or nil if the save failed.
- status: (string) The result of the save. SUCCESS indicates a successful save, other results indicate failure.
- details: (table) Table of detailed information for errors. Different status results will add different information to this table.
- elements: (array) Elements in the scene to save to the blueprint. Blueprints can contain SceneObjects and Joints
- filename: (string) Desired filename for the blueprint
- typecheck: (boolean, optional) If true, blueprint will not be saved if another resource of a different type already exists with the same filename. Defaults to true if not specified.

Creates a new blueprint from one or more scene elements, and saves it to your library


SceneManager.setBackgroundColor(color)

Sets the background color of the scene


SceneManager.setGravity(gravity)

- gravity: (number or Vector) desired acceleration due to gravity in the scene
If gravity is a number, if using metric units, it is interpreted as acceleration along the -z axis. Otherwise, it is along the +z axis. In other words, by default, to set gravity straight down, pass setGravity a single negative number.

Sets the gravity in the scene, which is uniformly applied as a continuous acceleration to all objects, to the input. If using metric units, this acceleration is in meters per second squares (m/s^2). Otherwise, it is in meters per 3600th of a second squared (3600 * m/s^2). In other words, by default, divide your acceleration due to gravity in m/s^2 by 3600 before passing it to setGravity(), unless you have turned on metric units. For example, if you have not turned on metric units, to set the acceleration due to gravity to its approximate Earth value (9.8 m/s^2), call SceneManager.setGravity(-0.0027). See documentation for Simulation.usesMetricUnits() for details.


SceneManager.setGroundPlane(height)

- height: (number) The height of the ground plane relative to the scene origin, in meters

sets the z coord for the ground plane


SceneManager.setProperty(propertyPath, property)

- propertyPath: (string) The path to the desired property location
- property: (property-type) The value of the property, or a table of string-keys mapping to property values

Stores a property in the scene


SceneManager.setScriptModule(module)

- module: (string or Nil) The module which will act as the root script for this scene. Must be a valid filename that represents a Lua script module.

Sets the module that provide the script for this scene.


SceneManager.setTargetVersion(version)

- version: (string or Nil) The desired version of the engine to use as the engine for this pocket

Sets the version of the engine to load this pocket in. Set to the empty string (or Nil) to target the currently running version. Note that changing the version target does not reload the engine; the pocket must be saved and reloaded to use the new target version. Note also that pockets saved with later versions may be incompatible with earlier versions of the engine.


SceneManager.showBones(flag)

Enables or disables joint display


SceneManager.showCollisions(flag)

Enables or disables collision display


>

class SceneObject

An specific object in the scene. SceneObjects are shown in the 3D view and can also physically interact with each other. They may also be members of a class, which extends the methods available to a SceneObject.

Member functions:

SceneObject:__eq(...)

equality test


SceneObject:__le(...)

Less than / equal test


SceneObject:__lt(...)

Less than test


SceneObject:addKeywords(keyword1,keyword2,...)

SceneObject:addKeywords(keywordsTable)

- keyword1: (string) keyword to set
- keywordsTable: (table) list of keyword strings to set

adds a keyword or keywords to an object


SceneObject:animationFade(endWeight,time,channel)

endWeight - The weight to fade to time - how much time in seconds to fade to channel - What channel the animation is playing on (default 1)

Fades the weights of an animation up and down. Default weight is 1, a weight of 0 results in no animation movement. Weights are all compared to other animations currently playing.


SceneObject:animationGetDefault()

Gets the default pose of an object and returns it as a 0 length animation.


SceneObject:applyAngularImpulse(impulse)

- impulse: (Vector) impulse (relative to the global axes) to apply

Applies an instantaneous angular impulse to the object. The angular impulse will instantaneously change the object's angular momentum. If using metric units, this impulse is in Newton meter seconds (N*m*s). Otherwise, it is in units of 60 Newton meter seconds (60 * N*m*s). In other words, by default, divide your angular impulse in N*m*s by 60 before passing it to applyAngularImpulse(), unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyForce(force, position)

- force: (Vector) force to apply over 1 frame
- position: (Vector, optional): location (specified in the global coordinate system) where the force should be applied.
If not specified, force is applied directly to the center of mass of the object

Applies a force at a position on the object relative to the object's center of mass. The force is applied over 1 physics frame (currently 1/240 of a second). This function is designed to apply a force over time. To apply an instantaneous impulse, see documentation for the function SceneObject:applyImpulse(). If using metric units, this force is in Newtons (N). Wild Pockets does not recommend using this function if you have not turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyImpulse(impulse,position)

- impulse: (Vector) impulse to apply
- position: (Vector, optional): location (specified in the global coordinate system) where the impulse should be applied.
If not specified, impulse is applied directly to the center of mass of the object

Applies an instantaneous impulse to the object at a position relative to the object' center of mass. The impulse will instantaneously change the object's momentum. If using metric units, this impulse is in Newton seconds (N*s). Otherwise, it is in units of 60 Newton seconds (60 * N*s). In other words, by default, divide your impulse in N*s by 60 before passing it to applyImpulse(), unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyRelAngularImpulse(impulse)

- impulse: (Vector) impulse (relative to the object's axes) to apply

Applies an instantaneous angular impulse to the object. The angular impulse will instantaneously change the object's angular momentum. If using metric units, this impulse is in Newton meter seconds (N*m*s). Otherwise, it is in units of 60 Newton meter seconds (60 * N*m*s). In other words, by default, divide your angular impulse in N*m*s by 60 before passing it to applyRelAngularImpulse(), unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyRelForce(force, position)

- force: (Vector) force to apply over 1 frame
- position: (Vector, optional): location (specified in the object's coordinate system) where the force should be applied.
If not specified, force is applied directly to the center of mass of the object

Applies a force at a position on the object relative to the object's center of mass. The force is applied over 1 physics frame (currently 1/240 of a second). This function is designed to apply a force over time. To apply an instantaneous impulse, see documentation for the function SceneObject:applyRelImpulse(). If using metric units, this force is in Newtons (N). Wild Pockets does not recommend using this function if you have not turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyRelHeadingTorque(torque)

- torque: (number) Torque to apply

Applies a torque around the object's local Z axis


SceneObject:applyRelImpulse(impulse,position)

- impulse: (Vector) impulse to apply
- position: (Vector, optional): location (specified in the object's coordinate system) where the impulse should be applied.
If not specified, impulse is applied directly to the center of mass of the object

Applies an instantaneous impulse to the object at a position relative to the object' center of mass. The impulse will instantaneously change the object's momentum. If using metric units, this impulse is in Newton seconds (N*s). Otherwise, it is in units of 60 Newton seconds (60 * N*s). In other words, by default, divide your impulse in N*s by 60 before passing it to applyRelImpulse(), unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyRelPitchTorque(torque)

- torque: (number) Torque to apply

Applies a torque around the object's local X axis


SceneObject:applyRelRollTorque(torque)

- torque: (number) Torque to apply

Applys a Torque to an object's local Y Axis


SceneObject:applyRelTorque(force)

- force: (Vector) torque (relative to the object's axes) to apply over 1 frame

Applies a torque to the object. The torque is applied over 1 physics frame (currently 1/240 of a second). This function is designed to apply a torque over time. To apply an instantaneous angular impulse, see documentation for the function SceneObject:applyRelAngularImpulse(). If using metric units, this force is in Newton meters (N*m). Wild Pockets does not recommend using this function if you have not turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:applyTorque(force)

- force: (Vector) torque (relative to the global axes) to apply over 1 frame

Applies a torque to the object. The torque is applied over 1 physics frame (currently 1/240 of a second). This function is designed to apply a torque over time. To apply an instantaneous angular impulse, see documentation for the function SceneObject:applyAngularImpulse(). If using metric units, this force is in Newton meters (N*m). Wild Pockets does not recommend using this function if you have not turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:clearKeyword(keyword)

- keyword: (string) The keyword to clear

Clears a keyword on the object

DEPRECATED IN V1.5

please use SceneObject:removeKeywords()"


SceneObject:clearParticleSystem()

Clears the scene object's particle system effect.

DEPRECATED IN V1.5

please use SceneObject:setParticleSystem(nil)


newObject = SceneObject:clone(location)

- newObject: (SceneObject) The new object, which is a duplicate of this object
- location : (Vector, optional) Location to create the object. If not specified,
the object will be created in the same place as this object

Clones an object, creating an identical copy.


distance = SceneObject:distance(point)

The distance operator can compute the distance between any two objects: they can be scene objects, cameras, transforms, or just points specified as vectors.


channels = SceneObject:getAllAnimations()

channels - table of all channels of animations currently playing in any way

Returns a list of all animations playing in a table. Usefull for looping through.


SceneObject:getAllKeywords( ? )

Undocumented method.


flag = SceneObject:getAlphaTestMode(mesh)

Returns True if AlphaTestMode is enabled

- mesh: (string) Name of the mesh to look up

Raises an exception if no mesh with a given name exists


anchored = SceneObject:getAnchored()

- anchored: (boolean) Returns the anchored property

Returns the current anchored state. The anchored property locks an object's orientation in space. The object will still collide with other objects, but collision will not move this object.


angularVelocity = SceneObject:getAngularVelocity()

- angularVelocity: (Vector) the object's angular velocity around the
x, y, an z axes of the world coordinate system

Gets the object's angular velocity. If using metric units, this velocity is in radians per second (rad/s). Otherwise, it is in radians per 60th of a second (60 * rad/s). In other words, by default, multiply the result of getAngularVelocity() by 60 in order to get the angular velocity in rad/s, unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


table = SceneObject:getAnimationInfo(channel)

channel - defaults to 1

table contains{
- speed: (number) Playback speed relative to the animation's recorded speed. 1 is 100% speed, 2 is 200%, .5 is 50%
- start: (number) Start time, in seconds.
- stop: (number) Stop time, in seconds.
- time: (number) Initialization time, in seconds. If the animation is looping, the first cycle will start at this time. Otherwise, this option will override 'start'.
- loop: (boolean) if true, animation will loop once it reaches the end. If false, animation will play once.
- callback: (function ()) Function to be called when the animation completes a cycle.
- callTime: (number) The amount of time before the end of the animation that the callback is called (default 0)
- prePad: (number) Seconds to stay on the first frame of the animation before starting to play (default 0)
- postPad: (number) Seconds to stay on the last frame of the animation after playing the full animation (default 0) (has no effect when loop = true)
- fadeInTime: (number) Seconds including prePad to fade the weight from 0 to the set weight. (default 0)
- fadeOutTime: (number) Seconds before the end, including postPad, to start fading from the set weight to 0 (default 0)
- weight: (number 0.0-1.0) The weight as compared to other animations currently playing on different channels. (default 1)
} Returns data about the animation on a given channel


loop = SceneObject:getAnimationLoop(channel)

- loop: (boolean) If true, animation should loop when it reaches the end
- channel: (number, optional) The channel to loop. If uspecified, channel 1 is set to loop.

Sets the animation to loop when it reaches the end of its timeline.


speed = SceneObject:getAnimationSpeed(channel)

- speed: (boolean) If true, animation should loop when it reaches the end
- channel: (number, optional) The channel to loop. If uspecified, channel 1 is set to loop.

Sets the animation to loop when it reaches the end of its timeline.


attachedJoints = SceneObject:getAttachedJoints(toObject)

- attachedJoints: (Joint array) All the joints attached to this object
- toObject: (SceneObject, optional) If specified, acts as a filter on
the joint list; only the joints going from this object to toObject will be returned. If omitted, all joints will be returned

Retrieves all the joints attached to the object


attachedObjects = SceneObject:getAttachedObjects()

- attachedObjects: (SceneObject array) The objects attached to this object via joints

returns a list of objects that are attached via joints


flag = SceneObject:getAutoCalculateInertia()

Retrieves the inertia auto-calcuation flag. If true, inertia is calculated from the collision volumes. If false, the collision arms are used to determine the inertia of the object.


avatar = SceneObject:getAvatar()

- avatar: (boolean) Value of the avatar flag

Brief : Gets the avatar property

Gets the avatar property. The avatar property is reserved for future development.


r,f,u,l,b,d = SceneObject:getAxes()

Get the object's local direction vectors. Returns six values:

* positive x axis (the 'right' vector)
* positive y axis (the 'forward' vector)
* positive z axis (the 'up' vector)
* negative x axis (the 'left' vector)
* negative y axis (the 'backward' vector)
* negative z axis (the 'down' vector)


vec = SceneObject:getBackwardVector()

Returns a vector that points backward out of the rear of the character's head. The backward vector is equal to the character's local negative Y-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


names = SceneObject:getBoneNames()

- names: (string array) The names of all the bones in the SceneObject's model

Retrieves all bone names.


parent = SceneObject:getBoneParent(name)

- name: Name of the bone

Returns the name of the bone's parent in the bone hierarchy. If the bone is the root bone, returns nil.


position = SceneObject:getBonePosition(name)

- position: (Vector) Position of the bone relative to the parent bone
- name: (string) Name of the bone

Retrieves the position of the named bone relative to its parent bone.


rotation = SceneObject:getBoneRotation(name)

- rotation: (Rotation) Rotation of the bone relative to its parent bone
- name: (string) Name of the bone

Retrieves the rotation of the named bone


scale = SceneObject:getBoneScale(name)

- scale: (Vector) Scale of the bone
- name: (string) Name of the bone

Retrieves the scale of the named bone


transform = SceneObject:getBoneTransform(name [, status [, frame]])

- name: Name of the bone
- status: either 'current' or 'original'
- frame: Frame of reference - 'world', 'model', or 'parent'

The frame can be any of the following strings:


- world - return absolute world-space transform of bone
- model - return transform of bone relative to the scene object
- parent - return transform of bone relative to parent bone

The status can be either the string 'current' or the string 'original'. Returns either the current position of the bone, or the original position of the bone as it was before any animations were played.

Default status is 'current'. Default frame is 'world'.


bounce = SceneObject:getBounciness()

- bounce: (number) The bounciness of the object

Gets the bounciness of the object. See SceneObject:setBounciness for more information on the meaning of bounciness in the physics simulation.


min,max = SceneObject:getBounds()

Gets the inital (unscaled) bounds of the object as two vectors (min and max)


flag = SceneObject:getBuildAnchored()

- flag: (boolean) if true, object becomes anchored in build mode only

This will only anchor an object if the scene is loaded in the builder. It will do nothing during normal game play.


transform = SceneObject:getCanonicalAggregateTransform(name)

- name: (string) Name of the bone

Retrieves the named bone's initial transform relative to the model's root


transfrom = SceneObject:getCanonicalRelativeTransform(name)

- name: (string) Name of the bone

Retrieves the named bone's initial transform relative to its parent bone


casts = SceneObject:getCastsShadow()

- casts: (boolean) If true, object casts a shadow

Retrieves the flag that controls shadow-casting. If true, the object casts a shadow


centerOfMass = SceneObject:getCenterOfMass()

-centerOfMass (Vector): The center of mass position relative to the center of the model

retrieves an object's center of mass, expressed as a position relative to the center of the model.


objlist = SceneObject:getCloseObjects([cutoff])

- cutoff: (number) The maximum distance to return objects from
- objlist: (table) Returns a table with keys "object","objects","distance","distances"

Returns a table with the closest object stored in key "object" and the distance to that object in key "distance". Also returns an array of all objects that are within the cutoff distance under the keys "objects" and "distances".


collidable = SceneObject:getCollidable()

Returns true if the object is collidable


color = SceneObject:getColor()

- color: (Color) The tinting color of the object

Returns the tint of the object.


direction = SceneObject:getCompassDirection([frame_of_reference])

Get the compass direction in which the object is facing. The return value is a string, one of: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE If the object's orientation is not exactly in one of these sixteen directions, it will approximate.


transform = SceneObject:getCurrentAggregateTransform(name)

- name: (string) Name of the bone

Retrieves the named bone's transform relative to the model's root


transform = SceneObject:getCurrentRelativeTransform(name)

- name: (string) Name of the bone

Retrieves the named bone's transform relative to its parent bone


filename = SceneObject:getDefaultTexture(index)

Retrieves the default texture as specified in the object's model for a given texture index.


amount = SceneObject:getDepth()

- amount: (number) The depth of the object in meters

Retrieves the current visual depth of the object (note: for animated models, this is the depth of the initial pose)


vec = SceneObject:getDownVector()

Returns a vector that points downward out of the bottom the character's feet. The down vector is equal to the character's local negative Z-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


enabled = SceneObject:getEnabled()

Returns true if the object is enabled in the physics simulation.

When objects are unmoving and undisturbed for a period of time, they become disabled in the physics simulation and will not move without being touched by another object. Use getEnabled to test whether an object is enabled in the physics simulation.


filename = SceneObject:getFilename()

Returns the filename associated with this scene object's model.


vec = SceneObject:getForwardVector()

Returns a vector that points forward out of the tip of the character's nose. The forward vector is equal to the character's local positive Y-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


heading,pitch,roll = SceneObject:getHPR([frame_of_reference])

Returns the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


heading = SceneObject:getHeading([frame_of_reference])

Returns the object's heading, where 0 is north, 90 is west, 180 is south, and 270 is east.


height = SceneObject:getHeight()

- height: (number) The height of the object in meters

Returns the height of the object. (Note: for animated models this is the initial height and not the current height)


armLengths = SceneObject:getInertiaArms()

- armLengths (Vector): The lengths of the X, Y, and Z arms

Retrieves the length of the 'arms' of the inertia model. See the documentation of setInertiaArms for more information.


rotation = SceneObject:getInertiaRotation()

Retrieves the rotation of the inertia arms relative to the model's principal axes


amount = SceneObject:getInitialDepth()

- amount: (number) The unscaled depth of the object in meters

Retrieves the unscaled depth of the object (note: for animated models, this is the depth of the initial pose)


amount = SceneObject:getInitialHeight()

- amount: (number) The unscaled height of the object in meters

Retrieves the unscaled height of the object (note: for animated models, this is the height of the initial pose)


amount = SceneObject:getInitialWidth()

- amount: (number) The unscaled width of the object in meters

Retrieves the unscaled width of the object (note: for animated models, this is the width of the initial pose)


vec = SceneObject:getLeftVector()

Returns a vector that points left out of the character's left shoulder. The left vector is equal to the character's local negative X-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


flag = SceneObject:getLightingEnable()

Returns true if lights should be applied to this object

DEPRECATED IN V1.5

please use sceneObject:getLightingEnabled()


flag = SceneObject:getLightingEnabled()

Returns true if lights should be applied to this object


lock = SceneObject:getLockX()

returns true if the objects movement is locked to X. Locked objects act like anchored objects but only in one dimension.

Note: an anchored object is not nececarily locked in XYZ.


lock = SceneObject:getLockY()

returns true if the objects movement is locked to Y. Locked objects act like anchored objects but only in one dimension.

Note: an anchored object is not nececarily locked in XYZ.


lock = SceneObject:getLockZ()

returns true if the objects movement is locked to Z. Locked objects act like anchored objects but only in one dimension.

Note: an anchored object is not nececarily locked in XYZ.


mass = SceneObject:getMass()

- mass: (number) mass, in kilograms

Retrieves the mass of the object


color = SceneObject:getMeshColor(mesh_name)

- mesh_name: (string) Name of the mesh to look up

Returns the color tint of the targeted mesh, or -1 if mesh_name doesn't correspond to a mesh.


meshCount = SceneObject:getMeshCount()

Retrieves the number of meshes in this object's model


SceneObject:getMeshMode(mesh)

Returns the string corresponding to the desired mesh mode

- mesh: (string) Name of the mesh to look up

Raises an exception if no mesh with a given name exists


SceneObject:getMeshes()

Returns a list of names of meshes used in this scene object.


name = SceneObject:getName()

- name: (string) Returns the object's name

Returns the object's name


count = SceneObject:getPolyCount()

Retrieves the number of triangles in this object


position = SceneObject:getPosition([frame_of_reference])

Get the position.


value = SceneObject:getProperty(key)

- value: (anything) Property value or a table of all the properties at this branch
- key: (string) The path to the property or property branch to retrieve

Retrieves a property from the object.


classname = SceneObject:getRecommendedScriptClassname()

Retrieves the name of the class recommended by the modeler for this object


filename = SceneObject:getRecommendedScriptFilename()

Retrieves the filename of the class recommended by the modeler for this object


relangularVelocity = SceneObject:getRelAngularVelocity()

- relangularVelocity: (Vector3d) The Objects angular velocity in relative coordinates to the current rotation of the object.

Gets the Objects angular velocity in relative coordinates to the current rotation of the object.


relVelocity = SceneObject:getRelVelocity()

- relVelocity: (Vector3d) The Objects velocity in relative coordinates to the current rotation of the object.

Gets the Objects velocity in relative coordinates to the current rotation of the object.


vec = SceneObject:getRightVector()

Returns a vector that points right out of the character's right shoulder. The right vector is equal to the character's local positive X-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


position = SceneObject:getRotation([frame_of_reference])

Get the rotation.


anchored = SceneObject:getRotationLock()

anchored -- string (\"none\", \"x\", \"y\", \"z\", \"all\")

returns a string representing what rotation lock is applied to the SceneObject


savable = SceneObject:getSavable()

- savable: (boolean) The flag value

Brief : Gets the savable property

Returns the current value of the savable property. Savable is a boolean flag that determines if the object is saved by SceneManager's scene-saving operations.


position = SceneObject:getScale()

Get the scale.


sx = SceneObject:getScaleX()

Returns the X-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


sx,sy,sz = SceneObject.getScaleXYZ()

Returns the X, Y, Z scale of the object as three values. It is also possible to obtain the scale as a single vector object by calling getScale instead.

DEPRECATED IN V1.5

please use Transform.getScale()


sy = SceneObject:getScaleY()

Returns the Y-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


sz = SceneObject:getScaleZ()

Returns the Z-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


module_or_classobject_or_nil, classname = SceneObject:getScriptClass()

Returns the class that has been assigned to this SceneObject.

The data that this function returns will vary depending on what method was used to set the class in the first place. See the documentation for setScriptClass() for more details on how the class can be set.

FORM 1: The class of an object has been set to a reference to a class in a Lua file. In this case, the return value will be two strings. The first string will be the filename that contains the class. The second string will be the name of the class.

FORM 2: The class of an object has been set directly to a Class object. In this case, there will be only one return value, and it will be said Class object.

FORM 3: The class of an object is not set. In this case, there will be two return values, and they will both be nil (the pair of nils is for backwards compatibility).

If you are unsure which of the three results to expect, you should capture two results, and test the first to see if it is a string, a table, or nil; for example:

r1,r2 = myobj:getScriptClass() if type(r1) == 'string' then
-- form 1
elseif type(r1) == 'table' then
-- form 2
else
-- form 3
end


flag = SceneObject:getStandardMode(mesh)

Returns True if StandardMode is enabled

- mesh: (string) Name of the mesh to look up

Raises an exception if no mesh with a given name exists


isStashed = SceneObject:getStashed()

- isStashed (boolean): Returns whether the object was stashed

Brief : Gets the stashed property

This function is buggy and is scheduled to be fixed later, use at your own risk.

Returns whether an object is stashed. Stashed objects are not rendered.


bounce = SceneObject:getSurfaceBounce()

Retrieves the 'surface bounce' value, which has no effect on the simulation.

DEPRECATED in v1.5

Use SceneObject:getBounciness insteaed


mu = SceneObject:getSurfaceMu()

- mu: (number) Mu value of the object

Gets the mu value (friction constant) for the object


texture = SceneObject:getTexture(slot)

- texture: (ResourceID or string) The texture, as either the ResourceID or a filename
- slot: (number) The slot to retrieve

Retrieves the texture at a given slot. Slots range from 1 to the number of textures on an object.


transform = SceneObject:getTransform()

- transform: (Transform) The object's transform in world coordinates

Gets the object's transform


vec = SceneObject:getUpVector()

Returns a vector that points upward out of the top of the character's head. The up vector is equal to the character's local positive Z-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


velocity = SceneObject:getVelocity()

- velocity: (Vector) the object's velocity

Gets the object's velocity. If using metric units, this velocity is in meters per second (m/s). Otherwise, it is in meters per 60th of a second (60 * m/s). In other words, by default, multiply the result of getVelocity() by 60 in order to get the velocity in m/s, unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


xcoord = SceneObject:getVelocityX()

- xcoord: (number) The X coordinate of the object's velocity

Gets the X coordinate of the object's velocity


ycoord = SceneObject:getVelocityY()

- ycoord: (number) The Y coordinate of the object's velocity

Gets the Y coordinate of the object's velocity


zcoord = SceneObject:getVelocityZ()

- zcoord: (number) The Z coordinate of the object's velocity

Gets the Z coordinate of the object's velocity


count = SceneObject:getVertexCount()

Retrieves the number of verticies in this object


weightless = SceneObject:getWeightless()

- weightless: (boolean) Returns whether the object is weightless

Brief : Gets the weightless property

Returns the current value of the weighless property. The weightless property, if set, blocks the effects of gravity on the object.


amount = SceneObject:getWidth()

- amount: (number) The width of the object in meters

Retrieves the current visual width of the object (note: for animated models, this is the width of the initial pose)


flag = SceneObject:getWireframeMode(mesh)

Returns True if WireframeMode is enabled

- mesh: (string) Name of the mesh to look up

Raises an exception if no mesh with a given name exists


X = SceneObject:getX([frame_of_reference])

Get the X-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


length = SceneObject:getXLength()

Gets the unscaled, unanimated length of the object in the x-axis


x,y,z = SceneObject.getXYZ([frame_of_reference])

Returns the X, Y, Z position of the object as three values. It is also possible to obtain the position as a single vector object by calling getPosition instead.

DEPRECATED IN V1.5

please use Transform.getPosition()


Y = SceneObject:getY([frame_of_reference])

Get the Y-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


length = SceneObject:getYLength()

Gets the unscaled, unanimated length of the object in the y-axis


Z = SceneObject:getZ([frame_of_reference])

Get the Z-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


length = SceneObject:getZLength()

Gets the unscaled, unanimated length of the object in the z-axis


flag = SceneObject:hasKeyword(keyword)

- flag: (boolean) If true, object has the specified keyword
- keyword: (string) Keyword to check

If the result is true, the object has the specified keyword


SceneObject:hide()

Makes the object stashed. Stashed objects are not rendered.

This function is buggy and is scheduled to be fixed later, use at your own risk.

DEPRECATED IN V1.5

please use SceneObject:setStashed(true)


SceneObject:highlight(color)

- color: (Color) The color to use to highlight the object

set to nil to clear the highlight

Highlights the object with a specified color. This is different from tinting with setColor because highlights are not saved.


anchored = SceneObject:isAnchored(flag)

- anchored: (boolean) Returns the anchored property
- flag: (boolean, optional) Sets the anchored states

When passed a boolean, sets the anchored property. Otherwise returns the current anchored state. The anchored property locks an object's orientation in space. The object will still collide with other objects, but collision will not move this object.

DEPRECATED IN V1.5

please use either SceneObject:getAnchored() or SceneObject:setAnchored()


playing = SceneObject:isAnimationPlaying(channel)

- playing: (boolean) If true, the animation is currently playing.
- channel: (number, optional) The channel to check. If uspecified, channel 1 is checked.

Checks whether an animation is playing on the specified channel.


avatar = SceneObject:isAvatar(avatar)

- avatar: (boolean) Value of the avatar flag
- avatar: (boolean) Value of the avatar flag

Brief : Gets or sets the avatar property

If no argument is provided, gets the avatar property. Otherwise, sets the avatar property. The avatar property is reserved for future development.

DEPRECATED IN V1.5

please use SceneObject:setAvatar(), and SceneObject:getAvatar()


savable = SceneObject:isSavable(savable)

- savable: (boolean) The flag value
- savable: (boolean) The flag value

Brief : Gets or sets the savable property

If an argument is provided, sets the object's savable property to the value provided. Otherwise, returns the current value of the savable property. Savable is a boolean flag that determines if the object is saved by SceneManager's scene-saving operations.

DEPRECATED IN V1.5

please use SceneObject:setSavable, and getSavable


isStashed = SceneObject:isStashed(flag)

- isStashed (boolean): Returns whether the object was stashed
- flag (boolean, optional): Sets whether the object is stashed

Brief : Gets or sets the stashed property

This function is buggy and is scheduled to be fixed later, use at your own risk.

Sets (and retrieves) whether an object is stashed. Stashed objects are not rendered.

DEPRECATED IN V1.5

please use SceneObject:setStashed() and SceneObject:getStashed()


flag = SceneObject:isValidMesh(mesh)

- mesh: (string) The name of the mesh to check
- flag: (boolean) returns true if the name is a valid mesh object


weightless = SceneObject:isWeightless(weightless)

- weightless: (boolean) Returns whether the object is weightless
- weightless: (boolean) Sets whether the object is weightless

Brief : Gets or sets the weightless property

If an argument is provided, sets the weightless property. Otherwise, returns the current value of the property. The weightless property, if set, blocks the effects of gravity on the object.

DEPRECATED IN V1.5

please use setWeightless, and getWeightless


newPath = SceneObject:makePath()

- newPath (Path): A path object that will affect this SceneObject

Creates a new Path that targets this object. The Path can then be changed, and when executed with Path:go() it will cause this object to move.


system = SceneObject:particles()

system: (ParticleSystem) The particle system attached to this object

Gets a handle to the scene object's particle system effect.


SceneObject:passThrough()

Can only be used inside a collision handler for this object. Directs the physics engine to cause the two objects to pass through each other for this frame. Objects that are passing through each other may still trigger collision handlers but do not interact physically, such as rebounding off of each other


SceneObject:pathToAxis(mode, vector)

Rotates the object to cause one axis of the object to align with the specified vector. Mode is a string, one of the following:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


SceneObject:pathToAxisAngle(axis, angle)

Rotates an object about an arbitrary (axis) by (angle)


SceneObject:pathToCompassDirection(direction [, frame_of_reference])

Set the compass direction in which the object is facing. The parameter must be a string, one of the following: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE.


SceneObject:pathToForwardVector(direction [, up] [, frame_of_reference])

Look in the specified direction. The direction must be a vector. The object is also made upright, insofar as possible subject to the constraint that it be looking in the specified direction. You can specify an optional up-vector.


SceneObject:pathToHPR(heading, pitch, roll [, frame_of_reference])

Sets the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


SceneObject:pathToHeading(heading [, frame_of_reference])

Causes the object to face in the given heading, where 0 is north, 90 is west, 180 is south, and 270 is east. In addition, the object is made upright.


SceneObject:pathToLookAt(otherobject)

Causes this object to look at (point toward) the other object. The other object can be a scene object, a transform, or a point in the form of a vector.


SceneObject:pathToPosition(x,y,z [, frame_of_reference])

Sets the position. The parameter is either a vector or three numbers.


SceneObject:pathToRotation(rotation [, frame_of_reference])

Sets the rotation. The parameter is a rotation object, typically constructed using Rotation.new or the like.


SceneObject:pathToScale(x,y,z)

Sets the scale. The parameter is either a vector or three numbers.


SceneObject:pathToScaleX(x)

Sets the X-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


SceneObject:pathToScaleXYZ(x,y,z)

Sets the scale.

DEPRECATED IN V1.5

please use Transform.setScale()


SceneObject:pathToScaleY(y)

Sets the Y-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


SceneObject:pathToScaleZ(z)

Sets the Z-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


SceneObject:pathToTransform(transform [, frame_of_reference])

Sets the entire transform.


SceneObject:pathToUpright([frame_of_reference])

Causes the object to upright itself - In other words, the object's local Z-axis is aligned with the world's Z-axis. If possible, the object's heading is not lost.


SceneObject:pathToX(x [, frame_of_reference])

Sets the X-component of the position. It may be more convenient to set all three using setXYZ.


SceneObject:pathToXYZ(x,y,z [, frame_of_reference])

Sets the position.

DEPRECATED IN V1.5

please use Transform:setPosition()


SceneObject:pathToY(y [, frame_of_reference])

Sets the Y-component of the position. It may be more convenient to set all three using setXYZ.


SceneObject:pathToZ(z [, frame_of_reference])

Sets the Z-component of the position. It may be more convenient to set all three using setXYZ.


SceneObject:playAnimation(animation,{speed (optional), channel (optional), uniqueChannel(optional), start (optional), stop (optional), time (optional), loop (optional), callback (optional), prePad (optional), postPad (optional), fadeInTime (optional), fadeOutTime (optional), weight (optional) } (optional) )

- animation: (Animation) The animation to play
- speed: (number) Playback speed relative to the animation's recorded speed. 1 is 100% speed, 2 is 200%, .5 is 50%
- channel: (number/string) Playback channel. Animations in different channels may be played simultaneously, animation blending will average between them if they touch the same bones.
- uniqueChannel: (boolean) if set to true it will create a random channel and not set channel to 1. (Overridden if channel is set)
- start: (number) Start time, in seconds.
- stop: (number) Stop time, in seconds.
- time: (number) Initialization time, in seconds. If the animation is looping, the first cycle will start at this time. Otherwise, this option will override 'start'.
- loop: (boolean) if true, animation will loop once it reaches the end. If false, animation will play once.
- callback: (function ()) Function to be called when the animation completes a cycle.
- callTime: (number) The amount of time before the end of the animation that the callback is called (default 0)
- prePad: (number) Seconds to stay on the first frame of the animation before starting to play (default 0)
- postPad: (number) Seconds to stay on the last frame of the animation after playing the full animation (default 0) (has no effect when loop = true)
- fadeInTime: (number) Seconds including prePad to fade the weight from 0 to the set weight. (default 0)
- fadeOutTime: (number) Seconds before the end, including postPad, to start fading from the set weight to 0 (default 0)
- fadeAll: (boolean) if set to true fades all other animations out and then back in again (default 0)
- weight: (number 0.0-1.0) The weight as compared to other animations currently playing on different channels. (default 1)

Plays an animation on the object. Several parameters can be specified to control the animation. Normally, the animation will play until it completes. The loop argument may be specified to continue playback. The speed argument can be used to adjust the speed of the animation. A speed of 1 is the default speed of the animation, 2 is twice as fast, .5 is half as fast. If a negative speed is specified, the animation will play in reverse (and either stop or loop when it reaches the 'start' time).

Animation blending allows multiple animations to be played simultaniously and the engine averages between the two of them based on their given weights. This allows one animation to be faded out while another is faded in and a semless transition to be seen between them.


SceneObject:pose(animation,time,boneNames)

- animation: (Animation) The animation to use for the pose information
- time: (number) The time (in seconds)within the animation to use as the bone
position information
- boneNames: (string array, optional) If specified, only the bones with names matching
the names in the array will be used. If omitted, all bones will be used

Poses a model via an animation at a specified time


SceneObject:removeCollisionHandler()

Cancels the effect of any previous calls to 'setCollisionHandler'

DEPRECATED IN V1.5

please use SceneObject:setCollisionHandler(nil)


SceneObject:removeHighlight()

turns the highlight for this object off

DEPRECATED IN V1.5

please use SceneObject:highlight(nil)


SceneObject:removeKeywords(keyword1,keyword2,...)

SceneObject:removeKeywords(keywordsTable)

- keyword1: (string) keyword to set
- keywordsTable: (table) list of keyword strings to set

Removes these keywords from an object


SceneObject:replaceModel(newModel)

- newModel: (string or SceneObject) Either the filename of a model file,
or another SceneObject that is using the desired model

Replaces the model on this SceneObject with a new model, retaining other properties of the SceneObject.


SceneObject:resetBone(name)

- name: (string) Name of the bone

Sets the bone to its canonical orientation.


SceneObject:resetBones()

Sets all bones to their canonical orientations.


SceneObject:rotateAboutAxis(axis, angle)

Rotates an object about an arbitrary (axis) by (angle)


SceneObject:setAllKeywords(keyword1,keyword2,...)

SceneObject:setAllKeywords(keywordsTable)

- keyword1: (string) keyword to set
- keywordsTable: (table) list of keyword strings to set

Sets the entire keyword table on an object. Replacing all other keywords.


SceneObject:setAlphaTestMode(mesh)

- mesh: (string) Name of the mesh to enable alpha test on

Raises an exception if no mesh with the given name exists


SceneObject:setAnchored(anchored)

- anchored: (boolean) Sets the anchored states

When passed a boolean, sets the anchored property. The anchored property locks an object's orientation in space. The object will still collide with other objects, but collision will not move this object.


SceneObject:setAngularVelocity(angularVelocity)

- angularVelocity: (Vector) desired rotational velocity around the
x, y, and z axes of the world coordinate system

Sets the object's angular velocity to the input. If using metric units, this velocity is in degrees per second (deg/s). Otherwise, it is in radians per 60th of a second (60 * rad/s). In other words, by default, divide your angular velocity in rad/s by 60 before passing it to setAngularVelocity(), unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:setAnimationLoop(flag,channel)

- loop: (boolean) If true, animation should loop when it reaches the end
- channel: (number, optional) The channel to loop. If uspecified, channel 1 is set to loop.

Sets the animation to loop when it reaches the end of its timeline.


SceneObject:setAnimationSpeed(speed,channel)

- speed: (number) The rate to play the animation.
- channel: (number, optional) The channel to loop. If uspecified, channel 1's speed is set.

Sets the play rate of the animation. 1 is the original rate; 2 is twice as fast, 0.5 is half as fast.


SceneObject:setAutoCalculateInertia(flag)

Sets the inertia auto-calcuation flag. If true, inertia is calculated from the collision volumes. If false, the collision arms are used to determine the inertia of the object.


SceneObject:setAvatar(avatar)

- avatar: (boolean) Value of the avatar flag

Brief : Sets the avatar property

Sets the avatar property. The avatar property is reserved for future development.


SceneObject:setAxis(mode, vector)

Rotates the object to cause one axis of the object to align with the specified vector. Mode is a string, one of the following:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


SceneObject:setBonePosition(name,position)

- name: (string) Name of the bone
- position: (Vector) Position of the bone relative to the parent bone

Sets the position of the named bone relative to its parent bone


SceneObject:setBoneRotation(name,rotation)

- name: (string) Name of the bone
- rotation: (Rotation) Rotation of the bone relative to its parent bone

Sets the rotation of the named bone relative to its parent bone


SceneObject:setBoneScale(name,scale)

- name: (string) Name of the bone
- scale: (Vector) Scale of the bone

Sets the scale of the named bone


SceneObject:setBounciness(bounce)

- bounce: (number) The bounce value of the object, or nil

Sets the bounciness of the object, which is roughly equal to the percentage of the object's kinetic energy that is returned to it on a collision. Set the value to 1 for fully elastic behavior; set it to 0 for fully inelastic behavior. If two objects collide that both have a value set, the amount of energy returned to both is the average of their bounciness.

Bounciness can also be set to nil, in which case the behavior in a collision is dependent upon the other object. If an object with bounciness collides with an object without, the bounciness value of that object is used as the bounciness of the collision. If both objects have nil bounciness, the collision acts as if the bounciness is 0.

NOTE 1: "Bounciness" and "elasticity" aren't exactly the same concept; two objects with 0 bounciness that collide will still have enough force applied to them to stop them from interpenetrating, not 0 force.

NOTE 2: Setting bounce to a number greater than 1 will cause energy to be added on collision. This can be used for interesting effects, but is usually undesirable.


SceneObject:setBuildAnchored(flag)

- flag: (boolean) if true, object becomes anchored in build mode only

This will return if the object is anchored in the builder. It will do nothing during normal game play.


SceneObject:setCastsShadow(cast)

- cast: (boolean) If true, object should cast shadow

Sets the shadow-casting flag. If true, object drops a circular shadow along the z-axis to an object below it.


SceneObject:setCenterOfMass(centerOfMassPosition)

-centerOfMassPosition (Vector): The new center of mass position relative to the center of the model

Sets an object's center of mass to a position relative to the center of the object's model.


SceneObject:setCollidable(value)

- value: (boolean) Sets whether or not the object collides with other objects

Set whether this object can collide with other objects. Objects that cannot collide are faster to calculate each frame.


SceneObject:setCollisionHandler(fn)

- fn: (function) A collision handler function, which accepts three arguments (nil clears the handler)

set to nil to clear the collision handler

Sets a collision handler function for this scene object. the function must accept three arguments: self, other, and mode. Self will point the first object in the collision. Other will point to the second object in the collision. Mode will be 'start', 'continue', or 'end'. For an explanation of these modes, see the manual on collision handling.

Side Note: Collisions with the ground plane will not trigger a collision event. This is due to the ground plane being a special case object that acts slightly different than all other objects.


SceneObject:setColor(color)

- color: (Color) The color to tint the object

Sets the object's tint


SceneObject:setCompassDirection(direction [, frame_of_reference])

Set the compass direction in which the object is facing. The parameter must be a string, one of the following: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE.


SceneObject:setDepth(amount,maintainAspect)

- amount: (number) The new depth of the object in meters
- maintainAspect: (boolean) If true or nil will stretch the Height and Width to maintain 1:1 aspect ratio

Sets the scale of the object to make it the depth specified. (Note: for animated models, this sets the initial depth before animation.)


SceneObject:setEnabled(enabled)

When objects are unmoving and undisturbed for a period of time, they become disabled in the physics simulation and will not move without being touched by another object. Use setEnabled to re-enable them in the physics simulation manually.


SceneObject:setForwardVector(direction [, up] [, frame_of_reference])

Look in the specified direction. The direction must be a vector. The object is also made upright, insofar as possible subject to the constraint that it be looking in the specified direction. You can specify an optional up-vector.


SceneObject:setHPR(heading, pitch, roll [, frame_of_reference])

Sets the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


SceneObject:setHeading(heading [, frame_of_reference])

Causes the object to face in the given heading, where 0 is north, 90 is west, 180 is south, and 270 is east. In addition, the object is made upright.


SceneObject:setHeight(amount,maintainAspect)

- amount: (number) The new height of the object in meters
- maintainAspect: (boolean) If true or nil will stretch the Width and Depth to maintain 1:1 aspect ratio

Sets the scale of the object to make it the height specified. (Note: for animated models, this sets the initial height before animation.)


SceneObject:setInertiaArms(armLengths)

- armLengths (Vector): The lengths of the X, Y, and Z arms

Sets the length of the 'arms' of the inertia model, if inertia is explicitly specified. The arms operate like a figure skater's arms when skating---longer arms increase the inertia and would make the object spin more slowly under a given applied torque, while shorter arms decrease the inertia and would make the object spin faster.

There are three arms aligned along the X, Y, and Z axes; lengthening the X arm makes the model spin more slowly around Y and Z, and similar rules hold for the Y arm and Z arm.


SceneObject:setInertiaRotation(rotation)

Sets the rotation of the inertia arms relative to the model's principal axes


SceneObject:setKeyword(keyword)

- keyword: (string) keyword to set

Sets a keyword in an object

DEPRECATED IN V1.5

please use SceneObject:addKeywords()


SceneObject:setLightingEnable(flag)

Enable or disable applying lights to the object. If light is disabled, the object is flatly lit at 100% intensity

DEPRECATED IN V1.5

please use sceneObject:setLightingEnabled()


SceneObject:setLightingEnabled(flag)

Enable or disable applying lights to the object. If light is disabled, the object is flatly lit at 100% intensity


SceneObject:setLockX(lock)

set to lock the objects movement to X. Locked objects act like anchored objects but only in one dimension.

Note: an anchored object is not nececarily locked in XYZ.


SceneObject:setLockY(lock)

set to lock the objects movement to Y. Locked objects act like anchored objects but only in one dimension.

Note: an anchored object is not nececarily locked in XYZ.


SceneObject:setLockZ(lock)

set to lock the objects movement to Z. Locked objects act like anchored objects but only in one dimension.

Note: an anchored object is not nececarily locked in XYZ.


SceneObject:setLookAt(otherobject)

Causes this object to look at (point toward) the other object. The other object can be a scene object, a transform, or a point in the form of a vector.


SceneObject:setMass(newMass)

- newMass: (number) The new mass, in kilograms

Sets the mass of the object, in kilograms


SceneObject:setMeshColor(mesh_name, color)

- mesh_name: (string) Name of the mesh to tint
- color: (Color) The color to tint the mesh

raises an error if no mesh by the given name exists


SceneObject:setMeshMode(mesh, mode)

- mesh: (string) Name of the mesh to modify
- mode: (string) Name of the mode to render the mesh with

Sets the mode of the mesh. The mesh can be in one of three modes:
* standard - Mesh is rendered with normal parameters
* wireframe - Mesh is rendered in wireframe mode; only the polygon edges are rendered
* alphatest - Mesh is rendered using the alpha channel as a binary filter; parts of the mesh with alpha less than 0.5 are not rendered, while parts with an alpha greater than 0.5 are rendered at full opacity. This mode is useful for objects such as chain link fences, which are not actually transparent but use the texture to describe where the links of the fence are located.

Raises an exception if no mesh by the given name exists.


SceneObject:setName(name)

- name: (string) The object's new name

Sets the objects unique name. If the name already exists in the scene this function fails.


SceneObject:setParticleSystem(system)

system: (ParticleSystem) The particle system to apply to this object (use nil to clear a particle system)

Sets the scene object's particle system effect.


SceneObject:setPosition(x,y,z [, frame_of_reference])

Sets the position. The parameter is either a vector or three numbers.


SceneObject:setProperty(key,value)

- key: (string) The propery name
- value: (property-type) The new value of the property

Sets the given property of an object


SceneObject:setRelAngularVelocity(relangularVelocity)

- relangularVelocity: (Vector3d) The Objects angular velocity in relative coordinates to the current rotation of the object.

Sets the Objects angular velocity in relative coordinates to the current rotation of the object.


SceneObject:setRelVelocity(relVelocity)

- relVelocity: (Vector3d) The Objects velocity in relative coordinates to the current rotation of the object.

Sets the Objects velocity in relative coordinates to the current rotation of the object.


SceneObject:setRotation(rotation [, frame_of_reference])

Sets the rotation. The parameter is a rotation object, typically constructed using Rotation.new or the like.


SceneObject:setRotationLock(anchored)

anchored -- string (\"none\", \"x\", \"y\", \"z\", \"all\")

sets a string representing what rotation lock is applied to the SceneObject


SceneObject:setSavable(savable)

- savable: (boolean) The flag value

Brief : Sets the savable property

Sets the object's savable property to the value provided. Savable is a boolean flag that determines if the object is saved by SceneManager's scene-saving operations.


SceneObject:setScale(x,y,z)

Sets the scale. The parameter is either a vector or three numbers.


SceneObject:setScaleX(x)

Sets the X-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


SceneObject:setScaleXYZ(x,y,z)

Sets the scale.

DEPRECATED IN V1.5

please use Transform.setScale()


SceneObject:setScaleY(y)

Sets the Y-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


SceneObject:setScaleZ(z)

Sets the Z-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


SceneObject:setScriptClass( ? )

Undocumented method.


SceneObject:setStandardMode(mesh)

- mesh: (string) Name of the mesh to set standard rendering on

Raises an exception if no mesh with the given name exists


SceneObject:setStashed(flag)

- flag (boolean, optional): Sets whether the object is stashed

Brief : Sets the stashed property

This function is buggy and is scheduled to be fixed later, use at your own risk.

Sets whether an object is stashed. Stashed objects are not rendered.


SceneObject:setSurfaceBounce(bounce)

Has no effect.

DEPRECATED in v1.5

Use SceneObject:setBounciness instead


SceneObject:setSurfaceMu(muTwo)

- muTwo: (number) The new mu value

Sets the object's surface mu value, which controls the "stickiness" of friction


SceneObject:setTexture(textureResource,slot)

- textureResource: (ResourceID or string) The texture resource to use, as either a ResourceID or filename
- slot: (number) The index of the texture to replace

Brief : Changes the specified texture

Replaces the texture at the specified index with a new texture. The textures range from 1 to the number of textures on the object.


SceneObject:setTransform(transform [, frame_of_reference])

Sets the entire transform.


SceneObject:setUpright([frame_of_reference])

Causes the object to upright itself - In other words, the object's local Z-axis is aligned with the world's Z-axis. If possible, the object's heading is not lost.


SceneObject:setVelocity(velocity)

- velocity: (Vector) desired velocity

Sets the object's velocity to the input. If using metric units, this velocity is in meters per second (m/s). Otherwise, it is in meters per 60th of a second (60 * m/s). In other words, by default, divide your velocity in m/s by 60 before passing it to setVelocity(), unless you have turned on metric units. See documentation for Simulation.usesMetricUnits() for details.


SceneObject:setVelocityX(xcoord)

- xcoord: (number) The X coordinate of the object's velocity

Sets the X coordinate of the object's velocity


SceneObject:setVelocityY(ycoord)

- ycoord: (number) The Y coordinate of the object's velocity

Sets the Y coordinate of the object's velocity


SceneObject:setVelocityZ(zcoord)

- zcoord: (number) The Z coordinate of the object's velocity

Sets the Z coordinate of the object's velocity


SceneObject:setWeightless(weightless)

- weightless: (boolean) Sets whether the object is weightless

Brief : Sets the weightless property

Sets the weightless property. The weightless property, if set, blocks the effects of gravity on the object.


SceneObject:setWidth(amount,maintainAspect)

- amount: (number) The new width of the object in meters
- maintainAspect: (boolean) If true or nil will stretch the Height and Depth to maintain 1:1 aspect ratio

Sets the scale of the object to make it the width specified. (Note: for animated models, this sets the initial width before animation.)


SceneObject:setWireframeMode(mesh)

- mesh: (string) Name of the mesh to modify

Raises an exception if no mesh with the given name exists


SceneObject:setX(x [, frame_of_reference])

Sets the X-component of the position. It may be more convenient to set all three using setXYZ.


SceneObject:setXYZ(x,y,z [, frame_of_reference])

Sets the position.

DEPRECATED IN V1.5

please use Transform:setPosition()


SceneObject:setY(y [, frame_of_reference])

Sets the Y-component of the position. It may be more convenient to set all three using setXYZ.


SceneObject:setZ(z [, frame_of_reference])

Sets the Z-component of the position. It may be more convenient to set all three using setXYZ.


SceneObject:show()

Unstashes a stashed object.

This function is buggy and is scheduled to be fixed later, use at your own risk.

DEPRECATED IN V1.5

Please use SceneObject:setStashed(false)


SceneObject:stopAnimation(channel (optional))

- channel: (number) The channel to stop

Stops the currently playing animation. A channel may be specified. If a channel is not specified, channel 1 is stopped.


>

class ShapeSequence

Organizes a collection of 3D geometric shapes to be drawn in a scene.

A ShapeSequence describes a sequence of primitive geometric shapes (spheres, boxes, and lines) to be rendered in a scene. The sequence is populated using methods such as ShapeSequence:addBox and ShapeSequence:addSphere, and is then made active using ShapeSequence:show(). Only one ShapeSequence can be active at a time; showing one automatically hides previous ones. Also, a ShapeSequence that is shown may be further modified, but modifications are ignored until the next show() call on the sequence.

All ShapeSequence add methods take in as their last argument a 'properties' table, which defines properties (such as color and position) for the shape. Properties that aren't specified will take on default values. All shapes support the following properties:

- name: (string, default '') Name of the shape, used in lookup operations
- position: (Vector, default 0,0,0) Position of the shape
- rotation: (Rotation, default identity-rotation) Rotation of the shape
- scale: (Vector, default 1,1,1) Scale of the shape
- color: (Color, default 1,0,0,1) Color of the shape
- overlay: (Boolean, default true) If true, shape appears on top of everything in the scene; otherwise, shape appears within the scene

Shapes can be named, which is useful for finding them again with lookup commands (ShapeSequence:find and ShapeSequence:atScreenCoordinates).

ShapeSequence is intended to be a low-level API upon which more complicated 3D widget systems can be built. One of these systems is the Gizmo system (see class Gizmo for more information).

Member functions:

ShapeSequence:addBox(dimensions,properties)

- dimensions: (Vector) width, height, and depth of box
- properties: (table) Properties table. See class documentation for more information

Adds a box shape to this sequence


ShapeSequence:addLine(endpoint1,endpoint2,properties)

- endpoint1: (Vector) First endpoint of the line segment
- endpoint2: (Vector) Second endpoint of the line segment
- properties: (table) Properties table. See class documentation for more information.
In addition to the regular properties, the following additional properties are supported by ShapeSequence:addLine
- - color1: (Color) Color of endpoint 1
- - color2: (Color) Color of endpoint 2

Adds a line segment to the sequence


ShapeSequence:addSphere(radius,properties)

- radius: (number) radius of the sphere, in meters
- properties: (table) Properties table. See class documentation for more information

Adds a sphere to this sequence


name = ShapeSequence.atScreenCoordinates(x,y)

- name : (string) Name of the object at the given screen coordinate
- x : (number) x-coordinate on the screen
- y : (number) y-coordinate on the screen

Determines the nearest shape to the camera at the given screen coordinate. Returns the name of the shape the test intersects with, or nil if no shapes intersect the ray.


name = ShapeSequence:find(origin,direction)

- name : (string) Name of the object the ray intersects
- origin: (Vector) Origin of the test ray
- direction: (Vector) Direction the test ray projects into the scene

Tests shapes in the sequence against the given ray. Returns the name of the shape the test intersects with, or nil if no shapes intersect the ray.


sequence = ShapeSequence.new()

Creates a new shape sequence


ShapeSequence:show()

Copies this shape sequence to the render buffer, discarding other shown sequences.


>

class Simulation

Undocumented class.

Member functions:

Simulation.forceGLState(flag)

Force the openGL state to be reset before every render. This is very slow and inefficient, but it's sometimes useful for debugging shader bugs.


fps = Simulation.getFps()

fps: (number) The current framerate, frames per second

Retrieves the current Frames Per Second rate of the scene rendering


enabled = Simulation.getIdleModeEnable()

The engine supports an 'idle mode' - when a game does not have the keyboard focus, it deliberately slows down to 2 FPS and 1/3 the normal simulation speed. This works fine for most games, but not all. If you set the idle mode enable to false, the game will not slow down when it loses keyboard focus. Setting the idle mode to true causes the engine to reduce CPU consumption whenever it loses focus.


Simulation.getLoadingScreen(flag)

Returns true, false, or 'auto'. See 'setLoadingScreen'.


stepsize = Simulation.getPhysicsStepSize()

-stepsize: The size of a physics step, in seconds

Retrieves the size of a physics step (dt) that is used in the physics simulator. NOTE: This is not the same as the physics simulation period; see the physics docmentation in the manual for more information.


params = Simulation.getUrlParameters()

- params : (table) The parameters passed to the url in key/value format.

This function will return parameters passed to your game in the URL. Any parameter that begins with 'param' will be passed. For example: http://www.wildpockets.com/Embed.php?OpenPocket=user/game&paramFoobar=hello would return a table with a singel key 'Foobar' with value 'hello'


loaded = Simulation.resourceLoaded(resourceId)

Returns true if the resource is loaded. Also queues the resource for loading.


Simulation.setIdleModeEnable(true / false)

The engine supports an 'idle mode' - when a game does not have the keyboard focus, it deliberately slows down to 2 FPS and 1/3 the normal simulation speed. This works fine for most games, but not all. If you set the idle mode enable to false, the game will not slow down when it loses keyboard focus. Setting the idle mode to true causes the engine to reduce CPU consumption whenever it loses focus.


Simulation.setLoadingScreen(flag)

If flag is true, displays the loading screen and suppresses normal rendering. If flag is false, renders the scene normally. If flag is 'auto', the system uses a heuristic to decide.


Simulation.suppressWarnings(string)

Suppress all warning messages containing the specified string.

Note: some of our warning messages fail to respect this directive. We are working on overhauling all our warning code to respect this mechanism.


Simulation.useGLFinish(flag)

Controls whether or not the engine calls glFinish. By default, it does not. Sometimes this produces better latency.


status = Simulation.usesMetricUnits(flag)

-status: (boolean) If true, simulation uses metric units - otherwise, behaves as before
-flag: (boolean, optional) If supplied, sets whether the simulation uses metric units

By default, the simulation uses non-standard units. Setting this flag enables metric units in the simulation. NOTE: This property is not currently saved in the scene; to make use of this feature, call Simulation.usesMetricUnits(true) at the top of onSceneStart()

Using Wild Pockets non-standard units, the engine simulates 60 real-life seconds in the span of 1 second. This will cause functions involving data such as velocity, acceleration, and force to be off by various scaling factors, all of which will be explained in those functions' documentation.

When metric units are turned on, all such data will use SI (kilograms, meters, seconds): velocities will be in m/s, impulses will be in N*s, et cetera.

DEPRECATED IN V1.5

Starting in version 1.5 Metric units are the default. If your game uses non-metric units you can use this function to reset to the old state, but when V1.6 is released, this will no longer be an option.


>

class Sound

A sound loaded from a resource, which can be played via script.

It is OK to create many copies of the same sound. For example, if you want to have a 'zap' sound every time somebody fires their gun, it is fine to create a new sound object each time they press the trigger. Sound objects are garbage collected properly, like any other Lua object.

Member functions:

length = Sound:getLength()

Returns the length of a Sound, in seconds


sound = Sound.new(filename)

Creates a new Sound.


Sound:play()

Starts playing the sound. If the sound was already playing, stops the sound and restarts it. If you want to have two copies of the same sound playing at the same time, you need to create two sound objects with the same filename.

Blocks until the sound downloads. If you don't want to block, check the sound status first, and don't play it if the status indicates that it is still downloading.


Sound:setVolume(volume)

Sets the volume, using a scale which ranges from 0-1. This scale can be converted to decibels using:

decibelGain = -((1.0 - volume) * (1.0 - volume) * 40.0)

As a special case, when the volume is exactly 0, the sound is disabled.


Sound:setVolumeDecibels(volume)

Sets the volume level, in relative decibels. In this scale, 0 is the loudest possible volume. -1 means one decibel softer than maximum, -2 means two decibels softer than maximum, and so forth.


Sound:status()

Returns the sound status. The status can be 'idle', 'playing', 'downloading', or an error code.


Sound:stop()

Stops playing the sound.


>

class Timer

This class enables you to cause code to be executed later - ie, in a delayed manner.

WildPockets runs as a discrete event simulation. What this means is that tasks are scheduled for specific, precise times. If you schedule a task for 10AM, then when the task is executed, the time is 10AM, by definition. If that task, in turn, schedules another task for 5 minutes in the future, then that task is scheduled for 10:05AM, by definition. This mathematical approach to time tends to preserve predictable simulation behavior, even if the computer is a little bogged down.

WildPockets will try very hard to run the simulation at a speed that matches real wall clock time. However, if the simulation is taking longer than real time, nothing can be done - the result will be a game whose simulation clock runs slower than real time (and therefore, appears to be running in slow-motion).

This differs from some other engines - in those engines, if the game code is too slow, the engine keeps running at the same speed, but it gets less and less accurate. In WildPockets, the simulation maintains the same accuracy, but runs slower and slower.

Member functions:

Timer.every(fn, interval [, key])

- fn: the function to be called
- interval: how often the function should be called, in seconds
- key: a name that can be used to delete this task

Causes a function to be called on a regular scheduled interval. The first call to the function is after the specified interval. The key can be used to delete this task using stopDoLater.


seconds = Timer.getTime()

Get the current simulation time.


Timer:getWallClockTime()

Get the current wall clock time. Usually, you don't want wall-clock time, you want discrete-event time, as returned by Timer.getTime. The difference is that if your computer gets bogged down for a minute, Timer.getTime will slow down to enable the simulation to catch up without losing accuracy, whereas Timer.getWallClockTime will barrel ahead. Using Timer.getWallClockTime can cause weird game artifacts.


Timer.later(fn, delay [, key])

Schedules a function to be called after a specified amount of time. The time is specified in seconds. The key, if specified, can be used to delete the entry from the scheduler using stopDoLater.


Timer.setLinearMode(mode)

THIS FUNCTION HAS BEEN DEPRECATED IN V1.5

mode - (boolean) sets to use the linear timer mode. (default false)

Use this function to change the mode of the timer loops to run in the same order every frame for Timer.every(0) loops. This function will be replaced in V1.6 with a much more robust system to allow some control over the system loops.


Timer.sleep(delay)

Causes the current thread to go to sleep for the specified number of seconds. Does *not* cause the entire engine to sleep - other threads run normally.


Timer.stop(key)

Removes all entries having the specified key from the scheduler. If called in the middle of that scheduled function, the function will run to completion but removed from any future scheduled events.


Timer.stopDoLater(key)

Removes all entries having the specified key from the scheduler.

DEPRECATED IN V1.5

please use Timer.stop(key)


>

class Transform

A transform has three parts: position, rotation, and scale. The position is a Vector, the rotation is a Rotation object, and the scale is a Vector. These three parts are stored separately, so that any one can be individually modified without touching the other two.

Methods whose names start with 'pathTo' are movement operators. These are complicated, please read the manual about movement operators.

Several other classes contain transforms: SceneObject and CameraBoom, for instance. Many methods that manipulate transforms also work on these other classes.

Member functions:

movedpoint = Transform.applyToPoint(point)

Applies the position, rotation, and scale to the point, and returns the transformed point.


transform = Transform:combine(parenttransform)

Combines two transforms. The resulting transform behaves as if the position and rotation of the parent transform were applied first, then the position, rotation, and scale of this transform. The scale of the parenttransform is not applied!


distance = Transform:distance(point)

The distance operator can compute the distance between any two objects: they can be scene objects, cameras, transforms, or just points specified as vectors.


r,f,u,l,b,d = Transform:getAxes()

Get the object's local direction vectors. Returns six values:

* positive x axis (the 'right' vector)
* positive y axis (the 'forward' vector)
* positive z axis (the 'up' vector)
* negative x axis (the 'left' vector)
* negative y axis (the 'backward' vector)
* negative z axis (the 'down' vector)


vec = Transform:getBackwardVector()

Returns a vector that points backward out of the rear of the character's head. The backward vector is equal to the character's local negative Y-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


direction = Transform:getCompassDirection([frame_of_reference])

Get the compass direction in which the object is facing. The return value is a string, one of: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE If the object's orientation is not exactly in one of these sixteen directions, it will approximate.


vec = Transform:getDownVector()

Returns a vector that points downward out of the bottom the character's feet. The down vector is equal to the character's local negative Z-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


vec = Transform:getForwardVector()

Returns a vector that points forward out of the tip of the character's nose. The forward vector is equal to the character's local positive Y-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


heading,pitch,roll = Transform:getHPR([frame_of_reference])

Returns the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


heading = Transform:getHeading([frame_of_reference])

Returns the object's heading, where 0 is north, 90 is west, 180 is south, and 270 is east.


vec = Transform:getLeftVector()

Returns a vector that points left out of the character's left shoulder. The left vector is equal to the character's local negative X-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


position = Transform:getPosition([frame_of_reference])

Get the position.


vec = Transform:getRightVector()

Returns a vector that points right out of the character's right shoulder. The right vector is equal to the character's local positive X-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


position = Transform:getRotation([frame_of_reference])

Get the rotation.


position = Transform:getScale()

Get the scale.


sx = Transform:getScaleX()

Returns the X-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


sx,sy,sz = Transform.getScaleXYZ()

Returns the X, Y, Z scale of the object as three values. It is also possible to obtain the scale as a single vector object by calling getScale instead.

DEPRECATED IN V1.5

please use Transform.getScale()


sy = Transform:getScaleY()

Returns the Y-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


sz = Transform:getScaleZ()

Returns the Z-component of the scale. It may be more convenient to use getScaleXYZ, which returns all three values.


vec = Transform:getUpVector()

Returns a vector that points upward out of the top of the character's head. The up vector is equal to the character's local positive Z-axis. If you need several of a character's vectors, it is quicker to use getAxes instead.


X = Transform:getX([frame_of_reference])

Get the X-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


x,y,z = Transform.getXYZ([frame_of_reference])

Returns the X, Y, Z position of the object as three values. It is also possible to obtain the position as a single vector object by calling getPosition instead.

DEPRECATED IN V1.5

please use Transform.getPosition()


Y = Transform:getY([frame_of_reference])

Get the Y-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


Z = Transform:getZ([frame_of_reference])

Get the Z-coordinate. It is often more convenient to use getXYZ, which returns all three coordinates.


transform = Transform.new()

Creates a new transform object. The initial position is the world origin, the rotation is facing north, and the scale is 1.0.


Transform:pathToAxis(mode, vector)

Rotates the object to cause one axis of the object to align with the specified vector. Mode is a string, one of the following:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


Transform:pathToAxisAngle(axis, angle)

Rotates an object about an arbitrary (axis) by (angle)


Transform:pathToCompassDirection(direction [, frame_of_reference])

Set the compass direction in which the object is facing. The parameter must be a string, one of the following: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE.


Transform:pathToForwardVector(direction [, up] [, frame_of_reference])

Look in the specified direction. The direction must be a vector. The object is also made upright, insofar as possible subject to the constraint that it be looking in the specified direction. You can specify an optional up-vector.


Transform:pathToHPR(heading, pitch, roll [, frame_of_reference])

Sets the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


Transform:pathToHeading(heading [, frame_of_reference])

Causes the object to face in the given heading, where 0 is north, 90 is west, 180 is south, and 270 is east. In addition, the object is made upright.


Transform:pathToLookAt(otherobject)

Causes this object to look at (point toward) the other object. The other object can be a scene object, a transform, or a point in the form of a vector.


Transform:pathToPosition(x,y,z [, frame_of_reference])

Sets the position. The parameter is either a vector or three numbers.


Transform:pathToRotation(rotation [, frame_of_reference])

Sets the rotation. The parameter is a rotation object, typically constructed using Rotation.new or the like.


Transform:pathToScale(x,y,z)

Sets the scale. The parameter is either a vector or three numbers.


Transform:pathToScaleX(x)

Sets the X-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


Transform:pathToScaleXYZ(x,y,z)

Sets the scale.

DEPRECATED IN V1.5

please use Transform.setScale()


Transform:pathToScaleY(y)

Sets the Y-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


Transform:pathToScaleZ(z)

Sets the Z-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


Transform:pathToTransform(transform [, frame_of_reference])

Sets the entire transform.


Transform:pathToUpright([frame_of_reference])

Causes the object to upright itself - In other words, the object's local Z-axis is aligned with the world's Z-axis. If possible, the object's heading is not lost.


Transform:pathToX(x [, frame_of_reference])

Sets the X-component of the position. It may be more convenient to set all three using setXYZ.


Transform:pathToXYZ(x,y,z [, frame_of_reference])

Sets the position.

DEPRECATED IN V1.5

please use Transform:setPosition()


Transform:pathToY(y [, frame_of_reference])

Sets the Y-component of the position. It may be more convenient to set all three using setXYZ.


Transform:pathToZ(z [, frame_of_reference])

Sets the Z-component of the position. It may be more convenient to set all three using setXYZ.


Transform:rotateAboutAxis(axis, angle)

Rotates an object about an arbitrary (axis) by (angle)


Transform:setAxis(mode, vector)

Rotates the object to cause one axis of the object to align with the specified vector. Mode is a string, one of the following:

- 'L' - left-vector is snapped.
- 'R' - right-vector is snapped.
- 'F' - forward-vector is snapped.
- 'B' - backward-vector is snapped.
- 'U' - up-vector is snapped.
- 'D' - down-vector is snapped.
- 'X' - xaxis, synonym for right-vector.
- 'Y' - yaxis, synonym for forward-vector.
- 'Z' - zaxis, synonym for up-vector.

The object will be rotated as little as possible to get it into a valid orientation.


Transform:setCompassDirection(direction [, frame_of_reference])

Set the compass direction in which the object is facing. The parameter must be a string, one of the following: N, NNW, NW, WNW, W, WSW, SW, SSW, S, SSE, SE, ESE, E, ENE, NE, NNE.


Transform:setForwardVector(direction [, up] [, frame_of_reference])

Look in the specified direction. The direction must be a vector. The object is also made upright, insofar as possible subject to the constraint that it be looking in the specified direction. You can specify an optional up-vector.


Transform:setHPR(heading, pitch, roll [, frame_of_reference])

Sets the heading, pitch, and roll. In the heading, 0 is north, 90 is west, 180 is south, and 270 is east. In the pitch, 0 is level, 90 is pointing straight up, and -90 is straight down. In the roll, negative values are tilting left, and positive values are tilting right.


Transform:setHeading(heading [, frame_of_reference])

Causes the object to face in the given heading, where 0 is north, 90 is west, 180 is south, and 270 is east. In addition, the object is made upright.


Transform:setLookAt(otherobject)

Causes this object to look at (point toward) the other object. The other object can be a scene object, a transform, or a point in the form of a vector.


Transform:setPosition(x,y,z [, frame_of_reference])

Sets the position. The parameter is either a vector or three numbers.


Transform:setRotation(rotation [, frame_of_reference])

Sets the rotation. The parameter is a rotation object, typically constructed using Rotation.new or the like.


Transform:setScale(x,y,z)

Sets the scale. The parameter is either a vector or three numbers.


Transform:setScaleX(x)

Sets the X-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


Transform:setScaleXYZ(x,y,z)

Sets the scale.

DEPRECATED IN V1.5

please use Transform.setScale()


Transform:setScaleY(y)

Sets the Y-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


Transform:setScaleZ(z)

Sets the Z-component of the scale. It may be more convenient to use setScaleXYZ to set all three components.


Transform:setTransform(transform [, frame_of_reference])

Sets the entire transform.


Transform:setUpright([frame_of_reference])

Causes the object to upright itself - In other words, the object's local Z-axis is aligned with the world's Z-axis. If possible, the object's heading is not lost.


Transform:setX(x [, frame_of_reference])

Sets the X-component of the position. It may be more convenient to set all three using setXYZ.


Transform:setXYZ(x,y,z [, frame_of_reference])

Sets the position.

DEPRECATED IN V1.5

please use Transform:setPosition()


Transform:setY(y [, frame_of_reference])

Sets the Y-component of the position. It may be more convenient to set all three using setXYZ.


Transform:setZ(z [, frame_of_reference])

Sets the Z-component of the position. It may be more convenient to set all three using setXYZ.


movedpoint = Transform.transform(point)

Applies the position, rotation, and scale to the point, and returns the transformed point.

DEPRECATED IN V1.5

please use Transform.applyToPoint()


transform = Transform.uncombine(parenttransform)

Generates a transform, which if combined with the parent transform, yields the current transform.


>

class Utils

Undocumented class.

Member functions:

canonicalName = Utils.canonicalizeFilename(filename)

Returns the passed passed filename in its canonical form. If the passed value is not a valid filename, returns nil.


Utils.safeExecuteJavascript(functionName, [arg1 [, arg2 ...]])

Execute a Javascript function in the parent webpage.

- functionName: Name of the Javascript function to execute. All
Javascript functions to be executed by this command must be prefixed by 'wpscript_', but the prefix should be omitted from this call. For example to call, a Javascript function named 'wpscript_myFunction', pass 'myFunction'.

- argn: Arguments to pass to the Javascript function. All
arguments must be strings.


value = Utils.urlencode(...)

Returns the passed string, having replaced all non-alphanumeric characters except -_. with a percent (%) sign followed by two hex digits, and spaces replaced by plus (+) signs.


>

class Vector

Used for storing both cartesian coordinates (X,Y,Z) and directional vectors.

Member functions:

vec = Vector.__add(other)

The addition operator operates in a componentwise fashion:
* result = (X + other.X, Y + other.Y, Z + other.Z)


value = Vector:__div(other)

The division operator operates in a componentwise fashion:
* result = (X / other.X, Y / other.Y, Z / other.Z)


value = Vector:__eq(othervector)

The equality comparison operator returns true if all components of the vectors match.


vec = Vector.__mul(other)

The multiplication operator operates in a componentwise fashion:
* result = (X * other.X, Y * other.Y, Z * other.Z)


vec = Vector.__sub(other)

The subtraction operator operates in a componentwise fashion:
* result = (X - other.X, Y - other.Y, Z - other.Z)


value = Vector:__unm()

The unary minus operator negates all three components of the vector.


value = Vector:cross(othervector)

Returns the cross-product of the two vectors.


xcomponent,ycomponent,zcomponent = Vector:decompose(object)

Separates the vector into three perpendicular components. The three components add up to the original vector. The first component points in the direction of the object's right-vector, the second in the direction of the object's forward-vector, and the third in the direction of the object's up-vector. The object can be a scene object, camera, transform, or any other object with a transform.


distance = Vector:distance(point)

The distance operator can compute the distance between any two objects: they can be scene objects, cameras, transforms, or just points specified as vectors.


value = Vector:dot(othervector)

Returns the dot-product of the two vectors.


value = Vector:getCrossProduct(othervector)

Returns the cross-product of the two vectors. Synonyms: getCrossProduct and cross.


value = Vector:getDotProduct(othervector)

Returns the dot-product of the two vectors.


unitvec = Vector:getNormal()

Returns a normalized vector - ie, a vector in the same direction, but with length 1.0. Synonyms: normalize, getNormal, unit.


value = Vector:getX()

Returns the X coordinate.


x,y,z = Vector:getXYZ()

Returns the X,Y,Z coordinates.


value = Vector:getY()

Returns the Y coordinate.


value = Vector:getZ()

Returns the Z coordinate.


len = Vector:length()

Returns the length of the vector. A synonym for magnitude.


len = Vector:magnitude()

Returns the length of the vector. A synonym for magnitude.


vec = Vector.new(x,y,z)

Creates a new vector. The parameters x,y,z are optional, the default values are zero. The global function 'vec' is shorthand for Vector.new.


unitvec = Vector:normalize()

Returns a normalized vector - ie, a vector in the same direction, but with length 1.0. Synonyms: normalize, getNormal, unit.


value = Vector:scale(scalar)

Multiplies each component of Vector by the scalar value.


Vector:setX(value)

Sets the X coordinate.


Vector:setY(value)

Sets the Y coordinate.


Vector:setZ(value)

Sets the Z coordinate.


unitvec = Vector:unit()

Returns a normalized vector - ie, a vector in the same direction, but with length 1.0.


>

class math

Math is not really a class, it's merely a container for math functions.

Member functions:

math.abs(x)

Returns the absolute value of x.


math.acos(x)

Returns the arc cosine of x (in radians).


math.asin(x)

Returns the arc sine of x (in radians).


math.atan(x)

Returns the arc tangent of x (in radians).


math.atan2(y, x)

Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of x being zero.)


math.ceil(x)

Returns the smallest integer larger than or equal to x.


math.cos(x)

Returns the cosine of x (assumed to be in radians).


math.cosh(x)

Returns the hyperbolic cosine of x.


number = math.datan2(dy,dx)

Returns the arctangent, in degrees.


value = math.dcos(angle)

Rounds the cosine of an angle, specified in degrees.


math.deg(x)

Returns the angle x (given in radians) in degrees.


value = math.dsin(angle)

Rounds the sine of an angle, specified in degrees.


sine,cosine = math.dsincos(angle)

Rounds the sine and cosine of an angle, specified in degrees.


number = math.dtan(angle)

Returns the tangent of an angle, specified in degrees.


math.exp(x)

Returns the value ex.


math.floor(x)

Returns the largest integer smaller than or equal to x.


math.fmod(x, y)

Returns the remainder of the division of x by y that rounds the quotient towards zero.


math.frexp(x)

Returns m and e such that x = m2e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).


math.ldexp(m, e)

Returns m2e (e should be an integer).


math.log(x)

Returns the natural logarithm of x.


math.log10(x)

Returns the base-10 logarithm of x.


math.max(x, ···)

Returns the maximum value among its arguments.


math.min(x, ···)

Returns the minimum value among its arguments.


math.mod(...)

Undocumented Lua builtin.


math.modf(x)

Returns two numbers, the integral part of x and the fractional part of x.


result = math.near(a,b,threshold)

- result: (boolean) If true, numbers were near each other
- a: (number) First value to compare
- b: (number) Second value to compare
- threshold: (number, optional) The range a and b must be within to be
considered near each other. If omitted, the threshold of 0.00001 is used

Executes a 'fuzzy equality' test on two values, returning true if they are numerically near each other


math.pow(x, y)

Returns xy. (You can also use the expression x^y to compute this value.)


math.rad(x)

Returns the angle x (given in degrees) in radians.


math.random([m [, n] ])

This function is an interface to the simple pseudo-random generator function rand provided by ANSI C. (No guarantees can be given for its statistical properties.)

When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n].


math.randomseed(x)

x: (number,optional) Seed value for the randon number generator. If ommitted, a seed value based on the time since computer startup is used; this should generate sufficient randomness for most purposes.

Sets x as the seed for the pseudo-random generator: equal seeds produce equal sequences of numbers.


number = math.round(number)

Rounds the number to the nearest integer.


sign = math.sign(number)

Returns the sign of the given number (-1, 0, 1)


math.sin(x)

Returns the sine of x (assumed to be in radians).


math.sinh(x)

Returns the hyperbolic sine of x.


math.sqrt(x)

Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)


math.tan(x)

Returns the tangent of x (assumed to be in radians).


math.tanh(x)

Returns the hyperbolic tangent of x.


>

class string

Class string contains all the methods that can be applied to lua text strings.

Lua strings are 8-bit clean, but are not in unicode.

Member functions:

string.byte(s [, i [, j] ])

Returns the internal numerical codes of the characters s[i], s[i+1], , s[j]. The default value for i is 1; the default value for j is i.

Note that numerical codes are not necessarily portable across platforms.


string.char(···)

Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

Note that numerical codes are not necessarily portable across platforms.


string = string:countlines()

Returns the number of lines in a string.


string.dump(function)

Returns a string containing a binary representation of the given function, so that a later loadstring on this string returns a copy of the function. function must be a Lua function without upvalues.


flag = string:endswith(suffix)

Returns true if this string ends with the specified suffix.


string:explode(delimiter [, limit])

Returns an array of strings, each of which is a substring of the input string formed by splitting the input string on boundaries formed by the string delimiter.

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string . If the limit parameter is negative, all components except the last -limit are returned. If the limit parameter is zero, then this is treated as 1.

It is an error to pass in a null-string delimiter.


string.find(s, pattern [, init [, plain] ])

Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered "magic". Note that if plain is given, then init must be given as well.

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.


string.format(formatstring, ···)

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written.

The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string.

This function does not accept string values containing embedded zeros, except as arguments to the q option.

More information in the lua manual.


string.gfind(...)

Deprecated function. This was renamed to string.gmatch.


string.gmatch(s, pattern)

Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If pattern specifies no captures, then the whole match is produced in each call.


string.gsub(s, pattern, repl [, n])

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.

If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0 stands for the whole match. The sequence %% stands for a single %.

If repl is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

More information in the lua manual.


string.implode(glue, stringarray)

Concatenates all the strings in an array of strings, inserting a glue string between each piece. The glue string can be the null string, in which case the result is just the concatenation of the strings in the string array.


string.len(s)

Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.


string.lower(s)

Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.


result = string:lstrip([whitespace])

Strips whitespace from the string. The optional whitespace argument determines which characters count as whitespace. If not specified, whitespace includes spaces, newlines, carriage returns, and tabs. lstrip only strips the left end of the string.


string.match(s, pattern [, init])

Looks for the first match of pattern in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative.


string:pad(length [, padstring [, type]])

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument padstring is not supplied, the input is padded with spaces, otherwise it is padded with characters from padstring up to the desired length. Type can be the string 'left', 'right', or 'both', if omitted, it defaults to 'right'.


string:partition(sep)

Searches the string for the separator, and returns three values: the part before the separator, the separator, and the part after the separator. If the separator is not found, returns two null strings and the whole.


string.rep(s, n)

Returns a string that is the concatenation of n copies of the string s.


string:replace(old, new [,count])

Replaces the old string with the new one. If count is specified, replaces at most the specified number of occurrences. Unlike string.gsub, the 'old' string is just a string, not a regex.


string.reverse(s)

Returns a string that is the string s reversed.


result = string:rstrip([whitespace])

Strips whitespace from the string. The optional whitespace argument determines which characters count as whitespace. If not specified, whitespace includes spaces, newlines, carriage returns, and tabs. rstrip only strips the right end of the string.


array = string:splitlines()

Split the string at line boundaries. Returns an array of lines.


flag = string:startswith(prefix)

Returns true if this string starts with the specified prefix.


result = string:strip([whitespace])

Strips whitespace from the string. The optional whitespace argument determines which characters count as whitespace. If not specified, whitespace includes spaces, newlines, carriage returns, and tabs.


string.sub(s, i [, j])

Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.


string:tokenize(newlines)

Tokenizes the string using a conventional programming language tokenizer. The parameter is a flag indicating whether newlines should be tokens (if not, they are ignored). Returns an array of strings.


string.trim(s)

undocumented string operation


string.upper(s)

Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.


>

class table

Tables are lua's most central data type. There's a lot to them, you will need to read the lua manual to learn about tables.

Member functions:

table.append(array1, array2, array3...)

Appends several arrays. Returns a new array containing all the elements from all the input arrays, in the order that they were input. It is valid to pass in zero arrays, in which case the output table is empty.

The inputs must be arrays (tables whose keys are integers starting with 1 and ascending.)


table.clear(table)

Removes all keys and values from the table. No return value.


table.concat(table [, sep [, i [, j] ] ])

Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.


result = table.copy(tab)

Makes a shallow copy of the table.


table.copyelts(srcTab, dstTab, keylist)

For every key in keylist, copies the value from srcTab to dstTab.


table.count(table, value)

Searches a table for a given value. Returns the number of times the value occurs in the table.


table.deepprint(tab)

Prints the contents of the table, and any tables it contains. Mostly for debugging purposes.


table.fill(table, start, end, value)

Fills a subrange of an array with a specified value. If end is less than start, no filling takes place. Start and end are NOT clamped to the range 1 to length. Returns the table itself.

This function can also be used to create a new initialized array. Pass in NIL as the table parameter, and a new table will be created, filled, and returned.


table.foreach(...)

Undocumented Lua builtin.


table.foreachi(...)

Undocumented Lua builtin.


table.getn(...)

Undocumented Lua builtin.


table.insert(table, [pos,] value)

Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t.


table.isearch(array, value [, start [, end]])

Searches an array for a given value. Returns the index, if the value is in the array, otherwise returns nil. If the value is in the array more than once, returns the lowest index. If start and end are specified, only the specified subrange is searched. If a start or end value outside the range 1-length is specified, the range is clamped to the valid indices. Start and end values are inclusive.

The input must be an array (a table whose keys are integers starting with 1 and ascending.)


table.makearray(size, size, size...)

Creates and returns a multidimensional array. A three-dimensional array would be accessed like this:


array[x][y][z] = value

The multidimensional array is implemented as a series of nested lua tables. The initial data is NIL.


table.maxn(table)

Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)


table.print(tab)

Prints the contents of the table. Mostly for debugging purposes.


table.remove(table [, pos])

Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.


table.replace(table, search-value, replace-value)

Searches a table for the search-value, and replaces it with the replace-value wherever it occurs. Modifies the input table. Returns the number of replacements it performed.


table.reverse(array)

Reverses an array. The return value is a new table containing the same values as the input table, but in the reverse order.

The input must be an array (a table whose keys are integers starting with 1 and ascending.)



table.setn(...)

Undocumented Lua builtin.


table.sort(table [, comp])

Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.


table.sortedkeys(tab [,comp])

Returns a list of the keys in table, in sorted order.


table.subrange(array, start, end)

Returns a new array containing a subrange of the input array. If a start or end value outside the range 1-length is specified, the range is clamped to the valid indices. Start and end values are inclusive. If end is less than start, an empty array is returned.

The input must be an array (a table whose keys are integers starting with 1 and ascending.)