|
|
// 从这里开始
var h1 = nullvar h2 = nullvar h3 = null
var oldtransformNodex = nullvar oldMeshOther = null
var drag = nullvar isRotating = truevar clickParentRotate = false
var targetAngles = { default: { // 初始视角
alpha: 2.5809, beta: 0.9804, radius: 3 }, alarm: { // 报警视角(示例)
alpha: 3.1213, // -π(180度)
beta: 0.5855, // π/4(45度)
radius: 3 // 更近的距离
}}
var camera
BABYLON.DefaultLoadingScreen.prototype.displayLoadingUI = function() { if (document.getElementById('customLoadingScreenDiv')) { document.getElementById('customLoadingScreenDiv').style.display = 'initial' return } this._loadingDiv = document.createElement('div') this._loadingDiv.id = 'customLoadingScreenDiv'
thecss = 'lohingifpc' thecss2 = 'zcpc'
this._loadingDiv.innerHTML = "<div class='oka'><div class='" + thecss + "'><image src='./logok.gif' class='jiazaiimg'/></div></div>"
this._resizeLoadingUI() window.addEventListener('resize', this._resizeLoadingUI) document.body.appendChild(this._loadingDiv)}
function prepareGroupButton2(transformNodex, color, qu) { var mesheses = null if (transformNodex.getClassName() === 'TransformNode') { mesheses = transformNodex.getChildMeshes(false) } else { mesheses = [] mesheses.push(transformNodex) }
for (var i = 0; i < mesheses.length; i++) { mesheses[i].actionManager = new BABYLON.ActionManager(scene) mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPointerOverTrigger, parameter: '' }, function() { isRotating = false camera.useAutoRotationBehavior = isRotating } ) ) // 移出事件
mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPointerOutTrigger, parameter: '' }, function() { if (clickParentRotate) { isRotating = true camera.useAutoRotationBehavior = isRotating } } ) ) mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPickTrigger, parameter: '' }, function() { clickbegin = true try { cameraClick(transformNodex) } catch (error) { } }) ) }}
function prepareGroupButton3(transformNodex, color, qu) { var mesheses = null if (transformNodex.getClassName() === 'TransformNode') { mesheses = transformNodex.getChildMeshes(false) } else { mesheses = [] mesheses.push(transformNodex) }
for (var i = 0; i < mesheses.length; i++) { mesheses[i].actionManager = new BABYLON.ActionManager(scene) mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPointerOverTrigger, parameter: '' }, function() { isRotating = false camera.useAutoRotationBehavior = isRotating } ) ) // 移出事件
mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPointerOutTrigger, parameter: '' }, function() { if (clickParentRotate) { isRotating = true camera.useAutoRotationBehavior = isRotating } } ) ) mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPickTrigger, parameter: '' }, function() { clickbegin = true try { archCabinetsClick(transformNodex) } catch (error) { } }) ) }}
BABYLON.DefaultLoadingScreen.prototype.hideLoadingUI = function() { show = 50 document.getElementById('customLoadingScreenDiv').style.display = 'none' document.getElementById('customLoadingScreenDiv_first').style.display = 'none' document.title = '档案室'
var prepareGroupButton2ByMesh = function(transformNodex, color, qu) { var mesheses = null if (transformNodex.getClassName() === 'Mesh') { mesheses = [] mesheses.push(transformNodex) }
for (var i = 0; i < mesheses.length; i++) { mesheses[i].actionManager = new BABYLON.ActionManager(scene) mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPointerOverTrigger, parameter: '' }, function() { if (oldMeshOther != null) { oldMeshOther.removeBehavior(drag) var mesheses2 = null if (oldMeshOther.getClassName() === 'Mesh') { mesheses2 = [] mesheses2.push(oldMeshOther) } for (var i = 0; i < mesheses2.length; i++) { try { h2.removeMesh(mesheses2[i]) } catch (error) { } } }
oldMeshOther = transformNodex var mesheses3 = null if (transformNodex.getClassName() === 'Mesh') { mesheses3 = [] mesheses3.push(transformNodex) } for (let i = 0; i < mesheses3.length; i++) { try { h2.addMesh(mesheses3[i], color) } catch (error) { } } isRotating = false camera.useAutoRotationBehavior = isRotating } ) ) // 移出事件
mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPointerOutTrigger, parameter: '' }, function() { var mesheses4 = null if (transformNodex.getClassName() === 'Mesh') { mesheses4 = [] mesheses4.push(transformNodex) } for (var i = 0; i < mesheses4.length; i++) { try { h2.removeMesh(mesheses4[i]) } catch (error) { } } if (clickParentRotate) { isRotating = true camera.useAutoRotationBehavior = isRotating } } ) ) mesheses[i].actionManager.registerAction( new BABYLON.ExecuteCodeAction({ trigger: BABYLON.ActionManager.OnPickTrigger, parameter: '' }, function() { try { cameraClick(transformNodex) } catch (error) { } } ) ) } }
// 绑功能点
var smokeAlarms = [] // 烟感
scene.transformNodes.forEach(function(node) { if (node.name.startsWith('smokealarm')) { smokeAlarms.push(node) } }) var length = smokeAlarms.length console.log('以 smokealarm 开头的对象数量:', length) smokeAlarms.forEach(function(jk01, index) { console.log('smokeAlarms', jk01) var parts = jk01.name.split('smokealarm') if (parts.length > 1) { const paddedIndex = String(index + 1).padStart(3, '0') jk01.nameID = `S${paddedIndex}` } else { jk01.nameID = 'S000' } jk01.baojing = false
prepareGroupButton2(jk01) }) // 存储所有 camera 相关的 Mesh 监控
const cameraMeshes = [] scene.transformNodes.forEach(function(node) { if (node.name.startsWith('有害生物去除器')) { cameraMeshes.push(node) } }) const cameraCount = cameraMeshes.length console.log('以 camera 开头的 Mesh 数量:', cameraCount) const colorBlue = new BABYLON.Color3(0, 0, 1) cameraMeshes.forEach((cam, index) => { const paddedIndex = String(index + 1).padStart(3, '0') // DAK_MO_CAM_001
// cam.nameID = `DAK_MO_CAM_${paddedIndex}`
cam.nameID = `cam_${paddedIndex}` prepareGroupButton2(cam) })
// 档案柜
const archivesCabinets = []; scene.transformNodes.forEach(function(node) { if (node.name.startsWith('档案柜')) { archivesCabinets.push(node); } }); const archivesCabinetsCount = archivesCabinets.length; console.log('以 档案柜 数量:', archivesCabinetsCount);
if (archivesCabinets.length > 0) { // 增加安全判断,避免数组为空时报错
const children = archivesCabinets[0]._children; const filteredChildren = children.filter(cam => cam.name !== "克隆_1");
for (let i = filteredChildren.length - 1; i >= 0; i--) { const cam = filteredChildren[i]; const paddedIndex = String(filteredChildren.length - i); cam.nameID = `cabinet-${paddedIndex}`; prepareGroupButton3(cam); } }
var light = new BABYLON.HemisphericLight('HemiLight', new BABYLON.Vector3(0, 1, 0), scene) light.intensity = 2 light.diffuse = new BABYLON.Color3(0.92, 0.92, 0.92)
// 给vue页面传值,加载完成之后
parent.getIframeLoading('false')}
BABYLON.DracoCompression.Configuration.decoder.wasmUrl = './js/draco_wasm_wrapper_gltf.js'BABYLON.DracoCompression.Configuration.decoder.wasmBinaryUrl = './js/draco_decoder_gltf.wasm'BABYLON.DracoCompression.Configuration.decoder.fallbackUrl = './js/draco_decoder_gltf.js'
// createScene function that creates and return the scene
var createScene = function() { engine.displayLoadingUI()
var scene = new BABYLON.Scene(engine) camera = new BABYLON.ArcRotateCamera( 'Camera', 4.02, 0.98, 2.6, new BABYLON.Vector3(1.2, 0.08, 0.03), scene ) camera.setTarget(new BABYLON.Vector3(0, 0, 0)) // 瞄准原点
camera.attachControl(canvas, true)
// ========== 关键修改:解决裁剪问题 ==========
camera.lowerRadiusLimit = 0.1 // 减小最小距离限制,允许相机更靠近物体
camera.upperRadiusLimit = 500 // 增大最大距离限制
camera.inertia = 0.1 // 设置裁剪平面(核心解决裁剪问题)
camera.minZ = 0.01 // 近裁剪平面:设置为较小值,避免近距离裁剪
camera.maxZ = 1000 // 远裁剪平面:设置为较大值,避免远距离裁剪
// 优化相机视场角(可选,根据需求调整)
camera.fov = 0.8 // 增大视场角,看到更多内容(默认约0.87弧度=50度)
camera.useAutoRotationBehavior = isRotating // 自动旋转
// 改变场景背景颜色 - 背景颜色opacity值设为0,达到透明背景的效果
scene.clearColor = new BABYLON.Color4(0, 0, 0, 0) scene.activeCamera = camera
scene.activeCamera.useInputToRestoreState = true
var assetsManager = new BABYLON.AssetsManager(scene)
// 加载GLB模型并处理材质
BABYLON.SceneLoader.LoadAssetContainerAsync('asset/', 'F5.glb', scene).then((container) => { // 遍历所有材质
container.materials.forEach(material => { // 可以保留材质处理逻辑
}) // 将加载的资产添加到场景中
container.addAllToScene()
// setTimeout(() => {
// moveCameraTo('alarm')
// }, 3000)
}).catch((error) => { console.error('加载模型时出错:', error) })
var hdrTexture = new BABYLON.CubeTexture.CreateFromPrefilteredData('textures/environmentSpecular.env', scene) scene.environmentTexture = hdrTexture
var spriteManagerPlayer = new BABYLON.SpriteManager('playerManager', './img/bl9.png', 10, { width: 100, height: 100 }, scene) spriteManagerPlayer.isPickable = true
scene.onPointerDown = function(evt) { var pickResult = scene.pickSprite(this.pointerX, this.pointerY)
var pick = scene.pick(scene.pointerX, scene.pointerY) console.log('pick', pick.pickedPoint) if (pickResult.pickedSprite != null) { if (pickResult.hit) { alert(pickResult.pickedSprite.name) } } }
assetsManager.load()
drag = new BABYLON.PointerDragBehavior({ dragPlaneNormal: new BABYLON.Vector3(0, 0, 1) })
drag.validateDrag = (targetPosition) => { if (targetPosition.x > 10.5 || targetPosition.x < -10.5) { return false } if (targetPosition.z > 10.5 || targetPosition.z < -10.5) { return false } if (oldtransformNodex != null) { return true } } drag.onDragEndObservable.add((event) => { // console.log("dragEnd");
}) // GUI
h1 = new BABYLON.HighlightLayer('hl1', scene) h2 = new BABYLON.HighlightLayer('hl2', scene) h3 = new BABYLON.HighlightLayer('hl3', scene) // 修复重复的ID问题
var step = 0.1 var currentx = 1
h1.blurHorizontalSize = 0.1 scene.registerAfterRender(() => { h1.blurHorizontalSize = h1.blurVerticalSize + currentx
var nodealert = scene.getTransformNodeByName('yan') if (nodealert != null) { var mesheses3 = null if (nodealert.getClassName() === 'TransformNode') { mesheses3 = nodealert.getChildMeshes(false) } else { mesheses3 = [] mesheses3.push(nodealert) } for (var i = 0; i < mesheses3.length; i++) { try { if (nodealert.baojing === true) { h3.addMesh(mesheses3[i], new BABYLON.Color3(1, 0, 0)) } else { h3.removeMesh(mesheses3[i]) } } catch (error) { } } } })
if (currentx > 0.5) { step *= -1 } if (currentx < 0) { step *= -1 } currentx += step return scene}
var canvas = document.getElementById('renderCanvas')// load the 3D engine
var engine = new BABYLON.Engine(canvas, true, { stencil: true})
// call the createScene function
var scene = createScene()scene.autoClear = truescene.imageProcessingConfiguration.exposure = 1scene.imageProcessingConfiguration.contrast = 1scene.environmentIntensity = 0.4engine.runRenderLoop(function() { scene.render()})
window.addEventListener('resize', function() { engine.resize()})
// 报警 true:表示报警, false :表示不报警
function cameraClick(TheCamera) { window.parent.postMessage( { type: 'cameraClick', data: TheCamera.nameID }, '*' )}
// 报警 true:表示报警, false :表示不报警
function archCabinetsClick(TheCamera) { window.parent.postMessage( { type: 'archCabinetsClick', data: TheCamera.nameID }, '*' )}
function handleAlarm(deviceId, isAlarm) { var cl = new BABYLON.Color3(0, 0, 1) var c2 = new BABYLON.Color3(1, 0, 0) const targetDevice = scene.transformNodes.find(node => node.nameID === deviceId) if (targetDevice) { targetDevice.baojing = isAlarm var mesheses = null if (targetDevice.getClassName() === 'TransformNode') { mesheses = targetDevice.getChildMeshes(false) } else { mesheses = [] mesheses.push(targetDevice) } if (isAlarm) { console.log('111') for (var i = 0; i < mesheses.length; i++) { h2.addMesh(mesheses[i], c2) } } else { console.log('222') for (var j = 0; j < mesheses.length; j++) { h2.removeMesh(mesheses[j]) h2.addMesh(mesheses[j], cl) } } } else { console.log(`未找到设备 ID 为 ${deviceId} 的设备`) }}
window.addEventListener( 'message', function(e) { if (e.data.type === 'deviceState') { console.log('ddd', e.data.data) const deviceData = e.data.data if (Array.isArray(deviceData)) { deviceData.forEach((device) => { handleAlarm(device.deviceId, device.isAlarm) }) } else { handleAlarm(deviceData.deviceId, deviceData.isAlarm) } } else if (e.data.type === 'isGetRotate') { const isGetRotate = e.data.value console.log('isGetRotate:', isGetRotate) toggleAutoRotation(isGetRotate) } }, false)
function toggleAutoRotation(isAutoRotating) { var camera = scene.activeCamera clickParentRotate = !isAutoRotating if (!isAutoRotating) { // 启用自动旋转
camera.useAutoRotationBehavior = true } else { // 禁用自动旋转
camera.useAutoRotationBehavior = false camera.angularSpeed = 0 // 停止旋转
}}
// 相机运动到指定视角(带动画)
function moveCameraTo(targetPreset) { // 获取目标参数
var target = targetAngles[targetPreset] if (!target) return console.error('无效的视角预设') var camera = scene.activeCamera
// 禁用用户交互(可选)
camera.panningInertia = 0 // 禁止平移
// 创建并设置动画
var animationAlpha = new BABYLON.Animation( 'cameraAlphaAnimation', 'alpha', 60, // 帧率
BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT )
var animationBeta = new BABYLON.Animation( 'cameraBetaAnimation', 'beta', 60, // 帧率
BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT )
var animationRadius = new BABYLON.Animation( 'cameraRadiusAnimation', 'radius', 60, // 帧率
BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT )
// 定义关键帧
var keysAlpha = [ { frame: 0, value: camera.alpha }, { frame: 120, value: target.alpha } ] var keysBeta = [ { frame: 0, value: camera.beta }, { frame: 120, value: target.beta } ] var keysRadius = [ { frame: 0, value: camera.radius }, { frame: 120, value: target.radius } ]
animationAlpha.setKeys(keysAlpha) animationBeta.setKeys(keysBeta) animationRadius.setKeys(keysRadius)
// 设置缓动函数
var easingFunction = new BABYLON.CubicEase() easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT) animationAlpha.setEasingFunction(easingFunction) animationBeta.setEasingFunction(easingFunction) animationRadius.setEasingFunction(easingFunction)
// 开始动画
scene.beginDirectAnimation(camera, [animationAlpha, animationBeta, animationRadius], 0, 120, false, 1, function() { // 动画完成后恢复用户交互
camera.panningInertia = 0.1 toggleAutoRotation(true) window.parent.postMessage({ type: 'autoRotationStatus', value: true }, '*') })}
|