/// <summary> /// Determine the X intercept of a polygon edge /// with a horizontal line at the Y value of the /// test point. /// </summary> public static double GetXIntercept(UV p, UV q, double y) { Debug.Assert(0 != (p.V - q.V), "unexpected horizontal segment"); return q.U - ((q.V - y) * ((p.U - q.U) / (p.V - q.V))); }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; UIDocument uiDoc = commandData.Application.ActiveUIDocument; SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView); if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 1); IList<Reference> refList = new List<Reference>(); refList = uiDoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Face); foreach (Reference reference in refList) { IList<UV> uvPts = new List<UV>(); List<double> doubleList = new List<double>(); IList<ValueAtPoint> valList = new List<ValueAtPoint>(); Face face = doc.GetElement(reference).GetGeometryObjectFromReference(reference)as Face; BoundingBoxUV bb = face.GetBoundingBox(); UV min = bb.Min; UV max = bb.Max; for (double u = min.U; u < max.U; u += (max.U - min.U) / 10) { for (double v = min.V; v < max.V; v += (max.V - min.V) / 10) { UV uv = new UV(u, v); if (face.IsInside(uv)) { uvPts.Add(uv); doubleList.Add(v + DateTime.Now.Second); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } } FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts); FieldValues vals = new FieldValues(valList); int idx = sfm.AddSpatialFieldPrimitive(reference); AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema 1", "Schema 1 Description"); sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, sfm.RegisterResult(resultSchema)); } return Result.Succeeded; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Result rc = Result.Failed; ViewPlan view = commandData.View as ViewPlan; if( null == view || view.ViewType != ViewType.AreaPlan ) { message = "Please run this command in an area plan view."; return rc; } UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Element room = Util.GetSingleSelectedElement( uidoc ); if( null == room || !(room is Room) ) { room = Util.SelectSingleElement( uidoc, "a room" ); } if( null == room || !( room is Room ) ) { message = "Please select a single room element."; } else { using ( Transaction t = new Transaction( doc ) ) { t.Start( "Create New Area" ); Location loc = room.Location; LocationPoint lp = loc as LocationPoint; XYZ p = lp.Point; UV q = new UV( p.X, p.Y ); Area area = doc.Create.NewArea( view, q ); rc = Result.Succeeded; t.Commit(); } } return rc; }
public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Application revit = commandData.Application; Document curDoc = revit.ActiveDocument; Level createlevel = curDoc.ActiveView.GenLevel; UV point = new UV(0, 0); // 利用标高,坐标创建房间对象 Room createdRoom = curDoc.Create.NewRoom(createlevel, ref point); if (null == createdRoom) { message = "Create the wall failed."; return IExternalCommand.Result.Failed; } curDoc.Create.NewRoomTag(createdRoom, ref point); return IExternalCommand.Result.Succeeded; }
/// <summary> /// Determine whether given 2D point lies within /// the polygon. /// /// Written by Jeremy Tammik, Autodesk, 2009-09-23, /// based on code that I wrote back in 1996 in C++, /// which in turn was based on C code from the /// article "An Incremental Angle Point in Polygon /// Test" by Kevin Weiler, Autodesk, in "Graphics /// Gems IV", Academic Press, 1994. /// /// Copyright (C) 2009 by Jeremy Tammik. All /// rights reserved. /// /// This code may be freely used. Please preserve /// this comment. /// </summary> public static bool PolygonContains(List<UV> polygon, UV point) { // initialize Int32 quad = GetQuadrant( polygon[0], point); Int32 angle = 0; // loop on all vertices of polygon Int32 next_quad, delta; int n = polygon.Count; for (int i = 0; i < n; ++i) { UV vertex = polygon[i]; UV next_vertex = polygon[(i + 1 < n) ? i + 1 : 0]; // calculate quadrant and delta from last quadrant next_quad = GetQuadrant(next_vertex, point); delta = next_quad - quad; AdjustDelta( ref delta, vertex, next_vertex, point); // add delta to total angle sum angle = angle + delta; // increment for next step quad = next_quad; } // complete 360 degrees (angle of + 4 or -4 ) // means inside return (angle == +4) || (angle == -4); // odd number of windings rule: // if (angle & 4) return INSIDE; else return OUTSIDE; // non-zero winding rule: // if (angle != 0) return INSIDE; else return OUTSIDE; }
/// <summary> /// Find all quadtree points (UVs) in the quadtree within a radius of the given UV location. /// </summary> /// <param name="center">The UV at the center of the search area.</param> /// <param name="radius">The radius of the search area.</param> /// <returns>A list of UVs.</returns> public List<UV> FindPointsWithinRadius(UV center, double radius) { if (center == null) { throw new ArgumentNullException( "center", Resources.FindPointsWithinRadiusNullPointMessage); } if (radius <= 0.0) { throw new ArgumentException( "radius", Resources.FindPointsWithinRadiusSearchRadiusMessage); } return Root.FindNodesWithinRadius(center, radius) .Where(n => n.Point != null) .Select(n => n.Point) .ToList(); }
public static void AdjustDelta( ref int delta, UV vertex, UV next_vertex, UV p) { switch (delta) { // make quadrant deltas wrap around: case 3: delta = -1; break; case -3: delta = 1; break; // check if went around point cw or ccw: case 2: case -2: if (GetXIntercept(vertex, next_vertex, p.V) > p.U) { delta = -delta; } break; } }
public override void Read(BinaryReader r) { base.Read(r); Flags2 = r.ReadUInt32(); // another filler var tmpdataStreamType = r.ReadUInt32(); DataStreamType = (DataStreamTypeEnum)Enum.ToObject(typeof(DataStreamTypeEnum), tmpdataStreamType); NumElements = r.ReadUInt32(); // number of elements in this chunk if (_model.FileVersion == FileVersionEnum.CryTek_3_5 || _model.FileVersion == FileVersionEnum.CryTek_3_4) { BytesPerElement = r.ReadUInt32(); // bytes per element } if (_model.FileVersion == FileVersionEnum.CryTek_3_6) { BytesPerElement = (uint)r.ReadInt16(); // Star Citizen 2.0 is using an int16 here now. r.ReadInt16(); // unknown value. Doesn't look like padding though. } SkipBytes(r, 8); // Now do loops to read for each of the different Data Stream Types. If vertices, need to populate Vector3s for example. switch (DataStreamType) { case DataStreamTypeEnum.VERTICES: // Ref is 0x00000000 Vertices = new Vector3[NumElements]; switch (BytesPerElement) { case 12: for (var i = 0; i < NumElements; i++) { Vertices[i].x = r.ReadSingle(); Vertices[i].y = r.ReadSingle(); Vertices[i].z = r.ReadSingle(); } break; case 8: // Prey files, and old Star Citizen files for (var i = 0; i < NumElements; i++) { // 2 byte floats. Use the Half structure from TK.Math //Vertices[i].x = Byte4HexToFloat(r.ReadUInt16().ToString("X8")); //Vertices[i].y = Byte4HexToFloat(r.ReadUInt16().ToString("X8")); r.ReadUInt16(); //Vertices[i].z = Byte4HexToFloat(r.ReadUInt16().ToString("X8")); //Vertices[i].w = Byte4HexToFloat(r.ReadUInt16().ToString("X8")); Vertices[i].x = new Half { bits = r.ReadUInt16() }.ToSingle(); Vertices[i].y = new Half { bits = r.ReadUInt16() }.ToSingle(); Vertices[i].z = new Half { bits = r.ReadUInt16() }.ToSingle(); r.ReadUInt16(); } break; case 16: //Console.WriteLine("method: (3)"); for (var i = 0; i < NumElements; i++) { Vertices[i].x = r.ReadSingle(); Vertices[i].y = r.ReadSingle(); Vertices[i].z = r.ReadSingle(); Vertices[i].w = r.ReadSingle(); // TODO: Sometimes there's a W to these structures. Will investigate. } break; } break; case DataStreamTypeEnum.INDICES: // Ref is Indices = new uint[NumElements]; if (BytesPerElement == 2) { for (var i = 0; i < NumElements; i++) { Indices[i] = (uint)r.ReadUInt16(); //Console.WriteLine(R"Indices {i}: {Indices[i]}"); } } if (BytesPerElement == 4) { for (var i = 0; i < NumElements; i++) { Indices[i] = r.ReadUInt32(); } } //Log($"Offset is {r.BaseStream.Position:X}"); break; case DataStreamTypeEnum.NORMALS: Normals = new Vector3[NumElements]; for (var i = 0; i < NumElements; i++) { Normals[i].x = r.ReadSingle(); Normals[i].y = r.ReadSingle(); Normals[i].z = r.ReadSingle(); } //Log($"Offset is {r.BaseStream.Position:X}"); break; case DataStreamTypeEnum.UVS: UVs = new UV[NumElements]; for (var i = 0; i < NumElements; i++) { UVs[i].U = r.ReadSingle(); UVs[i].V = r.ReadSingle(); } //Log($"Offset is {r..BaseStream.Position:X}"); break; case DataStreamTypeEnum.TANGENTS: Tangents = new Tangent[NumElements, 2]; Normals = new Vector3[NumElements]; for (var i = 0; i < NumElements; i++) { switch (BytesPerElement) { case 0x10: // These have to be divided by 32767 to be used properly (value between 0 and 1) Tangents[i, 0].x = r.ReadInt16(); Tangents[i, 0].y = r.ReadInt16(); Tangents[i, 0].z = r.ReadInt16(); Tangents[i, 0].w = r.ReadInt16(); // Tangents[i, 1].x = r.ReadInt16(); Tangents[i, 1].y = r.ReadInt16(); Tangents[i, 1].z = r.ReadInt16(); Tangents[i, 1].w = r.ReadInt16(); break; case 0x08: // These have to be divided by 127 to be used properly (value between 0 and 1) // Tangent Tangents[i, 0].w = r.ReadSByte() / 127.0f; Tangents[i, 0].x = r.ReadSByte() / 127.0f; Tangents[i, 0].y = r.ReadSByte() / 127.0f; Tangents[i, 0].z = r.ReadSByte() / 127.0f; // Binormal Tangents[i, 1].w = r.ReadSByte() / 127.0f; Tangents[i, 1].x = r.ReadSByte() / 127.0f; Tangents[i, 1].y = r.ReadSByte() / 127.0f; Tangents[i, 1].z = r.ReadSByte() / 127.0f; // Calculate the normal based on the cross product of the tangents. //Normals[i].x = (Tangents[i,0].y * Tangents[i,1].z - Tangents[i,0].z * Tangents[i,1].y); //Normals[i].y = 0 - (Tangents[i,0].x * Tangents[i,1].z - Tangents[i,0].z * Tangents[i,1].x); //Normals[i].z = (Tangents[i,0].x * Tangents[i,1].y - Tangents[i,0].y * Tangents[i,1].x); //Console.WriteLine("Tangent: {0:F6} {1:F6} {2:F6}", Tangents[i,0].x, Tangents[i, 0].y, Tangents[i, 0].z); //Console.WriteLine("Binormal: {0:F6} {1:F6} {2:F6}", Tangents[i, 1].x, Tangents[i, 1].y, Tangents[i, 1].z); //Console.WriteLine("Normal: {0:F6} {1:F6} {2:F6}", Normals[i].x, Normals[i].y, Normals[i].z); break; default: throw new Exception("Need to add new Tangent Size"); } } //Log($"Offset is {r.BaseStream.Position:X}"); break; case DataStreamTypeEnum.COLORS: switch (BytesPerElement) { case 3: RGBColors = new IRGB[NumElements]; for (var i = 0; i < NumElements; i++) { RGBColors[i].r = r.ReadByte(); RGBColors[i].g = r.ReadByte(); RGBColors[i].b = r.ReadByte(); } break; case 4: RGBAColors = new IRGBA[NumElements]; for (var i = 0; i < NumElements; i++) { RGBAColors[i].r = r.ReadByte(); RGBAColors[i].g = r.ReadByte(); RGBAColors[i].b = r.ReadByte(); RGBAColors[i].a = r.ReadByte(); } break; default: Log("Unknown Color Depth"); for (var i = 0; i < NumElements; i++) { SkipBytes(r, BytesPerElement); } break; } break; case DataStreamTypeEnum.VERTSUVS: // 3 half floats for verts, 3 half floats for normals, 2 half floats for UVs Vertices = new Vector3[NumElements]; Normals = new Vector3[NumElements]; RGBColors = new IRGB[NumElements]; UVs = new UV[NumElements]; switch (BytesPerElement) // new Star Citizen files { case 20: // Dymek wrote this. Used in 2.6 skin files. 3 floats for vertex position, 4 bytes for normals, 2 halfs for UVs. Normals are calculated from Tangents for (var i = 0; i < NumElements; i++) { Vertices[i].x = r.ReadSingle(); Vertices[i].y = r.ReadSingle(); Vertices[i].z = r.ReadSingle(); // For some reason, skins are an extra 1 meter in the z direction. // Normals are stored in a signed byte, prob div by 127. Normals[i].x = (float)r.ReadSByte() / 127; Normals[i].y = (float)r.ReadSByte() / 127; Normals[i].z = (float)r.ReadSByte() / 127; r.ReadSByte(); // Should be FF. UVs[i].U = new Half { bits = r.ReadUInt16() }.ToSingle(); UVs[i].V = new Half { bits = r.ReadUInt16() }.ToSingle(); //UVs[i].U = Byte4HexToFloat(r.ReadUInt16().ToString("X8")); //UVs[i].V = Byte4HexToFloat(r.ReadUInt16().ToString("X8")); } break; case 16: // Dymek updated this. //Console.WriteLine("method: (5), 3 half floats for verts, 3 colors, 2 half floats for UVs"); for (var i = 0; i < NumElements; i++) { ushort bver = 0; var ver = 0F; Vertices[i].x = Byte2HexIntFracToFloat2(r.ReadUInt16().ToString("X4")) / 127f; Vertices[i].y = Byte2HexIntFracToFloat2(r.ReadUInt16().ToString("X4")) / 127f; Vertices[i].z = Byte2HexIntFracToFloat2(r.ReadUInt16().ToString("X4")) / 127f; Vertices[i].w = Byte2HexIntFracToFloat2(r.ReadUInt16().ToString("X4")) / 127f; // Almost always 1 // Next structure is Colors, not normals. For 16 byte elements, normals are calculated from Tangent data. //RGBColors[i].r = r.ReadByte(); //RGBColors[i].g = r.ReadByte(); //RGBColors[i].b = r.ReadByte(); //r.ReadByte(); // additional byte. // //Normals[i].x = (r.ReadByte() - 128.0f) / 127.5f; //Normals[i].y = (r.ReadByte() - 128.0f) / 127.5f; //Normals[i].z = (r.ReadByte() - 128.0f) / 127.5f; //r.ReadByte(); // additional byte. // Read a Quat, convert it to vector3 var quat = new Vector4 { x = (r.ReadByte() - 128.0f) / 127.5f, y = (r.ReadByte() - 128.0f) / 127.5f, z = (r.ReadByte() - 128.0f) / 127.5f, w = (r.ReadByte() - 128.0f) / 127.5f }; Normals[i].x = (2 * (quat.x * quat.z + quat.y * quat.w)); Normals[i].y = (2 * (quat.y * quat.z - quat.x * quat.w)); Normals[i].z = (2 * (quat.z * quat.z + quat.w * quat.w)) - 1; // UVs ABSOLUTELY should use the Half structures. UVs[i].U = new Half { bits = r.ReadUInt16() }.ToSingle(); UVs[i].V = new Half { bits = r.ReadUInt16() }.ToSingle(); //Vertices[i].x = new Half { bits = r.ReadUInt16() }.ToSingle(); //Vertices[i].y = new Half { bits = r.ReadUInt16() }.ToSingle(); //Vertices[i].z = new Half { bits = r.ReadUInt16() }.ToSingle(); //Normals[i].x = new Half { bits = r.ReadUInt16() }.ToSingle(); //Normals[i].y = new Half { bits = r.ReadUInt16() }.ToSingle(); //Normals[i].z = new Half { bits = r.ReadUInt16() }.ToSingle(); //UVs[i].U = new Half { bits = r.ReadUInt16() }.ToSingle(); //UVs[i].V = new Half { bits = r.ReadUInt16() }.ToSingle(); } break; default: Log("Unknown VertUV structure"); SkipBytes(r, NumElements * BytesPerElement); break; } break; case DataStreamTypeEnum.BONEMAP: var skin = GetSkinningInfo(); skin.HasBoneMapDatastream = true; skin.BoneMapping = new List <MeshBoneMapping>(); // Bones should have 4 bone IDs (index) and 4 weights. for (var i = 0; i < NumElements; i++) { var tmpMap = new MeshBoneMapping(); switch (BytesPerElement) { case 8: tmpMap.BoneIndex = new int[4]; tmpMap.Weight = new int[4]; for (var j = 0; j < 4; j++) // read the 4 bone indexes first { tmpMap.BoneIndex[j] = r.ReadByte(); } for (var j = 0; j < 4; j++) // read the weights. { tmpMap.Weight[j] = r.ReadByte(); } skin.BoneMapping.Add(tmpMap); break; case 12: tmpMap.BoneIndex = new int[4]; tmpMap.Weight = new int[4]; for (var j = 0; j < 4; j++) // read the 4 bone indexes first { tmpMap.BoneIndex[j] = r.ReadUInt16(); } for (var j = 0; j < 4; j++) // read the weights. { tmpMap.Weight[j] = r.ReadByte(); } skin.BoneMapping.Add(tmpMap); break; default: Log("Unknown BoneMapping structure"); break; } } break; case DataStreamTypeEnum.UNKNOWN1: Tangents = new Tangent[NumElements, 2]; Normals = new Vector3[NumElements]; for (var i = 0; i < NumElements; i++) { Tangents[i, 0].w = r.ReadSByte() / 127.0f; Tangents[i, 0].x = r.ReadSByte() / 127.0f; Tangents[i, 0].y = r.ReadSByte() / 127.0f; Tangents[i, 0].z = r.ReadSByte() / 127.0f; // Binormal Tangents[i, 1].w = r.ReadSByte() / 127.0f; Tangents[i, 1].x = r.ReadSByte() / 127.0f; Tangents[i, 1].y = r.ReadSByte() / 127.0f; Tangents[i, 1].z = r.ReadSByte() / 127.0f; // Calculate the normal based on the cross product of the tangents. Normals[i].x = (Tangents[i, 0].y * Tangents[i, 1].z - Tangents[i, 0].z * Tangents[i, 1].y); Normals[i].y = 0 - (Tangents[i, 0].x * Tangents[i, 1].z - Tangents[i, 0].z * Tangents[i, 1].x); Normals[i].z = (Tangents[i, 0].x * Tangents[i, 1].y - Tangents[i, 0].y * Tangents[i, 1].x); } break; default: Log("***** Unknown DataStream Type *****"); break; } }
/// <summary> /// 获取当前模型指定视图内的所有最外层的墙体 /// Get all the outermost walls in the /// specified view of the current model /// </summary> /// <param name="doc"></param> /// <param name="view">视图,默认是当前激活的视图 /// View, default is currently active view</param> public static List <ElementId> GetOutermostWalls( Document doc, View view = null) { double offset = Util.MmToFoot(1000); if (view == null) { view = doc.ActiveView; } #region Obsolete code using wall location line instad of bounding box //获取顶点 最小x,最大y ; 最大x,最小y #if BEFORE_USING_BOUNDING_BOX List <Wall> wallList = new FilteredElementCollector(doc) .OfClass(typeof(Wall)) .Cast <Wall>() .ToList(); double maxX = -1D; double minX = -1D; double maxY = -1D; double minY = -1D; wallList.ForEach((wall) => { Curve curve = (wall.Location as LocationCurve).Curve; XYZ xyz1 = curve.GetEndPoint(0); XYZ xyz2 = curve.GetEndPoint(1); double _minX = Math.Min(xyz1.X, xyz2.X); double _maxX = Math.Max(xyz1.X, xyz2.X); double _minY = Math.Min(xyz1.Y, xyz2.Y); double _maxY = Math.Max(xyz1.Y, xyz2.Y); if (curve.IsCyclic) { Arc arc = curve as Arc; double _radius = arc.Radius; //粗略对x和y 加/减 _maxX += _radius; _minX -= _radius; _maxY += _radius; _minY += _radius; } if (minX == -1) { minX = _minX; } if (maxX == -1) { maxX = _maxX; } if (maxY == -1) { maxY = _maxY; } if (minY == -1) { minY = _minY; } if (_minX < minX) { minX = _minX; } if (_maxX > maxX) { maxX = _maxX; } if (_maxY > maxY) { maxY = _maxY; } if (_minY < minY) { minY = _minY; } }); double minX = bb.Min.X - offset; double maxX = bb.Max.X + offset; double minY = bb.Min.Y - offset; double maxY = bb.Max.Y + offset; CurveArray curves = new CurveArray(); Line line1 = Line.CreateBound(new XYZ(minX, maxY, 0), new XYZ(maxX, maxY, 0)); Line line2 = Line.CreateBound(new XYZ(maxX, maxY, 0), new XYZ(maxX, minY, 0)); Line line3 = Line.CreateBound(new XYZ(maxX, minY, 0), new XYZ(minX, minY, 0)); Line line4 = Line.CreateBound(new XYZ(minX, minY, 0), new XYZ(minX, maxY, 0)); curves.Append(line1); curves.Append(line2); curves.Append(line3); curves.Append(line4); #endif // BEFORE_USING_BOUNDING_BOX #endregion // Obsolete code using wall location line instad of bounding box BoundingBoxXYZ bb = GetBoundingBoxAroundAllWalls( doc, view); XYZ voffset = offset * (XYZ.BasisX + XYZ.BasisY); bb.Min -= voffset; bb.Max += voffset; XYZ[] bottom_corners = Util.GetBottomCorners( bb, 0); CurveArray curves = new CurveArray(); for (int i = 0; i < 4; ++i) { int j = i < 3 ? i + 1 : 0; curves.Append(Line.CreateBound( bottom_corners[i], bottom_corners[j])); } using (TransactionGroup group = new TransactionGroup(doc)) { Room newRoom = null; group.Start("Find Outermost Walls"); using (Transaction transaction = new Transaction(doc)) { transaction.Start( "Create New Room Boundary Lines"); SketchPlane sketchPlane = SketchPlane.Create( doc, view.GenLevel.Id); ModelCurveArray modelCaRoomBoundaryLines = doc.Create.NewRoomBoundaryLines( sketchPlane, curves, view); // 创建房间的坐标点 -- Create room coordinates double d = Util.MmToFoot(600); UV point = new UV(bb.Min.X + d, bb.Min.Y + d); // 根据选中点,创建房间 当前视图的楼层 doc.ActiveView.GenLevel // Create room at selected point on the current view level newRoom = doc.Create.NewRoom(view.GenLevel, point); if (newRoom == null) { string msg = "创建房间失败。"; TaskDialog.Show("xx", msg); transaction.RollBack(); return(null); } RoomTag tag = doc.Create.NewRoomTag( new LinkElementId(newRoom.Id), point, view.Id); transaction.Commit(); } //获取房间的墙体 -- Get the room walls List <ElementId> ids = RetrieveWallsGeneratingRoomBoundaries( doc, newRoom); group.RollBack(); // 撤销 return(ids); } }
public IndexedColor2D(Color color, UV parameter) { Color = color; Parameter = parameter; }
/// <summary> /// Attempts to create a clipping, recess, or opening from a collection of faces. /// </summary> /// <param name="exporterIFC">The exporter.</param> /// <param name="cuttingElement">The cutting element. This will help determine whether to use a clipping or opening in boundary cases.</param> /// <param name="extrusionBasePlane">The plane of the extrusion base.</param> /// <param name="extrusionDirection">The extrusion direction.</param> /// <param name="faces">The collection of faces.</param> /// <param name="range">The valid range of the extrusion.</param> /// <param name="origBodyRepHnd">The original body representation.</param> /// <returns>The new body representation. If the clipping completely clips the extrusion, this will be null. Otherwise, this /// will be the clipped representation if a clipping was done, or the original representation if not.</returns> public static IFCAnyHandle CreateClippingFromFaces(ExporterIFC exporterIFC, Element cuttingElement, Plane extrusionBasePlane, XYZ extrusionDirection, ICollection<Face> faces, IFCRange range, IFCAnyHandle origBodyRepHnd) { if (IFCAnyHandleUtil.IsNullOrHasNoValue(origBodyRepHnd)) return null; bool polygonalOnly = ExporterCacheManager.ExportOptionsCache.ExportAs2x2; IList<CurveLoop> outerCurveLoops = new List<CurveLoop>(); IList<Plane> outerCurveLoopPlanes = new List<Plane>(); IList<bool> boundaryIsPolygonal = new List<bool>(); bool allPlanes = true; UV faceOriginUV = new UV(0, 0); foreach (Face face in faces) { FaceBoundaryType faceBoundaryType; CurveLoop curveLoop = GetOuterFaceBoundary(face, null, polygonalOnly, out faceBoundaryType); outerCurveLoops.Add(curveLoop); boundaryIsPolygonal.Add(faceBoundaryType == FaceBoundaryType.Polygonal); if (face is PlanarFace) { PlanarFace planarFace = face as PlanarFace; XYZ faceOrigin = planarFace.Origin; XYZ faceNormal = planarFace.ComputeNormal(faceOriginUV); Plane plane = new Plane(faceNormal, faceOrigin); outerCurveLoopPlanes.Add(plane); if (!curveLoop.IsCounterclockwise(faceNormal)) curveLoop.Flip(); } else { outerCurveLoopPlanes.Add(null); allPlanes = false; } } if (allPlanes) { int numFaces = faces.Count; // Special case: one face is a clip plane. if (numFaces == 1) { return ProcessClippingFace(exporterIFC, outerCurveLoops[0], outerCurveLoopPlanes[0], extrusionBasePlane, extrusionDirection, range, false, origBodyRepHnd); } KeyValuePair<bool, bool> clipsExtrusionEnds = CollectionClipsExtrusionEnds(outerCurveLoops, extrusionDirection, range); if (clipsExtrusionEnds.Key == true || clipsExtrusionEnds.Value == true) { // Don't clip for a door, window or opening. if (CreateOpeningForCategory(cuttingElement)) throw new Exception("Unhandled opening."); ICollection<int> facesToSkip = new HashSet<int>(); bool clipStart = (clipsExtrusionEnds.Key == true); bool clipBoth = (clipsExtrusionEnds.Key == true && clipsExtrusionEnds.Value == true); if (!clipBoth) { for (int ii = 0; ii < numFaces; ii++) { double slant = outerCurveLoopPlanes[ii].Normal.DotProduct(extrusionDirection); if (!MathUtil.IsAlmostZero(slant)) { if (clipStart && (slant > 0.0)) throw new Exception("Unhandled clip plane direction."); if (!clipStart && (slant < 0.0)) throw new Exception("Unhandled clip plane direction."); } else { facesToSkip.Add(ii); } } } else { // If we are clipping both the start and end of the extrusion, we have to make sure all of the clipping // planes have the same a non-negative dot product relative to one another. int clipOrientation = 0; for (int ii = 0; ii < numFaces; ii++) { double slant = outerCurveLoopPlanes[ii].Normal.DotProduct(extrusionDirection); if (!MathUtil.IsAlmostZero(slant)) { if (slant > 0.0) { if (clipOrientation < 0) throw new Exception("Unhandled clipping orientations."); clipOrientation = 1; } else { if (clipOrientation > 0) throw new Exception("Unhandled clipping orientations."); clipOrientation = -1; } } else { facesToSkip.Add(ii); } } } IFCAnyHandle newBodyRepHnd = origBodyRepHnd; for (int ii = 0; ii < numFaces; ii++) { if (facesToSkip.Contains(ii)) continue; newBodyRepHnd = ProcessClippingFace(exporterIFC, outerCurveLoops[ii], outerCurveLoopPlanes[ii], extrusionBasePlane, extrusionDirection, range, true, newBodyRepHnd); if (newBodyRepHnd == null) return null; } return newBodyRepHnd; } } //not handled throw new Exception("Unhandled clipping."); }
/// <summary> /// Returns the color in this color range at the specified parameter. /// </summary> /// <param name="parameter">A UV between (0.0,0.0) and (1.0,1.0).</param> /// <returns>A Color.</returns> public Color GetColorAtParameter(UV parameter) { var color = Color.ByARGB(255, 255, 255, 255); var weightedColors = indexedColors.ToList() .OrderBy(ic => ic.Parameter.Area(parameter)).Take(4).ToList(); color = Color.Blerp(weightedColors, parameter); return color; }
public static Color BuildColorFrom2DRange(IList<Color> colors, IList<UV> parameters, UV parameter) { var colorRange = ColorRange2D.ByColorsAndParameters(colors, parameters); return colorRange.GetColorAtParameter(parameter); }
// This routine may return null geometry for one of three reasons: // 1. Invalid input. // 2. No IfcMaterialLayerUsage. // 3. The IfcMaterialLayerUsage isn't handled. // If the reason is #1 or #3, we want to warn the user. If it is #2, we don't. Pass back shouldWarn to let the caller know. private IList <GeometryObject> CreateGeometryFromMaterialLayerUsage(IFCImportShapeEditScope shapeEditScope, Transform extrusionPosition, IList <CurveLoop> loops, XYZ extrusionDirection, double currDepth, out ElementId materialId, out bool shouldWarn) { IList <GeometryObject> extrusionSolids = null; materialId = ElementId.InvalidElementId; try { shouldWarn = true; // Invalid input. // Check for valid input. if (shapeEditScope == null || extrusionPosition == null || loops == null || loops.Count() == 0 || extrusionDirection == null || !extrusionPosition.IsConformal || !Application.IsValidThickness(currDepth)) { return(null); } IFCProduct creator = shapeEditScope.Creator; if (creator == null) { return(null); } shouldWarn = false; // Missing, empty, or optimized out IfcMaterialLayerSetUsage - valid reason to stop. IIFCMaterialSelect materialSelect = creator.MaterialSelect; if (materialSelect == null) { return(null); } IFCMaterialLayerSetUsage materialLayerSetUsage = materialSelect as IFCMaterialLayerSetUsage; if (materialLayerSetUsage == null) { return(null); } IFCMaterialLayerSet materialLayerSet = materialLayerSetUsage.MaterialLayerSet; if (materialLayerSet == null) { return(null); } IList <IFCMaterialLayer> materialLayers = materialLayerSet.MaterialLayers; if (materialLayers == null || materialLayers.Count == 0) { return(null); } // Optimization: if there is only one layer, use the standard method, with possibly an overloaded material. ElementId baseMaterialId = GetMaterialElementId(shapeEditScope); if (materialLayers.Count == 1) { IFCMaterial oneMaterial = materialLayers[0].Material; if (oneMaterial == null) { return(null); } materialId = oneMaterial.GetMaterialElementId(); if (materialId != ElementId.InvalidElementId) { // We will not override the material of the element if the layer material has no color. if (Importer.TheCache.MaterialsWithNoColor.Contains(materialId)) { materialId = ElementId.InvalidElementId; } } return(null); } // Anything below here is something we should report to the user, with the exception of the total thickness // not matching the extrusion thickness. This would require more analysis to determine that it is actually // an error condition. shouldWarn = true; IList <IFCMaterialLayer> realMaterialLayers = new List <IFCMaterialLayer>(); double totalThickness = 0.0; foreach (IFCMaterialLayer materialLayer in materialLayers) { double depth = materialLayer.LayerThickness; if (MathUtil.IsAlmostZero(depth)) { continue; } if (depth < 0.0) { return(null); } realMaterialLayers.Add(materialLayer); totalThickness += depth; } // Axis3 means that the material layers are stacked in the Z direction. This is common for floor slabs. bool isAxis3 = (materialLayerSetUsage.Direction == IFCLayerSetDirection.Axis3); // For elements extruded in the Z direction, if the extrusion layers don't have the same thickness as the extrusion, // this could be one of two reasons: // 1. There is a discrepancy between the extrusion depth and the material layer set usage calculated depth. // 2. There are multiple extrusions in the body definition. // In either case, we will use the extrusion geometry over the calculated material layer set usage geometry. // In the future, we may decide to allow for case #1 by passing in a flag to allow for this. if (isAxis3 && !MathUtil.IsAlmostEqual(totalThickness, currDepth)) { shouldWarn = false; return(null); } int numLayers = realMaterialLayers.Count(); if (numLayers == 0) { return(null); } // We'll use this initial value for the Axis2 case, so read it here. double baseOffsetForLayer = materialLayerSetUsage.Offset; // Needed for Axis2 case only. The axisCurve is the curve defined in the product representation representing // a base curve (an axis) for the footprint of the element. Curve axisCurve = null; // The oriented cuve list represents the 4 curves of supported Axis2 footprint in the following order: // 1. curve along length of object closest to the first material layer with the orientation of the axis curve // 2. connecting end curve // 3. curve along length of object closest to the last material layer with the orientation opposite of the axis curve // 4. connecting end curve. IList <Curve> orientedCurveList = null; if (!isAxis3) { // Axis2 means that the material layers are stacked inthe Y direction. This is by definition for IfcWallStandardCase, // which has a local coordinate system whose Y direction is orthogonal to the length of the wall. if (materialLayerSetUsage.Direction == IFCLayerSetDirection.Axis2) { axisCurve = GetAxisCurve(creator, extrusionPosition); if (axisCurve == null) { return(null); } orientedCurveList = GetOrientedCurveList(loops, axisCurve, extrusionPosition.BasisZ, baseOffsetForLayer, totalThickness); if (orientedCurveList == null) { return(null); } } else { return(null); // Not handled. } } extrusionSolids = new List <GeometryObject>(); bool positiveOrientation = (materialLayerSetUsage.DirectionSense == IFCDirectionSense.Positive); // Always extrude in the positive direction for Axis2. XYZ materialExtrusionDirection = (positiveOrientation || !isAxis3) ? extrusionDirection : -extrusionDirection; // Axis2 repeated values. // The IFC concept of offset direction is reversed from Revit's. XYZ normalDirectionForAxis2 = positiveOrientation ? -extrusionPosition.BasisZ : extrusionPosition.BasisZ; bool axisIsCyclic = (axisCurve == null) ? false : axisCurve.IsCyclic; double axisCurvePeriod = axisIsCyclic ? axisCurve.Period : 0.0; Transform curveLoopTransform = Transform.Identity; IList <CurveLoop> currLoops = null; double depthSoFar = 0.0; for (int ii = 0; ii < numLayers; ii++) { IFCMaterialLayer materialLayer = materialLayers[ii]; // Ignore 0 thickness layers. No need to warn. double depth = materialLayer.LayerThickness; if (MathUtil.IsAlmostZero(depth)) { continue; } // If the thickness is non-zero but invalid, fail. if (!Application.IsValidThickness(depth)) { return(null); } double extrusionDistance = 0.0; if (isAxis3) { // Offset the curve loops if necessary, using the base extrusionDirection, regardless of the direction sense // of the MaterialLayerSetUsage. double offsetForLayer = positiveOrientation ? baseOffsetForLayer + depthSoFar : baseOffsetForLayer - depthSoFar; if (!MathUtil.IsAlmostZero(offsetForLayer)) { curveLoopTransform.Origin = offsetForLayer * extrusionDirection; currLoops = new List <CurveLoop>(); foreach (CurveLoop loop in loops) { CurveLoop newLoop = CurveLoop.CreateViaTransform(loop, curveLoopTransform); if (newLoop == null) { return(null); } currLoops.Add(newLoop); } } else { currLoops = loops; } extrusionDistance = depth; } else { // startClipCurve, firstEndCapCurve, endClipCurve, secondEndCapCurve. Curve[] outline = new Curve[4]; double[][] endParameters = new double[4][]; double startClip = depthSoFar; double endClip = depthSoFar + depth; outline[0] = orientedCurveList[0].CreateOffset(startClip, normalDirectionForAxis2); outline[1] = orientedCurveList[1].Clone(); outline[2] = orientedCurveList[2].CreateOffset(totalThickness - endClip, normalDirectionForAxis2); outline[3] = orientedCurveList[3].Clone(); for (int jj = 0; jj < 4; jj++) { outline[jj].MakeUnbound(); endParameters[jj] = new double[2]; endParameters[jj][0] = 0.0; endParameters[jj][1] = 0.0; } // Trim/Extend the curves so that they make a closed loop. for (int jj = 0; jj < 4; jj++) { IntersectionResultArray resultArray = null; outline[jj].Intersect(outline[(jj + 1) % 4], out resultArray); if (resultArray == null || resultArray.Size == 0) { return(null); } int numResults = resultArray.Size; if ((numResults > 1 && !axisIsCyclic) || (numResults > 2)) { return(null); } UV intersectionPoint = resultArray.get_Item(0).UVPoint; endParameters[jj][1] = intersectionPoint.U; endParameters[(jj + 1) % 4][0] = intersectionPoint.V; if (numResults == 2) { // If the current result is closer to the end of the curve, keep it. UV newIntersectionPoint = resultArray.get_Item(1).UVPoint; int endParamIndex = (jj % 2); double newParamToCheck = newIntersectionPoint[endParamIndex]; double oldParamToCheck = (endParamIndex == 0) ? endParameters[jj][1] : endParameters[(jj + 1) % 4][0]; double currentEndPoint = (endParamIndex == 0) ? orientedCurveList[jj].GetEndParameter(1) : orientedCurveList[(jj + 1) % 4].GetEndParameter(0); // Put in range of [-Period/2, Period/2]. double newDist = (currentEndPoint - newParamToCheck) % axisCurvePeriod; if (newDist < -axisCurvePeriod / 2.0) { newDist += axisCurvePeriod; } if (newDist > axisCurvePeriod / 2.0) { newDist -= axisCurvePeriod; } double oldDist = (currentEndPoint - oldParamToCheck) % axisCurvePeriod; if (oldDist < -axisCurvePeriod / 2.0) { oldDist += axisCurvePeriod; } if (oldDist > axisCurvePeriod / 2.0) { oldDist -= axisCurvePeriod; } if (Math.Abs(newDist) < Math.Abs(oldDist)) { endParameters[jj][1] = newIntersectionPoint.U; endParameters[(jj + 1) % 4][0] = newIntersectionPoint.V; } } } CurveLoop newCurveLoop = new CurveLoop(); for (int jj = 0; jj < 4; jj++) { if (endParameters[jj][1] < endParameters[jj][0]) { if (!outline[jj].IsCyclic) { return(null); } endParameters[jj][1] += Math.Floor(endParameters[jj][0] / axisCurvePeriod + 1.0) * axisCurvePeriod; } outline[jj].MakeBound(endParameters[jj][0], endParameters[jj][1]); newCurveLoop.Append(outline[jj]); } currLoops = new List <CurveLoop>(); currLoops.Add(newCurveLoop); extrusionDistance = currDepth; } // Determine the material id. IFCMaterial material = materialLayer.Material; ElementId layerMaterialId = (material == null) ? ElementId.InvalidElementId : material.GetMaterialElementId(); // The second option here is really for Referencing. Without a UI (yet) to determine whether to show the base // extusion or the layers for objects with material layer sets, we've chosen to display the base material if the layer material // has no color information. This means that the layer is assigned the "wrong" material, but looks better on screen. // We will reexamine this decision (1) for the Open case, (2) if there is UI to toggle between layers and base extrusion, or // (3) based on user feedback. if (layerMaterialId == ElementId.InvalidElementId || Importer.TheCache.MaterialsWithNoColor.Contains(layerMaterialId)) { layerMaterialId = baseMaterialId; } SolidOptions solidOptions = new SolidOptions(layerMaterialId, shapeEditScope.GraphicsStyleId); // Create the extrusion for the material layer. GeometryObject extrusionSolid = GeometryCreationUtilities.CreateExtrusionGeometry( currLoops, materialExtrusionDirection, extrusionDistance, solidOptions); if (extrusionSolid == null) { return(null); } extrusionSolids.Add(extrusionSolid); depthSoFar += depth; } } catch { // Ignore the specific exception, but let the user know there was a problem processing the IfcMaterialLayerSetUsage. shouldWarn = true; return(null); } return(extrusionSolids); }
public Shell(UV uv) : base() { this.U = uv.U; this.V = uv.V; }
/// <summary> /// Return a reference to the topmost face of the given element. /// </summary> private Reference FindTopMostReference(Element e) { Reference ret = null; Document doc = e.Document; #region Revit 2012 #if _2012 using (SubTransaction t = new SubTransaction(doc)) { t.Start(); // Create temporary 3D view //View3D view3D = doc.Create.NewView3D( // 2012 // viewDirection ); // 2012 ViewFamilyType vft = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault <ViewFamilyType>(x => ViewFamily.ThreeDimensional == x.ViewFamily); Debug.Assert(null != vft, "expected to find a valid 3D view family type"); View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013 XYZ eyePosition = XYZ.BasisZ; XYZ upDirection = XYZ.BasisY; XYZ forwardDirection = -XYZ.BasisZ; view.SetOrientation(new ViewOrientation3D( eyePosition, upDirection, forwardDirection)); XYZ viewDirection = -XYZ.BasisZ; BoundingBoxXYZ bb = e.get_BoundingBox(view); XYZ max = bb.Max; XYZ minAtMaxElevation = Create.NewXYZ( bb.Min.X, bb.Min.Y, max.Z); XYZ centerOfTopOfBox = 0.5 * (minAtMaxElevation + max); centerOfTopOfBox += 10 * XYZ.BasisZ; // Cast a ray through the model // to find the topmost surface #if DEBUG //ReferenceArray references // = doc.FindReferencesByDirection( // centerOfTopOfBox, viewDirection, view3D ); // 2011 IList <ReferenceWithContext> references = doc.FindReferencesWithContextByDirection( centerOfTopOfBox, viewDirection, view); // 2012 double closest = double.PositiveInfinity; //foreach( Reference r in references ) //{ // // 'Autodesk.Revit.DB.Reference.Element' is // // obsolete: Property will be removed. Use // // Document.GetElement(Reference) instead. // //Element re = r.Element; // 2011 // Element re = doc.GetElement( r ); // 2012 // if( re.Id.IntegerValue == e.Id.IntegerValue // && r.ProximityParameter < closest ) // { // ret = r; // closest = r.ProximityParameter; // } //} foreach (ReferenceWithContext r in references) { Element re = doc.GetElement( r.GetReference()); // 2012 if (re.Id.IntegerValue == e.Id.IntegerValue && r.Proximity < closest) { ret = r.GetReference(); closest = r.Proximity; } } string stable_reference = null == ret ? null : ret.ConvertToStableRepresentation(doc); #endif // DEBUG ReferenceIntersector ri = new ReferenceIntersector( e.Id, FindReferenceTarget.Element, view); ReferenceWithContext r2 = ri.FindNearest( centerOfTopOfBox, viewDirection); if (null == r2) { Debug.Print("ReferenceIntersector.FindNearest returned null!"); } else { ret = r2.GetReference(); Debug.Assert(stable_reference.Equals(ret .ConvertToStableRepresentation(doc)), "expected same reference from " + "FindReferencesWithContextByDirection and " + "ReferenceIntersector"); } t.RollBack(); } #endif // _2012 #endregion // Revit 2012 Options opt = doc.Application.Create .NewGeometryOptions(); opt.ComputeReferences = true; GeometryElement geo = e.get_Geometry(opt); foreach (GeometryObject obj in geo) { GeometryInstance inst = obj as GeometryInstance; if (null != inst) { geo = inst.GetSymbolGeometry(); break; } } Solid solid = geo.OfType <Solid>() .First <Solid>(sol => null != sol); double z = double.MinValue; foreach (Face f in solid.Faces) { BoundingBoxUV b = f.GetBoundingBox(); UV p = b.Min; UV q = b.Max; UV midparam = p + 0.5 * (q - p); XYZ midpoint = f.Evaluate(midparam); XYZ normal = f.ComputeNormal(midparam); if (Util.PointsUpwards(normal)) { if (midpoint.Z > z) { z = midpoint.Z; ret = f.Reference; } } } return(ret); }
private List <List <Floor> > createLiningConcreteAsFloor2(Document doc, ElementId myFoundtionId, string nameFamily, double offsetValue, bool isCutting) { Element myFoundation = doc.GetElement(myFoundtionId) as Element; //Get level from elemet Level myLevel = doc.GetElement(myFoundation.LevelId) as Level; //Get geometry from element GeometryElement geometryElement = myFoundation.get_Geometry(new Options()); //Get list Of face (with normal vector = xyz(0,0,-1); List <Face> myListBottomFace = new List <Face>(); using (Transaction myTrans = new Transaction(doc, "fil face of foundation")) { myTrans.Start(); UV myPoint = new UV(0, 0); foreach (GeometryObject geometryObject in geometryElement) { if (geometryObject is Solid) { Solid solid = geometryObject as Solid; XYZ myNormVec = new XYZ(); foreach (Face myFace in solid.Faces) { myNormVec = myFace.ComputeNormal(myPoint); // If normal vector of face has Z value == -1 add to list if (Math.Round(myNormVec.Z, 1) == -1.0) { myListBottomFace.Add(myFace); } } } } myTrans.Commit(); } // Now We has a list of face (with normal vector = (0,0,-1) //Save floor to a list List <Floor> myListLining = new List <Floor>(); // List Floor cutting List <Floor> myListLiningCutting = new List <Floor>(); using (Transaction trans = new Transaction(doc, "abc")) { trans.Start(); foreach (Face myPickedFace in myListBottomFace) { //Get Nomarl vector XYZ myNorVecFace = myPickedFace.ComputeNormal(new UV(0, 0)); List <CurveLoop> myListCurvefromFace = myPickedFace.GetEdgesAsCurveLoops() as List <CurveLoop>; CurveArray myBoundaFloor = new CurveArray(); foreach (CurveLoop myCurLoop in myListCurvefromFace) { if (myFoundation.Category.Name != "Structural Framing") { // Offset For Slab CurveLoop curOffset = CurveLoop.CreateViaOffset(myCurLoop, offsetValue, myNorVecFace); //TaskDialog.Show("abc", "xyz: " +curOffset.GetPlane().Normal.ToString()); foreach (Curve myCur in curOffset) { myBoundaFloor.Append(myCur); } } else { List <double> myOffsetDist = getOffsetDis(myCurLoop, offsetValue); CurveLoop curOffset = CurveLoop.CreateViaOffset(myCurLoop, myOffsetDist, myNorVecFace); //TaskDialog.Show("abc", "xyz: " +curOffset.GetPlane().Normal.ToString()); foreach (Curve myCur in curOffset) { myBoundaFloor.Append(myCur); } } } FloorType floorType = new FilteredElementCollector(doc) .OfClass(typeof(FloorType)) .OfCategory(BuiltInCategory.OST_Floors) .First <Element>(f => f.Name.Equals(nameFamily)) as FloorType; //Floor myLining = doc.Create.NewFoundationSlab(myBoundaFloor, floorType, myLevel, true, new XYZ(0,0,1)); //Floor myLining = doc.Create.NewFloor(myBoundaFloor, floorType, myLevel, true, new XYZ(0,0,1)); Floor myLining = doc.Create.NewFloor(myBoundaFloor, floorType, myLevel, true, new XYZ(0, 0, 1)); // Cutting if foundation is beam if (isCutting) { myListLiningCutting.Add(myLining); } myListLining.Add(myLining); } trans.Commit(); } // Switch Joint List <List <Floor> > myListListFloor = new List <List <Floor> >() { myListLining, myListLiningCutting }; return(myListListFloor); }
/// <summary> /// Return a string for a UV point /// or vector with its coordinates /// formatted to two decimal places. /// </summary> public static string PointString(UV p) { return(string.Format("({0},{1})", RealString(p.U), RealString(p.V))); }
private Point toPoint(UV p) { return(new Point(p.U, p.V)); }
public static SurfacePoint FromUV(UV uv) => new SurfacePoint(uv, null, null);
VecDot( UV va, UV vb ) { return ( ( va.U * vb.U ) + ( va.V * vb.V ) ); }
public static Coordinate ToNtsCoord(this UV _uv) { return(new Coordinate(_uv.U, _uv.V)); }
private static double Area(UV min, UV max) { var u = System.Math.Sqrt(System.Math.Pow(max.U - min.U, 2)); var v = System.Math.Sqrt(System.Math.Pow(max.V - min.V, 2)); return u * v; }
private void drawInRevit() { var timer = new System.Diagnostics.Stopwatch(); this._host.Hide(); UV p = this._host.OSM_to_BIM.PickPoint("Pick a vantage point to draw polygonal Isovist"); Cell cell = this._host.cellularFloor.FindCell(p); if (cell == null) { MessageBox.Show("Pick a point on the walkable field and try again!\n"); this._host.ShowDialog(); return; } switch (this._host.IsovistBarrierType) { case BarrierType.Visual: if (cell.VisualOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point outside visual barriers.\nTry again!"); this._host.ShowDialog(); return; } break; case BarrierType.Physical: if (cell.PhysicalOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point outside physical barriers.\nTry again!"); this._host.ShowDialog(); return; } break; case BarrierType.Field: if (cell.FieldOverlapState != OverlapState.Inside) { MessageBox.Show("Pick a point inside the walkable field.\nTry again!"); this._host.ShowDialog(); return; } break; case BarrierType.BarrierBuffer: if (cell.BarrierBufferOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point outside barrier buffers.\nTry again!"); this._host.ShowDialog(); return; } break; default: break; } try { timer.Start(); HashSet <UVLine> blocks = this._host.cellularFloor.PolygonalIsovistVisualObstacles(p, this._host.IsovistDepth, this._host.IsovistBarrierType); BarrierPolygon isovistPolygon = this._host.BIM_To_OSM.IsovistPolygon(p, this._host.IsovistDepth, blocks); timer.Stop(); isovistPolygon.Visualize(this._host.OSM_to_BIM, this._host.BIM_To_OSM.PlanElevation); this._host.IsovistInformation = new IsovistInformation(IsovistInformation.IsovistType.Polygonal, timer.Elapsed.TotalMilliseconds, isovistPolygon.GetArea(), isovistPolygon.GetPerimeter()); } catch (Exception error0) { this._host.IsovistInformation = null; MessageBox.Show(error0.Message); } timer = null; this._host.ShowDialog(); }
public override Value Evaluate(FSharpList<Value> args) { if (_reference.ElementReferenceType != ElementReferenceType.REFERENCE_TYPE_SURFACE && _reference.ElementReferenceType != ElementReferenceType.REFERENCE_TYPE_LINEAR ) { ElementId refElementId = _reference.ElementId; Element refElement = dynRevitSettings.Doc.Document.GetElement(refElementId); if (refElement is ReferencePoint) { ReferencePoint rp = refElement as ReferencePoint; XYZ rpXYZ = rp.Position; return Value.NewContainer(rpXYZ); } GeometryObject thisObjectPoint = SelectedElement.GetGeometryObjectFromReference(_reference); if (!(thisObjectPoint is Autodesk.Revit.DB.Point)) throw new Exception("Could not use face or edge which is not part of the model"); var thisPoint = thisObjectPoint as Autodesk.Revit.DB.Point; XYZ pointXYZ = thisPoint.Coord; return Value.NewContainer(pointXYZ); } GeometryObject thisObject = SelectedElement.GetGeometryObjectFromReference(_reference); Autodesk.Revit.DB.Transform thisTrf = null; if (_init && (old_refXyz == null || !_reference.Equals(old_refXyz))) _init = false; { GeometryObject geomObj = SelectedElement.get_Geometry(new Options()); var geomElement = geomObj as GeometryElement; // ugly code to detect if transform for geometry object is needed or not // filed request to provide this info via API, but meanwhile ... foreach (GeometryObject geob in geomElement) { if (!(geob is GeometryInstance)) continue; var ginsta = geob as GeometryInstance; GeometryElement gSymbolElement = ginsta.GetSymbolGeometry(); var geometryElements = new List<GeometryElement> { gSymbolElement }; bool found = false; for (; geometryElements.Count > 0 && !found;) { GeometryElement thisGeometryElement = geometryElements[0]; geometryElements.Remove(thisGeometryElement); foreach (GeometryObject geobSym in thisGeometryElement) { if (geobSym is GeometryElement) { geometryElements.Add(geobSym as GeometryElement); continue; } if ((thisObject is Curve) && (geobSym is Curve) && (thisObject == geobSym)) { found = true; break; } if (thisObject is Curve) continue; if ((thisObject is Autodesk.Revit.DB.Face) && (geobSym is Autodesk.Revit.DB.Face) && (thisObject == geobSym)) { found = true; break; } if ((thisObject is Edge) && (geobSym is Autodesk.Revit.DB.Face)) { var edge = thisObject as Edge; //use GetFace after r2013 support is dropped if (geobSym == edge.get_Face(0) || geobSym == edge.get_Face(1)) { found = true; break; } } if (!(geobSym is Solid)) continue; FaceArray solidFaces = ((Solid)geobSym).Faces; int numFaces = solidFaces.Size; for (int index = 0; index < numFaces && !found; index++) { Autodesk.Revit.DB.Face faceAt = solidFaces.get_Item(index); if ((thisObject is Autodesk.Revit.DB.Face) && (thisObject == faceAt)) { found = true; break; } if (thisObject is Edge) { var edge = thisObject as Edge; //use GetFace after r2013 support is dropped if (faceAt == edge.get_Face(0) || faceAt == edge.get_Face(1)) { found = true; break; } } } } } if (found) { thisTrf = ginsta.Transform; break; } } if (thisObject == null) throw new Exception("could not resolve reference for XYZ on Element"); } XYZ thisXYZ; if (_reference.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_SURFACE && thisObject is Autodesk.Revit.DB.Face) { var face = thisObject as Autodesk.Revit.DB.Face; if (!_init) { _param0 = _reference.UVPoint[0]; _param1 = _reference.UVPoint[1]; _init = true; } var uv = new UV(_param0, _param1); thisXYZ = face.Evaluate(uv); if (thisTrf != null) thisXYZ = thisTrf.OfPoint(thisXYZ); } else if (_reference.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_LINEAR) { Curve curve; if (thisObject is Edge) { var edge = (Edge)SelectedElement.GetGeometryObjectFromReference(_reference); curve = edge.AsCurve(); } else curve = (Curve)SelectedElement.GetGeometryObjectFromReference(_reference); if (curve != null) { if (_init) thisXYZ = curve.Evaluate(_param0, true); else { XYZ curPoint = _reference.GlobalPoint; if (thisTrf != null) { Autodesk.Revit.DB.Transform inverseTrf = thisTrf.Inverse; curPoint = inverseTrf.OfPoint(_reference.GlobalPoint); } IntersectionResult thisResult = curve.Project(curPoint); _param0 = curve.ComputeNormalizedParameter(thisResult.Parameter); _init = true; } thisXYZ = curve.Evaluate(_param0, true); _param1 = -1.0; } else throw new Exception("could not evaluate point on face or edge of the element"); if (thisTrf != null) thisXYZ = thisTrf.OfPoint(thisXYZ); } else throw new Exception("could not evaluate point on face or edge of the element"); old_refXyz = _reference; return Value.NewContainer(thisXYZ); }
private void mouseLeftButtonDown_GetPolygonalIsovist(object sender, MouseButtonEventArgs e) { var point = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV p = new UV(point.X, point.Y); Cell cell = this._host.cellularFloor.FindCell(p); if (cell == null) { MessageBox.Show("Pick a point on the walkable field and try again!\n"); return; } switch (this._host.IsovistBarrierType) { case BarrierType.Visual: if (cell.VisualOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point outside visual barriers.\nTry again!"); return; } break; case BarrierType.Physical: if (cell.PhysicalOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point outside physical barriers.\nTry again!"); return; } break; case BarrierType.Field: if (cell.FieldOverlapState != OverlapState.Inside) { MessageBox.Show("Pick a point inside the walkable field.\nTry again!"); return; } break; case BarrierType.BarrierBuffer: if (cell.BarrierBufferOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point outside barrier buffers.\nTry again!"); return; } break; default: break; } this._children.Clear(); var timer = new System.Diagnostics.Stopwatch(); try { timer.Start(); HashSet <UVLine> blocks = this._host.cellularFloor.PolygonalIsovistVisualObstacles(p, this._host.IsovistDepth, this._host.IsovistBarrierType); BarrierPolygon isovistPolygon = this._host.BIM_To_OSM.IsovistPolygon(p, this._host.IsovistDepth, blocks); IsovistPolygon newIsovistPolygon = new IsovistPolygon(isovistPolygon.BoundaryPoints, p); timer.Stop(); this._host.IsovistInformation = new IsovistInformation(IsovistInformation.IsovistType.Polygonal, timer.Elapsed.TotalMilliseconds, isovistPolygon.GetArea(), isovistPolygon.GetPerimeter()); this.draw(newIsovistPolygon); } catch (Exception error0) { this._host.IsovistInformation = null; MessageBox.Show(error0.Message); } timer = null; }
/// <summary> /// Converts a position in Revit internal units to IFC units. /// </summary> /// <param name="unscaledUV">The position in Revit internal units.</param> /// <returns>The position in IFC units.</returns> static public UV ScaleLength(UV unscaledUV) { return ExporterCacheManager.UnitsCache.Scale(UnitType.UT_Length, unscaledUV); }
private Point toPoint(UV uv) { return(new Point(uv.U, uv.V)); }
public void Execute(UIApplication uiapp) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name); if (uidoc.Selection.GetElementIds().Count != 1) { MessageBox.Show("Please select ONE Wall."); return; } Element myElementWall = doc.GetElement(uidoc.Selection.GetElementIds().First()); if (myElementWall.GetType() == typeof(FamilyInstance)) { FamilyInstance myFamilyInstance = myElementWall as FamilyInstance; myElementWall = myFamilyInstance.Host; if (myElementWall == null) { MessageBox.Show("Family instance must be hosted to a wall."); return; } } /// TECHNIQUE 08 OF 19 (EE08_MoveElementAroundHostingSurface.cs) ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ MOVING ELEMENTS AROUND A HOSTING SURFACE ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ /// The people walk around the perimeter of the wall, and it will work on any surface /// /// /// Interfaces and ENUM's: /// /// /// Demonstrates classes: /// Reference /// Face /// Transform /// PlanarFace /// CurveLoop /// /// /// Key methods: /// myElementWall.GetGeometryObjectFromReference(pickedRef) as Face /// pickedRef.ConvertToStableRepresentation(doc).Contains("INSTANCE")) /// (myElementWall as FamilyInstance).GetTotalTransform(); /// myFace.GetBoundingBox().Min /// myFace.Evaluate(myUV_Min) /// /// myXYZ_FamilyTransform.OfPoint(myXYZ_CornerOne) /// myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); /// myCurveLoop.GetExactLength(); /// /// /// L1.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); /// ElementTransformUtils.MoveElement(doc, myFamilyInstance.Id, myXYZ_MoveThisMuch); /// /// * class is actually part of the .NET framework (not Revit API) /// /// /// /// https://github.com/joshnewzealand/Revit-API-Playpen-CSharp List <Element> myListOfStuffOnWall = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_GenericModel).Where(x => (((FamilyInstance)x).Host != null)).Where(x => ((FamilyInstance)x).Host.Id == myElementWall.Id).ToList(); List <Element> myListOfFurniture = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Furniture).Where(x => (((FamilyInstance)x).Host != null)).Where(x => ((FamilyInstance)x).Host.Id == myElementWall.Id).ToList(); myListOfStuffOnWall.AddRange(myListOfFurniture); if (myListOfStuffOnWall.Count() > 0) { using (Transaction tx = new Transaction(doc)) { tx.Start("Rotate People"); foreach (FamilyInstance myFI in myListOfStuffOnWall) { FamilyInstance myFamilyInstance = myFI as FamilyInstance; Reference pickedRef = myFI.HostFace; ////doc.Delete(myListElementID); ////myListElementID.Clear(); Face myFace = myElementWall.GetGeometryObjectFromReference(pickedRef) as Face; if (myFace == null) { return; } Transform myXYZ_FamilyTransform = Transform.Identity; if (pickedRef.ConvertToStableRepresentation(doc).Contains("INSTANCE")) { myXYZ_FamilyTransform = (myElementWall as FamilyInstance).GetTotalTransform(); } Transform myTransform = Transform.Identity; if (myFace.GetType() != typeof(PlanarFace)) { return; } PlanarFace myPlanarFace = myFace as PlanarFace; UV myUV_Min = myFace.GetBoundingBox().Min; UV myUV_Max = myFace.GetBoundingBox().Max; XYZ myXYZ_CornerOne = myFace.Evaluate(myUV_Min); myTransform.Origin = myXYZ_FamilyTransform.OfPoint(myXYZ_CornerOne); myTransform.BasisX = myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); myTransform.BasisY = myXYZ_FamilyTransform.OfVector(myPlanarFace.YVector); myTransform.BasisZ = myXYZ_FamilyTransform.OfVector(myPlanarFace.FaceNormal); XYZ myXYZ_Centre = XYZ.Zero; XYZ myXYZ_Min = new XYZ(myUV_Min.U, myUV_Min.V, 0); XYZ myXYZ_Max = new XYZ(myUV_Max.U, myUV_Max.V, 0); XYZ myXYZ_UV_CornerOne = (((myXYZ_Max - myXYZ_Min) * 0.1)); //; + myXYZ_Min; XYZ myXYZ_UV_CornerTwo = (((myXYZ_Max - myXYZ_Min) * 0.9)); // + myXYZ_Min; XYZ myXYZ_UV_Corner01 = new XYZ(myXYZ_UV_CornerOne.X, myXYZ_UV_CornerOne.Y, 0); XYZ myXYZ_UV_Corner02 = new XYZ(myXYZ_UV_CornerTwo.X, myXYZ_UV_CornerOne.Y, 0); XYZ myXYZ_UV_Corner03 = new XYZ(myXYZ_UV_CornerTwo.X, myXYZ_UV_CornerTwo.Y, 0); XYZ myXYZ_UV_Corner04 = new XYZ(myXYZ_UV_CornerOne.X, myXYZ_UV_CornerTwo.Y, 0); Line L1 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner01), myTransform.OfPoint(myXYZ_UV_Corner02)); Line L2 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner02), myTransform.OfPoint(myXYZ_UV_Corner03)); Line L3 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner03), myTransform.OfPoint(myXYZ_UV_Corner04)); Line L4 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner04), myTransform.OfPoint(myXYZ_UV_Corner01)); CurveLoop myCurveLoop = new CurveLoop(); myCurveLoop.Append(L1); myCurveLoop.Append(L2); myCurveLoop.Append(L3); myCurveLoop.Append(L4); double myDouble_ExactLength = myCurveLoop.GetExactLength(); double myDouble_ExactLength_Twenty = myDouble_ExactLength / 40; XYZ myXYZ_Result = myTransform.OfPoint((myXYZ_Max - myXYZ_Min) / 2); int myIntCurrentSpinnerValue = myWindow1.myIntegerUpDown_OneToTwentyCount.Value.Value; int myInt_Positioning = (40 / myListOfStuffOnWall.Count()) * (myListOfStuffOnWall.IndexOf(myFI) + 1); myIntCurrentSpinnerValue = (40 - myInt_Positioning) + myIntCurrentSpinnerValue; if (myIntCurrentSpinnerValue > 40) { myIntCurrentSpinnerValue = myIntCurrentSpinnerValue - 40; } double myDouble_FutureForeach = myDouble_ExactLength_Twenty * myIntCurrentSpinnerValue; double myDouble_ThisFarAlong; switch (myDouble_FutureForeach) { case double n when n < L1.Length: myDouble_ThisFarAlong = myDouble_FutureForeach; myXYZ_Result = L1.GetEndPoint(0) + (L1.GetEndPoint(1) - L1.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; case double n when n >= L1.Length& n < L1.Length + L2.Length: myDouble_ThisFarAlong = myDouble_FutureForeach - L1.Length; myXYZ_Result = L2.GetEndPoint(0) + (L2.GetEndPoint(1) - L2.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; case double n when n >= L1.Length + L2.Length& n < L1.Length + L2.Length + L3.Length: myDouble_ThisFarAlong = myDouble_FutureForeach - L1.Length - L2.Length; myXYZ_Result = L3.GetEndPoint(0) + (L3.GetEndPoint(1) - L3.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; case double n when n >= L1.Length + L2.Length + L3.Length: myDouble_ThisFarAlong = myDouble_FutureForeach - L1.Length - L2.Length - L3.Length; myXYZ_Result = L4.GetEndPoint(0) + (L4.GetEndPoint(1) - L4.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; } XYZ myXYZ_MoveThisMuch = myXYZ_Result - ((LocationPoint)myFamilyInstance.Location).Point; ElementTransformUtils.MoveElement(doc, myFamilyInstance.Id, myXYZ_MoveThisMuch); //SketchPlane mySketchPlane = SketchPlane.Create(doc, pickedRef); //myListElementID.Add(doc.Create.NewModelCurve(L1, mySketchPlane).Id); //myListElementID.Add(doc.Create.NewModelCurve(L2, mySketchPlane).Id); //myListElementID.Add(doc.Create.NewModelCurve(L3, mySketchPlane).Id); //myListElementID.Add(doc.Create.NewModelCurve(L4, mySketchPlane).Id); } tx.Commit(); } if (myWindow1.myIntegerUpDown_OneToTwentyCount.Value.Value == 40) { myWindow1.myIntegerUpDown_OneToTwentyCount.Value = 0; } myWindow1.myIntegerUpDown_OneToTwentyCount.Value++; } } #region catch and finally catch (Exception ex) { DatabaseMethods.writeDebug("EE08_MoveElementAroundHostingSurface" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } finally { } #endregion }
/// <summary>Tries to allocate space for a rectangle in the packing area</summary> /// <param name="rectangleWidth">Width of the rectangle to allocate</param> /// <param name="rectangleHeight">Height of the rectangle to allocate</param> /// <param name="placement">Output parameter receiving the rectangle's placement</param> /// <returns>True if space for the rectangle could be allocated</returns> public abstract bool TryPack( double rectangleWidth, double rectangleHeight, out UV placement );
public void createALinearDimensionProject() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; using (Transaction trans = new Transaction(doc, "Create linear Dimension")) { trans.Start(); // S1: Pick an element Reference myRef = uiDoc.Selection.PickObject(ObjectType.Element, "Pick a foundation"); Element myE = doc.GetElement(myRef); Options geomOp = Application.Create.NewGeometryOptions(); geomOp.ComputeReferences = true; GeometryElement geometryElement = myE.get_Geometry(geomOp); // S2: Get Reference of face parallel // refArray to create dimension ReferenceArray ra = new ReferenceArray(); List <Face> myListFaces = new List <Face>(); List <Reference> myListRef = new List <Reference>(); foreach (GeometryObject geometryObject in geometryElement) { UV myPoint = new UV(); if (geometryObject is Solid) { Solid solid = geometryObject as Solid; XYZ myNormFace = new XYZ(); foreach (Face myFace in solid.Faces) { myNormFace = myFace.ComputeNormal(myPoint); if (Math.Abs(Math.Round(myNormFace.Z, 1)) == 1.0) { myListFaces.Add(myFace); myListRef.Add(myFace.Reference); ra.Append(myFace.Reference); } } } } // Pick a dimension to get line from it Reference myRefDim = uiDoc.Selection.PickObject(ObjectType.Element, "Pick a dimension...."); Dimension myDimExits = doc.GetElement(myRefDim) as Dimension; Line lineDim = myDimExits.Curve as Line; Line line2 = lineDim.CreateOffset(1, new XYZ(1, 1, 0)) as Line; Dimension myDim = doc.Create.NewDimension(doc.ActiveView, line2, ra); trans.Commit(); } }
Rescale(Autodesk.Revit.DB.View view, double x, double y) { double Rescale = 2; UV outline = new UV(view.Outline.Max.U - view.Outline.Min.U, view.Outline.Max.V - view.Outline.Min.V); if (outline.U > outline.V) { Rescale = outline.U / x * Rescale; } else { Rescale = outline.V / y * Rescale; } if (1 != view.Scale) { view.Scale = (int)(view.Scale * Rescale); } }
public void PickPointsForArea( UIDocument uidoc) { Document doc = uidoc.Document; View view = doc.ActiveView; #region COMPLICATED_UNRELIABLE_DOES_NOT_WORK #if COMPLICATED_UNRELIABLE_DOES_NOT_WORK using (Transaction t = new Transaction(doc)) { t.Start("Set Work Plane"); Plane plane = new Plane( view.ViewDirection, view.Origin); //SketchPlane sp = doc.Create.NewSketchPlane( plane ); SketchPlane sp = SketchPlane.Create(doc, plane); view.SketchPlane = sp; view.ShowActiveWorkPlane(); t.Commit(); } double differenceX; double differenceY; double differenceZ; double area; XYZ pt1 = uidoc.Selection.PickPoint(); XYZ pt2 = uidoc.Selection.PickPoint(); double pt1x = pt1.X; double pt1y = pt1.Y; double pt1z = pt1.Z; double pt2x = pt2.X; double pt2y = pt2.Y; double pt2z = pt2.Z; bool b; int caseSwitch = 0; if (b = (pt1z == pt2z)) { caseSwitch = 1; } if (b = (pt1y == pt2y)) { caseSwitch = 2; } if (b = (pt1x == pt2x)) { caseSwitch = 3; } switch (caseSwitch) { case 1: differenceX = pt2x - pt1x; differenceY = pt1y - pt2y; area = differenceX * differenceY; break; case 2: differenceX = pt2x - pt1x; differenceZ = pt1z - pt2z; area = differenceX * differenceZ; break; default: differenceY = pt2y - pt1y; differenceZ = pt1z - pt2z; area = differenceY * differenceZ; break; } #endif // COMPLICATED_UNRELIABLE_DOES_NOT_WORK #endregion // COMPLICATED_UNRELIABLE_DOES_NOT_WORK XYZ p1, p2; try { p1 = uidoc.Selection.PickPoint( "Please pick first point for area"); p2 = uidoc.Selection.PickPoint( "Please pick second point for area"); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return; } Plane plane = view.SketchPlane.GetPlane(); UV q1 = plane.ProjectInto(p1); UV q2 = plane.ProjectInto(p2); UV d = q2 - q1; double area = d.U * d.V; area = Math.Round(area, 2); if (area < 0) { area = area * (-1); } TaskDialog.Show("Area", area.ToString()); }
VecLength( UV v ) { double len = v.U * v.U + v.V * v.V; len = Math.Sqrt( len ); return ( len ); }
/// <summary> /// Convert a 2D Revit UV to a 3D millimetre /// integer point by scaling from feet to mm. /// </summary> public IntPoint3d(UV p) { X = Util.FootToMmInt(p.U); Y = Util.FootToMmInt(p.V); Z = 0; }
public CurveTriPoint(double u, UV uV, Point point) { U = u; UV = uV; Point = point; }
PlaceViews(ViewSet views, ViewSheet sheet) { double xDistance = 0; double yDistance = 0; CalculateDistance(sheet.Outline, views.Size, ref xDistance, ref yDistance); UV origin = GetOffset(sheet.Outline, xDistance, yDistance); UV temp = new UV(origin.U, origin.V); int n = 1; foreach (Autodesk.Revit.DB.View v in views) { UV location = new UV(temp.U, temp.V); Autodesk.Revit.DB.View view = v; Rescale(view, xDistance, yDistance); Viewport.Create(view.Document, sheet.Id, view.Id, new XYZ(location.U, location.V, 0)); if (0 != n++ % m_rows) { temp = new UV( temp.U + xDistance * (1 - TITLEBAR), temp.V ); } else { temp = new UV( origin.U,temp.V + yDistance); } } }
VecDot(UV va, UV vb) { return((va.U * vb.U) + (va.V * vb.V)); }
FrameWall( Autodesk.Revit.ApplicationServices.Application rvtApp, Autodesk.Revit.DB.Wall wall, double spacing, FamilySymbol columnType ) { Document rvtDoc = wall.Document; LocationCurve loc = (LocationCurve) wall.Location; XYZ startPt = loc.Curve.GetEndPoint( 0 ); XYZ endPt = loc.Curve.GetEndPoint( 1 ); UV wallVec = new UV( endPt.X - startPt.X, endPt.Y - startPt.Y ); UV axis = new UV( 1.0, 0.0 ); ElementId baseLevelId = wall.get_Parameter( BuiltInParameter.WALL_BASE_CONSTRAINT ).AsElementId(); ElementId topLevelId = wall.get_Parameter( BuiltInParameter.WALL_HEIGHT_TYPE ).AsElementId(); double wallLength = VecLength( wallVec ); wallVec = VecNormalise( wallVec ); int nmax = (int) ( wallLength / spacing ); MessageBox.Show( "Wall Length = " + wallLength + "\nSpacing = " + spacing + "\nMax Number = " + nmax, "Structural Sample", MessageBoxButtons.OK, MessageBoxIcon.Information ); double angle = VecAngle( wallVec, axis ); XYZ loc2 = startPt; double dx = wallVec.U * spacing; double dy = wallVec.V * spacing; for( int i = 0; i < nmax; i++ ) { PlaceColumn( rvtApp, rvtDoc, loc2, angle, columnType, baseLevelId, topLevelId ); loc2 = new XYZ( startPt.X + dx, startPt.Y + dy, startPt.Z ); } PlaceColumn( rvtApp, rvtDoc, endPt, angle, columnType, baseLevelId, topLevelId ); }
// Initialize and populate buffers that hold graphics primitives, set up related parameters that are needed for drawing. private void CreateBufferStorageForElement(GeometryElement geomElem, DisplayStyle displayStyle) { List <Solid> allSolids = new List <Solid>(); foreach (GeometryObject geomObj in geomElem) { if (geomObj is Solid) { Solid solid = (Solid)geomObj; if (solid.Volume > 1e-06) { allSolids.Add(solid); } } } m_nonTransparentFaceBufferStorage = new RenderingPassBufferStorage(displayStyle); m_transparentFaceBufferStorage = new RenderingPassBufferStorage(displayStyle); m_edgeBufferStorage = new RenderingPassBufferStorage(displayStyle); // Collect primitives (and associated rendering parameters, such as colors) from faces and edges. foreach (Solid solid in allSolids) { foreach (Face face in solid.Faces) { if (face.Area > 1e-06) { Mesh mesh = face.Triangulate(); ElementId materialId = face.MaterialElementId; bool isTransparent = false; ColorWithTransparency cwt = new ColorWithTransparency(127, 127, 127, 0); if (materialId != ElementId.InvalidElementId) { Material material = m_element.Document.GetElement(materialId) as Material; Color color = material.Color; int transparency0To100 = material.Transparency; uint transparency0To255 = (uint)((float)transparency0To100 / 100f * 255f); cwt = new ColorWithTransparency(color.Red, color.Green, color.Blue, transparency0To255); if (transparency0To255 > 0) { isTransparent = true; } } BoundingBoxUV env = face.GetBoundingBox(); UV center = 0.5 * (env.Min + env.Max); XYZ normal = face.ComputeNormal(center); MeshInfo meshInfo = new MeshInfo(mesh, normal, cwt); if (isTransparent) { m_transparentFaceBufferStorage.Meshes.Add(meshInfo); m_transparentFaceBufferStorage.VertexBufferCount += mesh.Vertices.Count; m_transparentFaceBufferStorage.PrimitiveCount += mesh.NumTriangles; } else { m_nonTransparentFaceBufferStorage.Meshes.Add(meshInfo); m_nonTransparentFaceBufferStorage.VertexBufferCount += mesh.Vertices.Count; m_nonTransparentFaceBufferStorage.PrimitiveCount += mesh.NumTriangles; } } } foreach (Edge edge in solid.Edges) { // if (edge.Length > 1e-06) { IList <XYZ> xyzs = edge.Tessellate(); m_edgeBufferStorage.VertexBufferCount += xyzs.Count; m_edgeBufferStorage.PrimitiveCount += xyzs.Count - 1; m_edgeBufferStorage.EdgeXYZs.Add(xyzs); } } } // Fill out buffers with primitives based on the intermediate information about faces and edges. ProcessFaces(m_nonTransparentFaceBufferStorage); ProcessFaces(m_transparentFaceBufferStorage); ProcessEdges(m_edgeBufferStorage); }
VecNormalise( UV v ) { double len = VecLength( v ); UV newV = new UV( v.U / len, v.V / len ); return ( newV ); }
public void Push(MeshRenderer renderer) { var meshFilter = renderer.GetComponent <MeshFilter>(); if (meshFilter == null) { Debug.LogWarningFormat("{0} has no mesh filter", renderer.name); return; } var mesh = meshFilter.sharedMesh; if (mesh == null) { Debug.LogWarningFormat("{0} has no mesh", renderer.name); return; } var indexOffset = Positions.Count; var boneIndexOffset = Bones.Count; Positions.AddRange(mesh.vertices .Select(x => renderer.transform.TransformPoint(x)) ); Normals.AddRange(mesh.normals .Select(x => renderer.transform.TransformVector(x)) ); UV.AddRange(mesh.uv); Tangents.AddRange(mesh.tangents .Select(t => { var v = renderer.transform.TransformVector(t.x, t.y, t.z); return(new Vector4(v.x, v.y, v.z, t.w)); }) ); var self = renderer.transform; var bone = self.parent; if (bone == null) { Debug.LogWarningFormat("{0} is root gameobject.", self.name); return; } var bindpose = bone.worldToLocalMatrix; BoneWeights.AddRange(Enumerable.Range(0, mesh.vertices.Length) .Select(x => new BoneWeight() { boneIndex0 = Bones.Count, weight0 = 1, }) ); BindPoses.Add(bindpose); Bones.Add(bone); for (int i = 0; i < mesh.subMeshCount; ++i) { var indices = mesh.GetIndices(i).Select(x => x + indexOffset); var mat = renderer.sharedMaterials[i]; var sameMaterialSubMeshIndex = SubMeshes.FindIndex(x => ReferenceEquals(x.Material, mat)); if (sameMaterialSubMeshIndex >= 0) { SubMeshes[sameMaterialSubMeshIndex].Indices.AddRange(indices); } else { SubMeshes.Add(new SubMesh { Indices = indices.ToList(), Material = mat, }); } } }
VecAngle( UV va, UV vb ) { UV vecA = VecNormalise( va ); UV vecB = VecNormalise( vb ); return ( ACos( VecDot( vecA, vecB ) ) ); }
public void Push(SkinnedMeshRenderer renderer) { var mesh = renderer.sharedMesh; if (mesh == null) { Debug.LogWarningFormat("{0} has no mesh", renderer.name); return; } // Renderers.Add(renderer); var indexOffset = Positions.Count; var boneIndexOffset = Bones.Count; Positions.AddRange(mesh.vertices); Normals.AddRange(mesh.normals); UV.AddRange(mesh.uv); Tangents.AddRange(mesh.tangents); if (mesh.vertexCount == mesh.boneWeights.Length) { BoneWeights.AddRange(mesh.boneWeights.Select(x => AddBoneIndexOffset(x, boneIndexOffset)).ToArray()); } else { BoneWeights.AddRange(Enumerable.Range(0, mesh.vertexCount).Select(x => new BoneWeight()).ToArray()); } BindPoses.AddRange(mesh.bindposes); Bones.AddRange(renderer.bones); for (int i = 0; i < mesh.subMeshCount; ++i) { var indices = mesh.GetIndices(i).Select(x => x + indexOffset); var mat = renderer.sharedMaterials[i]; var sameMaterialSubMeshIndex = SubMeshes.FindIndex(x => ReferenceEquals(x.Material, mat)); if (sameMaterialSubMeshIndex >= 0) { SubMeshes[sameMaterialSubMeshIndex].Indices.AddRange(indices); } else { SubMeshes.Add(new SubMesh { Indices = indices.ToList(), Material = mat, }); } } for (int i = 0; i < mesh.blendShapeCount; ++i) { var positions = (Vector3[])mesh.vertices.Clone(); var normals = (Vector3[])mesh.normals.Clone(); var tangents = mesh.tangents.Select(x => (Vector3)x).ToArray(); mesh.GetBlendShapeFrameVertices(i, 0, positions, normals, tangents); BlendShapes.Add(new BlendShape { VertexOffset = indexOffset, FrameWeight = mesh.GetBlendShapeFrameWeight(i, 0), Name = mesh.GetBlendShapeName(i), Positions = positions, Normals = normals, Tangents = tangents, }); } }
public static Color Blerp(IList<IndexedColor2D> colors, UV parameter) { var num = new double[4]; var totalArea = 0.0; foreach (var ci in colors) { var t = ci.Parameter; var d = Math.Sqrt(Math.Pow(t.U - parameter.U, 2) + Math.Pow(t.V - parameter.V, 2)); if (d == 0.0) { return ci.Color; } var w = 1 / d; num[0] += ci.Color.Alpha * w; num[1] += ci.Color.Red * w; num[2] += ci.Color.Green * w; num[3] += ci.Color.Blue * w; totalArea += w; } return ByARGB((int)(num[0] / totalArea), (int)(num[1] / totalArea), (int)(num[2] / totalArea), (int)(num[3] / totalArea)); }
public void Execute(UpdaterData data) { Document doc = data.GetDocument(); Autodesk.Revit.ApplicationServices.Application app = doc.Application; View view = doc.GetElement(viewID) as View; FamilyInstance sphere = doc.GetElement(sphereID) as FamilyInstance; LocationPoint sphereLP = sphere.Location as LocationPoint; XYZ sphereXYZ = sphereLP.Point; SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view); if (sfm == null) { sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point } sfm.Clear(); FilteredElementCollector collector = new FilteredElementCollector(doc, view.Id); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter); ICollection <Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); foreach (Face face in GetFaces(elements)) { int idx = sfm.AddSpatialFieldPrimitive(face.Reference); List <double> doubleList = new List <double>(); IList <UV> uvPts = new List <UV>(); IList <ValueAtPoint> valList = new List <ValueAtPoint>(); BoundingBoxUV bb = face.GetBoundingBox(); for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15) { for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15) { UV uvPnt = new UV(u, v); uvPts.Add(uvPnt); XYZ faceXYZ = face.Evaluate(uvPnt); // Specify three values for each point doubleList.Add(faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts); FieldValues vals = new FieldValues(valList); AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description"); IList <int> registeredResults = new List <int>(); registeredResults = sfm.GetRegisteredResults(); int idx1 = 0; if (registeredResults.Count == 0) { idx1 = sfm.RegisterResult(resultSchema1); } else { idx1 = registeredResults.First(); } sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1); } }
CollectEvent(object sender, CollectorEventArgs e) { // cast the sender object to the SnoopCollector we are expecting Collector snoopCollector = sender as Collector; if (snoopCollector == null) { Debug.Assert(false); // why did someone else send us the message? return; } // see if it is a type we are responsible for Location loc = e.ObjToSnoop as Location; if (loc != null) { Stream(snoopCollector.Data(), loc); return; } GeometryObject geomObj = e.ObjToSnoop as GeometryObject; if (geomObj != null) { Stream(snoopCollector.Data(), geomObj); return; } Options opts = e.ObjToSnoop as Options; if (opts != null) { Stream(snoopCollector.Data(), opts); return; } Transform trf = e.ObjToSnoop as Transform; if (trf != null) { Stream(snoopCollector.Data(), trf); return; } BoundingBoxXYZ bndBoxXyz = e.ObjToSnoop as BoundingBoxXYZ; if (bndBoxXyz != null) { Stream(snoopCollector.Data(), bndBoxXyz); return; } MeshTriangle meshTri = e.ObjToSnoop as MeshTriangle; if (meshTri != null) { Stream(snoopCollector.Data(), meshTri); return; } Reference reference = e.ObjToSnoop as Reference; if (reference != null) { Stream(snoopCollector.Data(), reference); return; } EdgeArray edgeArray = e.ObjToSnoop as EdgeArray; // NOTE: this is needed because EdgeArrayArray will display enumerable Snoop items if (edgeArray != null) { Stream(snoopCollector.Data(), edgeArray); return; } CurveArray curveArray = e.ObjToSnoop as CurveArray; // NOTE: this is needed because CurveArrayArray will display enumerable Snoop items if (curveArray != null) { Stream(snoopCollector.Data(), curveArray); return; } Plane plane = e.ObjToSnoop as Plane; if (plane != null) { Stream(snoopCollector.Data(), plane); return; } IntersectionResult intrResult = e.ObjToSnoop as IntersectionResult; if (intrResult != null) { Stream(snoopCollector.Data(), intrResult); return; } BoundingBoxUV bboxUV = e.ObjToSnoop as BoundingBoxUV; if (bboxUV != null) { Stream(snoopCollector.Data(), bboxUV); return; } SweepProfile sweepProf = e.ObjToSnoop as SweepProfile; if (sweepProf != null) { Stream(snoopCollector.Data(), sweepProf); return; } DimensionSegment dimSeg = e.ObjToSnoop as DimensionSegment; if (dimSeg != null) { Stream(snoopCollector.Data(), dimSeg); return; } UV uv = e.ObjToSnoop as UV; if (uv != null) { Stream(snoopCollector.Data(), uv); return; } }
private void Stream(ArrayList data, UV UV) { data.Add(new Snoop.Data.ClassSeparator(typeof(UV))); data.Add(new Snoop.Data.Uv("Basis U", UV.BasisU)); data.Add(new Snoop.Data.Uv("Basis V", UV.BasisV)); //data.Add(new Snoop.Data.Bool("Is normalized", UV.IsNormalized)); //data.Add(new Snoop.Data.Bool("Is zero", UV.IsZero)); //data.Add(new Snoop.Data.Double("Length", UV.)); data.Add(new Snoop.Data.Uv("Normalized", UV.Normalize())); data.Add(new Snoop.Data.Double("U", UV.U)); data.Add(new Snoop.Data.Double("V", UV.V)); data.Add(new Snoop.Data.Uv("Zero", UV.Zero)); }
/// <summary> /// Converts a position in Revit internal units to IFC units. /// </summary> /// <param name="unscaledUV">The position in Revit internal units.</param> /// <returns>The position in IFC units.</returns> static public UV ScaleLength(UV unscaledUV) { return(ExporterCacheManager.UnitsCache.Scale(SpecTypeId.Length, unscaledUV)); }
public override Value Evaluate(FSharpList<Value> args) { this.ClearPreviousResults(); //unwrap the values IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(q => (double)((Value.Number)q).Item); var curve = (Curve)((Value.Container)args[1]).Item; SpatialFieldManager = (Autodesk.Revit.DB.Analysis.SpatialFieldManager)((Value.Container)args[2]).Item; if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1)) { IList<int> arses = SpatialFieldManager.GetRegisteredResults(); foreach (int i in arses) { AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i); if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA) { schemaId = i; break; } } } else { var ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo."); schemaId = SpatialFieldManager.RegisterResult(ars); } Transform trf = Transform.Identity; //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3 var create = dynRevitSettings.Doc.Application.Application.Create; Transform t = curve.ComputeDerivatives(0, true); XYZ x = t.BasisX.Normalize(); XYZ y = t.BasisX.IsAlmostEqualTo(XYZ.BasisZ) ? t.BasisX.CrossProduct(XYZ.BasisY).Normalize() : t.BasisX.CrossProduct(XYZ.BasisZ).Normalize(); XYZ z = x.CrossProduct(y); Autodesk.Revit.DB.Ellipse arc1 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y,z,-Math.PI, 0); Autodesk.Revit.DB.Ellipse arc2 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, 0, Math.PI); var pathLoop = new Autodesk.Revit.DB.CurveLoop(); pathLoop.Append(curve); var profileLoop = new Autodesk.Revit.DB.CurveLoop(); profileLoop.Append(arc1); profileLoop.Append(arc2); double curveDomain = curve.get_EndParameter(1) - curve.get_EndParameter(0); int idx = -1; var s = GeometryCreationUtilities.CreateSweptGeometry(pathLoop, 0, 0, new List<Autodesk.Revit.DB.CurveLoop>{profileLoop}); foreach (Face face in s.Faces) { //divide the V domain by the number of incoming BoundingBoxUV domain = face.GetBoundingBox(); double vSpan = domain.Max.V - domain.Min.V; //analysis values idx = SpatialFieldManager.AddSpatialFieldPrimitive(face, trf); //a list to hold the analysis points IList<UV> uvPts = new List<UV>(); //a list to hold the analysis values IList<ValueAtPoint> valList = new List<ValueAtPoint>(); //int count = nvals.Count(); //this is creating a lot of sample points, but if we used less //sampling points, AVF would draw the two surfaces as if there was a hard //edge between them. this provides a better blend. int count = 10; for (int i = 0; i < count; i ++) { //get a UV point on the face //find its XYZ location and project to //the underlying curve. find the value which corresponds //to the location on the curve var uv = new UV(domain.Min.U, domain.Min.V + vSpan / count*(double) i); var uv1 = new UV(domain.Max.U, domain.Min.V + vSpan / count * (double)i); uvPts.Add(uv); uvPts.Add(uv1); XYZ facePt = face.Evaluate(uv); IntersectionResult ir = curve.Project(facePt); double curveParam = curve.ComputeNormalizedParameter(ir.Parameter); if (curveParam < 0) curveParam = 0; if (curveParam > 1) curveParam = 1; var valueIndex = (int)Math.Floor(curveParam * (double)nvals.Count()); if (valueIndex >= nvals.Count()) valueIndex = nvals.Count() - 1; //create list of values at this point - currently supporting only one //var doubleList = new List<double> { nvals.ElementAt(i) }; var doubleList = new List<double> { nvals.ElementAt(valueIndex) }; //add value at point object containing the value list valList.Add(new ValueAtPoint(doubleList)); valList.Add(new ValueAtPoint(doubleList)); } var pnts = new FieldDomainPointsByUV(uvPts); var vals = new FieldValues(valList); SpatialFieldManager.UpdateSpatialFieldPrimitive( idx, pnts, vals, schemaId); PastResultIds.Add(idx); } return Value.NewNumber(idx); }
public Superformula(UV uv) : base() { this.U = uv.U; this.V = uv.V; }
/// <summary> /// Generates the UV value of a point projected to a plane, given an extrusion direction. /// </summary> /// <param name="plane">The plane.</param> /// <param name="projDir">The projection direction.</param> /// <param name="point">The point.</param> /// <returns>The UV value.</returns> public static UV ProjectPointToPlane(Plane plane, XYZ projDir, XYZ point) { XYZ zDir = plane.Normal; double denom = projDir.DotProduct(zDir); if (MathUtil.IsAlmostZero(denom)) return null; XYZ xDir = plane.XVec; XYZ yDir = plane.YVec; XYZ orig = plane.Origin; double distToPlane = ((orig - point).DotProduct(zDir)) / denom; XYZ pointProj = distToPlane * projDir + point; XYZ pointProjOffset = pointProj - orig; UV pointProjUV = new UV(pointProjOffset.DotProduct(xDir), pointProjOffset.DotProduct(yDir)); return pointProjUV; }
public static Color BuildColorFrom2DRange(IList <Color> colors, IList <UV> parameters, UV parameter) { var colorRange = ColorRange.ByColorsAndParameters(colors, parameters); return(colorRange.GetColorAtParameter(parameter)); }
/// <summary> /// Create a room on a given level. /// </summary> void CreateRoom( Document doc, Level level) { Application app = doc.Application; Autodesk.Revit.Creation.Application appCreation = app.Create; Autodesk.Revit.Creation.Document docCreation = doc.Create; XYZ pt1 = new XYZ( 0, -5, 0 ); XYZ pt2 = new XYZ( 0, 5, 0 ); XYZ pt3 = new XYZ( 8, 5, 0 ); XYZ pt4 = new XYZ( 8, -5, 0 ); Line line1 = Line.CreateBound( pt1, pt2 ); Line line2 = Line.CreateBound( pt2, pt3 ); Line line3 = Line.CreateBound( pt3, pt4 ); Line line4 = Line.CreateBound( pt4, pt1 ); CurveArray curveArr = new CurveArray(); curveArr.Append( line1 ); curveArr.Append( line2 ); curveArr.Append( line3 ); curveArr.Append( line4 ); docCreation.NewRoomBoundaryLines( doc.ActiveView.SketchPlane, curveArr, doc.ActiveView ); // Create a new room UV tagPoint = new UV( 4, 0 ); Room room = docCreation.NewRoom( level, tagPoint ); if( null == room ) { throw new Exception( "Create a new room failed." ); } room.Number = "42"; room.Name = "Lobby"; // Creation.Document.NewRoomTag( Room, UV, View) is obsolete. // Use the NewRoomTag(LinkElementId, UV, ElementId) overload instead. //RoomTag tag = docCreation.NewRoomTag( room, tagPoint, doc.ActiveView ); // 2013 RoomTag tag = docCreation.NewRoomTag( new LinkElementId( room.Id ), tagPoint, doc.ActiveView.Id ); // 2014 }
/// <summary> /// Creates or populates Revit elements based on the information contained in this class. /// </summary> /// <param name="doc">The document.</param> protected override void Create(Document doc) { // Only set the project location for the site that contains the building. // NOTE: The file isn't required to have an IfcBuilding, even though it generally does. // Furthermore, it generally only has one ifcSite. As such, we may want to rethink // which the "main" IfcSite is. bool hasBuilding = false; foreach (IFCObjectDefinition objectDefinition in ComposedObjectDefinitions) { if (objectDefinition is IFCBuilding) { hasBuilding = true; break; } } if (hasBuilding) { ProjectLocation projectLocation = doc.ActiveProjectLocation; if (projectLocation != null) { SiteLocation siteLocation = projectLocation.GetSiteLocation(); if (siteLocation != null) { // Some Tekla files may have invalid information here that would otherwise cause the // link to fail. Recover with a warning. try { if (RefLatitude.HasValue) { siteLocation.Latitude = RefLatitude.Value * Math.PI / 180.0; } if (RefLongitude.HasValue) { siteLocation.Longitude = RefLongitude.Value * Math.PI / 180.0; } } catch (Exception ex) { Importer.TheLog.LogWarning(Id, "Invalid latitude or longitude value supplied for IFCSITE: " + ex.Message, false); } } if (ObjectLocation != null) { XYZ projectLoc = (ObjectLocation.RelativeTransform != null) ? ObjectLocation.RelativeTransform.Origin : XYZ.Zero; if (!MathUtil.IsAlmostZero(projectLoc.Z)) { Importer.TheLog.LogError(Id, "The Z-value of the IfcSite object placement relative transform should be 0. This will be ignored in favor of the RefElevation value.", false); } // Get true north from IFCProject. double trueNorth = 0.0; UV trueNorthUV = IFCImportFile.TheFile.IFCProject.TrueNorthDirection; if (trueNorthUV != null) { double geometricAngle = Math.Atan2(trueNorthUV.V, trueNorthUV.U); // Convert from geometric angle to compass direction. // This involves two steps: (1) subtract PI/2 from the angle, staying in (-PI, PI], then (2) reversing the result. trueNorth = (geometricAngle > -Math.PI / 2.0) ? geometricAngle - Math.PI / 2.0 : geometricAngle + Math.PI * 1.5; trueNorth = -trueNorth; } XYZ offset = new XYZ(projectLoc.X, projectLoc.Y, RefElevation); if (!XYZ.IsWithinLengthLimits(offset)) { ProjectPosition projectPosition = new ProjectPosition(projectLoc.X, projectLoc.Y, RefElevation, trueNorth); projectLocation.SetProjectPosition(XYZ.Zero, projectPosition); // Now that we've set the project position, remove the site relative transform, if the file is created correctly (that is, all entities contained in the site // have the local placements relative to the site. IFCLocation.RemoveRelativeTransformForSite(this); } } } } base.Create(doc); if (hasBuilding) { // There should only be one IfcSite in the file, but in case there are multiple, we want to make sure that the one // containing the IfcBuilding has its parameters stored somewhere. // In the case where we didn't create an element above, use the ProjectInfo element in the document to store its parameters. if (CreatedElementId == ElementId.InvalidElementId) { CreatedElementId = Importer.TheCache.ProjectInformationId; } } }
/// <summary> /// Creates IfcCartesianPoint object from a 2D point. /// </summary> /// <param name="file">The file.</param> /// <param name="point">The point</param> /// <returns>The IfcCartesianPoint handle.</returns> public static IFCAnyHandle CreateCartesianPoint(IFCFile file, UV point) { if (point == null) throw new ArgumentNullException("point"); List<double> points = new List<double>(); points.Add(point.U); points.Add(point.V); return CreateCartesianPoint(file, points); }
public MultithreadedCalculationContainer(string _docName, UV _min, UV _max) { m_docName = _docName; m_min = _min; m_max = _max; }
public ResultsData(UV uv, double value) { this.UV = uv; Value = value; }
public static double DistanceBetweenPoints(this Surface surface, UV point1, UV point2) { Point A = surface.PointAtParameter(point1.U, point1.V); Point B = surface.PointAtParameter(point2.U, point2.V); return A.DistanceTo(B); }