I try to make a very simple program with a clickable 3d object in Threejs. My code is based on
https://threejs.org/examples/#webgl_interactive_cubes
It works when I click on the object (although the resulting array contains the object twice, I assume because the ray intersects it when entering it and when exiting it).
But when I click in an area just surrounding the object raycaster.intersectObjects returns the object although it should return an empty array.
What am I doing wrong? Why is the object also intersected when I click next to it and not on it? And is an object always included twice in the intersect array because of the ray entering and exiting it?
A working example of the code is here:
https://codepen.io/ettir_deul/pen/PoGLNZx
(open the console to see the intersect array after you clicked on the screen)
And the code looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="libs/three.min.js.r116.1"></script>
</head>
<body>
<div id="threejsCanvas"></div>
<script>
let scene, center, camera, renderer, raycaster;
const mouse = new THREE.Vector2();
const threejsCanvas = document.getElementById("threejsCanvas");
init3d();
function init3d(){
scene = new THREE.Scene();
scene.background = new THREE.Color(0xAAAAEE);
center = new THREE.Vector3(0, 0, 0);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(center.x, center.y, center.z+1);
camera.lookAt(center);
buttonMesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 0.2), new THREE.MeshBasicMaterial({map : null, color: 0x008844, wireframe: false, side: THREE.DoubleSide}));
buttonMesh.position.set(center.x, center.y, center.z);
scene.add(buttonMesh);
buttonMesh.objId = "buttonMesh";
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
threejsCanvas.appendChild(renderer.domElement);
renderer.render(scene, camera);
raycaster = new THREE.Raycaster();
document.addEventListener('click', onMouseClick, false);
}
function onMouseClick(event){
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene.children);
console.log(intersects);
}
</script>
</body>
</html>
the reason for getting the object twice is the
side: THREE.DoubleSide
in the material. You can use THREE.FrontSide
The reason for picking the object when the mouse is close is the canvas and window dimensions not being equal.
If you add :
body{
padding: 0;
margin: 0;
}
in the CSS it is fixed.
Here is a codepen that works.
Two results - is OK. You got 2 faces of mesh. Each one intersects ray. Check result intersection properties: face, faceIndex, point.
Raycaster is not precise and pretty slow. You can use its 'params' to change precision (see https://threejs.org/docs/#api/en/core/Raycaster). I suggest using GPUPicker. It is precise and super fast. Check here:
https://github.com/brianxu/GPUPicker
Edit: Yes you can change material to avoid 2 intersections. But it is often it is not acceptable for surfaces.
Edit: Yes precision settings affects only points and line picking. But GPUPicker can pick exact rendering result of points (shader effects, symbols with transparency). But standard raycaster - can't.
Related
I'm a beginner to three.js.I'm trying to build something similar to this https://virtualshowroom.nissan.in/car-selected.html?selectedCar=ext360_deep_blue_pearl. I built everything using three.js, but I'm not able to figure out how to create a hotspot(like the red dot in the above link) and show pop up when you click on it. below is my project code, let me know if anything else is required.
<html>
<head>
<title>My first three.js app</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<h1></h1>
<script src="./three.js"></script>
<script type="module">
import { GLTFLoader } from 'https://threejs.org/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from 'https://threejs.org/examples/jsm/controls/OrbitControls.js';
var renderer,scene,camera;
scene = new THREE.Scene();
scene.background = new THREE.Color(0xfff6e6)
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var loader = new GLTFLoader();
var hlight = new THREE.AmbientLight(0x404040, 100)
scene.add(hlight)
var directionalLight = new THREE.DirectionalLight(0xffffff, 100)
directionalLight.position.set(0,1,0)
directionalLight.castShadow = true
scene.add(directionalLight)
var light = new THREE.PointLight(0xffffff, 10)
light.position.set(0, 300, 500)
scene.add(light)
var light2 = new THREE.PointLight(0xffffff, 10)
light2.position.set(500, 100, 0)
scene.add(light2)
var light3 = new THREE.PointLight(0xffffff, 10)
light3.position.set(0, 100, -500)
scene.add(light3)
var light4 = new THREE.PointLight(0xffffff, 10)
light4.position.set(-5000, 300, 0)
scene.add(light4)
var controls = new OrbitControls(camera, renderer.domElement);
document.body.appendChild(renderer.domElement)
var loader = new GLTFLoader();
loader.load( './scene.gltf', function ( gltf )
{
scene.add( gltf.scene );
}, undefined, function ( error ) { console.error( error ); } );
// load a image resource
camera.position.z = 5;
var animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>
Those “hotspots” as you call them are Annotations where the annotation content is basically pure HTML.
The tutorial in the link is probably the best step-by-step readiness you can follow to learn how to do it in your scene.
I can give a walkthrough on the steps required to get the desired effect since I have done it a few times myself.
define a 3d point in your scene where the hotspot should be. You can optionally nest this in a an other Object3D to make sure it scales, moves and rotates with the model / parent.
Add a plane to this point load a image texture to this plane. and there you have your visible hotspot
update the hotspots to make sure they are always looking at the camera by using the lookAt function.
when the user clicks the screen cast a raycast against all the hotspots you have in your scene. Easiest way to do this is by storing all your hotspots in an array.
When the raycast hits a hotspot get the location either of the hitpoint or the hotspots location. Transform that to screen coordinates. Search on stackoverflow how to do this. I am sure there is a post about this.
Final step display your html on the correct location you obtained from the previous step.
The advantage of this method is that the hotspot will integrate nicely with the model in your scene. Since html based hotspots will always be on top of the scene.
That is about all that is to it. Let me know if you need any further clarification!
I'm trying out Three.js, I followed a tutorial step-by-step. In the code editor I'm using( Visual Studio Code 2019) everything seems normal, but when I test it, nothing appears on the page.
the editor I'm using, used the desktop as the place to locate my code, since it is a .html file I could run it. When I did that, the only thing that appeared was the navbar I programmed, nothing else
This is the entire three.js code:
<script src="three.js-dev/build/three.min.js"> </script>
<script>
var scene = new THREE.scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight);
var renderer = new THREE.WebGLRenderer({antialias = true});
renderer.setSize( window.innerWidth, window.innerHeight);
$('body').append( renderer.domElement);
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial ( { color = 0xff0000 });
var cube = new THREE.Mesh( geometry, material) ;
scene.add( cube );
cube.position.z = -5;
var animate = function () {
cube.rotation.x += 0.01;
renderer.render(scene, camera);
requestAnimationFrame( animate );
};
animate();
and this the code before it:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script
src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4="
crossorigin="anonymous"></script>
</head>
<body>
<div id="navbar"><span>Three.js Tut</span></div>
I expected a red cube rotating, but nothing appeared. ¿Is there something I'm doing wrong?
You have a few errors in your code:
THREE.scene should be THREE.Scene
{antialias = true} should be {antialias: true}
{ color = 0xff0000 } should be { color: 0xff0000 }
Live demo with your code: https://jsfiddle.net/so736vxj/
BTW: If you are using VSCode, I'm a bit irritated that no errors are highlighted. Especially the last two syntax errors should be reported since it is no valid JavaScript.
three.js R105
I imported a model and found that shadow only show in a small area(green area in the picture). What can I do to let all objects show their shadow.
Here is my code.
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
light.castShadow = true;
light.shadow.camera.near = 0.01; // same as the camera
light.shadow.camera.far = 1000; // same as the camera
light.shadow.camera.fov = 50; // same as the camera
light.shadow.mapSize.width = 2048;
light.shadow.mapSize.height = 2048;
scene.add( light );
Thanks!!
EDIT:
I add gui to change light.shadow.camera.top / light.shadow.camera.bottom / light.shadow.camera.left / light.shadow.camera.right, but nothing happens.
var gui = new dat.GUI();
gui.add( light.shadow.camera, 'top' ).min( 1 ).max( 100000 ).onChange( function ( value ) {
light.shadow.camera.bottom = -value;
light.shadow.camera.left = value;
light.shadow.camera.right = -value;
});
That's happening because directional lights use an OrthographicCamera to draw a shadowmap to cast shadows. If there are objects outside the view of this camera, it won't be able to calculate their shadows, and will have the effect you're seeing outside the green box. If you want to extend the area that this camera covers, you can modify the .left .right .top .bottom properties of this shadow camera to cover your entire scene. I'm using a box of 100 units in the example below;
var side = 100;
light.shadow.camera.top = side;
light.shadow.camera.bottom = -side;
light.shadow.camera.left = side;
light.shadow.camera.right = -side;
... but you can change the dimensions to whatever you need. Keep in mind that .fov does nothing in your example code because ortho cameras don't use the field-of-view property.
All right, it would be great if you could show me a live example of your code as I have fixed this before for a project in boxelizer.com
The issue can be fixed by changing the light.shadow.camera.left, right, bottom and top properties as suggested before, however we might not be able to see what the effective area of our shadow might be and hence we might be really close to fixing it but not at all. My suggestion is using a helper momentarily just to see the effective shadow area of your light with:
var shadowHelper = new THREE.CameraHelper( light.shadow.camera );
scene.add( shadowHelper );
You are also welcome to see all the code I used in the link I referenced to.
Here's a function I use to set the shadowMap dimensions and coverage area:
//sz is the size in world units that the shadow should cover. (area)
// mapSize is the width,height of the texture to be used for shadowmap (resolution)
var setShadowSize=(light1, sz, mapSz)=>{
light1.shadow.camera.left = sz;
light1.shadow.camera.bottom = sz;
light1.shadow.camera.right = -sz;
light1.shadow.camera.top = -sz;
if(mapSz){
light1.shadow.mapSize.set(mapSz,mapSz)
}
}
setShadowSize(myLight,15.0,1024);
I try to include, into a main window (representing sphere), a subwindow representing a zoomed view of this sphere.
For this moment, I can display a right-bottom subwindow containing the three axes of main scene. These axes are rotating the same way I make rotate the sphere with mouse.
Now, I would like to display, into this subwindow, a zoomed view of the sphere instead of having the subwindow with 3D axes.
From Can multiple WebGLRenderers render the same scene?, we can't use a second time the THREE.WebGLRenderer() for the subwindow.
From How to render the same scene with different cameras in three.js? ,a solution may be to use setViewport function but I don't know if I can display the zoom of sphere in this subwindow.
I tried to do in render() function :
function render() {
controls.update();
requestAnimationFrame(render);
zoomCamera.position.copy(camera.position);
zoomCamera.position.sub(controls.target);
zoomCamera.position.setLength(500);
zoomCamera.lookAt(zoomScene.position );
// Add Viewport for zoomScene
renderer.setViewport(0, 0, width, height);
renderer.render(scene, camera);
zoomRenderer.setViewport(0, 0, 200 , 200);
zoomRenderer.render(zoomScene, zoomCamera);
}
From your advices, is it possible technically to have 2 object in the same time (one on main window and the other on right-bottom subwindow) ?
Can I solve my issue with setViewport ?
And if someone could give documentation on setViewport, this would be great.
Thanks in advance.
UPDATE :
#WestLangley , thanks, I did your modifications (with a unique scene) but the content of inset does not appear.
I think that issue comes from the fact that I don't know how to make the link between the container of inset and the drawing of this inset.
For example, into the link above, I tried :
...
// Add sphere to main scene
scene.add(sphere);
camera.position.z = 10;
var controls = new THREE.TrackballControls(camera);
// If I include these two lines below, nothing appears
// zoomContainer = document.getElementById('zoomContainer');
// zoomContainer.appendChild(renderer.domElement);
// Zoom camera
zoomCamera = new THREE.PerspectiveCamera(50, zoomWidth, zoomHeight, 1, 1000);
zoomCamera.position.z = 20;
zoomCamera.up = camera.up; // important!
// Call rendering function
render();
function render() {
controls.update();
requestAnimationFrame(render);
zoomCamera.position.copy(camera.position);
zoomCamera.position.sub(controls.target);
zoomCamera.position.setLength(camDistance);
zoomCamera.lookAt(scene.position);
// Add zoomCamera to main scene
scene.add(zoomCamera);
// render scene
renderer.clear();
renderer.setViewport(0, 0, width, height);
renderer.render(scene, camera);
// render inset
renderer.clearDepth(); // important!
renderer.setViewport(10, height - zoomHeight - 10, zoomWidth, zoomHeight);
renderer.render(scene, zoomCamera);
}
Given that I have only one renderer, I don't knwo how to assign the "inset" container to the renderer of Viewport (i.e with the good renderer.setViewport)
Would you have got a workaround ?
You want to render another view of your scene in an inset window.
Create one scene, and two cameras.
Make sure you set autoClear to false when you instantiate the renderer.
renderer.autoClear = false;
Then, in your render loop, use this pattern
// render scene
renderer.clear();
renderer.setViewport( 0, 0, window.innerWidth, window.innerHeight );
renderer.render( scene, camera );
// render inset
renderer.clearDepth(); // important!
renderer.setViewport( 10, window.innerHeight - insetHeight - 10, insetWidth, insetHeight );
renderer.render( scene, camera2 );
three.js r.75
I want to load multiple obj+mtl files using Three.js with the following code. It works OK with one or two obj data. But when I try to load multiple OBJs (more than three), it crashes especially on iOS.
The obj data is small, which is 6MB in total. If I clone the object after loading, it works even with ten objects, but it crashes if use THREE.OBJMTLLoader multiple times on iOS.
I couldn't find good example which load multiple obj files. Is there anything I should care about for multiple OBJs?
<!DOCTYPE html>
<html lang="ja">
<head><meta charset="UTF-8"></head>
<script src="http://threejs.org/build/three.min.js"></script>
<script src="http://threejs.org/examples/js/loaders/MTLLoader.js"></script>
<script src="http://threejs.org/examples/js/loaders/OBJMTLLoader.js"></script>
<body>
<div id="canvas_frame"></div>
<script>
var canvasFrame, scene, renderer, camera;
canvasFrame = document.getElementById('canvas_frame');
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
canvasFrame.appendChild( renderer.domElement );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set(50,50,50);
camera.lookAt( {x: 0, y: 0, z: 0} );
var ambient = new THREE.AmbientLight(0xFFFFFF);
scene.add(ambient);
function animate() {
renderer.render( scene, camera );
requestAnimationFrame( animate );
}
function loadObjMtl(objUrl, mtlUrl, url, x, y, z){
var loader = new THREE.OBJMTLLoader();
loader.crossOrigin = 'anonymous';
loader.load( objUrl, mtlUrl,
function ( object ) {
object.url = url;
object.position.set(x,y,z);
scene.add ( object );
});
}
objUrl = "http://test2.psychic-vr-lab.com/temp/mesh_reduced.obj";
mtlUrl = "http://test2.psychic-vr-lab.com/temp/mesh_reduced.mtl";
loadObjMtl(objUrl,mtlUrl,"",0,0,0);
loadObjMtl(objUrl,mtlUrl,"",20,20,0);
loadObjMtl(objUrl,mtlUrl,"",40,20,0);
loadObjMtl(objUrl,mtlUrl,"",60,0,0);
animate();
</script>
</body>
</html>
You probably run out of graphics memory on your iOS device.
The texture files you use are big, this for example is 4096x4096 http://test2.psychic-vr-lab.com/temp/tex_0.jpg
That is uncompressed to a raw bitmap for OpenGL use and takes a lot of memory then (tens of megs I think, 4096 * 4096 * 3 for RGB would be about 50MB).
Use a smaller resolution image. And additionally use a texture format which you can use in the compressed format, on iOS PVRTC, for which support to three.js was added in https://github.com/mrdoob/three.js/pull/5337 ("PVRTC support in examples")
Cloning works because you then reuse the same texture for many objects -- the big image is in memory only once. That's of course what you want if they all use the same image. But if you need different images for the various objects then you need to make their mem consumption smaller.