import * as THREE from 'three';
import { Vector3, Line3, Plane } from "three";

export class PlaneExt extends Plane
{
    constructor(normal?: Vector3, constant?: number)
    {
        super(normal, constant);
    }
    intersectLine(line: Line3, optionalTarget?: Vector3, extendLine?: boolean): Vector3
    {
        let v1 = new Vector3();

        let result = optionalTarget || new Vector3();

        let direction = line.delta(v1);

        let denominator = this.normal.dot(direction);

        if (denominator === 0)
        {
            // line is coplanar, return origin
            if (this.distanceToPoint(line.start) === 0)
            {
                return result.copy(line.start);
            }
            // Unsure if this is the correct method to handle this case.
            return undefined;
        }

        let t = - (line.start.dot(this.normal) + this.constant) / denominator;
        //If you not extendLine,check intersect point in Line
        if (!extendLine && (t < 0 || t > 1))
        {
            return undefined;
        }

        return result.copy(direction).multiplyScalar(t).add(line.start);
    }
    intersectRay(ray: THREE.Ray, optionalTarget?: Vector3, extendLine?: boolean): Vector3
    {
        // 从射线初始位置
        let line = new THREE.Line3(ray.origin.clone(), ray.origin.clone().add(ray.direction));
        return this.intersectLine(line, optionalTarget, extendLine);
    }
}
