3D Slicing web app Javascript and Three.js - javascript

I am developing a web application to estimate the cost of a 3D printing model with three.js and also do other stuff.
I have easily calculate bounding box and volume of object and I am now approaching slices.
Following this question I have managed to get intersections with a plane: Three JS - Find all points where a mesh intersects a plane and I put the function inside a for loop that appends to a three.js group.
// Slices
function drawIntersectionPoints() {
var contours = new THREE.Group();
for(i=0;i<10;i++){
a = new THREE.Vector3(),
b = new THREE.Vector3(),
c = new THREE.Vector3();
planePointA = new THREE.Vector3(),
planePointB = new THREE.Vector3(),
planePointC = new THREE.Vector3();
lineAB = new THREE.Line3(),
lineBC = new THREE.Line3(),
lineCA = new THREE.Line3();
var planeGeom = new THREE.PlaneGeometry(50,50);
planeGeom.rotateX(-Math.PI / 2);
var plane = new THREE.Mesh(planeGeom, new THREE.MeshBasicMaterial({
color: "lightgray",
transparent: true,
opacity: 0.75,
side: THREE.DoubleSide
}));
plane.position.y = i;
scene.add(plane);
var mathPlane = new THREE.Plane();
plane.localToWorld(planePointA.copy(plane.geometry.vertices[plane.geometry.faces[0].a]));
plane.localToWorld(planePointB.copy(plane.geometry.vertices[plane.geometry.faces[0].b]));
plane.localToWorld(planePointC.copy(plane.geometry.vertices[plane.geometry.faces[0].c]));
mathPlane.setFromCoplanarPoints(planePointA, planePointB, planePointC);
meshGeometry.faces.forEach(function(face) {
mesh.localToWorld(a.copy(meshGeometry.vertices[face.a]));
mesh.localToWorld(b.copy(meshGeometry.vertices[face.b]));
mesh.localToWorld(c.copy(meshGeometry.vertices[face.c]));
lineAB = new THREE.Line3(a, b);
lineBC = new THREE.Line3(b, c);
lineCA = new THREE.Line3(c, a);
setPointOfIntersection(lineAB, mathPlane);
setPointOfIntersection(lineBC, mathPlane);
setPointOfIntersection(lineCA, mathPlane);
});
var lines = new THREE.LineSegments(pointsOfIntersection, new THREE.LineBasicMaterial({
color: 0xbc4e9c,
lineWidth: 2,
}));
contours.add(lines);
function setPointOfIntersection(line, plane) {
pointOfIntersection = plane.intersectLine(line);
if (pointOfIntersection) {
pointsOfIntersection.vertices.push(pointOfIntersection.clone());
};
};
};
console.log(contours);
scene.add(contours);
And this is what I see:
The for loop works and I visualise all the planes and also the lines inside the group but only the first intersection is showing in the canvas (pink).
screenshot
Many thanks.

You have to call .updateMatrixWorld(true) on your plane object after you set its y-coordinate in the loop:
plane.position.y = i;
plane.updateMatrixWorld(true);
scene.add(plane);
jsfiddle example.

Related

Merging geometries in three.js

I have a scene which contains multiple meshes, each of varying shapes and sizes.
I have looped through each Mesh and using geometry.merge() I have been able to create a new mesh from the geometries in the scene.
I want to mask the entire mesh with an alphaMask, however, each geometry has the material applied to it separately.
An example of this can be seen here - https://codepen.io/danlong/pen/KXOObr
function addObjects(scene) {
// merged geomoetry & material
var mergedGeometry = new THREE.Geometry();
var mergedMaterial = new THREE.MeshStandardMaterial({ color: "#444", transparent: true, side: THREE.DoubleSide, alphaTest: 0.5, opacity: 1, roughness: 1 });
// multiple meshes
var geometry = new THREE.IcosahedronGeometry(30, 5);
var material = new THREE.MeshStandardMaterial({ color: "#444" });
var geo1 = new THREE.IcosahedronGeometry(30, 5);
var mesh1 = new THREE.Mesh( geo1, material );
mesh1.position.x = 10;
mesh1.position.y = 10;
mesh1.position.z = 0;
var geo2 = new THREE.IcosahedronGeometry(30, 5);
var mesh2 = new THREE.Mesh( geo2, material );
mesh2.position.x = 20;
mesh2.position.y = 20;
mesh2.position.z = 0;
var geo3 = new THREE.IcosahedronGeometry(30, 5);
var mesh3 = new THREE.Mesh( geo3, material );
mesh3.position.x = 30;
mesh3.position.y = 30;
mesh3.position.z = 0;
// scene.add(mesh1, mesh2, mesh3);
mesh1.updateMatrix();
mergedGeometry.merge(mesh1.geometry, mesh1.matrix);
mesh2.updateMatrix();
mergedGeometry.merge(mesh2.geometry, mesh2.matrix);
mesh3.updateMatrix();
mergedGeometry.merge(mesh3.geometry, mesh3.matrix);
// alpha texture
var image = document.createElement('img');
var alphaMap = new THREE.Texture(image);
image.onload = function() {
alphaMap.needsUpdate = true;
};
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGUlEQVQoU2NkYGD4z4AHMP7//x+/gmFhAgCXphP14bko/wAAAABJRU5ErkJggg==';
mergedMaterial.alphaMap = alphaMap;
mergedMaterial.alphaMap.magFilter = THREE.NearestFilter;
mergedMaterial.alphaMap.wrapT = THREE.RepeatWrapping;
mergedMaterial.alphaMap.repeat.y = 1;
// merged geometry with alpha mask
merge1 = new THREE.Mesh(mergedGeometry, mergedMaterial);
merge1.rotation.z = -Math.PI/4;
// merge geometry without alpha mask
var merge2 = new THREE.Mesh(mergedGeometry, material);
merge2.position.x = -100;
merge2.rotation.z = -Math.PI/4;
scene.add(merge1, merge2);
return mesh;
}
The mesh on the left is the merged geometries which I want to apply the alphaMask to. The mesh on the right is the outcome of this and instead of the map being applied to the mesh as a whole, each of the geometries has the map applied.
Is there a way to mask the entire mesh and not each geometry?
--
three.js r86
EDIT:
I've tried to apply a clipping plane to my mesh but it's not the effect I'm looking for. I want to be able to apply an alphaMask across the whole mesh and reveal it however I make my mask image. Something like this effect - https://codepen.io/supah/pen/zwJxdb
Is it something to do with the UV's being preserved from the original geometries? Do I need to change these in some way?
I think what you really want is an overlaid mask. This can be accomplished by rendering a single plane that has the alpha map applied, on top of the scene rendering. Using an orthographic camera, and controlling certain renderer settings, such as disabling automatic clearing of color.

How to color a shape in Babylon.js?

Working off the "Basic Scene" example on babylonjs-playground.com here, I am trying to do a simple modification on the color of the sphere.
Here is my attempt, which can be run interactively:
https://www.babylonjs-playground.com/#95BNBS
Here is the code:
var createScene = function () {
// The original example, without comments:
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
camera.setTarget(BABYLON.Vector3.Zero());
camera.attachControl(canvas, true);
var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
var sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);
sphere.position.y = 1;
var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);
// My attempt to color the sphere
var material = new BABYLON.StandardMaterial(scene);
material.alpha = 1;
material.diffuseColor = new BABYLON.Color3(1,0,0);
scene.material = material;
return scene;
};
My attempt to add the colored material to the sphere has no effect.
I also tried to look for color-related attributes on the sphere object:
Object.keys(sphere).filter((key) => return key.includes("Color") )
// => "outlineColor", "overlayColor", "_useVertexColors", "edgesColor"
Except for _useVertexColors, all of these seem to be color objects, but changing them has no effect:
sphere.overlayColor.g = 1;
sphere.outlineColor.g = 1;
sphere.edgesColor.g = 1;
You're pretty close. You are setting a color correctly with diffuseColor but you aren't actually adding it specifically to your sphere.
Your sphere object is stored in sphere so what you need to do is you need to set the material you created on sphere and not on scene.
// My attempt to color the sphere
var material = new BABYLON.StandardMaterial(scene);
material.alpha = 1;
material.diffuseColor = new BABYLON.Color3(1.0, 0.2, 0.7);
sphere.material = material; // <--
See this tutorial

Three JS - Find all points where a mesh intersects a plane

I have created a three.js scene that includes a plane that intersects a mesh. What I would like to do is get an array of points for all locations where an edge of the mesh crosses the plane. I have had a good look for solutions and can't seem to find anything.
Here is an image of what I currently have:
And here I have highlighted the coordinates I am trying to gather:
If anybody can point me in the right direction, that would be most appreciated.
Thanks,
S
This is not the ultimate solution. This is just a point where you can start from.
UPD: Here is an extension of this answer, how to form contours from given points.
Also, it's referred to this SO question with awesome anwers from WestLangley and Lee Stemkoski about the .localToWorld() method of THREE.Object3D().
Let's imagine that you want to find points of intersection of a usual geometry (for example, THREE.DodecahedronGeometry()).
The idea:
THREE.Plane() has the .intersectLine ( line, optionalTarget ) method
A mesh contains faces (THREE.Face3())
Each face has a, b, c properties, where indices of vertices are stored.
When we know indices of vertices, we can get them from the array of vertices
When we know coordinates of vertices of a face, we can build three THREE.Line3() objects
When we have three lines, we can check if our plane intersects them.
If we have a point of intersection, we can store it in an array.
Repeat steps 3 - 7 for each face of the mesh
Some explanation with code:
We have plane which is THREE.PlaneGeometry() and obj which is THREE.DodecahedronGeometry()
So, let's create a THREE.Plane():
var planePointA = new THREE.Vector3(),
planePointB = new THREE.Vector3(),
planePointC = new THREE.Vector3();
var mathPlane = new THREE.Plane();
plane.localToWorld(planePointA.copy(plane.geometry.vertices[plane.geometry.faces[0].a]));
plane.localToWorld(planePointB.copy(plane.geometry.vertices[plane.geometry.faces[0].b]));
plane.localToWorld(planePointC.copy(plane.geometry.vertices[plane.geometry.faces[0].c]));
mathPlane.setFromCoplanarPoints(planePointA, planePointB, planePointC);
Here, three vertices of any face of plane are co-planar, thus we can create mathPlane from them, using the .setFromCoplanarPoints() method.
Then we'll loop through faces of our obj:
var a = new THREE.Vector3(),
b = new THREE.Vector3(),
c = new THREE.Vector3();
obj.geometry.faces.forEach(function(face) {
obj.localToWorld(a.copy(obj.geometry.vertices[face.a]));
obj.localToWorld(b.copy(obj.geometry.vertices[face.b]));
obj.localToWorld(c.copy(obj.geometry.vertices[face.c]));
lineAB = new THREE.Line3(a, b);
lineBC = new THREE.Line3(b, c);
lineCA = new THREE.Line3(c, a);
setPointOfIntersection(lineAB, mathPlane);
setPointOfIntersection(lineBC, mathPlane);
setPointOfIntersection(lineCA, mathPlane);
});
where
var pointsOfIntersection = new THREE.Geometry();
...
var pointOfIntersection = new THREE.Vector3();
and
function setPointOfIntersection(line, plane) {
pointOfIntersection = plane.intersectLine(line);
if (pointOfIntersection) {
pointsOfIntersection.vertices.push(pointOfIntersection.clone());
};
}
In the end we'll make our points visible:
var pointsMaterial = new THREE.PointsMaterial({
size: .5,
color: "yellow"
});
var points = new THREE.Points(pointsOfIntersection, pointsMaterial);
scene.add(points);
jsfiddle example. Press the button there to get the points of intersection between the plane and the dodecahedron.
Update THREE.js r.146
Sharing complete example using BufferGeometry since Geometry is deprecated since r.125, while following the wonderful example of #prisoner849 and discourse thread Plane intersects mesh with three.js r125
Example includes clipping the geometry based on the intersection points which are used to generate the LineSegments.
Can also instead create a Plane from the PlanarGeometry Quanternion and Normal
let localPlane = new THREE.Plane();
let normal = new THREE.Vector3();
let point = new THREE.Vector3();
normal.set(0, -1, 0).applyQuaternion(planarGeometry.quaternion);
point.copy(planarGeometry.position);
localPlane.setFromNormalAndCoplanarPoint(normal, point).normalize();**
Function updates Lines with current intersection based on the current position of the PlanarGeometry
let lines = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0x000000,
linewidth: 5
})
);
function drawIntersectionLine() {
let a = new THREE.Vector3();
let b = new THREE.Vector3();
let c = new THREE.Vector3();
const isIndexed = obj.geometry.index != null;
const pos = obj.geometry.attributes.position;
const idx = obj.geometry.index;
const faceCount = (isIndexed ? idx.count : pos.count) / 3;
const clippingPlane = createPlaneFromPlanarGeometry(plane);
obj.material.clippingPlanes = [clippingPlane];
let positions = [];
for (let i = 0; i < faceCount; i++) {
let baseIdx = i * 3;
let idxA = baseIdx + 0;
a.fromBufferAttribute(pos, isIndexed ? idx.getX(idxA) : idxA);
let idxB = baseIdx + 1;
b.fromBufferAttribute(pos, isIndexed ? idx.getX(idxB) : idxB);
let idxC = baseIdx + 2;
c.fromBufferAttribute(pos, isIndexed ? idx.getX(idxC) : idxC);
obj.localToWorld(a);
obj.localToWorld(b);
obj.localToWorld(c);
lineAB = new THREE.Line3(a, b);
lineBC = new THREE.Line3(b, c);
lineCA = new THREE.Line3(c, a);
setPointOfIntersection(lineAB, clippingPlane, positions);
setPointOfIntersection(lineBC, clippingPlane, positions);
setPointOfIntersection(lineCA, clippingPlane, positions);
}
lines.geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(positions), 3)
);
}
function setPointOfIntersection(line, planarSrf, pos) {
const intersect = planarSrf.intersectLine(line, new THREE.Vector3());
if (intersect !== null) {
let vec = intersect.clone();
pos.push(vec.x);
pos.push(vec.y);
pos.push(vec.z);
}
}
Example CodePen

Is there a way to add different textures to an object with TextureLoader.load

I would like to add different textures to each face of a box but I am not sure if loader.load is the way to do it, right now I have:
loader.load('img/brick.jpg', function ( texture ){
var boxGeometry = new THREE.BoxGeometry( 3, 3, 3 );
var boxMaterial = new THREE.MeshLambertMaterial({
map: texture,
overdraw: 10
});
var box = new THREE.Mesh( boxGeometry, boxMaterial );
box.castShadow = true;
scene.add(box);
}
Is it possible to add more images in the loader.load or do I have to use a different method?
You can just load an image with loader.load, and store it in a variable:
var loader = new THREE.TextureLoader();
var brick = loader.load('img/brick.jpg');
var occlusion = loader.load('img/ao.jpg'); //Example texture
//More textures here
You can then apply it like so:
var boxGeometry = new THREE.BoxGeometry( 3, 3, 3 );
var boxMaterial = new THREE.MeshLambertMaterial({
map: brick,
aoMap: occlusion, //An example use
overdraw: 10
});
var box = new THREE.Mesh( boxGeometry, boxMaterial );
box.castShadow = true;
scene.add(box);
Instead of loading the texture and using an anonymous callback, just load the texture, store it in a variable, then apply where needed.

spline not match ExtrudeGeometry in Three.js

I create a closed spline and extrude geometry with rectangle shape to create a track for my game. I use spline to calculate the position of my ship, but when I check, the spline does not match completely with the geometry. Is there something wrong?
shape used to extrude example
extrude geometry and spline not match
Here is my code:
var genTrack = function (lanes, controlPoints, material, isClose) {
//extrude setting
var extrudeSettings = {
bevelEnabled: true,
bevelSegments: 2,
steps: 200,
material: 1,
extrudeMaterial: 1
};
//track shape
var trackShape = new THREE.Shape([
new THREE.Vector2(-config.laneHeight/2, config.laneWidth/2),
new THREE.Vector2(-config.laneHeight/2, - config.laneWidth/2),
new THREE.Vector2(config.laneHeight/2, - config.laneWidth/2),
new THREE.Vector2(config.laneHeight/2, config.laneWidth/2),
]);
//spline
if (isClose)
var spline = new THREE.ClosedSplineCurve3(controlPoints);
else
var spline = new THREE.SplineCurve3(controlPoints);
utils.public('spline', spline);
//set path
extrudeSettings.extrudePath = spline;
//frenet
var frenet = new THREE.TubeGeometry.FrenetFrames(spline, 200, false)
extrudeSettings.frames = frenet;
utils.public('extrudeSettings', extrudeSettings);
//create geometry
var geometry = new THREE.ExtrudeGeometry(trackShape, extrudeSettings);
var splineGeo = new THREE.TubeGeometry(spline, 200, 1, 4, true, false);
utils.public('frenet', frenet);
var angle = 0;
var track = new THREE.Object3D();
track.matrixAutoUpdate = false;
track.receiveShadow = true;
for (var i=0; i< lanes; i++){
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(i * (config.laneSpan + config.laneWidth), -30, 0);
//mesh.rotation.set(0, 0,angle);
//angle += Math.PI/180 * 20;
track.add(mesh);
}
track.scale.set(1.5, 1.5, 1.5);
var splineMesh = new THREE.Mesh(splineGeo, new THREE.MeshBasicMaterial({color: 0xffffff}));
return {
'geometry': geometry,
'mesh': track,
'spline': spline,
'frenet': frenet,
'splineMesh': splineMesh,
'controlPoints' : controlPoints
};
}
I believe your problem is with this line:
mesh.position.set(i * (config.laneSpan + config.laneWidth), -30, 0);
I think what you want is something more like:
mesh.position.set(i * config.laneWidth / lanes, config.laneHeight / 2, 0);
I haven't tested it, but I think you need something like this.

Categories

Resources