threejs Box UV Mapping
by realhunts
HTML
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>
<script src="https://rawcdn.githack.com/mrdoob/three.js/r101/examples/js/loaders/GLTFLoader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.4.0/gl-matrix-min.js"></script>
CSS
body {
overflow: hidden;
}
JavaScript
console.log(new THREE.Geometry)
function _applyBoxUV(geom, transformMatrix, bbox, bbox_max_size) {
let coords = [];
/* coords.length = 4* geom.attributes.position.array.length / 3 */;
console.log("length", geom.attributes.position.array.length / 3)
// geom.removeAttribute('uv');
if (geom.attributes.uv === undefined) {
geom.addAttribute('uv', new THREE.Float32BufferAttribute(coords, 2));
}
console.log(geom.index.array)
//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);
//console.log("jj", v0, v1)
//get normal of the face, to know into which cube side it maps better
let n0 = new THREE.Vector3();
n0.crossVectors(v1.clone().sub(v0), v1.clone().sub(v2)).normalize();
n0.x = Math.abs(n0.x);
n0.y = Math.abs(n0.y);
n0.z = Math.abs(n0.z);
const faceOri = quat.create();
quat.rotationTo( faceOri, [n0.x, n0.y, n0.z], [0, 0, 1] );
let avec = vec3.fromValues(v0.x, v0.y, v0.z);
vec3.transformQuat( avec, avec, faceOri );
v0.x = avec[0], v0.y = avec[1], v0.z = avec[2];
let bvec = vec3.fromValues(v1.x, v1.y, v1.z);
vec3.transformQuat( bvec, bvec, faceOri );
v1.x = bvec[0], v1.y = bvec[1], v1.z = bvec[2];
let cvec = vec3.fromValues(v2.x, v2.y, v2.z);
vec3.transformQuat( cvec, cvec, faceOri );
v2.x = cvec[0], v2.y = cvec[1], v2.z = cvec[2];
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);
console.log("normals new", n)
let uv0 = new THREE.Vector2();
let...