/// <summary> /// Calculate the average of the vectors from this node position to the centroid of connected elements. /// </summary> /// <returns></returns> public Vector AverageConnectionDirection() { Vector result = Vector.Zero; int count = 0; foreach (Vertex v in Vertices) { if (v.Owner != null) { VertexGeometry vG = v.Owner; if (vG is Curve) { Curve crv = (Curve)vG; Vector midPt = crv.PointAt(0.5); if (midPt.IsValid()) { result += (midPt - Position).Unitize(); count += 1; } } //TODO: To surface centroid? } } if (count > 1) { result /= count; } return(result); }
public VertexGeometryContent(VertexGeometry vg) { VertexGeometries = new List <VertexGeometry>() { vg }; }
/// <summary> /// Generate nodes for this element's vertices, if they do not already posess them /// them. This relies on the element being included as part of a Model to function. /// </summary> /// <param name="options">The node generation options</param> public virtual void GenerateNodes(NodeGenerationParameters options) { VertexGeometry geometry = GetGeometry(); foreach (Vertex v in geometry.Vertices) { v.GenerateNode(options); } }
/// <summary> /// Generate nodes for this element's vertices, if they do not already posess them /// them. This override of the GenerateNodes function does not require the element /// to be part of a Model. /// </summary> /// <param name="options">The node generation options</param> public virtual void GenerateNodes(NodeGenerationParameters options, NodeCollection nodes, NodeDDTree nodeTree) { VertexGeometry geometry = GetGeometry(); foreach (Vertex v in geometry.Vertices) { v.GenerateNode(options, nodes, nodeTree); } }
private void HandlesReplaceRhinoObject(object sender, RhinoReplaceObjectEventArgs e) { if (!RhinoOutput.Writing) { ModelObject mObj = LinkedModelObject(e.ObjectId); if (mObj != null) { RC.GeometryBase geometry = e.NewRhinoObject.Geometry; if (mObj is Element) { Element element = (Element)mObj; VertexGeometry vG = FromRC.Convert(geometry); if (vG == null && geometry is RC.Curve) { // If curve not convertable, reduce to straight line: RC.Curve rCrv = (RC.Curve)geometry; vG = new Line(FromRC.Convert(rCrv.PointAtStart), FromRC.Convert(rCrv.PointAtEnd)); } if (vG != null) { _Replacing = true; if (element is LinearElement && vG is Curve) { ((LinearElement)element).ReplaceGeometry((Curve)vG); } else if (element is PanelElement && vG is Surface) { ((PanelElement)element).ReplaceGeometry((Surface)vG); } _Replacing = false; _ReplacedElements.TryAdd(element); } } else if (mObj is Node) { _ReplacedNodesWaitingList[(Node)mObj] = e; /*RC.GeometryBase geometry = e.NewRhinoObject.Geometry; * if (geometry is RC.Point) * { * Node node = (Node)mObj; * node.Position = RCtoFB.Convert(((RC.Point)geometry).Location); * }*/ /*if (_ObjectReplacedWaitTimer == null) * { * _ObjectReplacedWaitTimer = new Timer(100); * _ObjectReplacedWaitTimer.AutoReset = false; * _ObjectReplacedWaitTimer.Elapsed += ProcessObjectReplacedWaitingList; * }*/ //if (!_ObjectReplacedWaitTimer.Enabled) } //if (_ObjectReplacedWaitTimer != null) _ObjectReplacedWaitTimer.Start(); } } _LastReplaced = e.ObjectId; }
/// <summary> /// Replace an object if it exists or bake a new one if it does not /// </summary> /// <param name="objID"></param> /// <param name="geometry"></param> /// <returns></returns> public static Guid BakeOrReplace(Guid objID, VertexGeometry geometry) { if (objID != Guid.Empty && Replace(objID, geometry)) { return(objID); } else { return(Bake(geometry)); } }
/// <summary> /// Does this element's geometry contain a reference to the specified node? /// </summary> /// <param name="node"></param> /// <returns></returns> public bool ContainsNode(Node node) { VertexGeometry geometry = GetGeometry(); foreach (Vertex v in geometry.Vertices) { if (v.Node == node) { return(true); } } return(false); }
/// <summary> /// Convert a Rhino object reference to Nucleus geometry with attached /// attributes. /// </summary> /// <param name="objRef"></param> /// <returns></returns> public static VertexGeometry Convert(ObjRef objRef) { VertexGeometry result = Convert(objRef.Geometry()); if (result != null) { GeometryAttributes attributes = new GeometryAttributes(); int layerIndex = objRef.Object().Attributes.LayerIndex; attributes.LayerName = RhinoDoc.ActiveDoc.Layers[layerIndex].Name; attributes.SourceID = objRef.ObjectId.ToString(); result.Attributes = attributes; } return(result); }
/// <summary> /// Convert a netDXF HatchBoundaryPath to a Nucleus PolyCurve /// or PolyLine /// </summary> /// <param name="path"></param> /// <returns></returns> public static Curve Convert(nDE.HatchBoundaryPath path) { PolyCurve result = new PolyCurve(); foreach (nDE.HatchBoundaryPath.Edge edge in path.Edges) { VertexGeometry edgeRep = Convert(edge.ConvertTo()); if (edgeRep != null && edgeRep is Curve) { result.Add((Curve)edgeRep); } } if (result.IsPolyline()) return result.ToPolyLine(); else return result; }
/// <summary> /// Read data from an ESRI Shapefile and convert it into a .NUCLEUS geometry layer /// </summary> /// <param name="filePath">The filepath of the shapefile</param> /// <returns></returns> public GeometryLayer ReadShapefile(FilePath filePath) { var result = new GeometryLayer(filePath.FileName); var shapeFile = DotSpatial.Data.Shapefile.OpenFile(filePath); foreach (IFeature feature in shapeFile.Features) { VertexGeometry vGeo = ToNucleus.Convert(feature); if (vGeo != null) { result.Add(vGeo); } } return(result); }
/// <summary> /// Create a new (or update an existing) element as a copy of another one /// </summary> /// <param name="element">The element to copy.</param> /// <param name="newGeometry">Optional. The set-out geometry to be used for the new element. /// Should be of the appropriate type for the element to be copied.</param> /// <param name="exInfo">Optional. The execution information of the current action. /// If an object has been created previously with matching execution information then /// instead of creating a new item this previous one will be updated and returned instead. /// This enables this method to be used parametrically.</param> /// <returns></returns> public Element CopyOf(Element element, VertexGeometry newGeometry = null, ExecutionInfo exInfo = null) { if (element is LinearElement) { return(CopyOf((LinearElement)element, newGeometry as Curve, exInfo)); } else if (element is PanelElement) { return(CopyOf((PanelElement)element, newGeometry as Surface, exInfo)); } else { return(null); } }
/// <summary> /// Convert Nucleus geometry into RhinoCommon geometry /// </summary> /// <param name="geometry"></param> /// <returns></returns> public static RC.GeometryBase Convert(VertexGeometry geometry) { if (geometry is Curve) { return(Convert((Curve)geometry)); } else if (geometry is Surface) { return(Convert((Surface)geometry)); } else if (geometry is Extrusion) { return(Convert((Extrusion)geometry)); } return(null); }
/// <summary> /// Convert a Nucleus geometry object to a Robot one /// </summary> /// <param name="geometry"></param> /// <returns></returns> public static RobotGeoObject Convert(VertexGeometry geometry) { if (geometry is PolyLine) { return((RobotGeoObject)Convert((PolyLine)geometry)); } else if (geometry is PolyCurve) { return((RobotGeoObject)Convert((PolyCurve)geometry)); } // TODO! else { return(null); } }
/// <summary> /// Convert a Nucleus geometry object to a netDXF /// </summary> /// <param name="geo"></param> /// <returns></returns> public static IList <nDE.EntityObject> Convert(VertexGeometry geo, IList <nDE.EntityObject> result = null) { if (result == null) { result = new List <nDE.EntityObject>(); } if (geo is Line) { result.Add(Convert((Line)geo)); } else if (geo is PolyLine) { result.Add(Convert((PolyLine)geo)); } else if (geo is Arc) { result.Add(Convert((Arc)geo)); } else if (geo is PolyCurve) { Convert((PolyCurve)geo, result); } else if (geo is PlanarRegion) { result.Add(Convert((PlanarRegion)geo)); } else if (geo is Label) { result.Add(Convert((Label)geo)); } else if (geo is Point) { result.Add(Convert((Point)geo)); } else if (geo is Cloud) { Convert((Cloud)geo, result); } else if (geo is Mesh) { result.Add(Convert((Mesh)geo)); } return(result); }
/// <summary> /// Bake a piece of Nucleus geometry in the active Rhino document /// </summary> /// <param name="geometry"></param> /// <returns></returns> public static Guid Bake(VertexGeometry geometry) { Guid result = Guid.Empty; if (geometry != null) { GeometryBase gB = ToRC.Convert(geometry); if (gB != null) { Writing = true; result = Bake(gB); Writing = false; } //else throw new NotImplementedException(); } return(result); }
public override VertexGeometryCollection EnterGeometry(string prompt = "Enter geometry", Type geometryType = null) { GetObject gO = new GetObject(); if (geometryType == typeof(Curve)) { gO.GeometryFilter = ObjectType.Curve; } else if (geometryType == typeof(Surface)) { gO.GeometryFilter = ObjectType.Surface | ObjectType.Mesh; } else if (geometryType == typeof(Point)) { gO.GeometryFilter = ObjectType.Point; } else { gO.GeometryFilter = ObjectType.Curve | ObjectType.Surface | ObjectType.Point | ObjectType.Mesh; //TODO: Support others } gO.SetCommandPrompt(prompt); if (gO.GetMultiple(1, 0) == GetResult.Cancel) { throw new OperationCanceledException("Operation cancelled by user"); } VertexGeometryCollection result = new VertexGeometryCollection(); foreach (ObjRef objRef in gO.Objects()) { try { VertexGeometry shape = FromRC.Convert(objRef); if (shape != null) { result.Add(shape); } } catch (NotImplementedException) { Core.PrintLine(objRef.Geometry()?.GetType().Name + "s not supported!"); } } return(result); }
/// <summary> /// Loads positions from aara file and returns a TriangleSet (a regular grid for triangulation is assumed). /// Further a translation offset can be applied to the position data /// </summary> public static TriangleSet GetTriangleSetFromPath(string posPath, M44d affine) { //create empty vg var vg = new VertexGeometry(GeometryMode.TriangleList); //read grid from aara file var grid = AaraHelpers.PointSampleGrid2dFromAaraFile(posPath); //apply affine with double prec //var transPos = grid.Positions // .Select(x => (V3f)(affine.TransformPos(x))) // .ToArray(); var positions = grid.Positions.ToArray(); //get indices while handling invalid positions var invPoints = OpcIndices.GetInvalidPositions(positions); var indices = IndexArrayCache.GetIndexArray(grid.Resolution, invPoints.ToList()); if (indices.Length == 0) { indices = new int[] { 0, 0, 0 } } ; vg.Positions = positions; vg.TransformV3d(affine); vg.Indices = indices; //build up triangle set var triangles = vg.Triangles .Where(x => !x.Point0.Position.IsNaN && !x.Point1.Position.IsNaN && !x.Point2.Position.IsNaN) .Select(x => x.ToTriangle3d()); return(new TriangleSet(triangles)); } }
protected override void setJSON(JObject obj, BaseClassIfc host, HashSet <int> processed) { base.setJSON(obj, host, processed); obj["VertexGeometry"] = VertexGeometry.getJson(this, processed); }
/// <summary> /// Read a DXF and convert it into native Nucleus geometry types. /// </summary> /// <param name="doc">The document to read from</param> /// <returns></returns> private VertexGeometryCollection ReadDXF(DxfDocument doc) { VertexGeometryCollection result = new VertexGeometryCollection(); double scale = 1.0; if (doc.DrawingVariables.InsUnits == netDxf.Units.DrawingUnits.Millimeters) { scale = 0.001; } else if (doc.DrawingVariables.InsUnits == netDxf.Units.DrawingUnits.Centimeters) { scale = 0.01; } FromDXF.ConversionScaling = scale; // Hatches foreach (netDxf.Entities.Hatch hatch in doc.Hatches) { result.AddRange(FromDXF.Convert(hatch)); } // Lines foreach (netDxf.Entities.Line line in doc.Lines) { result.Add(FromDXF.Convert(line)); } // Polylines foreach (netDxf.Entities.LwPolyline pLine in doc.LwPolylines) { result.Add(FromDXF.Convert(pLine)); } foreach (netDxf.Entities.Polyline pLine in doc.Polylines) { result.Add(FromDXF.Convert(pLine)); } // Arcs foreach (netDxf.Entities.Arc arc in doc.Arcs) { result.Add(FromDXF.Convert(arc)); } foreach (netDxf.Entities.Circle circle in doc.Circles) { result.Add(FromDXF.Convert(circle)); } // Splines foreach (netDxf.Entities.Spline spline in doc.Splines) { result.Add(FromDXF.Convert(spline)); } // Points foreach (netDxf.Entities.Point point in doc.Points) { result.Add(FromDXF.Convert(point)); } //TODO: Meshes foreach (netDxf.Entities.Mesh mesh in doc.Meshes) { result.Add(FromDXF.Convert(mesh)); } // Text foreach (netDxf.Entities.Text text in doc.Texts) { result.Add(FromDXF.Convert(text)); } foreach (netDxf.Entities.MText text in doc.MTexts) { result.Add(FromDXF.Convert(text)); } // Block inserts foreach (netDxf.Entities.Insert insert in doc.Inserts) { // Explode: // Note: There is some commented-out code in the library to do this: // see: https://netdxf.codeplex.com/SourceControl/latest#netDxf/Entities/Insert.cs // TODO: Review and improve? Vector translation = FromDXF.Convert(insert.Position); Transform transform = FromDXF.Convert(insert.GetTransformation(netDxf.Units.DrawingUnits.Meters)); foreach (netDxf.Entities.EntityObject entity in insert.Block.Entities) { VertexGeometry shape = FromDXF.Convert(entity); if (shape != null) { shape.Transform(transform); shape.Move(translation); result.Add(shape); } } } return(result); }
/// <summary> /// Read a map from a stream /// </summary> /// <param name="stream"></param> /// <param name="originLatLong"></param> /// <param name="layerNames"></param> /// <returns></returns> public GeometryLayerTable ReadMap(Stream stream, AnglePair originLatLong, IList <string> layerNames = null) { var result = new GeometryLayerTable(); var source = new XmlOsmStreamSource(stream); var nodes = new Dictionary <long, OsmSharp.Node>(); var ways = new Dictionary <long, OsmSharp.Way>(); if (layerNames == null) { layerNames = new List <string>(); layerNames.Add("Building"); layerNames.Add("Highway"); } foreach (var element in source) { if (element.Id != null) { if (element.Type == OsmSharp.OsmGeoType.Node) { nodes.Add((long)element.Id, (OsmSharp.Node)element); } else if (element.Type == OsmSharp.OsmGeoType.Way) { ways.Add((long)element.Id, (OsmSharp.Way)element); } //TODO: Relations? } } foreach (var way in ways.Values) { var pts = new List <Vector>(way.Nodes.Length); for (int i = 0; i < way.Nodes.Length; i++) { long nodeID = way.Nodes[i]; if (nodes.ContainsKey(nodeID)) { var node = nodes[nodeID]; pts.Add(node.Position(originLatLong)); } } VertexGeometry geometry = null; if (pts.Count == 2) { geometry = new Line(pts[0], pts[1]); } else if (pts.Count > 2) { geometry = new PolyLine(pts); //TODO: Areas } if (geometry != null) { string layerName = "Miscellaneous"; //Assign layer according to keys: if (way.Tags != null) { foreach (string name in layerNames) { string lName = name.ToLower(); if (way.Tags.ContainsKey(lName)) { string value = way.Tags[lName]; if (LayerSeparator != null && !string.IsNullOrWhiteSpace(value) && value != "yes") { layerName = name + LayerSeparator + value; } else { layerName = name; } break; } } if (ExtrudeBuildings) { if (geometry is Curve && way.Tags.ContainsKey("height")) { string heightTag = way.Tags["height"]; heightTag = heightTag.TrimEnd('m').Trim(); double height; if (double.TryParse(heightTag, out height)) { // TODO: Deal with tags with different units on the end! geometry = new Extrusion((Curve)geometry, new Vector(0, 0, height)); } } if (geometry is Curve && way.Tags.ContainsKey("building:levels")) { // Height not supplied - fall back to storeys: string levelsTag = way.Tags["building:levels"]; double levels; if (double.TryParse(levelsTag, out levels)) { geometry = new Extrusion((Curve)geometry, new Vector(0, 0, levels * StoreyHeight + ByStoreysExtraHeight)); } } if (geometry is Curve && DefaultBuildingHeight > 0 && way.Tags.ContainsKey("building")) { // No indication of height supplied - fall back to default: geometry = new Extrusion((Curve)geometry, new Vector(0, 0, DefaultBuildingHeight)); } } } var layer = result.GetOrCreate(layerName); layer.Add(geometry); } } return(result); }
public TransformUndoState(VertexGeometry geometry, Transform transform, Transform inverse) : this(geometry, transform) { _Inverse = inverse; }
public TransformUndoState(VertexGeometry geometry, Transform transform) { Geometry = geometry; Transform = transform; }
/// <summary> /// Add geometric contents to the canvas, automatically converting from /// Nucleus geometry to the WPF equivalent /// </summary> /// <param name="shape"></param> public void AddContents(VertexGeometry shape) { if (shape is Curve) { Curve crv = (Curve)shape; PathGeometry pathGeo = new PathGeometry(); pathGeo.Figures.Add(ToWPF.Convert(crv)); Path path = new Path(); path.DataContext = crv; //if (crv.Attributes == null || crv.Attributes.Brush == null) //{ // path.Stroke = DefaultBrush; //} //else path.Stroke = FBtoWPF.Convert(crv.Attributes.Brush); var strokeBinding = new Binding("Attributes.Brush"); strokeBinding.Converter = new Converters.BrushConverter(); strokeBinding.FallbackValue = DefaultBrush; path.SetBinding(Path.StrokeProperty, strokeBinding); path.StrokeStartLineCap = PenLineCap.Round; path.StrokeEndLineCap = PenLineCap.Round; //path.StrokeThickness = CurveThickness; //var thicknessBinding = new Binding("CurveThickness"); //thicknessBinding.Source = this; if (crv.Attributes == null) { //path.SetBinding(Path.StrokeThicknessProperty, thicknessBinding); path.StrokeThickness = CurveThickness; } else { /*var mBinding = new MultiBinding(); * mBinding.Converter = new Converters.MultiplicationConverter(); * mBinding.Bindings.Add(thicknessBinding); * mBinding.Bindings.Add(new Binding("Attributes.Weight")); * * path.SetBinding(Path.StrokeThicknessProperty, mBinding);*/ path.StrokeThickness = CurveThickness * crv.Attributes.Weight; } // * scaleFactor; path.Data = pathGeo; path.StrokeLineJoin = PenLineJoin.Round; if (crv.Closed && FillBrush != null) { path.Fill = FillBrush; } //fillBrush = null; path.Tag = shape; Children.Add(path); } else if (shape is PlanarRegion) { PlanarRegion reg = (PlanarRegion)shape; Curve perimeter = reg.Perimeter; CurveCollection voids = reg.Voids; PathGeometry perimeterPath = new PathGeometry(); perimeterPath.Figures.Add(ToWPF.Convert(perimeter)); CombinedGeometry cg = new CombinedGeometry(); cg.GeometryCombineMode = GeometryCombineMode.Exclude; cg.Geometry1 = perimeterPath; if (voids != null && voids.Count > 0) { PathGeometry inside = new PathGeometry(); foreach (Curve vCrv in voids) { inside.Figures.Add(ToWPF.Convert(vCrv)); } cg.Geometry2 = inside; } Path path = new Path(); path.DataContext = shape; //if (reg.Attributes == null || reg.Attributes.Brush == null) //{ // path.Fill = DefaultBrush; //} //else path.Fill = FBtoWPF.Convert(reg.Attributes.Brush, 192); var fillBinding = new Binding("Attributes.Brush"); fillBinding.Converter = new Converters.BrushConverter(); fillBinding.FallbackValue = DefaultBrush; fillBinding.ConverterParameter = 192; path.SetBinding(Path.FillProperty, fillBinding); //path.Stroke = Brushes.Black; //path.StrokeThickness = 0.01; path.Data = cg; path.Tag = shape; Children.Add(path); } else if (shape is FB.Label) { FB.Label label = (FB.Label)shape; TextBlock tB = new TextBlock(); tB.DataContext = label; tB.Padding = new Thickness(0); if (label.TextBinding != null) { tB.SetBinding(TextBlock.TextProperty, ToWPF.Convert(label.TextBinding)); } else { tB.SetBinding(TextBlock.TextProperty, new Binding("Text")); } tB.FontSize = 1; //label.TextSize; tB.RenderTransform = new ScaleTransform(label.TextSize, label.TextSize); //tB.RenderTransformOrigin = new System.Windows.Point(0, 1); var fillBinding = new Binding("Attributes.Brush"); fillBinding.Converter = new Converters.BrushConverter(); fillBinding.FallbackValue = DefaultBrush; tB.SetBinding(TextBlock.ForegroundProperty, fillBinding); FormattedText fT = new FormattedText(label.Text, CultureInfo.CurrentCulture, tB.FlowDirection, new Typeface(tB.FontFamily, tB.FontStyle, tB.FontWeight, tB.FontStretch), 1, tB.Foreground); double xOffset; if (label.HorizontalSetOut == HorizontalSetOut.Left) { xOffset = 0; } else if (label.HorizontalSetOut == HorizontalSetOut.Right) { xOffset = fT.Width * label.TextSize; } else { xOffset = label.TextSize * fT.Width / 2; } double yOffset; if (label.VerticalSetOut == VerticalSetOut.Top) { yOffset = 0; } else if (label.VerticalSetOut == VerticalSetOut.Bottom) { yOffset = fT.Height * label.TextSize; } else { yOffset = label.TextSize * fT.Height / 2; } SetLeft(tB, label.Position.X - xOffset); SetTop(tB, -label.Position.Y - yOffset); tB.Tag = shape; Children.Add(tB); } else if (shape is Cloud || shape is FB.Point) { double diameter = PointDiameter; if (shape.Attributes != null) { diameter *= shape.Attributes.Weight; } foreach (Vertex v in shape.Vertices) { Ellipse ellipse = new Ellipse(); ellipse.Width = diameter; ellipse.Height = diameter; ellipse.DataContext = shape; var fillBinding = new Binding("Attributes.Brush"); fillBinding.Converter = new Converters.BrushConverter(); fillBinding.FallbackValue = DefaultBrush; ellipse.SetBinding(Ellipse.FillProperty, fillBinding); SetLeft(ellipse, v.X - diameter / 2.0); SetTop(ellipse, -v.Y - diameter / 2.0); ellipse.Tag = shape; if (shape.Attributes != null && shape.Attributes.Interactive) { //TODO: CHANGE THIS! TEMP ONLY! ellipse.Cursor = Cursors.Hand; } Children.Add(ellipse); } } }
private void HandlesAddRhinoObject(object sender, RhinoObjectEventArgs e) { if (!RhinoOutput.Writing && !_Replacing) { if (e.TheObject.Attributes.HasUserData) { string data = e.TheObject.Attributes.GetUserString("SAL_ORIGINAL"); if (!string.IsNullOrEmpty(data) && data != e.ObjectId.ToString()) { Guid storedGuid = new Guid(data); if (this.Links.ContainsSecond(storedGuid)) { ModelObject mO = LinkedModelObject(storedGuid); //Create copy of object: if (mO is Element) { VertexGeometry geometry = FromRC.Convert(e.TheObject.Geometry); Element element = null; if (mO is LinearElement) { LinearElement lElement = ((LinearElement)mO).Duplicate();//Core.Instance.ActiveDocument?.Model?.Create.CopyOf((Element)mO, geometry); bool split = false; if (geometry is Curve) { Curve newCrv = (Curve)geometry; if (lElement.Geometry != null) { Curve oldCrv = lElement.Geometry; if (newCrv.Length < oldCrv.Length) { //TODO: Check end point distance to curve double maxDist = 0; foreach (Vertex v in newCrv.Vertices) { double dist = oldCrv.DistanceToSquared(v.Position); if (dist > maxDist) { maxDist = dist; } } if (maxDist < Tolerance.Distance) { split = true; } } } lElement.ReplaceGeometry(newCrv, split); } lElement.GenerateNodes(new NodeGenerationParameters()); element = lElement; } if (mO is PanelElement) { PanelElement pElement = ((PanelElement)mO).Duplicate();//Core.Instance.ActiveDocument?.Model?.Create.CopyOf((Element)mO, geometry); if (geometry is Surface) { pElement.ReplaceGeometry((Surface)geometry); } element = pElement; } RhinoOutput.SetOriginalIDUserString(e.ObjectId); if (element != null) { Links.Set(element.GUID, e.ObjectId); Core.Instance.ActiveDocument.Model.Add(element); } } else if (mO is Node) { if (e.TheObject.Geometry is RC.Point) { Node node = ((Node)mO).Duplicate(); RC.Point pt = (RC.Point)e.TheObject.Geometry; node.Position = FromRC.Convert(pt).Position; RhinoOutput.SetOriginalIDUserString(e.ObjectId); Links.Set(node.GUID, e.ObjectId); Core.Instance.ActiveDocument.Model.Add(node); } } } } } } }
/// <summary> /// Replace an object in the current Rhino document /// </summary> /// <param name="objID"></param> /// <param name="geometry"></param> /// <returns></returns> public static bool Replace(Guid objID, VertexGeometry geometry) { return(Replace(objID, ToRC.Convert(geometry))); }
/// <summary> /// Loads VertexGeometry from aara files. Beware: add Local2Global node for global space. /// </summary> /// <param name="positions">Raw positions, read from aara files for possible further processing.</param> /// <param name="dataType">DataType of positions.</param> /// <returns>Vertex Geometry in local OPC space.</returns> public static VertexGeometry LoadPatch(PatchFileInfo info, string basePath, PositionsType posType, out Array positions, out Symbol dataType, bool loadNormals = true, bool loadTexCoords = true, bool loadDiffTex = true, bool loadHueTex = true, float maxTriangleSize = float.PositiveInfinity, bool loadAsDoubles = false) { var vg = new VertexGeometry(GeometryMode.TriangleList); positions = null; // load metadata var aara3dPos = AaraData.FromFile( Path.Combine(basePath, posType == PositionsType.V3dPositions ? info.Positions : info.Positions2d)); dataType = aara3dPos.DataTypeAsSymbol; var resolution = new V2i(aara3dPos.Size); if (resolution.AnySmaller(2)) { Report.Warn("ignoring patch {0} due to invalid gridresolution {1}", basePath, resolution); return(null); } // load positions positions = aara3dPos.LoadElements(); var positions3d = loadAsDoubles ? positions : AaraData.ConvertArrayToV3fs[aara3dPos.DataTypeAsSymbol](positions); //var positionsV3 = loadAsDoubles ? // (Array)AaraData.ConvertArrayToV3ds[aara3dPos.DataTypeAsSymbol](positions) : // (Array); vg.Positions = positions3d; var p = AaraData.ConvertArrayToV3fs[aara3dPos.DataTypeAsSymbol](positions); // calculate indices var invalidPoints = OpcIndices.GetInvalidPositions(p); // limit triangle size if ((maxTriangleSize < float.PositiveInfinity) && (maxTriangleSize > 0.000001f)) { vg.Indices = OpcIndices.ComputeIndexArray(resolution, invalidPoints.ToList(), p, maxTriangleSize); } else { vg.Indices = OpcIndices.ComputeIndexArray(resolution, invalidPoints.ToList()); } // load normals if (loadNormals) { var normalPath = Path.Combine(basePath, "Normals.aara"); if (StorageConfig.FileExists(normalPath)) { var normals = AaraData.FromFile(normalPath); var normals3d = AaraData.ConvertArrayToV3fs[normals.DataTypeAsSymbol](normals.LoadElements()); vg.Normals = normals3d; } } // load coordinates vg.Coordinates = new CoordinatesMap(); if (loadTexCoords) { var coordPath = Path.Combine(basePath, info.Coordinates.First()); var coordinates = AaraData.FromFile(coordPath).LoadElements() as V2f[]; vg.Coordinates[VertexGeometry.Property.DiffuseColorCoordinates] = coordinates; } // load textures vg.Textures = new TexturesMap(); if (loadDiffTex) { var texFile = Path.ChangeExtension(info.Textures.First(), ".dds"); var texPath = Path.GetFullPath(Path.Combine(basePath, @"..\..\images", texFile)); if (StorageConfig.FileExists(texPath)) { var img = Convertible.FromFile(texPath); vg.Textures[VertexGeometry.Property.DiffuseColorTexture] = new Aardvark.Rendering.Texture(img) { ForceImmediateUpload = false }; } } if (loadHueTex) { vg.Textures[VertexGeometry.Property.LightMapTexture] = new Aardvark.Rendering.Texture(Resources.HueColorMap.Convertible()); } return(vg); }
// searches for oversized triangles and adds only invalid indices to invalid point list // (keep vertex indices for triangle side < maxTriangleSize) public static int[] GetInvalidPositionsFromOversizedTriangles(int[] invalidpositions, VertexGeometry vg, float maxTriangleSize) { var invalidPoints = new List <int>(invalidpositions); foreach (var t in vg.Triangles) { V3d p0, p1, p2; t.GetVertexPositions(out p0, out p1, out p2); if (p0.IsNaN || p1.IsNaN || p2.IsNaN) { continue; } List <V3d> vertexlist = new List <V3d>(); int p0_counter = 0; int p1_counter = 0; int p2_counter = 0; if (V3d.Distance(p0, p1) > maxTriangleSize) { vertexlist.Add(p0); vertexlist.Add(p1); } if (V3d.Distance(p0, p2) > maxTriangleSize) { vertexlist.Add(p0); vertexlist.Add(p2); } if (V3d.Distance(p1, p2) > maxTriangleSize) { vertexlist.Add(p1); vertexlist.Add(p2); } foreach (var p in vertexlist) { if (p == p0) { p0_counter++; } if (p == p1) { p1_counter++; } if (p == p2) { p2_counter++; } } if ((p0_counter > 1) && (!Array.Exists(invalidPoints.ToArray(), x => x == t.VertexIndex0))) { invalidPoints.Add(t.VertexIndex0); } if ((p1_counter > 1) && (!Array.Exists(invalidPoints.ToArray(), x => x == t.VertexIndex1))) { invalidPoints.Add(t.VertexIndex1); } if ((p2_counter > 1) && (!Array.Exists(invalidPoints.ToArray(), x => x == t.VertexIndex2))) { invalidPoints.Add(t.VertexIndex2); } } return(invalidPoints.ToArray()); }
protected override void setJSON(JObject obj, BaseClassIfc host, SetJsonOptions options) { base.setJSON(obj, host, options); obj["VertexGeometry"] = VertexGeometry.getJson(this, options); }
// searches for oversized triangles and removes and adds all 3 vertex indices to invalid point list // (if one triangle side > maxTriangleSize => skip whole triangle) public static int[] GetAllPositionsFromOversizedTriangles(int[] invalidpositions, VertexGeometry vg, float maxTriangleSize) { var invalidPoints = new List <int>(invalidpositions); foreach (var t in vg.Triangles) { V3d p0, p1, p2; t.GetVertexPositions(out p0, out p1, out p2); if (p0.IsNaN || p1.IsNaN || p2.IsNaN) { continue; } double dist_p0p1 = V3d.Distance(p0, p1); double dist_p0p2 = V3d.Distance(p0, p2); double dist_p1p2 = V3d.Distance(p1, p2); if ((dist_p0p1 > maxTriangleSize) || (dist_p0p2 > maxTriangleSize) || (dist_p1p2 > maxTriangleSize)) { foreach (var index in t.VertexIndices) { if (!Array.Exists(invalidPoints.ToArray(), x => x == index)) { invalidPoints.Add(index); } } } } return(invalidPoints.ToArray()); }