/// <summary> /// Get a parameter from a view by name /// </summary> /// <param name="plan"></param> /// <param name="paramName"></param> /// <returns></returns> public static Parameter GetParameterByName(ViewPlan plan, string paramName) { foreach (Parameter parameter in plan.Parameters) { if (parameter.Definition.Name == paramName) { return parameter; } } return null; }
/// <summary> /// Generates paths of travel from points in one room to a single target location using the slower (one-at-a-time) method. /// </summary> /// <param name="doc"></param> /// <param name="viewPlan"></param> /// <param name="room"></param> /// <param name="endPoint"></param> /// <param name="resultsSummary"></param> private static void GeneratePathsOfTravelForOneRoomOneDoor(Document doc, ViewPlan viewPlan, Room room, XYZ endPoint, ResultsSummary resultsSummary) { GeneratePathsOfTravelForOneRoomManyDoors(doc, viewPlan, room, new List <XYZ> { endPoint }, resultsSummary); }
/// <summary> /// Shared implementation for use of Path of Travel bulk creation routine from all near-corner room points to all doors. /// </summary> /// <param name="doc"></param> /// <param name="viewPlan"></param> /// <param name="mapAllStartsToAllEnds"></param> private static void CreatePathsOfTravelInAllRoomsAllDoorsMultiplePointsManyToMany(Document doc, ViewPlan viewPlan, bool mapAllStartsToAllEnds) { ElementId levelId = viewPlan.GenLevel.Id; // find rooms on level FilteredElementCollector fec = new FilteredElementCollector(doc, viewPlan.Id); fec.WherePasses(new Autodesk.Revit.DB.Architecture.RoomFilter()); // find doors on level FilteredElementCollector fec2 = new FilteredElementCollector(doc, viewPlan.Id); fec2.OfCategory(BuiltInCategory.OST_Doors); // setup results ResultsSummary resultsSummary = new ResultsSummary(); List <XYZ> endPoints = new List <XYZ>(); // Collect rooms List <Room> rooms = fec.Cast <Room>().ToList <Room>(); // Loop on doors and collect target points (the door's origin) foreach (Element element in fec2) { Instance doorElement = (Instance)element; Transform trf = doorElement.GetTransform(); endPoints.Add(trf.Origin); } resultsSummary.numDoors = endPoints.Count; using (TransactionGroup group = new TransactionGroup(doc, "Generate all paths of travel")) { group.Start(); GeneratePathsOfTravelForRoomsToEndpointsManyToMany(doc, viewPlan, rooms, endPoints, resultsSummary, mapAllStartsToAllEnds); group.Assimilate(); } ShowResults(resultsSummary); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; var acview = doc.ActiveView; var viewfamilytypes = doc.TCollector <ViewFamilyType>(); var viewplanfamilytype = viewfamilytypes.Where(m => m.ViewFamily == ViewFamily.FloorPlan).First(); var view3Dfamilytype = viewfamilytypes.Where(m => m.ViewFamily == ViewFamily.ThreeDimensional).First(); var levels = doc.TCollector <Level>(); FloorSelector fsui = FloorSelector.Instance; fsui.FloorBox.ItemsSource = levels; fsui.FloorBox.DisplayMemberPath = "Name"; fsui.FloorBox.SelectedIndex = 0; fsui.ShowDialog(); var targetfloor = fsui.FloorBox.SelectionBoxItem as Level; var upperfloor = levels.Where(m => m.Elevation > targetfloor.Elevation)?.OrderBy(m => m.Elevation)?.FirstOrDefault(); var categories = doc.Settings.Categories; var modelcategories = categories.Cast <Category>().Where(m => m.CategoryType == CategoryType.Model).ToList(); var filterslist = new List <ElementFilter>(); foreach (var modelcategory in modelcategories) { var categoryfilter = new ElementCategoryFilter(modelcategory.Id); filterslist.Add(categoryfilter); } var logicOrFilter = new LogicalOrFilter(filterslist); var collector = new FilteredElementCollector(doc); var modelelements = collector.WherePasses(logicOrFilter).WhereElementIsNotElementType().Where(m => m.Category.CategoryType == CategoryType.Model); var modelelementsids = modelelements.Select(m => m.Id).ToList(); var temboundingbox = default(BoundingBoxXYZ); Transaction temtran = new Transaction(doc, "temtransaction"); temtran.Start(); var temgroup = doc.Create.NewGroup(modelelementsids); var temview = ViewPlan.Create(doc, viewplanfamilytype.Id, targetfloor.Id); temboundingbox = temgroup.get_BoundingBox(temview); temtran.RollBack(); var zMin = targetfloor.Elevation; var zMax = upperfloor?.Elevation ?? temboundingbox.Max.Z; var oldmin = temboundingbox.Min; var oldmax = temboundingbox.Max; BoundingBoxXYZ newbox = new BoundingBoxXYZ(); newbox.Min = new XYZ(oldmin.X, oldmin.Y, zMin); newbox.Max = new XYZ(oldmax.X, oldmax.Y, zMax); var new3dview = default(View3D); doc.Invoke(m => { new3dview = View3D.CreateIsometric(doc, view3Dfamilytype.Id); new3dview.SetSectionBox(newbox); }, "楼层三维"); uidoc.ActiveView = new3dview; return(Result.Succeeded); }
private void CreateFrontViewSheets(int id) { if (uidoc.Document != null) { if (requestData != null) { List <Element> allNonViewElements = getAllNonViewElementsOfDoc(); for (int f = 0; f < requestData.frontSheetsInfo.Count; f++) { Tuple <string, string, string> curFrontSheetInfo = requestData.frontSheetsInfo[f]; ElementId titleBlocktId = GetTitleBlockIdByName(requestData.titleBlockName); if (titleBlocktId == null) { titleBlocktId = new ElementId(-1); } ViewSheet norViewSheet = ViewSheet.Create(uidoc.Document, titleBlocktId); norViewSheet.SheetNumber = curFrontSheetInfo.Item1; norViewSheet.Name = curFrontSheetInfo.Item2; View norSheetViewPlan = null; ViewFamilyType viewFamilyType = null; FilteredElementCollector collectorViewFamilyType = new FilteredElementCollector(uidoc.Document); var viewFamilyTypes = collectorViewFamilyType.OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in viewFamilyTypes) { ViewFamilyType v = e as ViewFamilyType; if (v.ViewFamily == ViewFamily.FloorPlan) { viewFamilyType = v; break; } } Level exLevel = null; FilteredElementCollector collectorLevel = new FilteredElementCollector(uidoc.Document); var levels = collectorLevel.OfClass(typeof(Level)).ToElements(); foreach (Element e in levels) { exLevel = e as Level; } if ((viewFamilyType != null) && (exLevel != null)) { norSheetViewPlan = ViewPlan.Create(uidoc.Document, viewFamilyType.Id, exLevel.Id); norSheetViewPlan.Name = norViewSheet.Name; } if (norSheetViewPlan != null) { View viewTemplate = GetViewByName(curFrontSheetInfo.Item3); if (viewTemplate != null) { List <ElementId> hiddenElemsIds = new List <ElementId>(); foreach (Element curHidVisElem in allNonViewElements) { if (curHidVisElem.IsHidden(viewTemplate)) { hiddenElemsIds.Add(curHidVisElem.Id); } } try { norSheetViewPlan.HideElements(hiddenElemsIds); } catch (Exception ex) { } } try { SetViewForSheet(norSheetViewPlan, norViewSheet, 1); } catch (Exception ex) { } } else { } } uidoc.RefreshActiveView(); } } else { TaskDialog.Show("Info", "doc is null"); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; IList <double> wallthicknessList = new List <double>(); XYZ normal = new XYZ(0, 0, 1); string previous = null; double previousWidth = 0; SpatialElementBoundaryOptions seb_opt = new SpatialElementBoundaryOptions(); FilteredElementCollector levels = new FilteredElementCollector(doc).OfClass(typeof(Level)); using (Transaction tx = new Transaction(doc)) { tx.Start("Create cropped views for each room"); string date_iso = DateTime.Now.ToString("yyyy-MM-dd"); foreach (Level level in levels) { Debug.Print(level.Name); ElementId id_view = level.FindAssociatedPlanViewId(); ViewPlan view = doc.GetElement(id_view) as ViewPlan; IEnumerable <Room> rooms = new FilteredElementCollector(doc, id_view).OfClass(typeof(SpatialElement)).Where <Element>(e => e is Room).Cast <Room>(); foreach (Room room in rooms) { wallthicknessList.Clear(); string view_name = string.Format("{0}_cropped_to_room_{1}_date_{2}", view.Name, room.Name, date_iso); id_view = view.Duplicate(ViewDuplicateOption.AsDependent); View view_cropped = doc.GetElement(id_view) as View; view_cropped.Name = view_name; IList <IList <BoundarySegment> > sloops = room.GetBoundarySegments(seb_opt); if (null == sloops) // the room may not be bound { continue; } CurveLoop loop = null; foreach (IList <BoundarySegment> sloop in sloops) { loop = new CurveLoop(); foreach (BoundarySegment s in sloop) { loop.Append(s.GetCurve()); ElementType type = doc.GetElement(s.ElementId) as ElementType; Element elem = doc.GetElement(s.ElementId); //Error when wall width varies across length //if (elem is Wall) //{ // Wall wall = elem as Wall; // wallthicknessList.Add(wall.Width*1.1); //} //else //{ // //Room separator // //Any other exceptions to walls need including?? // wallthicknessList.Add(0); //} if (elem != null)//The elem == null is due to room separators. Are there going to be any others? { if (firstPass) { if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_Walls) { Wall wall = elem as Wall; //Is there a better way of identifying Orientation (predominantly horizontal or Vertical) What if walls at 45 deg? if (Math.Abs(Math.Round(wall.Orientation.Y, 0)) == 1) { previous = "Y"; } else { previous = "X"; } firstPass = false; wallthicknessList.Add(wall.Width + 0.1); previousWidth = wall.Width + 0.1; } //Are there any other situations need taking account off? else if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines) { //Room separator Autodesk.Revit.DB.Options opt = new Options(); Autodesk.Revit.DB.GeometryElement geomElem = elem.get_Geometry(opt); foreach (GeometryObject geomObj in geomElem) { Line line = geomObj as Line; //Is there a better way of identifying Orientation (predominantly horizontal or Vertical) What if walls at 45 deg? if (0 - line.GetEndPoint(1).X - line.GetEndPoint(0).X > 0 - line.GetEndPoint(1).Y - line.GetEndPoint(0).Y) { previous = "Y"; } else { previous = "X"; } firstPass = false; wallthicknessList.Add(0.1); previousWidth = 0.1; } } } else { if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_Walls) { Wall wall = elem as Wall; if (Math.Abs(Math.Round(wall.Orientation.Y, 0)) == 1 && previous == "Y") { if (wall.Width > previousWidth) { //This would appear to avoid the Cannot properly trim error //How to allow for more than two wall thickness changes within the same length? //How to not require this and just offset wall widths? wallthicknessList[wallthicknessList.Count - 1] = wall.Width + 0.1; } wallthicknessList.Add(wall.Width + 0.1); previousWidth = wall.Width + 0.1; previous = "Y"; } else if (Math.Abs(Math.Round(wall.Orientation.X, 0)) == 1 && previous == "X") { if (wall.Width > previousWidth) { //This would appear to avoid the Cannot properly trim error //How to allow for more than two wall thickness changes within the same length? //How to not require this and just offset wall widths? wallthicknessList[wallthicknessList.Count - 1] = wall.Width + 0.1; } wallthicknessList.Add(wall.Width + 0.1); previousWidth = wall.Width + 0.1; previous = "X"; } else { if (Math.Abs(Math.Round(wall.Orientation.Y, 0)) == 1) { previous = "Y"; } else if (Math.Abs(Math.Round(wall.Orientation.X, 0)) == 1) { previous = "X"; } wallthicknessList.Add(wall.Width + 0.1); previousWidth = wall.Width + 0.1; } } else if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines)//Any other situations need taking account of? { //Room separator Autodesk.Revit.DB.Options opt = new Options(); Autodesk.Revit.DB.GeometryElement geomElem = elem.get_Geometry(opt); foreach (GeometryObject geomObj in geomElem) { Line line = geomObj as Line; //Is there a better way of identifying Orientation (predominantly horizontal or Vertical) What if walls at 45 deg? if (0 - line.GetEndPoint(1).X - line.GetEndPoint(0).X > 0 - line.GetEndPoint(1).Y - line.GetEndPoint(0).Y) { previous = "Y"; } else { previous = "X"; } wallthicknessList.Add(previousWidth); //Error "cannot trim" //wallthicknessList.Add(0.1); previousWidth = 0.1; } } } } else { wallthicknessList.Add(-0.1); } } // Skip out after first sloop - ignore // rooms with holes and disjunct parts break; } CurveLoop loop2 = CurveLoop.CreateViaOffset(loop, wallthicknessList, normal); CurveLoop newloop = new CurveLoop(); foreach (Curve curve in loop2) { List <XYZ> points = curve.Tessellate().ToList(); for (int ip = 0; ip < points.Count - 1; ip++) { Line l = Line.CreateBound(points[ip], points[ip + 1]); newloop.Append(l); } } ViewCropRegionShapeManager vcrs_mgr = view_cropped.GetCropRegionShapeManager(); bool valid = vcrs_mgr.IsCropRegionShapeValid(newloop); if (valid) { view_cropped.CropBoxVisible = true; view_cropped.CropBoxActive = true; vcrs_mgr.SetCropShape(newloop); } } } tx.Commit(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; SpatialElementBoundaryOptions seb_opt = new SpatialElementBoundaryOptions(); FilteredElementCollector levels = new FilteredElementCollector(doc) .OfClass(typeof(Level)); using (Transaction tx = new Transaction(doc)) { tx.Start("Create cropped views for each room"); string date_iso = DateTime.Now.ToString("yyyy-MM-dd"); foreach (Level level in levels) { Debug.Print(level.Name); ElementId id_view = level.FindAssociatedPlanViewId(); ViewPlan view = doc.GetElement(id_view) as ViewPlan; IEnumerable <Room> rooms = new FilteredElementCollector(doc, id_view) .OfClass(typeof(SpatialElement)) .Where <Element>(e => e is Room) .Cast <Room>(); foreach (Room room in rooms) { string view_name = string.Format( "{0}_cropped_to_room_{1}_date_{2}", view.Name, room.Name, date_iso); id_view = view.Duplicate( ViewDuplicateOption.AsDependent); View view_cropped = doc.GetElement( id_view) as View; view_cropped.Name = view_name; IList <IList <BoundarySegment> > sloops = room.GetBoundarySegments(seb_opt); if (null == sloops) // the room may not be bounded { continue; } CurveLoop room_outer_loop = GetOuterLoopOfRoomFromCreateViaOffset( view_cropped, sloops); //ViewCropRegionShapeManager vcrs_mgr // = view_cropped.GetCropRegionShapeManager(); //bool valid = vcrs_mgr.IsCropRegionShapeValid( // room_outer_loop ); //if( valid ) //{ // view_cropped.CropBoxVisible = true; // view_cropped.CropBoxActive = true; // vcrs_mgr.SetCropShape( room_outer_loop ); //} } } tx.Commit(); } return(Result.Succeeded); }
/// <summary> /// Makes a View3D from a click on a viewport on a sheet. /// </summary> /// <param name="uidoc">the currently active uidocument</param> /// <param name="doc">the currently active document</param> public static Autodesk.Revit.UI.Result MakeFromViewportClick(UIDocument uidoc) { if (null == uidoc) { throw new ArgumentNullException("uidoc"); } Document doc = uidoc.Document; if (null == doc) { throw new InvalidOperationException("The document can't be found."); } Result result = Result.Succeeded; // Have the user click on a plan view viewport on a sheet. XYZ click = uidoc.Selection.PickPoint("Click on a plan view viewport on a sheet to create a perspective View3D with its camera at that point."); if (null == click) { throw new InvalidOperationException("Please click on a plan view viewport on a sheet."); } // Make sure the active view was a sheet view. ViewSheet viewSheet = uidoc.ActiveGraphicalView as ViewSheet; if (null == viewSheet) { throw new InvalidOperationException("The click was not on a sheet."); } // Find which viewport was clicked. Viewport clickedViewport = GetViewportAtClick(viewSheet, click); if (null == clickedViewport) { throw new InvalidOperationException("The click was not on a viewport."); } // Verify that the transforms are reported by the viewport and its view. View clickedView = doc.GetElement(clickedViewport.ViewId) as View; if (null == clickedView || !clickedView.HasViewTransforms() || !clickedViewport.HasViewportTransforms()) { throw new InvalidOperationException("The clicked viewport doesn't report 3D model space to sheet space transforms."); } // Restrict application to plan view types. // Note: Sections and Elevations report transforms but are not covered in this demo. if (ViewType.AreaPlan != clickedView.ViewType && ViewType.CeilingPlan != clickedView.ViewType && ViewType.EngineeringPlan != clickedView.ViewType && ViewType.FloorPlan != clickedView.ViewType) { throw new InvalidOperationException("Only plan views are supported by this demo application."); } ViewPlan plan = clickedView as ViewPlan; if (null == plan) { throw new InvalidOperationException("Only plan views are supported by this demo application."); } // Convert the viewport click into a ray through 3d model space. // Note: The output XYZ needs to be projected onto the view's cut plane before use. XYZ clickAsModelRay = CalculateClickAsModelRay(clickedViewport, click); if (null == clickAsModelRay) { throw new InvalidOperationException("The click was outside the view crop regions."); } // Project the ray onto the view's cut plane. // This picks a reasonable height in the model for the View3D camera. Plane cutPlane = GetViewPlanCutPlane(plan); if (null == cutPlane) { throw new InvalidOperationException("An error occured when getting the view's cut plane."); } XYZ view3dCameraLocation = ProjectPointOnPlane(cutPlane, clickAsModelRay); if (null == view3dCameraLocation) { throw new InvalidOperationException("An error occured when calculating the View3D camera position."); } using (Transaction tran = new Transaction(doc, "New 3D View")) { tran.Start(); // Create a new perspective 3D View with its camera at the point. View3D view3d = Create3DView(doc, view3dCameraLocation, XYZ.BasisZ, XYZ.BasisY); if (null != view3d) { tran.Commit(); // Activate the new 3D view. uidoc.ActiveView = view3d; } else { tran.RollBack(); throw new InvalidOperationException("Failed to generate the 3D view."); } } return(result); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; IList <double> wallthicknessList = new List <double>(); XYZ normal = new XYZ(0, 0, 1); SpatialElementBoundaryOptions seb_opt = new SpatialElementBoundaryOptions(); FilteredElementCollector levels = new FilteredElementCollector(doc).OfClass(typeof(Level)); using (Transaction tx = new Transaction(doc)) { tx.Start("Create cropped views for each room"); string date_iso = DateTime.Now.ToString("yyyy-MM-dd"); foreach (Level level in levels) { wallthicknessList.Clear(); Debug.Print(level.Name); ElementId id_view = level.FindAssociatedPlanViewId(); ViewPlan view = doc.GetElement(id_view) as ViewPlan; IEnumerable <Room> rooms = new FilteredElementCollector(doc, id_view).OfClass(typeof(SpatialElement)).Where <Element>(e => e is Room).Cast <Room>(); foreach (Room room in rooms) { wallthicknessList.Clear(); string view_name = string.Format("{0}_cropped_to_room_{1}_date_{2}", view.Name, room.Name, date_iso); id_view = view.Duplicate(ViewDuplicateOption.AsDependent); View view_cropped = doc.GetElement(id_view) as View; view_cropped.Name = view_name; IList <IList <BoundarySegment> > sloops = room.GetBoundarySegments(seb_opt); if (null == sloops) // the room may not be bound { continue; } CurveLoop loop = null; foreach (IList <BoundarySegment> sloop in sloops) { loop = new CurveLoop(); foreach (BoundarySegment s in sloop) { loop.Append(s.GetCurve()); ElementType type = doc.GetElement(s.ElementId) as ElementType; Element elem = doc.GetElement(s.ElementId); if (elem is Wall) { Wall wall = elem as Wall; wallthicknessList.Add(wall.Width); } else { //Room separator //Any other exceptions to walls need including?? wallthicknessList.Add(0); } } // Skip out after first sloop - ignore // rooms with holes and disjunct parts break; } CurveLoop loop2 = CurveLoop.CreateViaOffset(loop, wallthicknessList, normal); CurveLoop newloop = new CurveLoop(); foreach (Curve curve in loop2) { List <XYZ> points = curve.Tessellate().ToList(); for (int ip = 0; ip < points.Count - 1; ip++) { Line l = Line.CreateBound(points[ip], points[ip + 1]); newloop.Append(l); } } ViewCropRegionShapeManager vcrs_mgr = view_cropped.GetCropRegionShapeManager(); bool valid = vcrs_mgr.IsCropRegionShapeValid(newloop); if (valid) { view_cropped.CropBoxVisible = true; view_cropped.CropBoxActive = true; vcrs_mgr.SetCropShape(newloop); } } } tx.Commit(); } return(Result.Succeeded); }
////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void CreateViewAndSheet(RoomConversionCandidate candidate) { // Create Sheet var sheet = ViewSheet.Create(doc, TitleBlockId); sheet.Name = candidate.DestinationSheetName; sheet.SheetNumber = candidate.DestinationSheetNumber; // Get Centre before placing any views var sheetCentre = CentreOfSheet(sheet, doc); if (CreatePlan) { // Create plan of room var plan = ViewPlan.Create(doc, GetFloorPlanViewFamilyTypeId(doc), candidate.Room.Level.Id); plan.CropBoxActive = true; plan.ViewTemplateId = ElementId.InvalidElementId; plan.Scale = Scale; var originalBoundingBox = candidate.Room.get_BoundingBox(plan); // Put them on sheets plan.CropBox = CreateOffsetBoundingBox(50000, originalBoundingBox); plan.Name = candidate.DestinationViewName; // Shrink the bounding box now that it is placed var vp = Viewport.Create(doc, sheet.Id, plan.Id, sheetCentre); // Shrink the bounding box now that it is placed plan.CropBox = CreateOffsetBoundingBox(CropRegionEdgeOffset, originalBoundingBox); // FIXME - To set an empty view title - so far this seems to work with the standard revit template... vp.ChangeTypeId(vp.GetValidTypes().Last()); // FIXME Apply a view template // NOTE This could cause trouble with view scales plan.ViewTemplateId = ViewTemplateId; } if (CreateRCP) { // Create rcp of room var rcp = ViewPlan.Create(doc, GetRCPViewFamilyTypeId(doc), candidate.Room.Level.Id); rcp.CropBoxActive = true; rcp.ViewTemplateId = ElementId.InvalidElementId; rcp.Scale = Scale; var originalBoundingBox = candidate.Room.get_BoundingBox(rcp); // Put them on sheets rcp.CropBox = CreateOffsetBoundingBox(50000, originalBoundingBox); rcp.Name = candidate.DestinationViewName; // Shrink the bounding box now that it is placed var vp = Viewport.Create(doc, sheet.Id, rcp.Id, sheetCentre); // Shrink the bounding box now that it is placed rcp.CropBox = CreateOffsetBoundingBox(CropRegionEdgeOffset, originalBoundingBox); // FIXME - To set an empty view title - so far this seems to work with the standard revit template... vp.ChangeTypeId(vp.GetValidTypes().Last()); // FIXME Apply a view template // NOTE This could cause trouble with view scales rcp.ViewTemplateId = ViewTemplateId; } if (CreateAreaPlan) { // Create plan of room var plan = ViewPlan.CreateAreaPlan(doc, AreaPlanTypeId, candidate.Room.Level.Id); //// var plan = ViewPlan.Create(doc, GetAreaPlanViewFamilyTypeId(doc), candidate.Room.Level.Id); plan.CropBoxActive = true; plan.ViewTemplateId = ElementId.InvalidElementId; plan.Scale = Scale; var originalBoundingBox = candidate.Room.get_BoundingBox(plan); // Put them on sheets plan.CropBox = CreateOffsetBoundingBox(50000, originalBoundingBox); plan.Name = candidate.DestinationViewName; // Shrink the bounding box now that it is placed var vp = Viewport.Create(doc, sheet.Id, plan.Id, sheetCentre); // Shrink the bounding box now that it is placed plan.CropBox = CreateOffsetBoundingBox(CropRegionEdgeOffset, originalBoundingBox); // FIXME - To set an empty view title - so far this seems to work with the standard revit template... vp.ChangeTypeId(vp.GetValidTypes().Last()); // FIXME Apply a view template // NOTE This could cause trouble with view scales plan.ViewTemplateId = ViewTemplateId; SCaddinsApp.WindowManager.ShowMessageBox("test"); } }
/// <summary> /// Get common informations for batch creation /// </summary> private void PreCreate() { try { Autodesk.Revit.Creation.Application appCreation = m_cmdData.Application.Application.Create; //Try to get Level named "Level 1" which will be used in most creations m_level = (from elem in new FilteredElementCollector(m_doc).OfClass(typeof(Level)).ToElements() let level = elem as Level where level!=null && "Level 1"==level.Name select level).First(); //If ViewPlan "Level 1" does not exist, try to create one. if (null != m_level) { try { m_viewPlan = m_doc.Create.NewAreaViewPlan("Level 1", m_level,AreaElemType.BOMAArea); } catch { } } if (null == m_level && null==m_viewPlan) { return; } //Create RectangularWallCreationData for Walls' batch creation List<RectangularWallCreationData> rectangularWallCreationDatas = new List<RectangularWallCreationData>(); //List of Curve is used to store Area's boundary lines List<Curve> curves = new List<Curve>(); Autodesk.Revit.DB.XYZ pt1 = new Autodesk.Revit.DB.XYZ (-4, 95, 0); Autodesk.Revit.DB.XYZ pt2 = new Autodesk.Revit.DB.XYZ (-106, 95, 0); Line line = appCreation.NewLine(pt1, pt2, true); RectangularWallCreationData rectangularWallCreationData = null; if (null != line) { rectangularWallCreationData = new RectangularWallCreationData(line, m_level, true); curves.Add(line); } if (null != rectangularWallCreationData) { rectangularWallCreationDatas.Add(rectangularWallCreationData); } pt1 = new Autodesk.Revit.DB.XYZ (-4, 105, 0); pt2 = new Autodesk.Revit.DB.XYZ (-106, 105, 0); line = appCreation.NewLine(pt1, pt2, true); if (null != line) { rectangularWallCreationData = new RectangularWallCreationData(line, m_level, true); curves.Add(line); } if (null != rectangularWallCreationData) { rectangularWallCreationDatas.Add(rectangularWallCreationData); } for (int i = 0; i < 11; i++) { pt1 = new Autodesk.Revit.DB.XYZ (-5 - i * 10, 94, 0); pt2 = new Autodesk.Revit.DB.XYZ (-5 - i * 10, 106, 0); line = appCreation.NewLine(pt1, pt2, true); if (null != line) { rectangularWallCreationData = new RectangularWallCreationData(line, m_level, true); curves.Add(line); } if (null != rectangularWallCreationData) { rectangularWallCreationDatas.Add(rectangularWallCreationData); } } // Create Area Boundary Line for Area // It is necessary if need to create closed region for Area // But for Room, it is not necessary. Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ (0, 0, 0); Autodesk.Revit.DB.XYZ norm = new Autodesk.Revit.DB.XYZ (0, 0, 1); Plane plane = appCreation.NewPlane(norm, origin); if(null != plane) { SketchPlane sketchPlane = m_doc.Create.NewSketchPlane(plane); if(null != sketchPlane) { foreach (Curve curve in curves) { m_doc.Create.NewAreaBoundaryLine(sketchPlane, curve, m_viewPlan); } } } //Create enclosed region using Walls for Room pt1 = new Autodesk.Revit.DB.XYZ (5, -5, 0); pt2 = new Autodesk.Revit.DB.XYZ (55, -5, 0); line = appCreation.NewLine(pt1, pt2, true); rectangularWallCreationData = null; if (null != line) { rectangularWallCreationData = new RectangularWallCreationData(line, m_level, true); } if (null != rectangularWallCreationData) { rectangularWallCreationDatas.Add(rectangularWallCreationData); } pt1 = new Autodesk.Revit.DB.XYZ (5, 5, 0); pt2 = new Autodesk.Revit.DB.XYZ (55, 5, 0); line = appCreation.NewLine(pt1, pt2, true); if (null != line) { rectangularWallCreationData = new RectangularWallCreationData(line, m_level, true); } if (null != rectangularWallCreationData) { rectangularWallCreationDatas.Add(rectangularWallCreationData); } for (int i = 0; i < 6; i++) { pt1 = new Autodesk.Revit.DB.XYZ (5 + i * 10, -5, 0); pt2 = new Autodesk.Revit.DB.XYZ (5 + i * 10, 5, 0); line = appCreation.NewLine(pt1, pt2, true); if (null != line) { rectangularWallCreationData = new RectangularWallCreationData(line, m_level, true); } if (null != rectangularWallCreationData) { rectangularWallCreationDatas.Add(rectangularWallCreationData); } } // Call Wall batch creation method to create Walls m_doc.Create.NewWalls(rectangularWallCreationDatas); } catch (Exception) { } }
public ElevationMarker PlaceMarker(Document doc, BoundingBoxXYZ wallbb, Wall w) { XYZ wallbbmin = wallbb.Min; XYZ wallbbmax = wallbb.Max; ViewPlan plan = DocumentElevPlanViews(doc); Parameter p = plan.get_Parameter(BuiltInParameter.VIEW_PHASE); //Debug("p equals " + p.AsElementId() + " phase called " + p.AsValueString()); ////Element planPhase = doc.GetElement(p.AsElementId()); ////Debug("planPhase equals " + planPhase); //List<Room> allRooms = RoomHelpers.GetAllRooms(doc); //foreach(Room room in allRooms) //{ // //Parameter roomPhase = room.get_Parameter(BuiltInParameter.VIEW_PHASE); // //Debug("Room Phase View Phase " + room.Name + " - " + roomPhase + " (" + roomPhase.AsValueString() + ")"); // Parameter roomPhase2 = room.get_Parameter(BuiltInParameter.PHASE_CREATED); // Debug("Room Phase Phase Created " + room.Name + " - " + roomPhase2.AsElementId().ToString() + " (" + roomPhase2.AsValueString() + ")"); // Parameter roomPhase3 = room.get_Parameter(BuiltInParameter.ROOM_PHASE); // Debug("Room Phase Room Phase " + room.Name + " - " + roomPhase3.AsElementId().ToString() + " (" + roomPhase3.AsValueString() + ")"); // //ElementId roomPhase1 = room.CreatedPhaseId; // //Debug("Room Phase 1 " + room.Name + " - " + roomPhase1 + " (" + roomPhase1.ToString() + ")"); //} //Debug("Wallbb min " + wallbbmin); //Debug("Wallbb max " + wallbbmax); //Debug("Plan phase Id " + p.AsElementId().ToString()); ////Debug("Plan phase Name " + planPhase.Name); XYZ wallCenter = new XYZ( (wallbbmax.X + wallbbmin.X) / 2, (wallbbmax.Y + wallbbmin.Y) / 2, wallbbmin.Z ); List <Room> phasedRooms = RoomHelpers.GetPhasedRooms(doc, p.AsElementId()); //Debug("Phase of wall " + w.CreatedPhaseId.ToString()); //Debug("Phase of wall name " + w.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString()); XYZ wallCenterYTranslatedPositive = new XYZ( wallCenter.X, wallCenter.Y + 10, wallCenter.Z ); XYZ wallCenterYTranslatedNegative = new XYZ( wallCenter.X, wallCenter.Y - 10, wallCenter.Z ); XYZ wallCenterXTranslatedPositive = new XYZ( wallCenter.X + 10, wallCenter.Y, wallCenter.Z ); XYZ wallCenterXTranslatedNegative = new XYZ( wallCenter.X - 10, wallCenter.Y, wallCenter.Z ); //Debug("wall center " + wallCenter); //Debug("wallCenterYTranslatedPositive " + wallCenterYTranslatedPositive); //Debug("wallCenterYTranslatedNegative " + wallCenterYTranslatedNegative); //Debug("wallCenterXTranslatedPositive " + wallCenterXTranslatedPositive); //Debug("wallCenterXTranslatedNegative " + wallCenterXTranslatedNegative); XYZ markerLocation = wallCenter; Debug("markerLocation before the loops " + markerLocation); Debug("length of list phasedrooms " + phasedRooms.Count); if ((wallbbmax.X - wallbbmin.X) > (wallbbmax.Y - wallbbmin.Y)) { foreach (Room r in phasedRooms) { if (r.IsPointInRoom(wallCenterYTranslatedPositive)) { Debug("room name " + r.Name); Debug("is Y positive in room " + r.IsPointInRoom(wallCenterYTranslatedPositive)); markerLocation = wallCenterYTranslatedNegative; break; } else if (r.IsPointInRoom(wallCenterYTranslatedNegative)) { Debug("room name " + r.Name); Debug("is Y negative in room " + r.IsPointInRoom(wallCenterYTranslatedNegative)); markerLocation = wallCenterYTranslatedPositive; break; } } Debug("is Y check done"); } else { foreach (Room r in phasedRooms) { if (r.IsPointInRoom(wallCenterXTranslatedPositive)) { Debug("room name " + r.Name); Debug("is X positive in room " + r.IsPointInRoom(wallCenterXTranslatedPositive)); markerLocation = wallCenterXTranslatedNegative; break; } else if (r.IsPointInRoom(wallCenterXTranslatedNegative)) { Debug("room name " + r.Name); Debug("is X negative in room " + r.IsPointInRoom(wallCenterXTranslatedNegative)); markerLocation = wallCenterXTranslatedPositive; break; } } Debug("is X check done"); } Debug("selected marker location after loops " + markerLocation); //change scale to user input ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, FindFamilyTypeId(doc), markerLocation, 96); marker.get_Parameter(BuiltInParameter.PHASE_CREATED).Set(p.AsElementId()); if (marker.IsAvailableIndex(0)) { ViewSection extElev = marker.CreateElevation(doc, plan.Id, 0); extElev.get_Parameter(BuiltInParameter.VIEW_PHASE).Set(p.AsElementId()); } return(marker); }
public static List <ViewPlan> DuplicateViewPlan(this ViewPlan viewPlan, IEnumerable <Level> levels = null, bool useExisting = false) { if (viewPlan == null || !viewPlan.IsValidObject || viewPlan.IsTemplate) { return(null); } Document document = viewPlan.Document; if (document == null) { return(null); } List <Level> levels_Temp = null; if (levels != null) { levels_Temp = new List <Level>(levels); } if (levels_Temp == null) { levels_Temp = new FilteredElementCollector(document).OfClass(typeof(Level)).Cast <Level>().ToList(); } List <Element> elements_ColorFillLegend = new FilteredElementCollector(document, viewPlan.Id).OfCategory(BuiltInCategory.OST_ColorFillLegends).ToList(); List <ViewPlan> result = new List <ViewPlan>(); foreach (Level level in levels_Temp) { if (level.Id == viewPlan.GenLevel.Id) { continue; } ViewPlan viewPlan_New = null; List <ViewPlan> viewPlans = new FilteredElementCollector(document).OfClass(typeof(ViewPlan)).Cast <ViewPlan>().ToList(); string name = level.Name; if (useExisting) { viewPlan_New = viewPlans.Find(x => x.Name == name); } if (viewPlan_New == null) { viewPlan_New = ViewPlan.Create(document, viewPlan.GetTypeId(), level.Id); // Check name uniqueness string name_Temp = name; int count = 0; while (viewPlans.Find(x => x.Name == name_Temp) != null) { count++; name_Temp = string.Format("{0} {1}", name, count); } viewPlan_New.Name = name_Temp; } foreach (Parameter parameter in viewPlan.ParametersMap) { if (parameter.Id.IntegerValue == (int)BuiltInParameter.VIEW_NAME) { continue; } Definition definition = parameter?.Definition; if (definition == null) { continue; } Parameter parameter_New = viewPlan_New.get_Parameter(parameter.Definition); if (parameter_New == null) { continue; } CopyValue(parameter, parameter_New); } if (elements_ColorFillLegend != null && elements_ColorFillLegend.Count != 0) { ElementTransformUtils.CopyElements(viewPlan, elements_ColorFillLegend.ConvertAll(x => x.Id), viewPlan_New, null, new CopyPasteOptions()); } result.Add(viewPlan_New); IEnumerable <ElementId> elementIds_Dependent = viewPlan.GetDependentViewIds(); if (elementIds_Dependent != null && elementIds_Dependent.Count() != 0) { foreach (ElementId elementId_Dependent in elementIds_Dependent) { ViewPlan viewPlan_Dependent = document.GetElement(elementId_Dependent) as ViewPlan; if (viewPlan_Dependent == null) { continue; } viewPlans = new FilteredElementCollector(document).OfClass(typeof(ViewPlan)).Cast <ViewPlan>().ToList(); string name_Dependent = name; if (viewPlan_Dependent.Name.StartsWith(viewPlan.Name)) { name_Dependent = level.Name + viewPlan_Dependent.Name.Substring(viewPlan.Name.Length); } else { Element scopeBox = viewPlan_Dependent.ScopeBox(); if (scopeBox != null) { name_Dependent = level.Name + " - " + scopeBox.Name; } } ViewPlan viewPlan_Dependent_New = null; if (useExisting) { viewPlan_Dependent_New = viewPlans.Find(x => x.Name == name_Dependent); } if (viewPlan_Dependent_New == null) { ElementId elementId_Dependent_New = viewPlan_New.Duplicate(ViewDuplicateOption.AsDependent); if (elementId_Dependent_New == null || elementId_Dependent_New == ElementId.InvalidElementId) { continue; } viewPlan_Dependent_New = document.GetElement(elementId_Dependent_New) as ViewPlan; if (viewPlan_Dependent_New == null) { continue; } // Check name uniqueness string name_Dependent_Temp = name_Dependent; int count = 0; while (viewPlans.Find(x => x.Name == name_Dependent_Temp) != null) { count++; name_Dependent_Temp = string.Format("{0} {1}", name_Dependent, count); } viewPlan_Dependent_New.Name = name_Dependent_Temp; } foreach (Parameter parameter in viewPlan_Dependent.ParametersMap) { if (parameter.Id.IntegerValue == (int)BuiltInParameter.VIEW_NAME) { continue; } Definition definition = parameter?.Definition; if (definition == null) { continue; } Parameter parameter_New = viewPlan_Dependent_New.get_Parameter(parameter.Definition); if (parameter_New == null) { continue; } CopyValue(parameter, parameter_New); } result.Add(viewPlan_Dependent_New); } } } return(result); }
private void AddNewViewSheets_OLD(int id) { if (uidoc.Document != null) { if (requestData != null) { for (int i = 0; i < requestData.viewSheetsInfo.Count; i++) { Tuple <string, string, string, string, string> curViewSheetInfo = requestData.viewSheetsInfo[i]; ElementId titleBlocktId = GetTitleBlockIdByName(curViewSheetInfo.Item5); if (titleBlocktId == null) { titleBlocktId = new ElementId(-1); } ViewSheet norViewSheet = ViewSheet.Create(uidoc.Document, titleBlocktId); norViewSheet.SheetNumber = curViewSheetInfo.Item1; norViewSheet.Name = curViewSheetInfo.Item2; View viewPlan = GetViewByName(curViewSheetInfo.Item4); if (viewPlan == null) { ViewFamilyType viewFamilyType = null; FilteredElementCollector collector = new FilteredElementCollector(uidoc.Document); var viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in viewFamilyTypes) { ViewFamilyType v = e as ViewFamilyType; if (v.ViewFamily == ViewFamily.FloorPlan) { viewFamilyType = v; break; } } Level exLevel = null; FilteredElementCollector collectorLevel = new FilteredElementCollector(uidoc.Document); var levels = collectorLevel.OfClass(typeof(Level)).ToElements(); foreach (Element e in levels) { exLevel = e as Level; } if ((viewFamilyType != null) && (exLevel != null)) { viewPlan = ViewPlan.Create(uidoc.Document, viewFamilyType.Id, exLevel.Id); viewPlan.Name = curViewSheetInfo.Item4; } } else { } if (viewPlan != null) { try { int curMainScale = GetScaleFromString(curViewSheetInfo.Item3); SetViewForSheet(viewPlan, norViewSheet, curMainScale); } catch (Exception ex) { TaskDialog.Show("Exc", ex.Message + " " + norViewSheet.SheetNumber); } } } uidoc.RefreshActiveView(); } } else { TaskDialog.Show("Info", "doc is null"); } }
public Result add_dimension_from_point(ViewPlan floorView, XYZ pt, XYZ normal, XYZ offset) { return(add_dimension_from_point(floorView, pt, normal, "", offset)); }
/// <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) { // We may re-use the ActiveView Level and View, since we can't delete them. // We will consider that we "created" this level and view for creation metrics. Level level = Importer.TheCache.UseElementByGUID <Level>(doc, GlobalId); bool reusedLevel = false; bool foundLevel = false; if (level == null) { if (ExistingLevelIdToReuse != ElementId.InvalidElementId) { level = doc.GetElement(ExistingLevelIdToReuse) as Level; Importer.TheCache.UseElement(level); ExistingLevelIdToReuse = ElementId.InvalidElementId; reusedLevel = true; } } else { foundLevel = true; } if (level == null) { level = doc.Create.NewLevel(m_Elevation); } else { level.Elevation = m_Elevation; } if (level != null) { CreatedElementId = level.Id; } if (CreatedElementId != ElementId.InvalidElementId) { if (!foundLevel) { if (!reusedLevel) { ElementId viewPlanTypeId = IFCBuildingStorey.GetViewPlanTypeId(doc); if (viewPlanTypeId != ElementId.InvalidElementId) { ViewPlan viewPlan = ViewPlan.Create(doc, viewPlanTypeId, CreatedElementId); if (viewPlan != null) { CreatedViewId = viewPlan.Id; } } if (CreatedViewId == ElementId.InvalidElementId) { Importer.TheLog.LogAssociatedCreationError(this, typeof(ViewPlan)); } } else { if (doc.ActiveView != null) { CreatedViewId = doc.ActiveView.Id; } } } } else { Importer.TheLog.LogCreationError(this, null, false); } TraverseSubElements(doc); }
public Result add_dimension_from_points(ViewPlan floorView, XYZ pt1, XYZ pt2, XYZ normal, string dimension, XYZ offset) { return(add_dimension_from_points(floorView, pt1, normal, pt2, -normal, dimension, offset)); }
protected GCViewLive(ViewPlan view) : base(view) { }
public Result add_dimension_from_points(ViewPlan floorView, XYZ pt1, XYZ normal1, XYZ pt2, XYZ normal2, string dimension, XYZ offset) { Transaction trans = new Transaction(doc); offset = new XYZ(offset.X / 12.0, offset.Y / 12.0, offset.Z); pt1 = new XYZ(pt1.X / 12, pt1.Y / 12, pt1.Z); pt2 = new XYZ(pt2.X / 12, pt2.Y / 12, pt2.Z); ElementClassFilter filter = new ElementClassFilter(typeof(WallType)); ViewFamilyType viewFamily = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .First(x => x.ViewFamily == ViewFamily.ThreeDimensional); View3D view; using (trans = new Transaction(doc)) { trans.Start("Create temp view"); view = View3D.CreateIsometric(doc, viewFamily.Id); trans.Commit(); } List <BuiltInCategory> builtInCats = new List <BuiltInCategory>(); builtInCats.Add(BuiltInCategory.OST_Roofs); builtInCats.Add(BuiltInCategory.OST_Ceilings); builtInCats.Add(BuiltInCategory.OST_Floors); builtInCats.Add(BuiltInCategory.OST_Walls); ElementMulticategoryFilter intersectFilter = new ElementMulticategoryFilter(builtInCats); ReferenceIntersector ri1 = new ReferenceIntersector(intersectFilter, FindReferenceTarget.Face, view); ReferenceIntersector ri2 = new ReferenceIntersector(intersectFilter, FindReferenceTarget.Face, view); ReferenceWithContext ref1 = ri1.FindNearest(pt1, normal1); ReferenceWithContext ref2 = ri2.FindNearest(pt2, normal2); using (trans = new Transaction(doc)) { trans.Start("Delete temp view"); doc.Delete(view.Id); trans.Commit(); } ReferenceArray ra = new ReferenceArray(); ra.Append(ref1.GetReference()); ra.Append(ref2.GetReference()); Line line = Line.CreateBound(pt1.Add(offset), pt1.Add(offset).Add(normal1)); Dimension dim; DimensionType dType = null; using (Transaction t = new Transaction(doc)) { t.Start("Create New Dimension"); dim = doc.Create.NewDimension(floorView, line, ra); if (dimension.Equals("")) { dType = new FilteredElementCollector(doc) .OfClass(typeof(DimensionType)) .Cast <DimensionType>().FirstOrDefault(q => q.Name == "type-unknown"); } else if (dimension.Equals(dim.ValueString)) { dType = new FilteredElementCollector(doc) .OfClass(typeof(DimensionType)) .Cast <DimensionType>().FirstOrDefault(q => q.Name == "type-correct"); } else { dType = new FilteredElementCollector(doc) .OfClass(typeof(DimensionType)) .Cast <DimensionType>().FirstOrDefault(q => q.Name == "type-incorrect"); } dim.DimensionType = dType; t.Commit(); } return(Result.Succeeded); }
/// <summary> /// Get common informations for batch creation /// </summary> private void PreCreate() { try { Autodesk.Revit.Creation.Application appCreation = m_cmdData.Application.Application.Create; //Try to get Level named "Level 1" which will be used in most creations m_level = (from elem in new FilteredElementCollector(m_doc).OfClass(typeof(Level)).ToElements() let level = elem as Level where level != null && "Level 1" == level.Name select level).First(); //If ViewPlan "Level 1" does not exist, try to create one. if (null != m_level) { ElementId AreaSchemeId = new FilteredElementCollector(m_doc).OfClass(typeof(AreaScheme)).FirstOrDefault(a => a.Name == "Rentable").Id; try { m_viewPlan = ViewPlan.CreateAreaPlan(m_doc, AreaSchemeId, m_level.Id); m_viewPlan.Name = "Level 1"; } catch { } } if (null == m_level && null == m_viewPlan) { return; } //List of Curve is used to store Area's boundary lines List <Curve> curves = new List <Curve>(); Autodesk.Revit.DB.XYZ pt1 = new Autodesk.Revit.DB.XYZ(-4, 95, 0); Autodesk.Revit.DB.XYZ pt2 = new Autodesk.Revit.DB.XYZ(-106, 95, 0); Line line = Line.CreateBound(pt1, pt2); curves.Add(line); pt1 = new Autodesk.Revit.DB.XYZ(-4, 105, 0); pt2 = new Autodesk.Revit.DB.XYZ(-106, 105, 0); line = Line.CreateBound(pt1, pt2); curves.Add(line); for (int i = 0; i < 11; i++) { pt1 = new Autodesk.Revit.DB.XYZ(-5 - i * 10, 94, 0); pt2 = new Autodesk.Revit.DB.XYZ(-5 - i * 10, 106, 0); line = Line.CreateBound(pt1, pt2); if (null != line) { curves.Add(line); } } // Create Area Boundary Line for Area // It is necessary if need to create closed region for Area // But for Room, it is not necessary. Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ(0, 0, 0); Autodesk.Revit.DB.XYZ norm = new Autodesk.Revit.DB.XYZ(0, 0, 1); Plane plane = appCreation.NewPlane(norm, origin); if (null != plane) { SketchPlane sketchPlane = SketchPlane.Create(m_doc, plane); if (null != sketchPlane) { foreach (Curve curve in curves) { m_doc.Create.NewAreaBoundaryLine(sketchPlane, curve, m_viewPlan); } } } //Create enclosed region using Walls for Room pt1 = new Autodesk.Revit.DB.XYZ(5, -5, 0); pt2 = new Autodesk.Revit.DB.XYZ(55, -5, 0); line = Line.CreateBound(pt1, pt2); Wall.Create(m_doc, line, m_level.Id, true); pt1 = new Autodesk.Revit.DB.XYZ(5, 5, 0); pt2 = new Autodesk.Revit.DB.XYZ(55, 5, 0); line = Line.CreateBound(pt1, pt2); Wall.Create(m_doc, line, m_level.Id, true); for (int i = 0; i < 6; i++) { pt1 = new Autodesk.Revit.DB.XYZ(5 + i * 10, -5, 0); pt2 = new Autodesk.Revit.DB.XYZ(5 + i * 10, 5, 0); line = Line.CreateBound(pt1, pt2); Wall.Create(m_doc, line, m_level.Id, true); } } catch (Exception) { } }
public ViewPlan setup_view(ViewType vt) { IList <Level> levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast <Level>().OrderBy(l => l.Elevation).ToList(); Transaction trans = new Transaction(doc); ViewFamily vf = ViewFamily.Invalid; if (vt == ViewType.FloorPlan) { vf = ViewFamily.StructuralPlan; } else if (vt == ViewType.CeilingPlan) { vf = ViewFamily.CeilingPlan; } ViewFamilyType FviewFamily = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .First(x => x.ViewFamily == vf); ViewPlan view = new FilteredElementCollector(doc) .OfClass(typeof(ViewPlan)) .Cast <ViewPlan>().FirstOrDefault(q => q.Name == level.Name && q.ViewType == vt); // FIXME : need to filter by vf using (trans = new Transaction(doc)) { trans.Start("View plans"); if (view is null) { view = ViewPlan.Create(doc, FviewFamily.Id, level.Id); } trans.Commit(); } if (vt == ViewType.FloorPlan) { FilteredElementCollector col_ = new FilteredElementCollector(doc); col_.OfClass(typeof(FamilySymbol)); col_.OfCategory(BuiltInCategory.OST_TitleBlocks); FamilySymbol fs = col_.FirstElement() as FamilySymbol; using (trans = new Transaction(doc)) { trans.Start("Sheet"); Family tf = null; //Choose appropriate path string tfamilyPath = @"C:\Users\John\Documents\owncloud\revit\Families\11x8 title block.rfa"; doc.LoadFamily(tfamilyPath, out tf); // Get the available title block from document FamilySymbol FS = null; FilteredElementCollector col__ = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_TitleBlocks); Element TB = null; foreach (Element e in col__) { if (e.Name.Contains("11x8")) { TB = e; } } ViewSheet viewSheet = ViewSheet.Create(doc, TB.Id); UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2); //viewSheet.AddView(view3D, location); Viewport.Create(doc, viewSheet.Id, view.Id, new XYZ(location.U, location.V, 0)); viewSheet.Name = level.Name; trans.Commit(); } } return(view); }
private void CreateLevelsAndMainViewSheets(int id) { if (uidoc.Document != null) { if (requestData != null) { List <Element> allNonViewElements = getAllNonViewElementsOfDoc(); if (requestData.mainSheetsInfo.Count == (requestData.levelsAmount * requestData.mainSheetsAmount)) { for (int l = 0; l < requestData.levelsAmount; l++) { double norLevelElevation = l * requestData.levelsDistance; Level norLevel = Level.Create(uidoc.Document, norLevelElevation); string levelName = "Level-" + (l + 1).ToString(); norLevel.Name = levelName; for (int m = 0; m < requestData.mainSheetsAmount; m++) { Tuple <string, string, string> curMainSheetInfo = requestData.mainSheetsInfo[l * requestData.mainSheetsAmount + m]; ElementId titleBlocktId = GetTitleBlockIdByName(requestData.titleBlockName); if (titleBlocktId == null) { titleBlocktId = new ElementId(-1); } ViewSheet norViewSheet = ViewSheet.Create(uidoc.Document, titleBlocktId); norViewSheet.SheetNumber = curMainSheetInfo.Item1; norViewSheet.Name = curMainSheetInfo.Item2; View norSheetViewPlan = null; ViewFamilyType viewFamilyType = null; FilteredElementCollector collector = new FilteredElementCollector(uidoc.Document); var viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in viewFamilyTypes) { ViewFamilyType v = e as ViewFamilyType; if (v.ViewFamily == ViewFamily.FloorPlan) { viewFamilyType = v; break; } } if ((viewFamilyType != null) && (norLevel != null)) { norSheetViewPlan = ViewPlan.Create(uidoc.Document, viewFamilyType.Id, norLevel.Id); norSheetViewPlan.Name = norViewSheet.Name; } if (norSheetViewPlan != null) { View viewTemplate = GetViewTemplateByName(curMainSheetInfo.Item3); bool templateApplied = false; if (viewTemplate != default(View)) { List <ElementId> hiddenElemsIds = new List <ElementId>(); foreach (Element curHidVisElem in allNonViewElements) { if (curHidVisElem.IsHidden(viewTemplate)) { hiddenElemsIds.Add(curHidVisElem.Id); } } try { norSheetViewPlan.HideElements(hiddenElemsIds); } catch (Exception ex) { } try { norSheetViewPlan.ViewTemplateId = viewTemplate.Id; templateApplied = true; } catch { } } try { int curMainScale; if (!templateApplied) { curMainScale = GetScaleFromString(requestData.mainSheetsScale); } else { if (uidoc.Document.DisplayUnitSystem == DisplayUnit.IMPERIAL) { curMainScale = GetScaleFromString(viewTemplate.get_Parameter(BuiltInParameter.VIEW_SCALE_PULLDOWN_IMPERIAL).AsValueString()); } else { curMainScale = GetScaleFromString(viewTemplate.get_Parameter(BuiltInParameter.VIEW_SCALE_PULLDOWN_METRIC).AsValueString()); } } SetViewForSheet(norSheetViewPlan, norViewSheet, curMainScale); } catch (Exception ex) { } } } } } else { } uidoc.RefreshActiveView(); } } else { TaskDialog.Show("Info", "doc is null"); } }
public Result add_dimension_from_point(ViewPlan floorView, XYZ pt, XYZ normal, string dimension) { XYZ offset = new XYZ(0, 0, 0); return(add_dimension_from_point(floorView, pt, normal, dimension, offset)); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { _uiapp = commandData.Application; _uidoc = _uiapp.ActiveUIDocument; _doc = _uidoc.Document; try { // Get list of all structural view plans IList <ViewPlan> viewPlanList = GetAllStructuralPlans(_doc, true); if (viewPlanList.Count == 0) { return(Result.Cancelled); } Dictionary <string, ViewPlan> viewDic = new Dictionary <string, ViewPlan>(); foreach (ViewPlan vp in viewPlanList) { // filter structural view plan Regex regex = new Regex(@"r\+\d+|rdc|ss\d|ss\-\d"); Match match = regex.Match(vp.Name.ToLower()); // TODO : to be improved if (match.Success && vp.Name.Contains("PH")) { if (!viewDic.ContainsKey(match.Value)) { viewDic.Add(match.Value.ToLower(), vp); } } } CADLinkForm form = new CADLinkForm(viewDic); if (form.ShowDialog() == DialogResult.OK) { DWGImportOptions opt = new DWGImportOptions { Placement = ImportPlacement.Origin, AutoCorrectAlmostVHLines = true, ThisViewOnly = false, Unit = form.Unit, }; ElementId linkId = ElementId.InvalidElementId; // add links foreach (DataGridViewRow row in form.DataGridView.Rows) { string keyword = row.Cells[0].Value.ToString(); if (!string.IsNullOrEmpty(keyword)) { ViewPlan view = viewDic[keyword]; string filePath = row.Cells[2].Value.ToString(); using (Transaction tran = new Transaction(_doc, "Quick Link")) { tran.Start(); _doc.Link(filePath, opt, view, out linkId); tran.Commit(); } } } return(Result.Succeeded); } else { return(Result.Cancelled); } } catch (Exception e) { message = e.Message; return(Result.Failed); } }
public void _99_DrawLinePatterns(bool patternsNotWeights, bool styles, UIDocument uidoc) { Document doc = uidoc.Document; bool modellines = false; bool closing = true; View view = doc.ActiveView; if (!modellines) { View3D myView3D = doc.ActiveView as View3D; if (myView3D != null) { TaskDialog.Show("Not the correct type of view", "'Detail' lines can't be drawn in 3D view."); return; } } if (modellines) { ViewPlan myViewPlan = doc.ActiveView as ViewPlan; if (myViewPlan == null) { TaskDialog.Show("Not the correct type of view", "The active view must be a view 'plan'"); return; } } UIView uiview = null; IList <UIView> uiviews = uidoc.GetOpenUIViews(); foreach (UIView uv in uiviews) { if (uv.ViewId.Equals(view.Id)) { uiview = uv; break; } } View nextView = doc.GetElement(view.GetPrimaryViewId()) as View; if (nextView != null) { TaskDialog.Show("Cannot proceed", "Please goto the 'parent' view."); return; } Rectangle rect = uiview.GetWindowRectangle(); IList <XYZ> corners = uiview.GetZoomCorners(); XYZ pXchanges = corners[0]; XYZ qXchanges = corners[1]; double divideScreeenWidthBy50 = ((corners[1].X - corners[0].X) / 50); double halfOfX = corners[0].X;//corners[0].X + ((corners[1].X - corners[0].X)/2); pXchanges = new XYZ(halfOfX + (divideScreeenWidthBy50 * 10), corners[0].Y + (corners[0].Y / 10), 0); qXchanges = new XYZ(halfOfX + (divideScreeenWidthBy50 * 10), corners[1].Y - (corners[1].Y / 10), 0); XYZ[] pts = new XYZ[] { pXchanges, qXchanges, }; List <Curve> profile = new List <Curve>(pts.Length); // 2013 var collector = new FilteredElementCollector(doc).OfClass(typeof(LinePatternElement)).ToList(); List <ElementId> ids = new List <ElementId>(); for (int i = 0; i < collector.Count(); i++) { // thenamesoflinepatterns = thenamesoflinepatterns + collector[i].Name + Environment.NewLine; ids.Add(collector[i].Id); } if (ids == null) { TaskDialog.Show("Cannot proceed", "is null"); return; } // transaction.Commit(); if (patternsNotWeights) { foreach (ElementId linePatternID in ids) { notToRepeatLoopContents(closing, pts, profile, divideScreeenWidthBy50, doc, modellines, linePatternID, -1, patternsNotWeights, uidoc); } } else { for (int ii = 1; ii <= 16; ii++) { notToRepeatLoopContents(closing, pts, profile, divideScreeenWidthBy50, doc, modellines, new ElementId(-1), ii, patternsNotWeights, uidoc); } } //writeDebug(thenamesoflinepatterns); }
/// <summary> /// Main function to create all views /// </summary> /// <param name="doc"></param> /// <returns></returns> private bool makeViews(Document doc) { // Get all View Type Families for Floor Plans IEnumerable <Element> viewFTypesFP = from e in new FilteredElementCollector(_doc).OfClass(typeof(ViewFamilyType)) let type = e as ViewFamilyType where type.ViewFamily == ViewFamily.FloorPlan select type; // Get all View Type Families for Floor Plans IEnumerable <Element> viewFTypesCP = from e in new FilteredElementCollector(_doc).OfClass(typeof(ViewFamilyType)) let type = e as ViewFamilyType where type.ViewFamily == ViewFamily.CeilingPlan select type; // Failures and Success string m_fails = ""; string m_sucess = ""; // Check that atleast on level is checked if (this.checkedListBox1.CheckedItems.Count == 0) { MessageBox.Show("Please choose at least one Level to create a view.", "Hold On Silly..."); return(false); } else { // Loop through each item checked foreach (Object obj in this.checkedListBox1.CheckedItems) { // Step Progress this.progressBar1.Increment(1); System.Windows.Forms.Application.DoEvents(); // Get the level Level level = obj as Level; string viewdiscipline = this.cbViewDiscipline.SelectedValue.ToString(); string viewtype = this.cbViewType.SelectedValue.ToString(); string viewtypename = this.cbViewType.SelectedValue.ToString(); string subdiscipline = this.textSubDiscipline.Text; string viewname = ""; if (app.myProduct == "MEP") { viewname = subdiscipline + " " + level.Name + " " + viewtypename; } else { viewname = viewdiscipline + " " + level.Name + " " + viewtypename; } viewname = viewname.ToUpper(); // Check that sub-discipline box has been filled if (app.myProduct == "MEP" && subdiscipline.Trim() == "") { MessageBox.Show("Sub-Discipline can not be blank.", "Hold On ..."); return(false); } else { // Start Transaction Transaction t = new Transaction(doc, "Create " + viewdiscipline + " " + level.Name + " " + viewtype); t.Start(); // View Name (for errors) string m_viewName = viewdiscipline + " " + level.Name + " " + viewtype; try { // Chcek viewtype if (viewtype == "Floor Plan") { // Create the view ViewPlan viewplan = ViewPlan.Create(_doc, viewFTypesFP.First().Id, level.Id); // Set the discipline based on combobox selection if (viewdiscipline == "Architectural") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(1); } else if (viewdiscipline == "Structural") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(2); } else if (viewdiscipline == "Mechanical") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(4); } else if (viewdiscipline == "Electrical") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(8); } else if (viewdiscipline == "Coordination") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(4095); } else { MessageBox.Show("Invalid Discipline", "Error"); break; } if (app.myProduct == "MEP") { // Set Sub-Discipline based on text box entry clsParameterData.GetParameterByName(viewplan, "Sub-Discipline").Set(subdiscipline); } } else { // Check viewtype ViewPlan viewplan = ViewPlan.Create(_doc, viewFTypesCP.First().Id, level.Id); // Set the discipline based on combobox selection if (viewdiscipline == "Architectural") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(1); } else if (viewdiscipline == "Structural") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(2); } else if (viewdiscipline == "Mechanical") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(4); } else if (viewdiscipline == "Electrical") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(8); } else if (viewdiscipline == "Coordination") { viewplan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(4095); } else { MessageBox.Show("Invalid Discipline", "Error"); break; } if (app.myProduct == "MEP") { // Set the discipline based on combobox selection clsParameterData.GetParameterByName(viewplan, "Sub-Discipline").Set(subdiscipline); } } // Commit m_sucess += "\n" + m_viewName.ToUpper(); t.Commit(); } catch { // Rollback on Failure t.RollBack(); m_fails += "\n" + m_viewName.ToUpper(); // return false; } } } } // Report to the user TaskDialog m_td = new TaskDialog("Here's What Happend:"); m_td.MainContent = "Successful Views:" + m_sucess + "\n\nFailed Views:" + m_fails; m_td.MainInstruction = "Created Some Views... or Not:"; m_td.Show(); return(true); }
private void WriteElementGeometry( int elementId ) { FilteredElementCollector viewCollector = new FilteredElementCollector( m_doc ); viewCollector.OfClass( typeof( ViewPlan ) ); Func<ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan; m_targetView = viewCollector.Cast<ViewPlan>().First<ViewPlan>( isLevel1FloorPlan ); Transaction createCurve = new Transaction( m_doc, "Create reference curves" ); createCurve.Start(); const double xReferenceLocation = 30; Line vLine = Line.CreateBound( new XYZ( xReferenceLocation, 0, 0 ), new XYZ( xReferenceLocation, 20, 0 ) ); m_vLine = m_doc.Create.NewDetailCurve( m_targetView, vLine ); const double yReferenceLocation = -10; Line hLine = Line.CreateBound( new XYZ( 0, yReferenceLocation, 0 ), new XYZ( 20, yReferenceLocation, 0 ) ); m_hLine = m_doc.Create.NewDetailCurve( m_targetView, hLine ); createCurve.Commit(); Element e = m_doc.GetElement( new ElementId( elementId ) ); Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; options.View = m_targetView; GeometryElement geomElem = e.get_Geometry( options ); foreach( GeometryObject geomObj in geomElem ) { if( geomObj is Solid ) { WriteSolid( (Solid) geomObj ); } else if( geomObj is GeometryInstance ) { TraverseGeometryInstance( (GeometryInstance) geomObj ); } else { m_writer.WriteLine( "Something else - " + geomObj.GetType().Name ); } } foreach( Curve curve in m_referencePlaneReferences ) { // Try to get the geometry object from reference Reference curveReference = curve.Reference; GeometryObject geomObj = e.GetGeometryObjectFromReference( curveReference ); if( geomObj != null ) { m_writer.WriteLine( "Curve reference leads to: " + geomObj.GetType().Name ); } } // Dimension to reference curves foreach( Curve curve in m_referencePlaneReferences ) { DetailCurve targetLine = m_vLine; Line line = (Line) curve; XYZ lineStartPoint = line.GetEndPoint( 0 ); XYZ lineEndPoint = line.GetEndPoint( 1 ); XYZ direction = lineEndPoint - lineStartPoint; Line dimensionLine = null; if( Math.Abs( direction.Y ) < 0.0001 ) { targetLine = m_hLine; XYZ dimensionLineStart = new XYZ( lineStartPoint.X + 5, lineStartPoint.Y, 0 ); XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X, dimensionLineStart.Y + 10, 0 ); dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd ); } else { targetLine = m_vLine; XYZ dimensionLineStart = new XYZ( lineStartPoint.X, lineStartPoint.Y + 5, 0 ); XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X + 10, dimensionLineStart.Y, 0 ); dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd ); } ReferenceArray references = new ReferenceArray(); references.Append( curve.Reference ); references.Append( targetLine.GeometryCurve.Reference ); Transaction t = new Transaction( m_doc, "Create dimension" ); t.Start(); m_doc.Create.NewDimension( m_targetView, dimensionLine, references ); t.Commit(); } }
/// <summary> /// Generates path of travels from room corner points to the corresponding list of end points. /// </summary> /// <param name="doc"></param> /// <param name="viewPlan"></param> /// <param name="rooms"></param> /// <param name="endPoints"></param> /// <param name="resultsSummary"></param> /// <param name="mapAllStartsToAllEnds"></param> private static void GeneratePathsOfTravelForRoomsToEndpointsManyToMany(Document doc, ViewPlan viewPlan, List <Room> rooms, List <XYZ> endPoints, ResultsSummary resultsSummary, bool mapAllStartsToAllEnds) { List <XYZ> allSourcePoints = new List <XYZ>(); foreach (Room room in rooms) { AppendRoomNearCornerPoints(room, allSourcePoints); } // foreach (Room room in rooms) // { // LocationPoint location = room.Location as LocationPoint; // if (location == null) // continue; // XYZ roomPoint = location.Point; // allSourcePoints.Add(roomPoint); // } resultsSummary.numSourcePoints += allSourcePoints.Count; List <XYZ> inputStartPoints = null; List <XYZ> inputEndPoints = null; // generate full lists of start and end points mapped to one another. // This is for testing purposes, the API option to do this mapping is likely more efficient for this case. if (mapAllStartsToAllEnds) { List <XYZ> allSourcePointsMappedToEnds = new List <XYZ>(); List <XYZ> allEndPointsMappedToEnds = new List <XYZ>(); foreach (XYZ source in allSourcePoints) { foreach (XYZ end in endPoints) { allSourcePointsMappedToEnds.Add(source); allEndPointsMappedToEnds.Add(end); } } inputStartPoints = allSourcePointsMappedToEnds; inputEndPoints = allEndPointsMappedToEnds; } else { inputStartPoints = allSourcePoints; inputEndPoints = endPoints; } GeneratePathsOfTravel(doc, viewPlan, inputStartPoints, inputEndPoints, resultsSummary, !mapAllStartsToAllEnds); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument UIdoc = commandData.Application.ActiveUIDocument; Document doc = UIdoc.Document; String pluginName = "PlaceInteriorElevations"; this.application = commandData.Application.Application; Debug("user path" + doc.Application.CurrentUserAddinsLocation); Debug("user data path" + doc.Application.CurrentUsersAddinsDataFolderPath); Debug("all user path" + doc.Application.AllUsersAddinsLocation); pluginConfig = Utility.ReadConfig(); Debug("telem url" + pluginConfig.telemetryURL); String slackMessage = ">Started"; Utility.SendTelemetryData(doc, pluginConfig.telemetryURL, pluginName, slackMessage); List <ViewFamilyType> viewFamilyTypeList = GetViewFamilyTypeList(doc); List <Autodesk.Revit.DB.View> viewTemplateList = GetViewtemplate(doc); List <FilledRegionType> filledRegionList = GetFilledRegions(doc); List <Element> lineStyleList = GetLineStyles(doc); DialogPlaceIntElevations ieDialog = new DialogPlaceIntElevations(this.application, viewFamilyTypeList, viewTemplateList, filledRegionList, lineStyleList); Boolean?dialogResult = ieDialog.ShowDialog(); int numRooms = 0; if (dialogResult == true) { try { List <Room> allRooms = new FilteredElementCollector(doc) .OfClass(typeof(SpatialElement)) .Select(e => e as Room) .Where(e => e != null) .ToList(); numRooms = allRooms.Count; List <ViewPlan> intElevPlans = DocumentElevPlanViews(doc); foreach (Room r in allRooms) { XYZ roomCenter = Utility.GetCenter(r); if (roomCenter == null) { continue; } ViewPlan intElevPlanOfRoom = GetViewPlanOfRoom(doc, intElevPlans, r); if (intElevPlanOfRoom == null) { continue; } using (Transaction tx = new Transaction(doc)) { tx.Start("Place Elevations"); int viewScale = ieDialog.SelectedScale; ElevationMarker marker; List <ViewSection> placedIntElev = PlaceElevations(doc, roomCenter, intElevPlanOfRoom, ieDialog.SelectedViewFamilyType, viewScale, out marker); Double angle = AngletoRotateElev(r); RotateMarker(marker, angle, roomCenter); foreach (ViewSection ie in placedIntElev) { AssignViewTemplate(ieDialog.SelectedViewTemplate, ie); SetCropBox(ie, r, roomCenter); try { CreateFilledRegion(doc, ie, ieDialog.SelectedFilledRegion, ieDialog.SelectedLineStyle); } catch (Exception e) { Debug("failed to create filled region " + e.ToString()); } RenameElevation(doc, ie, r); } tx.Commit(); } } } catch (Exception ex) { message = ex.ToString(); return(Result.Failed); } } else { return(Result.Cancelled); } //calculated 8 minutes saved per room automating elevations int timeSavedPerRoom = 8; int ROI = timeSavedPerRoom * numRooms; string ROIString; ROIString = string.Format("{0:0.00} hours", ROI / 60f); String slackMessage2 = $">Completed\n>Rooms in Project: {numRooms} rooms\n>ROI for run: {ROI} minutes ({ROIString}) saved\nData\t{numRooms}\t{ROI}"; Utility.SendTelemetryData(doc, pluginConfig.telemetryURL, pluginName, slackMessage2); return(Result.Succeeded); }
private void Stream( ArrayList data, ViewPlan view ) { data.Add( new Snoop.Data.ClassSeparator( typeof( ViewPlan ) ) ); Utils.StreamWithReflection( data, typeof( ViewPlan ), view ); // nothing at this level yet }
private ICollection <ElementId> GetDependenViewsID(ViewPlan floorPlan) { return(floorPlan.GetDependentViewIds()); }
private void AddNewViewSheets(int id) { if (uidoc.Document != null) { if (requestData != null) { Level firstLevel = getFirstLevel(uidoc.Document); if (firstLevel != null) { for (int i = 0; i < requestData.viewSheetsInfo.Count; i++) { Tuple <string, string, string, string, string> curViewSheetInfo = requestData.viewSheetsInfo[i]; ElementId titleBlocktId = GetTitleBlockIdByName(curViewSheetInfo.Item5); if (titleBlocktId == null) { titleBlocktId = new ElementId(-1); } ViewSheet norViewSheet = ViewSheet.Create(uidoc.Document, titleBlocktId); norViewSheet.SheetNumber = curViewSheetInfo.Item1; norViewSheet.Name = curViewSheetInfo.Item2; List <Element> allNonViewElements = getAllNonViewElementsOfDoc(); View norSheetViewPlan = null; ViewFamilyType viewFamilyType = null; FilteredElementCollector collector = new FilteredElementCollector(uidoc.Document); var viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in viewFamilyTypes) { ViewFamilyType v = e as ViewFamilyType; if (v.ViewFamily == ViewFamily.FloorPlan) { viewFamilyType = v; break; } } int curMainScale = GetScaleFromString(curViewSheetInfo.Item3); if ((viewFamilyType != null) && (firstLevel != null)) { norSheetViewPlan = ViewPlan.Create(uidoc.Document, viewFamilyType.Id, firstLevel.Id); norSheetViewPlan.Name = norViewSheet.Name + "_" + norViewSheet.SheetNumber; } if (norSheetViewPlan != null) { View viewTemplate = GetViewByName(curViewSheetInfo.Item4); if (viewTemplate != null) { List <ElementId> hiddenElemsIds = new List <ElementId>(); foreach (Element curHidVisElem in allNonViewElements) { if (curHidVisElem.IsHidden(viewTemplate)) { hiddenElemsIds.Add(curHidVisElem.Id); } } try { norSheetViewPlan.HideElements(hiddenElemsIds); } catch (Exception ex) { } } try { SetViewForSheet(norSheetViewPlan, norViewSheet, curMainScale); } catch (Exception ex) { TaskDialog.Show("Info", "Exception:" + ex.ToString()); } } } uidoc.Document.Regenerate(); uidoc.RefreshActiveView(); } else { TaskDialog.Show("Info", "firstLevel is null"); } } else { TaskDialog.Show("Info", "requestData is null"); } } else { TaskDialog.Show("Info", "doc is null"); } }
public WallsMPWRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Collect all the levels FilteredElementCollector levelsCollector = new FilteredElementCollector(doc); ICollection <Element> existingLevels = levelsCollector.OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements(); //Collect the wall types FilteredElementCollector wallTypesCollector = new FilteredElementCollector(doc); ICollection <Element> existingWallTypes = wallTypesCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().ToElements(); List <Line> wallLines = new List <Line>(); List <Wall> newWalls = new List <Wall>(); List <Element> selectedElements = new List <Element>(); //Get the wall type name from the MainUI combobox string selectedWallTypeName = uiForm.wallsMPWComboBoxWall.Text.ToString(); WallType wallTypeInput = null; double wallHeightInput = 0; //Ensure the active view is a plan view if (doc.ActiveView.GetType().ToString() != "Autodesk.Revit.DB.ViewPlan") { MessageBox.Show("Please run from a plan view"); } else { try { //Get the height of the walls to create from the MainUI, converted to a Double value in decimal feet wallHeightInput = (Convert.ToDouble(uiForm.wallsMPWNumericUpDownWallHeightFt.Value + (uiForm.wallsMPWNumericUpDownWallHeightIn.Value / 12))); } catch { //If the wall height input is invalid, let the user know throw new System.ArgumentException("Invalid wall height"); } double offsetDistance = 0; try { //To get the distance to offset the wall, get the wall type's thickness, then divide it in half because walls are placed along the centerline foreach (WallType wallType in existingWallTypes) { if (wallType.Name == selectedWallTypeName) { wallTypeInput = wallType; offsetDistance = (wallTypeInput.Width) / 2; break; } } } catch { new System.ArgumentException("No wall type was selected"); } //Get the active view and its associated level ViewPlan activeView = doc.ActiveView as ViewPlan; Level levelInput = activeView.GenLevel; //If the user selected a wall type, the level was obtained from the view, and the wall height is valid, continue if (wallTypeInput != null && levelInput != null && wallHeightInput != 0) { //Invoke selection of the rooms and get them from either the rooms or room tags selected List <Room> selectedRoomElements = RVTOperations.SelectRoomElements(uiApp); //Cycle through the room elements foreach (Room roomElem in selectedRoomElements) { try { //Get the location of the room as a point Location roomLocation = roomElem.Location; LocationPoint rlp = roomLocation as LocationPoint; //Get the room geometry Options geomOptions = new Options(); geomOptions.IncludeNonVisibleObjects = true; GeometryElement geomElements = roomElem.get_Geometry(geomOptions); foreach (GeometryObject geomObject in geomElements) { if (geomObject.GetType().ToString() == "Autodesk.Revit.DB.Solid") { //Grab the solid form of the room geometry Solid roomSolid = geomObject as Solid; FaceArray roomSolidFaces = roomSolid.Faces; foreach (PlanarFace roomSolidFace in roomSolidFaces) { //Get the bottom face of the room which is the face that has a -Z vector XYZ faceNormal = roomSolidFace.FaceNormal; if (faceNormal.Z == -1) { //Get the CurveLoops for the bottom face IList <CurveLoop> faceCurveLoops = roomSolidFace.GetEdgesAsCurveLoops(); foreach (CurveLoop curveLoop in faceCurveLoops) { //Offset the CurveLoop by the half thickness of the wall CurveLoop offsetCurveLoops = CurveLoop.CreateViaOffset(curveLoop, offsetDistance, XYZ.BasisZ); foreach (Line line in offsetCurveLoops) { //Collect the lines to draw walls along wallLines.Add(line); } } } } } } } catch { continue; } } //Start a transaction using (Transaction t1 = new Transaction(doc, "MakeWalls")) { t1.Start(); foreach (Line wallLine in wallLines) { //Draw a line along each of the lines and add them to a list of walls created Wall newWall = Wall.Create(doc, wallLine, wallTypeInput.Id, levelInput.Id, wallHeightInput, 0, true, false); newWalls.Add(newWall); } t1.Commit(); } //Start a new transaction to join the walls to adjacent walls using (Transaction t2 = new Transaction(doc, "JoinWalls")) { t2.Start(); foreach (Wall newWall in newWalls) { //Collect the walls in the project FilteredElementCollector existingWallsCollector = new FilteredElementCollector(doc, doc.ActiveView.Id); existingWallsCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements(); //Get the bounding box of each wall BoundingBoxXYZ wallBBox = newWall.get_BoundingBox(doc.ActiveView); //Get the outline of the bounding box using the minimum and maximum points Outline wallBBoxOutline = new Outline(wallBBox.Min, wallBBox.Max); //Generate a new BoundingBoxIntersectsFilter to find the other bounding boxes that intersect the outline BoundingBoxIntersectsFilter bBoxFilter = new BoundingBoxIntersectsFilter(wallBBoxOutline); //Get all walls that pass the filter (they intersect the evaluated new wall's outline) existingWallsCollector.WherePasses(bBoxFilter); foreach (Wall existingWall in existingWallsCollector) { try { //Try to joing the new wall to the existing walls so they are cut by the hosted elements JoinGeometryUtils.JoinGeometry(doc, newWall, existingWall); } catch { continue; } } } t2.Commit(); } } else if (levelInput == null) { //Let the user know if the level could not be obtained MessageBox.Show("No level set"); } else if (wallTypeInput == null) { //Let the user know if they didn't select a wall type MessageBox.Show("No wall type set"); } else if (wallHeightInput <= 0) { //Let the user know if they specified a 0 or negative wall height MessageBox.Show("Wall height must be set to greater than 0'"); } else { //If for some reason the script fails, report that one of the following settings could not be used. This is highly unlikely though MessageBox.Show(String.Format("One of the following settings could not be used: Wall Type = '{0}'; " + "Level = '{1}'; " + "Wall Height = '{2}'", ((Wall)doc.GetElement(wallTypeInput.Id)).WallType.Name.ToString(), ((Level)doc.GetElement(levelInput.Id)).Name.ToString(), (wallHeightInput / 12d).ToString())); } } }
private void WriteElementGeometry(int elementId) { FilteredElementCollector viewCollector = new FilteredElementCollector(m_doc); viewCollector.OfClass(typeof(ViewPlan)); Func <ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan; m_targetView = viewCollector.Cast <ViewPlan>().First <ViewPlan>(isLevel1FloorPlan); Transaction createCurve = new Transaction(m_doc, "Create reference curves"); createCurve.Start(); const double xReferenceLocation = 30; Line vLine = Line.CreateBound(new XYZ(xReferenceLocation, 0, 0), new XYZ(xReferenceLocation, 20, 0)); m_vLine = m_doc.Create.NewDetailCurve(m_targetView, vLine); const double yReferenceLocation = -10; Line hLine = Line.CreateBound(new XYZ(0, yReferenceLocation, 0), new XYZ(20, yReferenceLocation, 0)); m_hLine = m_doc.Create.NewDetailCurve(m_targetView, hLine); createCurve.Commit(); Element e = m_doc.GetElement(new ElementId(elementId)); Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; options.View = m_targetView; GeometryElement geomElem = e.get_Geometry(options); foreach (GeometryObject geomObj in geomElem) { if (geomObj is Solid) { WriteSolid((Solid)geomObj); } else if (geomObj is GeometryInstance) { TraverseGeometryInstance((GeometryInstance)geomObj); } else { m_writer.WriteLine("Something else - " + geomObj.GetType().Name); } } foreach (Curve curve in m_referencePlaneReferences) { // Try to get the geometry object from reference Reference curveReference = curve.Reference; GeometryObject geomObj = e.GetGeometryObjectFromReference(curveReference); if (geomObj != null) { m_writer.WriteLine("Curve reference leads to: " + geomObj.GetType().Name); } } // Dimension to reference curves foreach (Curve curve in m_referencePlaneReferences) { DetailCurve targetLine = m_vLine; Line line = (Line)curve; XYZ lineStartPoint = line.GetEndPoint(0); XYZ lineEndPoint = line.GetEndPoint(1); XYZ direction = lineEndPoint - lineStartPoint; Line dimensionLine = null; if (Math.Abs(direction.Y) < 0.0001) { targetLine = m_hLine; XYZ dimensionLineStart = new XYZ(lineStartPoint.X + 5, lineStartPoint.Y, 0); XYZ dimensionLineEnd = new XYZ(dimensionLineStart.X, dimensionLineStart.Y + 10, 0); dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd); } else { targetLine = m_vLine; XYZ dimensionLineStart = new XYZ(lineStartPoint.X, lineStartPoint.Y + 5, 0); XYZ dimensionLineEnd = new XYZ(dimensionLineStart.X + 10, dimensionLineStart.Y, 0); dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd); } ReferenceArray references = new ReferenceArray(); references.Append(curve.Reference); references.Append(targetLine.GeometryCurve.Reference); Transaction t = new Transaction(m_doc, "Create dimension"); t.Start(); m_doc.Create.NewDimension(m_targetView, dimensionLine, references); t.Commit(); } }
private static ViewBox getPlanViewBox(ViewPlan vp) { System.Diagnostics.Debug.WriteLine("ViewPlan: " + vp.Id + " Outline: " + vp.Outline.Min.U + "," + vp.Outline.Min.V + " to " + vp.Outline.Max.U + "," + vp.Outline.Max.V); System.Diagnostics.Debug.WriteLine("ViewPlan Scale: " + vp.Scale); XYZ tmp1 = vp.Origin.Add(new XYZ(vp.Outline.Min.U * (double)vp.Scale, vp.Outline.Min.V * (double)vp.Scale, 0)); XYZ tmp2 = vp.Origin.Add(new XYZ(vp.Outline.Max.U * (double)vp.Scale, vp.Outline.Max.V * (double)vp.Scale, 0)); // double check the cropbox, if it is smaller... if (vp.CropBoxActive) { tmp1 = vp.CropBox.Min; tmp2 = vp.CropBox.Max; } // in a plan view, we will work with the cropbox (if it is set?) ViewBox box = new ViewBox() { P1 = tmp1, P2 = tmp2 }; // now reset by the level and the viewdepth if (vp.GenLevel != null) { PlanViewRange pvr = vp.GetViewRange(); ElementId topId = pvr.GetLevelId(PlanViewPlane.TopClipPlane); ElementId bottomId = pvr.GetLevelId(PlanViewPlane.ViewDepthPlane); if (bottomId.IntegerValue == -4) bottomId = pvr.GetLevelId(PlanViewPlane.BottomClipPlane); if (bottomId.IntegerValue == -4) bottomId = pvr.GetLevelId(PlanViewPlane.UnderlayBottom); if (topId != ElementId.InvalidElementId) { Level top = vp.Document.GetElement(topId) as Level; box.P2 = new XYZ(box.P2.X, box.P2.Y, top.Elevation + pvr.GetOffset( PlanViewPlane.TopClipPlane ) ); } if (bottomId != ElementId.InvalidElementId) { Level bottom = vp.Document.GetElement(bottomId) as Level; box.P1 = new XYZ(box.P1.X, box.P1.Y, bottom.Elevation + pvr.GetOffset(PlanViewPlane.ViewDepthPlane)); } } // set the transform box.TransformationMatrix = Transform.Identity; box.DirectionUp = vp.UpDirection; box.EyePosition = vp.Origin.Add(vp.ViewDirection.Multiply(10)); box.DirectionView = vp.ViewDirection.Negate(); return box; }