Viewer 3D API v1.0

Getting started

The Viewer 3D API allows developers to embed the bimsync viewer in their applications.

Dependencies

The viewer requires jQuery 1.x to run.

Initialize

The viewer can either be automatically initialized by using the DOM data API or manually initialized in JavaScript.

DOM Data API

  1. Create a viewer access token by using the POST /viewer/access resources in the bimsync API.

  2. Add the viewer framework to you application:

    <script type="text/javascript" src="https://api.bimsync.com/1.0/js/viewer.js"></script>
    
  3. Create a viewer instance. The data attribute data-viewer must have the value webgl. The data attribute data-url must be the url field from a viewer access token.

    <div data-viewer="webgl" data-url="https://api.bimsync.com/1.0/viewer/access?token=897..."></div>
    

To enable the viewer UI plugin, add the data attribute, data-ui, to the viewer element. See the viewer UI plugin documentation for more info.

JavaScript

  1. Create a viewer access token by using the POST /viewer/access resources in the bimsync API.

  2. Create a DIV element which will contain the viewer.

    <div id="viewer-container"></div>
    
  3. Follow the pattern in the snippet below to initialize:

    <script type="text/javascript" src="https://api.bimsync.com/1.0/js/viewer.js"></script>
    <script type="text/javascript">
        // Load the Viewer API.
        bimsync.load();
    
        // Set a callback to run when the Viewer API is loaded
        bimsync.setOnLoadCallback(createViewer);
    
        // Callback that loads a viewer access token URL
        function createViewer() {
            $('#viewer-container').viewer('loadUrl', 'https://api.bimsync.com/1.0/viewer/access?token=897...');
        }
    </script>
    

To enable the viewer UI plugin, a parameter could be passed to the bimsync.load() method. See the viewer UI plugin documentation for more info.

Options

All options can be set using data attributes on the viewer element, or passed as an object when initializing with JavaScript.

var options = {
    defaultColor: String or Number,     // Any valid CSS color, default: '#101010'
    selectedColor: String or Number,    // Any valid CSS color, default: '#a7f555'
    translucentOpacity: Number,         // Default: 0.05
    fieldOfView: Number,                // Number in degrees, default: 60
    enableTouch: Boolean,               // Default: false
    enableClippingPlaneWidget: Boolean  // Default: false
}

Setting options when using JavaScript initialization:

$('#viewer-container').viewer({
    defaultColor: 'red',
    selectedColor: 'blue',
    translucentOpacity: 0.05,
    enableTouch: true,
    enableClippingPlaneWidget: true
});
$('#viewer-container').viewer('loadUrl', 'https://api.bimsync.com/1.0/viewer/access?token=897...');

Setting options when using data attribute initialization:

<div data-viewer="webgl" data-url="https://api.bimsync.com/1.0/viewer/access?token=897..."
    data-default-color="#22ff22" data-enable-touch="true" data-translucent-opacity="0.1"></div>

defaultColor

The default color for objects that has no color specified.

selectedColor

The color of selected objects.

translucentOpacity

The opacity of translucent objects.

fieldOfView

The camera field of view.

enableTouch

Enables touch support.

enableClippingPlaneWidget

Enables a clipping plane widget that makes viewing and selecting clipping planes easier. The widget will only appear when there exists at least one clipping plane.

Methods

All methods are invoked by calling the method viewer on the result of a jQuery/$ function call. The first argument to the viewer method must be the method name.

Chaining and callbacks

In bimsync Viewer API v1.0 all methods are chainable. This design decision causes the API to be rather callback heavy. A pattern being used is that the same method can be used to both set and get a value from the viewer. The value will then be returned using a callback function. When calling callbacks, the this value will be set to the viewer's DOM element.

Example

Given a viewer initialized using the DOM API:

<div class="viewer" data-viewer="webgl" data-url="..."></div>

The following chained method calls will isolate object id '1':

$('.viewer').viewer('hideAll').viewer('show', '1')

The following takes a screenshot of an isolated object and resets the view:

$('.viewer').viewer('hideAll')
            .viewer('show', '1')
            .viewer('screenshot', function(screenshot) {
    $('img').attr('src', screenshot);
    $(this).viewer('showAll');
});

show

Makes a hidden or translucent object visible.

Parameters:

  • id - String or Array

showAll

Makes all objects visible.

Parameters: None

hide

Makes object hidden.

Parameters:

  • id - String or Array

hideAll

Hides all objects.

Parameters: None

translucent

Makes object translucent.

Parameters:

  • id - String or Array

translucentAll

Make all objects translucent.

Parameters: None

select

Marks object as selected.

Parameters:

  • id - String or Array

deselect

Removes object from selected set.

Parameters:

  • id - String or Array

deselectAll

Clears selected set.

Parameters: None

showModel

Makes a hidden model visible.

Parameters:

  • id - String

hideModel

Hides a model.

Parameters:

  • id - String

loadUrl

Load the contents of a viewer access token.

Parameters:

  • url - String

Example:

$('.viewer').viewer('loadUrl', 'https://api.bimsync.com/1.0/viewer/access?token=8975b4a3149a49ba8bcc40f4ababc0d1');

unloadModel

Unloads a model.

Parameters:

  • id - String

transformModel

Moves, scales and rotates a model.

Parameters:

  • id - String
  • transform - Object

Example:

// Move the model along the x-axis, scale it in y-direction, rotate it around the z-axis
$('.viewer').viewer('transformModel', 'dabc6dfce6e849bfada976d9fa9e294a', {
    position: {x: 1, y: 0, z: 0},
    scale: {x: 1, y: 1.5, z: 1},
    rotation: {x: 0, y: 0, z: 1, angle: 1.57}
});

transitionSettings

Set camera transition settings. Controls camera transition animations triggered by calls to lookAt, lookAtBoundingBox or viewpoint.

The viewer is initialized with the following transition settings:

{
  duration: 0,
  easing: 'LinearNone'
}

Parameters:

  • settings - Object

Settings fields:

  • duration - Number - animation duration in milliseconds
  • easing - String - name of easing function

Easing functions:

The following easing functions are available:

  • LinearNone
  • QuadraticIn
  • QuadraticOut
  • QuadraticInOut
  • CubicIn
  • CubicOut
  • CubicInOut
  • QuarticIn
  • QuarticOut
  • QuarticInOut
  • QuinticIn
  • QuinticOut
  • QuinticInOut
  • SinusoidalIn
  • SinusoidalOut
  • SinusoidalInOut
  • ExponentialIn
  • ExponentialOut
  • ExponentialInOut
  • CircularIn
  • CircularOut
  • CircularInOut
  • ElasticIn
  • ElasticOut
  • ElasticInOut
  • BackIn
  • BackOut
  • BackInOut
  • BounceIn
  • BounceOut
  • BounceInOut

Example:

$('.viewer').viewer('transitionSettings', {
  duration: 500,
  easing: 'QuadraticInOut'
})

viewpoint

Get and set current viewpoint.

Parameters:

  • viewpoint - String or Object
  • optional callback - Function(Object viewpoint)

Example:

// Get current viewpoint
$('.viewer').viewer('viewpoint', null, function(viewpoint) {
    console.log(viewpoint);
});

// Set predefined viewpoint - available 'home', 'top', 'left', 'right', 'front', 'back'
$('.viewer').viewer('viewpoint', 'top');

// Set perspective viewpoint
$('.viewer').viewer('viewpoint', {
    direction: {
        x: 0,
        y: -1,
        z: 0
    },
    location: {
        x: 0,
        y: 100,
        z: 0,
    },
    up: {
        x: 0,
        y: 0,
        z: 1
    },
    fov: 50,
    type: 'perspective'
});

// Set orthogonal viewpoint
$('.viewer').viewer('viewpoint', {
    direction: {
        x: 0,
        y: 0,
        z: -1
    },
    location: {
        x: 7
        y: 2.5
        z: 17
    },
    up: {
        x: 0,
        y: 0,
        z: 1
    },
    viewToWorldScale: 14,
    type: 'orthogonal'
});

clippingPlanes

Set or get clipping planes. The viewer can display up to six clipping planes.

Parameters:

  • clippingPlanes - Array
  • optional callback - Function(Array clippingPlanes)

Example:

var clippingPlanes = [
  {
    location: {
      x: 6.9000000953674245,
      y: 2.4132123330870963,
      z: 4.384152126303485
    },
    direction: {
      x: 0,
      y: 0,
      z: 1
    }
  },
  {
    location: {
      x: 6.9000000953674245,
      y: 2.4132123333570963,
      z: 1.6841521263034842
    },
    direction: {
      x: 0,
      y: 0,
      z: -1
    }
  }
];

// Set
$('.viewer').viewer('clippingPlanes', clippingPlanes);
or
$('.viewer').bind('viewer.contextmenu', function(event, selected, intersects) {
    $('.viewer').viewer('clippingPlanes', [ { location: intersects.point, direction: intersects.normal } ]);
});

NOTE: To select a clipping plane you have to hold down the SHIFT key while clicking on the plane. When the plane is selected you should be able to move it using the mouse.

// Get
$('.viewer').viewer('clippingPlanes', null, function(clippingPlanes) {
    console.log(clippingPlanes);
});

clippingPlaneWidgetViewport

Set the position and size og the clipping plane widget. Note that the enableClippingPlaneWidget option have to be set to true to get this to work.

Parameters:

  • viewport - object

Viewport fields:

  • x - Number - widget x-coordinate
  • y - Number - widget y-coordinate
  • width - Number - width of the widget
  • height - Number - height of the widget

Example:

$('.viewer').viewer('clippingPlaneWidgetViewport', {x: 0, y: 300, width: 150, height: 150});

images

Set or get images. Images are displayed on a plane defined by a size and transformation. If not transformed, the image will be placed with its center in the origin (0, 0, 0) facing up (position Z-axis). Supported formats are PNG, JPG, GIF and DDS. Size and transform position is defined in meters.

Parameters:

  • images - Array
  • optional callback - Function(Array images)

Example:

// Set image
$('.viewer').viewer('images', [{
  url: 'http://example.com/example.jpg'),
  size: {width: 200, height: 100},
  transform: {
    position: {x: 100, y: 50, z: 0},
    rotation: {x: 0, y: 0, z: 1, angle: Math.PI / 2}
  }
}]);

section

Create clipping planes relative to the axis aligned bounding box of the provide objects.

Parameters:

  • id - String or Array
  • planes - Array containg one or more of 'top', 'bottom', 'left', 'right', 'front', 'back'

Example:

// Create clipping planes above and below objects
$('.viewer').viewer('section', [ '1', '2' ], ['top', 'bottom']);

screenshot

Create a screenshot as base64 encoded PNG.

Parameters:

  • callback - Function(String screenshot)

Example:

$('.viewer').viewer('screenshot', function(screenshot) {
    $('img').attr('src', screenshot);
});

color

Set or get object color.

Parameters:

  • color - String
  • id - String or Array
  • optional callback - Function(Object colors)

Example:

// RGB
$('.viewer').viewer('color', '#FF0000', [ '1', '2' ]);

// RGBA
$('.viewer').viewer('color', '#FF0000A0', [ '1', '2' ]);

// Get colors
$('.viewer').viewer('color', null, [ '1', '2' ], function(colors) {
    // 'colors' will contain
    // {
    //   1: {
    //     color: {r: 1.0, g: 0.0, b: 0.0},
    //     opacity: 1.0
    //     style: '#FF0000FF
    //   },
    //   2: { ...
    //   }
    // }
});

resetColors

Resets colors to the defaults.

Parameters: None

lookAt

Move given objects into view. An optional predefined camera direction can be provided.

Parameters:

  • id - String or Array
  • optional direction - String

Example:

// Use current camera direction
$('.viewer').viewer('lookAt', [ '18439659', '18439683', '18439751', '18439776' ]);

// Use predefined direction - available 'home', 'top', 'left', 'right', 'front', 'back'
$('.viewer').viewer('lookAt', [ '18439659', '18439683', '18439751', '18439776' ], 'top');

boundingBox

Calculate the axis aligned bounding box of one or more objects. If the id is null the bounding box of all objects is returned. The bounding box will have the shape

{
  min: {
    x: ...
    y: ...
    z: ...
  },
  max: {
    x: ...
    y: ...
    z: ...
  }
}

Parameters:

  • id - String or Array
  • callback - Function(Object boundingbox)

Example:

$('.viewer').viewer('boundingBox', [ '18439659', '18439683', '18439751', '18439776' ], function(boundingbox) {
  console.log(boundingbox);
});

lookAtBoundingBox

Move bounding box into view. An optional predefined camera direction can be provided.

Parameters:

  • boundingBox - Object
  • optional direction - String

Example:

// Get boundingbox of given objects
$('.viewer').viewer('boundingBox', [ '18439659', '18439683', '18439751', '18439776' ], function(boundingBox) {
    // Use current camera direction
    $('.viewer').viewer('lookAtBoundingBox', boundingBox);

    // Use predefined direction - available 'home', 'top', 'left', 'right', 'front', 'back'
    $('.viewer').viewer('lookAtBoundingBox', boundingBox, 'top');
});

// Get model bounding box
$('.viewer').viewer('modelInfo', 'ce168045...', function(modelInfos) {
    $('.viewer').viewer('lookAtBoundingBox', modelInfos[0].boundingBox);
});

each

Calls a function for each object.

Parameters:

For all objects in viewer:

  • callback - Function(String id)

All objects of a specific model:

  • modelId - String
  • callback - Function(String id)

eachSelected

Calls a function for each selected object.

Parameters:

  • callback - Function(String id)

Example:

$('.viewer').viewer('eachSelected', function(id) {
    $(this).viewer('hide', id);
});

objectInfo

Returns information for one or more objects. Each info object contains the following properties:

  • id - String - id of the object
  • modelId - String - id of the model the object belongs to.
  • triangleCount - Number - number of triangles

Querying information for unknown ids will result in the info object being null. If id is not provided, the method will return info for all objects.

Parameters:

  • optional id - String or Array
  • callback - Function(Array info)

Example:

$('.viewer').viewer('objectInfo', ['18439659', 'UNKNOWN_ID'], function(info) {
    console.log(info[0]);
    // info[1] will be null
});

modelInfo

Returns an array of model info objects. For now the modelId and the model boundingBox are returned.

Note that this method only returns information about loaded models.

Parameters: - optional modelId - String or Array - callback - Function(Array modelInfos)

Example:

$('.viewer').viewer('modelInfo', function(modelInfos) {
    console.log(modelInfos);
    // This will print model info for all loaded models
});

$('.viewer').viewer('modelInfo', 'ce168045...', function(modelInfos) {
    console.log(modelInfos[0]);
    // This will print model info for the given model id

    $('.viewer').viewer('lookAtBoundingBox', modelInfos[0].boundingBox);
});

keyDown

Move camera using one or more of the the following keywords:

  • moveForward
  • moveBackward
  • moveLeft
  • moveRight
  • moveUp
  • moveDown
  • rotateUp
  • rotateDown
  • rotateLeft
  • rotateRight

Parameters:

  • Object - Object where fields are keywords with a boolean specifiying if it is pressed

Example:

// When the user press the 'w' key, move forward
$('.viewer').viewer('keyDown', {moveForward: true});

// The camera will now move straight ahead until
$('.viewer').viewer('keyDown', {moveForward: false});

resetKeyDown

Mark all keys as being released.

Parameters: None

Example:

If the current browser window loose focus, keyup events may not trigger. To avoid moving after loosing focus on the window, trigger:

$(window).bind('blur', function() {
    $(viewer).viewer('resetKeyDown');
});

navigate

Navigate in one of the directions listed in the keydown method.

Parameters:

  • Object - Object where keys are one of the values listed in the keydown method, and the value is a number specifiying the movement force/speed

Example:

$('.viewer').viewer('navigate', { moveForward: 1.5, rotateRight: 0.5});

// Another example:
var randomMovement = function() {
    var sin = Math.sin(Math.random() * Math.PI);
    var cos = Math.cos(Math.random() * Math.PI);
    $('.viewer').viewer('navigate', {moveForward: sin, rotateRight: cos});
    setTimeout(randomMovement, 200);
}
randomMovement();

stopNavigation

Stops the movement started by the navigate method.

Parameters: None

Example:

// Start movement
$('.viewer').viewer('navigate', { moveForward: 1.5, rotateRight: 0.5});

// Stop movement
$('.viewer').viewer('stopNavigation');

navigationMode

Sets the current navigation mode.

Parameters:

  • mode - String or object

Predefined modes

The following predefined modes are available.

  • 'orbit' - default mode - orbit camera around a point on drag
  • 'pan' - pan camera on drag

Custom modes

The navigation mode can be customized by specifying an object containing a list of event/action pairs per device. The available devices are 'mouse', 'touch' and 'keyboard'. Passing an empty object ({}) will disable all navigation.

Download example

The source code for the definition of the predefined modes is available for download here.

Download example

Event matching

When an event is triggered by a device, all event/action pairs are evaluated to find the actions to be executed. The event name must match the triggered event and if filter is specified, all filters must match the event state.

Example

Given the following definition:

'mouse': [
  {
    'event': 'click',
    'action': 'click',
  },
  {
    'event': 'click',
    'action': 'select',
    'filter': {
      'button': 0
    }
  }
]

If a user clicks in the viewer with the left button (button 0) both event/action pairs will be executed. Clicking with the right button (button 2) will only execute the first.

Filters

The following filters are available:

  • button: 0 (left button), 1 (middle button), 2 (right button)
  • shiftKey: true, false
  • ctrlKey: true, false
  • metaKey: true, false
  • pointers: number of pointers active in touch events

Event execution

All actions that match an event are executed in the order specified in the device list. If an action is cancelled (e.g. a viewer.click event handler returns false) when executed, the rest of the matching actions will not be executed.

In the example below, the click action will be run before the select action. Cancelling the viewer.click event will stop the select action from executing.

'mouse': [
  {
    'event': 'click',
    'action': 'click',
    'filter': {
      'button': 0
    }
  },
  {
    'event': 'click',
    'action': 'select',
    'filter': {
      'button': 0
    }
  }
]

Action parameters

Each event/action pair can optionally contain the following action parameters passed as properties on the event/action pair object.

  • scale: Action multiplier. Default value is 1.0. Can be used to control sensitivity or invert the action direction by using a negative value.

Mouse events

  • 'click'
  • 'doubleClick'
  • 'wheel'
  • 'drag'

Touch events

  • 'tap'
  • 'doubleTap'
  • 'longPress'
  • 'pan'
  • 'pinch'

Keyboard events

  • 'rotateLeft'
  • 'rotateRight'
  • 'rotateUp'
  • 'rotateDown'
  • 'moveForward'
  • 'moveBackward'
  • 'moveLeft'
  • 'moveRight'
  • 'moveUp'
  • 'moveDown'

Actions

  • 'click'
  • 'doubleClick'
  • 'contextMenu'
  • 'select'
  • 'fitToView'
  • 'zoom'
  • 'zoomMove'
  • 'rotateZ'
  • 'rotateX'
  • 'moveForward'
  • 'moveLeft'
  • 'moveUp'
  • 'orbit'
  • 'pan'
  • 'pivot'

walkSpeed

Sets the walk speed used when navigating with the keyboard controls.

Parameters:

  • speed - Double, value in m/s

Example:

$('.viewer').viewer('walkSpeed', 3.0);

elevationSpeed

Sets the vertical movement speed used when navigating with the keyboard controls.

Parameters:

  • speed - Double, value in m/s

Example:

$('.viewer').viewer('elevationSpeed', 1.0);

rotationSpeed

Sets the rotation speed (in degrees/sec) used when navigating with the keyboard controls.

Parameters:

  • speed - Double, number of degrees to rotate per second

Example:

$('.viewer').viewer('rotationSpeed', 50.0);

fieldOfView

Sets the camera field of view angle in degrees.

Parameters:

  • fieldofview - Double, field of view angle in degrees

Example:

$('.viewer').viewer('fieldOfView', 50.0);

Events

The events created by the viewer are custom jQuery events. Attach a handler to an event with jQuery.bind.

$('.viewer').bind('viewer.select', function(event, selected) {
    console.log(selected);
});

viewer.load

Triggered when viewer and content is completely loaded.

Callback parameters

None

viewer.error

Triggered when something goes wrong.

type String

Error types:

  • 'no-webgl' - WebGL is not supported or disabled
  • 'load-failed' - Loading failed

Callback parameters

viewer.select

Triggered when the set of selected objects is changed by user events (e.g. mouse clicks).

Callback Parameters

selected Array Set of selected object IDs. If no objects are selected the array is empty.

viewer.viewpoint

Triggered when the current viewpoint is changed by user events (e.g. mouse drags).

Callback Parameters

viewpoint Object A viewpoint

viewer.click

Triggered when the user clicks inside the viewer. Returning false from the event handler will cancel the default viewer behavior.

Callback Parameters

id String Id of the object below the cursor. Undefined if no objects are below the cursors.
intersects Object Position of the object below the cursor, and a direction vector perpendicular to the surface of the object. Undefined if no objects are below the cursors.

viewer.doubleclick

Triggered when the user doubleclick clicks inside the viewer. Returning false from the event handler will cancel the default viewer behavior.

Callback Parameters

id String Id of the object below the cursor. Undefined if no objects are below the cursors.
intersects Object Position of the object below the cursor, and a direction vector perpendicular to the surface of the object. Undefined if no objects are below the cursors.

viewer.contextmenu

Triggered when the user summons the context menu (e.g. by right-clicking).

Callback Parameters

id String Id of the object below the cursor. Undefined if no objects are below the cursors.
intersects Object Position of the object below the cursor, and a direction vector perpendicular to the surface of the object. Undefined if no objects are below the cursors.