API Docs for: 1.0.0

Scene

Extends Component
Defined in: src/scene.js:1
Module: xeogl

A Scene models a 3D scene as a fully-editable and serializable component-entity graph.

Scene Structure

A Scene contains a soup of instances of various Component subtypes, such as Entity, Camera, Material, Lights etc. Each Entity has a link to one of each of the other types, and the same component instances can be shared among many Entities.

Under the hood: Within xeogl, each Entity represents a draw call, while its components define all the WebGL state that will be bound for that call. To render a Scene, xeogl traverses the graph to bind the states and make the draw calls, while using many optimizations for efficiency (eg. draw list caching and GL state sorting).

Default Components

A Scene provides its own default flyweight instance of each component type (except for Entity). Each Entity you create will implicitly link to a default instance for each type of component that you don't explicitly link it to. For example, when you create an Entity without a Lights, the Entity will link to the Scene's default lights. This mechanism provides training wheels to help you learn the API, and also helps keep examples simple, where many of the examples in this documentation are implicitly using those defaults when they are not central to discussion.

At the bottom of the diagram above, the blue Material, Geometry and Camera components represent some of the defaults provided by our Scene. For brevity, the diagram only shows those three types of component (there are actually around two dozen).

Note that we did not link the second Entity to a Material, causing it to be implicitly linked to our Scene's default Material. That Material is the only default our Entities are falling back on in this example, with other default component types, such as the Geometry and the Camera, hanging around dormant until an Entity is linked to them.

Note also how the same Camera is linked to both of our Entities. Whenever we update that Camera, it's going to affect both of those Entities in one shot. Think of the defaults as the Scene's global component instances, which you may optionally override on a per-Entity basis with your own component instances. In many Scenes, for example, you might not even bother to create your own Camera and just let all your Entities fall back on the default one.

Usage

Here's the JavaScript for the diagram above. As mentioned earlier, note that we only provide components for our Entities when we need to override the default components that the Scene would have provided them, and that the same component instances may be shared among multiple Entities.

var scene = new xeogl.Scene({
      id: "myScene"   // ID is optional on all components
 });

var material = new xeogl.PhongMaterial(myScene, {
      id: "myMaterial",         // We'll use this ID to show how to find components by ID
      diffuse: [ 0.6, 0.6, 0.7 ],
      specular: [ 1.0, 1.0, 1.0 ]
  });

var geometry = new xeogl.Geometry(myScene, {
      primitive: "triangles",
      positions: [...],
      normals: [...],
      uvs: [...],
      indices: [...]
 });

var camera = new xeogl.Camera(myScene);

var entity1 = new xeogl.Entity(myScene, {
      material: myMaterial,
      geometry: myGeometry,
      camera: myCamera
 });

// Second entity uses Scene's default Material
var entity3 = new xeogl.Entity(myScene, {
      geometry: myGeometry,
      camera: myCamera
 });

The Scene Canvas

See the Canvas component.

Finding Scenes and Components by ID

We can have as many Scenes as we want, and can find them by ID on the Xeogl entity's Xeogl/scenes:property map:

var theScene = xeogl.scenes["myScene"];

Likewise we can find a Scene's components within the Scene itself, such as the Material we created earlier:

var theMaterial = myScene.components["myMaterial"];

The Default Scene

When you create components without specifying a Scene for them, xeogl will put them in its default Scene.

For example:


var material2 = new xeogl.PhongMaterial({
   diffuse: { r: 0.6, g: 0.6, b: 0.7 },
   specular: { 1.0, 1.0, 1.0 }
});

var geometry2 = new xeogl.Geometry({
    primitive: "triangles",
    positions: [...],
    normals: [...],
    uvs: [...],
    indices: [...]
});

var camera = new xeogl.Camera();

var entity1 = new xeogl.Entity({
    material: material2,
    geometry: geometry2,
    camera: camera2
});

You can then obtain the default Scene from the Xeogl entity's Xeogl/scene:property property:

var theScene = xeogl.scene;

or from one of the components we just created:

var theScene = material2.scene;

Note: xeogl creates the default Scene as soon as you either create your first Sceneless Entity or reference the Xeogl entity's Xeogl/scene:property property. Expect to see the HTML canvas for the default Scene magically appear in the page when you do that.

WebGL 2

By default, our Scene will attempt to use WebGL 2. If that's not supported then it will fall back on WebGL 1, if available. You can force the Scene to use WebGL 1 by supplying this property to teh Scene's constructor:

var scene = new xeogl.Scene({
    webgl2: false // Default is true
});

// We can then check this property on the Canvas to see if WebGL 2 is supported:
var gotWebGL2 = scene.canvas.webgl2; // True if we have WebGL 2

Constructor

Scene

(
  • [cfg]
)

Defined in src/scene.js:1

Parameters:

  • [cfg] Object optional

    Scene parameters

    • [id] String optional

      Optional ID, unique among all Scenes in xeogl, generated automatically when omitted.

    • [meta] String:Object optional

      Optional map of user-defined metadata to attach to this Scene.

    • [canvasId] String optional

      ID of existing HTML5 canvas in the DOM - creates a full-page canvas automatically if this is omitted

    • [webgl2=true] Boolean optional

      Set this false when we don't want to use WebGL 2 for our Scene; the Scene will fall back on WebGL 1 if not available. This property will be deprecated when WebGL 2 is supported everywhere.

    • [components] Array(Object) optional

      JSON array containing parameters for Component subtypes to immediately create within the Scene.

    • [ticksPerRender=1] Number optional

      The number of Scene/tick:property that happen between each render or this Scene.

    • [passes=1] Number optional

      The number of times this Scene renders per frame.

    • [clearEachPass=false] Boolean optional

      When doing multiple passes per frame, specifies whether to clear the canvas before each pass (true) or just before the first pass (false).

    • [transparent=false] Boolean optional

      Whether or not the canvas is transparent.

    • [backgroundColor] Float32Array optional

      RGBA color for canvas background, when canvas is not transparent. Overridden by backgroundImage.

    • [backgroundImage] String optional

      URL of an image to show as the canvas background, when canvas is not transparent. Overrides backgroundImage.

Methods

_getSharedComponent

(
  • [cfg]
  • instanceId
)
private

Defined in src/scene.js:1503

Convenience method for creating or reusing a Component within this Scene.

You would typically use this method to conveniently instantiate components that you'd want to share (ie. "instance") among your Entities.

The method is given a component type, share ID and constructor attributes, like so:

var material = myScene.getComponent("xeogl.PhongMaterial", "myMaterial", { diffuse: [1,0,0] });

The first time you call this method for the given type and instanceId, this method will create the PhongMaterial, passing the given attributes to the component's constructor.

If you call this method again, specifying the same type and instanceId, the method will return the same component instance that it returned the first time, and will ignore the attributes:

var material2 = myScene.getComponent("xeogl.PhongMaterial", "myMaterial", { specular: [1,1,0] });

Each time you call this method with the same type and instanceId, the Scene will internally increment a reference count for the component instance. You can release the shared component instance with a call to Scene/putSharedComponent:method, and once you have released it as many times as you got it, the Scene will destroy the component.

Parameters:

  • [cfg] optional

    Attributes for the component instance - only used if this is the first time you are getting the component, ignored when reusing an existing shared component.

  • instanceId String | Number

    Identifies the shared component instance. Note that this is not used as the ID of the component - you can specify the component ID in the cfg parameter.

Returns:

:

clear

()

Defined in src/scene.js:1477

Resets this Scene to its default state.

References to any components in this Scene will become invalid.

create

(
  • [cfg]
  • [instanceId]
)

Convenience method for creating a Component within this Component's Scene.

You would typically use this method to conveniently instantiate components that you'd want to share (ie. "instance") among your Entities.

The method is given a component type, configuration and optional instance ID, like so:

var material = myComponent.create({
     type: "xeogl.PhongMaterial",
     diffuse: [1,0,0],
     specular: [1,1,0]
}, "myMaterial");

The first time you call this method for the given type and instanceId, this method will create the PhongMaterial, passing the given attributes to the component's constructor.

If you call this method again, specifying the same type and instanceId, the method will return the same component instance that it returned the first time, and will ignore the new configuration:

var material2 = component.create({ type: "xeogl.PhongMaterial", specular: [1,1,0] }, "myMaterial");

So in this example, our PhongMaterial will continue to have the red specular and diffuse color that we specified the first time.

Each time you call this method with the same type and instanceId, the Scene will internally increment a reference count for the component instance.

Parameters:

  • [cfg] optional

    Configuration for the component instance - only used if this is the first time you are getting the component, ignored when reusing an existing instance.

  • [instanceId] String | Number optional

    Identifies the shared component instance. Note that this is not used as the ID of the component - you can specify the component ID in the cfg parameter.

Returns:

:

destroy

()

Destroys this component.

Fires a destroyed event on this Component.

Automatically disassociates this component from other components, causing them to fall back on any defaults that this component overrode on them.

TODO: describe effect with respect to #create

error

(
  • message
)

Logs an error for this component to the JavaScript console.

The console message will have this format: [ERROR] [<component type> =<component id>: <message>

Also fires the message as an error event on the parent Scene.

Parameters:

  • message String

    The message to log

fire

(
  • event
  • value
  • [forget=false]
)

Fires an event on this component.

Notifies existing subscribers to the event, optionally retains the event to give to any subsequent notifications on the event as they are made.

Parameters:

  • event String

    The event type name

  • value Object

    The event parameters

  • [forget=false] Boolean optional

    When true, does not retain for subsequent subscribers

hasSubs

(
  • event
)
Boolean

Returns true if there are any subscribers to the given event on this component.

Parameters:

  • event String

    The event

Returns:

Boolean:

True if there are any subscribers to the given event on this component.

isType

(
  • type
)
Boolean

Tests if this component is of the given type, or is a subclass of the given type.

The type may be given as either a string or a component constructor.

This method works by walking up the inheritance type chain, which this component provides in property superTypes, returning true as soon as one of the type strings in the chain matches the given type, of false if none match.

Examples:

var myRotate = new xeogl.Rotate({ ... });

myRotate.isType(xeogl.Component); // Returns true for all xeogl components
myRotate.isType("xeogl.Component"); // Returns true for all xeogl components
myRotate.isType(xeogl.Rotate); // Returns true
myRotate.isType(xeogl.Transform); // Returns true
myRotate.isType("xeogl.Transform"); // Returns true
myRotate.isType(xeogl.Entity); // Returns false, because xeogl.Rotate does not (even indirectly) extend xeogl.Entity

Parameters:

  • type String | Function

    Component type to compare with, eg "xeogl.PhongMaterial", or a xeogl component constructor.

Returns:

Boolean:

True if this component is of given type or is subclass of the given type.

log

(
  • message
)

Logs a console debugging message for this component.

The console message will have this format: [LOG] [<component type> <component id>: <message>

Also fires the message as a log event on the parent Scene.

Parameters:

  • message String

    The message to log

off

(
  • handle
)

Cancels an event subscription that was previously made with on or once.

Parameters:

  • handle String

    Publication handle

on

(
  • event
  • callback
  • [scope=this]
)
String

Subscribes to an event on this component.

The callback is be called with this component as scope.

Parameters:

  • event String

    The event

  • callback Function

    Called fired on the event

  • [scope=this] Object optional

    Scope for the callback

Returns:

String:

Handle to the subscription, which may be used to unsubscribe with {@link #off}.

once

(
  • event
  • callback
  • [scope=this]
)

Subscribes to the next occurrence of the given event, then un-subscribes as soon as the event is handled.

This is equivalent to calling on, and then calling off inside the callback function.

Parameters:

  • event String

    Data event to listen to

  • callback Function(data)

    Called when fresh data is available at the event

  • [scope=this] Object optional

    Scope for the callback

pick

(
  • params
)

Defined in src/scene.js:1154

Attempts to pick an Entity in this Scene.

Ignores Entities with pickable set false.

Picking the Entity at the given canvas coordinates:

var hit = scene.pick({
    canvasPos: [23, 131]
 });

if (hit) { // Picked an Entity
    var entity = hit.entity;
}

Usage:

Picking the Entity that intersects a ray cast through the canvas:

var hit = scene.pick({
    pickSurface: true,
    canvasPos: [23, 131]
 });

if (hit) { // Picked an Entity

    var entity = hit.entity;

    // These properties are only on the hit result when we do a ray-pick:

    var primitive = hit.primitive; // Type of primitive that was picked, usually "triangles"
    var primIndex = hit.primIndex; // Position of triangle's first index in the picked Entity's Geometry's indices array
    var indices = hit.indices; // UInt32Array containing the triangle's vertex indices
    var localPos = hit.localPos; // Float32Array containing the picked Local-space position on the triangle
    var worldPos = hit.worldPos; // Float32Array containing the picked World-space position on the triangle
    var viewPos = hit.viewPos; // Float32Array containing the picked View-space position on the triangle
    var bary = hit.bary; // Float32Array containing the picked barycentric position within the triangle
    var normal = hit.normal; // Float32Array containing the interpolated normal vector at the picked position on the triangle
    var uv = hit.uv; // Float32Array containing the interpolated UV coordinates at the picked position on the triangle
}

Picking the Entity that intersects an arbitrarily-aligned World-space ray:

var hit = scene.pick({
    pickSurface: true,       // Picking with arbitrarily-positioned ray
    origin: [0,0,-5],    // Ray origin
    direction: [0,0,1]   // Ray direction
});

if (hit) { // Picked an Entity with the ray

    var entity = hit.entity;

    var primitive = hit.primitive; // Type of primitive that was picked, usually "triangles"
    var primIndex = hit.primIndex; // Position of triangle's first index in the picked Entity's Geometry's indices array
    var indices = hit.indices; // UInt32Array containing the triangle's vertex indices
    var localPos = hit.localPos; // Float32Array containing the picked Local-space position on the triangle
    var worldPos = hit.worldPos; // Float32Array containing the picked World-space position on the triangle
    var viewPos = hit.viewPos; // Float32Array containing the picked View-space position on the triangle
    var bary = hit.bary; // Float32Array containing the picked barycentric position within the triangle
    var normal = hit.normal; // Float32Array containing the interpolated normal vector at the picked position on the triangle
    var uv = hit.uv; // Float32Array containing the interpolated UV coordinates at the picked position on the triangle
    var origin = hit.origin; // Float32Array containing the World-space ray origin
    var direction = hit.direction; // Float32Array containing the World-space ray direction
}

Parameters:

  • params

    Picking parameters.

    • [pickSurface=false] Boolean optional

      Whether to find the picked position on the surface of the Entity.

    • [canvasPos] Float32Array optional

      Canvas-space coordinates. When ray-picking, this will override the origin and direction parameters and will cause the ray to be fired through the canvas at this position, directly along the negative View-space Z-axis.

    • [origin] Float32Array optional

      World-space ray origin when ray-picking. Ignored when canvasPos given.

    • [direction] Float32Array optional

      World-space ray direction when ray-picking. Also indicates the length of the ray. Ignored when canvasPos given.

Returns:

:

Hit record, returned when an Entity is picked, else null. See method comments for description.

render

(
  • [forceRender=false]
)

Defined in src/scene.js:550

Renders a single frame of this Scene.

The Scene will automatically call this method on itself to render after any updates, but you can call this method to force a render if required. This method is typically used when we want to synchronously take a snapshot of the canvas and need everything rendered right at that moment.

Parameters:

  • [forceRender=false] Boolean optional

    Forces a render when true, otherwise only renders if something has changed in this Scene since the last render.

warn

(
  • message
)

Logs a warning for this component to the JavaScript console.

The console message will have this format: [WARN] [<component type> =<component id>: <message>

Also fires the message as a warn event on the parent Scene.

Parameters:

  • message String

    The message to log

Properties

camera

Camera final

Defined in src/scene.js:788

The default Camera provided by this Scene.

This Camera has an id equal to "default.camera", with all other properties initialised to their default values.

Entities within this Scene are attached to this Camera by default.

canvas

Canvas final

Defined in src/scene.js:287

Manages the HTML5 canvas for this Scene.

clearEachPass

Boolean

Defined in src/scene.js:698

When doing multiple passes per frame, specifies whether to clear the canvas before each pass (true) or just before the first pass (false).

Fires a clearEachPass event on change.

Default: false

clips

Clips final

Defined in src/scene.js:837

The default Clips provided by this Scene.

This Clips has an id equal to "default.clips", with all other properties initialised to their default values.

Entities within this Scene are attached to this Clips by default.

components

String:xeogl.Component

Defined in src/scene.js:224

The Components within this Scene, mapped to their IDs.

Will also contain the Entitys contained in Entity/components:property.

configs

Configs final

Defined in src/scene.js:278

Configurations for this Scene. Set whatever properties on here that will be useful to the components within the Scene.

destroyed

Boolean

True as soon as this Component has been destroyed

entities

String:xeogl.Entity

Defined in src/scene.js:245

The Entitys within this Scene, mapped to their IDs.

The Entitys in this map will also be contained in Entity/components:property.

entities

String:xeogl.Model

Defined in src/scene.js:257

The Models within this Scene, mapped to their IDs.

geometry

BoxGeometry final

Defined in src/scene.js:860

The default geometry provided by this Scene, which is a BoxGeometry.

This BoxGeometry has an id equal to "default.geometry".

Entities within this Scene are attached to this Geometry by default.

id

String final

Unique ID for this Component within its parent Scene.

input

Input final

Defined in src/scene.js:317

Publishes input events that occur on this Scene's canvas.

isDefault

Boolean

Indicates whether this is one of the Scene's built-in Components.

json

JSON final

JSON object containing the state of this Component.

lights

Lights final

Defined in src/scene.js:881

The default Lights provided by this Scene.

This Lights has an id equal to "default.lights", with all other properties initialised to their default values (ie. the default set of light sources for a Lights).

Entities within this Scene are attached to this Lights by default.

material

PhongMaterial final

Defined in src/scene.js:950

The PhongMaterial provided as the default material by this Scene.

This PhongMaterial has an id equal to "default.material", with all other properties initialised to their default values.

Entities within this Scene are attached to this PhongMaterial by default.

metadata

Object

Arbitrary, user-defined metadata on this component.

morphTargets

MorphTargets private final

Defined in src/scene.js:974

The default MorphTargets provided by this Scene.

This MorphTargets has an id equal to "default.morphTargets", with all other properties initialised to their default values.

Entities within this Scene are attached to this MorphTargets by default.

outline

Outline final

Defined in src/scene.js:1022

The default Outline provided by this Scene.

This Outline has an id equal to "default.outline", a color set to [1,1,0] a thickness set to 15.

Entities within this Scene are attached to this Outline by default.

passes

Number

Defined in src/scene.js:652

The number of times this Scene renders per frame.

Fires a passes event on change.

Default: 1

project

Perspective final

Defined in src/scene.js:737

The default projection transform provided by this Scene, which is a Perspective.

This Perspective has an id equal to "default.project", with all other properties set to their default values.

Cameras within this Scene are attached to this Perspective by default.

scene

Scene final

The parent Scene that contains this Component.

string

String final

Inherited from Component but overwritten in src/component.js:1065

String containing the serialized JSON state of this Component.

superTypes

Array of String final

An array of strings that indicates the chain of super-types within this component's inheritance hierarchy.

For example, if this component is a Rotate, which extends Transform, which in turn extends Component, then this property will have the value:

["xeogl.Component", "xeogl.Transform"]
                    

Note that the chain is ordered downwards in the hierarchy, ie. from super-class down towards sub-class.

ticksPerRender

Number

Defined in src/scene.js:608

The number of Scene/tick:property that happen between each render or this Scene.

Fires a ticksPerRender event on change.

Default: 1

timeCreated

Number

Defined in src/scene.js:216

The epoch time (in milliseconds since 1970) when this Scene was instantiated.

transform

Transform final

Defined in src/scene.js:813

The default modelling Transform provided by this Scene.

This Transform has an id equal to "default.transform", with all other properties initialised to their default values (ie. an identity matrix).

Entities within this Scene are attached to this Transform by default.

type

String final

JavaScript class name for this Component.

This is used when loading Scenes from JSON, and is included in the JSON representation of this Component, so that this class may be instantiated when loading it from the JSON representation.

For example: "xeogl.AmbientLight", "xeogl.ColorTarget", "xeogl.Lights" etc.

types

String:{String:xeogl.Component}

Defined in src/scene.js:236

For each Component type, a map of IDs to instances.

view

Lookat final

Defined in src/scene.js:765

The default viewing transform provided by this Scene, which is a Lookat.

This Lookat has an id equal to "default.view", with all other properties initialised to their default values.

Cameras within this Scene are attached to this Lookat by default.

viewport

Viewport final

Defined in src/scene.js:997

The default Viewport provided by this Scene.

This Viewport has an id equal to "default.viewport" and autoBoundary set true.

Entities within this Scene are attached to this Viewport by default.

worldBoundary

Boundary3D final

Defined in src/scene.js:1071

The World-space 3D boundary of this Scene.

The Boundary3D will be lazy-initialized the first time you reference this property, and will persist on this Scene until you call destroy on the Boundary3D again. The property will then be set to a fresh Boundary3D instance next time you reference it.

Performance

To minimize performance overhead, only reference this property if you need it, and destroy the Boundary3D as soon as you don't need it anymore.

xray

XRay final

Defined in src/scene.js:1048

The default XRay provided by this Scene.

Entities within this Scene are attached to this XRay by default.

Events

clearEachPass

Defined in src/scene.js:722

Fired whenever this Scene's clearEachPass property changes.

Event Payload:

  • value Boolean

    The property's new value

componentCreated

Defined in src/scene.js:464

Fired whenever a component has been created within this Scene.

Event Payload:

  • value Component

    The component that was created

componentDestroyed

Defined in src/scene.js:515

Fired whenever a component within this Scene has been destroyed.

Event Payload:

  • value Component

    The component that was destroyed

destroyed

Fired when this Component is destroyed.

error

Defined in src/scene.js:195

Fired whenever an error is logged on a component within this Scene.

Event Payload:

  • value String

    The error message

log

Defined in src/scene.js:189

Fired whenever a debug message logged on a component within this Scene.

Event Payload:

  • value String

    The debug message

passes

Defined in src/scene.js:684

Fired whenever this Scene's passes property changes.

Event Payload:

  • value Boolean

    The property's new value

rendering

Defined in src/scene.js:594

Fired when we have just rendered a frame for a Scene.

Event Payload:

  • sceneID String

    The ID of this Scene.

  • pass Number

    Index of the pass we rendered (see passes).

rendering

Defined in src/scene.js:581

Fired when about to render a frame for a Scene.

Event Payload:

  • sceneID String

    The ID of this Scene.

  • pass Number

    Index of the pass we are about to render (see passes).

ticksPerRender

Defined in src/scene.js:638

Fired whenever this Scene's ticksPerRender property changes.

Event Payload:

  • value Boolean

    The property's new value

warn

Defined in src/scene.js:201

Fired whenever a warning is logged on a component within this Scene.

Event Payload:

  • value String

    The warning message