this is my project
/* 运行 项目需要一个初始化场景
场景为默认场景,加载完后自动去获取后台数据,
如果有资源,就加载。没有资源就为默认
*/
let loadMesh=[];
let JsonObject;
let MeshMap={};
var floor=[];
var SceneLoader=(function(){
function SceneLoader(){ //初始化一个默认的场景
var _this=this;
var canvas=document.getElementById(“renderCanvas”);
this.engine = new BABYLON.Engine(canvas, true,{ preserveDrawingBuffer: true, stencil: true },{doNotHandleContextLost: true});
this.engine.enableOfflineSupport = false; //关闭IdexedDB,默认情况下所有资源保存在本地,以便在多次加载相同文件时减少网格调用
this.scene=null;
// Resize
window.addEventListener(“resize”, function () {
_this.engine.resize();
});
this.InitScene();
}
SceneLoader.prototype.InitScene=function(){
var _this=this;
this.scene=new BABYLON.Scene(this.engine);
//var _initScreen=new loadingscreen();
//_initScreen.displayLoading(this.scene);
this._sceneOptimization();
this._InitLight();
this._InitCamera();
this._InitPlane();
this._InitSky();
this._InitGame();
this._meshInteraction(_this.scene);
this.scene.debugLayer.show();
this.engine.runRenderLoop(function () {
var divfps=document.getElementById("fps");
if (_this.scene) {
_this.scene.render(); //Render scene
_this.hemi_light.position=_this.camera.position;
divfps.innerHTML = " Fps: "+_this.engine.getFps().toFixed(); //Render FPS
}
});
},
SceneLoader.prototype._InitPlane=function(){
//初始化地形
this.ground = BABYLON.Mesh.CreatePlane("plane", 500, this.scene);
this.ground.position.y = 2;
this.ground.checkCollisions = true;
this.ground.rotation.x = Math.PI / 2;
this.ground.alwaysSelectAsActiveMesh=true;
this.ground.receiveShadows=true; //激活阴影
//Creation of a repeated textured material
this.materialPlane = new BABYLON.StandardMaterial("texturePlane", this.scene);
this.materialPlane.diffuseTexture = new BABYLON.Texture("../Resources/textures/Ground/GreenSkin.jpg", this.scene);
this.materialPlane.diffuseTexture.uScale = 5.0;
this.materialPlane.diffuseTexture.vScale = 5.0;
this.materialPlane.backFaceCulling = true;
this.materialPlane.freeze(); //减少着色器开销(目前使用静态材质)
this.ground.material = this.materialPlane;
}
SceneLoader.prototype._InitCamera=function(){
//初始化相机
this.camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(-12.76, 27.68,208.00), this.scene);
this.camera.setTarget(new BABYLON.Vector3(-12.53,27.43,207.05));
this.camera.speed=1.0;
this.camera.attachControl(this.engine.getRenderingCanvas(),true);
this.camera.checkCollisions=true; //相机添加碰撞
//这是包围相机的椭圆体
this.camera.ellipsoid = new BABYLON.Vector3(1.3, 1.3, 1.3);
this.camera.ellipsoidoffset=new BABYLON.Vector3(1,1,1);
this.camera.keysLeft=[65];
this.camera.keysRight=[68];
this.camera.keysUp=[87];
this.camera.keysDown=[83];
}
SceneLoader.prototype._InitSky=function(){
//初始化天空盒
this.skybox = BABYLON.Mesh.CreateBox("skyBox", 3000.0, this.scene);
this.skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this.scene);
this.skyboxMaterial.backFaceCulling = false;
this.skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("../Resources/textures/SkyBox_SunnyDay/TropicalSunnyDay", this.scene);
this.skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
this.skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
this.skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
this.skyboxMaterial.disableLighting = true;
this.skybox.alwaysSelectAsActiveMesh=true;
this.skybox.material = this.skyboxMaterial;
}
SceneLoader.prototype._InitLight=function(){
//初始化光源
this.hemi_light = new BABYLON.HemisphericLight('', new BABYLON.Vector3(2.88, 150 ,100), this.scene);
this.hemi_light.intensity =2.0;
this.hemi_light.specular = new BABYLON.Color3.Black(); //避免光从地面照射
this.Direct_Light = new BABYLON.DirectionalLight('', new BABYLON.Vector3(-0.5, -1, -0.5), this.scene);
this.Direct_Light.position.copyFrom(this.Direct_Light.direction.scale(-10));
this.Direct_Light.diffuse = new BABYLON.Color3(1, 1, 1);
this.Direct_Light.specular = new BABYLON.Color3(1, 1, 1);
this.Direct_Light.groundColor = new BABYLON.Color3(0, 0, 0);
this.Direct_Light.position = new BABYLON.Vector3(20, 40, 20);
this.shadowGenerator = new BABYLON.ShadowGenerator(2048, this.Direct_Light);
this.shadowGenerator.useBlurVarianceShadowMap = true;
this.shadowGenerator.setDarkness(0.05);
this.shadowGenerator.bias = 0.0001;
this.shadowGenerator.blurScale = 2;
this.shadows = this.shadowGenerator;
}
SceneLoader.prototype._InitGame=function(){
//加载模型的时候,先异步解析下是否有数据,如果有,则加载,反之则为空
$(document).ready(function () {
$.ajax({
url:"../Resources/Scene/data.js",
async:false,
error:function(){
return alert("!");
},
success:function(result_data){
JsonObject=eval(result_data);//读取数据,异步解析
for(let i=0;i<JsonObject.length;i++){
if(typeof(JsonObject[i].url)!="undefined"&&(JsonObject[i].filename)!="undefined"){
loadMesh=BABYLON.SceneLoader.ImportMeshAsync(null,JsonObject[i].url, JsonObject[i].filename, this.scene).then(
function (result){
var index=result.meshes.length-1;
console.log(i,index,result.meshes[index]);
result.meshes[index].showBoundingBox=true;
result.meshes[index].checkCollisions = true;
result.meshes[index].computeWorldMatrix(true);
// result.meshes[index].setAbsolutePosition(BABYLON.Vector3.Zero())
//通过数组存储每个对象本身的ID,然后对应他自己的mesh
MeshMap[JsonObject[i].id] = result.meshes[index];
floor[i]=new BABYLON.TransformNode("floor"+i,this.scene);
floor[i].level=i;
floor[i].clicked=true;
MeshMap[JsonObject[i].id].parent=floor[i];
console.log("floor "+MeshMap[JsonObject[i].id]);
if(i===2){
result.meshes[1].dispose();
}
//result.meshes[0].alwaysSelectAsActiveMesh=true;
//result.meshes[0].freezeWorldMatrix(); //冻结网格模型矩阵
})
}
}
Promise.all([loadMesh]).then(() => {
//当所有模型加载完成后,生成树
getTree(JsonObject,MeshMap);
console.log("资源加载正常!");
});
}});
});
}
SceneLoader.prototype.GetJsonObj=function(){return JsonObject;};
SceneLoader.prototype._optionSceneOptimiser=function(){
//网格优化
var result = new BABYLON.SceneOptimizerOptions(70, 1000);
result.optimizations.push(new BABYLON.ShadowsOptimization(0));
result.optimizations.push(new BABYLON.LensFlaresOptimization(1));
result.optimizations.push(new BABYLON.TextureOptimization(2, 56));
result.optimizations.push(new BABYLON.PostProcessesOptimization(3));
result.optimizations.push(new BABYLON.RenderTargetsOptimization(5));
return result;
}
SceneLoader.prototype._sceneOptimization=function(){
//场景优化:通过optimize
this.engine.setHardwareScalingLevel(0.5); //改善抗锯齿功能
this.scene.autoClear = true; //
this.scene.freezeActiveMeshes(); //减少世界矩阵计算
this.scene.useGeometryIdsMap=true; //将加速Geometry场景中的添加和删除
this.scene.useMaterialMeshMap=true; //将Material通过减少查找绑定网格所花费的时间来加速处理
this.scene.useClonedMeshMap=true; //将Mesh通过减少查找关联克隆网格所花费的时间来加速处理
this.scene.gravity = new BABYLON.Vector3(0, -0.9, 0); //Set gravity for the scene (G force like, on Y-axis)
this.scene.collisionsEnabled=true; //场景添加碰撞
this.scene.checkCollisions=true;
}
SceneLoader.prototype._meshInteraction=function(_scene){//获取当前选中模型的的上方模型,并隐藏
_scene.onPointerObservable.add((pointerInfo) => {
switch (pointerInfo.type) {
case BABYLON.PointerEventTypes.POINTERDOUBLETAP:
for(let i in floor) { floor[i].setEnabled(true);}
if(pointerInfo.pickInfo.hit){
if(pointerInfo.pickInfo.pickedMesh.parent==null){
return pointerInfo.pickInfo.hit=false;
}
else{
pointerInfo.pickInfo.pickedMesh.onCollideObservable.add(function (d,s) {
console.log(d);
});
var level = pointerInfo.pickInfo.pickedMesh.parent.level;
floor[level].clicked = !floor[level].clicked;
for(let i = level+1; i < floor.length; i++) {
floor[i].setEnabled(floor[level].clicked);
}
}
}
break;
case BABYLON.PointerEventTypes.POINTERWHEEL:
//滑轮拉动相机
var event = pointerInfo.event;
var delta = 0;
if (event.deltaY) {
delta = event.deltaY;
}
else if (event.detail) {
delta = -event.deltaY;
}
if (delta) {
var dir = _scene.activeCamera.getDirection(BABYLON.Axis.Z);
if (delta>0)
_scene.activeCamera.position.subtractInPlace(dir);
else
_scene.activeCamera.position.addInPlace(dir);
}
break;
}
});
}
return SceneLoader;
}());