ibms-dome/Frontend/js/forge/forgemodel.js

595 lines
20 KiB
JavaScript

var viewer;
// const devices = [
// {
// id: "Sensor 1",
// position: {
// x: -22.779729106182415,
// y: 5.431043023608719,
// z: 4.553068469137088,
// },
// type: "combo",
// sensorTypes: ["temperature", "co2"],
// dbId: 1,
// },
// {
// id: "Sensor 2",
// position: {
// x: 0.20752051811882666,
// y: 5.431043023608719,
// z: 4.553068469137088,
// },
// type: "combo",
// sensorTypes: ["temperature", "co2"],
// dbId: 2,
// },
// ];
// var sensorStyleDefinitions = {
// co2: {
// url: "https://d2zqnmauvnpnnm.cloudfront.net/assets-1/images/co2.svg",
// color: 0xffffff,
// },
// temperature: {
// url: "https://d2zqnmauvnpnnm.cloudfront.net/assets-1/images/thermometer.svg",
// color: 0xffffff,
// },
// default: {
// url: "https://d2zqnmauvnpnnm.cloudfront.net/assets-1/images/circle.svg",
// color: 0xffffff,
// },
// };
// Initialize sensor values
//let sensorVals = [];
let fragProxy;
var targetFloorZ;
var elevatorSpeed;
// for (let i = 0; i < devices.length; i++) {
// sensorVals[i] = Math.random();
// }
function launchViewer(urn, callback) {
var options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken
};
Autodesk.Viewing.Initializer(options, () => {
viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('forgeViewer'));
//viewer = new Autodesk.Viewing.Viewer3D(document.getElementById('forgeViewer'));
viewer.start();
var documentId = 'urn:' + urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
$("#forgeViewer").on("autodesk:loaded", function (e,nodeIds) {
callback ? callback(viewer, nodeIds) : "";
})
//test
// for (let i = 0; i < urn.length; i++) {
// Autodesk.Viewing.Document.load(urn[i]["urn"], async (doc) => {
// let viewables = doc.getRoot().getDefaultGeometry();
// let model = await viewer.loadDocumentNode(doc, viewables, {
// preserveView: false,
// keepCurrentModels: true,
// placementTransform: (new THREE.Matrix4()).setPosition(urn[i]["xform"]),
// keepCurrentModels: true,
// globalOffset: {
// x: 0,
// y: 0,
// z: 0
// }
// });
// await viewer.waitForLoadDone(); //!<<< Wait for loading materials, properties and geometries for this model (URN)
// });
// }
//loadHeatmaps(viewer.getAllModels()[0]); //!<<< equals to viewer.model
});
}
function launchViewerNoTools(urn, callback) {
var options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken
};
Autodesk.Viewing.Initializer(options, () => {
//viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('forgeViewer'));
viewer = new Autodesk.Viewing.Viewer3D(document.getElementById('forgeViewer'));
viewer.start();
var documentId = 'urn:' + urn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
$("#forgeViewer").on("autodesk:loaded", function (e, nodeIds) {
callback ? callback(viewer, nodeIds) : "";
})
});
}
function getAllLeafComponents(viewer, callback) {
var cbCount = 0;
var tree;
var jsData = []
function getLeafComponentsRec(current, parent) {
cbCount++;
if (tree.getChildCount(current) != 0) {
tree.enumNodeChildren(current, function (children) {
getLeafComponentsRec(children, current);
}, false);
}
var nodeName = viewer.model.getInstanceTree().getNodeName(current)
jsData.push({ id: current, parent: parent, text: nodeName })
if (--cbCount == 0) callback(jsData);
}
viewer.getObjectTree(function (objectTree) {
tree = objectTree;
var rootId = tree.getRootId()
var nodeName = viewer.model.getInstanceTree().getNodeName(rootId)
jsData.push({ id: rootId, parent: '#', text: nodeName })
var allLeafComponents = getLeafComponentsRec(rootId, '#');
});
}
class elevator3D {
constructor(option = {}) {
this.ele = option.element;
this.viewer = option.viewer;
this.nodeId = option.nodeId;
this.speed = option.speed ?? 0.03;
this.fragProxys = [];
this.fragProxy = null;
this.initCallback = option.inited ?? null;
this.movStatus = 0;
this.targetFloorZ = 0;
this.floorHeight = option.floorHeight ?? [{}];
this.init();
}
setTreeFrag = function (callback) {
let tree = this.viewer?.model?.getData().instanceTree;
if (!tree) {
return;
}
let nodeId = this.nodeId;
if (nodeId) {
let childCnt = tree.getChildCount(nodeId);
let curIdx = 1;
this.fragProxys.filter(x => x.nodeId == nodeId).forEach((x) => {
let idx = this.fragProxys.indexOf(x);
this.fragProxys.splice(idx,1);
})
tree.enumNodeFragments(nodeId, (frag) => {
let fragProxy = this.viewer.impl.getFragmentProxy(this.viewer.model, frag);
this.fragProxys.push({ nodeId: nodeId, fragId: frag, frag: fragProxy });
fragProxy.getAnimTransform();
let fragPosition = new THREE.Vector3(0, 0, 0);// 一樓0 二樓15 三樓 26
fragProxy.position = fragPosition;
fragProxy.updateAnimTransform();
if (childCnt == curIdx) {
this.initCallback ? this.initCallback() : "";
callback ? callback() : "";
}
curIdx++;
}, true);
}
this.viewer.impl.sceneUpdated(true);
if (typeof $(this.ele)[0]._elevator3D == "undefined") {
$(this.ele)[0]._elevator3D = [];
}
$(this.ele)[0]._elevator3D.push({ nodeId: nodeId, obj: this });
}
init = function (callback = null) {
this.setTreeFrag(callback);
}
setElevatorFloor = function (floor) {
this.targetFloorZ = this.floorHeight.filter(x => x.floor == floor)[0]?.height ?? 0;
}
setElevatorSpeed = function (speed) { //0.01 ~ 1
this.speed = speed;
}
movElevator = function () {
let tree = this.viewer.model.getData().instanceTree;
let nodeId = this.nodeId;
let fragProxyZ = 0;
let fragProxy = this.fragProxys.filter(x => x.nodeId == nodeId)[0]?.frag;
if (!fragProxy) {
return;
}
changeColor(nodeId);
if ((this.movStatus == 2 && fragProxy.position.z.roundDecimal(2) < this.targetFloorZ.roundDecimal(2)) ||
(this.movStatus == 1 && fragProxy.position.z.roundDecimal(2) > this.targetFloorZ.roundDecimal(2)) ||
fragProxy.position.z.roundDecimal(2) == this.targetFloorZ.roundDecimal(2)) {
stoped(this);
}
//if (movStatus == 0) {
// recoverTransparentBuilding();
// return;
//}
if (fragProxy.position.z.roundDecimal(2) > this.targetFloorZ.roundDecimal(2)) {
this.movStatus = 2;
}
else if (fragProxy.position.z.roundDecimal(2) < this.targetFloorZ.roundDecimal(2)) {
this.movStatus = 1;
}
tree.enumNodeFragments(nodeId, (frag) => {
let fragProxy = this.viewer.impl.getFragmentProxy(this.viewer.model, frag);
fragProxy.getAnimTransform();
//let fragPosition = new THREE.Vector3(0, 0, 15);// 一樓0 二樓15 三樓 26
if (this.movStatus == 2) {
fragProxy.position.z -= this.speed;
}
else if (this.movStatus == 1) {
fragProxy.position.z += this.speed;
}
this.fragProxys.filter(x => x.nodeId == nodeId && x.fragId == frag)[0].frag.position.z = fragProxy.position.z;
fragProxyZ = fragProxy.position.z;
fragProxy.updateAnimTransform()
}, true);
this.viewer.impl.sceneUpdated(true);
/*setTransparentBuilding();*/
let movElevator = $(this.ele)[0]._elevator3D.filter(x => x.nodeId == this.nodeId)[0]?.obj.movElevator.bind(this);
if (this.movStatus == 2) {
if (fragProxyZ >= this.targetFloorZ) {
requestAnimationFrame(() => {
movElevator();
});
} else {
stoped(this);
}
}
else if (this.movStatus == 1) {
if (fragProxyZ <= this.targetFloorZ) {
requestAnimationFrame(() => {
movElevator();
});
} else {
stoped(this);
}
} else {
stoped(this);
}
function stoped(obj) {
obj.movStatus = 0;
/*recoverTransparentBuilding();*/
hideColor(nodeId);
return;
}
//let fragPosition = new THREE.Vector3(position);// 一樓0 二樓15 三樓 26
//fragProxy.position = fragPosition;
//fragProxy.updateAnimTransform();
//viewer.impl.sceneUpdated(true);
}
}
function onDocumentLoadSuccess(doc, eleOption) {
var viewables = doc.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(doc, viewables).then(i => {
// documented loaded, any action?
});
// viewer.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT, (args) => {
// var currSelection = viewer.getSelection();
// var domElem = document.getElementById('id_printer');
// domElem.innerText = currSelection[0];
// });
viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function () {
let instanceTree = viewer.model.getData().instanceTree;
console.log(instanceTree.nodeAccess)
allDbIdsStr = Object.keys(instanceTree.nodeAccess.dbIdToIndex);
getNodeIdByDbIds(allDbIdsStr, (nodeIds) => {
$("#forgeViewer").trigger("autodesk:loaded", nodeIds );
});
});
}
function getNodeIdByDbIds(allDbIdsStr,callback) {
let curDbId = 0;
let tagId = 0;
let _parentId = 0;
let _childId = 0;
let evelMap = new Map();
let finTimeout = null;
allDbIdsStr.forEach((dbId) => {
curDbId = parseInt(dbId);
viewer.getProperties(curDbId, function (e) {
e.properties.forEach(function (item, idx) {
if (item.displayName == "tag_id" && e.name == "【電梯】") {
tagId = e.dbId;
viewer.getProperties(tagId, function (e2) {
e2.properties.forEach(function (item2, idx2) {
if (item2.displayName == "child") {
_parentId = item2.displayValue;
viewer.getProperties(_parentId, function (e3) {
//var childIdArr = new Array();
/*childIdArr.push(_parentId)*/
//e3.properties.forEach(function (item3, idx3) {
// if (item3.displayName == "child") {
// _childId = item3.displayValue;
// childIdArr.push(_childId);
// }
//});
evelMap.set(item.displayValue, e3.dbId)
console.log("map: " + evelMap);
clearTimeout(finTimeout)
finTimeout = setTimeout(() => {
callback ? callback(evelMap) : "";
}, 10)
})
}
});
})
}
});
})
})
return evelMap;
}
function setElevatorFloor(floor) {
if (floor == 0)
targetFloorZ = 0;
else if (floor == 1)
targetFloorZ = 15;
else if (floor == 2)
targetFloorZ = 26;
}
function setElevatorSpeed(speed) { //0.01 ~ 1
elevatorSpeed = speed;
}
function movElevator() {
let tree = viewer.model.getData().instanceTree;
let nodeId = 10952;
let fragProxyZ = 0;
var movStatus = 0; // 0=no 1=up 2=down
if (fragProxy.position.z > targetFloorZ) {
movStatus = 2
}
else if (fragProxy.position.z < targetFloorZ) {
movStatus = 1
}
if (movStatus == 0) {
return;
}
tree.enumNodeFragments(nodeId, function (frag) {
fragProxy = viewer.impl.getFragmentProxy(viewer.model, frag);
fragProxy.getAnimTransform();
//let fragPosition = new THREE.Vector3(0, 0, 15);// 一樓0 二樓15 三樓 26
if (movStatus == 2) {
fragProxy.position.z -= elevatorSpeed;
}
else if (movStatus == 1) {
fragProxy.position.z += elevatorSpeed;
}
fragProxyZ = fragProxy.position.z;
fragProxy.updateAnimTransform()
});
viewer.impl.sceneUpdated(true);
if (movStatus == 2) {
if (fragProxyZ >= targetFloorZ) {
requestAnimationFrame(movElevator);
}
}
else if (movStatus == 1) {
if (fragProxyZ <= targetFloorZ) {
requestAnimationFrame(movElevator);
}
}
//let fragPosition = new THREE.Vector3(position);// 一樓0 二樓15 三樓 26
//fragProxy.position = fragPosition;
//fragProxy.updateAnimTransform();
//viewer.impl.sceneUpdated(true);
}
function getAllDbIds(viewer) {
var instanceTree = viewer.model.getData().instanceTree;
var allDbIdsStr = Object.keys(instanceTree.nodeAccess.dbIdToIndex);
return allDbIdsStr.map(function (id) { return parseInt(id) });
}
/**
* Autodesk.Viewing.Document.load() failuire callback.
*/
function onDocumentLoadFailure(viewerErrorCode) {
console.error("onDocumentLoadFailure() - errorCode:" + viewerErrorCode);
}
function getForgeToken(callback) {
fetch(baseApiUrl + '/api/forge/oauth/token').then(res => {
res.json().then(data => {
callback(data.dictionary.access_token, data.dictionary.expires_in);
});
});
//callback("eyJhbGciOiJSUzI1NiIsImtpZCI6IlU3c0dGRldUTzlBekNhSzBqZURRM2dQZXBURVdWN2VhIn0.eyJzY29wZSI6WyJkYXRhOndyaXRlIiwiZGF0YTpyZWFkIiwiYnVja2V0OnJlYWQiLCJidWNrZXQ6dXBkYXRlIiwiYnVja2V0OmNyZWF0ZSJdLCJjbGllbnRfaWQiOiJUQTNocXNGZnpRYk5PVVhLcGxkS1VLU2V3NFNKMjF3NSIsImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9hand0ZXhwNjAiLCJqdGkiOiJiemxzWE5qWElvZ2R1UjUzTUJkdlhrTTNTT01qeVB1bHJrMmdTVWJudGNTeDg1b01kRG1xejg3Z05jenJkRzhpIiwiZXhwIjoxNjY4MTgzMDM2fQ.VU3qLwTJ9nlXnomKCdk4y5UcgszGEO_zlvE7w5mWWajeBMwKLo-zw7LJEqUEajRksvssppR9SbVsjLSx-vDVc3DRhCo3jYTWKPT1T3wQrlkOSqLeIrAdnKdBDNBWKgrGJt_xcmXc3dZ3XNKf9L_F6Ex808rUlo6cem1mcPpKl1jCBDqKu1mAX7aDtZ65TTQZbGGhbG4HdnET-d1i5w4LunGN11UAHhDUW3n0SWWIBL27PiiUQONZttajhD5st6IngYLcjr93BYVyJmDF7-wm4WZlHSw2OnXIfbJcFXEd83uVv_Rej4UXjzZ0e6kHwzc2nvGvKSIFu3Nt7CabdR8CkA", 3599);
}
async function loadHeatmaps(model) {
const dataVizExtn = await viewer.loadExtension("Autodesk.DataVisualization");
// Given a model loaded from Forge
const structureInfo = new Autodesk.DataVisualization.Core.ModelStructureInfo(model);
const devices = [
{
id: "Oficina 6",
name: "Oficina-",
position: { x: 22.475382737884104, y: 7.4884431474006163, z: 3.0 },
sensorTypes: ["temperature", "humidity"]
}
];
var offset = Autodesk.viewer.model.getGlobalOffset();
removeOffset(devices[0], offset)
// Generates `SurfaceShadingData` after assigning each device to a room.
const shadingData = await Autodesk.structureInfo.generateSurfaceShadingData(devices);
// Use the resulting shading data to generate heatmap from.
await dataVizExtn.setupSurfaceShading(model, shadingData);
// Register color stops for the heatmap. Along with the normalized sensor value
// in the range of [0.0, 1.0], `renderSurfaceShading` will interpolate the final
// heatmap color based on these specified colors.
const sensorColors = [0x0000ff, 0x00ff00, 0xffff00, 0xff0000];
// Set heatmap colors for temperature
const sensorType = "temperature";
dataVizExtn.registerSurfaceShadingColors(sensorType, sensorColors);
// Function that provides sensor value in the range of [0.0, 1.0]
function getSensorValue(surfaceShadingPoint, sensorType) {
// The `SurfaceShadingPoint.id` property matches one of the identifiers passed
// to `generateSurfaceShadingData` function. In our case above, this will either
// be "cafeteria-entrace-01" or "cafeteria-exit-01".
const deviceId = surfaceShadingPoint.id;
// Read the sensor data, along with its possible value range
let sensorValue = readSensorValue(deviceId, sensorType);
const maxSensorValue = getMaxSensorValue(sensorType);
const minSensorValue = getMinSensorValue(sensorType);
// Normalize sensor value to [0, 1.0]
sensorValue = (sensorValue - minSensorValue) / (maxSensorValue - minSensorValue);
return clamp(sensorValue, 0.0, 1.0);
}
// This value can also be a room instead of a floor
const floorName = "01 - Entry Level";
dataVizExtn.renderSurfaceShading(floorName, sensorType, getSensorValue);
}
function setTransparentBuilding() {
//allDbIdsStr.forEach((dbId) => {
// setTransparency(dbId, 0.2);
//})
for (var i = 0; i < allDbIdsStr.length; i++) {
setTransparency(parseInt(allDbIdsStr[i]), 0.2);
}
}
function recoverTransparentBuilding() {
//allDbIdsStr.forEach((dbId) => {
// setTransparency(dbId, 1);
//})
for (var i = 0; i < allDbIdsStr.length; i++) {
setTransparency(parseInt(allDbIdsStr[i]), 1);
}
}
//設定模型 透明度
function setTransparency(nodeId, opacity) {
var model = viewer.model;
//var nodeId = 1633;
var fragList = viewer.model.getFragmentList();
var fragIds = []
model.getData().instanceTree.enumNodeFragments(
nodeId, (fragId) => {
fragIds.push(fragId)
});
fragIds.forEach((fragId) => {
//获取材质
var material = fragList.getMaterial(fragId);
if (material) {
//设置透明度
material.opacity = opacity;//0.5;
material.transparent = true;
//标记更新
material.needsUpdate = true;
}
})
//更新viewer
viewer.impl.invalidate(true, true, true);
}
function changeColor(nodeId) {//電梯變綠色
let instanceTree = viewer.model.getData().instanceTree;
instanceTree.enumNodeChildren(nodeId, function (chiNodeId) {
var color = new THREE.Vector4(0, 1, 0, 1);
viewer.setThemingColor(chiNodeId, color);
},true)
}
function hideColor(nodeId) {//顏色改成透明
let instanceTree = viewer.model.getData().instanceTree;
instanceTree.enumNodeChildren(nodeId, function (chiNodeId) {
var color = new THREE.Vector4(0, 1, 0, 0);
viewer.setThemingColor(chiNodeId, color);
},true)
}