/// <summary> /// Get saved addresses in Storage. Currently only one address is supported /// </summary> /// <param name="document">The document storing the saved address.</param> /// <param name="schema">The schema for address.</param> /// <returns>List of stored addresses</returns> private IList<DataStorage> GetAddressInStorage(Document document, Schema schema) { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(DataStorage)); Func<DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid()); return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>(); }
/// <summary> /// Gets the saved setups from the document. /// </summary> /// <returns>The saved configurations.</returns> private IList <DataStorage> GetSavedConfigurations(Schema schema) { FilteredElementCollector collector = new FilteredElementCollector(IFCCommandOverrideApplication.TheDocument); collector.OfClass(typeof(DataStorage)); Func <DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid()); return(collector.Cast <DataStorage>().Where <DataStorage>(hasTargetData).ToList <DataStorage>()); }
/// <summary> /// Gets the saved setups from the document. /// </summary> /// <param name="document">The document storing the saved configuration.</param> /// <returns>The saved configurations.</returns> private IList <DataStorage> GetSavedConfigurations(Document document) { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(DataStorage)); Func <DataStorage, bool> hasTargetData = ds => ds.GetEntity(m_schema) != null; return(collector.Cast <DataStorage>().Where <DataStorage>(hasTargetData).ToList <DataStorage>()); }
private static IList <DataStorage> GetViewsStorage(Document document, Schema schema) { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(DataStorage)); Func <DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid()); return(collector.Cast <DataStorage>().Where <DataStorage>(hasTargetData).ToList <DataStorage>()); }
private void RenLinePatterns(Document pDoc, string pstrFind, string pstrReplace, bool pblnMatchCase) { //Category linesCat = pDoc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); FilteredElementCollector coll = new FilteredElementCollector(mDoc).OfClass(typeof(LinePatternElement)); IList <LinePatternElement> patternElement; using (Transaction tr = new Transaction(pDoc, "Rename Line Patterns")) { tr.Start(); if (pblnMatchCase) { patternElement = coll.Cast <LinePatternElement>().Where(c => c.Name.ToUpper().Contains(pstrFind.ToUpper())).ToList(); } else { patternElement = coll.Cast <LinePatternElement>().Where(c => c.Name.Contains(pstrFind)).ToList(); } foreach (LinePatternElement cat in patternElement) { ElementId eid = cat.Id as ElementId; Element type = pDoc.GetElement(eid); if (null != type) { type.Name = CommFun.Rename(cat.Name, pstrFind, pstrReplace); } } tr.Commit(); if (patternElement.Count > 0) { MessageBox.Show(patternElement.Count + " Line Patterns containing the word " + pstrFind + " have been succesfully renamed!"); } else { MessageBox.Show("Nome of the Line Patterns match with you find rules"); } } }
/// <summary> /// Checks if level has views. /// </summary> /// <param name="level"> /// The level. /// </param> /// <returns> /// True if the level has views generated, false otherwise. /// </returns> public static bool LevelHasViews(Level level) { if (level == null) return false; FilteredElementCollector viewCollector = new FilteredElementCollector(level.Document); viewCollector.OfClass(typeof(View)); Func<View, bool> viewIsNonTemplateAndGeneratedByLevel = view => !view.IsTemplate && IsViewGeneratedByLevel(view, level); return viewCollector.Cast<View>().FirstOrDefault<View>(viewIsNonTemplateAndGeneratedByLevel) != null; }
View CreateDrafting(Document doc) { FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(ViewFamilyType)); ViewFamilyType viewFamilyType = collector.Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting); ViewDrafting drafting = ViewDrafting.Create(doc, viewFamilyType.Id); return(drafting as View); }
///////////////////////////////////////////////////////////////////////////////////////////////// ////// Custom seeking container for any object. Uses FilteredElementCollector ////////// public IEnumerable <T> GetElements <T>(Document document) where T : Element { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(T)); return(collector.Cast <T>()); // In code ex: <T> name = GetElements<T>(doc) // .Where (i => i.Name == "whatever"); }
public static ViewDrafting viewDraftingCreate(Document doc, string viewName) { FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)); ViewFamilyType viewFamilyType = collector.Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting); ViewDrafting view = ViewDrafting.Create(doc, viewFamilyType.Id); view.ViewName = viewName; return(view); }
internal static ElementId GetViewTypeIdByViewType(Document doc, ViewFamily viewFamily, string typeName) { ElementId elementId; using (FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType))) { elementId = fec.Cast <ViewFamilyType>().Where(x => x.ViewFamily == viewFamily && x.Name == typeName).FirstOrDefault().Id; } return(elementId); }
/// <summary> /// Gets the saved setups from the document. /// </summary> /// <returns>The saved configurations.</returns> private IList <DataStorage> GetProjectConfigurations(Schema schema) { FilteredElementCollector collector = new FilteredElementCollector(UIDoc?.Document); collector.OfClass(typeof(DataStorage)); // ReSharper disable once ConvertToLocalFunction Func <DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid()); return(collector.Cast <DataStorage>().Where(hasTargetData).ToList()); }
/// <summary> /// Return the first 3D view which is not a template, /// useful for input to FindReferencesByDirection(). /// In this case, one cannot use FirstElement() directly, /// since the first one found may be a template and /// unsuitable for use in this method. /// This demonstrates some interesting usage of /// a .NET anonymous method. /// </summary> public static Element GetFirstNonTemplate3dView(Document doc) { FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(View3D)); return(collector .Cast <View3D>() .First <View3D>(v3 => !v3.IsTemplate)); }
/// <summary> /// get all the hook types in current project, and store in m_hookTypes data /// </summary> /// <param name="commandData">the ExternalCommandData reference</param> /// <returns>true if some hook types can be gotton, otherwise false</returns> private bool GetHookTypes(ExternalCommandData commandData) { // Initialize the m_hookTypes which used to store all hook types. FilteredElementCollector filteredElementCollector = new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document); filteredElementCollector.OfClass(typeof(RebarHookType)); m_hookTypes = filteredElementCollector.Cast <RebarHookType>().ToList <RebarHookType>(); // If no hook types in revit return false, otherwise true return((0 == m_hookTypes.Count) ? false : true); }
/// <summary> /// Draw detail curves based on List<Curve> /// </summary> public static void DrawDetailLines(Document doc, List <Curve> crvs, int weight = 2, string color = "red", string pattern = "") { GetListOfLinestyles(doc); View view = doc.ActiveView; Color palette = new Color(0, 0, 0); switch (color) { case "red": palette = new Color(200, 50, 80); break; case "blue": palette = new Color(100, 149, 237); break; case "orange": palette = new Color(255, 140, 0); break; } FilteredElementCollector fec = new FilteredElementCollector(doc) .OfClass(typeof(LinePatternElement)); LinePatternElement linePatternElem = null; if (pattern != "") { try { linePatternElem = fec .Cast <LinePatternElement>() .First <LinePatternElement>(linePattern => linePattern.Name == pattern); } catch { Debug.Print("There's no matching pattern in the document"); } } using (Transaction tx = new Transaction(doc)) { tx.Start("Create Detail Curves"); foreach (Curve crv in crvs) { // Should do style setting here or...? DetailCurve detailCrv = doc.Create.NewDetailCurve(view, crv); GraphicsStyle gs = detailCrv.LineStyle as GraphicsStyle; gs.GraphicsStyleCategory.LineColor = palette; gs.GraphicsStyleCategory.SetLineWeight(weight, gs.GraphicsStyleType); if (linePatternElem != null) { gs.GraphicsStyleCategory.SetLinePatternId(linePatternElem.Id, GraphicsStyleType.Projection); } } tx.Commit(); } }
/// <summary> /// Create a new line style using NewSubcategory /// </summary> void CreateLineStyle(Document doc) { // Use this to access the current document in a macro. // //Document doc = this.ActiveUIDocument.Document; // Find existing linestyle. Can also opt to // create one with LinePatternElement.Create() FilteredElementCollector fec = new FilteredElementCollector( doc ) .OfClass( typeof( LinePatternElement ) ); LinePatternElement linePatternElem = fec .Cast<LinePatternElement>() .First<LinePatternElement>( linePattern => linePattern.Name == "Long dash" ); // The new linestyle will be a subcategory // of the Lines category Categories categories = doc.Settings.Categories; Category lineCat = categories.get_Item( BuiltInCategory.OST_Lines ); using( Transaction t = new Transaction( doc ) ) { t.Start( "Create LineStyle" ); // Add the new linestyle Category newLineStyleCat = categories .NewSubcategory( lineCat, "New LineStyle" ); doc.Regenerate(); // Set the linestyle properties // (weight, color, pattern). newLineStyleCat.SetLineWeight( 8, GraphicsStyleType.Projection ); newLineStyleCat.LineColor = new Color( 0xFF, 0x00, 0x00 ); newLineStyleCat.SetLinePatternId( linePatternElem.Id, GraphicsStyleType.Projection ); t.Commit(); } }
internal static IList <ElementType> ViewportTypes(Document doc) { FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId((int)BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM), "Viewport", false); ElementParameterFilter filter = new ElementParameterFilter(rule); IList <ElementType> viewportTypes; using (FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(ElementType)).WherePasses(filter)) { viewportTypes = fec.Cast <ElementType>().ToList(); } return(viewportTypes); }
/// <summary> /// Create a new line style using NewSubcategory /// </summary> void CreateLineStyle(Document doc) { // Use this to access the current document in a macro. // //Document doc = this.ActiveUIDocument.Document; // Find existing linestyle. Can also opt to // create one with LinePatternElement.Create() FilteredElementCollector fec = new FilteredElementCollector(doc) .OfClass(typeof(LinePatternElement)); LinePatternElement linePatternElem = fec .Cast <LinePatternElement>() .First <LinePatternElement>(linePattern => linePattern.Name == "Long Dash"); // The new linestyle will be a subcategory // of the Lines category Categories categories = doc.Settings.Categories; Category lineCat = categories.get_Item( BuiltInCategory.OST_Lines); using (Transaction t = new Transaction(doc)) { t.Start("Create LineStyle"); // Add the new linestyle Category newLineStyleCat = categories .NewSubcategory(lineCat, "New LineStyle"); doc.Regenerate(); // Set the linestyle properties // (weight, color, pattern). newLineStyleCat.SetLineWeight(8, GraphicsStyleType.Projection); newLineStyleCat.LineColor = new Color( 0xFF, 0x00, 0x00); newLineStyleCat.SetLinePatternId( linePatternElem.Id, GraphicsStyleType.Projection); t.Commit(); } }
public IEnumerable <T> GetElements <T>(BuiltInCategory builtInCategory) where T : Element { FilteredElementCollector collector = new FilteredElementCollector(doc); // Seems you must be a subclass of element to use the OfClass method if (typeof(T) != typeof(Element)) { collector.OfClass(typeof(T)); } collector.OfCategory(builtInCategory); return(collector.Cast <T>()); }
public static DuctType[] GetDuctTypes(Document doc, DuctShapeEnum shape) { FilteredElementCollector coll = new FilteredElementCollector(doc); coll.OfClass(typeof(DuctType)); IEnumerable <DuctType> pts = coll.Cast <DuctType>(); if ((pts == null) || (pts.Count <DuctType>() == 0)) { return(null); } List <string> familyNames = new List <string>(); switch (shape) { case DuctShapeEnum.Round: familyNames.Add("Round Duct"); familyNames.Add("Gaine circulaire"); break; case DuctShapeEnum.Rectangular: familyNames.Add("Rectangular Duct"); familyNames.Add("Gaine rectangulaire"); break; case DuctShapeEnum.Oval: familyNames.Add("Oval Duct"); familyNames.Add("Gaine ovale"); break; } List <DuctType> types = new List <DuctType>(); foreach (DuctType dt in pts) { Parameter p = dt.get_Parameter(BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM); foreach (string familyName in familyNames) { if (p.AsString().ToUpper() == familyName.ToUpper()) { types.Add(dt); } } } if (types.Count == 0) { return(null); } return(types.ToArray()); }
private ViewDrafting CreateNewDraftingView() { var drfViews = new FilteredElementCollector(CurrentDocument) .OfClass(typeof(ViewFamilyType)); var dvId = drfViews .Cast <ViewFamilyType>() .FirstOrDefault(v => v.ViewFamily == ViewFamily.Drafting).Id; var newView = ViewDrafting.Create(CurrentDocument, dvId); return(newView); }
public void ShowMaterialInfo(Document doc) { // Find material FilteredElementCollector fec = new FilteredElementCollector(doc); fec.OfClass(typeof(Material)); String materialName = "Checker"; // "Copper";//"Prism - Glass - Textured"; // "Parking Stripe"; // "Copper"; // "Carpet (1)";// "Prism - Glass - Textured";// "Parking Stripe"; // "Prism 1";// "Brick, Common" ;// "Acoustic Ceiling Tile 24 x 48"; // "Aluminum" Material mat = fec.Cast <Material>().First <Material>(m => m.Name == materialName); ElementId appearanceAssetId = mat.AppearanceAssetId; AppearanceAssetElement appearanceAsset = doc.GetElement(appearanceAssetId) as AppearanceAssetElement; Asset renderingAsset = appearanceAsset.GetRenderingAsset(); RenderAppearanceDescriptor rad = new RenderAppearanceDescriptor(renderingAsset); PropertyDescriptorCollection collection = rad.GetProperties(); TaskDialog.Show("Total properties", "Properties found: " + collection.Count); string s = ": Material Asset Properties"; TaskDialog dlg = new TaskDialog(s); dlg.MainInstruction = mat.Name + s; s = string.Empty; List <PropertyDescriptor> orderableCollection = new List <PropertyDescriptor>(collection.Count); foreach (PropertyDescriptor descr in collection) { orderableCollection.Add(descr); } foreach (AssetPropertyPropertyDescriptor descr in orderableCollection.OrderBy <PropertyDescriptor, String>(pd => pd.Name).Cast <AssetPropertyPropertyDescriptor>()) { object value = descr.GetValue(rad); s += "\nname: " + descr.Name + " | type: " + descr.PropertyType.Name + " | value: " + value; } dlg.MainContent = s; dlg.Show(); }
/// <summary> /// Initialize the data member /// </summary> private void Initialize() { Document doc = m_commandData.Application.ActiveUIDocument.Document; FilteredElementIterator iter = (new FilteredElementCollector(doc)).OfClass(typeof(Level)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { m_levels.Add(iter.Current as Level); } FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc); filteredElementCollector.OfClass(typeof(RoofType)); m_roofTypes = filteredElementCollector.Cast <RoofType>().ToList <RoofType>(); // FootPrint Roofs m_footPrintRoofs = new ElementSet(); iter = (new FilteredElementCollector(doc)).OfClass(typeof(FootPrintRoof)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { m_footPrintRoofs.Insert(iter.Current as FootPrintRoof); } // Extrusion Roofs m_extrusionRoofs = new ElementSet(); iter = (new FilteredElementCollector(doc)).OfClass(typeof(ExtrusionRoof)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { m_extrusionRoofs.Insert(iter.Current as ExtrusionRoof); } // Reference Planes iter = (new FilteredElementCollector(doc)).OfClass(typeof(ReferencePlane)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { ReferencePlane plane = iter.Current as ReferencePlane; // just use the vertical plane if (Math.Abs(plane.Normal.DotProduct(Autodesk.Revit.DB.XYZ.BasisZ)) < 1.0e-09) { if (plane.Name == "Reference Plane") { plane.Name = "Reference Plane" + "(" + plane.Id.IntegerValue.ToString() + ")"; } m_referencePlanes.Add(plane); } } }
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; // cleaning element selection set Selection sel = uidoc.Selection; List <ElementId> emptyElementSet = new List <ElementId>() { }; sel.SetElementIds(emptyElementSet); // collecting view sheets List <ViewSheet> viewSheets = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Sheets) .ToElements() .Cast <ViewSheet>() .ToList(); List <string> viewSheetsNames = (from viewSheet in viewSheets select viewSheet.Title).ToList(); Dictionary <string, ViewSheet> viewSheetsDic = viewSheetsNames .Zip(viewSheets, (vsn, vs) => new { vsn, vs }) .ToDictionary(item => item.vsn, item => item.vs); // opening a select from list form SelectFromList selectFromList = new SelectFromList(viewSheets.Cast <Element>().ToList()); selectFromList.ShowDialog(); // if cancelled if (selectFromList.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(Result.Cancelled); } // getting the sheet views selected List <ViewSheet> selectedViewSheets = new List <ViewSheet>(); ExportToDwg exportToDwg = new ExportToDwg(doc, selectFromList.GetChoosedElements() .Cast <ViewSheet>() .ToList()); exportToDwg.Export(); return(Result.Succeeded); }
/// <summary> /// Constructor, initialize fields of RebarBarTypes and RebarShapes. /// </summary> /// <param name="rvtApp"></param> public NewRebarForm(Autodesk.Revit.DB.Document rvtDoc) : this() { m_rvtDoc = rvtDoc; FilteredElementCollector filteredElementCollector = new FilteredElementCollector(m_rvtDoc); filteredElementCollector.OfClass(typeof(RebarBarType)); m_rebarBarTypes = filteredElementCollector.Cast <RebarBarType>().ToList <RebarBarType>(); filteredElementCollector = new FilteredElementCollector(m_rvtDoc); filteredElementCollector.OfClass(typeof(RebarShape)); m_rebarShapes = filteredElementCollector.Cast <RebarShape>().ToList <RebarShape>(); }
/// <summary> /// MatchGrids main window /// </summary> /// <param name="commandData"></param> public MatchGridsWPF(ExternalCommandData commandData) { Document doc = commandData.Application.ActiveUIDocument.Document; InitializeComponent(); DataContext = this; CbItems = new ObservableCollection <ComboBoxItem>(); FilteredElementCollector viewsCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views); List <View> filteredV = viewsCollector.Cast <View>() .Where(sh => sh.ViewType == ViewType.AreaPlan || sh.ViewType == ViewType.CeilingPlan || sh.ViewType == ViewType.Elevation || sh.ViewType == ViewType.FloorPlan || sh.ViewType == ViewType.Section || sh.ViewType == ViewType.ThreeD) .Where(view => !view.IsTemplate) .ToList(); IOrderedEnumerable <View> views = filteredV.OrderBy(v => v.ViewType).ThenBy(v => v.Name); FilteredViewsCheckBox = filteredV; int count = 0; foreach (var v in views) { ComboBoxItem comb = new ComboBoxItem(); comb.Content = v.ViewType + " - " + v.Name; comb.Tag = v; CbItems.Add(comb); if (count == 0) { SelectedComboItem = comb; } count++; } // Associate the event-handling method with the SelectedIndexChanged event this.comboDisplay.SelectionChanged += new SelectionChangedEventHandler(MyComboChanged); ViewCheckBoxes(doc); }
void DrawAll(Document doc) { foreach (string s in staticFamilies) { try { string file_path = File.ReadAllText("C://ProgramData//Autodesk//Revit//Addins//2019//Linear//settings.set"); file_path += "\\static\\" + s; loader.LoadFamilyIntoProject(file_path, doc); } catch { throw new Exception("Ошибка загрузки семейств чертежных примитивов из папки static."); } } FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)); foreach (ARKModule b in ARKBLocks) { try { FamilySymbol famToPlace = null; ViewFamilyType vt = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(vft => vft.ViewFamily == ViewFamily.Drafting); ElementId id = vt.Id; Transaction trans = new Transaction(doc); trans.Start("Отрисовка"); ViewDrafting vd = ViewDrafting.Create(doc, id); b.setVD(vd); ElementId viewId = vd.Id; drawingviews.Add(viewId); famToPlace = collector.Cast <FamilySymbol>().Where(x => x.Name == b.filename).First(); b.revitSymbol = famToPlace; b.revitModule = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), famToPlace, vd); arkmoduleIds.Add(b.revitModule.Id); trans.Commit(); } catch { throw new Exception("Ошибка добавления АРК-модулей на чертежные листы."); } } SetArkIndexes(doc); DrawLines(doc); foreach (ARKModule b in ARKBLocks) { try { b.createTable(doc, new XYZ(10, 3, 0)); } catch { throw new Exception("Ошибка создания таблицы элементов."); } } }
/// <summary> /// Get necessary data from revit.such as selected beams, wall types and level information /// </summary> /// <param name="project">A reference of current document</param> /// <returns>true if no error happens; otherwise, false.</returns> Boolean PrepareData(Autodesk.Revit.UI.UIDocument project) { // Search all the wall types in the Revit FilteredElementCollector filteredElementCollector = new FilteredElementCollector(project.Document); filteredElementCollector.OfClass(typeof(WallType)); m_wallTypeCollection = filteredElementCollector.Cast <WallType>().ToList <WallType>(); // Find the selection of beams in Revit ElementSet selection = new ElementSet(); foreach (ElementId elementId in project.Selection.GetElementIds()) { selection.Insert(project.Document.GetElement(elementId)); } AnalyticalModel model; // store the AnalyticalModel of the beam. foreach (Autodesk.Revit.DB.Element e in selection) { FamilyInstance m = e as FamilyInstance; // Use StructuralType property can judge whether it is a beam. if (null != m && StructuralType.Beam == m.StructuralType) { m_beamCollection.Add(e); // store the beams // Get the curve of beam's AnalyticalModel. model = m.GetAnalyticalModel(); if (null == model) { m_errorInformation = "The beam should have analytical model."; return(false); } m_analyticalLineCollection.Add(model.GetCurve()); } } if (0 == m_beamCollection.Count) { m_errorInformation = "Can not find any beams."; return(false); } // Get the level which will be used in create method FilteredElementCollector collector = new FilteredElementCollector(project.Document); m_level = collector.OfClass(typeof(Level)).FirstElement() as Level; return(true); }
/// <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); }
/// <summary> /// get all the beam types, truss types and all the view plans from the active document /// </summary> public void DataInitialize() { // get all the beam types GetBeamTypes(); // get all the truss types // there's no truss type in the active document FilteredElementCollector filteredElementCollector = new FilteredElementCollector(m_activeDocument.Document); filteredElementCollector.OfClass(typeof(FamilySymbol)); filteredElementCollector.OfCategory(BuiltInCategory.OST_Truss); IList <TrussType> trussTypes = filteredElementCollector.Cast <TrussType>().ToList <TrussType>(); if (null == trussTypes || 0 == trussTypes.Count) { TaskDialog.Show("Load Truss Type", "Please load at least one truss type into your project."); this.Close(); } foreach (TrussType trussType in trussTypes) { if (null == trussType) { continue; } String trussTypeName = trussType.get_Parameter (BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM).AsString(); this.TrussTypeComboBox.Items.Add(trussTypeName); m_trussTypes.Add(trussType); } // get all the views // Skip view templates because they're behind-the-scene and invisible in project browser; also invalid for API..., etc. m_views = from elem in new FilteredElementCollector(m_activeDocument.Document).OfClass(typeof(ViewPlan)).ToElements() let viewPlan = elem as ViewPlan where viewPlan != null && !viewPlan.IsTemplate select viewPlan; foreach (Autodesk.Revit.DB.View view in m_views) { this.ViewComboBox.Items.Add(view.Name); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { try { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document thisDoc = uidoc.Document; if (new RevitHelpers().NotInThisView(thisDoc)) { return(Result.Succeeded); } Selection sel = uidoc.Selection; Section2dPickFilter selFilter = new Section2dPickFilter(thisDoc); Reference pickedRef = sel.PickObject(ObjectType.Element, selFilter, "Pick the section to far clip adjust."); Element elem = thisDoc.GetElement(pickedRef); // sheesh, another crazy linq way to do this FilteredElementCollector viewCollector = new FilteredElementCollector(thisDoc); viewCollector.OfClass(typeof(Autodesk.Revit.DB.View)); Func <Autodesk.Revit.DB.View, bool> isNamedView = v2 => (v2.Name.Equals(elem.Name)); Autodesk.Revit.DB.View thisV = viewCollector.Cast <Autodesk.Revit.DB.View>().First <Autodesk.Revit.DB.View>(isNamedView); string fcs = Properties.Settings.Default.PreferFarClip.ToString(); using (Transaction t = new Transaction(thisDoc, "FarSide Change")) { t.Start(); Parameter vFarclip = thisV.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR); vFarclip.SetValueString(fcs); t.Commit(); } } catch (Exception ex) { // MessageBox.Show(ex.Message, "Sorry, No Can Do."); } return(Result.Succeeded); }
private BoundingBoxXYZ GetBoundingBoxOfLevel(IList <Level> strLevels, int highFloorLevelInd, View3D view) { Level highFloorLevel = strLevels[highFloorLevelInd]; Level lowFloorLevel = strLevels[highFloorLevelInd - 1]; // Get the outline of the entire 3D model FilteredElementCollector fec = new FilteredElementCollector(_doc).OfClass(typeof(Wall)); BoundingBoxXYZ ibb = fec.Cast <Wall>().First().get_BoundingBox(view); Outline outline = new Outline(ibb.Min, ibb.Max); foreach (Wall wall in fec) { BoundingBoxXYZ boxXYZ = wall.get_BoundingBox(view); outline.AddPoint(boxXYZ.Min); outline.AddPoint(boxXYZ.Max); } // Create a new BoundingBoxXYZ to define a 3D rectangular space BoundingBoxXYZ boundingBoxXYZ = new BoundingBoxXYZ(); if (highFloorLevelInd == 1) { // Set the lower left botton corner of the box // To show the fondation, use the Z of the current level - BOTTOMOFFSET boundingBoxXYZ.Min = new XYZ( outline.MinimumPoint.X - SECTION_BOX_XY_MARGIN, outline.MinimumPoint.Y - SECTION_BOX_XY_MARGIN, lowFloorLevel.ProjectElevation - BOTTOM_OFFSET); } else { // Use the Z of the current level. boundingBoxXYZ.Min = new XYZ( outline.MinimumPoint.X - SECTION_BOX_XY_MARGIN, outline.MinimumPoint.Y - SECTION_BOX_XY_MARGIN, lowFloorLevel.ProjectElevation); } boundingBoxXYZ.Max = new XYZ( outline.MaximumPoint.X + SECTION_BOX_XY_MARGIN, outline.MaximumPoint.Y + SECTION_BOX_XY_MARGIN, highFloorLevel.ProjectElevation); return(boundingBoxXYZ); }
/// <summary> /// Merge <paramref name="boundingBoxXyz"/> with the 'BoundingBoxXYZ's of /// all 'GenericForm's in <paramref name="document"/> that are solid into /// a new 'BoundingBoxXYZ'. /// Exclude all 'GenericForm's in /// <paramref name="genericFormExclusionSet"/> from being found in /// <paramref name="document"/>. /// </summary> /// <param name="document">The Revit 'Document' to search for all /// 'GenericForm's excluding the ones in /// <paramref name="genericFormExclusionSet"/>.</param> /// <param name="boundingBoxXyz">The 'BoundingBoxXYZ' to merge with.</param> /// <param name="genericFormExclusionSet">A 'HashSet' of all the /// 'GenericForm's to exclude from being merged with in /// <paramref name="document"/>.</param> /// <returns>The new merged 'BoundingBoxXYZ' of /// <paramref name="boundingBoxXyz"/> and all 'GenericForm's excluding /// the ones in <paramref name="genericFormExclusionSet"/> /// in <paramref name="document"/></returns> private static BoundingBoxXYZ MergeSolidBoundingBoxXyz( Document document, BoundingBoxXYZ boundingBoxXyz, ISet <ElementId> genericFormExclusionSet) { BoundingBoxXYZ mergedResult = boundingBoxXyz; FilteredElementCollector genericFormCollector = new FilteredElementCollector(document) .OfClass(typeof(GenericForm)); if (genericFormExclusionSet != null && genericFormExclusionSet.Any()) { genericFormCollector.Excluding( genericFormExclusionSet); } foreach (GenericForm solid in genericFormCollector .Cast <GenericForm>() .Where(genericForm => genericForm.IsSolid)) { BoundingBoxXYZ solidBoundingBox = solid.get_BoundingBox(null); if (solidBoundingBox == null) { continue; } if (mergedResult == null) { mergedResult = new BoundingBoxXYZ(); mergedResult.Min = solidBoundingBox.Min; mergedResult.Max = solidBoundingBox.Max; continue; } mergedResult = MergeBoundingBoxXyz( mergedResult, solidBoundingBox); } return(mergedResult); }
public void SetGraphicsStyleToSketch(Document doc) { // Find GraphicsStyle FilteredElementCollector collector = new FilteredElementCollector(doc) .OfClass(typeof(GraphicsStyle)); GraphicsStyle style = collector .Cast <GraphicsStyle>() .FirstOrDefault <GraphicsStyle>(gs => gs.Name.Equals("<Sketch>")); if (style != null) { GraphicsStyleId = style.Id; } }
/// <summary> /// Gets the saved setups from the document. /// </summary> /// <returns>The saved configurations.</returns> private IList<DataStorage> GetSavedConfigurations(Schema schema) { FilteredElementCollector collector = new FilteredElementCollector(IFCCommandOverrideApplication.TheDocument); collector.OfClass(typeof(DataStorage)); Func<DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid()); return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>(); }
/// <summary> /// Iterate directly over the filtered element collector. /// In general, there is no need to create a copy of it. /// Calling ToElements creates a copy, allocating space /// for that and wasting both memory and time. /// No need to cast either, foreach can do that /// automatically. /// </summary> IEnumerable<Element> IterateOverCollector( Document doc) { // Do not do this! FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( Family ) ).ToElements(); IEnumerable<Family> nestedFamilies = collector.Cast<Family>(); String str = ""; foreach( Family f in nestedFamilies ) { str = str + f.Name + "\n"; foreach( ElementId symbolId in f.GetFamilySymbolIds() ) { Element symbolElem = doc.GetElement( symbolId ); str = str + " family type: " + symbolElem.Name + "\n"; } } // Iterate directly over the collector instead. // No need for ToElements, which creates a copy. // The copy wastes memory and time. // No need for a cast, even. FilteredElementCollector families = new FilteredElementCollector( doc ) .OfClass( typeof( Family ) ); foreach( Family f in families ) { str = str + f.Name + "\n"; // ... } return families; }
// main function public void ExportToLux() { //loop through views and export to lux foreach (Autodesk.Revit.DB.View3D ExportView in v3DViewToExport) { // Create new stopwatch Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //set up list geoFile to include List<String>GeoFileList = new List<string>(); //get all elements in view FilteredElementCollector viewCollector = new FilteredElementCollector(vDoc, ExportView.Id); //i could add a filter for each category here ( or for specials like lights...) //viewCollector.OfCategory(BuiltInCategory.OST_Walls); //cast views elements to list IEnumerable<Element> ElementList = viewCollector.Cast<Element>(); //create scene folder //check whether folder allready exists //if not create scene folder //create PLY folder //create RES folder (textures & other data) if (Directory.Exists(vOutputFilePath + ExportView.Name.ToString())) { //delete folder?? } else { //create all directories //make sure view name has no illegal characters: {} //create scene Directory Directory.CreateDirectory(vOutputFilePath + ExportView.Name.ToString()); //create PLY folder Directory.CreateDirectory(vOutputFilePath + ExportView.Name.ToString() + "/" + "PLY"); //create resources folder Directory.CreateDirectory(vOutputFilePath + ExportView.Name.ToString() + "/" + "RES"); } //set up geofile path variable String sOutputPathGeoFile = ""; //setup PLY path variable String PLYDirectory = ""; //check for linked Revit Files visible in view LuxExporter.Revit_Filter Filter = new Revit_Filter(vDoc); List<Element> RevitLinks = Filter.GetRevitLinks(ExportView.Id); //setup the geomtry option for the current view Autodesk.Revit.DB.Options GeometryOption = new Options(); GeometryOption.ComputeReferences = true; GeometryOption.View = ExportView; //export linked files if (RevitLinks.Count > 0) { //count how many instances of each individual link exist //check whether any of these instances collides with section box if there is any //if collision no instance, if no collision or no section box instanciate whole file //export link file and instanciate as often as required //create dictionary storing linked file name and number of occurences Dictionary<String, int> DRevitLinks = new Dictionary<string, int>(); //list containing all links of models not cut by section box and their transformation data List<LuxExporter.Revit_Linked_Files> lWholeModelLinks = new List<Revit_Linked_Files>(); //list containing all links of models cut by section box and their transformation data List<LuxExporter.Revit_Linked_Files> lCutModelLinks = new List<Revit_Linked_Files>(); int LinkCounter = 0; //loop through link list and sort items before exporting foreach (Element LinkItem in RevitLinks) { //increase link Counter LinkCounter++; //remove stuff from name String LinkName = LinkItem.Name.ToString().Substring(0, LinkItem.Name.ToString().IndexOf(".rvt")); //flag for bounding box check Boolean BoundingBoxOK = true; //check whether bounding box active //pointer int NumberOfLinkOccurences = 0; if (ExportView.SectionBox.Enabled) { //if yes does link clash with box? //get boundingbox of item BoundingBoxXYZ ElementBounding = LinkItem.get_BoundingBox(ExportView); //get sectionbox Autodesk.Revit.DB.BoundingBoxXYZ ViewSectionBox = ExportView.SectionBox; //check whether element bounding box is completely enclosed in view bounding box if not disable instancing! LuxExporter.Revit_BoundingBox_Checker checker = new Revit_BoundingBox_Checker(); BoundingBoxOK = checker.BoundingBox_Checker(ElementBounding, ViewSectionBox); } //get the link transformation Instance inst = LinkItem as Instance; RevitLinkTransform = inst.GetTransform(); if (BoundingBoxOK) { //if no boundingbox and no clash //check whether link already in list if (lWholeModelLinks.Contains(new LuxExporter.Revit_Linked_Files(LinkName))) { //get link class and add transformation LuxExporter.Revit_Linked_Files dummyLink = new Revit_Linked_Files(LinkName); LuxExporter.Revit_Linked_Files ExLink = lWholeModelLinks.Find(xy => xy.LinkName == dummyLink.LinkName); ExLink.AddTransForm(RevitLinkTransform); } else { //create new link class LuxExporter.Revit_Linked_Files dummyLink = new Revit_Linked_Files(LinkName); //add transformation dummyLink.AddTransForm(RevitLinkTransform); //add link element dummyLink.RevitLink = LinkItem; //add link short name dummyLink.LinkShortName = LinkCounter.ToString(); //check if this link has been exported before if (DRevitLinks.TryGetValue(LinkName, out NumberOfLinkOccurences)) { //increase counter DRevitLinks[LinkName] = NumberOfLinkOccurences + 1; NumberOfLinkOccurences++; } else { //add link to dictionary DRevitLinks.Add(LinkName, 0); } //remove .rvt from link instance name PLYDirectory = vOutputFilePath + ExportView.Name.ToString() + "/PLY/" + LinkName + "_" + NumberOfLinkOccurences.ToString() + "/"; //store unique LinkName in class dummyLink.UniqueLinkName = LinkName + "_" + NumberOfLinkOccurences.ToString(); //store path in class dummyLink.PLYFolderPath = PLYDirectory; //create geometry file name String GeoFilePath = vOutputFilePath + ExportView.Name.ToString() + "/" + LinkName + "_" + NumberOfLinkOccurences.ToString() + "-geom.lxo"; dummyLink.GeoFilePath = GeoFilePath; //add to list lWholeModelLinks.Add(dummyLink); } } else { //file need to be exported again //create new link class LuxExporter.Revit_Linked_Files dummyLink = new Revit_Linked_Files(LinkName); //add transformation dummyLink.AddTransForm(RevitLinkTransform); //add link element dummyLink.RevitLink = LinkItem; //add link short name dummyLink.LinkShortName = LinkCounter.ToString(); //check if this link has been exported before if (DRevitLinks.TryGetValue(LinkName, out NumberOfLinkOccurences)) { //increase counter DRevitLinks[LinkName] = NumberOfLinkOccurences + 1; NumberOfLinkOccurences++; } else { //add link to dictionary DRevitLinks.Add(LinkName, 0); } //remove .rvt from link instance name PLYDirectory = vOutputFilePath + ExportView.Name.ToString() + "/PLY/" + LinkName + "_" + NumberOfLinkOccurences.ToString() + "/"; //store unique LinkName in class dummyLink.UniqueLinkName = LinkName + "_" + NumberOfLinkOccurences.ToString(); //store path in class dummyLink.PLYFolderPath = PLYDirectory; //create geometry file name String GeoFilePath = vOutputFilePath + ExportView.Name.ToString() + "/" + LinkName + "_" + NumberOfLinkOccurences.ToString() + "-geom.lxo"; dummyLink.GeoFilePath = GeoFilePath; //add to list lCutModelLinks.Add(dummyLink); } } //combine linked model lists into one list List<LuxExporter.Revit_Linked_Files> lModelsCombined = new List<Revit_Linked_Files>(); lModelsCombined.AddRange(lWholeModelLinks.ToArray()); lModelsCombined.AddRange(lCutModelLinks.ToArray()); try { //loop through all model links and export them //foreach (LuxExporter.Revit_Linked_Files item in lWholeModelLinks) foreach (LuxExporter.Revit_Linked_Files item in lModelsCombined) { //create PLY output directory Directory.CreateDirectory(item.PLYFolderPath); //get elements in link foreach (Document ditem in vLinkedFiles) { //check for match in name if (ditem.PathName.Contains(item.LinkName)) { //export materials if (FilteredElementCollector.IsViewValidForElementIteration(ditem,ExportView.Id)) { //get all elements in view FilteredElementCollector LinkViewCollector = new FilteredElementCollector(ditem, ExportView.Id); //cast views elements to list IEnumerable<Element> LinkElementList = LinkViewCollector.Cast<Element>(); //export link GeoFileList.Add(ExportElementList(LinkElementList, ExportView, GeometryOption, item.GeoFilePath, item.PLYFolderPath, item)); } else { //get model element filter LuxExporter.Revit_Filter FilterUtility = new Revit_Filter(); //this filter also select non placed items!!! Autodesk.Revit.DB.LogicalOrFilter ModelFilter = FilterUtility.BuildFullModelFilter(); //filter elements from linked file Autodesk.Revit.DB.FilteredElementCollector collector = new FilteredElementCollector(ditem); //filter out types collector.WherePasses(ModelFilter).WhereElementIsNotElementType(); //pass eklement list IEnumerable<Element> LinkElementList =collector.Cast<Element>(); //export link GeoFileList.Add(ExportElementList(LinkElementList, ExportView, GeometryOption, item.GeoFilePath, item.PLYFolderPath, item)); } } } } } catch (Exception ex) { MessageBox.Show("Test"+ex.Message); throw; } } //reset the link transform RevitLinkTransform = null; sOutputPathGeoFile = vOutputFilePath + ExportView.Name.ToString() + "/" + ExportView.ViewName.ToString() + "-geom.lxo"; PLYDirectory = vOutputFilePath + ExportView.Name.ToString() + "/PLY/"; //export host file GeoFileList.Add(ExportElementList(ElementList, ExportView, GeometryOption, sOutputPathGeoFile,PLYDirectory,null)); // Stop timing stopwatch.Stop(); MessageBox.Show("Time elapsed: {0}" + stopwatch.Elapsed); //create material outputfilepath String sOutputPathMatFile = vOutputFilePath + ExportView.Name.ToString() + "/" + ExportView.ViewName.ToString() + "-mat.lxm"; try { //global::System.Windows.Forms.MessageBox.Show("Test"); //write out materials file //get materials in view only -->> does not work! //MaterialSet LMaterials = ExportView.Materials; //get materials in project LuxExporter.Revit_Filter MaterialFilter = new Revit_Filter(vDoc); List<Material> LMaterials = MaterialFilter.GetAllMaterials(); //setup helper class LuxExporter.Revit_Material_Worker MaterialExporter = new Revit_Material_Worker(vDoc); //setup export String StringBuilder MaterialExport = new StringBuilder("# Lux Render CVS - Material File"); MaterialExport.AppendLine("# Exported by LuxRev 0.2- ALPHA"); MaterialExport.AppendLine("# View Name: " + ExportView.ViewName.ToString()); MaterialExport.AppendLine(""); //add glass2 presets: //World MaterialExport.AppendLine("MakeNamedVolume \"World\" \"homogeneous\""); MaterialExport.AppendLine("\"float fresnel\" [1.000292658805847]"); MaterialExport.AppendLine("\"color g\" [-0.30000001 -0.30000001 -0.30000001]"); MaterialExport.AppendLine("\"color sigma_a\" [0.00000000 0.00000000 0.00000000]"); MaterialExport.AppendLine("\"color sigma_s\" [0.02500000 0.02500000 0.02500000]"); //Glass MaterialExport.AppendLine("MakeNamedVolume \"Glass\" \"clear\""); MaterialExport.AppendLine("\"float fresnel\" [1.519999980926514]"); MaterialExport.AppendLine("\"color absorption\" [0.01614268 0.00300774 0.03046782]"); //loop through all materials and export foreach (Material RevitMaterial in LMaterials) { MaterialExport.Append(MaterialExporter.ExportMaterial(RevitMaterial)); } //write out materials file using (System.IO.StreamWriter MatFile = new System.IO.StreamWriter(sOutputPathMatFile)) { MatFile.WriteLine(MaterialExport); } } catch (Exception) { MessageBox.Show("Failed To write mat file"); throw; } //view utility class LuxExporter.Revit_View_ThreeD ViewData = new Revit_View_ThreeD(ExportView); //get the camera data XYZ CameraPosition = ViewData.CameraPosition; XYZ CameraViewDirection = ViewData.CameraViewDirection; XYZ CameraUp = ViewData.CameraUp; //get the screenwindow date //assume resolution of 800 x 600 //lens shift is 0 for x and y //scale as per view double dScreenaspectRatio = (800.00 / 600.00); LuxExporter.LuxExporter_ScreenWindow ScreenWindow = new LuxExporter_ScreenWindow(dScreenaspectRatio, 0, 0, ExportView.Scale); Double[] vScreenWindow = ScreenWindow.GetScreenWindow(); //create string for header file - mainly hardcoded as of yet StringBuilder LXS = new StringBuilder("# Lux Render CVS - Scene File"); LXS.AppendLine("# Exported by LuxRev 0.2- ALPHA"); LXS.AppendLine("# View Name: "+ ExportView.ViewName.ToString()); LXS.AppendLine("LookAt "+CameraPosition.X.ToString("f6")+" "+CameraPosition.Y.ToString("f6")+" "+CameraPosition.Z.ToString("f6")); LXS.AppendLine(" " + CameraViewDirection.X.ToString("f6") + " " + CameraViewDirection.Y.ToString("f6") + " " + CameraViewDirection.Z.ToString("f6")); LXS.AppendLine(" "+CameraUp.X.ToString("f6")+" "+CameraUp.Y.ToString("f6")+" "+CameraUp.Z.ToString("f6")); LXS.AppendLine(""); LXS.AppendLine("Camera \"perspective\""); LXS.AppendLine(" \"float fov\" [150]"); LXS.AppendLine(" \"float hither\" [0]"); LXS.AppendLine(" \"float yon\" [10000000]"); LXS.AppendLine(" \"float lensradius\" [0]"); LXS.AppendLine(" \"bool autofocus\" [\"true\"]"); LXS.AppendLine(" \"float shutteropen\" [0]"); LXS.AppendLine(" \"float shutterclose\" [1]"); LXS.AppendLine( " \"float screenwindow\" ["+vScreenWindow[0]+" "+vScreenWindow[1]+" "+vScreenWindow[2]+" "+vScreenWindow[3]+"]"); LXS.AppendLine(""); LXS.AppendLine("Film \"fleximage\""); LXS.AppendLine(" \"integer xresolution\" [800]"); LXS.AppendLine(" \"integer yresolution\" [600]"); LXS.AppendLine(" \"integer haltspp\" [0]"); LXS.AppendLine(" \"bool premultiplyalpha\" [\"false\"]"); LXS.AppendLine(" \"string tonemapkernel\" [\"reinhard\"]"); LXS.AppendLine(" \"float reinhard_postscale\" [1.200000]"); LXS.AppendLine(" \"float reinhard_burn\" [6.000000]"); LXS.AppendLine(" \"integer displayinterval\" [8]"); LXS.AppendLine(" \"integer writeinterval\" [120]"); LXS.AppendLine(" \"string ldr_clamp_method\" [\"lum\"]"); LXS.AppendLine(" \"bool write_exr\" [\"false\"]"); LXS.AppendLine(" \"bool write_png\" [\"true\"]"); LXS.AppendLine(" \"string write_png_channels\" [\"RGB\"]"); LXS.AppendLine(" \"bool write_png_16bit\" [\"false\"]"); LXS.AppendLine(" \"bool write_png_gamutclamp\" [\"true\"]"); LXS.AppendLine(" \"bool write_tga\" [\"false\"]"); LXS.AppendLine(" \"string filename\" [\"C:\\\\temp\\\\lux\\\\"+ExportView.ViewName.ToString()+"\"]"); LXS.AppendLine(" \"bool write_resume_flm\" [\"false\"]"); LXS.AppendLine(" \"bool restart_resume_flm\" [\"true\"]"); LXS.AppendLine(" \"integer reject_warmup\" [128]"); LXS.AppendLine(" \"bool debug\" [\"false\"]"); LXS.AppendLine(" \"float colorspace_white\" [0.314275 0.329411]"); LXS.AppendLine(" \"float colorspace_red\" [0.630000 0.340000]"); LXS.AppendLine(" \"float colorspace_green\" [0.310000 0.595000]"); LXS.AppendLine(" \"float colorspace_blue\" [0.155000 0.070000]"); LXS.AppendLine(" \"float gamma\" [2.2]"); LXS.AppendLine(""); LXS.AppendLine("PixelFilter \"mitchell\""); LXS.AppendLine(" \"float B\" [0.75]"); LXS.AppendLine(" \"float C\" [0.125]"); LXS.AppendLine(""); LXS.AppendLine("Sampler \"metropolis\""); LXS.AppendLine(" \"float largemutationprob\" [0.4]"); LXS.AppendLine(""); LXS.AppendLine("SurfaceIntegrator \"bidirectional\""); LXS.AppendLine(" \"integer eyedepth\" [48]"); LXS.AppendLine(" \"integer lightdepth\" [48]"); LXS.AppendLine(""); LXS.AppendLine("VolumeIntegrator \"single\""); LXS.AppendLine(" \"float stepsize\" [1]"); LXS.AppendLine("Accelerator \"tabreckdtree\""); LXS.AppendLine(" \"integer intersectcost\" [80]"); LXS.AppendLine(" \"integer traversalcost\" [1]"); LXS.AppendLine(" \"float emptybonus\" [0.2]"); LXS.AppendLine(" \"integer maxprims\" [1]"); LXS.AppendLine(" \"integer maxdepth\" [-1]"); LXS.AppendLine(""); LXS.AppendLine("WorldBegin"); LXS.AppendLine(""); LXS.AppendLine("AttributeBegin"); LXS.AppendLine("LightGroup \"default\""); LXS.AppendLine(" LightSource \"sunsky\""); LXS.AppendLine("AttributeEnd"); LXS.AppendLine(""); LXS.AppendLine("Include \""+sOutputPathMatFile+"\""); LXS.AppendLine(""); foreach (String FilePath in GeoFileList) { LXS.AppendLine("Include \"" + FilePath + "\""); } LXS.AppendLine(""); LXS.AppendLine("WorldEnd"); //create outputfilepath String sOutputPathSceneFile = vOutputFilePath + ExportView.Name.ToString()+"/"+ ExportView.ViewName.ToString() + ".lxs"; //write out Scene file using (System.IO.StreamWriter LXSFile = new System.IO.StreamWriter(sOutputPathSceneFile)) { LXSFile.WriteLine(LXS); } } }
/// <summary> /// Return a sketch plane from the given document with /// the specified normal vector, if one exists, else null. /// </summary> static SketchPlane findSketchPlane( Document doc, XYZ normal) { FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( SketchPlane ) ); #if EXPLICIT_CODE SketchPlane result = null; foreach( SketchPlane e in collector ) { if( e.Plane.Normal.IsAlmostEqualTo( normal ) ) { result = e; break; } } return result; #endif // EXPLICIT_CODE //Func<SketchPlane, bool> normalEquals = e => e.Plane.Normal.IsAlmostEqualTo( normal ); // 2013 Func<SketchPlane, bool> normalEquals = e => e.GetPlane().Normal.IsAlmostEqualTo( normal ); // 2014 return collector.Cast<SketchPlane>().First<SketchPlane>( normalEquals ); }
/// <summary> /// External command mainline. /// </summary> public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { IWin32Window revit_window = new JtWindowHandle( Autodesk.Windows .ComponentManager.ApplicationWindow ); if( !Util.FileSelectObj( Config.DefaultFolderObj, ref _filename ) ) { return Result.Cancelled; } Config.DefaultFolderObj = Path.GetDirectoryName( _filename ); long fileSize = Util.GetFileSize( _filename ); if( fileSize > Config.MaxFileSize ) { string msg = string.Format( "Excuse me, but " + "you are attempting to load a file that is " + "{0} bytes in size. We suggest ensuring " + "that the file size is no larger than {1} " + "bytes, since Revit will refuse to handle " + "meshes exceeding a certain size anyway. " + "Please refer to the troubleshooting page " + "at\r\n\r\n{2}\r\n\r\n" + "for suggestions on how to optimise the " + "mesh and thus reduce file size.", fileSize, Config.MaxFileSize, TroubleshootingUrl ); TaskDialog.Show( App.Caption, msg ); return Result.Failed; } FileLoadResult<Scene> obj_load_result = null; List<XYZ> vertices = null; try { bool loadTextureImages = true; obj_load_result = FileFormatObj.Load( _filename, loadTextureImages ); foreach( var m in obj_load_result.Messages ) { Debug.Print( "{0}: {1} line {2} in {3}", m.MessageType, m.Details, m.FileName, m.LineNumber ); } // Convert OBJ vertices to Revit XYZ. // OBJ assumes X to the right, Y up and Z out of the screen. // Revit 3D view assumes X right, Y away // from the screen and Z up. double scale = Config.InputScaleFactor; int n = obj_load_result.Model.Vertices.Count; vertices = new List<XYZ>( n ); XYZ w; foreach( Vertex v in obj_load_result.Model.Vertices ) { w = new XYZ( v.x * scale, -v.z * scale, v.y * scale ); Debug.Print( "({0},{1},{2}) --> {3}", Util.RealString( v.x ), Util.RealString( v.y ), Util.RealString( v.z ), Util.PointString( w ) ); vertices.Add( w ); } foreach( Face f in obj_load_result.Model.UngroupedFaces ) { n = f.Indices.Count; Debug.Assert( 3 == n || 4 == n, "expected triangles or quadrilaterals" ); Debug.Print( string.Join( ", ", f.Indices.Select<Index, string>( i => i.vertex.ToString() ) ) ); } } catch( System.Exception ex ) { message = string.Format( "Exception reading '{0}':" + "\r\n{1}:\r\n{2}", _filename, ex.GetType().FullName, ex.Message ); return Result.Failed; } if( vertices.Count > Config.MaxNumberOfVertices ) { string msg = string.Format( "Excuse me, but " + "you are attempting to load a mesh defining " + "{0} vertices. We suggest using no more than " + "{1}, since Revit will refuse to handle such " + "a large mesh anyway. " + "Please refer to the troubleshooting page at " + "\r\n\r\n{2}\r\n\r\n" + "for suggestions on how to optimise the mesh " + "and thus reduce its size.", vertices.Count, Config.MaxNumberOfVertices, TroubleshootingUrl ); TaskDialog.Show( App.Caption, msg ); return Result.Failed; } UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; string appGuid = uiapp.ActiveAddInId.GetGUID().ToString(); string shapeName = Util.Capitalize( Path.GetFileNameWithoutExtension( _filename ) .Replace( '_', ' ' ) ); // Retrieve "<Sketch>" graphics style, // if it exists. FilteredElementCollector collector = new FilteredElementCollector( doc ) .OfClass( typeof( GraphicsStyle ) ); GraphicsStyle style = collector.Cast<GraphicsStyle>() .FirstOrDefault<GraphicsStyle>( gs => gs.Name.Equals( "<Sketch>" ) ); ElementId graphicsStyleId = null; if( style != null ) { graphicsStyleId = style.Id; } Result rc = Result.Failed; try { using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Create DirectShape from OBJ" ); int nFaces = 0; // set to -1 on fatal error int nFacesTotal = 0; if( 0 < obj_load_result.Model.UngroupedFaces.Count ) { nFacesTotal = nFaces = NewDirectShape( vertices, obj_load_result.Model.UngroupedFaces, doc, graphicsStyleId, appGuid, shapeName ); } if( -1 < nFaces ) { foreach( Group g in obj_load_result.Model.Groups ) { string s = string.Join( ".", g.Names ); if( 0 < s.Length ) { s = "." + s; } nFaces = NewDirectShape( vertices, g.Faces, doc, graphicsStyleId, appGuid, shapeName + s ); if( -1 == nFaces ) { break; } nFacesTotal += nFaces; } } if( -1 == nFaces ) { message = "Invalid OBJ file. Error: face " + "vertex index exceeds total vertex count."; } else if( 0 == nFacesTotal ) { message = "Invalid OBJ file. Zero faces found."; } else { tx.Commit(); rc = Result.Succeeded; } } } catch( System.Exception ex ) { message = string.Format( "Exception generating DirectShape '{0}':" + "\r\n{1}:\r\n{2}", shapeName, ex.GetType().FullName, ex.Message ); return Result.Failed; } return rc; }
/// <summary> /// Initializes custom property sets from schedules. /// </summary> /// <param name="propertySets">List to store property sets.</param> /// <param name="fileVersion">The IFC file version.</param> private static void InitCustomPropertySets(IList<IList<PropertySetDescription>> propertySets) { Document document = ExporterCacheManager.Document; IList<PropertySetDescription> customPropertySets = new List<PropertySetDescription>(); // Collect all ViewSchedules from the document to use as custom property sets. FilteredElementCollector viewScheduleElementCollector = new FilteredElementCollector(document); ElementFilter viewScheduleElementFilter = new ElementClassFilter(typeof(ViewSchedule)); viewScheduleElementCollector.WherePasses(viewScheduleElementFilter); List<ViewSchedule> filteredSchedules = viewScheduleElementCollector.Cast<ViewSchedule>().ToList(); int unnamedScheduleIndex = 1; string includePattern = "PSET|IFC|COMMON"; if (ExporterCacheManager.ExportOptionsCache.PropertySetOptions.ExportSpecificSchedules) { var resultQuery = from viewSchedule in viewScheduleElementCollector where viewSchedule.Name != null && System.Text.RegularExpressions.Regex.IsMatch(viewSchedule.Name, includePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase) select viewSchedule; filteredSchedules = resultQuery.Cast<ViewSchedule>().ToList(); } foreach (ViewSchedule schedule in filteredSchedules) { //property set Manufacturer Information PropertySetDescription customPSet = new PropertySetDescription(); string scheduleName = schedule.Name; if (string.IsNullOrWhiteSpace(scheduleName)) { scheduleName = "Unnamed Schedule " + unnamedScheduleIndex; unnamedScheduleIndex++; } customPSet.Name = scheduleName; ScheduleDefinition definition = schedule.Definition; if (definition == null) continue; // The schedule will be responsible for determining which elements to actually export. customPSet.ViewScheduleId = schedule.Id; customPSet.EntityTypes.Add(IFCEntityType.IfcProduct); int fieldCount = definition.GetFieldCount(); if (fieldCount == 0) continue; HashSet<ElementId> containedElementIds = new HashSet<ElementId>(); FilteredElementCollector elementsInViewScheduleCollector = new FilteredElementCollector(document, schedule.Id); foreach (Element containedElement in elementsInViewScheduleCollector) { containedElementIds.Add(containedElement.Id); } ExporterCacheManager.ViewScheduleElementCache.Add(new KeyValuePair<ElementId, HashSet<ElementId>>(schedule.Id, containedElementIds)); IDictionary<ElementId, Element> cachedElementTypes = new Dictionary<ElementId, Element>(); for (int ii = 0; ii < fieldCount; ii++) { ScheduleField field = definition.GetField(ii); ScheduleFieldType fieldType = field.FieldType; if (fieldType != ScheduleFieldType.Instance && fieldType != ScheduleFieldType.ElementType) continue; ElementId parameterId = field.ParameterId; if (parameterId == ElementId.InvalidElementId) continue; // We use asBuiltInParameterId to get the parameter by id below. We don't want to use it later, however, so // we store builtInParameterId only if it is a proper member of the enumeration. BuiltInParameter asBuiltInParameterId = (BuiltInParameter)parameterId.IntegerValue; BuiltInParameter builtInParameterId = Enum.IsDefined(typeof(BuiltInParameter), asBuiltInParameterId) ? asBuiltInParameterId : BuiltInParameter.INVALID; Parameter containedElementParameter = null; // We could cache the actual elements when we store the element ids. However, this would almost certainly take more // time than getting one of the first few elements in the collector. foreach (Element containedElement in elementsInViewScheduleCollector) { if (fieldType == ScheduleFieldType.Instance) containedElementParameter = containedElement.get_Parameter(asBuiltInParameterId); // shared parameters can return ScheduleFieldType.Instance, even if they are type parameters, so take a look. if (containedElementParameter == null) { ElementId containedElementTypeId = containedElement.GetTypeId(); Element containedElementType = null; if (containedElementTypeId != ElementId.InvalidElementId) { if (!cachedElementTypes.TryGetValue(containedElementTypeId, out containedElementType)) { containedElementType = document.GetElement(containedElementTypeId); cachedElementTypes[containedElementTypeId] = containedElementType; } } if (containedElementType != null) containedElementParameter = containedElementType.get_Parameter(asBuiltInParameterId); } if (containedElementParameter != null) break; } if (containedElementParameter == null) continue; PropertySetEntry ifcPSE = PropertySetEntry.CreateParameterEntry(containedElementParameter); ifcPSE.RevitBuiltInParameter = builtInParameterId; ifcPSE.PropertyName = field.ColumnHeading; customPSet.AddEntry(ifcPSE); } customPropertySets.Add(customPSet); } propertySets.Add(customPropertySets); }
/// <summary> /// Gets the saved setups from the document. /// </summary> /// <param name="document">The document storing the saved configuration.</param> /// <returns>The saved configurations.</returns> private IList<DataStorage> GetSavedConfigurations(Document document) { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(DataStorage)); Func<DataStorage, bool> hasTargetData = ds => ds.GetEntity(m_schema) != null; return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>(); }
/// <summary> /// Retrieve all openings in a given wall. /// </summary> void GetOpeningsInWall( Document doc, Wall wall) { ElementId id = wall.Id; BuiltInCategory bic = BuiltInCategory.OST_SWallRectOpening; FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( Opening ) ); collector.OfCategory( bic ); // explicit iteration and manual // checking of a property: List<Element> openings = new List<Element>(); foreach( Opening e in collector ) { if( e.Host.Id.Equals( id ) ) { openings.Add( e ); } } // using LINQ: IEnumerable<Opening> openingsOnLevelLinq = from e in collector.Cast<Opening>() where e.Host.LevelId.Equals( id ) select e; // using an anonymous method: IEnumerable<Opening> openingsOnLevelAnon = collector.Cast<Opening>().Where<Opening>( e => e.Host.Id.Equals( id ) ); }
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(); } }