All files / lib/services/base meshing.service.ts

94.76% Statements 163/172
68.42% Branches 26/38
88.23% Functions 15/17
96.89% Lines 156/161

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                    28x 28x 28x 158x 158x 158x 2268x 2268x 2268x 2268x         2268x     2268x       28x                 32x 32x 32x 32x 32x         32x   32x 3x 3x     3x 3x 3x       32x 32x     32x 32x 32x   167x 167x 167x   167x                       167x 167x   167x 167x     167x 167x 167x 16980x 16980x 16980x 16980x 16980x 16980x 16980x 16980x       167x 167x 167x 167x 16980x 16980x 16980x 16980x       167x 167x 167x 167x 167x 32604x 32604x 32604x 32604x 32604x 20378x 20378x 20378x   32604x 32604x 32604x 32604x   167x 167x   167x   167x 167x 167x 167x           32x 167x 167x       32x 32x 339x           339x 339x 339x 339x     339x 339x 339x 339x 2248x 2248x         2248x           339x 339x 169x     339x   339x 2248x 339x 339x 339x 339x     32x 32x 32x 1336x 1336x 1336x       32x 32x   32x 32x       9x 9x   9x 9x   9x     9x 9x 17x 17x 16x         1x               9x       5x 5x   5x 5x   5x       3x   3x 6x 6x 6x 6x 2x 2x 2x       6x 6x   3x       1x   1x 2x 2x 2x 2x             2x 2x   1x        
import {
    Handle_Poly_Triangulation,
    OpenCascadeInstance,
    TopoDS_Shape, TopoDS_Wire
} from "../../../bitbybit-dev-occt/bitbybit-dev-occt";
import * as Inputs from "../../api/inputs/inputs";
import { EdgesService } from "./edges.service";
import { FacesService } from "./faces.service";
import { ShapeGettersService } from "./shape-getters";
import { TransformsService } from "./transforms.service";
import { WiresService } from "./wires.service";
import { BaseBitByBit } from "../../base";
 
export class MeshingService {
 
    constructor(
        public readonly occ: OpenCascadeInstance,
        public readonly shapeGettersService: ShapeGettersService,
        public readonly transformsService: TransformsService,
        public readonly edgesService: EdgesService,
        public facesService: FacesService,
        public readonly wiresService: WiresService,
        public readonly base: BaseBitByBit
    ) { }
 
    shapeFacesToPolygonPoints(inputs: Inputs.OCCT.ShapeFacesToPolygonPointsDto<TopoDS_Shape>): Inputs.Base.Point3[][] {
        const def = this.shapeToMesh(inputs);
        const res = [];
        def.faceList.forEach(face => {
            const vertices = face.vertex_coord;
            const indices = face.tri_indexes;
            for (let i = 0; i < indices.length; i += 3) {
                const p1 = indices[i];
                const p2 = indices[i + 1];
                const p3 = indices[i + 2];
                let pts = [
                    [vertices[p1 * 3], vertices[p1 * 3 + 1], vertices[p1 * 3 + 2]],
                    [vertices[p2 * 3], vertices[p2 * 3 + 1], vertices[p2 * 3 + 2]],
                    [vertices[p3 * 3], vertices[p3 * 3 + 1], vertices[p3 * 3 + 2]],
                ];
                Iif (inputs.reversedPoints) {
                    pts = pts.reverse();
                }
                res.push(pts);
            }
        });
 
        return res;
    }
 
    shapesToMeshes(inputs: Inputs.OCCT.ShapesToMeshesDto<TopoDS_Shape>): Inputs.OCCT.DecomposedMeshDto[] {
        return inputs.shapes.map(shape => this.shapeToMesh({ shape, precision: inputs.precision, adjustYtoZ: inputs.adjustYtoZ }));
    }
 
    shapeToMesh(inputs: Inputs.OCCT.ShapeToMeshDto<TopoDS_Shape>): Inputs.OCCT.DecomposedMeshDto {
 
        const faceList: Inputs.OCCT.DecomposedFaceDto[] = [];
        const edgeList: Inputs.OCCT.DecomposedEdgeDto[] = [];
        const pointsList: Inputs.Base.Point3[] = [];
        let shapeToUse = inputs.shape;
        Iif (shapeToUse.IsNull()) return { faceList, edgeList, pointsList: [] };
 
        // This could be made optional...
        // Clean cached triangulation data for the shape.
        // This allows to get lower res models out of higher res that was once computed and cached.
        this.occ.BRepTools.Clean(shapeToUse, true);
 
        if (inputs.adjustYtoZ) {
            const shapeToUseRotated = this.transformsService.rotate({ shape: inputs.shape, axis: [1, 0, 0], angle: -90 });
            const shapeMirrored = this.transformsService.mirrorAlongNormal(
                { shape: shapeToUseRotated, origin: [0, 0, 0], normal: [0, 0, 1] }
            );
            shapeToUseRotated.delete();
            shapeToUse.delete();
            shapeToUse = shapeMirrored;
        }
 
        // Iterate through the faces and triangulate each one
        const triangulations: Handle_Poly_Triangulation[] = [];
        const faces = this.shapeGettersService.getFaces({ shape: shapeToUse });
 
        let incrementalMeshBuilder;
        Eif (faces && faces.length) {
            incrementalMeshBuilder = new this.occ.BRepMesh_IncrementalMesh_2(shapeToUse, inputs.precision, false, 0.5, false);
            faces.forEach((myFace, faceIndex) => {
 
                const aLocation = new this.occ.TopLoc_Location_1();
                const myT = this.occ.BRep_Tool.Triangulation(myFace, aLocation, 0);
                Iif (myT.IsNull()) { console.error("Encountered Null Face!"); return; }
 
                const thisFace: Inputs.OCCT.DecomposedFaceDto = {
                    vertex_coord: [],
                    normal_coord: [],
                    uvs: [],
                    tri_indexes: [],
                    vertex_coord_vec: [],
                    number_of_triangles: 0,
                    center_point: undefined,
                    center_normal: undefined,
                    face_index: faceIndex
                };
 
                thisFace.center_point = this.facesService.pointOnUV({ shape: myFace, paramU: 0.5, paramV: 0.5 });
                thisFace.center_normal = this.facesService.normalOnUV({ shape: myFace, paramU: 0.5, paramV: 0.5 });
 
                const pc = new this.occ.Poly_Connect_2(myT);
                const triangulation = myT.get();
 
                // write vertex buffer
                thisFace.vertex_coord = new Array(triangulation.NbNodes() * 3);
                thisFace.vertex_coord_vec = [];
                for (let i = 0; i < triangulation.NbNodes(); i++) {
                    const p = triangulation.Node(i + 1).Transformed(aLocation.Transformation());
                    const uv = triangulation.UVNode(i + 1);
                    thisFace.uvs[(i * 2) + 0] = uv.X();
                    thisFace.uvs[(i * 2) + 1] = uv.Y();
                    thisFace.vertex_coord[(i * 3) + 0] = p.X();
                    thisFace.vertex_coord[(i * 3) + 1] = p.Y();
                    thisFace.vertex_coord[(i * 3) + 2] = p.Z();
                    thisFace.vertex_coord_vec.push([p.X(), p.Y(), p.Z()]);
                }
 
                // write normal buffer
                const myNormal = new this.occ.TColgp_Array1OfDir_2(1, triangulation.NbNodes());
                this.occ.StdPrs_ToolTriangulatedShape.Normal(myFace, pc, myNormal);
                thisFace.normal_coord = new Array(myNormal.Length() * 3);
                for (let i = 0; i < myNormal.Length(); i++) {
                    const d = myNormal.Value(i + 1);
                    thisFace.normal_coord[(i * 3) + 0] = d.X();
                    thisFace.normal_coord[(i * 3) + 1] = d.Y();
                    thisFace.normal_coord[(i * 3) + 2] = d.Z();
                }
 
                // write triangle buffer
                const orient = myFace.Orientation_1();
                const triangles = myT.get().Triangles();
                thisFace.tri_indexes = new Array(triangles.Length() * 3);
                let validFaceTriCount = 0;
                for (let nt = 1; nt <= myT.get().NbTriangles(); nt++) {
                    const t = triangles.Value(nt);
                    let n1 = t.Value(1);
                    let n2 = t.Value(2);
                    const n3 = t.Value(3);
                    if (orient !== this.occ.TopAbs_Orientation.TopAbs_FORWARD) {
                        const tmp = n1;
                        n1 = n2;
                        n2 = tmp;
                    }
                    thisFace.tri_indexes[(validFaceTriCount * 3) + 0] = n1 - 1;
                    thisFace.tri_indexes[(validFaceTriCount * 3) + 1] = n2 - 1;
                    thisFace.tri_indexes[(validFaceTriCount * 3) + 2] = n3 - 1;
                    validFaceTriCount++;
                }
                thisFace.number_of_triangles = validFaceTriCount;
                faceList.push(thisFace);
 
                triangulations.push(myT);
 
                aLocation.delete();
                myNormal.delete();
                triangles.delete();
                pc.delete();
 
            });
        }
 
        // Nullify Triangulations between runs so they're not stored in the cache
        for (let i = 0; i < triangulations.length; i++) {
            triangulations[i].Nullify();
            triangulations[i].delete();
        }
 
        // Get the free edges that aren't on any triangulated face/surface
        const edges = this.shapeGettersService.getEdges({ shape: shapeToUse });
        edges.forEach((myEdge, index) => {
            const thisEdge: Inputs.OCCT.DecomposedEdgeDto = {
                vertex_coord: [],
                middle_point: undefined,
                edge_index: -1
            };
 
            thisEdge.middle_point = this.edgesService.pointOnEdgeAtParam({ shape: myEdge, param: 0.5 });
            const aLocation = new this.occ.TopLoc_Location_1();
            const adaptorCurve = new this.occ.BRepAdaptor_Curve_2(myEdge);
            const tangDef = new this.occ.GCPnts_TangentialDeflection_2(adaptorCurve, inputs.precision, 0.1, 2, 1.0e-9, 1.0e-7);
 
            // write vertex buffer
            thisEdge.vertex_coord = [];
            const nrPoints = tangDef.NbPoints();
            const tangDefValues = [];
            for (let j = 0; j < nrPoints; j++) {
                const tangDefVal = tangDef.Value(j + 1);
                thisEdge.vertex_coord.push([
                    tangDefVal.X(),
                    tangDefVal.Y(),
                    tangDefVal.Z()
                ]);
                tangDefValues.push(tangDefVal);
            }
            
            // Check if the edge orientation is reversed
            // GCPnts_TangentialDeflection meshes the curve in its natural direction,
            // so we need to reverse the points if the edge orientation is TopAbs_REVERSED
            const orientation = myEdge.Orientation_1();
            if (orientation === this.occ.TopAbs_Orientation.TopAbs_REVERSED) {
                thisEdge.vertex_coord.reverse();
            }
            
            thisEdge.edge_index = index;
 
            edgeList.push(thisEdge);
            tangDefValues.forEach(v => v.delete());
            aLocation.delete();
            adaptorCurve.delete();
            tangDef.delete();
            this.occ.BRepTools.Clean(myEdge, true);
        });
 
        const vertices = this.shapeGettersService.getVertices({ shape: shapeToUse });
        Eif (vertices.length > 0) {
            vertices.forEach(v => {
                const pt = this.occ.BRep_Tool.Pnt(v);
                pointsList.push([pt.X(), pt.Y(), pt.Z()]);
                pt.delete();
            });
        }
 
        Eif (incrementalMeshBuilder) {
            incrementalMeshBuilder.Delete();
        }
        this.occ.BRepTools.Clean(shapeToUse, true);
        return { faceList, edgeList, pointsList };
    }
 
    meshMeshIntersectionWires(inputs: Inputs.OCCT.MeshMeshIntersectionTwoShapesDto<TopoDS_Shape>): TopoDS_Wire[] {
        const shape1 = inputs.shape1;
        const shape2 = inputs.shape2;
 
        const mesh1 = this.shapeFacesToPolygonPoints({ shape: shape1, precision: inputs.precision1, adjustYtoZ: false, reversedPoints: false }) as Inputs.Base.Mesh3;
        const mesh2 = this.shapeFacesToPolygonPoints({ shape: shape2, precision: inputs.precision2, adjustYtoZ: false, reversedPoints: false }) as Inputs.Base.Mesh3;
 
        const res = this.base.mesh.meshMeshIntersectionPolylines({
            mesh1, mesh2
        });
        const wires = [];
        res.forEach(r => {
            Eif (r.points && r.points.length > 0) {
                if (r.isClosed) {
                    wires.push(
                        this.wiresService.createPolygonWire({
                            points: r.points,
                        }));
                } else {
                    wires.push(
                        this.wiresService.createPolylineWire({
                            points: r.points,
                        })
                    );
                }
            }
        });
        return wires;
    }
 
    meshMeshIntersectionPoints(inputs: Inputs.OCCT.MeshMeshIntersectionTwoShapesDto<TopoDS_Shape>): Inputs.Base.Point3[][] {
        const shape1 = inputs.shape1;
        const shape2 = inputs.shape2;
 
        const mesh1 = this.shapeFacesToPolygonPoints({ shape: shape1, precision: inputs.precision1, adjustYtoZ: false, reversedPoints: false }) as Inputs.Base.Mesh3;
        const mesh2 = this.shapeFacesToPolygonPoints({ shape: shape2, precision: inputs.precision2, adjustYtoZ: false, reversedPoints: false }) as Inputs.Base.Mesh3;
 
        return this.base.mesh.meshMeshIntersectionPoints({ mesh1, mesh2 });
    }
 
    meshMeshIntersectionOfShapesWires(inputs: Inputs.OCCT.MeshMeshesIntersectionOfShapesDto<TopoDS_Shape>): TopoDS_Wire[] {
        const wireIntersections: TopoDS_Wire[] = [];
 
        inputs.shapes.forEach((shape, index) => {
            const shape1 = inputs.shape;
            const shape2 = inputs.shapes[index];
            let precision2 = inputs.precision;
            if (inputs.precisionShapes && inputs.precisionShapes.length > 0) {
                const p = inputs.precisionShapes[index];
                Eif (p) {
                    precision2 = p;
                }
            }
 
            const wires = this.meshMeshIntersectionWires({ shape1, shape2, precision1: inputs.precision, precision2 });
            wireIntersections.push(...wires);
        });
        return wireIntersections;
    }
 
    meshMeshIntersectionOfShapesPoints(inputs: Inputs.OCCT.MeshMeshesIntersectionOfShapesDto<TopoDS_Shape>): Inputs.Base.Point3[][] {
        const pointIntersections: Inputs.Base.Point3[][] = [];
 
        inputs.shapes.forEach((shape, index) => {
            const shape1 = inputs.shape;
            const shape2 = inputs.shapes[index];
            let precision2 = inputs.precision;
            Iif (inputs.precisionShapes && inputs.precisionShapes.length > 0) {
                const p = inputs.precisionShapes[index];
                if (p) {
                    precision2 = p;
                }
            }
 
            const points = this.meshMeshIntersectionPoints({ shape1, shape2, precision1: inputs.precision, precision2 });
            pointIntersections.push(...points);
        });
        return pointIntersections;
    }
 
}