17 May 2017

Preparing your viewing application for multi-model workflows - Part 2: Model Loader

In my previous post I exposed the code for the base extension class I'm using in my app in order to handle efficiently multiple models in the viewer. The first extension that relies on it is the ModelLoader: its purpose is to expose controls that let the user insert models into the scene, manage inserted models and remove them if needed.  

It can load models from the Autodesk Cloud as well as local ones, using the approach I described in an earlier post: Working seamlessly online/offline when developing your Web applications with the Forge Viewer

Upon insertion of a new model,  the extension is tagging the model object with a randomly generated guid, so each model can be uniquely identified at a later stage if needed by another extension. The way to achieve it is pretty straighforward, using the callback method provided by viewer.loadModel

const onModelLoaded = (model) => {

      model.guid = guid()

viewer.loadModel(path, loadOption, onModelLoaded)

Here is my implementation for guid() function:

guid (format = 'xxxxxxxxxxxx') {

  var d = new Date().getTime()

  const guid = format.replace(
    function (c) {
      var r = (d + Math.random() * 16) % 16 | 0
      d = Math.floor(d / 16)
      return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16)

  return guid

Another useful thing the extension is doing is to fire "model.activated" event when a model is being activated: this occurs either when a model is being selected by user directly through the viewer (and the model was not previously the active one) or the model is being selected in the dropdown control of ModelLoader extnesion. The purpose of that event is to trigger modelActivated callback that allows other multi-model extensions to reload their current data is they are interested in the active model. I will present such extensions in the future.

The UI also provides controls to transform models (translate, rotate, scale), however this logic is not implemented by the extension itself: controls are created and handled by the ModelTransformer extension and injected into the parent UI using React.   

You can take a look at a live demo of the ModelLoader extension there and refer to the full source code below 

Related Article