I need to draw .obj file, without its loading. For example I have .obj file with follow content
v 0.1 0.2 0.3
v 0.2 0.1 0.5
vt 0.5 -1.3
vn 0.7 0.0 0.7
f 1 2 3
I read this file, parse content and have its data in a JavaScript object.
{
v: [
{x:0.1, 0.2, 0.3}
{x:0.2, 0.1, 0.5}
],
vt: [
{u: 0.5, v: -1.3}
],
vn: [
{x: 0.7, 0.0, 0.7}
],
f: [
// ...
]
}
Next I need to draw this data with three.js. I read documentation, but can't find any example or description how to do it. Who knows?
Is there any method for that purpose?
First question is, why wont you use THREE.ObjLoader ? The reason is not clear to me. There could be so much different test cases for loading obj file. Its better to use THREE.ObjLoader.
If you cant use that then
My preferred way would be to create a THREE.BufferGeometry. We are going to create some THREE.BufferAttribute from the arrays of your javascript object. One THREE.BufferAttribute for each vertex attribute. Also, we gonna set the index buffer. Here is a function to do it -
function make_3D_object(js_object) {
let vertices = new Float32Array(js_object.v);
let uvs = new Float32Array(js_object.vt);
let normals = new Float32Array(js_object.vn);
let indices = new Uint8Array(js_object.f);
// this is to make it 0 indexed
for(let i = 0; i < indices.length; i++)
indices[i]--;
let geom = new THREE.BufferGeometry();
geom.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geom.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
geom.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));
geom.setIndex(new THREE.BufferAttribute(indices, 1));
let material = new THREE.MeshPhongMaterial( {
map: js_object.texture, // assuming you have texture
color: new THREE.Color().setRGB(1, 1, 1),
specular: new THREE.Color().setRGB(0, 0,0 )
} );
let obj_mesh = new THREE.Mesh(geom, material);
return obj_mesh;
}
In this code i have assumed you have only a single body, a single material with only a texture. Also this code is not tested.
Related
I want to create a grid of, let's say 500x500, and I want it to be able to be curved in certain places (think of it as space-time plane that's curved due to gravity). I'm stuck at the start.
This is what I found on the documentation:
// Create a sine-like wave
const curve = new THREE.SplineCurve( [
new THREE.Vector2( -10, 0 ),
new THREE.Vector2( -5, 5 ),
new THREE.Vector2( 0, 0 ),
new THREE.Vector2( 5, -5 ),
new THREE.Vector2( 10, 0 )
] );
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
// Create the final object to add to the scene
const splineObject = new THREE.Line( geometry, material );
I think this should be working but it doesn't. I don't know how to create a multiple lines from here. I tried to handle some array but I didn't know where or how. I have done my research but I can't make any headway.
I have another question: Is that this is a Vector2 I need to make it 3d for that work? There a lot of other classes like CatmullRomCurve3, CubicBezierCurve3, etc, but the problem still is that i need to make an array to create all the vectors and lines.
--
EDIT i created a code for the grid lines but the curve probleme still the same
let size = 12, step = 1;
const geometry = new THREE.BufferGeometry();
// create a simple square shape. We duplicate the top left and bottom right
// vertices because each vertex needs to appear once per triangle.
const vertices = [];
for(var i = - size; i <= size; i += step) {
vertices.push( - size, - 0.4, i);
vertices.push( size, - 0.4, i);
vertices.push( i, - 0.4, - size);
vertices.push( i, - 0.4, size);
}
let positionAttribute = new THREE.Float32BufferAttribute(vertices, 3);
geometry.setAttribute("position", positionAttribute);
let lines = new THREE.LineSegments(geometry, new THREE.LineBasicMaterial());
I have loaded .obj using OBJLoader2 and also with its .mtl , now when user click on one of Mesh, then i want to change mesh geometry such like that it divides into two equal parts and also have different material for them.
//this.currentobj represents the user clicked mesh.
let geometry = this.currentobj.geometry;
geometry.clearGroups();
geometry.addGroup( 0, Infinity, 0 );
geometry.addGroup( 0, Infinity, 1 );
geometry.addGroup( 0, Infinity, 2 );
geometry.addGroup( 0, Infinity, 3 );
let material0 = new THREE.MeshBasicMaterial({color: 0xff0000});
let material1 = new THREE.MeshBasicMaterial({color: 0x444444});
let material2 = new THREE.MeshBasicMaterial({color: 0x111111});
let material3 = new THREE.MeshBasicMaterial({color: 0x555555});
var materials = [ material0, material1, material2, material3 ];
let mesh = new THREE.Mesh(geometry, materials);
this.scene.add(mesh);
Dividing mesh is a solved problem in three.js. It was recently revised with a new implementation in Jun by #Manthrax and mrdoob requested it be pulled to main as the original csg solution had issues, as per this thread: https://discourse.threejs.org/t/looking-for-updated-plug-in-for-csg/6785/8
I do not know the current status of main, but Manthrax's library is available here: https://github.com/manthrax/THREE-CSGMesh with example code.
The operation returns the resulting mesh collection and the material objects can be modified individually. My own tangentially related question was answered here by Manthrax in April: Threecsg flat sides when expecting volumetric result It shows two different materials on the resulting cut of a sphere and a cube.
For example:
function doCSG(a,b,op,mat){
var bspA = CSG.fromMesh( a );
var bspB = CSG.fromMesh( b );
var bspC = bspA[op]( bspB );
var result = CSG.toMesh( bspC, a.matrix );
result.material = mat;
result.castShadow = result.receiveShadow = true;
return result;
}
var meshA = new THREE.Mesh(new THREE.BoxGeometry(1,1,1));
var meshB = new THREE.Mesh(new THREE.BoxGeometry(1,1,1));
meshB.position.add(new THREE.Vector3( 0.5, 0.5, 0.5);
var meshC = doCSG( meshA,meshB, 'subtract',meshA.material);
console.log(meshC.material);//mesh C result has it's own material derived from meshA but can be new Material.
In your case you'd want to use the bounding box helper to produce a mesh that you move half way into the object and then use that to cut your geometry in half.
I'm making a custom three.js geometry for non-orthogonal cubes. It is loosely based on the existing Box-geometry in three.js, but greatly simplified insofar that it only supports one segment per side and also has the absolute position of its vertices fed directly to it.
I have problems both in wire frame rendering and texture rendering. In wire frame rendering I only get to see one of the six sides, as can be seen here:
This is the snippet that I use for setting the material:
if (woodTexture) {
texture = THREE.ImageUtils.loadTexture( 'crate.gif' );
texture.anisotropy = makeRenderer.renderer.getMaxAnisotropy();
material = new THREE.MeshBasicMaterial( { map: texture } );
} else {
material = new THREE.MeshBasicMaterial( { color: color, wireframe: true, side: THREE.DoubleSide } );
}
I know for sure the path for crate.gif is valid, as it works for Box geometries.
Here follows my faulty geometry. The 'quadruplets' array contains six arrays with each four Vector3 instances. Each inner array delineates a side of the cube.
THREE.Box3Geometry = function (quadruplets, debug) {
THREE.Geometry.call(this);
var constructee = this; // constructee = the instance currently being constructed by the Box3Geometry constructor
buildPlane(quadruplets[0], 0, debug); // px
buildPlane(quadruplets[1], 1); // nx
buildPlane(quadruplets[2], 2); // py
buildPlane(quadruplets[3], 3); // ny
buildPlane(quadruplets[4], 4); // pz
buildPlane(quadruplets[5], 5); // nz
function buildPlane(quadruplet, materialIndex, debug) {
// populate the vertex array:
constructee.vertices.push(quadruplet[0]);
constructee.vertices.push(quadruplet[1]);
constructee.vertices.push(quadruplet[2]);
constructee.vertices.push(quadruplet[3]);
// construct faceVertexUvs:
var uva = new THREE.Vector2(0, 1);
var uvb = new THREE.Vector2(0, 0);
var uvc = new THREE.Vector2(1, 0);
var uvd = new THREE.Vector2(1, 1);
// construct faces:
var a = 0; // vertex: u:50, v:50
var b = 2; // vertex: u:50, v:-50
var c = 3; // vertex: u:-50, v:-50
var d = 1; // vertex: u:-50, v:50
// construct normal:
var pv0 = quadruplet[1].clone().sub(quadruplet[0]); // pv = plane vector
var pv1 = quadruplet[2].clone().sub(quadruplet[0]);
normal = new THREE.Vector3(0,0,0).crossVectors(pv0, pv1).normalize();;
var face1 = new THREE.Face3(a, b, d);
face1.normal.copy(normal);
face1.vertexNormals.push(normal.clone(), normal.clone(), normal.clone());
face1.materialIndex = materialIndex;
constructee.faces.push(face1);
constructee.faceVertexUvs[ 0 ].push([ uva, uvb, uvd ]);
var face2 = new THREE.Face3(b, c, d);
face2.normal.copy(normal);
face2.vertexNormals.push(normal.clone(), normal.clone(), normal.clone());
face2.materialIndex = materialIndex;
constructee.faces.push(face2);
constructee.faceVertexUvs[ 0 ].push([ uvb.clone(), uvc, uvd.clone() ]);
}
this.mergeVertices();
};
THREE.Box3Geometry.prototype = Object.create(THREE.Geometry.prototype);
And this is the Box geometry from which I was "inspired".
You build a nice array of vertices, but give every face1/face2 combo the same set of indexes into that array: 0, 1, 2, 3. You essentially define the same quad 6 times.
What you need to do is keep a running base offset and add that to the vertex indices used to define each face. If you look at your BoxGeometry example, you'll that they do exactly that.
I have the following situation: I need to draw a Line with holes (a discontinuous line). That means that my Line consists of several segments which are not combined visually but they belong together in some other context. These segments consists of more than just two points, so not the way like THREE.LinePieces works.
At this time, I am using a BufferGeometry to store my vertices. A colleague told me, that in WebGL it is possible to create two arrays additional to the vertices: one which contains the indices of the vertices and one which contains the order of how the vertices should be combined.
Here an example of what I mean:
indices = [0,1,2,3,4,5]
vertices = [x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, x5, y5, z5]
order = [0,1,1,2,3,4,4,5]
With this I would get two lines: the first one from Point 0 over 1 to 2, then a hole, then a second line from 3 over 4 to 5.
So something like this:
.___.___. .___.___.
0 1 2 3 4 5
I am not familiar with WebGL, so I'm trusting my colleague that it is possible to create such a construct. But is this also possible with Three.js? If yes, how do you do it?
EDIT:
I talked once more to my colleague and I got this code snippet
indexBufferData = [0,1,1,2,3,4,4,5];
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER,
indexBufferData.limit() * Buffers.SIZEOF_INT,
indexBufferData, GL.GL_STATIC_DRAW);
He said I only have to duplicate the indices and NOT the vertices (would also be possible but not recommended) to get line segments.
So I searched in the WebGLRenderer and saw on line 2380 that if there is an attribute index in my BufferGeometry, the necessary buffer will be created. But setting this attribute has no effect. When using THREE.LinePieces it is still connecting only two points.
A code example and a fiddle to play around with.
// .___.___.___. .___.
// 0 1 2 3 4 5
// line material
var material = new THREE.LineBasicMaterial({
color: 0xffffff
});
vertices = [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(10, 0, 0),
new THREE.Vector3(20, 0, 0),
new THREE.Vector3(30, 0, 0),
new THREE.Vector3(40, 0, 0),
new THREE.Vector3(50, 0, 0)
];
var positions = new Float32Array(vertices.length * 3);
for (var i = 0; i < vertices.length; i++) {
positions[i * 3] = vertices[i].x;
positions[i * 3 + 1] = vertices[i].y;
positions[i * 3 + 2] = vertices[i].z;
}
indices = [0, 1, 1, 2, 2, 3, 4, 5];
var geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setIndex(new THREE.BufferAttribute(new Uint16Array(indices), 1));
var line = new THREE.LineSegments(geometry, material);
scene.add(line);
If you are trying to draw a series of connected line segments, followed by a gap, and then another series of connected line segments, you use THREE.LineSegments for that.
For example, this is the pattern for a line with three segments, followed with a line with one segment:
v0, v1, v1, v2, v2, v3, v4, v5
Looks like this:
.___.___.___. .___.
0 1 2 3 4 5
three.js r.91
Can I bind two different shapes together as one shape?
For example, binding sphere and cylinder together as one?
Kind of, yes. There are multiple options:
via hierarchy you can simply add one mesh to another using the add() function
via the GeometryUtil's merge() function to merge vertices and meshes of two Geometry objects into one
using a basic 3D editor that supports Boolean operations between meshes and exporting.
Method 1 is pretty straightforward:
var sphere = new THREE.Mesh(new THREE.SphereGeometry(100, 16, 12), new THREE.MeshLambertMaterial({ color: 0x2D303D, wireframe: true, shading: THREE.FlatShading }));
var cylinder = new THREE.Mesh(new THREE.CylinderGeometry(100, 100, 200, 16, 4, false), new THREE.MeshLambertMaterial({ color: 0x2D303D, wireframe: true, shading: THREE.FlatShading } ));
cylinder.position.y = -100;
scene.add(sphere);
scene.add(cylinder);
Notice that 16 is repeated, so the subdivisions level in one mesh matches the other (for a decent look).
Method 2.1 - via GeometryUtils
// Make a sphere
var sg = new THREE.SphereGeometry(100, 16, 12);
// Make a cylinder - ideally the segmentation would be similar to predictable results
var cg = new THREE.CylinderGeometry(100, 100, 200, 16, 4, false);
// Move vertices down for cylinder, so it maches half the sphere - offset pivot
for(var i = 0 ; i < cg.vertices.length; i++)
cg.vertices[i].position.y -= 100;
// Merge meshes
THREE.GeometryUtils.merge(sg, cg);
var mesh = new THREE.Mesh(sg, new THREE.MeshLambertMaterial({ color: 0x2D303D, wireframe: true, shading: THREE.FlatShading }));
scene.add(mesh);
Method 2.2 merging a Lathe half-sphere and a cylinder:
var pts = []; // Points array
var detail = .1; // Half-circle detail - how many angle increments will be used to generate points
var radius = 100; // Radius for half_sphere
var total = Math.PI * .51;
for(var angle = 0.0; angle < total ; angle+= detail) // Loop from 0.0 radians to PI (0 - 180 degrees)
pts.push(new THREE.Vector3(0,Math.cos(angle) * radius,Math.sin(angle) * radius)); // Angle/radius to x,z
var lathe = new THREE.LatheGeometry(pts, 16); // Create the lathe with 12 radial repetitions of the profile
// Rotate vertices in lathe geometry by 90 degrees
var rx90 = new THREE.Matrix4();
rx90.setRotationFromEuler(new THREE.Vector3(-Math.PI * .5, 0, 0));
lathe.applyMatrix(rx90);
// Make cylinder - ideally the segmentation would be similar for predictable results
var cg = new THREE.CylinderGeometry(100, 100, 200, 16, 4, false);
// Move vertices down for cylinder, so it maches half the sphere
for(var i = 0 ; i < cg.vertices.length; i++)
cg.vertices[i].position.y -= 100;
// Merge meshes
THREE.GeometryUtils.merge(lathe, cg);
var mesh = new THREE.Mesh(lathe, new THREE.MeshLambertMaterial({ color: 0x2D303D, wireframe: true, shading: THREE.FlatShading}));
mesh.position.y = 150;
scene.add(mesh);
The one problem I can't address at the moment comes from the faces that are inside the mesh. Ideally, those would have normals flipped, so they wouldn't render, but I haven't found a quick solution for that.
The third is fairly straightforward. Most 3D packages allow Boolean operation on meshes (e.g., merging two meshes together with the ADD operation (meshA + meshB)). Try creating a cylinder and a sphere in Blender (free and opensource), which already has a Three.js exporter. Alternatively you can export an .obj file of the merged meshes from your 3D editor or choice and use the convert_obj_three script.
I've found yet another method, which might be easier/more intuitive. Remember the Boolean operations I've mentioned above?
It turns out there is an awesome JavaScript library just for that: Constructive Solid Geometry:
Chandler Prall wrote some handy functions to connect CSG with three.js. So with the CSG library and the Three.js wrapper for it, you can simply do this:
var cylinder = THREE.CSG.toCSG(new THREE.CylinderGeometry(100, 100, 200, 16, 4, false), new THREE.Vector3(0, -100, 0));
var sphere = THREE.CSG.toCSG(new THREE.SphereGeometry(100, 16, 12));
var geometry = cylinder.union(sphere);
var mesh = new THREE.Mesh(THREE.CSG.fromCSG(geometry), new THREE.MeshNormalMaterial());
Which gives you a nice result (no problems with extra faces/flipping normals, etc.):