Sculpt.js 15 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import * as THREE from 'three';
import { acceleratedRaycast, computeBoundsTree } from 'three-mesh-bvh';
import { getIntersectsTriangleIndices } from './bvh';

THREE.Mesh.prototype.raycast = acceleratedRaycast;
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;

const SizeValue = [1, 2, 3, 4, 5, 6, 7];
const IntensityValue = [5, 20, 40, 60];

const getmouse2D = (e, container) => {
    const rect = container.getBoundingClientRect();
    const mouse = new THREE.Vector2();
    mouse.x = ((e.clientX - rect.left) / (rect.right - rect.left)) * 2 - 1;
    mouse.y = -((e.clientY - rect.top) / (rect.bottom - rect.top)) * 2 + 1;
    return mouse;
};

const updateAngledNormal = (geometry, triangles, angle) => {
    const indexAttr = geometry.index;
    const posAttr = geometry.attributes.position;
    const normalAttr = geometry.attributes.normal;

    const pA = new THREE.Vector3();
    const pB = new THREE.Vector3();
    const pC = new THREE.Vector3();
    const nA = new THREE.Vector3();
    const nB = new THREE.Vector3();
    const nC = new THREE.Vector3();
    const cb = new THREE.Vector3();
    const ab = new THREE.Vector3();

    triangles.forEach((tri) => {
        const tri3 = tri * 3;
        const i0 = tri3 + 0;
        const i1 = tri3 + 1;
        const i2 = tri3 + 2;

        // get the indices the triangle/face is built with
        const v0 = indexAttr.getX(i0);
        const v1 = indexAttr.getX(i1);
        const v2 = indexAttr.getX(i2);

        pA.fromBufferAttribute(posAttr, v0);
        pB.fromBufferAttribute(posAttr, v1);
        pC.fromBufferAttribute(posAttr, v2);
        cb.subVectors(pC, pB);
        ab.subVectors(pA, pB);
        cb.cross(ab);
        nA.fromBufferAttribute(normalAttr, v0);
        nB.fromBufferAttribute(normalAttr, v1);
        nC.fromBufferAttribute(normalAttr, v2);
        nA.add(cb);
        nB.add(cb);
        nC.add(cb);
        normalAttr.setXYZ(v0, nA.x, nA.y, nA.z);
        normalAttr.setXYZ(v1, nB.x, nB.y, nB.z);
        normalAttr.setXYZ(v2, nC.x, nC.y, nC.z);
    });
    /*
      updatedNormal.forEach((entry) => {
      const index = entry.index;
      const normal = entry.normal;
      normalAttr.setXYZ(index, normal.x, normal.y, normal.z);
      });
*/

    normalAttr.needsUpdate = true;
};

class Sculpt extends THREE.EventDispatcher {
    constructor({ scene, camera, domElement }) {
        super();
        this._scene = scene;
        this._camera = camera;
        this._domElement = domElement;
        this._raycaster = new THREE.Raycaster();
        this.enabled = true;
        this._selected = false;
        this._currentVector3 = new THREE.Vector3();

        this._brushMesh = null;

        this.addEvents();

        this._intersecTriangleIndics = [];
        this._intersecIndics = [];

        this.param = {
            size: 2,
            intensity: 400,
            brush: 'clay',
            negated: 1
        };

        this.targetMesh = null;
        this.brushObject = null;

        this.normal = new THREE.Vector3();
    }

    dispose = () => {
        this.removeEvents();
        this._intersecTriangleIndics = [];
        this._intersecIndics = [];
        const objects = this._scene.children.filter((el) => el.name === 'brush');
        objects.forEach((element) => {
            this._scene.remove(element);
        });
    };

    removeEvents = () => {
        if (!this._domElement) return;
        this._domElement.removeEventListener('pointermove', this.pointerMove);
        this._domElement.removeEventListener('pointerdown', this.pointerDown);
        this._domElement.removeEventListener('pointerup', this.pointUp);
    };

    addEvents = () => {
        if (!this._domElement) return;
        this._domElement.addEventListener('pointermove', this.pointerMove);
        this._domElement.addEventListener('pointerdown', this.pointerDown);
        this._domElement.addEventListener('pointerup', this.pointUp);
    };

    setTargetMesh = (mesh) => {
        // mesh.geometry = BufferGeometryUtils.mergeVertices(mesh.geometry);
        mesh.geometry.attributes.position.setUsage(THREE.DynamicDrawUsage);
        mesh.geometry.attributes.normal.setUsage(THREE.DynamicDrawUsage);
        if (!mesh.geometry.boundsTree) {
            mesh.geometry.computeBoundsTree();
        }
        this.targetMesh = mesh;
        this.initBrush();
    };

    setToolMode = (val) => {
        switch (val) {
            case 'add':
                this.param.brush = 'clay';
                this.param.negated = 1;
                break;
            case 'remove':
                this.param.brush = 'clay';
                this.param.negated = -1;
                break;
            case 'smooth':
                this.param.brush = 'smooth';
                this.param.negated = 1;
                break;
            case 'flatten':
                this.param.brush = 'flatten';
                this.param.negated = 1;
                break;
            default:
                break;
        }
    };

    setBrushSize = (val) => {
        this.param.size = val;
        if (this.brushObject) {
            this.brushObject.scale.set(this.param.size * 0.6, this.param.size * 0.6, 0.1);
        }
    };

    setIntensity = (val) => {
        this.param.intensity = val * 100;
    };

    pointerDown = (e) => {
        if (!this.enabled) return;
        if (!this._domElement) return;
        if (!this._camera) return;
        if (!this.targetMesh) return;
        if (!this.brushObject) return;
        if (e.button !== 0) return;
        const mouse = getmouse2D(e, this._domElement);
        const raycaster = this._raycaster;
        raycaster.firstHitOnly = false;
        raycaster.setFromCamera(mouse, this._camera);
        const res = raycaster.intersectObjects([this.targetMesh]);
        if (res.length > 0) {
            this._selected = true;
            this.excuteEdit(res[0].normal);
        }
    };

    pointerMove = (e) => {
        if (!this.enabled) return;
        if (!this.brushObject) return;
        if (!this._camera) return;
        if (!this._domElement) return;

        const mouse = getmouse2D(e, this._domElement);
        const raycaster = this._raycaster;
        raycaster.firstHitOnly = false;
        raycaster.setFromCamera(mouse, this._camera);

        const res = raycaster.intersectObjects([this.targetMesh]);

        if (res.length > 0) {
            this.normal.copy(res[0].normal);
            this.brushObject.position.copy(res[0].point);
            this.brushObject.visible = true;
            this.brushObject.scale.set(this.param.size * 0.6, this.param.size * 0.6, 0.1);
            this.excuteEdit(res[0].normal);
        } else {
            this.brushObject.visible = false;
        }
    };

    initBrush = () => {
        const brushSegments = [new THREE.Vector3(), new THREE.Vector3(0, 0, 1)];
        for (let i = 0; i < 50; i++) {
            const nexti = i + 1;
            const x1 = Math.sin((2 * Math.PI * i) / 50);
            const y1 = Math.cos((2 * Math.PI * i) / 50);

            const x2 = Math.sin((2 * Math.PI * nexti) / 50);
            const y2 = Math.cos((2 * Math.PI * nexti) / 50);

            brushSegments.push(new THREE.Vector3(x1, y1, 0), new THREE.Vector3(x2, y2, 0));
        }
        const brush = new THREE.LineSegments();
        brush.geometry.setFromPoints(brushSegments);
        brush.material.color.set(0xfb8c00);
        brush.material.depthTest = false;
        brush.material.transparent = true;
        brush.renderOrder = 3;
        brush.name = 'brush';
        this.brushObject = brush;

        const objects = this._scene.children.filter((el) => el.name === 'brush');
        objects.forEach((element) => {
            this._scene.remove(element);
        });

        this._scene.add(brush);
    };

    pointUp = () => {
        this._selected = false;
        this._intersecIndics.length = 0;
        this._intersecTriangleIndics.length = 0;

        const back = this._scene.getObjectByName('active:back:aligner');
        if (back) {
            back.geometry = this.targetMesh.geometry.clone();
        }
    };

    excuteEdit = (hitNormal) => {
        if (!this.targetMesh) return;

        const lookAtVector = new THREE.Vector3(
            this._camera.matrix.elements[8],
            this._camera.matrix.elements[9],
            this._camera.matrix.elements[10]
        );

        let triangleIndics = this._intersecTriangleIndics;

        let sets = {};

        sets = getIntersectsTriangleIndices(this.targetMesh, this.brushObject.position, this.param.size, this._camera);
        triangleIndics = sets.indices;
        this._intersecTriangleIndics = triangleIndics;

        if (triangleIndics.length == 0) return;

        const indices = sets.indices;

        //console.log(triangleIndics);

        const posAttr = this.targetMesh.geometry.attributes.position;
        const normalAttr = this.targetMesh.geometry.attributes.normal;
        // let position = this.targetMesh.geometry.getAttribute('position');

        const tempVec = new THREE.Vector3();
        const normal = new THREE.Vector3();

        const localPoint = new THREE.Vector3();

        localPoint.copy(this.brushObject.position);

        const planePoint = new THREE.Vector3();
        let totalPoints = 0;

        indices.forEach((index) => {
            tempVec.fromBufferAttribute(normalAttr, index);
            //if (lookAtVector.angleTo(tempVec) < (Math.PI / 180) * 90) {
            normal.add(tempVec.clone());
            totalPoints++;
            tempVec.fromBufferAttribute(posAttr, index);
            planePoint.add(tempVec.clone());
            //}
        });

        normal.multiplyScalar(1 / totalPoints);

        normal.normalize();
        const normalZ = new THREE.Vector3(0, 0, 1);
        this.brushObject.quaternion.setFromUnitVectors(normalZ, normal);

        if (!this._selected) return;

        if (totalPoints) {
            planePoint.multiplyScalar(1 / totalPoints);
        }

        const plane = new THREE.Plane();
        plane.setFromNormalAndCoplanarPoint(normal, planePoint);

        let pushIntensity = this.param.intensity;

        pushIntensity *= 1.5;

        const targetHeight = pushIntensity * 0.0001;

        const normalTempVec = new THREE.Vector3();

        let a = [];

        indices.forEach((index) => {
            normalTempVec.fromBufferAttribute(normalAttr, index);

            tempVec.fromBufferAttribute(posAttr, index);

            const point = tempVec.clone();

            // compute the offset intensity
            const dist = point.distanceTo(localPoint);

            let intensity = 1.0 - dist / this.param.size;

            const { negated } = this.param;

            // offset the vertex
            let planeDistF = 0;
            switch (this.param.brush) {
                case 'clay':
                    intensity **= 3;
                    const planeDistC = plane.distanceToPoint(point);
                    const clampedIntensity = negated * Math.min(intensity * 2, 1.0);
                    point.addScaledVector(
                        normal,
                        clampedIntensity * targetHeight - negated * planeDistC * clampedIntensity * 0.3
                    );
                    break;
                case 'smooth':
                    intensity **= 2;
                    planeDistF = plane.distanceToPoint(point);
                    point.addScaledVector(normal, -planeDistF * intensity * pushIntensity * 0.00025 * 0.3);
                    break;
                case 'flatten':
                    intensity **= 2;
                    planeDistF = plane.distanceToPoint(point);
                    point.addScaledVector(lookAtVector, -planeDistF * intensity * pushIntensity * 0.0005 * 0.25);
                    break;
                case 'normal':
                    intensity **= 2;
                    point.addScaledVector(normal, negated * intensity * targetHeight * 2);
                    break;
                default:
                    break;
            }
            posAttr.setXYZ(index, point.x, point.y, point.z);
            normalAttr.setXYZ(index, 0, 0, 0);
        });

        // removeMesh(this._scene, "points");

        // const p = drawPoints(a, 0xff5809, 0.07);
        // p.name = "points";
        //   this._scene.add(p);

        this.targetMesh.geometry.boundsTree.refit(sets.accumulatedTraversedNodeIndices);

        // this.targetMesh.geometry.boundsTree.refit();

        // If we found vertices
        if (indices.size > 0) {
            posAttr.needsUpdate = true;
        }

        // this.updateNormals(sets.accumulatedTriangles, sets.accumulatedIndices);

        updateAngledNormal(this.targetMesh.geometry, sets.accumulatedTriangles, (Math.PI / 180) * 0.1);
        // this.targetMesh.geometry.computeVertexNormals();
    };

    updateNormals = (triangles, indices) => {
        const tempVec = new THREE.Vector3();
        const tempVec2 = new THREE.Vector3();
        const indexAttr = this.targetMesh.geometry.index;
        const posAttr = this.targetMesh.geometry.attributes.position;
        const normalAttr = this.targetMesh.geometry.attributes.normal;

        // accumulate the normals in place in the normal buffer
        const triangle = new THREE.Triangle();
        triangles.forEach((tri) => {
            const tri3 = tri * 3;
            const i0 = tri3 + 0;
            const i1 = tri3 + 1;
            const i2 = tri3 + 2;

            const v0 = indexAttr.getX(i0);
            const v1 = indexAttr.getX(i1);
            const v2 = indexAttr.getX(i2);

            triangle.a.fromBufferAttribute(posAttr, v0);
            triangle.b.fromBufferAttribute(posAttr, v1);
            triangle.c.fromBufferAttribute(posAttr, v2);
            triangle.getNormal(tempVec2);

            if (indices.has(v0)) {
                tempVec.fromBufferAttribute(normalAttr, v0);
                tempVec.add(tempVec2);
                normalAttr.setXYZ(v0, tempVec.x, tempVec.y, tempVec.z);
            }

            if (indices.has(v1)) {
                tempVec.fromBufferAttribute(normalAttr, v1);
                tempVec.add(tempVec2);
                normalAttr.setXYZ(v1, tempVec.x, tempVec.y, tempVec.z);
            }

            if (indices.has(v2)) {
                tempVec.fromBufferAttribute(normalAttr, v2);
                tempVec.add(tempVec2);
                normalAttr.setXYZ(v2, tempVec.x, tempVec.y, tempVec.z);
            }
        });

        // normalize the accumulated normals
        indices.forEach((index) => {
            tempVec.fromBufferAttribute(normalAttr, index);
            tempVec.normalize();
            normalAttr.setXYZ(index, tempVec.x, tempVec.y, tempVec.z);
        });

        normalAttr.needsUpdate = true;
    };

    sizeChanged = (index) => {
        if (this._brushMesh) {
            const radius = SizeValue[index];
            this._brushMesh.geometry.dispose();
            this._brushMesh.geometry = new THREE.SphereGeometry(radius, 32, 32);
            this.param.size = radius;
        }
    };

    intensityChanged = (index) => {
        this.param.intensity = IntensityValue[index];
    };
}

export default Sculpt;