Stretching Texture across Merged Geometries - three.js

I am building a first person maze - each wall in the maze is a THREE.PlaneGeometry. As i understand, it is much better practice to have these walls all merged into single object. I have created a class "walls" which does this each time a new "wall" is added:
this.geometry.merge(wall.mesh.geometry, wall.mesh.matrix);
After all the walls are added, I create a material + apply a texture:
this.material = new THREE.MeshBasicMaterial( {
map: this.texture,
side: THREE.DoubleSide
} );
this.mesh = new THREE.Mesh( this.geometry, this.material );
The problem I am having is that the walls are not all the same width and so the texture mapping goes all funky (Image Here) on the merged geo. Each plane receives the entire texture and stretches it to its dimensions. Bearing in mind that all the walls require the same texturing, what would be the best way to 'wrap' the texture around the walls? Or should I be constructing my walls differently in the first place?
I have also given both Three.MultiMaterial(materials) and THREE.MeshFaceMaterial(materials) a go (giving a unique material to each wall), but these both seriously kill performance.
Thanks in advance,
Happy Days,
J
Screenshot: Maze Image

Run a loop over each faceVertexUV of each wall's geo. Multiply each UV.x by the width of the wall (eliminate stretching / shrinking). Add an offset to the UV.x of the wall that corresponds to a summation of the width of walls thus far:
var len = wall.geometry.faceVertexUvs[0].length;
for (var i = 0; i < len; i++){
for (var j = 0; j < 3; j++){
wall.geometry.faceVertexUvs[0][i][j].x *= wall.w;
wall.geometry.faceVertexUvs[0][i][j].x += this.w;
}
}
this.w += wall.w;

Related

3D three.js Create the ground surface of a 3D building

Following my post last week three.js How to programatically produce a plane from dataset I come back to the community to solve a problem of definition of surface occupied on the ground by a 3D building.
The solution proposed in comments in this post works for this building but is not universal.
To make it universal I chose the following method: when the walls are built I create their clone in another group (see this previous post for walls creation)
// prepare the clones
var clones = new THREE.Group();
scene.add(clones);
var num=0;
// drawing the real walls
var wallGeometry = new THREE.PlaneGeometry(size,(hstair*batims[i][1]));
val = 0xFFFFFF;
opa = 0.5;
if(deltaX > deltaY){val = 0x000000; opa = 0.05;} // shaded wall
var wallMaterial = new THREE.MeshBasicMaterial({color:val,transparent:true, opacity:opa, side:THREE.DoubleSide});
var walls = new THREE.Mesh(wallGeometry, wallMaterial);
walls.position.set((startleft+endleft)/2,(hstair*batims[i][1])/2,(startop+endtop)/2);
walls.rotation.y = -rads;
scene.add(walls);
// add the pseudo-walls to scene
var cloneGeometry=new THREE.PlaneGeometry(long,3);
var cloneMaterial=new THREE.MeshBasicMaterial({color:0xff0000,transparent:true,opacity:0.5,side:THREE.DoubleSide});
var clone=new THREE.Mesh(pseudomursGeometry,pseudomursMaterial);
clone.position.set((startleft+endleft)/2,3,(startop+endtop)/2);
clone.rotation.y=-rads;
clones.add(clone);
num++;
The idea is now to rotate this pseudo-building so that the longest wall is vertical, which allows me to determine the exact floor area occupied with its boundingBox:
var angle=turn=0;
for(i=0; i<dists.length; i++) { // dists is the array of wall lengths
if(dists[i]==longs[0]){ // longs is the reordered lengths array
angle=angles[i][1]; // angle of the longest wall
}
}
// we can now rotate the whole group to put the longest wall vertical
if(angle>0){
turn = angle*-1+(Math.PI/2);
}
else {
turn = angle+(Math.PI/2);
}
clones.rotation.y=turn;
It works perfectly as long as the building has a right angle, whatever its shape: triangle, rectangle, bevel, right angle polygons,
var boundingBox = new THREE.Box3().setFromObject(clones);
var thisarea = boundingBox.getSize();
// area size gives the expected result
console.log('AREA SIZE = '+thisarea.x+' '+thisarea.y+' '+thisarea.z);
...but not when there are no more right angles, for example a trapezoid
The reason is that we rotate the group, and not the cloned walls. I can access and rotate each wall by
for(n=0;n<num;n++){
thisangle = clones.children[n].rotation.y;
clones.children[n].rotation.y = turn-thisangle;
}
But the result is wrong for the others pseudo-walls:
So the question is: how to turn each red pseudo-wall so that the longest one is vertical and the others remain correctly positioned in relation to it? In this way, any building with any shape can be reproduced in 3D with its internal equipment. Any idea on how to achieve this result?
A weird & ugly but well-working solution:
// 1. determines which is the longest side
for(i=0; i<dists.length; i++) {
if(dists[i]==longs[0]){
longest=i;
break; // avoid 2 values if rectangle
}
}
// 2. the group is rotated until the longest side has an angle in degrees
// close to 0 or 180
var letsturn = setInterval(function() {
clones.rotation.y += 0.01;
var group_rotation = THREE.Math.radToDeg(clones.rotation.y); // degrees
var stop = Math.round(angles[longest][0] - group_rotation);
// 3. stop when longest wall is vertical
if( (stop>=179 && stop<=181) || (stop>=-1 && stop<=1) ) {
clearInterval(letsturn);
createPlane() // we can now use boundingBox in reliability
}
}, 1);
et voilĂ .

How fill a loaded STL mesh ( NOT SIMPLE SHAPES LIKE CUBE ETC) with random particles and animate with this geometry bound in three.js

How I can fill a loaded STL mesh ( like suzane NOT SIMPLE SHAPES LIKE CUBE etc) with random particles and animate it inside this geometry bounds with three.js ?
I see many examples but all of it for simple shapes with geometrical bounds like cube or sphere with limit by coordinates around center
https://threejs.org/examples/?q=points#webgl_custom_attributes_points3
TNX
A concept, using a ray, that counts intersections of the ray with faces of a mesh, and if the number is odd, it means that the point is inside of the mesh:
Codepen
function fillWithPoints(geometry, count) {
var ray = new THREE.Ray()
var size = new THREE.Vector3();
geometry.computeBoundingBox();
let bbox = geometry.boundingBox;
let points = [];
var dir = new THREE.Vector3(1, 1, 1).normalize();
for (let i = 0; i < count; i++) {
let p = setRandomVector(bbox.min, bbox.max);
points.push(p);
}
function setRandomVector(min, max){
let v = new THREE.Vector3(
THREE.Math.randFloat(min.x, max.x),
THREE.Math.randFloat(min.y, max.y),
THREE.Math.randFloat(min.z, max.z)
);
if (!isInside(v)){return setRandomVector(min, max);}
return v;
}
function isInside(v){
ray.set(v, dir);
let counter = 0;
let pos = geometry.attributes.position;
let faces = pos.count / 3;
let vA = new THREE.Vector3(), vB = new THREE.Vector3(), vC = new THREE.Vector3();
for(let i = 0; i < faces; i++){
vA.fromBufferAttribute(pos, i * 3 + 0);
vB.fromBufferAttribute(pos, i * 3 + 1);
vC.fromBufferAttribute(pos, i * 3 + 2);
if (ray.intersectTriangle(vA, vB, vC)) counter++;
}
return counter % 2 == 1;
}
return new THREE.BufferGeometry().setFromPoints(points);
}
The concepts from the previous answer is very good, but it has some performance limitations:
the whole geometry is tested with every ray
the recursion on points outside can lead to stack overflow
Moreover, it's incompatible with indexed geometry.
It can be improved by creating a spatial hashmap storing the geometry triangles and limiting the intersection test to only some part of the mesh.
Demonstration

Three.mesh got partially blocked by model

I was intended to fill the space between two THREE.Lines with some color. I tried to use THREE. It looks fine from some angles below the model, but if looking from top to bottom, the mesh area got partially blocked (the image is here). The other THREE.js objects, such as the red points and red lines are not affected by model while the Three.mesh gets screwed up. The following is my code for the Three.mesh:
// push vertices
geom.vertices.push((new THREE.Vector3()).fromArray(borepoint));
// add faces to mesh
for(let i =0; i < geom.vertices.length-2; i++){
for(let j = i + 1; j < geom.vertices.length-1; j++){
for(let k = j + 1; k < geom.vertices.length;k++){
geom.faces.push(new THREE.Face3(i,j,k));
}
}
}
const fillMesh = new THREE.Mesh(geom , new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0x2f92d7,
transparent: false,
opacity: 0.5,
}));
Does anyone has any idea about this? Thanks!
In this case, the problem turned out to be .depthTest. The Object is getting hidden behind the terrain geometry due to z-buffering (aka depthTest).
Disabling .deptTest on the blue objects material, fixed it.
Setting .transparent = true on the material, flags to be rendered second, in the transparency pass. Without it being set, drawing order may or may not be correct and the problem could still remain.
One way to ensure that it will always render on top, is to have the geometry in a different scene which you renderer.render after the terrain scene but that may be overkill for this scenario.

Three.js, center camera to view all objects that is in the scene

I write an algorithm that can explode (fold and unfold) mechanical set by double clicking on then.
But i want to move the camera backward or forward after that to see all my objects in the fov.
I'm trying to use frustum to calculate intersection between frustum and objects, but i don't undestand how to use planes.
I'm working with OrthographicCamera.
What i do :
At every frame i recalculate the new frustum (when camera move):
projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
frustum.setFromMatrix(projScreenMatrix);
Then i do a loop over the 6 planes and bounding box of all objects in the scene :
for (var i = 0; i < planes.length; i++) {
var plane = planes[i];
for (var j = 0; j < boxs.length; j++) {
var box = boxs[j];
var line = new THREE.Line3(box.min, nox.max);
//console.log({'plane': plane, 'line': line});
if (plane.isIntersectionLine(line))
// move camera
};
};
but plane.isIntersectionLine(line) is always false.
Do you have any ideas ?
Thanks

three.js - Set the rotation of an object in relation to its own axes

I'm trying to make a static 3D prism out of point clouds with specific numbers of particles in each. I've got the the corner coordinates of each side of the prism based on the angle of turn, and tried spawning the particles in the area bound by these coordinates. Instead, the resulting point clouds have kept only the bottom left coordinate.
Screenshot: http://i.stack.imgur.com/uQ7Q8.png
I've tried to set the rotation of each cloud object such that their edges meet, but they will rotate only around the world centre. I gather this is something to do with rotation matrices and Euler angles, but, having been trying to work them out for 3 solid days, I've despaired. (I'm a sociologist, not a dev, and haven't touched graphics before this project.)
Please help? How do I set the rotation on each face of the prism? Or maybe there is a more sensible way to get the particles to spawn in the correct area in the first place?
The code:
// draw the particles
var n = 0;
do {
var geom = new THREE.Geometry();
var material = new THREE.PointCloudMaterial({size: 1, vertexColors: true, color: 0xffffff});
for (i = 0; i < group[n]; i++) {
if (geom.vertices.length < group[n]){
var particle = new THREE.Vector3(
Math.random() * screens[n].bottomrightback.x + screens[n].bottomleftfront.x,
Math.random() * screens[n].toprightback.y + screens[n].bottomleftfront.y,
Math.random() * screens[n].bottomrightfront.z + screens[n].bottomleftfront.z);
geom.vertices.push(particle);
geom.colors.push(new THREE.Color(Math.random() * 0x00ffff));
}
}
var system = new THREE.PointCloud(geom, material);
scene.add(system);
**// something something matrix Euler something?**
n++
}
while (n < numGroups);
I've tried to set the rotation of each cloud object such that their
edges meet, but they will rotate only around the world centre.
It is true they only rotate around 0,0,0. The simple solution then is to move the object to the center, rotate it, and then move it back to its original position.
For example (Code not tested so might take a bit of tweaking):
var m = new THREE.Matrix4();
var movetocenter = new THREE.Matrix4();
movetocenter.makeTranslation(-x, -y, -z);
var rotate = new THREE.Matrix4();
rotate.makeRotationFromEuler(); //Build your rotation here
var moveback = new THREE.Matrix4();
moveback .makeTranslation(x, y, z);
m.multiply(movetocenter);
m.multiply(rotate);
m.multiply(moveback);
//Now you can use geometry.applyMatrix(m)

Resources