Wrong coordinates for bounding box in three.js - javascript

I have some strange behaviour with bounding box in three.js.
I use STLLoader and for some models everything works fine, but for some of them box is shifted.
For example:
http://oi37.tinypic.com/35a1y4l.jpg
and
http://oi34.tinypic.com/4hf4tl.jpg
Bounding box has right size and it's position is (0,0,0). The same position has loaded STL model.
And here is my code:
function stlLoader() {
var redPhongMaterial = new THREE.MeshPhongMaterial({ color: 0xFFEA32, side: THREE.DoubleSide, ambient:0x000000}); // yellow
var stlLoader = new THREE.STLLoader();
stlLoader.addEventListener('load', function (event) {
var stlGeometry = event.content;
var mesh = new THREE.Mesh(stlGeometry, redPhongMaterial);
mesh.scale.set(2, 2, 2);
mesh.castShadow = true;
mesh.receiveShadow = true;
stlGeometry.computeBoundingBox();
var boundingBox = mesh.geometry.boundingBox.clone();
drawBoundingBox(boundingBox, mesh.scale.x, mesh.scale.y, mesh.scale.z);
mesh.position.y = 0;
mesh.position.x = 0;
mesh.position.z = 0;
scene.add( mesh );
loadComplete();
} );
stlLoader.load( ptsfilestoload );
}
function drawBoundingBox(box, scaleX, scaleY, scaleZ)
{
var length = scaleX * (box.max.x - box.min.x);
var height = scaleY * (box.max.y - box.min.y);
var depth = scaleZ * (box.max.z - box.min.z);
var boundingBoxGeometry = new THREE.CubeGeometry( length, height, depth );
for ( var i = 0; i < boundingBoxGeometry.faces.length; i ++ )
{
boundingBoxGeometry.faces[i].color.setHex( Math.random() * 0xffffff );
}
var boundingBoxMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors, transparent: true, opacity: 0.7 } );
var boundingBoxMesh = new THREE.Mesh( boundingBoxGeometry, boundingBoxMaterial);
scene.add( boundingBoxMesh );
}
Or maybe this is problem with STLLoader? I'm really new to webgl and three.js so any help appreciated

In your drawBoundingBox routine you need
var bboxCenter = box.center ();
boundingBoxMesh .translateX (bboxCenter.x);
boundingBoxMesh .translateY (bboxCenter.y);
boundingBoxMesh .translateZ (bboxCenter.z);
just before you add the mesh to the scene. Your Cube is created around 0,0,0.

Related

How do I delete a subset of mesh's from a scene?

When I create multiple mesh's with the same name I can't select them all when I want to remove them from a scene.
I've tried traversing the function to no avail.
event.preventDefault();
scene.traverse(function(child) {
if (child.name === "blueTiles") {
var remove_object = scene.getObjectByName( "blueTiles", true );
scene.remove(remove_object);
}
});
var surroundMaterial = new THREE.MeshBasicMaterial({ color: 0x154995, side: THREE.DoubleSide, transparent: true, opacity: 0.8 });
surroundingCubes = new THREE.Mesh( geometry, surroundMaterial );
scene.add( surroundingCubes );
surroundingCubes.name = "blueTiles";
surroundingCubes.position.set(selectedObject.position.x - 1, 0.11, selectedObject.position.z);
var surroundMaterial = new THREE.MeshBasicMaterial({ color: 0x154995, side: THREE.DoubleSide, transparent: true, opacity: 0.8 });
surroundingCubes = new THREE.Mesh( geometry, surroundMaterial );
scene.add( surroundingCubes );
surroundingCubes.name = "blueTiles";
surroundingCubes.position.set(selectedObject.position.x + 1, 0.11, selectedObject.position.z);
surroundingCubes.rotation.x = Math.PI / 2;
I should be able to only delete all the objects with the name blueTiles
EDIT I switched from names to Groups, and that worked wonders
SOLUTION BELOW
function onDocumentMouseDown(event) {
for (var i = group.children.length - 1; i >= 0; i--) {
group.remove(group.children[i]);
}
var surroundingMaterial = new THREE.MeshBasicMaterial({ color: 0x154995, side: THREE.DoubleSide, transparent: true, opacity: 0.8 });
var geometry = new THREE.PlaneGeometry(1, 1, 1, 1);
if ( selectedObject.position.x - 1 >= 0) {
surroundingCube = new THREE.Mesh( geometry, surroundingMaterial );
surroundingCube.position.set(selectedObject.position.x - 1, 0.11, selectedObject.position.z);
surroundingCube.rotation.x = Math.PI / 2;
group.add(surroundingCube);
}
if ( selectedObject.position.x + 1 <= 9) {
surroundingCube = new THREE.Mesh( geometry, surroundingMaterial );
surroundingCube.position.set(selectedObject.position.x + 1, 0.11, selectedObject.position.z);
surroundingCube.rotation.x = Math.PI / 2;
group.add(surroundingCube);
}
scene.add( group );
}
You can try grouping the meshes using the THREE.group class.
A very basic usage would be something like:
var meshes = new THREE.Group();
var mesh1 = new THREE.Mesh( geometry, material );
var mesh2 = new THREE.Mesh( geometry, material );
var mesh3 = new THREE.Mesh( geometry, material );
meshes.add( mesh1 );
meshes.add( mesh2 );
meshes.add( mesh3 );
scene.add( meshes );
getObjectByName just calls getObjectByProperty (using the name property) which only returns the first object it finds.
You really just need to loop over children of the scene / object3d, check their name, and remove.
If you know all the ones you want to remove will be at the top level it is simple.
Something like....(untested)
for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
if (scene.children[i].name === 'blueTiles') {
scene.remove(scene.children[i]);
}
}
If you also want to check at lower levels, you probably want some sort of recursion.
EDIT...
After having another look at your question..and remembering that there is a traverse function
You seem to already be traversing the scene and have access to the child.
I think you just need to change your function (and not call getObjectByName at all).
scene.traverse(function(child) {
if (child.name === "blueTiles") {
scene.remove(child);
}
});

Three.js - Bigger bounding box after rotation

So I am having this code:
computeCarBoundingBox(mesh);
mesh.rotation.x = this.rotationVal[ 0 ];
mesh.rotation.y = this.rotationVal[ 1 ];
mesh.rotation.z = this.rotationVal[ 2 ];
Where I try to compute a bounding box for a mesh, if I compute it after rotation look like this:
If I compute it after the rotation look like this:
My compute bounding box function is this:
function computeCarBoundingBox(mesh){
var box = new THREE.Box3().setFromObject(mesh);
var boundingBoxHelper = new THREE.Box3Helper( box, 0xffff00 );
scope.carBoundingBox =boundingBoxHelper;
scene.add(scope.carBoundingBox);
console.log(box.min); // x, y, and z are all Infinity.
console.log(box.max); // x, y, and z are all -Infinity.
}
I do have a geometry. This is a part of my code :
this.loadCar = function ( carsVector,carName,roadName ) {
if(carName=='veyron')
{
var index = 0;
}
else if(carName=='F50')
{
var index = 1;
}
else
{
var index = 2;
}
console.log("Selected car name:"+carName);
var carLoader = new THREE.BinaryLoader();
carLoader.load( carsVector[Object.keys(carsVector)[index]].url, function( geometry ) {
geometry.sortFacesByMaterialIndex();
console.log("url--->"+carsVector[Object.keys(carsVector)[index]].url);
var materials = [];
this.scaleVal = carsVector[ Object.keys(carsVector)[index] ].scale * 1;
if(roadName =='road01'){
this.positionVal = carsVector[ Object.keys(carsVector)[index] ].position_r1;
}
else if(roadName=='road02'){
this.positionVal = carsVector[ Object.keys(carsVector)[index] ].position_r2;
}
this.rotationVal = carsVector[ Object.keys(carsVector)[index] ].init_rotation;
for ( var i in carsVector[ Object.keys(carsVector)[index] ].materialsMap ) {
materials[ i ] = carsVector[ Object.keys(carsVector)[index] ].materialsMap[ i ];
}
createObject(geometry,materials);
});
return scope.carMesh;
}
// internal helper methods
function createObject ( geometry, materials ) {
scope.carGeometry = geometry;
scope.carMaterials = materials;
createCar();
};
function createCar () {
console.log("CREATE CARRRRRRRRRRRRRRRRR");
if ( scope.carGeometry ) {
var carMaterial = new THREE.MeshFaceMaterial( scope.carMaterials );
var mesh = new THREE.Mesh( scope.carGeometry, carMaterial );
mesh.scale.x = mesh.scale.y = mesh.scale.z = this.scaleVal;
mesh.position.set( this.positionVal[0], this.positionVal[1], this.positionVal[2]);
mesh.rotation.x = this.rotationVal[ 0 ];
mesh.rotation.y = this.rotationVal[ 1 ];
mesh.rotation.z = this.rotationVal[ 2 ];
this.carMesh = mesh;
//
computeCarBoundingBox(mesh);
console.log("This car mesh"+this.carMesh);
addShadows();
scene.add(this.carMesh);
//this.carBoundingBox.rotation.x =this.r[0];
//this.carBoundingBox.rotation.y = this.r[1];
//this.carBoundingBox.rotation.z = this.r[2];
//scene.add( this.carBoundingBox );
}
if ( scope.callback ) {
scope.callback(this.carMesh);
}
}
These are the methods I'm using in my project where I add the bounding boxes after rotation. If you don't rotate first you don't need the adjustRelativeTo step see e.g. https://codepen.io/seppl2019/pen/zgJVKM
class ChildPart {
constructor(mesh) {
this.mesh=mesh;
this.boxwire=null;
}
// add my bounding box wire to the given mesh
addBoundingBoxWire(toMesh) {
var boxwire = new THREE.BoxHelper(this.mesh, 0xff8000);
this.boxwire=boxwire;
ChildPart.adjustRelativeTo(boxwire,toMesh);
toMesh.add(boxwire);
}
static adjustRelativeTo(mesh,toMesh) {
//logSelected("adjusting toMesh",toMesh);
//logSelected("beforeAdjust",this.mesh);
toMesh.updateMatrixWorld(); // important !
mesh.applyMatrix(new THREE.Matrix4().getInverse(toMesh.matrixWorld));
//logSelected("afterAdjust",this.mesh);
}
}
I run into this problem recently. Thanks to #Wolfgang Fahl 's resolution.
Tt’s the right direction, but when I was doing it, I found something was wrong.
When the mesh have rotation effection. the box is still bigger than original one.
So you need to remove rotation before create BoxHelper, then add rotation back.
static adjustRelativeTo(mesh, toMesh) {
toMesh.updateMatrixWorld(); // important !
mesh.applyMatrix4(new THREE.Matrix4().copy( toMesh.matrixWorld ).invert());
}
addBoundingBox(mesh, toMesh) {
// remove rotation
let rotate = mesh.rotation.clone();
mesh.rotation.set(0, 0 , 0);
let box = new THREE.BoxHelper( mesh, 0xffff00);
// apply to parent matrix
adjustRelativeTo(box, toMesh);
toMesh.add(box);
// 然后再把旋转加上
mesh.rotation.set(rotate.x, rotate.y, rotate.z);
}
That's how .setFromObject() works, when object is wide and when you rotate it, its box will be bigger, as it's world-axis-aligned:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 5, 5);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var light = new THREE.DirectionalLight(0xffffff, 0.75);
light.position.set(-10, 10, -10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.25));
scene.add(new THREE.GridHelper(10, 10));
var geometry = new THREE.BoxGeometry(2, 1, 3);
geometry.translate(0, 0.5, 0);
var mesh1 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: "gray"
}));
mesh1.position.x = -2.5;
scene.add(mesh1);
var mesh2 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: "aqua"
}));
mesh2.position.x = 2.5;
mesh2.rotation.y = THREE.Math.degToRad(45);
scene.add(mesh2);
var bbox1 = new THREE.Box3().setFromObject(mesh1);
var bbox2 = new THREE.Box3().setFromObject(mesh2);
var bhelp1 = new THREE.Box3Helper(bbox1, 0xffff00);
scene.add(bhelp1);
var bhelp2 = new THREE.Box3Helper(bbox2, 0xff00ff);
scene.add(bhelp2);
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
Alright I have two theories, and no certain answer. sorry!
1) It is possible for meshes to be without geometry. Does your mesh have a geometry? If not the code called from setFromObject will fail. (expandByPoint will never be called and min and max will remain at Infinity since the previous makeEmpty-call).
2) Seeing how deeply dependent that recursive "expandByOject" code is on scope and this, I would try adding parenthesis to your new-operator var box = (new THREE.Box3()).setFromObject(mesh); It's a bit of a shot in the dark, but perhaps the scope is never properly set.
Sorry for not taking the time and testing things out first.

scene loaded via objectloader, bump map not rendering

attempting to apply a bump map to an object loaded, but no change is seen on the material
var loader = new THREE.ObjectLoader();
loader.load("../js/brain2.json", function(object) {
var mapHeight = new THREE.TextureLoader().load( "../js/texture.jpg" );
var material = new THREE.MeshPhongMaterial( { color: 0x888888, specular: 0xEEEEEE, shininess: 5} );
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = material;
child.material.bumpMap = mapHeight;
child.material.bumpScale = 1;
var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
geometry.computeFaceNormals();
geometry.mergeVertices();
geometry.computeVertexNormals();
child.geometry = new THREE.BufferGeometry().fromGeometry( geometry );
var modifier = new THREE.BufferSubdivisionModifier(1);
modifier.modify(geometry);
child.material.overdraw = 1
};
});
object.scale.set(15, 15, 15);
object.position.x = 1;
object.position.y = 1;
object.position.z = 1;
object.rotation.set( 5, 1, 1 );
scene.add( object );
});
I've already fixed earlier issues with this code, including applying a subdivision modifier to it, but now it appears the bump map refuses to be applied.

child objects drawing order

Got the following problem:
im trying to make rings around saturn, but it seems they are somehow rendered in wrong order:
The thing is how each planet is created. Each planet is a child of different root object (THREE.Object3d), which contains a bodyContainer (THREE.Object3d). BodyContainer contains the planet mesh. When I add the rings mesh to body or bodycontainer it is rendered as on the picture above.
For tests ive created a 'free' sphere and rings, which ive added. to the scene and everything works as supposed for objects added directly to the scene.
Even if I add rings as a child of the sphere which is added to the scene it works fine.
Here is the code I use to generate the planet body:
export default function generateBody(radius, basic, name) {
var geometry = new THREE.SphereGeometry( radius, 24, 24 );
var material;
if(basic) {
material = new THREE.MeshBasicMaterial({color: 0xFBE200});
} else {
material = new THREE.MeshLambertMaterial({
//depthWrite: false,
//depthTest: true,
});
if(textures[name].hasOwnProperty('map')) material.map = THREE.ImageUtils.loadTexture(textures[name].map);
if(textures[name].hasOwnProperty('bump')) material.bumpMap = THREE.ImageUtils.loadTexture(textures[name].bump);
if(textures[name].hasOwnProperty('specular')) material.specularMap = THREE.ImageUtils.loadTexture(textures[name].specular);
if(textures[name].hasOwnProperty('normal')) material.normalMap = THREE.ImageUtils.loadTexture(textures[name].specular);
}
var mesh = new THREE.Mesh( geometry, material )
mesh.scale.set( params.bodyScale, params.bodyScale, params.bodyScale );
mesh.rotateX(Math.PI / 2);
mesh.renderOrder = 0;
return mesh;
}
and how i add the rings:
var circlemesh = new THREE.XRingGeometry(1.2 * (def && def.diameter || 139822000) * M_TO_AU / 2, 2 * (def && def.diameter || 139822000) * M_TO_AU / 2, 2 * 64, 5, 0, Math.PI * 2);
var circleMaterial = new THREE.MeshLambertMaterial( {
map: THREE.ImageUtils.loadTexture('../img/planet-textures/saturn/saturnringcolor.jpg'),
alphaMap: THREE.ImageUtils.loadTexture('../img/planet-textures/saturn/saturnringpattern.gif'),
//transparent: true,
side: THREE.DoubleSide,
//depthWrite: false,
//depthTest: true
});
var mesh = new THREE.Mesh(circlemesh, circleMaterial);
mesh.renderOrder = 1;
this.body.add(mesh);
furtheron:
this.bodyContainer.add(this.body)
this.root.add(this.bodyContainer)
scene.add(this.root)
For testing on a sphere added directly to the scene i use just a plain sphere geometry and the same mesh for rings used here.
var circlemesh = new THREE.XRingGeometry(1.2 * 5, 2 * 5, 2 * 64, 5, 0, Math.PI * 2);
var circleMaterial = new THREE.MeshLambertMaterial( {
map: THREE.ImageUtils.loadTexture('../img/planet-textures/saturn/saturnringcolor.jpg'),
alphaMap: THREE.ImageUtils.loadTexture('../img/planet-textures/saturn/saturnringpattern.gif'),
transparent: true,
side: THREE.DoubleSide,
//depthWrite: false,
//depthTest: true
});
var ringmesh = new THREE.Mesh(circlemesh, circleMaterial);
//ringmesh.renderOrder = 1;
//scene.add(ringmesh);
var SPHEREgeometry = new THREE.SphereGeometry( 5, 32, 32 );
var SPHEREmaterial = new THREE.MeshLambertMaterial( {color: 0xffff00} );
var sphere = new THREE.Mesh( SPHEREgeometry, SPHEREmaterial );
//sphere.renderOrder = 0;
scene.add( sphere );
sphere.add( ringmesh );
What fixed the problem was increasing the near of the camera.
No extra parameters in material weren't needed.
Here's how you can use Object3D in a parent child setup in THREE:
Object3D Parent Child Fiddle
var root = new THREE.Object3D();
var rootcontainer = new THREE.Object3D();
root.parent = rootcontainer;
mesh = new THREE.Mesh( geometry, material );
root.add( mesh );
rootcontainer.add(root);
scene.add(rootcontainer);

copy texture Three.js

I want to load the left half of video texture to left Geometry and right half of video texture to the right Geometry
var video = document.createElement("video");
var texture = new THREE.Texture(video);
texture.offset = new THREE.Vector2(0,0);
texture.repeat = new THREE.Vector2( 0.5, 1 );
var material = new THREE.MeshLambertMaterial({
map: texture,
side: THREE.DoubleSide
});
this is the left plane texture
var texture2 = new THREE.Texture(video);
texture2.minFilter = THREE.NearestFilter;
texture2.offset = new THREE.Vector2(0.5,0);
texture2.repeat = new THREE.Vector2( 0.5, 1 );
var material2 = new THREE.MeshLambertMaterial({
map: texture2,
side: THREE.DoubleSide
});
this is the right plane texture
var plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(320, 240), material);
var plane2 = new THREE.Mesh(new THREE.PlaneBufferGeometry(320, 240), material2);
loading two video texture didn't work,the left plane does display but the right not ,Than I try to copy texture instead of loading the same video texture:
texture2 = THREE.Texture.clone(texture);
or
texture = texture;
both don't work,too.Because(in three.js reference):
.clone(texture)
Make copy of texture. Note this is not a "deep copy", the image is shared.
What if anything can I do ?
function change_uvs( geometry, unitx, unity, offsetx, offsety ) {
var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
for ( var i = 0; i < faceVertexUvs.length; i ++ ) {
var uvs = faceVertexUvs[ i ];
for ( var j = 0; j < uvs.length; j ++ ) {
var uv = uvs[ j ];
uv.x = ( uv.x + offsetx ) * unitx;
uv.y = ( uv.y + offsety ) * unity;
}
}
}
var P1 = new THREE.PlaneGeometry(320, 240);
var p2 = new THREE.PlaneGeometry(320, 240);
change_uvs(p1,0.5,1,0,0);//left plane
change_uvs(p2,0.5,1,1,0);// right plane
by changging the uvMapping of planes i solve the problem :)
If it was to work in theory You will need to change the UV co-ordinates on either plane and add the texture to that. I had a similar issue with an image file more or less, check here :
three.js webgl custom shader sharing texture with new offset
There is a lot of info i had put there and should help you with a resolution.

Categories

Resources