The ShapeDiver API

Introduction

The professional version of the ShapeDiver viewer comes with it's own integrated API which can be accessed from scripts on the website where it is embedded.
It works by using web messaging to send commands to the viewer iframe and receive responses from it.
This allows you to integrate a parametric 3d viewer into your own applications and control things like camera movements, parameter updates,
screenshot creation and much much more.
A simple example in which the API is used to read the parameter definitions from a model and set up external sliders to control them can be found here.
We will go through this example in detail below.

Register for use

Since the API is currently under heavy development, we would like to have a good overview of the people who use it and their applications.
On one hand, this enables us to contact you in case of major changes in functionality, updates or news.
On the other hand, knowing what the API is used for should help us target our development resources (which are quite limited at the moment) to those features that are actually needed.

To register for API use, please contact us and let us know a little bit about you and your project.
We will then upgrade your ShapeDiver user account so that

API access is enabled for all your models

you can use extended embedding features like disabling the internal controls in the viewer

Hello world

Let's take a closer look at the example mentioned above. It uses the ShapeDiver demo cube, a very simple model with three number sliders.

The HTML part consists mainly of a ShapeDiver iframe embed code with a single option, showControls, set to false.
This is turning off the internal viewer controls and it is done because we will use the API to set up external controls outside the viewer.
A separate div is added to hold these external controls.

The main functionality is implemented in Javascript, so let's look at the different parts of it step by step.

Here, we simply wait for the iframe to load an then request information about all the parameters set up for this model.
The this within this function refers to the iframe DOM element and as you can see, we send it a simple command without any arguments.
Please note that the ShapeDiver.com domain is added as a second argument to the postMessage function.
This is important for security reasons and makes sure that messages are restricted to the intended recipient, in this case our viewer page.

The function receiveMessage will be called whenever the current document receives a message from the iframe.
As a first step, we retrieve the origin of the message and check if it is legitimate.
Then, we get the actual message data and store its source, which in this case is our ShapeDiver iframe object.

// we expect a JSON object with two values: a command name and a result
if (!data.hasOwnProperty("command")) {
console.warn("Message did not contain command name. Aborting.")
return;
}
// at this point the result might be undefined for the command setParameterValue in many cases, this is being fixed asap
if (!data.hasOwnProperty("result")) {
console.warn("Message did not contain command result. Aborting.")
return;
}
var commandName = data.command;
var result = data.result;

The general structure of messages received from the viewer is very similar to that of messages sent to it.
They always include a commandName which indicates the command to which this message is a response and a result
which can be as simple as a boolean or as complex as parameter descriptions or an image data blob.

Now we get to the only step in this example that is a bit intricate.
We retrieve the actual parameter information from a message and set up number inputs (sliders) using this info.

Reading parameter info and setting up sliders

If the message we received is an answer to getParameterDefinitions we assume that the result is an object containing the definitions of all parameters in the embedded model.
For our example model, this object might look like this:

Using this information, the our function adds three range inputs to the prepared div.
A little problem in this very simple setup is the fact that pure HTML range inputs are a bit limited when it comes to values with decimal places.
We help ourselves by multiplying the values with 10 before applying them to the slider and vice versa.

In the second part of the function above, we set up event watchers for each of the sliders.
On each change of the slider value, we send a message to the viewer which triggers an update.
The setParameterValue command has two arguments: the parameter id and the new value.

As a last step, the function calls to retrieve the current, initial parameter values.
Normally these should be the default values shown in the parameter definitions but there are exceptions to this rule.
The response to this call will be read (see below) and the initial slider values will be set accordingly.

Last but not least, we set an event watcher that catches every message sent to our window and relays it to the receiveMessage function we just created.

This is for sure not the most concise "Hello world" example you have ever seen, but we hope that it does provide a first look at the ShapeDiver API and its basic usage.
If you have feedback, suggestions or questions regarding the API or this introduction, please feel free to write us in our forum.

You can find the complete and constantly growing command reference for the API on this page. When we'll come up with additional examples, we will post them here as well.
If you have built an application or tool that you think should be featured here, please feel free to let us know!

Returns

Boolean

True if the path definition is valid.

This command will prompt the viewer to move its camera on a smooth path interpolating a given set of 3d locations. The camera rotation values and targets are interpolated as well.
The most straightforward way to come up with proper input values for predefined paths is to manually move the camera to a desired location and read the values from the viewer using the getCamera command.

Using the ShapeDiver plugin, designers can define several types of geometry exports in their Grasshopper definitions. Currently, geometry can be downloaded in the browser or sent to an email address specified by the designer. This command returns a list of available exports with their types and names. They can then be triggered by using the requestExport command.

getModelData()

Returns

The object members are named as the unique ids of the individual data members. Their properties include the value and name of the data object.

Retrieves any model data created by ShapeDiver data output Grasshopper components. Values are updated whenever the parameters are changed.

getParameterDefinitions()

Requests the parameter definition information for the loaded model.

Returns

Object

An object describing all available parameter for the
current model. See below for details.

Sending this command will prompt the viewer to return an object
containing the complete parameter information for the loaded model.
The 'result' object will contain one object for each parameter, named
with a unique parameter id.
The content of these parameter objects will vary depending on the type
of the parameter.

Common elements

The following elements are included for all parameter types:

Element

Type

Definition

type

String

The parameter type description.

title

String

The title of the parameter as defined in the GH model.

default

varies

The default value for this parameter. This can be changed
on shapediver.com via the model edit pane.

visibleName

String

The name of the parameter as set in shapediver.com's edit
mode. After uploading a mode, this will be identical to
'title'.

Numerical parameters

The following additional elements are featured in numeric parameter types:

Element

Type

Definition

min

Number

The maximum admissible parameter value.

max

Number

The minimum admissible parameter value.

decimalPlaces

Integer

Number of decimal places allowed for values of this parameter.
If more are provided, the viewer will truncate them before
updating.

List parameters

The parameter types Checklist, Cycle, Sequence and DropDown
are special in that their values consist of integers describing a
selection of values from a list.
For Checklist, the format of the value is a comma separated list
of integer indices as any number of choices can be selected. For the
others, a single integer defines the active choice.
Choices are described in an array aptly named 'choices'.

Element

Type

Definition

choices

Array{String}

Describes the choices from which one (or several) can be
selected.

The following code snippet is an example for the information returned
by the viewer to a parameter definition request:

Returns an object with the ids and current values of all parameters of the loaded model. Please note that when a parameter is updated by the user or via the API, this command will immediately begin to return the new parameter value as 'current'. However, it might still take a while until the viewer actually displays the updated geometry. To get a full overview over the status of the viewer, combine this command with getStatus.

Requests the execution of an export using the current parameter set. The triggered action depends on the type of the export. For exports of type download, the command triggers the user's browser to download the exported geometry in the file format specified by the designer. Exports of type email will prompt the ShapeDiver servers to send an email with a download link and the current parameter set to the email address specified by the designer. In this case, the user does not get direct access to the exported geometry.

restrictCamera(component,blnMax,value)

Arguments

If true, the value is set as an upper bound, otherwise as a lower bound.

value

Number

The coordinate used as an upper or lower bound on camera movement.

Returns

Boolean

True if the camera movement was successfully restricted.

Restricts the effective movement of the viewer's camera beyong a given axis-parallel plane. As an example, you could prohibit the camera from moving below the xy-plane by setting a lower bound on the z-coordinate.

setEdgeColorByObject(byObject)

Arguments

Param

Type

Details

byObject

Boolean

True if edges should be colored according to their parent object.

Returns

Boolean

True if the setting was changed, false if it was already at the desired value.

Configure how the color of visible edges is defined. If you set this to true, edges will be colored according to the main color of the object they correspond to. Otherwise, all visible edges will have the color set using setEdgeColor.

setIgnoreMouse(bIgnoreMouse)

Arguments

If true, all mouse input to the 3d viewer window will be ignored. This does not apply to the parameter widget, which will stil function normally.

Returns

Boolean

True if command could be processed.

setParameterValue(id,value)

Tells the viewer to update a given parameter to a new value.

Arguments

Param

Type

Details

id

String

The unique id of the parameter which should be updated.

value

(String/Number/Boolean)

The new value of the parameter. Subject to constraints set in parameter definition.

Returns

Boolean

True if parameter id and value are valid.

This is one of the most basic and important commands in the ShapeDiver API. Given the unique id of a parameter of the loaded model as well as a valid new value for this parameter, the viewer will update the model to reflect the new value.

The viewer will check if the parameter id and value provided are valid based on its stored parameter information and respond accordingly once this check has been finished. Please note that the viewer's response will typically be returned before the actual update has been received from the ShapeDiver servers and is being displayed. Therefore, errors might still occur after a positive response to this command, which might cause the geometry update to fail. To get information about the loading status of the viewer please use the getStatus command.

setParameterValues(ids,values)

Tells the viewer to update a number of given parameters to new values.

Arguments

Param

Type

Details

ids

Array{String}

Unique ids or names of the parameters which are to be updated.

values

Array{String/Number/Boolean}

New values for the updated parameters, in the same order as the ids array.

Returns

Boolean

True if all parameter ids and values were valid.

This function allows you to update several or even all parameter values while only causing a single geometry update operation. This might be useful to restore saved settings or if a complex logic requires changes to several parameters based on user input. Please see the setParameterValue command for more detailed info.