提交 7bce9073 编写于 作者: doc_wei's avatar doc_wei

新增光源

上级 8a876878
......@@ -8,6 +8,9 @@ layui.config({
winui.renderColor();
var index = parent.layer.getFrameIndex(window.name);
// 添加方向光光源
threeUtil.initDirectionalLight();
// 加入模型到场景
$("body").on("click", "#modeList .item", function(e){
var url = $(this).attr("src");
......@@ -19,22 +22,10 @@ layui.config({
matchingLanguage();
//加入地板到场景
// 加入地板到场景
$("body").on("click", "#floorList .item", function(e){
var url = $(this).attr("src");
var loader = new THREE.TextureLoader();
//加载一个资源
var groundTexture = loader.load(url);
console.log(editor);
console.log(groundTexture);
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set(5, 5);
//地基材料
var groundMaterial = new THREE.MeshLambertMaterial({ map: groundTexture });
var mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(30, 30), groundMaterial);
mesh.rotation.x = -Math.PI / 2;
mesh.receiveShadow = true;
editor.scene.add(mesh);
threeUtil.initFloor(url);
});
});
......
......@@ -10,16 +10,13 @@ function Config() {
'project/title': '',
'project/editable': false,
'project/vr': false,
'project/renderer/antialias': true,
'project/renderer/shadows': true,
'project/renderer/shadowType': 1, // PCF
'project/renderer/physicallyCorrectLights': false,
'project/renderer/toneMapping': 0, // NoToneMapping
'project/renderer/toneMappingExposure': 1,
'settings/history': false,
'settings/shortcuts/translate': 'w',
'settings/shortcuts/rotate': 'e',
'settings/shortcuts/scale': 'r',
......@@ -28,49 +25,30 @@ function Config() {
};
if ( window.localStorage[ name ] === undefined ) {
window.localStorage[ name ] = JSON.stringify( storage );
} else {
var data = JSON.parse( window.localStorage[ name ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
}
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
}
window.localStorage[ name ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );
},
clear: function () {
delete window.localStorage[ name ];
}
};
}
......
......@@ -550,54 +550,34 @@ Editor.prototype = {
},
selectById: function ( id ) {
if ( id === this.camera.id ) {
this.select( this.camera );
return;
}
this.select( this.scene.getObjectById( id ) );
},
selectByUuid: function ( uuid ) {
var scope = this;
this.scene.traverse( function ( child ) {
if ( child.uuid === uuid ) {
scope.select( child );
}
} );
},
deselect: function () {
this.select( null );
},
focus: function ( object ) {
if ( object !== undefined ) {
this.signals.objectFocused.dispatch( object );
}
},
focusById: function ( id ) {
this.focus( this.scene.getObjectById( id ) );
},
clear: function () {
......@@ -626,58 +606,38 @@ Editor.prototype = {
this.materials = {};
this.textures = {};
this.scripts = {};
this.materialsRefCounter.clear();
this.animations = {};
this.mixer.stopAllAction();
this.deselect();
this.signals.editorCleared.dispatch();
},
//
fromJSON: async function ( json ) {
var loader = new THREE.ObjectLoader();
var camera = await loader.parseAsync( json.camera );
this.camera.copy( camera );
this.signals.cameraResetted.dispatch();
this.history.fromJSON( json.history );
this.scripts = json.scripts;
this.setScene( await loader.parseAsync( json.scene ) );
},
toJSON: function () {
// scripts clean up
var scene = this.scene;
var scripts = this.scripts;
for ( var key in scripts ) {
var script = scripts[ key ];
if ( script.length === 0 || scene.getObjectByProperty( 'uuid', key ) === undefined ) {
delete scripts[ key ];
}
}
//
return {
metadata: {},
project: {
shadows: this.config.getKey( 'project/renderer/shadows' ),
......@@ -691,33 +651,23 @@ Editor.prototype = {
scene: this.scene.toJSON(),
scripts: this.scripts,
history: this.history.toJSON()
};
},
objectByUuid: function ( uuid ) {
return this.scene.getObjectByProperty( 'uuid', uuid, true );
},
execute: function ( cmd, optionalName ) {
this.history.execute( cmd, optionalName );
},
undo: function () {
this.history.undo();
},
redo: function () {
this.history.redo();
}
};
......
......@@ -26,40 +26,23 @@ function Loader( editor ) {
};
this.loadFiles = function ( files, filesMap ) {
if ( files.length > 0 ) {
var filesMap = filesMap || LoaderUtils.createFilesMap( files );
var manager = new THREE.LoadingManager();
manager.setURLModifier( function ( url ) {
url = url.replace( /^(\.?\/)/, '' ); // remove './'
var file = filesMap[ url ];
if ( file ) {
console.log( 'Loading', url );
return URL.createObjectURL( file );
}
return url;
} );
manager.addHandler( /\.tga$/i, new TGALoader() );
for ( var i = 0; i < files.length; i ++ ) {
scope.loadFile( files[ i ], manager );
}
}
};
this.loadFile = function ( file, manager ) {
......@@ -78,28 +61,18 @@ function Loader( editor ) {
} );
switch ( extension ) {
case '3dm':
reader.addEventListener( 'load', async function ( event ) {
var contents = event.target.result;
var { Rhino3dmLoader } = await import( '../../examples/jsm/loaders/3DMLoader.js' );
var loader = new Rhino3dmLoader();
loader.setLibraryPath( '../examples/jsm/libs/rhino3dm/' );
loader.parse( contents, function ( object ) {
editor.execute( new AddObjectCommand( editor, object ) );
} );
}, false );
reader.readAsArrayBuffer( file );
break;
case '3ds':
reader.addEventListener( 'load', async function ( event ) {
......@@ -149,23 +122,15 @@ function Loader( editor ) {
break;
case 'dae':
reader.addEventListener( 'load', async function ( event ) {
var contents = event.target.result;
var { ColladaLoader } = await import( '../../examples/jsm/loaders/ColladaLoader.js' );
var loader = new ColladaLoader( manager );
var collada = loader.parse( contents );
collada.scene.name = filename;
editor.execute( new AddObjectCommand( editor, collada.scene ) );
}, false );
reader.readAsText( file );
break;
case 'drc':
......@@ -257,45 +222,28 @@ function Loader( editor ) {
break;
case 'gltf':
reader.addEventListener( 'load', async function ( event ) {
var contents = event.target.result;
var loader;
if ( isGLTF1( contents ) ) {
alert( 'Import of glTF asset not possible. Only versions >= 2.0 are supported. Please try to upgrade the file to glTF 2.0 using glTF-Pipeline.' );
} else {
var { DRACOLoader } = await import( '../../examples/jsm/loaders/DRACOLoader.js' );
var { GLTFLoader } = await import( '../../examples/jsm/loaders/GLTFLoader.js' );
var dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( '../examples/js/libs/draco/gltf/' );
loader = new GLTFLoader( manager );
loader.setDRACOLoader( dracoLoader );
}
loader.parse( contents, '', function ( result ) {
var scene = result.scene;
scene.name = filename;
scene.animations.push( ...result.animations );
editor.execute( new AddObjectCommand( editor, scene ) );
} );
}, false );
reader.readAsArrayBuffer( file );
break;
case 'js':
case 'json':
......
......@@ -28,8 +28,6 @@ function Viewport( editor ) {
container.add( new ViewportCamera( editor ) );
container.add( new ViewportInfo( editor ) );
//
var renderer = null;
var pmremGenerator = null;
......@@ -41,15 +39,15 @@ function Viewport( editor ) {
var objects = [];
// helpers
var grid = new THREE.Group();
var grid1 = new THREE.GridHelper( 30, 30, 0x888888 );
// 网格为30*30
var grid1 = new THREE.GridHelper(threeUtil.gridWidth, threeUtil.gridHeight, 0x888888);
grid1.material.color.setHex( 0x888888 );
grid1.material.vertexColors = false;
grid.add( grid1 );
var grid2 = new THREE.GridHelper( 30, 6, 0x222222 );
// 将网格划分为6个大格子
var grid2 = new THREE.GridHelper(threeUtil.gridWidth, threeUtil.gridBigCell, 0x222222);
grid2.material.color.setHex( 0x222222 );
grid2.material.depthFunc = THREE.AlwaysDepth;
grid2.material.vertexColors = false;
......@@ -58,8 +56,6 @@ function Viewport( editor ) {
var viewHelper = new ViewHelper( camera, container );
var vr = new VR( editor );
//
var box = new THREE.Box3();
var selectionBox = new THREE.BoxHelper();
......@@ -74,83 +70,48 @@ function Viewport( editor ) {
var transformControls = new TransformControls( camera, container.dom );
transformControls.addEventListener( 'change', function () {
var object = transformControls.object;
if ( object !== undefined ) {
selectionBox.setFromObject( object );
var helper = editor.helpers[ object.id ];
if ( helper !== undefined && helper.isSkeletonHelper !== true ) {
helper.update();
}
signals.refreshSidebarObject3D.dispatch( object );
}
render();
} );
transformControls.addEventListener( 'mouseDown', function () {
transformControls.addEventListener( 'mouseDown', function () {
var object = transformControls.object;
objectPositionOnDown = object.position.clone();
objectRotationOnDown = object.rotation.clone();
objectScaleOnDown = object.scale.clone();
controls.enabled = false;
} );
transformControls.addEventListener( 'mouseUp', function () {
transformControls.addEventListener( 'mouseUp', function () {
var object = transformControls.object;
if ( object !== undefined ) {
switch ( transformControls.getMode() ) {
case 'translate':
if ( ! objectPositionOnDown.equals( object.position ) ) {
editor.execute( new SetPositionCommand( editor, object, object.position, objectPositionOnDown ) );
}
break;
case 'rotate':
if ( ! objectRotationOnDown.equals( object.rotation ) ) {
editor.execute( new SetRotationCommand( editor, object, object.rotation, objectRotationOnDown ) );
}
break;
case 'scale':
if ( ! objectScaleOnDown.equals( object.scale ) ) {
editor.execute( new SetScaleCommand( editor, object, object.scale, objectScaleOnDown ) );
}
break;
}
}
controls.enabled = true;
} );
sceneHelpers.add( transformControls );
......@@ -163,20 +124,14 @@ function Viewport( editor ) {
// events
function updateAspectRatio() {
camera.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
camera.updateProjectionMatrix();
}
function getIntersects( point, objects ) {
mouse.set( ( point.x * 2 ) - 1, - ( point.y * 2 ) + 1 );
raycaster.setFromCamera( mouse, camera );
return raycaster.intersectObjects( objects );
}
var onDownPosition = new THREE.Vector2();
......@@ -184,107 +139,65 @@ function Viewport( editor ) {
var onDoubleClickPosition = new THREE.Vector2();
function getMousePosition( dom, x, y ) {
var rect = dom.getBoundingClientRect();
return [ ( x - rect.left ) / rect.width, ( y - rect.top ) / rect.height ];
}
function handleClick() {
if ( onDownPosition.distanceTo( onUpPosition ) === 0 ) {
var intersects = getIntersects( onUpPosition, objects );
if ( intersects.length > 0 ) {
var object = intersects[ 0 ].object;
if ( object.userData.object !== undefined ) {
// helper
editor.select( object.userData.object );
} else {
editor.select( object );
}
} else {
editor.select( null );
}
render();
}
}
function onMouseDown( event ) {
// event.preventDefault();
var array = getMousePosition( container.dom, event.clientX, event.clientY );
onDownPosition.fromArray( array );
document.addEventListener( 'mouseup', onMouseUp, false );
}
function onMouseUp( event ) {
var array = getMousePosition( container.dom, event.clientX, event.clientY );
onUpPosition.fromArray( array );
handleClick();
document.removeEventListener( 'mouseup', onMouseUp, false );
}
function onTouchStart( event ) {
var touch = event.changedTouches[ 0 ];
var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
onDownPosition.fromArray( array );
document.addEventListener( 'touchend', onTouchEnd, false );
}
function onTouchEnd( event ) {
var touch = event.changedTouches[ 0 ];
var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
onUpPosition.fromArray( array );
handleClick();
document.removeEventListener( 'touchend', onTouchEnd, false );
}
function onDoubleClick( event ) {
var array = getMousePosition( container.dom, event.clientX, event.clientY );
onDoubleClickPosition.fromArray( array );
var intersects = getIntersects( onDoubleClickPosition, objects );
if ( intersects.length > 0 ) {
var intersect = intersects[ 0 ];
signals.objectFocused.dispatch( intersect.object );
}
}
container.dom.addEventListener( 'mousedown', onMouseDown, false );
......@@ -331,295 +244,174 @@ function Viewport( editor ) {
} );
signals.rendererUpdated.add( function () {
scene.traverse( function ( child ) {
if ( child.material !== undefined ) {
child.material.needsUpdate = true;
}
} );
render();
} );
// 创建渲染器
signals.rendererCreated.add( function ( newRenderer ) {
if ( renderer !== null ) {
renderer.setAnimationLoop( null );
renderer.dispose();
pmremGenerator.dispose();
container.dom.removeChild( renderer.domElement );
}
renderer = newRenderer;
// 首先渲染器开启阴影
renderer.shadowMap.enabled = true;
renderer.setAnimationLoop( animate );
renderer.setClearColor( 0xaaaaaa );
if ( window.matchMedia ) {
var mediaQuery = window.matchMedia( '(prefers-color-scheme: dark)' );
mediaQuery.addListener( function ( event ) {
renderer.setClearColor( event.matches ? 0x333333 : 0xaaaaaa );
updateGridColors( grid1, grid2, event.matches ? [ 0x222222, 0x888888 ] : [ 0x888888, 0x282828 ] );
render();
} );
renderer.setClearColor( mediaQuery.matches ? 0x333333 : 0xaaaaaa );
updateGridColors( grid1, grid2, mediaQuery.matches ? [ 0x222222, 0x888888 ] : [ 0x888888, 0x282828 ] );
}
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );
pmremGenerator = new THREE.PMREMGenerator( renderer );
pmremGenerator.compileEquirectangularShader();
container.dom.appendChild( renderer.domElement );
render();
} );
signals.sceneGraphChanged.add( function () {
render();
} );
signals.cameraChanged.add( function () {
render();
} );
signals.objectSelected.add( function ( object ) {
selectionBox.visible = false;
transformControls.detach();
if ( object !== null && object !== scene && object !== camera ) {
box.setFromObject( object );
if ( box.isEmpty() === false ) {
selectionBox.setFromObject( object );
selectionBox.visible = true;
}
transformControls.attach( object );
}
render();
} );
signals.objectFocused.add( function ( object ) {
controls.focus( object );
} );
signals.geometryChanged.add( function ( object ) {
if ( object !== undefined ) {
selectionBox.setFromObject( object );
}
render();
} );
signals.objectAdded.add( function ( object ) {
object.traverse( function ( child ) {
objects.push( child );
} );
} );
signals.objectChanged.add( function ( object ) {
if ( editor.selected === object ) {
selectionBox.setFromObject( object );
}
if ( object.isPerspectiveCamera ) {
object.updateProjectionMatrix();
}
if ( editor.helpers[ object.id ] !== undefined ) {
editor.helpers[ object.id ].update();
}
render();
} );
signals.objectRemoved.add( function ( object ) {
controls.enabled = true; // see #14180
if ( object === transformControls.object ) {
transformControls.detach();
}
object.traverse( function ( child ) {
objects.splice( objects.indexOf( child ), 1 );
} );
} );
signals.helperAdded.add( function ( object ) {
var picker = object.getObjectByName( 'picker' );
if ( picker !== undefined ) {
objects.push( picker );
}
} );
signals.helperRemoved.add( function ( object ) {
var picker = object.getObjectByName( 'picker' );
if ( picker !== undefined ) {
objects.splice( objects.indexOf( picker ), 1 );
}
} );
signals.materialChanged.add( function () {
render();
} );
signals.animationStopped.add( function () {
render();
} );
// background
signals.sceneBackgroundChanged.add( function ( backgroundType, backgroundColor, backgroundTexture, backgroundEquirectangularTexture ) {
switch ( backgroundType ) {
case 'None':
scene.background = null;
break;
case 'Color':
scene.background = new THREE.Color( backgroundColor );
break;
case 'Texture':
if ( backgroundTexture ) {
scene.background = backgroundTexture;
}
break;
case 'Equirectangular':
if ( backgroundEquirectangularTexture ) {
backgroundEquirectangularTexture.mapping = THREE.EquirectangularReflectionMapping;
scene.background = backgroundEquirectangularTexture;
}
break;
}
render();
} );
// environment
signals.sceneEnvironmentChanged.add( function ( environmentType, environmentEquirectangularTexture ) {
switch ( environmentType ) {
case 'None':
scene.environment = null;
break;
case 'Equirectangular':
scene.environment = null;
if ( environmentEquirectangularTexture ) {
scene.environment = pmremGenerator.fromEquirectangular( environmentEquirectangularTexture ).texture;
}
break;
case 'ModelViewer':
scene.environment = pmremGenerator.fromScene( new RoomEnvironment(), 0.04 ).texture;
break;
}
render();
} );
// fog
signals.sceneFogChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) {
switch ( fogType ) {
case 'None':
scene.fog = null;
break;
......@@ -631,15 +423,11 @@ function Viewport( editor ) {
break;
}
render();
} );
signals.sceneFogSettingsChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) {
switch ( fogType ) {
case 'Fog':
scene.fog.color.setHex( fogColor );
scene.fog.near = fogNear;
......@@ -649,136 +437,86 @@ function Viewport( editor ) {
scene.fog.color.setHex( fogColor );
scene.fog.density = fogDensity;
break;
}
render();
} );
signals.viewportCameraChanged.add( function () {
var viewportCamera = editor.viewportCamera;
if ( viewportCamera.isPerspectiveCamera ) {
viewportCamera.aspect = editor.camera.aspect;
viewportCamera.projectionMatrix.copy( editor.camera.projectionMatrix );
} else if ( viewportCamera.isOrthographicCamera ) {
// TODO
}
// disable EditorControls when setting a user camera
controls.enabled = ( viewportCamera === editor.camera );
render();
} );
signals.exitedVR.add( render );
//
signals.windowResize.add( function () {
updateAspectRatio();
renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );
render();
} );
signals.showGridChanged.add( function ( showGrid ) {
grid.visible = showGrid;
render();
} );
signals.showHelpersChanged.add( function ( showHelpers ) {
showSceneHelpers = showHelpers;
transformControls.enabled = showHelpers;
render();
} );
signals.cameraResetted.add( updateAspectRatio );
// animations
var clock = new THREE.Clock(); // only used for animations
function animate() {
var mixer = editor.mixer;
var delta = clock.getDelta();
var needsUpdate = false;
if ( mixer.stats.actions.inUse > 0 ) {
mixer.update( delta );
needsUpdate = true;
}
if ( viewHelper.animating === true ) {
viewHelper.update( delta );
needsUpdate = true;
}
if ( vr.currentSession !== null ) {
needsUpdate = true;
}
if ( needsUpdate === true ) render();
}
//
var startTime = 0;
var endTime = 0;
function render() {
startTime = performance.now();
// Adding/removing grid to scene so materials with depthWrite false
// don't render under the grid.
scene.add( grid );
renderer.setViewport( 0, 0, container.dom.offsetWidth, container.dom.offsetHeight );
renderer.render( scene, editor.viewportCamera );
scene.remove( grid );
if ( camera === editor.viewportCamera ) {
renderer.autoClear = false;
if ( showSceneHelpers === true ) renderer.render( sceneHelpers, camera );
if ( vr.currentSession === null ) viewHelper.render( renderer );
renderer.autoClear = true;
}
endTime = performance.now();
editor.signals.sceneRendered.dispatch( endTime - startTime );
}
return container;
}
function updateGridColors( grid1, grid2, colors ) {
......
......@@ -102,7 +102,6 @@
};
//
var editor = new Editor();
window.editor = editor; // Expose editor to Console
......
......@@ -30,6 +30,7 @@ var customerJS = {
"adminAssistantUtil": "../../assets/lib/layui/customer/adminAssistantUtil.js", // 行政管理模块相关工具
"codeDocUtil": "../../assets/lib/layui/customer/codeDocUtil.js", // 代码生成器相关工具类
"organizationUtil": "../../assets/lib/layui/customer/organizationUtil.js", // 组织机构相关工具类
"threeUtil": "../../assets/lib/layui/customer/threeUtil.js", // 3D编辑器相关工具类
};
//系统基础信息
......
// 3D编辑器相关工具类
var threeUtil = {
// 编辑器网格数量
gridWidth: 30,
gridHeight: 30,
gridBigCell: 6,
/**
* 添加方向光光源
*/
initDirectionalLight: function () {
var directionalLight = new THREE.DirectionalLight(0xaaaaaa)
directionalLight.position.set(0, 200, 100)
directionalLight.name = "方向光";
// 开启阴影投射
directionalLight.castShadow = true;
editor.scene.add(directionalLight);
},
/**
* 添加地板
*
* @param url 地板文件路径
*/
initFloor: function (url) {
// 加载一个资源
var loader = new THREE.TextureLoader();
var groundTexture = loader.load(url);
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set(threeUtil.gridWidth / threeUtil.gridBigCell, threeUtil.gridHeight / threeUtil.gridBigCell);
// 地基材料
var groundMaterial = new THREE.MeshLambertMaterial({ map: groundTexture });
var floor = new THREE.Mesh(new THREE.PlaneBufferGeometry(threeUtil.gridWidth, threeUtil.gridHeight), groundMaterial);
floor.rotation.x = -Math.PI / 2;
// 地板接受阴影开启
floor.receiveShadow = true;
floor.position.y = 0;
floor.name = "地板";
// 设置模型的每个部位都可以投影
floor.traverse(function (child) {
if (child.isMesh) {
child.castShadow = true
child.receiveShadow = true
}
})
editor.scene.add(floor);
}
};
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册