Search code examples
autodeskautodesk-forgeautodesk-viewer

Identify unique model programmatically


How can you identify a model in the viewer programmatically? i.e. what parameters of the model can help differentiate between different models?

What I tried:

viewer.model.id always returns 1.

viewer.model.myData.basePath or viewer.model.myData.urn is just a string of a path and one model can potentially take the same path of another at a later time.

Hashing more unique values like packFileTotalSize and primitiveCount in viewer.model.myData could give closer to 1 to 1 ids, but it's more of a hack.

Is there a hash, name or model id that's more likely to be unique to one model?


Solution

  • A very easy way to handle that is to tag the model yourself right after you load it, here is how I do it in my app:

    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(
        /[xy]/g,
        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
    }
    

    This is just an example, you could replace guid by some value from a database record or some other source. I am assuming that you know from where your model is coming from at the time of the loading.