Proper pattern for merging curved lines into one geometry? - javascript

I've got thousands of sparsely arranged curved lines (made with CubicBezierCurve3) being merged into one geometry for obvious performance reasons.
Is it possible to feed them all into a single THREE.Line without the interconnecting segments becoming connected? Or make those interconnecting line segments invisible?
LinePieces/LineSegments (line strip) would work, but it would double the number of vertices and doesn't seem like the right approach..

So yes you can in fact send over NaN to instruct OpenGL to jump. Then just give three.js a bogus empty bounding sphere (or do a proper calculation of if). The bogus bounding sphere will mess up normal calculation, which didn't matter in my use but might in others'. Here's the pseudocode solution:
var positions = [];
for(....)
{
...
var pts = curve.getPoints(...);
for(var p = 0; p < pts.length; p++)
positions.push(pts[p].x, pts[p].y, pts[p].z);
positions.push(NaN, NaN, NaN);
}
var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array(positions), 3, true ) );
geometry.boundingSphere = new THREE.Sphere();

Related

Expand or make a THREE.LineSegments thicker

I'm working on visualizing paths of lines in Three.JS and have successfully added a bunch of lines to the scene with the correct vertices, and material that I want but the lines are hard to see. Is there a way to convert a line segment into a tube of sorts without having to start from scratch and change the type of geometry I'm using?
I may not be using the correct terminology but I basically want to turn a generated THREE.LineSegments() into a thicker line in 3D. Below is a snippet of my code:
var geo = new THREE.BufferGeometry();
geo.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2*numTravelVertices), 3));
var travelVertices = geo.attributes.position.array;
var vertIndex = 0;
this.set('travelVertices', travelVertices);
<add vertex indicies for points on the path>
geo.rotateX(-Math.PI / 2);
var mat = new THREE.LineBasicMaterial({color: parseInt(this.get('travelColor')), transparent: false});
var lineSegments = new THREE.LineSegments(geo, new THREE.MultiMaterial([mat]));
You can draw thick lines by setting the LineBasicMaterial linewidth parameter:
material.linewidth = 4; // default is 1
This currently does not work on some Windows platforms. So an alternate solution is to use the thrid-party class THREE.MeshLine, which renders thick lines by drawing a strip of triangles.
You can use THREE.TubeGeometry, but that would not be as performant as MeshLine.
three.js r.82

Three.js: Updating Geometries vs Replacing

I have a scene with lots of objects using ExtrudeGeometry. Each of these need to update each frame, where the shape that is being extruded is changing, along with the amount of extrusion. The shapes are being generated using d3's voronoi algorithm.
See example.
Right now I am achieving this by removing every object from the scene and redrawing them each frame. This is very costly and causing performance issues. Is there a way to edit each mesh/geometry instead of removing from the scene? Would this help with performance? Or is there a more efficient way of redrawing the scene?
I'd need to edit both the shape of the extrusion and the amount of extrusion.
Thanks for taking a look!
If you're not changing the number of faces, you can use morph targets http://threejs.org/examples/webgl_morphtargets.html
You should
Create your geometry
Clone the geometry and make your modifications to it, such as the maximum length of your geometry pillar
Set both geometries as morph targets to your base geometry, for example
baseGeo.morphTargets.push(
{ name: "targetName", vertices: [ modifiedVertexArray ] }
);
After that, you can animate the mesh this using mesh.updateMorphTargets()
See http://threejs.org/examples/webgl_morphtargets.html
So I managed to come up with a way of not having to redraw the scene every time and it massively improved performance.
http://jsfiddle.net/x00xsdrt/4/
This is how I did it:
Created a "template geometry" with ExtrudeGeometry using a dummy
10 sided polygon.
As before, created a bunch of "points", this time assigning each
point one of these template geometries.
On each frame, iterated through each geometry, updating each vertex
to that of the new one (using the voronoi alg as before).
If there are extra vertices left over, "bunch" them up into a single point. (see http://github.com/mrdoob/three.js/wiki/Updates.)
Looking at it now, it's quite a simple process. Before, the thought of manipulating each vertex seemed otherworldly to me, but it's not actually too tricky with simple shapes!
Here's how I did the iteration, polycColumn is just a 2 item array with the same polygon in each item:
// Set the vertex index
var v = 0;
// Iterate over both top and bottom of poly
for (var p=0;p<polyColumn.length;p++) {
// Iterate over half the vertices
for (var j=0;j<verts.length/2;j++) {
// create correct z-index depending on top/bottom
if (p == 1) {
var z = point.extrudeAmount;
} else {
var z = 0;
}
// If there are still legitimate verts
if (j < poly.length) {
verts[v].x = poly[j][0];
verts[v].y = poly[j][1];
verts[v].z = z;
// If we've got extra verts, bunch them up in the same place
} else {
verts[v].x = verts[v - 1].x;
verts[v].y = verts[v - 1].y;
verts[v].z = z;
}
v++;
}
}
point.mesh.geometry.verticesNeedUpdate = true;

Remove adjoining faces in three.js

I'm trying to optimize a scene where I'm rendering cubes based off of an image's pixel data:
http://jsfiddle.net/majman/4sukB/
The code simply checks each pixel in an image and creates & positions a cube mesh accordingly.
However, as you can see if you toggle wireframes on, there is an abundance of unnecessary internal faces.
I am using mergeVertices as well as THREE.GeometryUtils.merge - so things are partially optimized.
I ran across this approach of comparing all the faces of merged geometry, but because each cube face is now a pair of tri's - they are difficult to compare as the two triangles of adjoining faces will be flipped.
I've also looked at the minecraft example, but I havne't been able to wrap my head around that approach.
Ok, with WestLangley's help - I was able to get there.
http://jsfiddle.net/majman/4sukB/2/
Took some fiddling to figure out which faces to adjust within buildPlane. After that, comparing centroids was relatively straight forward:
function removeDuplicateFaces(geometry){
for(var i=0; i<geometry.faces.length; i++){
var centroid = geometry.faces[i].centroid;
for(var j=0; j < i; j++){
var f2 = geometry.faces[j];
if( f2 !== undefined ){
var centroid2 = f2.centroid;
if(centroid.equals(centroid2)){
delete geometry.faces[i];
delete geometry.faces[j];
}
}
}
}
geometry.faces = geometry.faces.filter( function(a){ return a!== undefined });
return geometry;
}

Face normals on dynamic geometry

I'm trying to create a vertex animation for a mesh.
Just imagine a vertex shader, but in software instead of hardware.
Basically what I do is to apply a transformation matrix to each vertex. The mesh it's ok but the normals doesn't look good at all.
I've try to use both computeVertexNormals() and computeFaceNormals() but it just doesn't work.
The following code is the one I used for the animation (initialVertices are the initial vertices generated by the CubeGeometry):
for (var i=0;i<mesh1.geometry.vertices.length; i++)
{
var vtx=initialVertices[i].clone();
var dist = vtx.y;
var rot=clock.getElapsedTime() - dist*0.02;
matrix.makeRotationY(rot);
vtx.applyMatrix4(matrix);
mesh1.geometry.vertices[i]=vtx;
}
mesh1.geometry.verticesNeedUpdate = true;
Here there're two examples, one working correctly with CanvasRenderer:
http://kile.stravaganza.org/lab/js/dynamic/canvas.html
and the one that doesn't works in WebGL:
http://kile.stravaganza.org/lab/js/dynamic/webgl.html
Any idea what I'm missing?
You are missing several things.
(1) You need to set the ambient reflectance of the material. It is reasonable to set it equal to the diffuse reflectance, or color.
var material = new THREE.MeshLambertMaterial( {
color:0xff0000,
ambient:0xff0000
} );
(2) If you are moving vertices, you need to update centroids, face normals, and vertex normals -- in the proper order. See the source code.
mesh1.geometry.computeCentroids();
mesh1.geometry.computeFaceNormals();
mesh1.geometry.computeVertexNormals();
(3) When you are using WebGLRenderer, you need to set the required update flags:
mesh1.geometry.verticesNeedUpdate = true;
mesh1.geometry.normalsNeedUpdate = true;
Tip: is it a good idea to avoid new and clone in tight loops.
three.js r.63

Applying Textures to Non-Cube Polyhedra with Three.js

I am using Three.js to generate a polyhedron with differing colors and text on each face, generated from a canvas element. For now, I'm sticking with polyhedra for which Three.js includes native classes, but at some point, I'd like to branch out into more irregular shapes.
There are a number of examples available online (including StackOverflow posts, like Three.js cube with different texture on each face) that explain how to do this with cubes. I haven't succeeded in finding any samples that show the same technique applied to non-cubes, but for the most part, the same process that works for CubeGeometry also works for TetrahedronGeometry and so forth.
Here's a simplified version of the code I'm using to generate the polyhedron:
switch (shape) {
case "ICOSAHEDRON" :
// Step 1: Create the appropriate geometry.
geometry = new THREE.IcosahedronGeometry(PolyHeatMap.GEOMETRY_CIRCUMRADIUS);
// Step 2: Create one material for each face, and combine them into one big
// MeshFaceMaterial.
material = new THREE.MeshFaceMaterial(createMaterials(20, textArray));
// Step 3: Pair each face with one of the materials.
for (x = 0; face = geometry.faces[x]; x++)
{
face.materialIndex = x;
}
break;
// And so on, for other shapes.
}
function createTexture (title, color) {
var canvas = document.createElement("canvas");
// Magical canvas generation happens here.
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return new THREE.MeshLambertMaterial({ map : texture });
}
function createMaterials (numFacets, textArray)
{
var materialsArray = [],
material;
for (var x = 0, xl = numFacets; x < xl; x++)
{
material = createTexture(textArray[x], generateColor(textArray[x]));
material.side = THREE.DoubleSide;
materials.push(oMaterial);
}
return materials;
}
Cubes render perfectly using this technique, but with other polyhedra, the textures do not behave as expected:
It's hard to explain precisely what's happening here. Essentially, each face is displaying the correct texture, but the texture itself has been stretched and shifted as if to cover the entire polyhedron. In other words - looking at the shape dead-on - the upper-left face is only showing the upper-left portion of its texture, the upper-right face is only showing the upper-right portion, and so on.
The faces on the opposite side of the polyhedron shows no texture detail at all; only colors.
I had no experience with 3D rendering prior to experimenting with Three.js, so I imagine that there's some step I'm missing that is handled automatically by CubeGeometry but not its sister classes. I'd refer to other examples that have been posted, but most examples are rendering cubes, and those that don't are usually using solid colors.
What needs to happen for the textures on the non-cube shapes to be scaled and centered properly?
You need to set new UVs.
I made a simple example how to do it, don't know if it's the best way.
jsFiddle example
Update
geometry.faceVertexUvs[0] = [];
for(var i = 0; i < geometry.faces.length; i++){
// set new coordinates, all faces will have same mapping.
geometry.faceVertexUvs[0].push([
new THREE.Vector2( 0,0 ),
new THREE.Vector2( 0,1 ),
new THREE.Vector2( 1,1),
]);
}

Categories

Resources