three.js camera tween with switch statement - three.js

I am trying to tween a camera in three.js.
I have the following code in my init function.
A switch statement i am passing through an iFrame.
window.onmessage = function(evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {
y: camera.position.y
};
var to01 = {
y: yPos01
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos02':
var from02 = {
y: camera.position.y
};
var to02 = {
y: yPos02
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos03':
var from03 = {
y: camera.position.y
};
var to03 = {
y: yPos03
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
}
}
In my main website where the iFrame is, I have 3 buttons.
Once one of them is pressed I want the camera to animate to the new Y position.
export function button03_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos03'});
console.log("cameraPos = -300");
}
export function button02_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos02'});
console.log("cameraPos = 0");
}
export function button01_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos01'});
console.log("cameraPos = 300");
}
This is my animate function
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
and this is my render function
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
I manged to get it working with out a tween but now with the tween set
as soon as I press one of the buttons the model disappears from view.
I am sorry for not having a live version I am under strict NDA and switching the models just for this is allot of work. hope you understand.
Any help is most appreciated.
Thanks
You can see the full code here
<script>
/* Global vars
---------------------------------------------------
*/
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var camera, scene;
var canvasRenderer, webglRenderer;
var models_loaded = false;
var textures_loaded = false;
var container, mesh, geometry, loader, preloader;
var cameraPos
var yPos01 = 300;
var yPos02 = 0;
var yPos03 = -300;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var light;
var mouseX = 0, mouseY = 0;
/*
---------------------------------------------------
*/
/* Global materials and lighting controls
---------------------------------------------------
*/
//material
var roughness = 0.83;
var metal = 0.8;
var diffuse = 0x675f00;
//lights
var environmentInt = 0.5;
var ambiLightInt = 0.2;
var dirLightInt = 1.2;
var dirLightScalar = 1;
var hemiLightInt = 1;
/*
---------------------------------------------------
*/
/* Page Preloader
---------------------------------------------------
*/
preloader = document.createElement('img');
preloader.onload = function(){
window.addEventListener("mousemove", onmousemove, false);
init();
animate();
}
preloader.src = "https://assets.parastorage.com/marketingstudio/jessica_walsh/06/textures_512/preloader.gif";
preloader.className = "preloader";
document.body.appendChild(preloader);
/*
---------------------------------------------------
*/
/* init start
-----------------------------------------------------------------------------------------------------------------------------
*/
function init() {
/* 3D Json Loader
---------------------------------------------------
*/
container = document.createElement('div');
container.className = 'container';
container.style.visibility = 'hidden';
document.body.appendChild(container);
var manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
function onComplete(){
if(models_loaded && textures_loaded){
document.body.removeChild(preloader);
container.style.visibility = 'visible';
container.style.opacity =1;
SITE_BACKGROUNDcurrentVideovideo.play();
console.log( 'Loading completed');
}
}
manager.onLoad = function ( ) {
models_loaded = true;
onComplete();
};
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) {
//console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
manager.onError = function ( url ) {
//console.log( 'There was an error loading ' + url );
};
loader = new THREE.JSONLoader(manager);
/*
---------------------------------------------------
*/
/* Creating the camera
---------------------------------------------------
*/
camera = new THREE.PerspectiveCamera(20, window.innerWidth / window.innerHeight, 10, 1500);
camera.position.z = 340;
/* Passing event through the iframe
---------------------------------------------------
*/
window.onmessage = function (evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {y: camera.position.y};
var to01 = {y: yPos01};
TWEEN.removeAll();
var tween01 = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos02':
var from02 = {y: camera.position.y};
var to02 = {y: yPos02};
TWEEN.removeAll();
var tween02 = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos03':
var from03 = {y: camera.position.y};
var to03 = {y: yPos03};
TWEEN.removeAll();
var tween03 = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
}
};
/* Bulding the scene
---------------------------------------------------
*/
scene = new THREE.Scene();
//Lights
scene.add(new THREE.AmbientLight(0xffffff, ambiLightInt));
/* Main light
---------------------------------------------------
*/
light = new THREE.DirectionalLight(0xffffff, dirLightInt);
//light.position.set(100, -350, 0);
light.position.multiplyScalar(dirLightScalar);
//light.position.x = 100;
light.position.y = 100;
light.position.z = 100;
//Shadow parameters
light.castShadow = true;
light.shadowCameraVisible = true;
//light.shadowBias = 0.001;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
//Shadow camera fov and position
var d = 50;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowcameranear = 0.1;
light.shadowCameraFar = 2000;
light.shadowcamerafov = 30;
light.shadowDarkness = 0;
scene.add(light);
/*
---------------------------------------------------
*/
//Skylight
var skylight = new THREE.HemisphereLight( 0xffffff, 0x080820, hemiLightInt );
scene.add( skylight );
/* Texture Loader
---------------------------------------------------
*/
var tx_manager = new THREE.LoadingManager();
tx_manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
//console.log(itemsTotal);
//console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
var total_textures = 0
tx_manager.itemEnd=function (url){
total_textures++;
if(total_textures == 20){
textures_loaded = true;
onComplete();
}
//console.log(++total_textures);
}
tx_manager.onLoad = function ( x) {
console.log(textureLoader);
//console.log( 'tx_manager complete!');
};
var textureLoader = new THREE.TextureLoader(tx_manager);
/*
---------------------------------------------------
*/
/* Environment map images
---------------------------------------------------
*/
var envUrls = [
'textures/env/02/px.jpg',
'textures/env/02/nx.jpg',
'textures/env/02/py.jpg',
'textures/env/02/ny.jpg',
'textures/env/02/pz.jpg',
'textures/env/02/nz.jpg'
],
// wrap it up into the object that we need
cubemap = THREE.ImageUtils.loadTextureCube(envUrls);
// set the format, likely RGB unless you've gone crazy
cubemap.format = THREE.RGBFormat;
/*
---------------------------------------------------
*/
/* 3D Json files loading
---------------------------------------------------
*/
// TRUNK 01
loader.load( "models/trunk_01.json", function( geometry, mat ) {
//var trunk_color = 0x0061ff;
//var trunk_01_color = textureLoader.load( "textures/trunk_01_curvature.jpg" );
var trunk_01_normal = textureLoader.load( "textures_512/trunk_01_normal.jpeg" );
var trunk_01_roughness = textureLoader.load( "textures_512/trunk_01_roughness.jpeg" );
trunk_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_01_roughness,
normalMap: trunk_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_01 = new THREE.Mesh( geometry, mat );
trunk_01.material = trunk_01_Material;
trunk_01.scale.set( 1, 1, 1 );
trunk_01.position.x = 0;
trunk_01.position.z = 0;
trunk_01.position.x = 0;
trunk_01.castShadow = true;
trunk_01.receiveShadow = true;
trunk_one = trunk_01;
scene.add( trunk_01 );
//controls_01 = new THREE.DeviceOrientationControls(trunk_one, true);
} );
// TRUNK 02
loader.load( "models/trunk_02.json", function( geometry, mat ) {
//var trunk_02_color = textureLoader.load( "textures/trunk_02_curvature.jpg" );
var trunk_02_normal = textureLoader.load( "textures_512/trunk_02_normal.jpeg" );
var trunk_02_roughness = textureLoader.load( "textures_512/trunk_02_roughness.jpg" );
trunk_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_02_roughness,
normalMap: trunk_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_02 = new THREE.Mesh( geometry, mat );
trunk_02.material = trunk_02_Material;
trunk_02.scale.set( 1, 1, 1 );
trunk_02.position.x = 0;
trunk_02.position.z = 0;
trunk_02.position.x = 0;
trunk_02.castShadow = true;
trunk_02.receiveShadow = true;
trunk_two = trunk_02;
scene.add( trunk_02 );
//controls_02 = new THREE.DeviceOrientationControls(trunk_two, true);
} );
// LEAFS
loader.load( "models/leafs.json", function( geometry, mat ) {
//var leafs_color = textureLoader.load( "textures/leafs_curvature.jpg" );
var leafs_normal = textureLoader.load( "textures_512/leafs_normal.jpeg" );
var leafs_roughness = textureLoader.load( "textures_512/leafs_roughness.jpeg" );
leafs_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: leafs_roughness,
normalMap: leafs_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var leafs = new THREE.Mesh( geometry, mat );
leafs.material = leafs_Material;
leafs.scale.set( 1, 1, 1 );
leafs.position.x = 0;
leafs.position.z = 0;
leafs.position.x = 0;
leafs.castShadow = true;
leafs.receiveShadow = true;
all_leafs = leafs;
scene.add( leafs );
//controls_03 = new THREE.DeviceOrientationControls(all_leafs, true);
} );
// ROSES
loader.load( "models/roses.json", function( geometry, mat ) {
//var roses_color = textureLoader.load( "textures/roses_curvature.jpg" );
var roses_normal = textureLoader.load( "textures_512/roses_normal.jpeg" );
var roses_roughness = textureLoader.load( "textures_512/roses_roughness.jpeg" );
roses_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: roses_roughness,
normalMap: roses_normal,
normalScale: new THREE.Vector2( 0.7, 0.7 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var roses = new THREE.Mesh( geometry, mat );
roses.material = roses_Material;
roses.scale.set( 1, 1, 1 );
roses.position.x = 0;
roses.position.z = 0;
roses.position.x = 0;
roses.castShadow = true;
roses.receiveShadow = true;
all_roses = roses;
scene.add( roses );
//controls_04 = new THREE.DeviceOrientationControls(all_roses, true);
} );
// TOPS
loader.load( "models/tops.json", function( geometry, mat ) {
//var tops_color = textureLoader.load( "textures/tops_curvature.jpg" );
var tops_normal = textureLoader.load( "textures_512/tops_normal.jpeg" );
var tops_roughness = textureLoader.load( "textures_512/tops_roughness.jpeg" );
tops_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: tops_roughness,
normalMap: tops_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var tops = new THREE.Mesh( geometry, mat );
tops.material = tops_Material;
tops.scale.set( 1, 1, 1 );
tops.position.x = 0;
tops.position.z = 0;
tops.position.x = 0;
tops.castShadow = true;
tops.receiveShadow = true;
all_tops = tops;
scene.add( tops );
//controls_05 = new THREE.DeviceOrientationControls(all_tops, true);
} );
// STEMS
loader.load( "jessica_walsh/06/models/stems.json", function( geometry, mat ) {
//var stems_color = textureLoader.load( "textures/stems_curvature.jpg" );
var stems_normal = textureLoader.load( "textures_512/stems_normal.jpeg" );
var stems_roughness = textureLoader.load( "textures_512/stems_roughness.jpeg" );
stems_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: stems_roughness,
normalMap: stems_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var stems = new THREE.Mesh( geometry, mat );
stems.material = stems_Material;
stems.scale.set( 1, 1, 1 );
stems.position.x = 0;
stems.position.z = 0;
stems.position.x = 0;
stems.castShadow = true;
stems.receiveShadow = true;
all_stems = stems;
scene.add( stems );
//controls_06 = new THREE.DeviceOrientationControls(all_stems, true);
} );
// THORNES 01
loader.load( "models/thornes_01.json", function( geometry, mat ) {
//var thornes_01_color = textureLoader.load( "textures/thornes_01_curvature.jpg" );
var thornes_01_normal = textureLoader.load( "textures_512/thornes_01_normal.jpeg" );
var thornes_01_roughness = textureLoader.load( "textures_512/thornes_01_roughness.jpeg" );
thornes_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_01_roughness,
normalMap: thornes_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_01 = new THREE.Mesh( geometry, mat );
thornes_01.material = thornes_01_Material;
thornes_01.scale.set( 1, 1, 1 );
thornes_01.position.x = 0;
thornes_01.position.z = 0;
thornes_01.position.x = 0;
thornes_01.castShadow = true;
thornes_01.receiveShadow = true;
thornes_one = thornes_01;
scene.add( thornes_01 );
//controls_07 = new THREE.DeviceOrientationControls(thornes_one, true);
} );
// THORNES 02
loader.load( "models/thornes_02.json", function( geometry, mat ) {
//var thornes_02_color = textureLoader.load( "textures/thornes_02_curvature.jpg" );
var thornes_02_normal = textureLoader.load( "textures_512/thornes_02_normal.jpeg" );
var thornes_02_roughness = textureLoader.load( "textures_512/thornes_02_roughness.jpeg" );
thornes_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_02_roughness,
normalMap: thornes_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_02 = new THREE.Mesh( geometry, mat );
thornes_02.material = thornes_02_Material;
thornes_02.scale.set( 1, 1, 1 );
thornes_02.position.x = 0;
thornes_02.position.z = 0;
thornes_02.position.x = 0;
thornes_02.castShadow = true;
thornes_02.receiveShadow = true;
thornes_two = thornes_02;
scene.add( thornes_02 );
//controls_08 = new THREE.DeviceOrientationControls(thornes_two, true);
} );
// SNAKE BOSY
loader.load( "models/snake_body.json", function( geometry, mat ) {
//var snake_body_color = textureLoader.load( "textures/snake_body_curvature.jpg" );
var snake_body_normal = textureLoader.load( "textures_512/snake_body_normal.jpeg" );
var snake_body_roughness = textureLoader.load( "textures_512/snake_body_roughness.jpg" );
snake_body_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_body_roughness,
normalMap: snake_body_normal,
normalScale: new THREE.Vector2( 1.5, 1.5 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_body = new THREE.Mesh( geometry, mat );
snake_body.material = snake_body_Material;
snake_body.scale.set( 1, 1, 1 );
snake_body.position.x = 0;
snake_body.position.z = 0;
snake_body.position.x = 0;
snake_body.castShadow = true;
snake_body.receiveShadow = true;
snake_b = snake_body;
scene.add( snake_body );
//controls_09 = new THREE.DeviceOrientationControls(snake_b, true);
} );
// SNAKE HEAD
loader.load( "models/snake_head.json", function( geometry, mat ) {
//var snake_head_color = textureLoader.load( "textures/snake_head_curvature.jpg" );
var snake_head_normal = textureLoader.load( "textures_512/snake_head_normal.jpeg" );
var snake_head_roughness = textureLoader.load( "textures_512/snake_head_roughness.jpeg" );
snake_head_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_head_roughness,
normalMap: snake_head_normal,
normalScale: new THREE.Vector2( 2, 2 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_head = new THREE.Mesh( geometry, mat );
snake_head.material = snake_head_Material;
snake_head.scale.set( 1, 1, 1 );
snake_head.position.x = 0;
snake_head.position.z = 0;
snake_head.position.x = 0;
snake_head.castShadow = true;
snake_head.receiveShadow = true;
snake_h = snake_head;
scene.add( snake_head );
//controls_10 = new THREE.DeviceOrientationControls(snake_h, true);
} );
/* 3D Json files end
---------------------------------------------------
*/
// RENDERER
webglRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
webglRenderer.shadowMapEnabled = true;
//webglRenderer.shadowMapSoft = true;
webglRenderer.shadowMapType = THREE.PCFSoftShadowMap; // options are THREE.BasicShadowMap | THREE.PCFShadowMap | THREE.PCFSoftShadowMap
container.appendChild(webglRenderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
/* init end
-----------------------------------------------------------------------------------------------------------------------------
*/
/* Mouse mapping
---------------------------------------------------
*/
function onmousemove(event) {
//mouseX = (event.clientX / window.innerWidth) * 2 - 1;
//mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
mouseX = ( event.clientX - windowHalfX ) / 6;
mouseY = ( event.clientY - windowHalfY ) / 4;
}
/*
---------------------------------------------------
*/
/* Window resize
---------------------------------------------------
*/
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
var f = (camera.aspect/1.583);
if(f < 1){
camera.position.z = 340 /(camera.aspect/1.583);
}else{
camera.position.z = 340;
}
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
/*
---------------------------------------------------
*/
/* Animate
---------------------------------------------------
*/
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
/*
---------------------------------------------------
*/
/* Render
---------------------------------------------------
*/
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
//Light Position
light.position.x += ( - mouseX - camera.position.x ) * 0.03;
light.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
/*
---------------------------------------------------
*/
</script>
As seeinvisible said the tween is passing an object
with all 3 parameters and I tried to pass only the Y.
This is my updated tween
var from01 = {y: camera.position.y, z: camera.position.z};
var to01 = {y: yPos01, z: zPos01};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
camera.position.set(camera.position.x, this.y, this.z);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();

In your onUpdate function you have camera.position.set(this.y). However that seems to take 3 parameters x, y, z. Try camera.position.setY(this.y) to only set the y value.

Related

why can't I cast or receive shadows in Three.js

I'm pretty new to this and I'm trying to create lightning and shadows on the objects I just made. As you can see on the picture of the result bellow none of them actually cast or recieve shadows.
I've already enable shadow mapping for the renderer, and also enabled shadow casting and receiving for all of my objects. What am I doing wrong?
<head>
<meta charset=utf-8>
<title>Three.js Object Tester</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script type="module">
import * as THREE from './js-r119/build/three.module.js';
import { TrackballControls } from './js-r119/examples/jsm/controls/TrackballControls.js';
var WIDTH, HEIGHT, aspectRatio;
var renderer;
var scene, camera;
var controls;
var mesh;
init();
animate();
function init() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
aspectRatio = WIDTH / HEIGHT;
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( WIDTH, HEIGHT );
renderer.setClearColor( 0x000000 );
renderer.shadowMap.enabled = true;
document.body.appendChild( renderer.domElement );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, aspectRatio, 0.1, 1000 );
camera.position.set( 0, 40, 80 );
camera.lookAt( scene.position );
var light = new THREE.AmbientLight( 0xF5F5F3 ); //ambiens fény
scene.add( light );
var floorgeometry = new THREE.PlaneGeometry( 150, 150, 1, 1 );
var floormaterial = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, wireframe: false } );
var floor = new THREE.Mesh( floorgeometry, floormaterial );
floor.material.side = THREE.DoubleSide;
floor.rotation.x = 1.57;
floor.position.z = 0;
floor.position.x = 0;
floor.position.y = -42.5;
floor.receiveShadow = true;
floor.castShadow = true;
scene.add( floor );
var vertgeometry = new THREE.BoxGeometry( 20, 45, 20);
var vertmaterial = new THREE.MeshLambertMaterial( { color: 0xD5D8DC, wireframe: false } );
var vert = new THREE.Mesh( vertgeometry, vertmaterial );
vert.castShadow = true;
vert.receiveShadow = true;
vert.rotation.z = 0;
vert.rotation.x = 0;
vert.rotation.y = 0;
vert.position.z = 0;
vert.position.x = 0;
vert.position.y = -20;
var horgeometry = new THREE.BoxGeometry( 20, 40, 20);
var hormaterial = new THREE.MeshLambertMaterial( { color: 0xD5D8DC, wireframe: false } );
var hor = new THREE.Mesh( horgeometry, hormaterial );
hor.castShadow = true;
hor.position.z = 0;
hor.position.y = -32.5;
hor.position.x = 30;
hor.rotation.z = 1.57;
hor.rotation.x = 0;
hor.rotation.y = 0;
scene.add( hor );
var roofgeometry = new THREE.ConeGeometry( 14.142, 40, 4);
var roofmaterial = new THREE.MeshLambertMaterial( { color: 0xF98E76, wireframe: false } );
var roof = new THREE.Mesh( roofgeometry, roofmaterial );
roof.castShadow = true;
roof.position.z = 0;
roof.position.y = 22.5;
roof.position.x = 0;
roof.rotation.z = 0;
roof.rotation.x = 0;
roof.rotation.y = 0.775;
scene.add( roof );
scene.add( vert );
var lampgeometry = new THREE.BoxGeometry( 2, 25, 2);
var lampmaterial = new THREE.MeshLambertMaterial( { color: 0x566573, wireframe: false } );
var lamp = new THREE.Mesh( lampgeometry, lampmaterial );
lamp.castShadow = true;
lamp.rotation.z = 0;
lamp.rotation.y = 0;
lamp.position.z = 0;
lamp.position.x = -60;
lamp.position.y = -30;
var spotgeometry = new THREE.BoxGeometry( 3, 3, 3);
var spotmaterial = new THREE.MeshLambertMaterial( { color: 0xF6F50B, wireframe: false } );
var spot = new THREE.Mesh( spotgeometry, spotmaterial );
spot.position.z = 0;
spot.position.y = -17.5;
spot.position.x = -60;
scene.add( lamp );
scene.add( spot );
var geometry = new THREE.SphereGeometry( 200, 20, 20);
var appearence = new THREE.MeshLambertMaterial ({
color: 0xa2a7a9,
wireframe: false
});
var objgeometry = new THREE.BoxGeometry(8,12,8);
var objmaterial = new THREE.MeshLambertMaterial({color: 0x1C1C03, wireframe: false});
var obj = new THREE.Mesh(objgeometry, objmaterial);
obj.castShadow = true;
obj.receiveShadow = true;
obj.position.z = 0;
obj.position.x = -40;
obj.position.y = -36.5;
scene.add(obj);
var sLight = new THREE.SpotLight( 0xF6F50B, 3 ); // spotfény segédgeometriával
sLight.position.set( -60, -17.5, 0 );
sLight.castShadow = true;
sLight.distance = 100;
sLight.target = obj;
sLight.castShadow = true;
sLight.shadow.mapSize.width = 2048;
sLight.shadow.mapSize.height = 2048;
scene.add( sLight );
var spotLightHelper = new THREE.SpotLightHelper( sLight );
scene.add( spotLightHelper );
window.addEventListener( 'resize', handleWindowResize, false );
controls = new TrackballControls( camera, renderer.domElement );
controls.rotateSpeed = 5.0;
controls.panSpeed = 1.0;
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
console.log( 'WIDTH=' + WIDTH + '; HEIGHT=' + HEIGHT );
renderer.setSize( WIDTH, HEIGHT );
aspectRatio = WIDTH / HEIGHT;
camera.aspect = aspectRatio;
camera.updateProjectionMatrix();
render();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
render();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html>
If you place a spot light in your scene, you have to ensure that no shadow casting meshes block the emissions of the lights. This happens in your app since the light is place "inside" the lamp mesh. Update code:
var WIDTH, HEIGHT, aspectRatio;
var renderer;
var scene, camera;
var controls;
var mesh, spotLightHelper;
init();
animate();
function init() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
aspectRatio = WIDTH / HEIGHT;
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor(0x000000);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 1000);
camera.position.set(0, 40, 80);
camera.lookAt(scene.position);
var light = new THREE.AmbientLight(0xF5F5F3, 0.4); //ambiens fény
scene.add(light);
var floorgeometry = new THREE.PlaneGeometry(150, 150, 1, 1);
var floormaterial = new THREE.MeshPhongMaterial({
color: 0xFFFFFF,
wireframe: false
});
var floor = new THREE.Mesh(floorgeometry, floormaterial);
//floor.material.side = THREE.DoubleSide;
floor.rotation.x = -Math.PI * 0.5;
floor.position.z = 0;
floor.position.x = 0;
floor.position.y = -42.5;
floor.receiveShadow = true;
scene.add(floor);
var vertgeometry = new THREE.BoxGeometry(20, 45, 20);
var vertmaterial = new THREE.MeshPhongMaterial({
color: 0xD5D8DC,
wireframe: false
});
var vert = new THREE.Mesh(vertgeometry, vertmaterial);
vert.castShadow = true;
vert.receiveShadow = true;
vert.rotation.z = 0;
vert.rotation.x = 0;
vert.rotation.y = 0;
vert.position.z = 0;
vert.position.x = 0;
vert.position.y = -20;
var horgeometry = new THREE.BoxGeometry(20, 40, 20);
var hormaterial = new THREE.MeshPhongMaterial({
color: 0xD5D8DC,
wireframe: false
});
var hor = new THREE.Mesh(horgeometry, hormaterial);
hor.castShadow = true;
hor.position.z = 0;
hor.position.y = -32.5;
hor.position.x = 30;
hor.rotation.z = 1.57;
hor.rotation.x = 0;
hor.rotation.y = 0;
scene.add(hor);
var roofgeometry = new THREE.ConeGeometry(14.142, 40, 4);
var roofmaterial = new THREE.MeshPhongMaterial({
color: 0xF98E76,
wireframe: false
});
var roof = new THREE.Mesh(roofgeometry, roofmaterial);
roof.castShadow = true;
roof.position.z = 0;
roof.position.y = 22.5;
roof.position.x = 0;
roof.rotation.z = 0;
roof.rotation.x = 0;
roof.rotation.y = 0.775;
scene.add(roof);
scene.add(vert);
var lampgeometry = new THREE.BoxGeometry(2, 25, 2);
var lampmaterial = new THREE.MeshPhongMaterial({
color: 0x566573,
wireframe: false
});
var lamp = new THREE.Mesh(lampgeometry, lampmaterial);
lamp.rotation.z = 0;
lamp.rotation.y = 0;
lamp.position.z = 0;
lamp.position.x = -60;
lamp.position.y = -30;
var spotgeometry = new THREE.BoxGeometry(3, 3, 3);
var spotmaterial = new THREE.MeshPhongMaterial({
color: 0xF6F50B,
wireframe: false
});
var spot = new THREE.Mesh(spotgeometry, spotmaterial);
spot.position.z = 0;
spot.position.y = -17.5;
spot.position.x = -60;
scene.add(lamp);
scene.add(spot);
var geometry = new THREE.SphereGeometry(200, 20, 20);
var appearence = new THREE.MeshPhongMaterial({
color: 0xa2a7a9,
wireframe: false
});
var objgeometry = new THREE.BoxGeometry(8, 12, 8);
var objmaterial = new THREE.MeshPhongMaterial({
color: 0x1C1C03,
wireframe: false
});
var obj = new THREE.Mesh(objgeometry, objmaterial);
obj.castShadow = true;
obj.receiveShadow = true;
obj.position.z = 0;
obj.position.x = -40;
obj.position.y = -36.5;
scene.add(obj);
var sLight = new THREE.SpotLight(0xF6F50B, 1); // spotfény segédgeometriával
sLight.position.set(-60, -17.5, 0);
sLight.castShadow = true;
sLight.distance = 100;
sLight.target = obj;
sLight.angle = Math.PI * 0.2;
sLight.shadow.camera.near = 0.1;
sLight.shadow.camera.far = 100;
sLight.shadow.mapSize.width = 2048;
sLight.shadow.mapSize.height = 2048;
scene.add(sLight);
spotLightHelper = new THREE.SpotLightHelper(sLight);
scene.add(spotLightHelper);
var cameraHelper = new THREE.CameraHelper(sLight.shadow.camera);
scene.add(cameraHelper)
window.addEventListener('resize', handleWindowResize, false);
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
aspectRatio = WIDTH / HEIGHT;
camera.aspect = aspectRatio;
camera.updateProjectionMatrix();
render();
}
function animate() {
requestAnimationFrame(animate);
spotLightHelper.update();
render();
}
function render() {
renderer.render(scene, camera);
}
body {
margin: 0;
}
canvas {
display: block;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.121.1/build/three.js"></script>
BTW: When using SpotLightHelper, makes sure to update this helper in the animation loop. Besides, CameraHelper is useful for debugging the shadow frustum.

Make the plane draggable in ThreeJS

How to make the plane draggable in X , Y direction. Here I'm trying to work on box clipping where I draw a plane on X and Y direction. But I have no idea how to make it draggable to the particular direction. Can anyone help me put with the issue.
I want to make the plane to be draggable only in the own direction on mouse event
import * as THREE from '../build/three.module.js';
import Stats from './jsm/libs/stats.module.js';
import { GUI } from './jsm/libs/dat.gui.module.js';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
import { DragControls } from './jsm/controls/DragControls.js';
var camera, scene, renderer, startTime, object, stats;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.0001, 100000);
camera.position.set(0, 1.3, 8);
scene = new THREE.Scene();
// Lights
scene.add(new THREE.AmbientLight(0x505050));
scene.background = new THREE.Color('white')
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.angle = Math.PI / 5;
spotLight.penumbra = 0.2;
spotLight.position.set(2, 3, 3);
spotLight.castShadow = true;
spotLight.shadow.camera.near = 3;
spotLight.shadow.camera.far = 10;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
scene.add(spotLight);
var dirLight = new THREE.DirectionalLight(0x55505a, 1);
dirLight.position.set(0, 3, 0);
dirLight.castShadow = true;
dirLight.shadow.camera.near = 1;
dirLight.shadow.camera.far = 10;
dirLight.shadow.camera.right = 1;
dirLight.shadow.camera.left = - 1;
dirLight.shadow.camera.top = 1;
dirLight.shadow.camera.bottom = - 1;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
scene.add(dirLight);
// ***** Clipping planes: *****
var localPlane = new THREE.Plane(new THREE.Vector3(0, - 1, 0), 1.5);
var helper1 = new THREE.PlaneHelper(localPlane, 3, 0xffff00);
scene.add(helper1);
var globalPlane = new THREE.Plane(new THREE.Vector3(- 1, 0, 0), 1);
var helper = new THREE.PlaneHelper(globalPlane, 3, 0xffff00);
scene.add(helper); // Geometry
var material = new THREE.MeshPhongMaterial({
color: 0x80ee10,
shininess: 100,
side: THREE.DoubleSide,
// ***** Clipping setup (material): *****
clippingPlanes: [localPlane],
clipShadows: true
});
var geometry = new THREE.TorusKnotBufferGeometry(0.4, 0.08, 95, 20);
object = new THREE.Mesh(geometry, material);
object.castShadow = true;
scene.add(object);
var ground = new THREE.Mesh(
new THREE.PlaneBufferGeometry(9, 9, 1, 1),
new THREE.MeshPhongMaterial({ color: 0xa0adaf, shininess: 150 })
);
ground.rotation.x = - Math.PI / 2; // rotates X/Y to X/Z
ground.receiveShadow = true;
// scene.add( ground );
// Stats
stats = new Stats();
document.body.appendChild(stats.dom);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.shadowMap.enabled = true;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
window.addEventListener('resize', onWindowResize, false);
document.body.appendChild(renderer.domElement);
// ***** Clipping setup (renderer): *****
var globalPlanes = [globalPlane],
Empty = Object.freeze([]);
renderer.clippingPlanes = Empty; // GUI sets it to globalPlanes
renderer.localClippingEnabled = true;
renderer.clippingPlanes = globalPlanes;
// Controls
var controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1, 0);
controls.update();
// controls1 = new DragControls([...globalPlane], camera, renderer.domElement);
// controls1.addEventListener('drag', render);
// GUI
var gui = new GUI(),
folderLocal = gui.addFolder('Local Clipping'),
propsLocal = {
get 'Enabled'() {
return renderer.localClippingEnabled;
},
set 'Enabled'(v) {
renderer.localClippingEnabled = v;
},
get 'Shadows'() {
return material.clipShadows;
},
set 'Shadows'(v) {
material.clipShadows = v;
},
get 'Plane'() {
return localPlane.constant;
},
set 'Plane'(v) {
localPlane.constant = v;
}
},
folderGlobal = gui.addFolder('Global Clipping'),
propsGlobal = {
get 'Enabled'() {
console.log('hitting 1')
return renderer.clippingPlanes !== Empty;
console.log(renderer.clippingPlanes);
},
set 'Enabled'(v) {
console.log('hitting 2')
renderer.clippingPlanes = v ? globalPlanes : Empty;
console.log(renderer.clippingPlanes);
},
get 'Plane'() {
return globalPlane.constant;
},
set 'Plane'(v) {
globalPlane.constant = v;
}
};
folderLocal.add(propsLocal, 'Enabled');
folderLocal.add(propsLocal, 'Shadows');
folderLocal.add(propsLocal, 'Plane', 0.3, 1.25);
folderGlobal.add(propsGlobal, 'Enabled');
folderGlobal.add(propsGlobal, 'Plane', - 0.4, 3);
// Start
startTime = Date.now();
document.addEventListener('click', onClick, false);
}
function onClick(event) {
event.preventDefault();
if (enableSelection === true) {
var draggableObjects = controls.getObjects();
draggableObjects.length = 0;
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersections = raycaster.intersectObjects(objects, true);
if (intersections.length > 0) {
var object = intersections[0].object;
if (group.children.includes(object) === true) {
object.material.emissive.set(0x000000);
scene.attach(object);
} else {
object.material.emissive.set(0xaaaaaa);
group.attach(object);
}
controls.transformGroup = true;
draggableObjects.push(group);
}
if (group.children.length === 0) {
controls.transformGroup = false;
draggableObjects.push(...objects);
}
}
render();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
// var currentTime = Date.now();
// var time = ( currentTime - startTime ) / 1000;
requestAnimationFrame(animate);
// object.position.y = 0.8;
// object.rotation.x = time * 0.5;
// object.rotation.y = time * 0.2;
// object.scale.setScalar( Math.cos( time ) * 0.125 + 0.875 );
stats.begin();
renderer.render(scene, camera);
stats.end();
}
In order to move things in three.js you use TransformControls. Check out https://threejs.org/docs/#examples/en/controls/TransformControls for its documentation and https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_transform.html for implementation example.
Here you can set the mode to "translate" and scale to "XY" to restrict the movement in X and Y direction only.
controls.axis ="XY";

Three js enabling shadow render slow

I am loading a building model to the scene using GLTFLoader and apply some texture, also Adding two PointLight source with shadow enabled. I am using self shadow for the building, that is the building itself should create shadow from light source.
But when I load the page, I am having some performance issue withe page, the frame rate is too slow on status and entire system behave hang.
But if disable the shadow everything work as expected. Is this expected or I can improve it on coding.
Here is the working fiddle
http://jsfiddle.net/n9eg3kox/
var camera, scene, renderer, stats;
var mesh;
var controls;
var BuildingObj;
var OutFloor;
var enableShadow = true; // if I make it false the code work fine
var pointLight2, pointLight3;
function init() {
var webglEl = document.getElementById('webgl');
if (!Detector.webgl) {
Detector.addGetWebGLMessage(webglEl);
alert("WebGL no Support");
return;
}
THREE.ImageUtils.crossOrigin = '';
renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setPixelRatio(window.devicePixelRatio * 1.5);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.physicallyCorrectLights = true;
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMap.enabled = enableShadow;
renderer.toneMapping = THREE.ReinhardToneMapping;
webglEl.appendChild(renderer.domElement);
renderer.setClearColor(0x555555, 1);
var width = window.innerWidth, height = window.innerHeight;
camera = new THREE.PerspectiveCamera(45, width / height, 0.01, 2000);
camera.position.x = 0;
camera.position.y = 4;
camera.position.z = 30;
scene = new THREE.Scene();
var axesHelper = new THREE.AxesHelper(100);
scene.add(axesHelper);
var intensity = 5;
var distance = 40;
var decay = 1.0;
pointLight2 = new THREE.PointLight(0xFFFFFF, intensity);
pointLight2.add(new THREE.Mesh(new THREE.SphereBufferGeometry(3, 16, 16), new THREE.MeshPhongMaterial({ color: 0xfffdfb, emissive: 0xfffdfb, emissiveIntensity: 100 })));
pointLight2.position.set(-60, 80, 40);
pointLight2.castShadow = enableShadow;
pointLight2.visible = true;
pointLight2.shadow.mapSize.width = 1024;
pointLight2.shadow.mapSize.height = 1024;
scene.add(pointLight2);
pointLight3 = new THREE.PointLight(0xFFFFFF, intensity);
pointLight3.add(new THREE.Mesh(new THREE.SphereBufferGeometry(3, 16, 16), new THREE.MeshPhongMaterial({ color: 0xfffdfb, emissive: 0xfffdfb, emissiveIntensity: 100 })));
pointLight3.position.set(60, 80, 40);
pointLight3.castShadow = enableShadow;
pointLight3.shadow.mapSize.width = 1024;
pointLight3.shadow.mapSize.height = 1024;
pointLight3.visible = true;
scene.add(pointLight3);
//var light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 21 );
//scene.add( light );
controls = new THREE.OrbitControls(camera, webglEl);
stats = new Stats();
webglEl.appendChild(stats.dom);
loadObject();
animate();
}
function animate() {
controls.update();
stats.update();
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function loadObject() {
var loader = new THREE.GLTFLoader();
loader.load(
//'./Model/GLTF/test.glb',
'./test/test.glb',
function (gltf) {
gltf.scene.traverse(function (node) {
if (node.isGroup) {
if (node.name === "Building") {
BuildingObj = node;
} else if (node.name === "Cube") {
OutFloor = node;
}
}
});
scene.add(OutFloor);
scene.add(BuildingObj);
applyMaterialToObject();
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (error) {
console.log('An error happened---' + error);
}
);
}
function applyMaterialToObject(object) {
for (var i = 0; i < BuildingObj.children.length; i++) {
var obj = BuildingObj.children[i];
var material = new THREE.MeshStandardMaterial({ roughness: 0.8, metalness: 0.3, bumpScale: - 0.05, color: 0xffffff, });
loadTexturesToMaterial(BuildingObj.children[i], material, "./test/brick.jpg", "./test/brick_b.jpg", "./test/brick_r.jpg", 25, 70, Math.PI / 2);
}
for (var i = 0; i < OutFloor.children.length; i++) {
var obj = OutFloor.children[i];
var material = new THREE.MeshStandardMaterial({ roughness: 0.5, metalness: 0.8, bumpScale: - 0.05, color: 0xffffff });
loadTexturesToMaterial(obj, material, "./test/tile2.jpg", "./test/tile2_b.jpg", "./test/tile2_r.jpg", 35, 100, Math.PI / 2);
}
}
function loadTexturesToMaterial(obj, material, map_img, bumpMap_img, roughnessMap_img, v_count, h_count, rotation) {
obj.receiveShadow = enableShadow;
obj.castShadow = enableShadow;
obj.material = material;
obj.material.side = THREE.DoubleSide;
var textureLoader = new THREE.TextureLoader();
textureLoader.load(map_img, function (map) {
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.rotation = rotation;
map.repeat.set(v_count, h_count);
obj.material.map = map;
obj.material.needsUpdate = true;
});
textureLoader.load(bumpMap_img, function (map) {
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.rotation = rotation;
map.repeat.set(v_count, h_count);
obj.material.bumpMap = map;
obj.material.needsUpdate = true;
});
textureLoader.load(roughnessMap_img, function (map) {
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.rotation = rotation;
map.repeat.set(v_count, h_count);
obj.material.roughnessMap = map;
obj.material.needsUpdate = true;
});
}
Note: I have created the model using blender.
Edit: Texture and model link
https://github.com/SourceCodeZone/3D

Three.js Restrict the mouse movement to Scene only

I am working on the cube example from three.js (webgl_interactive_cubes_gpu.html). I realized that events goes to the entire html page. I mean i can rotate, zoom in or zoom out, even if the mouse pointer is not inside the scene..
I google a little bit and found some answers (Allow mouse control of three.js scene only when mouse is over canvas) but they do not work for me..Below is my code...
var container, stats;
var camera, controls, scene, renderer;
var pickingData = [], pickingTexture, pickingScene;
var objects = [];
var highlightBox;
var mouse = new THREE.Vector2();
var offset = new THREE.Vector3( 10, 10, 10 );
init();
animate();
function init() {
container = document.getElementById( "container" );
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
//camera.translateZ( -500 );
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 4;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
pickingScene = new THREE.Scene();
pickingTexture = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
pickingTexture.minFilter = THREE.LinearFilter;
pickingTexture.generateMipmaps = false;
scene.add( new THREE.AmbientLight( 0x555555 ));
var light = new THREE.SpotLight( 0xffffff, 1.5 );
light.position.set( 0, 500, 2000 );
scene.add( light );
var geometry = new THREE.Geometry(),
pickingGeometry = new THREE.Geometry(),
pickingMaterial = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } ),
defaultMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors} );
function applyVertexColors( g, c ) {
g.faces.forEach( function( f ) {
var n = ( f instanceof THREE.Face3 ) ? 3 : 4;
for( var j = 0; j < n; j ++ ) {
f.vertexColors[ j ] = c;
}
} );
}
var geom = new THREE.BoxGeometry(0.005, 0.005, 0.005 );
var color = new THREE.Color();
var matrix = new THREE.Matrix4();
var quaternion = new THREE.Quaternion();
var coord="219_163_189;130_173_179;161_113_231;
var splitCoord=coord.split(";");
var coordColr="0_255_255;255_255_0;0_0_255;0_255_0;255_255_0;
var splitCoordColor=coordColr.split(";");
for ( var i = 0; i < splitCoord.length; i++ ) {
var position = new THREE.Vector3();
var xyz=splitCoord[i].split("_");
var col=splitCoordColor[i].split("_");
position.x = xyz[0];
position.y = xyz[1];
position.z = xyz[2];
var rotation = new THREE.Euler();
rotation.x = 0
rotation.y = 0;
rotation.z = 0;
var scale = new THREE.Vector3();
scale.x = 200 + 100;
scale.y = 200 + 100;
scale.z = 200 + 100;
quaternion.setFromEuler(rotation, false );
matrix.compose( position, quaternion, scale);
col[0]=col[0]/255;
col[1]=col[1]/255;
col[2]=col[2]/255;
applyVertexColors(geom, color.setRGB(col[0], col[1], col[2]));
geometry.merge(geom, matrix);
// give the geom's vertices a color corresponding to the "id"
applyVertexColors( geom, color.setHex( i ) );
pickingGeometry.merge( geom, matrix );
pickingData[ i ] = {
position: position,
rotation: rotation,
scale: scale
};
}
var drawnObject = new THREE.Mesh( geometry, defaultMaterial );
scene.add(drawnObject);
pickingScene.add( new THREE.Mesh( pickingGeometry, pickingMaterial ) );
highlightBox = new THREE.Mesh(
new THREE.BoxGeometry( 0.01, 0.01, 0.01 ),
new THREE.MeshLambertMaterial( { color: 0xffff00 }
) );
scene.add( highlightBox );
renderer = new THREE.WebGLRenderer( );
//renderer.setClearColor( 0xffffff );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(800, 800);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
//renderer.domElement.addEventListener('mousemove', onMouseMove );
}
function onMouseMove( e ) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function pick() {
//render the picking scene off-screen
renderer.render( pickingScene, camera, pickingTexture );
//create buffer for reading single pixel
var pixelBuffer = new Uint8Array( 4 );
//read the pixel under the mouse from the texture
renderer.readRenderTargetPixels(pickingTexture, mouse.x, pickingTexture.height - mouse.y, 1, 1, pixelBuffer);
//interpret the pixel as an ID
var id = ( pixelBuffer[0] << 16 ) | ( pixelBuffer[1] << 8 ) | ( pixelBuffer[2] );
var data = pickingData[ id ];
if (data) {
//move our highlightBox so that it surrounds the picked object
if ( data.position && data.rotation && data.scale ){
highlightBox.position.copy( data.position );
highlightBox.rotation.copy( data.rotation );
highlightBox.scale.copy( data.scale ).add( offset );
highlightBox.visible = true;
}
} else {
highlightBox.visible = false;
}
}
function render() {
controls.update();
pick();
renderer.render( scene, camera );
}
any help is greatly appreciated..
Thanks
You can pass in the canvas as an argument to the TrackballsControls constructor.
var controls = new THREE.TrackballControls(camera, renderer.domElement);
That should solve the problem.
EDIT: included a working example,
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, 400 / 300, 1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 300);
document.body.appendChild(renderer.domElement);
var controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 4;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var render = function() {
requestAnimationFrame(render);
controls.update();
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
could not get your code to run at all so..

THREE.JS Update 64 - SpriteMaterial - definition changed

I have a current application that runs on Three.js V60. I want to migrate it to V64 but I have issue with one of functionnality which is a mouse tooltip. It follows the example from http://stemkoski.github.io/Three.js/Mouse-Tooltip.html.
In V64, we don't have useScreenCoordinates, sizeAttenuation and alignment properties, so i have strange behaviour with the tooltip when I removed this parameters. The behaviour I have is that mousetooltip is fixed on scene. Can someone help me ?
Below is a testing code I have made :
<pre><code>
// standard global variables
var container, scene, camera, renderer, controls, stats;
// custom global variables
var cube;
var projector, mouse = { x: 0, y: 0 }, INTERSECTED;
var ballSprite;
init();
animate();
// FUNCTIONS
function init()
{
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,150,400);
camera.lookAt(scene.position);
// RENDERER
renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setClearColor(0xFFFFFF, 1.0);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
// LIGHT
var light = new THREE.PointLight(0xffffff);
light.position.set(0,250,0);
scene.add(light);
////////////
// CUSTOM //
////////////
var cubeGeometry = new THREE.CubeGeometry( 50, 50, 50 );
var cubeMaterial = new THREE.MeshBasicMaterial( { color: 0x000088 } );
cube = new THREE.Mesh( cubeGeometry, cubeMaterial );
cube.position.set(0,26,0);
scene.add(cube);
// initialize object to perform world/screen calculations
projector = new THREE.Projector();
// when the mouse moves, call the given function
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
var ballTexture = THREE.ImageUtils.loadTexture( 'http://stemkoski.github.io/Three.js/images/redball.png' );
var ballMaterial = new THREE.SpriteMaterial( { map: ballTexture} );
ballSprite = new THREE.Sprite( new THREE.SpriteMaterial(ballMaterial) );
ballSprite.scale.set( 32, 32, 1.0 );
ballSprite.position.set( 50, 50, 0 );
scene.add( ballSprite );
}
function onDocumentMouseMove( event )
{
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
// event.preventDefault();
// update sprite position
ballSprite.position.set( event.clientX, event.clientY, 0 );
}
function animate()
{
requestAnimationFrame( animate );
render();
update();
}
function update()
{
}
function render()
{
renderer.clear();
renderer.render( scene, camera );
}
</code></pre>
Update :
I have looked at the webgl_sprites.html example and have adapted my using ortho cam. It works partially : I have now the tooltip that is display orthogonally but it doesn't follow the mouse (while it works with previous V60).
While the example uses a picture, I use a canvas2D to draw some text and lines, convert it as a texture and apply it to a spriteMaterial and create a mesh from it.
When I drag the mouse, the mesh coordonates changed but on the screen, it stays static.
Can someone helps me?
Here is the code :
<pre><code>
THREE.MouseTooltip = function (o) {
Object.call(this);
var defaults = { // default options
ResourcesPath: "", // Location of ressoruce file
ImagesPath: "",
Scene: null,
Container: null
};
this.options = $.extend(defaults, o); // merge defaults and options object
if (this.options.Scene == null || this.options.Container == null) {
throw "Error : MouseTooltip scene and container inputs must be specified";
return;
}
this.canvas = null;
this.context = null;
this.texture = null;
this.material = null;
this.mesh = null;
this.width = 0
this.updateDisplay = false;
this.init(this.options.Scene);
};
THREE.MouseTooltip.prototype = Object.create(Object.prototype);
THREE.MouseTooltip.prototype.init = function (scene) {
this.canvas = document.createElement('canvas');
this.canvas.width = this.options.Container.offsetWidth;
this.canvas.height = this.options.Container.offsetHeight;
this.context = this.canvas.getContext('2d');
this.context.font = "20px Arial";
this.context.fillStyle = "rgba(0,0,0,0.95)";
this.context.fillText('', 0, 20);
this.width = 20;
this.texture = new THREE.Texture(this.canvas);
this.texture.needsUpdate = true;
this.material = new THREE.SpriteMaterial({ map: this.texture/*, useScreenCoordinates: true, alignment: THREE.SpriteAlignment.topLeft */});
this.mesh = new THREE.Sprite(this.material);
this.mesh.name = "tooltip";
this.mesh.scale.set(this.canvas.width/1.5, this.canvas.height/1.5, 1.0);
this.mesh.material.depthTest = false;
this.mesh.material.transparent = false;
this.mesh.matrixAutoUpdate = false;
this.mesh.visible = false;
this.mesh.userData = "";
scene.add(this.mesh);
};
THREE.MouseTooltip.prototype.setContent = function (message) {
if (message == this.mesh.userData) {
return;
}
var metrics = this.context.measureText(message);
var lineHeight = 20;
this.width = metrics.width + 8;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.fillStyle = "rgba(0,0,0,1)"; // black border
this.context.beginPath();
this.context.moveTo(0, (lineHeight + 8) / 2);
this.context.lineTo(10, (lineHeight + 8) / 2 + 10);
this.context.lineTo(10, (lineHeight + 8) / 2 - 10);
this.context.lineTo(0, (lineHeight + 8) / 2);
this.context.fill();
this.context.closePath();
this.context.fillRect(12, 0, this.width, lineHeight + 8);
this.context.fillStyle = "rgba(255,255,255,1)"; // white filler
this.context.fillRect(14, 2, this.width - 4, lineHeight + 4);
this.context.fillStyle = "rgba(0,0,0,1)"; // text color
this.context.fillText(message, 16, lineHeight);
this.mesh.userData = message;
this.texture.needsUpdate = true;
};
THREE.MouseTooltip.prototype.isVisible = function (b) {
return this.mesh.visible;
};
THREE.MouseTooltip.prototype.hide = function (b) {
this.mesh.visible = false;
};
THREE.MouseTooltip.prototype.show = function (b) {
this.mesh.visible = true;
};
THREE.MouseTooltip.prototype.clear = function () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.texture.needsUpdate = true;
};
THREE.MouseTooltip.prototype.move = function (mouseX, mouseY) {
this.mesh.position.x = (mouseX - this.options.Container.offsetLeft+16) - this.canvas.width;
this.mesh.position.y = (mouseY - this.options.Container.offsetTop) - this.canvas.height;
this.mesh.position.z = 1;
};
</pre></code>
Regarding to the example in http://threejs.org/examples/webgl_sprites.html your actual positions would be
this.mesh.position.x = -(SCREEN_WIDTH / 2) + mouseX;
this.mesh.poyition.y = (SCREEN_WIDTH / 2) - mouseY;

Resources