EditCurve.js 15.8 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 462
import DragControl from '@/utility/jsm//controls/DragControl';
import { Raycaster, Mesh, Vector2, Vector3, CatmullRomCurve3, TubeGeometry, MeshStandardMaterial } from 'three';
import { acceleratedRaycast } from 'three-mesh-bvh';

Mesh.prototype.raycast = acceleratedRaycast;

const getMousePosition = (event, container) => {
    const rect = container.getBoundingClientRect();
    const mouse = { x: 0, y: 0 };
    mouse.x = ((event.clientX - rect.left) / (rect.right - rect.left)) * 2 - 1;
    mouse.y = -((event.clientY - rect.top) / (rect.bottom - rect.top)) * 2 + 1;
    return mouse;
};

const findNearestPoints = (targetPoint, points) => {
    let min = Infinity;
    let nearestPoint = null;
    let id = -1;
    points.forEach((el, index) => {
        const distance = el.distanceTo(targetPoint);
        if (distance <= min) {
            min = distance;
            nearestPoint = el;
            id = index;
        }
    });
    return {
        nearestPoint,
        index: id
    };
};

const getPointsDistances = (points) => {
    let distance = 0;
    for (let i = 0; i < points.length - 1; i++) {
        distance += points[i].distanceTo(points[i + 1]);
    }
    return distance;
};

class EditCurve {
    constructor({ camera, scene, domElement }) {
        this._camera = camera;
        this._scene = scene;
        this._domElement = domElement;
        this.activeMesh = null;

        this._DragControls = null;
        this._DrawMargin = null;

        this.raycaster = new Raycaster();
        this.raycaster.firstHitOnly = true;

        this.mode = 'drag'; // 'drag' or 'draw'
        this.drawEnabled = false;
        this.mousepress = false;
        this.drawPoints = [];
        this.drawLines = null;

        this.initDrawLines();
        this.addEvents();
        this.initDragControl();
    }

    initDrawLines = () => {
        const points = [new Vector3(0, 0, 0), new Vector3(0, 0, 1)];
        const curve = new CatmullRomCurve3(points, true);
        const geometry = new TubeGeometry(curve, points.length * 2, 0.1, 100, true);
        const material = new MeshStandardMaterial({
            color: 0xff5809,
            roughness: 0.5
        });
        const mesh = new Mesh(geometry, material);
        mesh.visible = false;
        this.drawLines = mesh;
        this._scene.add(this.drawLines);
    };

    addEvents = () => {
        this._domElement.addEventListener('pointerdown', this.onPointerdown);
        this._domElement.addEventListener('pointermove', this.onPointermove);
        this._domElement.addEventListener('pointerup', this.onPointerup);
    };

    initDragControl = () => {
        this._DragControls = new DragControl(this._camera, this._scene, this._domElement);
        this._DragControls.addEventListener('dragMousemove', this.dragMousemove);
    };

    dispose = () => {
        this.removeEvents();
        this._DragControls.dispose();
    };

    removeEvents = () => {
        this._domElement.removeEventListener('pointerdown', this.onPointerdown);
        this._domElement.removeEventListener('pointermove', this.onPointermove);
        this._domElement.removeEventListener('pointerup', this.onPointerup);
    };

    setCurveClass = (DrawMargin) => {
        this._DrawMargin = DrawMargin;
        if (!this._DragControls) return;
        if (!this._DrawMargin.controlPointsMesh) return;
        const objects = this._DrawMargin.controlPointsMesh.children;
        this._DragControls.setRootsObjects(objects);
    };

    dragMousemove = (e) => {
        if (this.drawEnabled) return;
        const { object, event } = e;
        if (!this._DrawMargin) return;
        this.update(object, event, this.projectToSurface);
    };

    setActiveMesh = (mesh) => {
        this.activeMesh = mesh;
    };

    /**
     * 將原始線段打斷,由 '移動的控制點' 與 '前''後'一個控制點,產生新的曲線,再接回去原始線段更新
     * @param {*THREE.Mesh} object 選擇移動的控制點
     */
    update = (object, event) => {
        const vec2d = getMousePosition(event, this._domElement);
        const mouse = new Vector2(vec2d.x, vec2d.y);

        this._camera.near = 1;
        this.raycaster.setFromCamera(mouse, this._camera);

        const res = this.raycaster.intersectObjects([this.activeMesh]);
        if (res.length > 0) {
            const point = res[0].point;
            object.position.copy(point);

            const id = object.name;
            const index = this._DrawMargin.controlPoints.findIndex((el) => el.originPointIndex === id);
            this._DrawMargin.controlPoints[index].point.copy(point);

            const points = [];
            this._DrawMargin.controlPoints.forEach((el) => {
                points.push(el.point);
            });

            this._DrawMargin.updateCurveMesh(points, this.activeMesh);
        }

        return;
        const targetPoint = object.position;
        const id = object.name;
        const index = this._DrawMargin.controlPoints.findIndex((el) => el.originPointIndex === id);
        if (index > -1) {
            this._DrawMargin.controlPoints[index].point.copy(targetPoint);

            let left = -1;
            let right = -1;
            if (index === 0) {
                left = this._DrawMargin.controlPoints.length - 1;
                right = 1;
            } else if (index === this._DrawMargin.controlPoints.length - 1) {
                left = this._DrawMargin.controlPoints.length - 2;
                right = 0;
            } else {
                left = index - 1;
                right = index + 1;
            }

            let fittedLeftIndex = this._DrawMargin.controlPoints[left].originPointIndex;
            let fittedRightIndex = this._DrawMargin.controlPoints[right].originPointIndex;

            // 0 ~ fittedLeftIndex, fittedRightIndex ~ last    => 原始線段
            // new : fittedLeftIndex, index ,fittedRightIndex  => 更新線段

            // create a new segment points
            const newSegmentPoints = [
                this._DrawMargin.controlPoints[left].point,
                targetPoint,
                this._DrawMargin.controlPoints[right].point
            ];

            const curves = new CatmullRomCurve3(newSegmentPoints, false);
            curves.curveType = 'chordal';
            const addPoints = curves.getPoints(50);
            addPoints.pop();

            this._DrawMargin.controlPoints[index].point.copy(addPoints[Math.ceil(addPoints.length * 0.5)]);

            const passPoints1 = this._DrawMargin.originPoints.slice(0, fittedLeftIndex);
            const passPoints2 = addPoints;
            const passPoints3 = this._DrawMargin.originPoints.slice(
                fittedRightIndex,
                this._DrawMargin.originPoints.length
            );

            // 新的曲線點
            let points = [...passPoints1, ...passPoints2, ...passPoints3];

            // 更新控制點紀錄 index
            this._DrawMargin.controlPoints[left].originPointIndex = this.findPointsEqualIndex(
                this._DrawMargin.controlPoints[left].point,
                points
            );
            this._DrawMargin.controlPoints[index].originPointIndex = this.findPointsEqualIndex(
                this._DrawMargin.controlPoints[index].point,
                points
            );
            this._DrawMargin.controlPoints[right].originPointIndex = this.findPointsEqualIndex(
                this._DrawMargin.controlPoints[right].point,
                points
            );

            object.name = this._DrawMargin.controlPoints[index].originPointIndex;

            for (let i = right; i < this._DrawMargin.controlPoints.length; i++) {
                this._DrawMargin.controlPoints[i].originPointIndex = this.findPointsEqualIndex(
                    this._DrawMargin.controlPoints[i].point,
                    points
                );
                this._DrawMargin.controlPoints[i].mesh.name = this._DrawMargin.controlPoints[i].originPointIndex;
            }

            this.projectToSurface(index, this._DrawMargin.controlPoints, points, passPoints2, event);
            points = [...passPoints1, ...passPoints2, ...passPoints3];

            this._DrawMargin.originPoints = [...points];

            // 更新曲線Mesh
            this._DrawMargin.updateCurveMesh(points);
        }
    };

    findPointsEqualIndex = (point, points) => {
        let i = points.length - 1;
        let index = -1;
        while (i >= 0) {
            if (points[i].equals(point)) {
                index = i;
                break;
            }
            i--;
        }
        return index;
    };

    //        const target = this.activeMesh.geometry.boundsTree.closestPointToPoint(passPoints[i], a).point;
    projectToSurface = (activeIndex, controlPoints, points, passPoints, event) => {
        for (let i = 1; i < passPoints.length; i++) {
            if (i === Math.ceil(passPoints.length * 0.5)) continue;
            const a = {};
            const target = this.activeMesh.geometry.boundsTree.closestPointToPoint(passPoints[i], a).point;
            passPoints[i].copy(target);
        }

        return;

        if (!this.activeMesh) return;

        const vec2d = getMousePosition(event, this._domElement);
        const mouse = new Vector2(vec2d.x, vec2d.y);

        this._camera.near = 1;
        this.raycaster.setFromCamera(mouse, this._camera);

        const res = this.raycaster.intersectObjects([this.activeMesh]);
        if (res.length > 0) {
            const point = res[0].point;
            controlPoints[activeIndex].mesh.position.copy(point);
            controlPoints[activeIndex].point.copy(point);
            points[controlPoints[activeIndex].originPointIndex].copy(point);
            return;

            const vector = new Vector3(
                this._camera.matrix.elements[8],
                this._camera.matrix.elements[9],
                this._camera.matrix.elements[10]
            );
            vector.multiplyScalar(-1);
            controlPoints[activeIndex].mesh.position.copy(point);
            // 曲線投影
            for (let i = 1; i < passPoints.length; i++) {
                if (i === Math.ceil(passPoints.length * 0.5)) continue;
                const originPoint = passPoints[i];
                this.raycaster.set(originPoint, vector);
                const res = this.raycaster.intersectObjects([this.activeMesh]);
                if (res.length > 0) {
                    passPoints[i].copy(res[0].point);
                }
            }
        }
    };

    setEditMode = (val) => {
        this.mode = val;
        switch (this.mode) {
            case 'drag':
                this.setDragMode();
                break;
            case 'draw':
                this.setDrawMode();
                break;
            default:
                break;
        }
        this.drawEnabled = this.mode === 'draw';
        if (!this._DrawMargin) return;
        this._DrawMargin.controlPointsMesh.visible = this.mode === 'drag';
    };

    setDragMode = () => {
        if (!this._DrawMargin) return;
    };

    setDrawMode = () => {
        if (!this._DrawMargin) return;
    };

    onPointerdown = (e) => {
        if (!this.drawEnabled) return;
        if (e.button === 0) this.mousepress = true;
    };

    onPointermove = (e) => {
        if (!this.drawEnabled) return;
        if (!this.mousepress) return;

        const vec2d = getMousePosition(e, this._domElement);
        const mouse = new Vector2(vec2d.x, vec2d.y);

        this.raycaster.setFromCamera(mouse, this._camera);

        const res = this.raycaster.intersectObjects([this.activeMesh]);
        if (res.length > 0) {
            const point = res[0].point;
            this.drawPoints.push(point);
            if (this.drawPoints.length > 1) this.drawPointLines([...this.drawPoints]);
        }
    };

    onPointerup = (e) => {
        if (!this.drawEnabled) return;
        this.mousepress = false;
        this.drawLines.visible = false;

        if (this.drawPoints.length === 0) return;

        const curve = new CatmullRomCurve3(this.drawPoints, false);
        const pts = curve.getPoints(this.drawPoints.length);

        const v0 = pts[0];
        const v1 = pts[pts.length - 1];

        if (!this._DrawMargin) return;

        const points = [];
        this._DrawMargin.curvePoints.forEach((el) => {
            points.push(el);
        });

        const contorls = [];
        this._DrawMargin.controlPoints.forEach((el) => {
            contorls.push(el.point);
        });

        const v0Nearest = findNearestPoints(v0, points);
        const v1Nearest = findNearestPoints(v1, points);

        const v0NearestControl = findNearestPoints(v0, contorls);
        const v1NearestControl = findNearestPoints(v1, contorls);

        if (v0Nearest.index > -1 && v1Nearest.index > -1) {
            let v0index = v0Nearest.index;
            let v1index = v1Nearest.index;

            if (v0index > v1index) {
                v0index = v1Nearest.index;
                v1index = v0Nearest.index;
                pts.reverse();
            }

            const points_ = [];
            const distance_ = getPointsDistances(pts);
            const count = Math.ceil(distance_);

            for (let i = 0; i < pts.length - 1; i += Math.round((pts.length / count) * 1.2)) {
                points_.push(pts[i]);
            }

            const segment1 = points.slice(0, v0index);
            const segment2 = points.slice(v1index, points.length);

            let v0indexControl = v0NearestControl.index;
            let v1indexControl = v1NearestControl.index;

            if (v0indexControl > v1indexControl) {
                v0indexControl = v1NearestControl.index;
                v1indexControl = v0NearestControl.index;
            }

            const segment1__ = contorls.slice(0, v0indexControl);
            const segment2__ = contorls.slice(v1indexControl, contorls.length);

            const controlPoints = [];
            this._DrawMargin.controlPoints.forEach((el) => {
                controlPoints.push(el.point);
            });

            const segment1_ = [...segment1];
            const segment2_ = [...segment2];

            const controlPointsSeg1_ = [];
            const controlPointsSeg2_ = [];

            segment1__.forEach((el) => {
                const { nearestPoint, index } = findNearestPoints(el, segment1_);
                if (index > -1) {
                    controlPointsSeg1_.push(nearestPoint);
                    segment1_.splice(index, 1);
                }
            });

            segment2__.forEach((el) => {
                const { nearestPoint, index } = findNearestPoints(el, segment2_);
                if (index > -1) {
                    controlPointsSeg2_.push(nearestPoint);
                    segment2_.splice(index, 1);
                }
            });

            const newPoints = [...controlPointsSeg1_, ...points_, ...controlPointsSeg2_, points[points.length - 1]];

            const segmentRests = contorls.slice(v0indexControl, v1indexControl);
            let newsPoints2 = [...segmentRests, ...points_];
            const d1 = getPointsDistances(newPoints);
            const d2 = getPointsDistances(newsPoints2);

            if (d2 > d1) {
                newsPoints2 = [...segmentRests, ...points_.reverse()];
            }

            const updatePoints = d1 > d2 ? newPoints : newsPoints2;

            this._DrawMargin.updateCurveMesh(updatePoints, this.activeMesh);

            // update control points
            this._DrawMargin.updateControlPoints(updatePoints);
            const objects = this._DrawMargin.controlPointsMesh.children;
            this._DragControls.setRootsObjects(objects);
        }

        this.drawPoints = [];
    };

    drawPointLines = (points) => {
        const curve = new CatmullRomCurve3(points, false);
        const geometry = new TubeGeometry(curve, points.length * 2, 0.06, 100, false);
        this.drawLines.geometry.dispose();
        this.drawLines.geometry = geometry;
        this.drawLines.visible = true;
    };
}

export default EditCurve;