three.js r74 BufferGeometry Sphere Instead of Squares - javascript

I have the following code:
var geometry = new THREE.BufferGeometry(4, 4, 4);
var length = parsedData.length;
var positions = new Float32Array(length * 3);
var colors = new Float32Array(length * 3);
var color = new THREE.Color();
var i = 0;
for (i; i < length * 3; i += 3) {
var index = Math.floor(i / 3);
positions[i] = parsedData[index].vector.x;
positions[i + 1] = parsedData[index].vector.y;
positions[i + 2] = parsedData[index].vector.z;
color.setHex(parsedData[index].color);
colors[i] = color.r;
colors[i + 1] = color.g;
colors[i + 2] = color.b;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
var material = new THREE.PointsMaterial({vertexColors: THREE.VertexColors});
var particleSystem = new THREE.Points(geometry, material);
scene.add(particleSystem);
render();
Which will render cubes quickly and fine, but I need spheres. Could anyone explain to me how that works with Revision 74? I have found this question, however it isn't working anymore.
Thanks!

Related

How to detect what side of a cube is clicked

Right now, I am trying to make a navigational menu, but to do this, I need to detect what side is clicked by the user. Is there any way to do this with raycasting, or if not, any other way?
Here is my code if you need it:
CodePen Link
The short version is here
var geometry = new THREE.BoxGeometry(200, 200, 200);
var material = new THREE.MeshLambertMaterial(
{
color: 65535,
morphTargets: true
});
for (var i = 0; i < 8; i++)
{
var vertices = [];
for (var v = 0; v < geometry.vertices.length; v++)
{
vertices.push(geometry.vertices[v].clone());
if (v === i)
{
vertices[vertices.length - 1].x *= 2;
vertices[vertices.length - 1].y *= 2;
vertices[vertices.length - 1].z *= 2
}
}
geometry.morphTargets.push(
{
name: "target" + i,
vertices: vertices
})
}
mesh = new THREE.Mesh(geometry, material);
mesh.position.y = 0;
scene.add(mesh);
scene.background = new THREE.Color(15790320);
var params = {
influence1: 1,
influence2: 1,
influence3: 1,
influence4: 1,
influence5: 1,
influence6: 1,
influence7: 1,
influence8: 1
};
var geometry = new THREE.PlaneBufferGeometry(5e3, 5e3);
geometry.rotateX(-Math.PI / 2);
var material = new THREE.MeshBasicMaterial(
{
color: 975132,
overdraw: .5
});
onMouseDown(event) {
this.mouse.x = (event.pageX / window.innerWidth) * 2 - 1;
this.mouse.y = -(event.pageY / window.innerHeight) * 2 + 1;
this.raycaster.setFromCamera(this.mouse, this.camera);
let intersectCube = this.raycaster.intersectObjects( Cube , true );
}
Make a raycaster on your mouse and check for intersections with the Cube or its faces

How can i manipulate every object im creating? Three.js

Im creating a scene using three.js and im adding 3 spheres to it. Then im trying to switching all spheres created from wireframe to non-wireframe material. I not using scene.traverse() because i have more objects on my scene and i only want to switch the spheres, but with this code i can only switch one sphere. How can i get to every sphere? Any help? Thanks!
var numSpheres = 3;
function createSphere (x, y, z){
sphere = new THREE.Object3D();
material = new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true});
geometry = new THREE.SphereGeometry (2, 8, 8);
mesh = new THREE.Mesh(geometry, material);
sphere.add(mesh);
sphere.position.set(x, y, z);
scene.add(sphere);
}
createSpheres(numSpheres){
for(i = 1; i <= numSpheres; i++){
var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
createSphere(randomnumber1, 3, randomnumber2);
}
}
function onKeyDown(e){
case 65:
case 97:
sphere.traverse(function (node){
if(node instanceof THREE.mesh) {
node.material.wireframe = !node.material.wireframe;
}
});
As #prisoner849 suggested, put your objects you want to manipulate in an array or map (as #prisoner849 suggested). This way, you avoid the test instanceof THREE.Mesh and you only manipulate the objects you want to manipulate.
var numSpheres = 3;
var spheresMap = {}; // OR
var spheresArray = [];
function createSphere (x, y, z){
var sphere = new THREE.Object3D();
material = new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true});
geometry = new THREE.SphereGeometry (2, 8, 8);
mesh = new THREE.Mesh(geometry, material);
sphere.add(mesh);
sphere.position.set(x, y, z);
scene.add(sphere);
spheresMap[sphere.id] = sphere; // OR
spheresArray.push(sphere);
}
createSpheres(numSpheres){
for(i = 1; i <= numSpheres; i++){
var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
createSphere(randomnumber1, 3, randomnumber2);
}
}
function onKeyDown(e){
case 65:
case 97:
for (var key in spheresMap) {
spheresMap[key].material.wireframe = !spheresMap[key].material.wireframe;
}
// OR
for (var i=0; i<spheresArray.length; i++) {
spheresArray[i].material.wireframe = !spheresArray[i].material.wireframe;
}
}
If You can reach your spheres one by one in the future, most relative is array in object:
function createSphere (x, y, z){
var sphere= new THREE.Mesh(new THREE.SphereGeometry (2, 8, 8), new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true}));
scene.add(sphere);
sphere.position.set(x, y, z);
return sphere;
}
mySpheres = {};
mySpheres.models = [];
mySpheres.materials = [];
for(i = 1; i <= 3; i++){
var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var obj = createSphere(randomnumber1, 3, randomnumber2); //
var id = obj.id; // or whartever (redone,barrack,donald,george)
mySpheres.models[id] = obj;
mySpheres.materials.push(obj.material);
}
//after that you can do
mySpheres.models['donald'].translateX(10);
//or
mySpheres.models['george'].material.opacity = 0.5;
//or
mySpheres.materials.forEach(function(m) {
m.opacity = 0.5;
});

Three.js render white part of plain geometry

I'm trying to turn this plainGeometry, into this (sort of mask).
This code works: (to sum-up, create two materials, divide the plane to segments and decide for each one which material is it with MeshFaceMaterial)
Button.onClick(function () {
var obj = editor.selected;
var material = obj.material;
var tex = material.map;
var objHeight = obj.geometry.parameters.height;
var objWidth = obj.geometry.parameters.width;
var texHeight = tex.image.height;
var texWidth = tex.image.width;
var geometry = new THREE.PlaneGeometry(objWidth, objHeight, objWidth, objHeight);
var facesNum = objHeight * objWidth * 2;
var facesX = objWidth * 2;
var facesInX = texWidth * 2;
var materials = [];
materials.push(material);
materials.push(new THREE.MeshBasicMaterial({ }));
for (var i = 0; i < facesNum; i++) {
if ((i % facesX >= objWidth - texWidth) &&
(i % facesX <= (facesInX + objWidth - texWidth - 1)) &&
(i <= (texHeight * objWidth * 2) - 1)) {
geometry.faces[i].materialIndex = 0;
}
else {
geometry.faces[i].materialIndex = 1;
}
}
obj.geometry = geometry;
obj.material = new THREE.MeshFaceMaterial(materials);
editor.signals.materialChanged.dispatch(obj);
});
But I'm wondering if there is a simpler way to go. Any suggestions?
Another way to do this is to use an alpha channel on your texture. You can do this with Gimp or Photoshop.
You then duplicate the mesh and push it just a tad out the axis with polygonOffsetFactor on the material. Apply the background material to the first mesh, and the foreground material with the texture with alpha to the second.
See this fiddle alphaTest. (you may need to disable cross-domain access security so the texture can load in this fiddle, chrome will allow this if you run it with the --disable-web-security flag)
The advantage to this method is that the image can be of any shape and location, and doesn't need to fit into a geometry face.
Another way, if the geometry you were using is complicated, is to use Three.DecalGeometry to cut a mesh piece out and use it shifted a bit with polygonOffsetFactor on the material. See the three.js decals example for this.
Source for the example fiddle is below:
var renderer;
var pointLight;
var scene;
var plane1;
var plane2;
function addPlane()
{
var material1 = new THREE.MeshPhongMaterial({ color: 0xFFFFFF });
var material2;
var loader = new THREE.TextureLoader();
loader.load('http://i.imgur.com/ETdl4De.png',
function ( texture ) {
var material2 = new THREE.MeshPhongMaterial({
color: 0xFFFFFF,
map: texture,
alphaTest: 0.7,
polygonOffset: true,
polygonOffsetFactor: - 4,
});
var geometry1 = new THREE.PlaneGeometry(12, 12, 12, 12);
var geometry2 = geometry1.clone();
plane1 = new THREE.Mesh(geometry1,material1);
plane2 = new THREE.Mesh(geometry2,material2);
scene.add(plane2);
scene.add(plane1);
}
);
}
(function() {
'use strict';
scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 10000);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
addPlane();
camera.position.z = 52;
pointLight = new THREE.DirectionalLight(0xffffff,1);
pointLight.position.x = 11;
pointLight.position.y = 5;
pointLight.position.z = 25;
scene.add(pointLight);
var reqAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
var render = function() {
reqAnimFrame(render);
renderer.render(scene, camera);
};
render();
}());
this did it, eventually:
var obj = editor.selected;
var tex = obj.material.map.;
var materials = [];
materials.push(new THREE.MeshBasicMaterial({ map: tex }));
materials.push(new THREE.MeshBasicMaterial({}));
var material = new THREE.MeshFaceMaterial(materials);
var objHeight = obj.geometry.parameters.height;
var objWidth = obj.geometry.parameters.width;
var texHeight = tex.image.height;
var texWidth = tex.image.width;
tex.repeat = new THREE.Vector2(3, 3);
tex.offset = new THREE.Vector2(0, 0);
var geometry = new THREE.PlaneGeometry(objWidth, objHeight, 3, 3);
var v = geometry.vertices;
var facesNum = geometry.faces.length;
v[1] = new THREE.Vector3(-texWidth / 2, objHeight / 2, 0);
v[2] = new THREE.Vector3(texWidth / 2, objHeight / 2, 0);
v[5] = new THREE.Vector3(-texWidth / 2, (objHeight / 2) - texHeight, 0);
v[6] = new THREE.Vector3(texWidth / 2, (objHeight / 2) - texHeight, 0);
v[9] = v[13];
v[10] = v[14];
v[4] = v[8] = v[12];
v[7] = v[11] = v[15];
for (var i = 0; i < facesNum; i++) {
if (i !== 2 && i !== 3) geometry.faces[i].materialIndex = 1;
}
obj.material = material;
obj.geometry = geometry;
editor.signals.materialChanged.dispatch(obj);

How to add faces to THREE.BufferGeometry?

I have created programmatically a simple mesh:
var CreateSimpleMesh = new function () {
var xy = [],
maxX = 7,
maxY = 10,
river = [[0, 5], [0, 4], [1, 3], [2, 2], [3, 2], [4, 1], [5, 1], [6, 0]],
grassGeometry = new THREE.BufferGeometry(),
grassVertexPositions = []
this.init = function () {
for (i = 0; i < maxX; i++) {
for (j = 0; j < maxY; j++) {
xy.push([i, j])
}
}
for (var i = 0; i < xy.length; i++) {
grassVertexPositions.push([xy[i][0], xy[i][1], 0])
grassVertexPositions.push([xy[i][0] + 1, xy[i][1], 0])
grassVertexPositions.push([xy[i][0], xy[i][1] + 1, 0])
grassVertexPositions.push([xy[i][0] + 1, xy[i][1] + 1, 0])
grassVertexPositions.push([xy[i][0], xy[i][1] + 1, 0])
grassVertexPositions.push([xy[i][0] + 1, xy[i][1], 0])
}
for (var i = 0; i < grassVertexPositions.length; i++) {
for (var j = 0; j < river.length; j++) {
if (river[j][0] == grassVertexPositions[i][0] && river[j][1] == grassVertexPositions[i][1]) {
grassVertexPositions[i][2] = -0.5
}
}
}
var grassVertices = new Float32Array(grassVertexPositions.length * 3)
for (var i = 0; i < grassVertexPositions.length; i++) {
grassVertices[i * 3 + 0] = grassVertexPositions[i][0];
grassVertices[i * 3 + 1] = grassVertexPositions[i][1];
grassVertices[i * 3 + 2] = grassVertexPositions[i][2];
}
grassGeometry.addAttribute('position', new THREE.BufferAttribute(grassVertices, 3))
var grassMaterial = new THREE.MeshLambertMaterial({color: 0x00ff00}),
grassMesh = new THREE.Mesh(grassGeometry, grassMaterial)
grassMesh.rotation.x = -Math.PI / 2
Test.getScene().add(grassMesh);
}
}
Problem is that this mesh has only vertices. I have tried to add to it faces like in this question using THREE.Shape.Utils.triangulateShape but BufferGeometry is different than normal geometry and it does not work. Is it possible to add faces to BufferGeometry?
EDIT:
Working fiddle
Here is how to create a mesh having BufferGeometry. This is the simpler "non-indexed" BufferGeometry where vertices are not shared.
// non-indexed buffer geometry
var geometry = new THREE.BufferGeometry();
// number of triangles
var NUM_TRIANGLES = 10;
// attributes
var positions = new Float32Array( NUM_TRIANGLES * 3 * 3 );
var normals = new Float32Array( NUM_TRIANGLES * 3 * 3 );
var colors = new Float32Array( NUM_TRIANGLES * 3 * 3 );
var uvs = new Float32Array( NUM_TRIANGLES * 3 * 2 );
var color = new THREE.Color();
var scale = 15;
var size = 5;
var x, y, z;
for ( var i = 0, l = NUM_TRIANGLES * 3; i < l; i ++ ) {
if ( i % 3 === 0 ) {
x = ( Math.random() - 0.5 ) * scale;
y = ( Math.random() - 0.5 ) * scale;
z = ( Math.random() - 0.5 ) * scale;
} else {
x = x + size * ( Math.random() - 0.5 );
y = y + size * ( Math.random() - 0.5 );
z = z + size * ( Math.random() - 0.5 );
}
var index = 3 * i;
// positions
positions[ index ] = x;
positions[ index + 1 ] = y;
positions[ index + 2 ] = z;
//normals -- we will set normals later
// colors
color.setHSL( i / l, 1.0, 0.5 );
colors[ index ] = color.r;
colors[ index + 1 ] = color.g;
colors[ index + 2 ] = color.b;
// uvs
uvs[ index ] = Math.random(); // just something...
uvs[ index + 1 ] = Math.random();
}
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
// optional
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
// set the normals
geometry.computeVertexNormals(); // computed vertex normals are orthogonal to the face for non-indexed BufferGeometry
See the three.js examples for many additional examples of creating BufferGeometry. Also check out the source code for PlaneGeometry and SphereGeometry, which are reasonably easy to understand.
three.js r.143
You can add faces using three.js internal function- fromBufferGeometry. In your case it would be something like this.
var directGeo = new THREE.Geometry();
directGeo.fromBufferGeometry(grassGeometry);
Then use directGeo to build your mesh, and it will have faces.

THREE.js generate UV coordinate

I am working on importing a model into a scene using the THREE.js OBJ loader.
I know that I am able to import the geometry fine, because when I assign a MeshNormalMaterial to it, it shows up great. However, if I use anything that requires UV coordinates, It gives me the error:
[.WebGLRenderingContext]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 1
I know this is because the loaded OBJ has no UV coordinates, but I was wondering if there was any way to generate the needed texture coordinates. I have tried
material.needsUpdate = true;
geometry.uvsNeedUpdate = true;
geometry.buffersNeedUpdate = true;
...but to no avail.
Is there any way to automagically generate UV textures using three.js, or do I have to assign the coordinates myself?
To my knowledge there is no automatic way to calculate UV.
You must calculate yourself. Calculate a UV for a plane is quite easy, this site explains how: calculating texture coordinates
For a complex shape, I don't know how. Maybe you could detect planar surface.
EDIT
Here is a sample code for a planar surface (x, y, z) where z = 0:
geometry.computeBoundingBox();
var max = geometry.boundingBox.max,
min = geometry.boundingBox.min;
var offset = new THREE.Vector2(0 - min.x, 0 - min.y);
var range = new THREE.Vector2(max.x - min.x, max.y - min.y);
var faces = geometry.faces;
geometry.faceVertexUvs[0] = [];
for (var i = 0; i < faces.length ; i++) {
var v1 = geometry.vertices[faces[i].a],
v2 = geometry.vertices[faces[i].b],
v3 = geometry.vertices[faces[i].c];
geometry.faceVertexUvs[0].push([
new THREE.Vector2((v1.x + offset.x)/range.x ,(v1.y + offset.y)/range.y),
new THREE.Vector2((v2.x + offset.x)/range.x ,(v2.y + offset.y)/range.y),
new THREE.Vector2((v3.x + offset.x)/range.x ,(v3.y + offset.y)/range.y)
]);
}
geometry.uvsNeedUpdate = true;
The other answers here were a great help but didn't quite fit my requirements to apply a repeating pattern texture to all sides of a shape with mostly flat surfaces. The problem is that using only the x and y components as u and v results in weird stretched textures on vertical surfaces.
My solution below uses surface normals to pick which two components (x, y and z) to map to u and v. It's still pretty crude but it works quite well.
function assignUVs(geometry) {
geometry.faceVertexUvs[0] = [];
geometry.faces.forEach(function(face) {
var components = ['x', 'y', 'z'].sort(function(a, b) {
return Math.abs(face.normal[a]) > Math.abs(face.normal[b]);
});
var v1 = geometry.vertices[face.a];
var v2 = geometry.vertices[face.b];
var v3 = geometry.vertices[face.c];
geometry.faceVertexUvs[0].push([
new THREE.Vector2(v1[components[0]], v1[components[1]]),
new THREE.Vector2(v2[components[0]], v2[components[1]]),
new THREE.Vector2(v3[components[0]], v3[components[1]])
]);
});
geometry.uvsNeedUpdate = true;
}
This function doesn't normalise the UVs to the size of the object. This works better when applying the same texture to different sized objects in the same scene. However depending on the size of your world coordinate system, you'll probably need to scale and repeat the texture as well:
texture.repeat.set(0.1, 0.1);
texture.wrapS = texture.wrapT = THREE.MirroredRepeatWrapping;
Box UV mapping is possibly most useful thing in three.js configurators of any sort, -
https://jsfiddle.net/mmalex/pcjbysn1/
The solution works per face both with indexed and non-indexed buffer geometries.
Example of usage:
//build some mesh
var bufferGeometry = new THREE.BufferGeometry().fromGeometry(new THREE.DodecahedronGeometry(2.5, 0));
let material = new THREE.MeshPhongMaterial({
color: 0x10f0f0,
map: new THREE.TextureLoader().load('http://mbnsay.com/rayys/images/1K_UV_checker.jpg')
});
//find out the dimensions, to let texture size 100% fit without stretching
bufferGeometry.computeBoundingBox();
let bboxSize = bufferGeometry.boundingBox.getSize();
let uvMapSize = Math.min(bboxSize.x, bboxSize.y, bboxSize.z);
//calculate UV coordinates, if uv attribute is not present, it will be added
applyBoxUV(bufferGeometry, new THREE.Matrix4().getInverse(cube.matrix), uvMapSize);
//let three.js know
bufferGeometry.attributes.uv.needsUpdate = true;
The example is based on the following implementation of applyBoxUV
function _applyBoxUV(geom, transformMatrix, bbox, bbox_max_size) {
let coords = [];
coords.length = 2 * geom.attributes.position.array.length / 3;
// geom.removeAttribute('uv');
if (geom.attributes.uv === undefined) {
geom.addAttribute('uv', new THREE.Float32BufferAttribute(coords, 2));
}
//maps 3 verts of 1 face on the better side of the cube
//side of the cube can be XY, XZ or YZ
let makeUVs = function(v0, v1, v2) {
//pre-rotate the model so that cube sides match world axis
v0.applyMatrix4(transformMatrix);
v1.applyMatrix4(transformMatrix);
v2.applyMatrix4(transformMatrix);
//get normal of the face, to know into which cube side it maps better
let n = new THREE.Vector3();
n.crossVectors(v1.clone().sub(v0), v1.clone().sub(v2)).normalize();
n.x = Math.abs(n.x);
n.y = Math.abs(n.y);
n.z = Math.abs(n.z);
let uv0 = new THREE.Vector2();
let uv1 = new THREE.Vector2();
let uv2 = new THREE.Vector2();
// xz mapping
if (n.y > n.x && n.y > n.z) {
uv0.x = (v0.x - bbox.min.x) / bbox_max_size;
uv0.y = (bbox.max.z - v0.z) / bbox_max_size;
uv1.x = (v1.x - bbox.min.x) / bbox_max_size;
uv1.y = (bbox.max.z - v1.z) / bbox_max_size;
uv2.x = (v2.x - bbox.min.x) / bbox_max_size;
uv2.y = (bbox.max.z - v2.z) / bbox_max_size;
} else
if (n.x > n.y && n.x > n.z) {
uv0.x = (v0.z - bbox.min.z) / bbox_max_size;
uv0.y = (v0.y - bbox.min.y) / bbox_max_size;
uv1.x = (v1.z - bbox.min.z) / bbox_max_size;
uv1.y = (v1.y - bbox.min.y) / bbox_max_size;
uv2.x = (v2.z - bbox.min.z) / bbox_max_size;
uv2.y = (v2.y - bbox.min.y) / bbox_max_size;
} else
if (n.z > n.y && n.z > n.x) {
uv0.x = (v0.x - bbox.min.x) / bbox_max_size;
uv0.y = (v0.y - bbox.min.y) / bbox_max_size;
uv1.x = (v1.x - bbox.min.x) / bbox_max_size;
uv1.y = (v1.y - bbox.min.y) / bbox_max_size;
uv2.x = (v2.x - bbox.min.x) / bbox_max_size;
uv2.y = (v2.y - bbox.min.y) / bbox_max_size;
}
return {
uv0: uv0,
uv1: uv1,
uv2: uv2
};
};
if (geom.index) { // is it indexed buffer geometry?
for (let vi = 0; vi < geom.index.array.length; vi += 3) {
let idx0 = geom.index.array[vi];
let idx1 = geom.index.array[vi + 1];
let idx2 = geom.index.array[vi + 2];
let vx0 = geom.attributes.position.array[3 * idx0];
let vy0 = geom.attributes.position.array[3 * idx0 + 1];
let vz0 = geom.attributes.position.array[3 * idx0 + 2];
let vx1 = geom.attributes.position.array[3 * idx1];
let vy1 = geom.attributes.position.array[3 * idx1 + 1];
let vz1 = geom.attributes.position.array[3 * idx1 + 2];
let vx2 = geom.attributes.position.array[3 * idx2];
let vy2 = geom.attributes.position.array[3 * idx2 + 1];
let vz2 = geom.attributes.position.array[3 * idx2 + 2];
let v0 = new THREE.Vector3(vx0, vy0, vz0);
let v1 = new THREE.Vector3(vx1, vy1, vz1);
let v2 = new THREE.Vector3(vx2, vy2, vz2);
let uvs = makeUVs(v0, v1, v2, coords);
coords[2 * idx0] = uvs.uv0.x;
coords[2 * idx0 + 1] = uvs.uv0.y;
coords[2 * idx1] = uvs.uv1.x;
coords[2 * idx1 + 1] = uvs.uv1.y;
coords[2 * idx2] = uvs.uv2.x;
coords[2 * idx2 + 1] = uvs.uv2.y;
}
} else {
for (let vi = 0; vi < geom.attributes.position.array.length; vi += 9) {
let vx0 = geom.attributes.position.array[vi];
let vy0 = geom.attributes.position.array[vi + 1];
let vz0 = geom.attributes.position.array[vi + 2];
let vx1 = geom.attributes.position.array[vi + 3];
let vy1 = geom.attributes.position.array[vi + 4];
let vz1 = geom.attributes.position.array[vi + 5];
let vx2 = geom.attributes.position.array[vi + 6];
let vy2 = geom.attributes.position.array[vi + 7];
let vz2 = geom.attributes.position.array[vi + 8];
let v0 = new THREE.Vector3(vx0, vy0, vz0);
let v1 = new THREE.Vector3(vx1, vy1, vz1);
let v2 = new THREE.Vector3(vx2, vy2, vz2);
let uvs = makeUVs(v0, v1, v2, coords);
let idx0 = vi / 3;
let idx1 = idx0 + 1;
let idx2 = idx0 + 2;
coords[2 * idx0] = uvs.uv0.x;
coords[2 * idx0 + 1] = uvs.uv0.y;
coords[2 * idx1] = uvs.uv1.x;
coords[2 * idx1 + 1] = uvs.uv1.y;
coords[2 * idx2] = uvs.uv2.x;
coords[2 * idx2 + 1] = uvs.uv2.y;
}
}
geom.attributes.uv.array = new Float32Array(coords);
}
function applyBoxUV(bufferGeometry, transformMatrix, boxSize) {
if (transformMatrix === undefined) {
transformMatrix = new THREE.Matrix4();
}
if (boxSize === undefined) {
let geom = bufferGeometry;
geom.computeBoundingBox();
let bbox = geom.boundingBox;
let bbox_size_x = bbox.max.x - bbox.min.x;
let bbox_size_z = bbox.max.z - bbox.min.z;
let bbox_size_y = bbox.max.y - bbox.min.y;
boxSize = Math.max(bbox_size_x, bbox_size_y, bbox_size_z);
}
let uvBbox = new THREE.Box3(new THREE.Vector3(-boxSize / 2, -boxSize / 2, -boxSize / 2), new THREE.Vector3(boxSize / 2, boxSize / 2, boxSize / 2));
_applyBoxUV(bufferGeometry, transformMatrix, uvBbox, boxSize);
}
The answers here are brilliant and helped me a lot.
Only one thing: If you are updating vertices, do not re-assign uvs, but set them, as in (scope is my geometry):
scope.updateUVs = (copy=true) => {
scope.computeBoundingBox();
var max = scope.boundingBox.max;
var min = scope.boundingBox.min;
var offset = new THREE.Vector2(0 - min.x, 0 - min.y);
var range = new THREE.Vector2(max.x - min.x, max.y - min.y);
if (!copy) {
scope.faceVertexUvs[0] = [];
}
var faces = scope.faces;
for (i = 0; i < scope.faces.length ; i++) {
var v1 = scope.vertices[faces[i].a];
var v2 = scope.vertices[faces[i].b];
var v3 = scope.vertices[faces[i].c];
var uv0 = new THREE.Vector2( ( v1.x + offset.x ) / range.x , ( v1.y + offset.y ) / range.y );
var uv1 = new THREE.Vector2( ( v2.x + offset.x ) / range.x , ( v2.y + offset.y ) / range.y );
var uv2 = new THREE.Vector2( ( v3.x + offset.x ) / range.x , ( v3.y + offset.y ) / range.y );
if (copy) {
var uvs =scope.faceVertexUvs[0][i];
uvs[0].copy(uv0);
uvs[1].copy(uv1);
uvs[2].copy(uv2);
} else {
scope.faceVertexUvs[0].push([uv0, uv1, uv2]);
}
}
scope.uvsNeedUpdate = true;
}
This is a general version that works for spherical mapping (yaw, pitch coordinates), see example here, (look at loadSuzanne function):
function assignUVs(geometry) {
geometry.faceVertexUvs[0] = [];
geometry.faces.forEach(function(face) {
var uvs = [];
var ids = [ 'a', 'b', 'c'];
for( var i = 0; i < ids.length; i++ ) {
var vertex = geometry.vertices[ face[ ids[ i ] ] ].clone();
var n = vertex.normalize();
var yaw = .5 - Math.atan( n.z, - n.x ) / ( 2.0 * Math.PI );
var pitch = .5 - Math.asin( n.y ) / Math.PI;
var u = yaw,
v = pitch;
uvs.push( new THREE.Vector2( u, v ) );
}
geometry.faceVertexUvs[ 0 ].push( uvs );
});
geometry.uvsNeedUpdate = true;
}

Categories

Resources