public void SameBeginning() { var body1 = TestData.GetBodyFromBRep(Path.Combine(_BasePath, "Source1.brep")); var body2 = TestData.GetBodyFromBRep(Path.Combine(_BasePath, "Source2.brep")); var(first, second) = BoxJoint.Create(body1, body2); first.ReverseOrder = false; first.BoxCount = 4; // Only visible if boxcount is even first.RemoveExcess = true; second.RemoveExcess = true; Assert.IsTrue(first.Make(Shape.MakeFlags.None)); Assert.IsTrue(second.Make(Shape.MakeFlags.None)); var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); builder.Add(compound, body1.GetTransformedBRep()); builder.Add(compound, body2.GetTransformedBRep()); AssertHelper.IsSameModel(compound, Path.Combine(_BasePath, "SameBeginning")); first.ReverseOrder = true; Assert.IsTrue(first.Make(Shape.MakeFlags.None)); Assert.IsTrue(second.Make(Shape.MakeFlags.None)); compound = new TopoDS_Compound(); builder.MakeCompound(compound); builder.Add(compound, body1.GetTransformedBRep()); builder.Add(compound, body2.GetTransformedBRep()); AssertHelper.IsSameModel(compound, Path.Combine(_BasePath, "SameBeginning2")); }
//-------------------------------------------------------------------------------------------------- public TopoDS_Compound Reconstruct() { var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); var thicknessVector = SliceDirection.ToVec().Multiplied(SliceThickness / Slices.Length); if (thicknessVector.SquareMagnitude() == 0) { Messages.Error("Sliced shape has no thickness."); return(compound); } for (int index = 0; index < Slices.Length; index++) { var basePlane = Slices[index].CutPlane.Translated(thicknessVector.Multiplied(0.5).ToPnt(), Pnt.Origin); var location = new TopLoc_Location(new Trsf(basePlane.Position, Ax3.XOY)); var relocatedShape = Slices[index].BRep.Located(location); var thickener = new BRepPrimAPI_MakePrism(relocatedShape, thicknessVector, true); builder.Add(compound, thickener.Shape()); } return(compound); }
//-------------------------------------------------------------------------------------------------- public static TopoDS_Shape TransformSketchShape(TopoDS_Shape original, IEnumerable <Trsf2d> transforms, bool includeOriginal) { // Make copies var builder = new BRep_Builder(); var shapeBuildEdge = new ShapeBuild_Edge(); var newShape = new TopoDS_Compound(); builder.MakeCompound(newShape); foreach (var transform in transforms) { foreach (var wire in original.Wires()) { foreach (var edge in wire.Edges()) { if (includeOriginal) { builder.Add(newShape, edge); } var tedge = edge.TShape() as BRep_TEdge; var curves = tedge.CurvesList(); foreach (BRep_CurveOnSurface curveRep in curves.OfType <BRep_CurveOnSurface>()) { // Transform PCurve var curve = curveRep.PCurve(); double first = curve.FirstParameter(); double last = curve.LastParameter(); var newCurve = shapeBuildEdge.TransformPCurve(curve, transform, 1.0, ref first, ref last); // Transform UVs Pnt2d uv0 = new Pnt2d(); Pnt2d uv1 = new Pnt2d(); curveRep.UVPoints(ref uv0, ref uv1); uv0.Transform(transform); uv1.Transform(transform); var makeEdge = new BRepBuilderAPI_MakeEdge2d(newCurve, uv0, uv1); builder.Add(newShape, makeEdge.Edge()); } } } } return(BuildWiresFromEdges(newShape)); }
//-------------------------------------------------------------------------------------------------- public static TopoDS_Solid MakeSolid(TopoDS_Shell shell, bool correctOrientation) { var builder = new BRep_Builder(); var solid = new TopoDS_Solid(); builder.MakeSolid(solid); builder.Add(solid, shell); if (correctOrientation) { var classifier = new BRepClass3d_SolidClassifier(solid); classifier.PerformInfinitePoint(Precision.Confusion()); if (classifier.State() == TopAbs_State.TopAbs_IN) { solid = new TopoDS_Solid(); builder.MakeSolid(solid); builder.Add(solid, shell.Reversed()); } } return(solid); }
//-------------------------------------------------------------------------------------------------- void _UpdateReconstructed() { // Update reconstructed var visObject = WorkspaceController.VisualObjects.Get(_Body, true) as VisualShape; if (visObject == null) { return; } visObject.OverrideBrep = _Component.ReconstructedBRep?.Located(new TopLoc_Location(_Body.GetTransformation()));; _IsReconstructedActive = true; // Update preview var builder = new BRep_Builder(); var compound = new TopoDS_Compound(); builder.MakeCompound(compound); if (_Component.Layers != null) { foreach (var layer in _Component.Layers) { var location = new TopLoc_Location(new Trsf(layer.CutPlane.Position, Ax3.XOY)); builder.Add(compound, layer.BRep.Located(location)); } } compound.Location(new TopLoc_Location(_Body.GetTransformation())); if (_AisPreviewShape == null) { _AisPreviewShape = new AIS_Shape(compound); _AisPreviewShape.SetColor(Colors.FilteredSubshapesHot); _AisPreviewShape.SetWidth(2.0); _AisPreviewShape.SetZLayer(-2); // Top WorkspaceController.Workspace.AisContext.Display(_AisPreviewShape, 0, -1, false, false); } else { _AisPreviewShape.SetShape(compound); WorkspaceController.Workspace.AisContext.RecomputePrsOnly(_AisPreviewShape, false); } // Finalize _IsReconstructeUpdating = false; WorkspaceController.Invalidate(); }
//-------------------------------------------------------------------------------------------------- void _CreateLayer(List <VectorExportLayer> layers, VectorExportLayerType layerTypeType, HlrEdgeType edgeType1, HlrEdgeType edgeType2, HlrBRepAlgoBase hlrAlgo) { var shape1 = _IncludeEdgeTypes.Contains(edgeType1) ? hlrAlgo.GetResult(edgeType1) : null; var shape2 = _IncludeEdgeTypes.Contains(edgeType2) ? hlrAlgo.GetResult(edgeType2) : null; if (shape1 != null && shape2 != null) { var builder = new BRep_Builder(); var compound = new TopoDS_Compound(); builder.MakeCompound(compound); builder.Add(compound, hlrAlgo.GetResult(edgeType1)); builder.Add(compound, hlrAlgo.GetResult(edgeType2)); layers.Add(new VectorExportLayer(layerTypeType, compound)); } else if (shape1 != null) { layers.Add(new VectorExportLayer(layerTypeType, shape1)); } else if (shape2 != null) { layers.Add(new VectorExportLayer(layerTypeType, shape2)); } }
public void ComplexMeshRead() { var exchanger = new ObjExchanger(); var path = Path.Combine(TestData.TestDataDirectory, Path.Combine(_BasePath, "ComplexMeshRead_Source.obj")); Assert.IsTrue((exchanger as IBodyImporter).DoImport(path, out var bodies)); Assert.IsNotNull(bodies); var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); foreach (var body in bodies) { builder.Add(compound, body.Shape.GetTransformedBRep()); } AssertHelper.IsSameModel(compound, Path.Combine(_BasePath, "ComplexMeshRead"), ModelCompare.CompareFlags.SaveTriangulation | ModelCompare.CompareFlags.CompareBytes); }
public void ReadMultipleSolids() { var exchanger = new StepExchanger(); var path = Path.Combine(TestData.TestDataDirectory, Path.Combine(_BasePath, "ReadSolid_Source.stp")); Assert.IsTrue((exchanger as IBodyImporter).DoImport(path, out var bodies)); Assert.IsNotNull(bodies); Assert.AreEqual(47, bodies.Count()); var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); foreach (var body in bodies) { builder.Add(compound, body.Shape.GetTransformedBRep()); } AssertHelper.IsSameModel(compound, Path.Combine(_BasePath, "ReadMultipleSolids")); }
//-------------------------------------------------------------------------------------------------- static List <Body> _CreateBodies(List <ObjectDescription> objectDescList, string bodyName, bool singleBody) { // Create bodies var bodyList = new List <Body>(); if (singleBody) { var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); foreach (var objectDesc in objectDescList) { builder.Add(compound, objectDesc.Face); } var body = Body.Create(Mesh.Create(compound)); body.Name = bodyName; bodyList.Add(body); } else { int index = 1; foreach (var objectDesc in objectDescList) { var body = Body.Create(Mesh.Create(objectDesc.Face)); if (!objectDesc.Name.IsNullOrWhiteSpace()) { body.Name = objectDesc.Name; } else { body.Name = $"{bodyName}_{index++}"; } bodyList.Add(body); } } return(bodyList); }
//-------------------------------------------------------------------------------------------------- #endregion #region IBrepExporter bool IBodyExporter.DoExport(string fileName, IEnumerable <Body> bodies) { try { var builder = new BRep_Builder(); var compound = new TopoDS_Compound(); builder.MakeCompound(compound); foreach (var body in bodies) { var bodyShape = body.Shape?.GetTransformedBRep(); if (bodyShape == null) { Messages.Warning($"BRep Exporter: The body {body.Name} has no valid shape, thus it will not be included in the export."); continue; } builder.Add(compound, bodyShape); } var bytes = Settings.ExportBinaryFormat ? BRepExchange.WriteBinary(compound, true) : BRepExchange.WriteASCII(compound, true); if (bytes == null || bytes.Length == 0) { Messages.Error("BRep Exporter: Error generating BRep from body shapes."); return(false); } File.WriteAllBytes(fileName, bytes); return(true); } catch (Exception e) { Console.WriteLine(e); Messages.Exception("Error exporting file " + fileName + ".", e); } return(false); }
//-------------------------------------------------------------------------------------------------- public static TopoDS_Shape BuildWiresFromEdges(TopoDS_Shape shape) { var edges = new TopTools_HSequenceOfShape(); foreach (var edge in shape.Edges()) { edges.Append(edge); } var wires = new TopTools_HSequenceOfShape(); ShapeAnalysis_FreeBounds.ConnectEdgesToWires(edges, 1e-8, false, wires); var builder = new BRep_Builder(); var newShape = new TopoDS_Compound(); builder.MakeCompound(newShape); for (int i = wires.Lower(); i <= wires.Upper(); i++) { builder.Add(newShape, wires.Value(i)); } return(newShape); }
//-------------------------------------------------------------------------------------------------- public bool DoImport(string fileName, out IEnumerable <Body> bodies) { bodies = null; try { var reader = new Occt.Helper.IgesReader(); if (!reader.ReadFromFile(fileName)) { Messages.Error("IGES Importer: Error importing file " + fileName + "."); return(false); } var rootShape = reader.GetRootShape(); if (rootShape == null) { Messages.Error("IGES Importer: No shapes found to import from file " + fileName + "."); return(false); } var shapes = new List <TopoDS_Shape>(); var solids = rootShape.Solids(); if (solids.Count == 0) { shapes.Add(rootShape); } else { if (Settings.ImportSingleBody) { var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); foreach (var solid in solids) { builder.Add(compound, solid); } shapes.Add(compound); } else { shapes.AddRange(solids); } } var bodyList = new List <Body>(); int index = 1; string bodyName = Path.GetFileNameWithoutExtension(fileName); foreach (var shape in shapes) { // Get top level transformation for body var trsf = shape.Location().Transformation(); var position = trsf.TranslationPart().ToPnt(); var rotation = trsf.GetRotation(); // eliminate top level transformation shape.Location(new TopLoc_Location()); var body = Body.Create(Solid.Create(shape)); body.Position = position; body.Rotation = rotation; body.Name = $"{bodyName}_{index++}"; bodyList.Add(body); } bodies = bodyList; return(true); } catch (Exception e) { Console.WriteLine(e); Messages.Exception("Error importing file " + fileName + ".", e); } return(false); }
//-------------------------------------------------------------------------------------------------- bool IBodyImporter.DoImport(string fileName, out IEnumerable <Body> bodies) { bodies = null; try { using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { var vertices = new List <Pnt>(); var currentObject = ObjectDescription.Create(); var objectDescList = new List <ObjectDescription>(); var reader = new ObjAsciiReader(fs); // Read string cmd; while (reader.MoveNext(out cmd)) { switch (cmd) { case "o": case "g": if (currentObject.Indices.Count != 0) { objectDescList.Add(currentObject); } currentObject = ObjectDescription.Create(); reader.GetObjectOrGroup(out currentObject.Name); break; case "v": if (!reader.GetVertex(out var vertex)) { return(false); } vertices.Add(vertex); break; case "f": case "fo": if (!reader.GetFace(out var indices)) { continue; } // Negative indices must be correctly re-assigned // -1 => vertices.Count // -2 => vertices.Count-1 for (int i = 0; i < indices.Length; i++) { if (indices[i] < 0) { indices[i] = vertices.Count + (indices[i] + 1); } } if (indices.Length == 3) { currentObject.Indices.AddRange(indices.Take(3).Select(index => index - 1)); // Correct lower bound (from 1 to 0) } else { var triangulator = new EarClippingTriangulator(); var result = triangulator.DoTriangulation(vertices, indices.Select(index => index - 1)); // Correct lower bound (from 1 to 0) if (result != null) { currentObject.Indices.AddRange(result); } } break; } } if (currentObject.Indices.Count != 0) { objectDescList.Add(currentObject); } // Create Faces foreach (var objectDesc in objectDescList) { // Extract used vertices var usedVertices = new List <Pnt>(); var indexMap = new Dictionary <int, int>(); for (int index = 0; index < objectDesc.Indices.Count; index++) { int newIndex; int oldIndex = objectDesc.Indices[index]; if (!indexMap.TryGetValue(oldIndex, out newIndex)) { newIndex = usedVertices.Count; usedVertices.Add(vertices[oldIndex]); indexMap.Add(oldIndex, newIndex); } objectDesc.Indices[index] = newIndex; } // Create shape objectDesc.Face = TriangulationHelper.CreateFaceFromTriangulation(new TriangulationData(objectDesc.Indices.ToArray(), usedVertices.ToArray())); } // Create bodies var bodyList = new List <Body>(); string bodyName = Path.GetFileNameWithoutExtension(fileName); if (Settings.ImportSingleBody) { var compound = new TopoDS_Compound(); var builder = new BRep_Builder(); builder.MakeCompound(compound); foreach (var objectDesc in objectDescList) { builder.Add(compound, objectDesc.Face); } var body = Body.Create(Mesh.Create(compound)); body.Name = bodyName; bodyList.Add(body); } else { int index = 1; foreach (var objectDesc in objectDescList) { var body = Body.Create(Mesh.Create(objectDesc.Face)); if (!objectDesc.Name.IsNullOrWhiteSpace()) { body.Name = objectDesc.Name; } else { body.Name = $"{bodyName}_{index++}"; } bodyList.Add(body); } } bodies = bodyList; // Cleanup fs.Close(); } return(true); } catch (Exception e) { Messages.Exception($"Exception occured while importing {fileName}.", e); return(false); } }