新增三维通号VR测试场景

This commit is contained in:
sunzhenyu 2020-07-30 15:08:17 +08:00
parent b72362640d
commit ef09632c8b
25 changed files with 12992 additions and 19 deletions

View File

@ -0,0 +1,692 @@
import { Staticmodel } from '@/jlmap3d/jl3ddevice/config.js';
//loader
import { FBXLoader } from '@/jlmap3d/main/loaders/FBXLoader';
import { OBJLoader } from '@/jlmap3d/main/loaders/OBJLoader';
import { Pathfinding } from '@/jlmap3d/jl3dpassflow/utils/Pathfinding.js';
import { OrbitControls } from '@/jlmap3d/main/control/OrbitControls';
import { ModelManagerVR } from '@/jlmap3d/jl3dmaintainer/utils/vrloader.js';
import { VRButton } from '@/jlmap3d/jl3dmaintainer/utils/VRButton.js';
import { VrGui } from '@/jlmap3d/jl3dmaintainer/utils/vrgui.js';
import { MoveanimateVr } from '@/jlmap3d/jl3dmaintainer/utils/moveanimatevr.js';
import { Textconfig } from '@/jlmap3d/jl3ddevice/component/textconfig.js';
import { getPublish3dMapDetail} from '@/api/jlmap3d/load3ddata';
import StompClient from '@/utils/sock';
import { getBaseUrl } from '@/utils/baseUrl'
import { getToken } from '@/utils/auth';
import { sendCommandNew } from '@/api/jmap/training';
var clock = new THREE.Clock();
let movegroup = new THREE.Group();
let human = new THREE.Object3D();
let controller1, controller2,raycastervr;
let vrPlane;
let vrPlaneStatus = false;
let tempMatrix = new THREE.Matrix4();
let nowdevice = null;
export function Jl3dfaultdeviceVR(dom,group,token,skinCode) {
var scope = this;
const ZONE = 'level';
const SPEED = 10;
const OFFSET = 0.2;
THREE.Pathfinding = Pathfinding;
let groupID,path,level,navmesh;
let pathPoints = [];
let playerPosition = new THREE.Vector3( -3.5, 0.5, 5.5 );
let targetPosition = new THREE.Vector3();
let pathfinder = new THREE.Pathfinding();
var textureNav = new THREE.TextureLoader().load( '../../static/vrtest/daohang.png' );
textureNav.wrapS = THREE.RepeatWrapping;
textureNav.wrapT=THREE.RepeatWrapping;
textureNav.repeat.x = 40;
textureNav.repeat.y = 2;
var materialNav = new THREE.MeshBasicMaterial( {
map: textureNav,
transparent: true,
} );
let navMesh;
let navStatus = false;
let switchModel;
this.dom = dom;
this.nowcode = null;
this.animateswitch = false;
this.mixers = [];
this.showmodel = null;
let helpbox,textplane;
let daochamodel;
let psdtexturemap = [];
//点击事件状态
this.raycasterstatus = false;
//动画状态
this.animastats = true;
//当前选中模型
this.nowobject = null;
//当前动画播放模型
this.animationmodel = null;
this.stationtexture = [];
this.devicetext = new Textconfig();
this.windowstatus = '0';
//初始化webgl渲染
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setClearColor(new THREE.Color(0x000000));
this.renderer.setPixelRatio( window.devicePixelRatio );
this.renderer.setSize(window.innerWidth, window.innerHeight);
// this.renderer.shadowMap.enabled = true;
// this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.gammaInput = true;
this.renderer.gammaOutput = true;
this.renderer.vr.enabled = true;
this.dom.appendChild(this.renderer.domElement);
document.body.appendChild( VRButton.createButton( this.renderer ) );
//定义相机
this.camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 200);
this.camera.position.set(0, 0, 0);
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
//定义场景(渲染容器)
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xa0a0a0);
this.scene.add(human);
this.scene.add( movegroup );
human.add(scope.camera);
controller1 = scope.renderer.vr.getController( 0 );
controller1.addEventListener( 'selectstart', onSelectStart );
controller1.addEventListener( 'selectend', onSelectEnd );
controller1.addEventListener( 'squeeze', squeezeStart );
human.add( controller1 );
controller2 = scope.renderer.vr.getController( 1 );
controller2.addEventListener( 'selectstart', onControlModelStart );
controller2.addEventListener( 'selectend', onControlModelEnd );
human.add( controller2 );
var geometry = new THREE.BufferGeometry().setFromPoints( [ new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, - 1 ) ] );
var line = new THREE.Line( geometry );
line.name = 'line';
line.scale.z = 5;
controller1.add( line.clone() );
controller2.add( line.clone() );
vrPlane = new VrGui();
raycastervr = new THREE.Raycaster();
let loaderObj = new THREE.OBJLoader();
// load a resource
loaderObj.load(
// resource URL
'../../static/vrtest/path.obj',
// called when resource is loaded
function ( object ) {
// console.time('createZone()');
console.log(object);
const zone = THREE.Pathfinding.createZone(object.children[0].geometry);
// console.timeEnd('createZone()');
pathfinder.setZoneData( ZONE, zone );
const navWireframe = new THREE.Mesh(object.children[0].geometry, new THREE.MeshBasicMaterial({
color: 0x808080,
wireframe: true
}));
navWireframe.position.y = OFFSET / 2;
// scene.add(navWireframe);
navmesh = object;
// scene.add(navmesh);
// movegroup.add(navmesh);
// Set the player's navigation mesh group
groupID = pathfinder.getGroup( ZONE, playerPosition );
},
// called when loading is in progresses
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);
let moveanima = new MoveanimateVr(scope);
//定义全局光
let ambientLight = new THREE.AmbientLight(0xffffff, 1.3);
this.scene.add(ambientLight);
var spotLight = new THREE.SpotLight(0xececff);
spotLight.position.set(-50, 80, 0);
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 2048;
spotLight.shadow.mapSize.height = 2048;
this.scene.add(spotLight);
this.controls = new THREE.OrbitControls(this.camera, dom);
this.controls.maxPolarAngle = Math.PI / 2;
this.controls.minPolarangle = Math.PI / 5;
this.controls.maxDistance = 80;
this.controls.screenSpacePanning = true;
this.controls.update();
document.addEventListener( "mousedown", onselect, false );
let vrwebworker = new Worker("../../static/workertest/vrwebworker.js");
let connectmsg = {
type:'init',
baseurl:getBaseUrl(),
topic:'/user/queue/simulation/jl3d/'+group,
token:getToken(),
};
vrwebworker.postMessage(connectmsg);
vrwebworker.onmessage = function (event) {
console.log(event.data.type);
console.log(event.data);
if(event.data.type == "Device_Fault_Set_3D"){
if(event.data.body.type == "SWITCH"){
nowdevice = {
code:event.data.body.code,
name:'',
type:event.data.body.type,
typetext:'',
text:event.data.body.fault,
fault:event.data.body.fault,
}
nowdevice.name = "道岔"+nowdevice.code+"故障";
nowdevice.typetext = "道岔";
if(event.data.body.fault == "SPLIT"){
nowdevice.text = "道岔失表";
}
setTextVr(nowdevice,vrPlane);
}
return;
}
if(event.data.type == "SWITCH"){
scope.updateaction(event.data);
}
if(event.data.type == "Device_Fault_Over_3D"){
vrPlane.group.remove(textplane);
// console.log(event.data);
//
// deletefault(event.data.body.code);
}
};
window.onresize = function () {
scope.camera.aspect = window.innerWidth / window.innerHeight;
scope.camera.updateProjectionMatrix();
scope.renderer.setSize(window.innerWidth, window.innerHeight);
}
this.domresize = function(){
scope.camera.aspect = window.innerWidth/ window.innerHeight;
scope.camera.updateProjectionMatrix();
scope.renderer.setSize(window.innerWidth, window.innerHeight);
}
this.modelmanager = new ModelManagerVR();
// getPublish3dMapDetail(skinCode).then(netdata => {
// let netDataAssets = JSON.parse(netdata.data.assets);
// setpsdstationmap(JSON.parse(netdata.data.stands));
scope.modelmanager.loadpromise(scope.mixers).then(function (data) {
console.log(scope.modelmanager.testmodel);
switchModel = scope.modelmanager.testmodel.mesh.getObjectByName("SWITCH");
moveanima.initlistnew(switchModel);
console.log(switchModel);
scope.devicetext.initdevicetext(switchModel);
// scope.scene.add(switchModel);
// switchModel.position.set(switchPos.x,switchPos.y,switchPos.z);
human.position.set(switchModel.matrixWorld.elements[12],switchModel.matrixWorld.elements[13],switchModel.matrixWorld.elements[14]);
// scope.modelmanager.testmodel.mesh.scale.set(0.1,0.1,0.1);
scope.scene.add(scope.modelmanager.testmodel.mesh);
vrwebworker.postMessage("connect");
animate();
});
// });
function onSelectStart( event ) {
var controller = event.target;
console.log(event);
let clickGui = getGuiButton(controller);
if(clickGui.length > 0){
var intersection = clickGui[ 0 ];
var object = intersection.object;
if(object.name == "shebeijian"){
human.position.set( -199.90, 0.20+0.6, -5.76 );
}
if(object.name == "jiankongshi"){
human.position.set( -213.610, 0.20+0.6,5.38);
}
if(object.name == "station1"){
human.position.set( -242.37, -4.46+0.6, 4.13);
}
if(object.name == "station2"){
human.position.set( -242.621, 0.20+0.6, 4.90 );
}
if(object.name == "anime"){
if(scope.animastats){
scope.animastats = false;
moveanima.setplaylist(moveanima.animatelist["undefinedon"],true)
}else{
scope.animastats = true;
moveanima.setplaylist(moveanima.animatelist["undefinedoff"],true);
}
}
if(object.name == "nav"){
if(navMesh){
scope.scene.remove( navMesh );
}
if(navStatus){
navStatus = false;
}else{
navStatus = true;
pathPoints = [];
let startPoint = new THREE.Vector3(human.position.x,human.position.y-0.6,human.position.z);
pathPoints.push(new THREE.Vector3(human.position.x,human.position.y,human.position.z));
groupID = pathfinder.getGroup( ZONE, startPoint );
targetPosition = new THREE.Vector3(switchModel.matrixWorld.elements[12],-5.596,switchModel.matrixWorld.elements[14]);
//
// console.log(pathPoints[0]);
// console.log(targetPosition);
// console.log(ZONE);
// console.log(groupID);
let path = pathfinder.findPath( startPoint, targetPosition, ZONE, groupID );
if(path){
for(let i=0;i<path.length;i++){
pathPoints.push(new THREE.Vector3(path[i].x,path[i].y+0.6,path[i].z));
}
let curve = new THREE.CatmullRomCurve3(pathPoints,false);
var geometry = new THREE.TubeGeometry( curve, 100, 0.2, 50, false );
navMesh = new THREE.Mesh( geometry, materialNav );
scope.scene.add( navMesh );
}
}
}
if(object.name == "reset"){
scope.resetmodel();
}
if(object.name == "repire"){
if(nowdevice){
let command = {
code:nowdevice.code,
faultType:nowdevice.fault,
};
sendCommandNew(group,"Cancel_Fault", command).then((response) => {
resolve(response);
if(response.code == 200){
nowdevice = null;
}
}).catch(error => {
});
}
}
}else{
var intersections = getIntersections( controller );
// console.log(intersections);
if ( intersections.length > 0 ) {
console.log(intersections);
var intersection = intersections[ 0 ];
console.log(intersection);
var object = intersection.object;
// object.matrix.premultiply( tempMatrix );
// object.matrix.decompose( object.position, object.quaternion, object.scale );
// object.material.emissive.b = 1;
// controller.add( object );
// controller.userData.selected = object;
// console.log(object.matrixWorld.elements);
human.position.set( intersection.point.x, intersection.point.y+0.6, intersection.point.z );
}
}
}
function onSelectEnd( event ) {
var controller = event.target;
if ( controller.userData.selected !== undefined ) {
// var object = controller.userData.selected;
// object.matrix.premultiply( controller.matrixWorld );
// object.matrix.decompose( object.position, object.quaternion, object.scale );
// object.material.emissive.b = 0;
// group.add( object );
controller.userData.selected = undefined;
}
}
function onControlModelStart( event ) {
var controller = event.target;
var intersections = getIntersections( controller );
if ( intersections.length > 0 ) {
// for(){}
// console.log(intersections);
var intersection = intersections[ 0 ];
console.log(intersection.object);
// console.log(intersection);
// tempMatrix.getInverse( controller.matrixWorld );
//
// var object = intersection.object;
// object.matrix.premultiply( tempMatrix );
// object.matrix.decompose( object.position, object.quaternion, object.scale );
// object.material.emissive.b = 1;
// controller.add( object );
}
}
function onControlModelEnd( event ) {
var controller = event.target;
if ( controller.userData.selected !== undefined ) {
// var object = controller.userData.selected;
// object.matrix.premultiply( controller.matrixWorld );
// object.matrix.decompose( object.position, object.quaternion, object.scale );
// // object.material.emissive.b = 0;
// group.add( object );
// controller.userData.selected = undefined;
}
}
function squeezeStart(){
console.log("squeez");
scope.modelmanager.testmodel.action.play();
console.log(moveanima.animatelist);
if(vrPlaneStatus){
vrPlaneStatus = false;
// vrPlane.group.position.copy(circle.position);
scope.scene.remove( vrPlane.group );
}else{
vrPlaneStatus = true;
vrPlane.group.position.copy(circle.position);
vrPlane.group.lookAt(human.position);
scope.scene.add( vrPlane.group );
}
}
this.animationmsgshowon = function(nowobject){
scope.animationmodel = nowobject;
if(helpbox){
scope.animationmodel.helpbox = null;
scope.scene.remove( helpbox );
helpbox = undefined;
}
// settext(scope.animationmodel,scope.animationmodel.position);
// console.log(scope.animationmodel);
helpbox = new THREE.BoxHelper( scope.animationmodel, 0xff0000 );
moveanima.updatehelpbox(helpbox,textplane);
// settext(intersects[0].object,intersects[0].point);
// getdevicemsg(intersects[0].object.name);
scope.scene.add( helpbox );
getdevicemsg(nowobject.name);
}
this.animationmsgshowoff = function(nowobject){
if(helpbox){
scope.animationmodel.helpbox = null;
scope.scene.remove( helpbox );
helpbox = undefined;
}
if(textplane){
scope.scene.remove(textplane);
textplane.geometry.dispose();
textplane.material.dispose();
}
scope.animationmodel = null;
}
function getGuiButton( controller ) {
tempMatrix.identity().extractRotation( controller.matrixWorld );
raycastervr.ray.origin.setFromMatrixPosition( controller.matrixWorld );
raycastervr.ray.direction.set( 0, 0, - 1 ).applyMatrix4( tempMatrix );
return raycastervr.intersectObjects( vrPlane.group.children,true );
}
function getIntersections( controller ) {
tempMatrix.identity().extractRotation( controller.matrixWorld );
raycastervr.ray.origin.setFromMatrixPosition( controller.matrixWorld );
raycastervr.ray.direction.set( 0, 0, - 1 ).applyMatrix4( tempMatrix );
return raycastervr.intersectObjects( navmesh.children,true );
}
var loader = new THREE.TextureLoader();
var circle;
loader.load(
'../../static/vrtest/ring.png',
// onLoad callback
function ( texture ) {
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var geometry = new THREE.PlaneBufferGeometry( 0.6, 0.6, 32 );
// var geometry = new THREE.CircleBufferGeometry( 0.2, 32 );
circle = new THREE.Mesh( geometry, material );
circle.rotation.x = -Math.PI/2;
scope.scene.add( circle );
},
// onProgress callback currently not supported
undefined,
// onError callback
function ( err ) {
console.error( 'An error happened.' );
}
);
function intersectObjects( controller ) {
var intersections = getIntersections( controller );
if ( intersections.length > 0 ) {
var intersection = intersections[ 0 ];
var object = intersection.object;
circle.position.set( intersection.point.x, intersection.point.y+0.01, intersection.point.z );
}
}
// function setpsdstationmap(stationlist){
// for(let i=0,leni=stationlist.length;i<leni;i++){
// psdtexturemap[stationlist[i].direction1.code] = stationlist[i].code;
// psdtexturemap[stationlist[i].direction2.code] = stationlist[i].code;
// }
// }
function animate() {
scope.renderer.setAnimationLoop( render );
}
function render() {
intersectObjects( controller1 );
moveanima.animateupdate();
let delta = clock.getDelta();
if (scope.mixers) {
for (let i = 0; i < scope.mixers.length; i++) {
if (scope.mixers[i]) {
scope.mixers[i].update(delta);
}
}
}
scope.controls.update();
scope.renderer.render(scope.scene, scope.camera);
}
this.resetmodel = function(){
scope.animastats = true;
moveanima.setplaylist(moveanima.animatelist["undefinedfuwei"],true);
};
this.updateaction = function (data) {
if (data.type == "SWITCH") {
console.log("pay");
if (data.normal == "0") {
console.log("play1");
scope.modelmanager.testmodel.normalPosition = "0";
scope.modelmanager.testmodel.action.reset();
scope.modelmanager.testmodel.action.time = 0;
scope.modelmanager.testmodel.action.timeScale = 1;
scope.modelmanager.testmodel.action.play();
} else if (data.normal == "1") {
console.log("play2");
scope.modelmanager.testmodel.normalPosition = "1";
scope.modelmanager.testmodel.action.reset();
scope.modelmanager.testmodel.action.time = scope.modelmanager.testmodel.action._clip.duration;
scope.modelmanager.testmodel.action.timeScale = -1;
scope.modelmanager.testmodel.action.play();
}
}
}
function getdevicemsg(selectname){
// console.log(selectname);
for(let i=0,leni=scope.devicetext.devicelist.length;i<leni;i++){
if(selectname == scope.devicetext.devicelist[i].name){
// updatemsg(scope.devicetext.devicelist[i].text,scope.devicetext.devicelist[i].msg);
i=leni;
}
}
}
this.updatewindowstatus = function(nowwindowstatus){
scope.windowstatus == nowwindowstatus;
}
function setTextVr(intersects,plane){
console.log(intersects);
console.log(plane);
if(intersects.text){
let textgeometry = new THREE.PlaneBufferGeometry( 0.6, 0.4, 1 );
let textt = new THREE.CanvasTexture(getTextCanvas(intersects));
let textmaterial = new THREE.MeshBasicMaterial( {
side: THREE.DoubleSide,
map:textt ,transparent: true,
alphaTest:0.1
} );
if(textplane){
scope.scene.remove(textplane);
textplane.geometry.dispose();
textplane.material.dispose();
}
textplane= new THREE.Mesh( textgeometry, textmaterial );
// textplane.name = data[i].code;
textplane.position.x = 0;
textplane.position.y = 0.8;
textplane.position.z = 0.01;
// console.log(textplane.position);
// textplane.tcode = data[i].code;
// textplane.rotation.y = -Math.PI/2;
// scope.textlist.push(textplane);
// newmesh.children[0].add(textplane);
plane.group.add(textplane);
textgeometry.dispose();
textmaterial.dispose();
textt.dispose();
}
}
var beauty = new Image();
beauty.src = "../../static/texture/scene.png";
//canvas文字贴图方法
//PS:待提炼 增强功能
function getTextCanvas(text){
var canvas = document.getElementById('canvastexture');
canvas.width = 256;
canvas.height = 128;
var ctx = canvas.getContext('2d');
//var bg = canvas.createPattern(img, "no-repeat");
//ctx.fillStyle = bg;
ctx.fillRect(0, 0,256,128);
ctx.font = "20px Verdana";
ctx.fillStyle = '#FFFFFF';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.clearRect(0,0,256,128);
//console.log(text.groupNumber);
ctx.drawImage(beauty,0,0,256, 128);
ctx.fillText("新的设备故障", 110,30);
ctx.fillText(text.name, 110,65);
ctx.fillText("故障原因:"+text.text, 110,100);
//ctx.fillText(text.trainModel.name, width/2,height*3/4);
let data = ctx.getImageData(0, 0,256, 128);
return data;
}
}

View File

@ -0,0 +1,261 @@
/**
* @author mrdoob / http://mrdoob.com
* @author Mugen87 / https://github.com/Mugen87
*/
var VRButton = {
createButton: function ( renderer, options ) {
if ( options && options.referenceSpaceType ) {
renderer.vr.setReferenceSpaceType( options.referenceSpaceType );
}
function showEnterVR( device ) {
button.style.display = '';
button.style.cursor = 'pointer';
button.style.left = 'calc(50% - 50px)';
button.style.width = '100px';
button.textContent = 'ENTER_VR';
button.onmouseenter = function () {
button.style.opacity = '1.0';
};
button.onmouseleave = function () {
button.style.opacity = '0.5';
};
button.onclick = function () {
device.isPresenting ? device.exitPresent() : device.requestPresent( [ { source: renderer.domElement } ] );
};
renderer.vr.setDevice( device );
}
function showEnterXR( /*device*/ ) {
var currentSession = null;
function onSessionStarted( session ) {
session.addEventListener( 'end', onSessionEnded );
renderer.vr.setSession( session );
button.textContent = 'EXIT VR';
currentSession = session;
}
function onSessionEnded( /*event*/ ) {
currentSession.removeEventListener( 'end', onSessionEnded );
renderer.vr.setSession( null );
button.textContent = 'ENTER VR';
currentSession = null;
}
//
button.style.display = '';
button.style.cursor = 'pointer';
button.style.left = 'calc(50% - 50px)';
button.style.width = '100px';
button.textContent = 'ENTER VR';
button.onmouseenter = function () {
button.style.opacity = '1.0';
};
button.onmouseleave = function () {
button.style.opacity = '0.5';
};
button.onclick = function () {
if ( currentSession === null ) {
// WebXR's requestReferenceSpace only works if the corresponding feature
// was requested at session creation time. For simplicity, just ask for
// the interesting ones as optional features, but be aware that the
// requestReferenceSpace call will fail if it turns out to be unavailable.
// ('local' is always available for immersive sessions and doesn't need to
// be requested separately.)
var sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor' ] };
navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
} else {
currentSession.end();
}
};
}
function disableButton() {
button.style.display = '';
button.style.cursor = 'auto';
button.style.left = 'calc(50% - 75px)';
button.style.width = '150px';
button.onmouseenter = null;
button.onmouseleave = null;
button.onclick = null;
}
function showVRNotFound() {
disableButton();
button.textContent = 'VR NOT FOUND';
renderer.vr.setDevice( null );
}
function showXRNotFound() {
disableButton();
button.textContent = 'VR NOT FOUND';
}
function stylizeElement( element ) {
element.style.position = 'absolute';
element.style.bottom = '20px';
element.style.padding = '12px 6px';
element.style.border = '1px solid #fff';
element.style.borderRadius = '4px';
element.style.background = 'rgba(0,0,0,0.1)';
element.style.color = '#fff';
element.style.font = 'normal 13px sans-serif';
element.style.textAlign = 'center';
element.style.opacity = '0.5';
element.style.outline = 'none';
element.style.zIndex = '999';
}
if ( 'xr' in navigator ) {
console.log("xr");
var button = document.createElement( 'button' );
button.style.display = 'none';
stylizeElement( button );
navigator.xr.isSessionSupported( 'immersive-vr' ).then( function ( supported ) {
if ( supported ) {
showEnterXR();
} else {
showXRNotFound();
}
} );
return button;
} else if ( 'getVRDisplays' in navigator ) {
console.log("vr");
var button = document.createElement( 'button' );
button.style.display = 'none';
stylizeElement( button );
window.addEventListener( 'vrdisplayconnect', function ( event ) {
showEnterVR( event.display );
}, false );
window.addEventListener( 'vrdisplaydisconnect', function ( /*event*/ ) {
showVRNotFound();
}, false );
window.addEventListener( 'vrdisplaypresentchange', function ( event ) {
button.textContent = event.display.isPresenting ? 'EXIT_VR' : 'ENTER_VR';
}, false );
window.addEventListener( 'vrdisplayactivate', function ( event ) {
event.display.requestPresent( [ { source: renderer.domElement } ] );
}, false );
navigator.getVRDisplays()
.then( function ( displays ) {
if ( displays.length > 0 ) {
showEnterVR( displays[ 0 ] );
} else {
showVRNotFound();
}
} ).catch( showVRNotFound );
return button;
} else {
var message = document.createElement( 'a' );
message.href = 'https://immersive-web.github.io/webxr/';
message.innerHTML = 'WEBXR NOT SUPPORTED';
message.style.left = 'calc(50% - 90px)';
message.style.width = '180px';
message.style.textDecoration = 'none';
stylizeElement( message );
return message;
}
}
};
export { VRButton };

View File

@ -0,0 +1,380 @@
export function MoveanimateVr(main){
let scope = this;
this.helpbox = null;
this.textplane = null;
//动画列表
this.animatelist = [];
this.playlist = null;
this.playorder = 0;
//动画播放器开关
this.enable = true;
//动画开关状态
this.status = true;
//当前动画模型
this.nowmodelname = undefined;
this.initlistnew = function(switchmodel){
scope.animatelist[switchmodel.animacode+"chaijie"] = [];
scope.animatelist[switchmodel.animacode+"fuwei"] = [];
for(let i=0,leni=switchmodel.children.length;i<leni;i++){
if(switchmodel.children[i].name == "DDJ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x-1.5,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"dizuoon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x-1.5,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"dizuooff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "DJZ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x-3,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"Lxingon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x-3,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"Lxingoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "DINGK"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+9,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"jiaoxingxiantieon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+9,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"jiaoxingxiantieoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "SZ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x-1.5,switchmodel.children[i].position.y,switchmodel.children[i].position.z-1));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"zhongchuipianon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.xx-1.5,switchmodel.children[i].position.y,switchmodel.children[i].position.z-1));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"zhongchuipianoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "JSQ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x-3,switchmodel.children[i].position.y+3,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"laganon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x-3,switchmodel.children[i].position.y+3,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"laganoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "YWJCQ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z+3));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"dongjiedianzhouon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z+3));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"dongjiedianzhouoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "ESWCJJ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"neibuon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"neibuoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "AQJD"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z-2));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"jiedianon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z-2));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"jiedianoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "QDP"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z-3));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"yapianon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z-3));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"yapianoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "SDP"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z-4));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"fanghuozhaoon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z-4));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"fanghuozhaooff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "ZDKBQ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+3,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"dianyuanpianon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+3,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"dianyuanpianoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name == "ZZ"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x+3,switchmodel.children[i].position.y+3,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"xinpianon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x+3,switchmodel.children[i].position.y+3,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"xinpianoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name =="BSG"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x+1,switchmodel.children[i].position.y,switchmodel.children[i].position.z-5));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"jueyuanzhouon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x+1,switchmodel.children[i].position.y,switchmodel.children[i].position.z-5));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"jueyuanzhouoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name =="DZG"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x-1,switchmodel.children[i].position.y,switchmodel.children[i].position.z-5));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"cigangon",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x-1,switchmodel.children[i].position.y,switchmodel.children[i].position.z-5));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"cigangoff",points2,0.5,true,0);
}
if(switchmodel.children[i].name =="CTK"){
let points1 = [];
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
points1.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"chaijie"],switchmodel.children[i],switchmodel.name+"ccichuihuqion",points1,0.5,true,0);
let points2 = [];
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y+6,switchmodel.children[i].position.z));
points2.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
scope.initanimate(scope.animatelist[switchmodel.animacode+"fuwei"],switchmodel.children[i],switchmodel.name+"ccichuihuqioff",points2,0.5,true,0);
}
}
// let points = [];
// points.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
// points.push(new THREE.Vector3(switchmodel.children[i].position.x,switchmodel.children[i].position.y,switchmodel.children[i].position.z));
// scope.initanimate(switchmodel.children[i],switchmodel.name+"select1",points,true);
let modelorderlist = [];
modelorderlist[switchmodel.animacode] = [
{name:"SZ",pos:[-1.5,0,-1]},//锁子
{name:"DINGK",pos:[0,0,9]},//顶盖
{name:"DJZ",pos:[-3,0,0]},
{name:"DDJ",pos:[-1.5,0,0]},
{name:"JSQ",pos:[-3,0,3]},
{name:"ZDKBQ",pos:[0,0,3]},
{name:"ZZ",pos:[3,0,3]},
{name:"ESWCJJ",pos:[0,0,6]},
{name:"CTK",pos:[0,0,6]},
{name:"YWJCQ",pos:[0,3,6]},
{name:"AQJD",pos:[0,-2,6]},
{name:"QDP",pos:[0,-3,6]},
{name:"SDP",pos:[0,-4,6]},
{name:"BSG",pos:[1,-5,0]},
{name:"DZG",pos:[-1,-5,0]}
];
scope.animatelist[switchmodel.animacode+"on"] = [];
scope.animatelist[switchmodel.animacode+"off"] = [];
for(let i=0,leni=modelorderlist[switchmodel.animacode].length;i<leni;i++){
let orderdata = modelorderlist[switchmodel.animacode];
let modelon = switchmodel.getObjectByName(orderdata[i].name);
// modelon.helpbox = undefined;
let pointson = [];
pointson.push(new THREE.Vector3(modelon.position.x,modelon.position.y,modelon.position.z));
pointson.push(new THREE.Vector3(modelon.position.x+orderdata[i].pos[0],modelon.position.y+orderdata[i].pos[1],modelon.position.z+orderdata[i].pos[2]));
let pointsoff = [];
pointsoff.push(new THREE.Vector3(modelon.position.x+orderdata[i].pos[0],modelon.position.y+orderdata[i].pos[1],modelon.position.z+orderdata[i].pos[2]));
pointsoff.push(new THREE.Vector3(modelon.position.x,modelon.position.y,modelon.position.z));
// if(i == 0){
scope.initanimate(scope.animatelist[switchmodel.animacode+"on"],modelon,switchmodel.animacode+modelon.name+"on",pointson,0.03,true,i);
scope.initanimate(scope.animatelist[switchmodel.animacode+"off"],modelon,switchmodel.animacode+modelon.name+"off",pointsoff,0.03,true,leni-i-1);
// }else if((i+1)<leni){
// scope.initanimate(modelon,switchmodel.animacode+modelon.name+"on",pointson,0.03,true,switchmodel.animacode+orderdata[i+1].name+"on");
// scope.initanimate(modelon,switchmodel.animacode+modelon.name+"off",pointsoff,0.03,true,switchmodel.animacode+orderdata[i-1].name+"off");
// }else{
// scope.initanimate(modelon,switchmodel.animacode+modelon.name+"on",pointson,0.03,true);
// scope.initanimate(modelon,switchmodel.animacode+modelon.name+"off",pointsoff,0.03,true,switchmodel.animacode+orderdata[i-1].name+"off");
// }
// if(switchmodel.children[i].name == "xinpian"){
// }
// if(switchmodel.children[i].name =="cigang"){
// }
}
}
//动画对象定义
this.initanimate = function(list,modelobject,name,points,speed,type,nextname){
let curve = new THREE.CatmullRomCurve3(points);
// curve动画轨迹
// progress动画进度
// enable当前动画开关
// speed动画速度
let animate = {
name:name,
curve:curve,
progress:0,
directchange:false,
connectmodel:modelobject,
enable:false,
status:"start",
speed:speed,
next:null
};
// list[nextname] = [];
if(list[nextname] == undefined){
list[nextname] = [];
}
list[nextname].push(animate);
if(nextname){
// list[nextname] = animate;
// animate.next = nextname;
}else{
// list.push(animate);
}
}
this.setplaylist = function(nowlist,enable){
scope.playlist = nowlist;
scope.enable = enable;
scope.playorder = 0;
for(let i=0;i<scope.playlist[scope.playorder].length;i++){
scope.playlist[scope.playorder][i].status = "start";
}
}
this.updatehelpbox = function(nowhelpbox,nowtextplane){
scope.textplane = nowtextplane;
scope.helpbox = nowhelpbox;
}
this.startstop = function(){
}
this.next = function(){
}
this.before = function(){
}
//动画播放器
this.animateupdate = function(){
// console.log(scope.animatelist);
if(scope.enable){
if(scope.playlist){
for(let i=0;i<scope.playlist[scope.playorder].length;i++){
if(scope.playlist[scope.playorder][i].status == "start"){
}
if(scope.playlist[scope.playorder][i].progress>=1){
let point = scope.playlist[scope.playorder][i].curve.getPointAt(1);
//更新模型坐标
scope.playlist[scope.playorder][i].connectmodel.position.x = point.x;
scope.playlist[scope.playorder][i].connectmodel.position.y = point.y;
scope.playlist[scope.playorder][i].connectmodel.position.z = point.z;
scope.playlist[scope.playorder][i].enable = false;
scope.playlist[scope.playorder][i].status = "end";
scope.playlist[scope.playorder][i].progress = 0;
if(i >= scope.playlist[scope.playorder].length-1){
if(scope.playorder >= scope.playlist.length-1 ){
scope.playlist = null;
scope.status = true;
scope.enable = false;
main.animationmsgshowoff();
scope.nowmodelname = undefined;
scope.playorder = null;
break;
}else{
scope.playorder += 1;
}
}
}else{
// console.log(scope.animatelist[k].connectmodel);
if(scope.nowmodelname != scope.playlist[scope.playorder][i].connectmodel.name){
scope.nowmodelname = scope.playlist[scope.playorder][i].connectmodel.name;
main.animationmsgshowon(scope.playlist[scope.playorder][i].connectmodel);
}
//根据动画进度获取动画轨迹上点
scope.status = false;
let point = scope.playlist[scope.playorder][i].curve.getPointAt(scope.playlist[scope.playorder][i].progress);
//更新模型坐标
scope.playlist[scope.playorder][i].connectmodel.position.x = point.x;
scope.playlist[scope.playorder][i].connectmodel.position.y = point.y;
scope.playlist[scope.playorder][i].connectmodel.position.z = point.z;
if(scope.helpbox){
scope.helpbox.update();
}
if(scope.textplane){
scope.textplane.position.x = scope.playlist[scope.playorder][i].connectmodel.matrixWorld.elements[12];
scope.textplane.position.y = scope.playlist[scope.playorder][i].connectmodel.matrixWorld.elements[13]+100;
scope.textplane.position.z = scope.playlist[scope.playorder][i].connectmodel.matrixWorld.elements[14];
}
//判断模型转向
if(scope.playlist[scope.playorder][i].directchange){
let tangent = scope.playlist[scope.playorder][i].curve.getPointAt(scope.playlist[scope.playorder][i].progress+0.001);
// scope.animatelist[k]
tangent = null;
}
//增加动画进度,释放点变量
scope.playlist[scope.playorder][i].progress += scope.playlist[scope.playorder][i].speed;
point = null;
}
}
}
}
}
}

View File

@ -0,0 +1,123 @@
export function VrGui(){
let scope = this;
this.group = new THREE.Group();
var geometryPlane = new THREE.PlaneBufferGeometry( 0.7, 1, 16);
var texturePlane = new THREE.TextureLoader().load( '../../static/texture/devicemsgpane.png' );
var materialPlane = new THREE.MeshBasicMaterial( {
map: texturePlane,
side: THREE.DoubleSide,
transparent: true,
} );
var plane = new THREE.Mesh( geometryPlane, materialPlane );
plane.position.y = 0.6;
// plane.position.z = -1.5;
// plane.rotation.x = -Math.PI/6;
scope.group.add( plane );
var geometry = new THREE.PlaneBufferGeometry( 0.15, 0.15, 16 );
var textureshebei = new THREE.TextureLoader().load( '../../static/vrtest/shebei.png' );
var material = new THREE.MeshBasicMaterial( {
map: textureshebei,
transparent: true,
} );
var buttonShiBei = new THREE.Mesh( geometry, material );
buttonShiBei.name = "shebeijian";
buttonShiBei.position.x = -0.24;
buttonShiBei.position.y = -0.13;
buttonShiBei.position.z = 0.01;
plane.add( buttonShiBei );
var texturezhankong = new THREE.TextureLoader().load( '../../static/vrtest/zhankong.png' );
var material = new THREE.MeshBasicMaterial( {
map: texturezhankong,
transparent: true,
} );
var buttonZhankong = new THREE.Mesh( geometry, material );
buttonZhankong.name = "jiankongshi";
buttonZhankong.position.x = -0.08;
buttonZhankong.position.y = -0.13;
buttonZhankong.position.z = 0.01;
plane.add( buttonZhankong );
var texture = new THREE.TextureLoader().load( '../../static/vrtest/station1.png' );
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var buttonStation1 = new THREE.Mesh( geometry, material );
buttonStation1.name = "station1";
buttonStation1.position.x = 0.08;
buttonStation1.position.y = -0.13;
buttonStation1.position.z = 0.01;
plane.add( buttonStation1 );
var texture = new THREE.TextureLoader().load( '../../static/vrtest/station2.png' );
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var buttonStation2 = new THREE.Mesh( geometry, material );
buttonStation2.name = "station2";
buttonStation2.position.x = 0.24;
buttonStation2.position.y = -0.13;
buttonStation2.position.z = 0.01;
plane.add( buttonStation2 );
var texture = new THREE.TextureLoader().load( '../../static/vrtest/nav.png' );
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var button1 = new THREE.Mesh( geometry, material );
button1.name = "nav";
button1.position.x = -0.24;
button1.position.y = -0.3;
button1.position.z = 0.01;
plane.add( button1 );
var texture = new THREE.TextureLoader().load( '../../static/vrtest/anime.png' );
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var buttonnav = new THREE.Mesh( geometry, material );
buttonnav.name = "anime";
buttonnav.position.x = -0.08;
buttonnav.position.y = -0.3;
buttonnav.position.z = 0.01;
plane.add( buttonnav );
var texture = new THREE.TextureLoader().load( '../../static/vrtest/reset.png' );
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var button2 = new THREE.Mesh( geometry, material );
button2.name = "reset";
button2.position.x = 0.08;
button2.position.y = -0.3;
button2.position.z = 0.01;
plane.add( button2 );
var texture = new THREE.TextureLoader().load( '../../static/texture/xiuli.png' );
var material = new THREE.MeshBasicMaterial( {
map: texture,
transparent: true,
} );
var buttonreset = new THREE.Mesh( geometry, material );
buttonreset.name = "repire";
buttonreset.position.x = 0.24;
buttonreset.position.y = -0.3;
buttonreset.position.z = 0.01;
plane.add( buttonreset );
}

View File

@ -0,0 +1,56 @@
export function ModelManagerVR(){
let scope = this;
this.testmodel = {
code:"test",
locateType:"01",
mesh:null,
url:"../../static/vrtest/vrtest.FBX"
};
this.loadpromise = function (mixers){
let initlist = [];
initlist.push(fbxpromise(mixers,scope.testmodel));
// initlist.push(fbxpromise(data.Switch,mixers,scope.switchmodel));
// initlist.push(fbxpromise(data.Signal,mixers,scope.signalmodel));
// initlist.push(fbxpromise(data.stationstand,mixers,scope.standmodel));
// initlist.push(fbxpromise(data.section,mixers,scope.sectionmodel));
// initlist.push(fbxpromise(data.room,mixers,scope.roommodel));
return new Promise(function(resolve, reject){
Promise.all(initlist).then((result) => {
resolve("success"); //['成功了', 'success']
}).catch((error) => {
//console.log(error);
});
});
}
}
function fbxpromise(mixers,model){
return new Promise(function(resolve, reject){
var loader = new THREE.FBXLoader();
loader.load( model.url, function ( object ) {
let mixer = new THREE.AnimationMixer( object );
object.animacode = model.code;
model.mesh = object;
if(object.animations.length>0){
model.action = mixer.clipAction( object.animations[ 0 ] );
model.action.setLoop(THREE.LoopOnce);
model.action.clampWhenFinished = true;
mixers.push(mixer);
//model.action.play();
}
resolve(model.locateType);
} );
});
}

View File

@ -9,7 +9,6 @@ import { ModelManager } from '@/jlmap3d/jl3dpassflow/loader.js';
import { SkeletonUtils } from '@/jlmap3d/main/utils/SkeletonUtils.js'; import { SkeletonUtils } from '@/jlmap3d/main/utils/SkeletonUtils.js';
import { Pathfinding } from '@/jlmap3d/jl3dpassflow/utils/Pathfinding.js'; import { Pathfinding } from '@/jlmap3d/jl3dpassflow/utils/Pathfinding.js';
// const Pathfinding = window.threePathfinding.Pathfinding;
import { ZoneManager } from '@/jlmap3d/jl3dpassflow/model/zonemanager.js'; import { ZoneManager } from '@/jlmap3d/jl3dpassflow/model/zonemanager.js';
import {Materialload} from '@/jlmap3d/main/loaders/Materialload.js'; import {Materialload} from '@/jlmap3d/main/loaders/Materialload.js';
@ -20,7 +19,6 @@ import { PassflowConnect } from '@/jlmap3d/jl3dpassflow/connect/passflowconnect.
import StompClient from '@/utils/sock'; import StompClient from '@/utils/sock';
import { Loading } from 'element-ui'; import { Loading } from 'element-ui';
// const Pathfinding = window.threePathfinding.Pathfinding;
let clock = new THREE.Clock(); let clock = new THREE.Clock();
let delta; let delta;
let scene,camerass,renderer; let scene,camerass,renderer;

View File

@ -16,6 +16,7 @@ const Jlmap3dPassFlow = () => import('@/views/jlmap3d/passflow/jl3dpassflow');
const Jlmap3dStation = () => import('@/views/jlmap3d/station/jl3dstation'); const Jlmap3dStation = () => import('@/views/jlmap3d/station/jl3dstation');
const Jlmap3dModel = () => import('@/views/jlmap3d/device/jl3ddevice'); const Jlmap3dModel = () => import('@/views/jlmap3d/device/jl3ddevice');
const Jlmap3dTrain = () => import('@/views/jlmap3d/devicetrain/jl3ddevicetrain'); const Jlmap3dTrain = () => import('@/views/jlmap3d/devicetrain/jl3ddevicetrain');
const Jlmap3dMaintainerVr = () => import('@/views/jlmap3d/maintainer/jl3dmaintainervr');
// const Jl3dMaintainer = () => import('@/views/jlmap3d/maintainer/jl3dmaintainer'); // const Jl3dMaintainer = () => import('@/views/jlmap3d/maintainer/jl3dmaintainer');
const Display = () => import('@/views/display/index'); const Display = () => import('@/views/display/index');
@ -231,6 +232,12 @@ export const constantRoutes = [
component: Jlmap3dTrain, component: Jlmap3dTrain,
hidden: true hidden: true
}, },
{
path: '/jlmap3d/maintainervr', // 贵阳 继电器
component: Jlmap3dMaintainerVr,
hidden: true
},
{ // 竞赛系统报名 { // 竞赛系统报名
path: '/jsxtApply', path: '/jsxtApply',
component: JsxtApply, component: JsxtApply,

View File

@ -16,7 +16,6 @@
</Jl3ddevice-Msg> </Jl3ddevice-Msg>
<Jl3ddevice-List v-show="isswitch" :devicelist="equiplist" @sdevice="sdevice"> <Jl3ddevice-List v-show="isswitch" :devicelist="equiplist" @sdevice="sdevice">
</Jl3ddevice-List> </Jl3ddevice-List>
<canvas id="canvastexture" />
<div class="jl3dcontrolpane" v-show="isswitch"> <div class="jl3dcontrolpane" v-show="isswitch">
<el-button-group> <el-button-group>
<el-button type="primary" @click="initdevice">初始化</el-button> <el-button type="primary" @click="initdevice">初始化</el-button>
@ -49,7 +48,6 @@
return { return {
datastatus:"", datastatus:"",
jl3d: null, jl3d: null,
psdlist:this.$store.state.map.map.psdList,
windowstatus:false, windowstatus:false,
nowdevice:null, nowdevice:null,

View File

@ -1,7 +1,10 @@
<template> <template>
<div class="jalmap3ddiv"> <div class="jalmap3ddiv">
<div class="jl3dmap3dMaintainerSelect" v-show="selectShow">
<div class="maintainerSelectButton" style="left:33%" @click="initNormal">通号检修模式</div>
<div class="maintainerSelectButton" style="right:33%" @click="initVR">通号检修模式(VR)</div>
</div>
<div class="display-draft"> <div class="display-draft">
<el-button-group> <el-button-group>
@ -16,12 +19,14 @@
@selectdevice="selectdevice" @selectdevice="selectdevice"
> >
</Devicefault-List> </Devicefault-List>
<Fault-Device <Fault-Device
v-show="deviceShow" v-show="deviceShow"
ref = "faultdevice" ref = "faultdevice"
@closedevice3dview ="devicemodel" @closedevice3dview ="devicemodel"
/> />
<div id="testjlmap3d" class="jlmap3ddraw"> <div id="testjlmap3d" class="jlmap3ddraw">
<canvas id="canvastexture" /> <canvas id="canvastexture" />
</div> </div>
@ -55,10 +60,11 @@ import { JLmap3dMaintainer } from '@/jlmap3d/jl3dmaintainer/jlmap3dmaintainer.js
import DevicefaultList from '@/views/jlmap3d/maintainer/component/devicefaultlist'; import DevicefaultList from '@/views/jlmap3d/maintainer/component/devicefaultlist';
import FaultDevice from '@/views/jlmap3d/maintainer/component/faultdevice'; import FaultDevice from '@/views/jlmap3d/maintainer/component/faultdevice';
import Jlmap3dConfig from '@/views/jlmap3d/simulation/show/configmenu'; import Jlmap3dConfig from '@/views/jlmap3d/simulation/show/configmenu';
import { ProjectIcon } from '@/scripts/ProjectConfig'; import { ProjectIcon } from '@/scripts/ProjectConfig';
import bgPsdImg from '@/assets/bg_psd.png';
// import Jlmap3dMsg from '@/views/jlmap3d/show/msg'; // import Jlmap3dMsg from '@/views/jlmap3d/show/msg';
var train; var train;
@ -67,7 +73,6 @@ export default {
components: { components: {
DevicefaultList, DevicefaultList,
FaultDevice, FaultDevice,
// Jlmap3dMsg // Jlmap3dMsg
// ShowProperty // ShowProperty
}, },
@ -85,6 +90,7 @@ export default {
mapid:null, mapid:null,
group:null, group:null,
token:null, token:null,
selectShow:true,
faultlistshow:true, faultlistshow:true,
devicelist:[], devicelist:[],
deviceShow:true, deviceShow:true,
@ -123,12 +129,12 @@ export default {
this.mapid = this.$route.query.mapId; this.mapid = this.$route.query.mapId;
this.group = this.$route.query.group; this.group = this.$route.query.group;
this.token = this.$route.query.token; this.token = this.$route.query.token;
this.init(this.mapid, this.group);
}, },
show: function (skinCode, group) { show: function (skinCode, group) {
if (this.jlmap3d == null) { if (this.jlmap3d == null) {
this.init(skinCode, group); this.initNormal(skinCode, group);
} else { } else {
// this.jlmap3d.restart(); // this.jlmap3d.restart();
this.jlmap3d.eventon(); this.jlmap3d.eventon();
@ -136,21 +142,38 @@ export default {
} }
}, },
init: function (skinCode, group) { initNormal: function () {
this.selectShow = false;
this.deviceShow = false;
// this.deviceShow = true;
// this.faultlistshow = true;
const mapdata = this.$store.getters['map/map']; const mapdata = this.$store.getters['map/map'];
const dom = document.getElementById('app'); const dom = document.getElementById('app');
const project = this.$route.query.project; const project = this.$route.query.project;
// console.log(project); // console.log(project);
this.deviceShow = false;
if (project) { if (project) {
this.jlmap3d = new JLmap3dMaintainer(dom, mapdata, skinCode, this.$store, group, project); this.jlmap3d = new JLmap3dMaintainer(dom, mapdata, this.mapid, this.$store, this.group, project);
} else { } else {
this.jlmap3d = new JLmap3dMaintainer(dom, mapdata, skinCode, this.$store, group, ''); this.jlmap3d = new JLmap3dMaintainer(dom, mapdata, this.mapid, this.$store, this.group, '');
} }
this.jlmap3d.eventon(); this.jlmap3d.eventon();
}, },
initVR:function (skinCode, group) {
const routeData = this.$router.resolve({
path:'/jlmap3d/maintainervr',
query:{
mapid:this.mapid,
group:this.group,
token:this.token,
noPreLogout: true
}
});
window.open(routeData.href);
},
raystand() { raystand() {
this.jlmap3d.rayswitch('stand'); this.jlmap3d.rayswitch('stand');
}, },
@ -182,8 +205,6 @@ export default {
this.devicelist.push(fault); this.devicelist.push(fault);
}, },
deletefault(code){ deletefault(code){
console.log(code);
console.log(this.devicelist);
for(let i=0,leni=this.devicelist.length;i<leni;i++){ for(let i=0,leni=this.devicelist.length;i<leni;i++){
if(code == this.devicelist[i].code){ if(code == this.devicelist[i].code){
this.devicelist.splice(i,1); this.devicelist.splice(i,1);
@ -204,14 +225,12 @@ export default {
this.$refs.faultdevice.showmodel(divicedata); this.$refs.faultdevice.showmodel(divicedata);
}, },
warningmsg(nowmsg){ warningmsg(nowmsg){
console.log(nowmsg);
this.controlmsg = nowmsg; this.controlmsg = nowmsg;
this.msgshow = true; this.msgshow = true;
setTimeout(this.warningmsgoff,3000); setTimeout(this.warningmsgoff,3000);
}, },
warningmsgoff(){ warningmsgoff(){
this.msgshow = false; this.msgshow = false;
}, },
showroom(){ showroom(){
this.deviceShow = true; this.deviceShow = true;
@ -221,7 +240,6 @@ export default {
this.$emit('back'); this.$emit('back');
this.isswitch = false; this.isswitch = false;
}, },
} }
}; };
</script> </script>
@ -278,6 +296,31 @@ export default {
z-index: 2; z-index: 2;
} }
.jl3dmap3dMaintainerSelect{
position:absolute;
width: 100%;
height: 100%;
z-index: 35;
background-image:url("/static/texture/bg.jpg");
// background-repeat:no-repeat;
background-size:100%;
}
.maintainerSelectButton{
position:absolute;
width: 200px;
height: 100px;
position:absolute;
top:49%;
text-align: center;
font-size: 20px;
line-height:100px;
background-image:url("/static/texture/scene.png");
background-repeat:no-repeat;
background-size:100%;
}
.jlmap3ddraw { .jlmap3ddraw {
float: left; float: left;
left: 0; left: 0;

View File

@ -0,0 +1,115 @@
<template>
<div id="jl3ddevicefaultvr" class="jl3dfaultdraw">
<canvas id="canvastexture" />
</div>
</template>
<script>
import Vue from 'vue';
import { Jl3dfaultdeviceVR } from '@/jlmap3d/jl3dmaintainer/Jl3dfaultdevicevr.js';
import { sendCommandNew } from '@/api/jmap/training';
import Command from '@/scripts/cmdPlugin/Command';
import Handler from '@/scripts/cmdPlugin/Handler';
export default {
name: 'MaintainerVR',
components: {
},
data() {
return {
}
},
watch: {
},
computed: {
code() {
return this.$route.query.code;
},
mapId() {
return this.$route.query.mapid;
},
group(){
return this.$route.query.group;
},
},
mounted() {
let code = this.$route.query.code;
let group = this.$route.query.group;
let header = this.$route.query.token;
this.datastatus = "new";
this.initnewdata(group,header);
},
beforeDestroy() {
},
methods: {
initnewdata: function (group,header){
let dom = document.getElementById('jl3ddevicefaultvr');
this.jl3d = new Jl3dfaultdeviceVR(dom,group,header,this.mapId);
},
}
}
</script>
<style scoped>
/* #jl3d {
width: 937px;
height: 937px;
} */
.jl3dfaultdraw {
position: absolute;
float: right;
top:0;
right:0;
/* left: 0; */
width: 100%;
height: 100%;
z-index: 3;
}
#canvastexture {
position: absolute;
float: left;
left: 0;
z-index: -12;
}
.repirbutton{
width:160px;
height:160px;
position: absolute;
right:15px;
bottom:5px;
background-image:url("/static/texture/xiuli.png");
background-repeat:no-repeat;
background-size:100%;
}
.backbutton{
width:50px;
height:50px;
position: absolute;
right:125px;
top:5px;
background-image:url("/static/texture/xx.png");
background-repeat:no-repeat;
background-size:100%;
}
#canvastexture {
position: absolute;
float: left;
left: 0;
z-index: -12;
}
.jl3dcontrolpane{
position: absolute;
top:0;
right:275px;
z-index: 10;
}
</style>

BIN
static/texture/bg.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

1023
static/threeold2019.min.js vendored Normal file

File diff suppressed because one or more lines are too long

BIN
static/vrtest/anime.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
static/vrtest/daohang.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
static/vrtest/nav.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

9526
static/vrtest/path.obj Normal file

File diff suppressed because it is too large Load Diff

BIN
static/vrtest/reset.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
static/vrtest/ring.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

BIN
static/vrtest/shebei.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
static/vrtest/station1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
static/vrtest/station2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
static/vrtest/vrtest.FBX Normal file

Binary file not shown.

BIN
static/vrtest/zhankong.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -0,0 +1,751 @@
// importScripts('sockjs.js');
// import { getToken } from '@/utils/auth';
// import { getBaseUrl } from '@/utils/baseUrl';
// import SockJS from 'sockjs-client';
// const websocketUrl = 'ws://test.joylink.club/jlcloud/joylink-websocket?token=';
// const websocketUrl = `http://192.168.3.6:9000/joylink-websocket?token=`;
let websocketUrl = null;
let token = null;
var StompClient = function (headers,token) {
let scope = this;
this.url = websocketUrl + token;
this.headers = headers || {};
this.connect();
};
StompClient.prototype = {
socket: null,
clientIns: null,
subscribeMap: null,
url: '',
status: false,
sockStatus: 0,
headers: {
// 'X-Token': getToken()
},
count: 0,
topic: '',
onmessage: null,
checkTimer: null,
// 连接服务端
connect() {
return new Promise((resolve, reject) => {
try {
// 断开已有连接
if (this.clientIns && this.clientIns.connected) {
this.clientIns.disconnect();
this.clientIns = null;
}
// // 建立连接对象(还未发起连接)
// this.socket = new SockJS(websocketUrl + token);
//
// // 获取 STOMP 子协议的客户端对象
// this.clientIns = Stomp.over(this.socket);
this.websocket = new WebSocket(this.url.replace(/https/, 'wss').replace(/http/, 'ws'));
this.clientIns = Stomp.over(this.websocket);
this.closeStompDebug();
// 向服务器发起websocket连接并发送CONNECT帧
this.clientIns.connect({ 'X-Token': token }, () => {
console.info('连接成功.');
this.count = 0;
this.status = true;
// 恢复订阅
if (this.topic && this.onmessage) {
this.unsubscribe(this.topic);
this.subscribe(this.topic, this.onmessage, this.headers);
}
resolve(this);
}, () => {
if (this.checkTimer) {
clearInterval(this.checkTimer);
this.checkTimer = null;
}
});
} catch (err) {
reject(err);
}
});
},
logOut(err) {
if (err.code == 50008 || err.code == 50014) {
this.url = websocketUrl + token;
this.status = false;
this.count++;
this.reconnect(this.count);
}
},
// 恢复链接
reconnect(count) {
console.info(`尝试第${count || 1}次连接.`);
this.connect().then(() => { }).catch(() => {
this.count++;
this.reconnect(this.count);
});
},
closeStompDebug() {
if (this.clientIns) {
this.clientIns.debug = undefined;
}
},
// 订阅指定的topic
subscribe(topic, onmessage, headers) {
this.topic = topic;
this.onmessage = onmessage;
this.headers = headers;
if (this.status) {
if (!this.subscribeMap) {
this.subscribeMap = new Map();
}
try {
var subscription = this.subscribeMap.get(topic);
if (!subscription) {
subscription = this.clientIns.subscribe(topic, onmessage, headers); // 接收消息通过 subscribe() 方法实现
this.subscribeMap.set(topic, subscription);
}
} catch (err) {
setTimeout(() => {
this.subscribe(topic, onmessage, headers);
}, 300);
}
} else {
setTimeout(() => {
this.subscribe(topic, onmessage, headers);
}, 300);
}
},
unsubscribe(topic) {
if (this.subscribeMap) {
const subscription = this.subscribeMap.get(topic);
if (subscription) {
subscription.unsubscribe();
this.subscribeMap.delete(topic);
console.log('取消订阅');
}
}
},
// 发送消息
send(url, msg) {
if (this.status) {
if (msg) {
msg = JSON.stringify(msg);
}
try {
this.clientIns.send(url, {}, msg);
} catch (err) {
this.status = false;
this.send(url, msg);
}
} else {
setTimeout(() => {
this.send(url, msg);
}, 300);
}
},
disconnect() {
if (this.checkTimer) {
clearInterval(this.checkTimer);
this.checkTimer = null;
}
if (this.clientIns && this.clientIns.connected) {
this.clientIns.disconnect();
this.clientIns = null;
}
this.status = false;
console.log('断开连接');
}
};
var Byte, Client, Frame, Stomp,
__hasProp = {}.hasOwnProperty,
__slice = [].slice;
Byte = {
LF: '\x0A',
NULL: '\x00'
};
Frame = (function() {
var unmarshallSingle;
function Frame(command, headers, body) {
this.command = command;
this.headers = headers != null ? headers : {};
this.body = body != null ? body : '';
}
Frame.prototype.toString = function() {
var lines, name, skipContentLength, value, _ref;
lines = [this.command];
skipContentLength = this.headers['content-length'] === false ? true : false;
if (skipContentLength) {
delete this.headers['content-length'];
}
_ref = this.headers;
for (name in _ref) {
if (!__hasProp.call(_ref, name)) continue;
value = _ref[name];
lines.push("" + name + ":" + value);
}
if (this.body && !skipContentLength) {
lines.push("content-length:" + (Frame.sizeOfUTF8(this.body)));
}
lines.push(Byte.LF + this.body);
return lines.join(Byte.LF);
};
Frame.sizeOfUTF8 = function(s) {
if (s) {
return encodeURI(s).match(/%..|./g).length;
} else {
return 0;
}
};
unmarshallSingle = function(data) {
var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;
divider = data.search(RegExp("" + Byte.LF + Byte.LF));
headerLines = data.substring(0, divider).split(Byte.LF);
command = headerLines.shift();
headers = {};
trim = function(str) {
return str.replace(/^\s+|\s+$/g, '');
};
_ref = headerLines.reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
idx = line.indexOf(':');
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
}
body = '';
start = divider + 2;
if (headers['content-length']) {
len = parseInt(headers['content-length']);
body = ('' + data).substring(start, start + len);
} else {
chr = null;
for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {
chr = data.charAt(i);
if (chr === Byte.NULL) {
break;
}
body += chr;
}
}
return new Frame(command, headers, body);
};
Frame.unmarshall = function(datas) {
var data;
return (function() {
var _i, _len, _ref, _results;
_ref = datas.split(RegExp("" + Byte.NULL + Byte.LF + "*"));
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
if ((data != null ? data.length : void 0) > 0) {
_results.push(unmarshallSingle(data));
}
}
return _results;
})();
};
Frame.marshall = function(command, headers, body) {
var frame;
frame = new Frame(command, headers, body);
return frame.toString() + Byte.NULL;
};
return Frame;
})();
Client = (function() {
var now;
function Client(ws) {
this.ws = ws;
this.ws.binaryType = "arraybuffer";
this.counter = 0;
this.connected = false;
this.heartbeat = {
outgoing: 10000,
incoming: 10000
};
this.maxWebSocketFrameSize = 16 * 1024;
this.subscriptions = {};
}
Client.prototype.debug = function(message) {
var _ref;
return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? _ref.log(message) : void 0 : void 0;
};
now = function() {
if (Date.now) {
return Date.now();
} else {
return new Date().valueOf;
}
};
Client.prototype._transmit = function(command, headers, body) {
var out;
out = Frame.marshall(command, headers, body);
if (typeof this.debug === "function") {
this.debug(">>> " + out);
}
while (true) {
if (out.length > this.maxWebSocketFrameSize) {
this.ws.send(out.substring(0, this.maxWebSocketFrameSize));
out = out.substring(this.maxWebSocketFrameSize);
if (typeof this.debug === "function") {
this.debug("remaining = " + out.length);
}
} else {
return this.ws.send(out);
}
}
};
Client.prototype._setupHeartbeat = function(headers) {
var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;
if ((_ref = headers.version) !== Stomp.VERSIONS.V1_1 && _ref !== Stomp.VERSIONS.V1_2) {
return;
}
_ref1 = (function() {
var _i, _len, _ref1, _results;
_ref1 = headers['heart-beat'].split(",");
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
_results.push(parseInt(v));
}
return _results;
})(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];
if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {
ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
if (typeof this.debug === "function") {
this.debug("send PING every " + ttl + "ms");
}
this.pinger = Stomp.setInterval(ttl, (function(_this) {
return function() {
_this.ws.send(Byte.LF);
return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;
};
})(this));
}
if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {
ttl = Math.max(this.heartbeat.incoming, serverOutgoing);
if (typeof this.debug === "function") {
this.debug("check PONG every " + ttl + "ms");
}
return this.ponger = Stomp.setInterval(ttl, (function(_this) {
return function() {
var delta;
delta = now() - _this.serverActivity;
if (delta > ttl * 2) {
if (typeof _this.debug === "function") {
_this.debug("did not receive server activity for the last " + delta + "ms");
}
return _this.ws.close();
}
};
})(this));
}
};
Client.prototype._parseConnect = function() {
var args, connectCallback, errorCallback, headers;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
headers = {};
switch (args.length) {
case 2:
headers = args[0], connectCallback = args[1];
break;
case 3:
if (args[1] instanceof Function) {
headers = args[0], connectCallback = args[1], errorCallback = args[2];
} else {
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];
}
break;
case 4:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];
break;
default:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];
}
return [headers, connectCallback, errorCallback];
};
Client.prototype.connect = function() {
var args, errorCallback, headers, out;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
out = this._parseConnect.apply(this, args);
headers = out[0], this.connectCallback = out[1], errorCallback = out[2];
if (typeof this.debug === "function") {
this.debug("Opening Web Socket...");
}
this.ws.onmessage = (function(_this) {
return function(evt) {
var arr, c, client, data, frame, messageID, onreceive, subscription, _i, _len, _ref, _results;
data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = arr.length; _i < _len; _i++) {
c = arr[_i];
_results.push(String.fromCharCode(c));
}
return _results;
})()).join('')) : evt.data;
_this.serverActivity = now();
if (data === Byte.LF) {
if (typeof _this.debug === "function") {
_this.debug("<<< PONG");
}
return;
}
if (typeof _this.debug === "function") {
_this.debug("<<< " + data);
}
_ref = Frame.unmarshall(data);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
frame = _ref[_i];
switch (frame.command) {
case "CONNECTED":
if (typeof _this.debug === "function") {
_this.debug("connected to server " + frame.headers.server);
}
_this.connected = true;
_this._setupHeartbeat(frame.headers);
_results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);
break;
case "MESSAGE":
subscription = frame.headers.subscription;
onreceive = _this.subscriptions[subscription] || _this.onreceive;
if (onreceive) {
client = _this;
messageID = frame.headers["message-id"];
frame.ack = function(headers) {
if (headers == null) {
headers = {};
}
return client.ack(messageID, subscription, headers);
};
frame.nack = function(headers) {
if (headers == null) {
headers = {};
}
return client.nack(messageID, subscription, headers);
};
_results.push(onreceive(frame));
} else {
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);
}
break;
case "RECEIPT":
_results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);
break;
case "ERROR":
_results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);
break;
default:
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);
}
}
return _results;
};
})(this);
this.ws.onclose = (function(_this) {
return function() {
var msg;
msg = "Whoops! Lost connection to " + _this.ws.url;
if (typeof _this.debug === "function") {
_this.debug(msg);
}
_this._cleanUp();
return typeof errorCallback === "function" ? errorCallback(msg) : void 0;
};
})(this);
return this.ws.onopen = (function(_this) {
return function() {
if (typeof _this.debug === "function") {
_this.debug('Web Socket Opened...');
}
headers["accept-version"] = Stomp.VERSIONS.supportedVersions();
headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');
return _this._transmit("CONNECT", headers);
};
})(this);
};
Client.prototype.disconnect = function(disconnectCallback, headers) {
if (headers == null) {
headers = {};
}
this._transmit("DISCONNECT", headers);
this.ws.onclose = null;
this.ws.close();
this._cleanUp();
return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;
};
Client.prototype._cleanUp = function() {
this.connected = false;
if (this.pinger) {
Stomp.clearInterval(this.pinger);
}
if (this.ponger) {
return Stomp.clearInterval(this.ponger);
}
};
Client.prototype.send = function(destination, headers, body) {
if (headers == null) {
headers = {};
}
if (body == null) {
body = '';
}
headers.destination = destination;
return this._transmit("SEND", headers, body);
};
Client.prototype.subscribe = function(destination, callback, headers) {
var client;
if (headers == null) {
headers = {};
}
if (!headers.id) {
headers.id = "sub-" + this.counter++;
}
headers.destination = destination;
this.subscriptions[headers.id] = callback;
this._transmit("SUBSCRIBE", headers);
client = this;
return {
id: headers.id,
unsubscribe: function() {
return client.unsubscribe(headers.id);
}
};
};
Client.prototype.unsubscribe = function(id) {
delete this.subscriptions[id];
return this._transmit("UNSUBSCRIBE", {
id: id
});
};
Client.prototype.begin = function(transaction) {
var client, txid;
txid = transaction || "tx-" + this.counter++;
this._transmit("BEGIN", {
transaction: txid
});
client = this;
return {
id: txid,
commit: function() {
return client.commit(txid);
},
abort: function() {
return client.abort(txid);
}
};
};
Client.prototype.commit = function(transaction) {
return this._transmit("COMMIT", {
transaction: transaction
});
};
Client.prototype.abort = function(transaction) {
return this._transmit("ABORT", {
transaction: transaction
});
};
Client.prototype.ack = function(messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("ACK", headers);
};
Client.prototype.nack = function(messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("NACK", headers);
};
return Client;
})();
Stomp = {
VERSIONS: {
V1_0: '1.0',
V1_1: '1.1',
V1_2: '1.2',
supportedVersions: function() {
return '1.1,1.0';
}
},
client: function(url, protocols) {
var klass, ws;
if (protocols == null) {
protocols = ['v10.stomp', 'v11.stomp'];
}
klass = Stomp.WebSocketClass || WebSocket;
ws = new klass(url, protocols);
return new Client(ws);
},
over: function(ws) {
return new Client(ws);
},
Frame: Frame
};
if (typeof exports !== "undefined" && exports !== null) {
exports.Stomp = Stomp;
}
Stomp.setInterval = function(interval, f) {
return setInterval(f, interval);
};
Stomp.clearInterval = function(id) {
return clearInterval(id);
};
let data = null;
let topic = null;
let header = null;
function timedCount(){
onmessage = (e) => {
if(e.data.type == "init"){
topic = e.data.topic;
header = {'X-Token': e.data.token };
token = e.data.token;
websocketUrl = e.data.baseurl+'/joylink-websocket?token=';
}
if(e.data == "connect"){
let teststomp = new StompClient(header,token);
teststomp.subscribe(topic, callback, header);
}
}
function callback(Response) {
data = JSON.parse(Response.body);
// if(data.type == 'TrainRun_3D'){
// for (let i=0,leni = data.body.length; i<leni; i++) {
// data.body[i].type = "TRAIN";
// postMessage(data.body[i]);
// }
// }
if(data.type == "Device_Fault_Set_3D"){
postMessage(data);
return;
}
if(data.type == "Device_Fault_Over_3D"){
postMessage(data);
return;
}
if(data.type == "Device_Load_Destroy_3D"){
postMessage(data);
return;
}
//
// if(data.type == 'TrainRun_3D'){
// postMessage(data);
// return;
// }
//data.type == 'Simulation_DeviceStatus' &&
// if(data.type == 'Simulation_DeviceStatus'){
// for (let i= 0,leni = data.body.length; i<leni; i++) {
// if(data.body[i].deviceType == "TRAIN"){
// postMessage(data.body[i]);
// }
// }
// }
// if(data.type == "Train_Hmi_3D"){
// postMessage(data);
// return;
// }
if(data.type == 'DeviceCtrl_3D'){
// console.log(data);
postMessage(data.body);
return;
}
if(data.type == 'Simulation_Reset'){
postMessage(data);
return;
}
// if( data.body.length>300){
// // console.log(data);
// postMessage(data);
// return;
// }
}
}
timedCount();