Error in viewing files in Autodesk forge viewer - error calling doc.getRootItem() - autodesk-forge

When viewing files in Autodesk forge viewer, getting the following errors,
Cannot read property ‘setEndpoint’ of undefined. Screenshot
doc.getRootItem is not a function. Screenshot
And will be able to view after empty cache and hard reload (Ctrl + Shift +R) the page. Sometimes the same errors will persist even after hard reload and clearing browser cache.
Code for the second error.
var options = {
env: 'AutodeskProduction',
accessToken: getAccessToken() //Method to get access token- no errors here
};
var documentId = 'urn:' + urn;
Autodesk.Viewing.Initializer(options, function onInitialized() {
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
//Autodesk.Viewing.Document.load - success function.
function onDocumentLoadSuccess(doc) {
setTimeout(function() {
debugger;
}, 5000);
//Error is thrown in the line below.
var viewables = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
'type': 'geometry'
}, true); //throws error on calling doc.getRootItem()
if (viewables.length === 0) {
console.error('Document contains no viewables.');
return;
}
// Choose any of the avialble viewables
var initialViewable = viewables[0];
var svfUrl = doc.getViewablePath(initialViewable);
var modelOptions = {
sharedPropertyDbPath: doc.getPropertyDbPath()
};
var viewerDiv = document.getElementById('divViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);
viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
}

You must have unwitting upgraded to Viewer V7 with which getRootItem and several other functions have been deprecated - see here for its release notes and migration guide.
Stick with V6 with <script src="https://developer-stg.api.autodesk.com/modelderivative/v2/viewers/viewer3D.js?v=6.6"></script> - if you don't specify a version by default the latest stable version would be served which is now V7.0.

Related

how to use the .impl methods in forge viewer V7*

I have been using following .impl methods in V6*
viewerApp.getCurrentViewer().impl.invalidate
viewerApp.getCurrentViewer().impl.matman()._materials
How to proceed with V7*
Thank you
EDIT :
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2',
getAccessToken: function(onTokenReady) {
var token = accessToken;
var timeInSeconds = 3600;
onTokenReady(token, timeInSeconds);
}
};
var documentId = "urn:" + urn;
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
...
Then I'm using impl methods as below ..
var mats = viewer.impl.matman()._materials;
But I still get the error
Cannot read property 'impl' of null
not sure why but may be my global viewer variable is null , any idea why this is happening or what have i done wrong.
Anything under the impl is typically considered internal implementation, and as such should not be relied on in production code. With that said, the impl property is still available, and if needed, you can use it in Forge Viewer version 7.* like so:
const viewer = new Autodesk.Viewing.GuiViewer3D(...);
viewer.impl.invalidate();
viewer.impl.matman();

Object selection in forge viewer

I have created the sample application for forge viewer.
I am able to view the Revit and navisworks files in forge viewer.
I want to select an item from the viewer by passing inputs to viewer.bubble.search method.
I am using the same coding from the url:
https://forge.autodesk.com/en/docs/viewer/v7/reference/Viewing/BubbleNode/
I am using the below code. Please help.
var viewer;
var urn1;
var accestoken1;
var jsdata;
function uploadfile(file) {
document.getElementById('<%=UploadBtn.ClientID%>').click();
}
function showModel(urn) {
var options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken
};
Autodesk.Viewing.Initializer(options, () => {
viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('forgeViewer'), { extensions: ['Autodesk.DocumentBrowser'] });
viewer.start();
var documentId = 'urn:' + urn;
urn1 = urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
// viewer.fitToView([270005], viewer.model);
// viewer.select([270005]);
});
}
function myFunction1() {
setTimeout(function () {
myFunction2();
}, 500);
}
function onDocumentLoadSuccess(doc) {
var viewables = viewer.bubble.search({ type: 'geometry', role: '3d', name: 'DOMW PIPE' });
if (viewables.length === 0) {
console.error('Document contains no viewables.');
return;
}
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
function getForgeToken(callback) {
fetch('/api/forge/oauth/token').then(res => {
res.json().then(data => {
callback(data.access_token, data.expires_in);
accestoken1 = data.access_token;
});
});
}
with thanks and regards.
Castro Nelson
If you'd like to make it possible to choose which of the 2D or 3D views (that the Model Derivative service extracted from your original design) to load in the viewer, consider using the built-in viewer extension called Autodesk.DocumentBrowser. The extension will add a new UI to the viewer that can be used to switch between the different 2D/3D views quite easily.
You can experiment with the extension on https://forge-extensions.autodesk.io:

Cannot load SVF2 model in Autodesk Forge Viewer

I just tried out the SVF2 public beta but couldn't get the model to load in the Viewer. I believe the model was translated successfully since the manifest returned has:
"name": "XXXX_ARC.nwd",
"progress": "complete",
"outputType": "svf2",
"status": "success"
However, when I tried to load the model in Viewer, it would fail on this line:
theViewer.loadModel(svfURL, onItemLoadSuccess, onItemLoadFail);
The svfURL is something like this:
https://cdn.derivative.autodesk.com/modeldata/file/urn:adsk.fluent:fs.file:autodesk-360-translation-storage-prod/*MyURN*/output/otg_files/0/output/0/otg_model.json
And the errors I got from Chrome browser:
403 GET errors. Seems like I don't have privilege to access the model?
Is there some additional setting I need to do?
Additional Info:
I have setup the Viewer environment as follows:
var options = {
env: 'MD20ProdUS',
api: 'D3S',
getAccessToken: getForgeToken
};
var documentId = 'urn:' + urn;
Autodesk.Viewing.Initializer(options, function onInitialized() {
var htmlDiv = document.getElementById('forgeViewer');
var config3d = {
extensions: ['ToolbarExtension', 'HandleSelectionExtension', .....a few extensions ],
loaderExtensions: { svf: "Autodesk.MemoryLimited" }
};
theViewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv, config3d);
var startedCode = theViewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
I have also tried removing the config3d when creating the viewer but it still returned the same messages. The code got into onDocumentLoadSuccess but failed at theViewer.loadModel(svfURL, onItemLoadSuccess, onItemLoadFail);, jumping into onItemLoadFail.
Because you mention mainly the viewer not loading the SVF2, I can suspect that maybe you have not specified the correct Viewer environment.
Here is some sample code, and pay attention to the options where you have to set env and API:
var viewer;
var options = {
// These are the SVF2 viewing settings during public beta
env: 'MD20ProdUS', // or MD20ProdEU (for EMEA)
api: 'D3S',
getAccessToken: getForgeToken
};
var documentId = 'urn:' + getUrlParameter('urn');
// Run this when the page is loaded
Autodesk.Viewing.Initializer(options, function onInitialized() {
// Find the element where the 3d viewer will live.
var htmlElement = document.getElementById('MyViewerDiv');
if (htmlElement) {
// Create and start the viewer in that element
viewer = new Autodesk.Viewing.GuiViewer3D(htmlElement);
viewer.start();
// Load the document into the viewer.
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
}
});
I am facing the same problem.
Although the model has been converted to SVF2 format, my cloud credits are being used up .
An excerpt from the manifest:
"name": "7085-33cc-9464.rvt",
"progress": "complete",
"outputType": "svf2",
"status": "success"
No matter with which settings, only the SVF format is loaded in the viewer.
I don't get an error message from the viewer, everything works as before, except that SVF is still loaded and not SVF2.
Viewer init options:
const viewerEnv = await this.initialize({
//env: dbModel.env,
env: "MD20ProdEU",
api: "D3S",
//accessToken: "",
});
Not sure if this has been solved on a separate thread, but the issue was probably that acmSessionId was not set in the options for loadModel() - see https://forge.autodesk.com/blog/403-error-when-trying-view-svf2
function onDocumentLoadSuccess(doc) {
let items = doc.getRoot().search({
'type': 'geometry',
'role': '3d'
}, true)
let url = doc.getViewablePath(items[0])
viewer.loadModel(url, { acmSessionId: doc.getAcmSessionId(url) })
}
The best thing is to just use loadDocumentNode() instead of loadModel()

Set Autodesk Forge Viewer to Infinity Pool environment

Im trying to set the Infinity pool environment on the viewer but it doesn't change, it still has the initial grey background, any ideas? I'm trying to set the light preset in the ondocumentLoadSuccess Callback
var viewer;
function launchViewer(urn, accessToken, expires) {
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function (onTokenReady) {
var token = accessToken;
var timeInSeconds = expires; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function () {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Viewer3D(htmlDiv);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:' + urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
}
function onDocumentLoadSuccess(viewerDocument) {
viewer.setLightPreset(7);
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
In some cases the model you are loading into the viewer may be trying to set its own environment. Try calling the viewer.setLightPreset method after the model is loaded.

Button for markupCore extension not showing in dockingpanel

I have followed Philippe Leefsma's tutorial on how to implement the markup tool, but without any luck. Link here: http://adndevblog.typepad.com/cloud_and_mobile/2016/02/playing-with-the-new-view-data-markup-api.html
and here: https://developer.api.autodesk.com/viewingservice/v1/viewers/docs/tutorial-feature_markup.html
I get errors that I need to include requireJS, but I don't want to use it. So instead I used this script in my html file:
<script src="https://autodeskviewer.com/viewers/2.2/extensions/MarkupsCore.js">
I don't know if this is the right way to go? I get no errors in the console, but the markup button doesn't show up in the dockingpanel.
This is my code for loading the extension in the viewer:
viewerApp = null;
function initializeViewer(containerId, urn, params) {
function getToken(url) {
return new Promise(function (resolve, reject) {
$.get(url, function (response) {
resolve(response.access_token);
});
});
}
var initOptions = {
documentId: 'urn:' + urn,
env: 'AutodeskProduction',
getAccessToken: function (onGetAccessToken) {
getToken(params.gettokenurl).then(function (val) {
var accessToken = val;
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
});
}
}
function onDocumentLoaded(doc) {
var rootItem = doc.getRootItem();
// Grab all 3D items
var geometryItems3d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '3d' }, true);
// Grab all 2D items
var geometryItems2d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '2d' }, true);
// Pick the first 3D item otherwise first 2D item
var selectedItem = (geometryItems3d.length ?
geometryItems3d[0] :
geometryItems2d[0]);
var domContainer = document.getElementById('viewerContainer');
var config = { extensions: ["Autodesk.Viewing.MarkupsCore"] };
// GUI Version: viewer with controls
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(domContainer, config);
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.initialize();
viewer.loadModel(doc.getViewablePath(selectedItem));
var extension = viewer.getExtension("Autodesk.Viewing.MarkupsCore");
viewerApp = viewer;
}
function onEnvInitialized() {
Autodesk.Viewing.Document.load(
initOptions.documentId,
function (doc) {
onDocumentLoaded(doc);
},
function (errCode) {
onLoadError(errCode);
})
}
function onLoadError(errCode) {
console.log('Error loading document: ' + errCode);
}
Autodesk.Viewing.Initializer(
initOptions,
function () {
onEnvInitialized()
})
}
Any help is highly appreciated!
Unfortunately there has been a few changes to the API since I wrote that blog post. The MarkupCore.js is now included in the viewer3D.js source, so you don't need to reference any extra file or use requireJS if you use the latest version of the viewer API.
Keep in mind that this is an API-only feature, so even after loading the markup extension, you won't get any UI out of the box. You have to implemented it yourself, for example create a dialog with buttons that may eventually create markups by calling the API.
Some of the code from my blog post may still be valid and give you an idea about what you need to do.
Hope that helps.