public override void GetConvertHash() { m_hash = Command.HookTypes; Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(-1); if (!m_hash.ContainsKey("None")) { m_hash.Add("None", id); } }
ElementId(string label, Autodesk.Revit.DB.ElementId val, Document doc) : base(label) { m_val = val; try { if (val != Autodesk.Revit.DB.ElementId.InvalidElementId) m_elem = doc.GetElement(val); // TBD: strange signature! } catch (System.Exception) { m_elem = null; } }
// get surface ids from analytical energy model based on type public static List <EnergyAnalysisForDynamo.ElementId> GetSurfaceIdsFromMassEnergyAnalyticalModelBasedOnType(MassEnergyAnalyticalModel MassEnergyAnalyticalModel, string SurfaceTypeName = "Mass Exterior Wall") { //get the MassSurfaceData ids of the definitions belonging to external faces //we'll output these, and then try to visualize the faces and change parameters in another component //get references to the faces using the mass - we need these to get at the surface data IList <Reference> faceRefs = MassEnergyAnalyticalModel.GetReferencesToAllFaces(); //some faces supposedly share massSurfaceData definitions (although i think they are all unique in practice) - here we're pulling out unique data definitions. Dictionary <int, MassSurfaceData> mySurfaceData = new Dictionary <int, MassSurfaceData>(); foreach (var fr in faceRefs) { Autodesk.Revit.DB.ElementId id = MassEnergyAnalyticalModel.GetMassSurfaceDataIdForReference(fr); if (!mySurfaceData.ContainsKey(id.IntegerValue)) { MassSurfaceData d = (MassSurfaceData)MassEnergyAnalyticalModel.Document.GetElement(id); mySurfaceData.Add(id.IntegerValue, d); } } //filter by category = mass exterior wall var allSurfsList = mySurfaceData.Values.ToList(); var selectedSurfList = from n in allSurfsList where n.Category.Name == SurfaceTypeName select n; //output list List <Autodesk.Revit.DB.ElementId> SelectedSurfaceIds = new List <Autodesk.Revit.DB.ElementId>(); foreach (var s in selectedSurfList) { SelectedSurfaceIds.Add(s.Id); } List <ElementId> outSelectedSurfaceIds = SelectedSurfaceIds.Select(e => new ElementId(e.IntegerValue)).ToList(); return(outSelectedSurfaceIds); }
private Autodesk.Revit.DB.View GetViewByName(string name) { FilteredElementCollector docFilter = new FilteredElementCollector(doc); if (docFilter != null) { FilteredElementIterator viewsIterator = docFilter.OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator(); while (viewsIterator.MoveNext()) { Autodesk.Revit.DB.View curView = viewsIterator.Current as Autodesk.Revit.DB.View; string curViewTypeName = curView.GetType().Name; if ((curViewTypeName == "ViewDrafting") || (curViewTypeName == "ViewPlan")) { Autodesk.Revit.DB.ElementId curElementId = curView.GetTypeId(); Autodesk.Revit.DB.ElementType curElementType = doc.GetElement(curElementId) as ElementType; if (curElementType != null) { if (curElementType.GetType().Name == "ViewFamilyType") { Autodesk.Revit.DB.ViewFamilyType curViewFamilyType = (ViewFamilyType)curElementType; if (curViewFamilyType != null) { string curViewName = curViewFamilyType.Name + ": " + curView.Name; if (curViewName == name) { return(curView); } } } } } } } return(null); }
private List <string> GetDraftAndPlanViewsNames() { List <string> names = new List <string>(); FilteredElementCollector viewFilter = new FilteredElementCollector(doc); if (viewFilter != null) { FilteredElementIterator viewsIterator = viewFilter.OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator(); while (viewsIterator.MoveNext()) { Autodesk.Revit.DB.View curView = viewsIterator.Current as Autodesk.Revit.DB.View; string curViewTypeName = curView.GetType().Name; if ((curViewTypeName == "ViewDrafting") || (curViewTypeName == "ViewPlan")) { Autodesk.Revit.DB.ElementId curElementId = curView.GetTypeId(); Autodesk.Revit.DB.ElementType curElementType = doc.GetElement(curElementId) as ElementType; if (curElementType != null) { if (curElementType.GetType().Name == "ViewFamilyType") { Autodesk.Revit.DB.ViewFamilyType curViewFamilyType = (ViewFamilyType)curElementType; if (curViewFamilyType != null) { string curName = curViewFamilyType.Name + ": " + curView.Name; names.Add(curName); } } } } } } names.Sort(); return(names); }
/// <summary> /// Create foundation slabs. /// </summary> /// <returns>The bool value suggest successful or not.</returns> public bool CreateFoundationSlabs() { // Create a foundation slab for each selected regular slab. foreach (RegularSlab slab in m_allBaseSlabList) { if (!slab.Selected) { continue; } // Create a new slab. Transaction t = new Transaction(m_revit.ActiveUIDocument.Document, Guid.NewGuid().GetHashCode().ToString()); t.Start(); CurveLoop loop = new CurveLoop(); foreach (Curve curve in slab.OctagonalProfile) { loop.Append(curve); } List <CurveLoop> floorLoops = new List <CurveLoop> { loop }; Floor foundationSlab = Floor.Create(m_revit.ActiveUIDocument.Document, floorLoops, m_foundationSlabType.Id, m_levelList.Values[0].Id, true, null, 0.0); t.Commit(); if (null == foundationSlab) { return(false); } // Delete the regular slab. Transaction t2 = new Transaction(m_revit.ActiveUIDocument.Document, Guid.NewGuid().GetHashCode().ToString()); t2.Start(); Autodesk.Revit.DB.ElementId deleteSlabId = slab.Id; m_revit.ActiveUIDocument.Document.Delete(deleteSlabId); t2.Commit(); } return(true); }
public override bool NeedsToBeExpired(DB.Events.DocumentChangedEventArgs e) { var elementFilter = ElementFilter; var _Filter_ = Params.IndexOfInputParam("Filter"); var filters = _Filter_ < 0 ? Enumerable.Empty <DB.ElementFilter>() : Params.Input[_Filter_].VolatileData.AllData(true).OfType <Types.ElementFilter>().Select(x => new DB.LogicalAndFilter(x.Value, elementFilter)); foreach (var filter in filters.Any() ? filters : Enumerable.Repeat(elementFilter, 1)) { var added = filter is null?e.GetAddedElementIds() : e.GetAddedElementIds(filter); if (added.Count > 0) { return(true); } var modified = filter is null?e.GetModifiedElementIds() : e.GetModifiedElementIds(filter); if (modified.Count > 0) { return(true); } var deleted = e.GetDeletedElementIds(); if (deleted.Count > 0) { var document = e.GetDocument(); var empty = new DB.ElementId[0]; foreach (var param in Params.Output.OfType <Kernel.IGH_ElementIdParam>()) { if (param.NeedsToBeExpired(document, empty, deleted, empty)) { return(true); } } } } return(false); }
bool Kernel.IGH_ElementIdParam.NeedsToBeExpired ( DB.Document doc, ICollection <DB.ElementId> added, ICollection <DB.ElementId> deleted, ICollection <DB.ElementId> modified ) { // If anything of that type is added we need to update ListItems if (added.Where(id => PassesFilter(doc, id)).Any()) { return(true); } // If selected items are modified we need to expire dependant components foreach (var data in VolatileData.AllData(true).OfType <Types.IGH_ElementId>()) { if (!data.IsElementLoaded) { continue; } if (modified.Contains(data.Id)) { return(true); } } // If an item in ListItems is deleted we need to update ListItems foreach (var item in ListItems.Select(x => x.Value).OfType <Grasshopper.Kernel.Types.GH_Integer>()) { var id = new DB.ElementId(item.Value); if (deleted.Contains(id)) { return(true); } } return(false); }
/// <summary> /// Get selected beam (truss member) by select index /// </summary> /// <param name="commandData">object which contains reference of Revit Application</param> /// <returns>index of selected member</returns> public FamilyInstance GetSelectedBeam(ExternalCommandData commandData) { m_clickMemberIndex = m_selectMemberIndex; Autodesk.Revit.DB.ElementId id = null; List <ElementId> idSet = m_truss.Members as List <ElementId>; IEnumerator iter = idSet.GetEnumerator(); iter.Reset(); int i = 0; while (iter.MoveNext()) { if (i == m_selectMemberIndex) { id = iter.Current as Autodesk.Revit.DB.ElementId; break; } i++; } return((FamilyInstance)commandData.Application.ActiveUIDocument.Document.GetElement(id)); }
public SerialElementId(RevitElemId Id, [DefaultArgument("Synthetic.Revit.Document.Current()")] RevitDoc Document) { this.Id = Id.IntegerValue; RevitElem elem = Document.GetElement(Id); if (elem != null) { this.Name = elem.Name; this.Class = elem.GetType().FullName; this.UniqueId = elem.UniqueId; RevitDB.Category cat = elem.Category; if (cat != null) { this.Category = elem.Category.Name; } } }
public static void createRVTWalls( Autodesk.Revit.DB.Document targetDoc, List <Curve> curves_list, Autodesk.Revit.DB.ElementId levelId ) { foreach (Curve _curve in curves_list) { // *** REQUIRES REVIT: Wall newWall = Wall.Create(targetDoc, _curve, levelId, false); IList <Parameter> UnconnectedHeigth_Params = newWall.GetParameters("Unconnected Height"); if (UnconnectedHeigth_Params.Count > 0) { if (!UnconnectedHeigth_Params[0].IsReadOnly) { // can set, but the result is not 100 UnconnectedHeigth_Params[0].Set(40); } } } }
public override sealed bool CastFrom(object source) { if (base.CastFrom(source)) { return(true); } var document = Revit.ActiveDBDocument; var parameterId = DB.ElementId.InvalidElementId; if (source is IGH_Goo goo) { if (source is IGH_Element element) { source = element.Document?.GetElement(element.Id); } else { source = goo.ScriptVariable(); } } switch (source) { case int integer: parameterId = new DB.ElementId(integer); break; case DB.ElementId id: parameterId = id; break; case DB.Parameter parameter: SetValue(parameter.Element.Document, parameter.Id); return(true); } if (parameterId.TryGetBuiltInParameter(out var _)) { SetValue(document, parameterId); return(true); } return(base.CastFrom(source)); }
/// <summary> /// Cast the selected element to a dynamo node /// </summary> public override IEnumerable <AssociativeNode> BuildOutputAst(List <AssociativeNode> inputAstNodes) { // If there are no elements in the dropdown or the selected Index is invalid return a Null node. if (!CanBuildOutputAst(Properties.Resources.NoTypesFound, Properties.Resources.None)) { return new[] { AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), AstFactory.BuildNullNode()) } } ; // Cast the selected object to a Revit Element and get its Id Autodesk.Revit.DB.ElementId Id = ((Autodesk.Revit.DB.Element)Items[SelectedIndex].Item).Id; // Select the element using the elementIds Integer Value var node = AstFactory.BuildFunctionCall("Revit.Elements.ElementSelector", "ByElementId", new List <AssociativeNode> { AstFactory.BuildIntNode(Id.IntegerValue) }); // Return the selected element return(new[] { AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), node) }); } }
DB.GraphicsStyle MapGraphicsStyle(DB.Document project, DB.Document family, DB.ElementId graphicsStyleId, bool createIfNotExist = false) { try { if (project.GetElement(graphicsStyleId) is DB.GraphicsStyle graphicsStyle) { if (family.OwnerFamily.FamilyCategory.SubCategories.Contains(graphicsStyle.GraphicsStyleCategory.Name) && family.OwnerFamily.FamilyCategory.SubCategories.get_Item(graphicsStyle.GraphicsStyleCategory.Name) is DB.Category subCategory) { return(subCategory.GetGraphicsStyle(graphicsStyle.GraphicsStyleType)); } if (createIfNotExist) { return(family.Settings.Categories.NewSubcategory(family.OwnerFamily.FamilyCategory, graphicsStyle.GraphicsStyleCategory.Name). GetGraphicsStyle(graphicsStyle.GraphicsStyleType)); } } } catch (Autodesk.Revit.Exceptions.InvalidOperationException) { } return(null); }
public static DB.ElementId GetDefaultElementTypeId(DB.Document doc, DB.ElementId categoryId) { var elementTypeId = doc.GetDefaultFamilyTypeId(categoryId); if (elementTypeId.IsValid()) { return(elementTypeId); } if (categoryId.TryGetBuiltInCategory(out var cat)) { foreach (var elementTypeGroup in Enum.GetValues(typeof(DB.ElementTypeGroup)).Cast <DB.ElementTypeGroup>()) { var type = doc.GetElement(doc.GetDefaultElementTypeId(elementTypeGroup)) as DB.ElementType; if (type?.Category?.Id.IntegerValue == (int)cat) { return(type.Id); } } } return(DB.ElementId.InvalidElementId); }
/// <summary> /// find a parameter according to the parameter's name /// </summary> /// <param name="element">the host object of the parameter</param> /// <param name="parameterName">parameter name</param> /// <param name="value">the value of the parameter with Autodesk.Revit.DB.ElementId type</param> /// <returns>if find the parameter return true</returns> public static bool SetParameter(Element element, string parameterName, ref Autodesk.Revit.DB.ElementId value) { ParameterSet parameters = element.Parameters; Parameter findParameter = FindParameter(parameters, parameterName); if (null == findParameter) { return(false); } if (!findParameter.IsReadOnly) { StorageType parameterType = findParameter.StorageType; if (StorageType.ElementId != parameterType) { throw new Exception("The types of value and parameter are different!"); } findParameter.Set(value); return(true); } return(false); }
/// <summary> /// find a parameter according to the parameter's name /// </summary> /// <param name="element">the host object of the parameter</param> /// <param name="paraIndex">parameter index</param> /// <param name="value">the value of the parameter with Autodesk.Revit.DB.ElementId type</param> /// <returns>if find the parameter return true</returns> public static bool SetParameter(Element element, BuiltInParameter paraIndex, ref Autodesk.Revit.DB.ElementId value) { Parameter parameter = element.get_Parameter(paraIndex); if (null == parameter) { return(false); } if (!parameter.IsReadOnly) { StorageType parameterType = parameter.StorageType; if (StorageType.ElementId != parameterType) { throw new Exception("The types of value and parameter are different!"); } parameter.Set(value); return(true); } return(false); }
/// <summary> /// set parameter's value /// </summary> /// <param name="parameter">parameter of a Material</param> /// <param name="value"> /// value will be set to parameter /// </param> public static void SetParameterValue(Parameter parameter, Object value) { //first,check whether this parameter is read only if (parameter.IsReadOnly) { return; } switch (parameter.StorageType) { case StorageType.Double: //set value with unit, Set() can set value without unit parameter.SetValueString(value as string); break; case StorageType.ElementId: Autodesk.Revit.DB.ElementId elementId = (Autodesk.Revit.DB.ElementId)(value); parameter.Set(elementId); break; case StorageType.Integer: //set value with unit, Set() can set value without unit parameter.SetValueString(value as string); break; case StorageType.None: parameter.SetValueString(value as string); break; case StorageType.String: parameter.Set(value as string); break; default: break; } }
private void ReadJournalData() { RevitDB.Document doc = m_commandData.Application.ActiveUIDocument.Document; IDictionary <string, string> dataMap = m_commandData.JournalData; string dataValue = null; dataValue = GetSpecialData(dataMap, "Wall Type Name"); foreach (RevitDB.WallType type in m_wallTypeList) { if (dataValue == type.Name) { m_createType = type; break; } } if (null == m_createType) { throw new InvalidDataException("Can't find the wall type from the journal."); } dataValue = GetSpecialData(dataMap, "Level Id"); RevitDB.ElementId id = new RevitDB.ElementId(Convert.ToInt32(dataValue)); m_createlevel = doc.GetElement(id) as RevitDB.Level; if (null == m_createlevel) { throw new InvalidDataException("Can't find the level from the journal."); } dataValue = GetSpecialData(dataMap, "Start Point"); m_startPoint = StringToXYZ(dataValue); if (m_startPoint.Equals(m_endPoint)) { throw new InvalidDataException("Start point is equal to end point."); } }
// get surface ids from zone based on type public static List <EnergyAnalysisForDynamo.ElementId> GetSurfaceIdsFromZoneBasedOnType(MassZone MassZone, string SurfaceTypeName = "Mass Exterior Wall") { //some faces supposedly share massSurfaceData definitions (although i think they are all unique in practice) - here we're pulling out unique data definitions. Dictionary <int, Autodesk.Revit.DB.Element> mySurfaceData = new Dictionary <int, Autodesk.Revit.DB.Element>(); List <Autodesk.Revit.DB.ElementId> SurfaceIds = new List <Autodesk.Revit.DB.ElementId>(); //get references to all of the faces IList <Reference> faceRefs = MassZone.GetReferencesToEnergyAnalysisFaces(); foreach (var faceRef in faceRefs) { var srfType = faceRef.GetType(); string refType = faceRef.ElementReferenceType.ToString(); //get the element ID of the MassSurfaceData object associated with this face Autodesk.Revit.DB.ElementId id = MassZone.GetMassDataElementIdForZoneFaceReference(faceRef); //add it to our dict if it isn't already there if (!mySurfaceData.ContainsKey(id.IntegerValue)) { Autodesk.Revit.DB.Element mySurface = MassZone.Document.GetElement(id); //add id and surface to dictionary to keep track of data mySurfaceData.Add(id.IntegerValue, mySurface); if (mySurface.Category.Name == SurfaceTypeName) { // collect the id SurfaceIds.Add(id); } } } //loop over the output lists, and wrap them in our ElementId wrapper class List <ElementId> outSurfaceIds = SurfaceIds.Select(e => new ElementId(e.IntegerValue)).ToList(); return(outSurfaceIds); }
/// <summary> /// Constructor. /// </summary> /// <param name="floor">The floor object.</param> /// <param name="floorProfile">The floor's profile.</param> /// <param name="bBox">The floor's bounding box.</param> public RegularSlab(Floor floor, CurveArray floorProfile, BoundingBoxXYZ bBox) { // Get floor's properties. if (null != floor) { // Get floor's Mark property. Parameter markPara = floor.get_Parameter(BuiltInParameter.ALL_MODEL_MARK); if (null != markPara) { m_mark = markPara.AsString(); } m_level = floor.Document.GetElement(floor.LevelId) as Level; // Get floor's level. m_type = floor.Document.GetElement(floor.GetTypeId()) as ElementType; // Get floor's type. m_id = floor.Id; // Get floor's Id. m_profile = floorProfile; // Get floor's profile. } // Create an octagonal profile for the floor according to it's bounding box. if (null != bBox) { CreateOctagonProfile(bBox.Min, bBox.Max); } }
public static Element FromElementId(DB.Document doc, DB.ElementId id) { if (doc is null || !id.IsValid()) { return(null); } if (Category.FromElementId(doc, id) is Category c) { return(c); } if (ParameterKey.FromElementId(doc, id) is ParameterKey p) { return(p); } if (LinePatternElement.FromElementId(doc, id) is LinePatternElement l) { return(l); } return(FromElement(doc.GetElement(id))); }
public GraphicalElement(DB.Document doc, DB.ElementId id) : base(doc, id) { }
/// <summary> /// Handler method for ViewPrinting event. /// This method will dump EventArgument information of event firstly and then create TextNote element for this view. /// View print will be canceled if TextNote creation failed. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments of ViewPrinting event.</param> public void AppViewPrinting(object sender, Autodesk.Revit.DB.Events.ViewPrintingEventArgs e) { // Setup log file if it still is empty if (null == m_eventsLog) { SetupLogFiles(); } // // header information Trace.WriteLine(System.Environment.NewLine + "View Print Start: ------------------------"); // // Dump the events arguments DumpEventArguments(e); // // Create TextNote for current view, cancel the event if TextNote creation failed bool failureOccured = false; // Reserves whether failure occurred when create TextNote try { String strText = String.Format("Printer Name: {0}{1}User Name: {2}", e.Document.PrintManager.PrinterName, System.Environment.NewLine, System.Environment.UserName); // // Use non-debug compile symbol to write constant text note #if !(Debug || DEBUG) strText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; #endif using (Transaction eventTransaction = new Transaction(e.Document, "External Tool")) { eventTransaction.Start(); TextNoteOptions options = new TextNoteOptions(); options.HorizontalAlignment = HorizontalTextAlignment.Center; options.TypeId = e.Document.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); TextNote newTextNote = TextNote.Create(e.Document, e.View.Id, XYZ.Zero, strText, options); eventTransaction.Commit(); // Check to see whether TextNote creation succeeded if (null != newTextNote) { Trace.WriteLine("Create TextNote element successfully..."); m_newTextNoteId = newTextNote.Id; } else { failureOccured = true; } } } catch (System.Exception ex) { failureOccured = true; Trace.WriteLine("Exception occurred when creating TextNote, print will be canceled, ex: " + ex.Message); } finally { // Cancel the TextNote creation when failure occurred, meantime the event is cancellable if (failureOccured && e.Cancellable) { e.Cancel(); } } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool"); try { transaction.Start(); ElementSet elems = commandData.Application.ActiveUIDocument.Selection.Elements; #region selection error handle //if user have some wrong selection, give user an Error message if (1 != elems.Size) { message = "please select one PathReinforcement."; return(Autodesk.Revit.UI.Result.Cancelled); } Autodesk.Revit.DB.Element selectElem = null; foreach (Autodesk.Revit.DB.Element e in elems) { selectElem = e; } if (!(selectElem is Autodesk.Revit.DB.Structure.PathReinforcement)) { message = "please select one PathReinforcement."; return(Autodesk.Revit.UI.Result.Cancelled); } #endregion //clear all rebar bar type. if (s_rebarBarTypes.Count > 0) { s_rebarBarTypes.Clear(); } //get all bar type. FilteredElementCollector collector = new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document); FilteredElementIterator itor = collector.OfClass(typeof(RebarBarType)).GetElementIterator(); itor.Reset(); while (itor.MoveNext()) { RebarBarType bartype = itor.Current as RebarBarType; if (null != bartype) { Autodesk.Revit.DB.ElementId id = bartype.Id; String name = bartype.Name; s_rebarBarTypes.Add(name, id); } } //Create a form to view the path reinforcement. Autodesk.Revit.DB.Structure.PathReinforcement pathRein = selectElem as Autodesk.Revit.DB.Structure.PathReinforcement; using (PathReinforcementForm form = new PathReinforcementForm(pathRein, commandData)) { form.ShowDialog(); } } catch (Exception e) { transaction.RollBack(); message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } finally { transaction.Commit(); } return(Autodesk.Revit.UI.Result.Succeeded); }
public Category(DB.Document doc, DB.ElementId id) : base(doc, id) { }
/// <summary> /// Find the Nature and Category of the Load Case. /// </summary> /// <returns>A value that signifies whether success(true) or not.</returns> private bool FindProperty() { Parameter pNumber = m_loadCase.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.LOAD_CASE_NUMBER); if (null == pNumber) { m_loadCasesNumber = ""; } m_loadCasesNumber = pNumber.AsInteger().ToString(); Parameter pCategoryid = m_loadCase.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.LOAD_CASE_CATEGORY); m_loadCasesCategoryId = pCategoryid.AsElementId(); Parameter pNatureId = m_loadCase.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.LOAD_CASE_NATURE); m_loadCasesNatureId = pNatureId.AsElementId(); return true; }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded; try { UIDocument activeDoc = commandData.Application.ActiveUIDocument; string str; Material materialElement = null; SelElementSet selection = activeDoc.Selection.Elements; if (selection.Size != 1) { message = "Please select only one element."; res = Autodesk.Revit.UI.Result.Failed; return(res); } System.Collections.IEnumerator iter; iter = activeDoc.Selection.Elements.ForwardIterator(); iter.MoveNext(); // we need verify the selected element is a family instance FamilyInstance famIns = iter.Current as FamilyInstance; if (famIns == null) { TaskDialog.Show("Revit", "Not a type of FamilyInsance!"); res = Autodesk.Revit.UI.Result.Failed; return(res); } // we need select a column instance foreach (Parameter p in famIns.Parameters) { string parName = p.Definition.Name; // The "Beam Material" and "Column Material" family parameters have been replaced // by the built-in parameter "Structural Material". //if (parName == "Column Material" || parName == "Beam Material") if (parName == "Structural Material") { Autodesk.Revit.DB.ElementId elemId = p.AsElementId(); materialElement = activeDoc.Document.GetElement(elemId) as Material; break; } } if (materialElement == null) { TaskDialog.Show("Revit", "Not a column!"); res = Autodesk.Revit.UI.Result.Failed; return(res); } // the PHY_MATERIAL_PARAM_TYPE built in parameter contains a number // that represents the type of material Parameter materialType = materialElement.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_TYPE); str = "Material type: " + (materialType.AsInteger() == 0 ? "Generic" : (materialType.AsInteger() == 1 ? "Concrete" : "Steel")) + "\r\n"; // A material type of more than 0 : 0 = Generic, 1 = Concrete, 2 = Steel if (materialType.AsInteger() > 0) { // Common to all types // Young's Modulus double[] youngsModulus = new double[3]; youngsModulus[0] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD1).AsDouble(); youngsModulus[1] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD2).AsDouble(); youngsModulus[2] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD3).AsDouble(); str = str + "Young's modulus: " + youngsModulus[0].ToString() + "," + youngsModulus[1].ToString() + "," + youngsModulus[2].ToString() + "\r\n"; // Poisson Modulus double[] PoissonRatio = new double[3]; PoissonRatio[0] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD1).AsDouble(); PoissonRatio[1] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD2).AsDouble(); PoissonRatio[2] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD3).AsDouble(); str = str + "Poisson modulus: " + PoissonRatio[0].ToString() + "," + PoissonRatio[1].ToString() + "," + PoissonRatio[2].ToString() + "\r\n"; // Shear Modulus double[] shearModulus = new double[3]; shearModulus[0] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD1).AsDouble(); shearModulus[1] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD2).AsDouble(); shearModulus[2] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD3).AsDouble(); str = str + "Shear modulus: " + shearModulus[0].ToString() + "," + shearModulus[1].ToString() + "," + shearModulus[2].ToString() + "\r\n"; // Thermal Expansion Coefficient double[] thermalExpCoeff = new double[3]; thermalExpCoeff[0] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF1).AsDouble(); thermalExpCoeff[1] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF2).AsDouble(); thermalExpCoeff[2] = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF3).AsDouble(); str = str + "Thermal expansion coefficient: " + thermalExpCoeff[0].ToString() + "," + thermalExpCoeff[1].ToString() + "," + thermalExpCoeff[2].ToString() + "\r\n"; // Unit Weight double unitWeight; unitWeight = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_UNIT_WEIGHT).AsDouble(); str = str + "Unit weight: " + unitWeight.ToString() + "\r\n"; // Damping Ratio double dampingRatio; dampingRatio = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_DAMPING_RATIO).AsDouble(); str = str + "Damping ratio: " + dampingRatio.ToString() + "\r\n"; // Behavior 0 = Isotropic, 1 = Orthotropic int behaviour; behaviour = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_BEHAVIOR).AsInteger(); str = str + "Behavior: " + behaviour.ToString() + "\r\n"; // Concrete Only if (materialType.AsInteger() == 1) { // Concrete Compression double concreteCompression; concreteCompression = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_CONCRETE_COMPRESSION).AsDouble(); str = str + "Concrete compression: " + concreteCompression.ToString() + "\r\n"; // Lightweight double lightWeight; lightWeight = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_LIGHT_WEIGHT).AsDouble(); str = str + "Lightweight: " + lightWeight.ToString() + "\r\n"; // Shear Strength Reduction double shearStrengthReduction; shearStrengthReduction = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_STRENGTH_REDUCTION).AsDouble(); str = str + "Shear strength reduction: " + shearStrengthReduction.ToString() + "\r\n"; } // Steel only else if (materialType.AsInteger() == 2) { // Minimum Yield Stress double minimumYieldStress; minimumYieldStress = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_YIELD_STRESS).AsDouble(); str = str + "Minimum yield stress: " + minimumYieldStress.ToString() + "\r\n"; // Minimum Tensile Strength double minimumTensileStrength; minimumTensileStrength = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_TENSILE_STRENGTH).AsDouble(); str = str + "Minimum tensile strength: " + minimumTensileStrength.ToString() + "\r\n"; // Reduction Factor double reductionFactor; reductionFactor = materialElement.get_Parameter( BuiltInParameter.PHY_MATERIAL_PARAM_REDUCTION_FACTOR).AsDouble(); str = str + "Reduction factor: " + reductionFactor.ToString() + "\r\n"; } // end of if/else materialType.Integer == 1 } // end if materialType.Integer > 0 TaskDialog.Show("Physical materials", str); } catch (Exception ex) { TaskDialog.Show("PhysicalProp", ex.Message); res = Autodesk.Revit.UI.Result.Failed; } finally { } return(res); } // end command
/// <summary> /// Constructor /// </summary> /// <param name="es"></param> public ElectricalSystemItem(ElectricalSystem es) { m_name = es.Name; m_id = es.Id; }
/// <summary> /// Set Level /// </summary> /// <param name="levelIDValue">Pass a Level's ID value</param> /// <param name="levelName">Pass a Level's Name</param> /// <param name="levelElevation">Pass a Level's Elevation</param> /// <returns>True if succeed, else return false</returns> public bool SetLevel(int levelIDValue, String levelName, double levelElevation) { try { Autodesk.Revit.DB.ElementId levelID = new Autodesk.Revit.DB.ElementId(levelIDValue); Level systemLevel = m_revit.Application.ActiveUIDocument.Document.get_Element(levelID) as Level; Parameter elevationPara = systemLevel.get_Parameter(BuiltInParameter.LEVEL_ELEV); elevationPara.SetValueString(levelElevation.ToString()); systemLevel.Name = levelName; return true; } catch (Exception) { return false; } }
/// <summary> /// provide Autodesk.Revit.DB.ElementId collection /// </summary> /// <param name="context"></param> /// <returns></returns> public override StandardValuesCollection GetStandardValues( ITypeDescriptorContext context) { ParameterConverter.StandardValuesCollection standardValues= null; Autodesk.Revit.DB.ElementId[] Ids = new Autodesk.Revit.DB.ElementId[m_hash.Values.Count]; int i = 0; foreach (DictionaryEntry de in m_hash) { Ids[i++] = (Autodesk.Revit.DB.ElementId)(de.Value); } standardValues = new StandardValuesCollection(Ids); return standardValues; }
void handleMessage(MessageBuffer buf, int msgType,Document doc,UIDocument uidoc) { // create Avatar object if not present /* if (avatarObject == null) { createAvatar(doc,uidoc); }*/ switch ((MessageTypes)msgType) { case MessageTypes.SetParameter: { int elemID = buf.readInt(); int paramID = buf.readInt(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); foreach (Autodesk.Revit.DB.Parameter para in elem.Parameters) { if (para.Id.IntegerValue == paramID) { switch (para.StorageType) { case Autodesk.Revit.DB.StorageType.Double: double d = buf.readDouble(); try { para.Set(d); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } d = para.AsDouble(); break; case Autodesk.Revit.DB.StorageType.ElementId: //find out the name of the element int tmpid = buf.readInt(); Autodesk.Revit.DB.ElementId eleId = new Autodesk.Revit.DB.ElementId(tmpid); try { para.Set(eleId); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; case Autodesk.Revit.DB.StorageType.Integer: try { para.Set(buf.readInt()); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; case Autodesk.Revit.DB.StorageType.String: try { para.Set(buf.readString()); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; default: try { para.SetValueString(buf.readString()); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; } } } } break; case MessageTypes.SetTransform: { int elemID = buf.readInt(); double x = buf.readDouble(); double y = buf.readDouble(); double z = buf.readDouble(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(x, y, z); Autodesk.Revit.DB.LocationCurve ElementPosCurve = elem.Location as Autodesk.Revit.DB.LocationCurve; if (ElementPosCurve != null) ElementPosCurve.Move(translationVec); Autodesk.Revit.DB.LocationPoint ElementPosPoint = elem.Location as Autodesk.Revit.DB.LocationPoint; if (ElementPosPoint != null) ElementPosPoint.Move(translationVec); } break; case MessageTypes.UpdateView: { int elemID = buf.readInt(); double ex = buf.readDouble(); double ey = buf.readDouble(); double ez = buf.readDouble(); double dx = buf.readDouble(); double dy = buf.readDouble(); double dz = buf.readDouble(); double ux = buf.readDouble(); double uy = buf.readDouble(); double uz = buf.readDouble(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); Autodesk.Revit.DB.View3D v3d = (Autodesk.Revit.DB.View3D)elem; Autodesk.Revit.DB.ViewOrientation3D ori = new Autodesk.Revit.DB.ViewOrientation3D(new Autodesk.Revit.DB.XYZ(ex, ey, ez), new Autodesk.Revit.DB.XYZ(ux, uy, uz), new Autodesk.Revit.DB.XYZ(dx, dy, dz)); v3d.SetOrientation(ori); } break; case MessageTypes.AvatarPosition: { double ex = buf.readDouble(); double ey = buf.readDouble(); double ez = buf.readDouble(); double dx = buf.readDouble(); double dy = buf.readDouble(); double dz = buf.readDouble(); Level currentLevel = getLevel(doc, ez); string lev = ""; if (currentLevel != null) { lev = currentLevel.Name; } Room testRaum = getRoom(doc, ex, ey, ez); XYZ point = new XYZ(ex, ey, ez); Room currentRoom = doc.GetRoomAtPoint(point); if (currentRoom == null) { point = new XYZ(ex, ey, currentLevel.ProjectElevation); currentRoom = doc.GetRoomAtPoint(point); if (currentRoom == null) currentRoom = testRaum; } if (currentRoom != null) { string nr = currentRoom.Number; string name = currentRoom.Name; double area = currentRoom.Area; MessageBuffer mb = new MessageBuffer(); mb.add(nr); mb.add(name); mb.add(area); mb.add(lev); sendMessage(mb.buf, MessageTypes.RoomInfo); } else { string nr = "-1"; string name = "No Room"; double area = 0.0; MessageBuffer mb = new MessageBuffer(); mb.add(nr); mb.add(name); mb.add(area); mb.add(lev); sendMessage(mb.buf, MessageTypes.RoomInfo); } if (avatarObject != null) { /* Autodesk.Revit.DB.LocationCurve ElementPosCurve = avatarObject.Location as Autodesk.Revit.DB.LocationCurve; Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(ex, ey, ez); ElementPosCurve.Move(translationVec);*/ } } break; } }
public Autodesk.Revit.UI.Result Execute( ExternalCommandData revit, ref string message, ElementSet elements) { try { // Get the active document and view UIDocument revitDoc = revit.Application.ActiveUIDocument; Autodesk.Revit.DB.View view = revitDoc.Document.ActiveView; foreach (Autodesk.Revit.DB.Element elem in revitDoc.Selection.Elements) { //if( elem.GetType() == typeof( Autodesk.Revit.DB.Structure.Rebar ) ) if (elem is Rebar) { string str = ""; Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem; ParameterSet pars = rebar.Parameters; foreach (Parameter param in pars) { string val = ""; string name = param.Definition.Name; Autodesk.Revit.DB.StorageType type = param.StorageType; switch (type) { case Autodesk.Revit.DB.StorageType.Double: val = param.AsDouble().ToString(); break; case Autodesk.Revit.DB.StorageType.ElementId: Autodesk.Revit.DB.ElementId id = param.AsElementId(); Autodesk.Revit.DB.Element paraElem = revitDoc.Document.get_Element(id); if (paraElem != null) { val = paraElem.Name; } break; case Autodesk.Revit.DB.StorageType.Integer: val = param.AsInteger().ToString(); break; case Autodesk.Revit.DB.StorageType.String: val = param.AsString(); break; default: break; } str = str + name + ": " + val + "\r\n"; } MessageBox.Show(str, "Rebar parameters"); return(Autodesk.Revit.UI.Result.Succeeded); } } message = "No rebar selected!"; return(Autodesk.Revit.UI.Result.Failed); } catch (Exception e) { message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } }
public static Dictionary <string, object> ExportMassToGBXML(string FilePath, AbstractFamilyInstance MassFamilyInstance, List <AbstractFamilyInstance> MassShadingInstances, Boolean Run = false) { // Local variables Boolean IsSuccess = false; string FileName = string.Empty; string Folder = string.Empty; // Check if path and directory valid if (System.String.IsNullOrEmpty(FilePath) || FilePath == "No file selected.") { throw new Exception("No File selected !"); } FileName = Path.GetFileNameWithoutExtension(FilePath); Folder = Path.GetDirectoryName(FilePath); // Check if Directory Exists if (!Directory.Exists(Folder)) { throw new Exception("Folder doesn't exist. Input valid Directory Path!"); } //make RUN? inputs set to True mandatory if (Run == false) { throw new Exception("Set 'Connect' to True!"); } //local variables Document RvtDoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument.Document; //enable the analytical model in the document if it isn't already try { PrepareEnergyModel.ActivateEnergyModel(RvtDoc); } catch (Exception) { throw new Exception("Something went wrong when trying to enable the energy model."); } //get the id of the analytical model associated with that mass Autodesk.Revit.DB.ElementId myEnergyModelId = MassEnergyAnalyticalModel.GetMassEnergyAnalyticalModelIdForMassInstance(RvtDoc, MassFamilyInstance.InternalElement.Id); if (myEnergyModelId.IntegerValue == -1) { throw new Exception("Could not get the MassEnergyAnalyticalModel from the mass - make sure the Mass has at least one Mass Floor."); } MassEnergyAnalyticalModel mea = (MassEnergyAnalyticalModel)RvtDoc.GetElement(myEnergyModelId); ICollection <Autodesk.Revit.DB.ElementId> ZoneIds = mea.GetMassZoneIds(); // get shading Ids List <Autodesk.Revit.DB.ElementId> ShadingIds = new List <Autodesk.Revit.DB.ElementId>(); for (int i = 0; i < MassShadingInstances.Count(); i++) { // make sure input mass is valid as a shading if (MassInstanceUtils.GetMassLevelDataIds(RvtDoc, MassShadingInstances[i].InternalElement.Id).Count() > 0) { throw new Exception("Item " + i.ToString() + " in MassShadingInstances has mass floors assigned. Remove the mass floors and try again."); } ShadingIds.Add(MassShadingInstances[i].InternalElement.Id); } if (ShadingIds.Count != 0) { MassGBXMLExportOptions gbXmlExportOptions = new MassGBXMLExportOptions(ZoneIds.ToList(), ShadingIds); // two constructors RvtDoc.Export(Folder, FileName, gbXmlExportOptions); } else { MassGBXMLExportOptions gbXmlExportOptions = new MassGBXMLExportOptions(ZoneIds.ToList()); // two constructors RvtDoc.Export(Folder, FileName, gbXmlExportOptions); } // if the file exists return success message if not return failed message string path = Path.Combine(Folder, FileName + ".xml"); if (System.IO.File.Exists(path)) { // Modify the xml Program Info element, aithorize the XmlDocument doc = new XmlDocument(); doc.Load(path); // EE: There must be a shorter way ! XmlNode node = doc.DocumentElement; foreach (XmlNode node1 in node.ChildNodes) { foreach (XmlNode node2 in node1.ChildNodes) { if (node2.Name == "ProgramInfo") { foreach (XmlNode childnode in node2.ChildNodes) { if (childnode.Name == "ProductName") { string productname = "Dynamo _ " + childnode.InnerText; childnode.InnerText = productname; } } } } } //doc.DocumentElement.Attributes["ProgramInfo"].ChildNodes[1].Value += "Dynamo "; doc.Save(path); IsSuccess = true; } string message = "Failed to create gbXML file!"; if (IsSuccess) { message = "Success! The gbXML file was created"; } else { path = string.Empty; } // Populate Output Values return(new Dictionary <string, object> { { "report", message }, { "gbXMLPath", path } }); }
/// <summary> /// Use Autodesk.Revit.DB.ElementId to get the corresponding element /// </summary> /// <param name="id">the element id value</param> /// <returns>the corresponding element</returns> Autodesk.Revit.DB.Element GetElementById(int id) { // Create a Autodesk.Revit.DB.ElementId data Autodesk.Revit.DB.ElementId elementId = new Autodesk.Revit.DB.ElementId(id); // Get the corresponding element return m_revit.ActiveUIDocument.Document.get_Element(elementId); }
public Material(DB.Document doc, DB.ElementId id) : base(doc, id) { }
/// <summary> /// Handler method for ViewPrinting event. /// This method will dump EventArgument information of event firstly and then create TextNote element for this view. /// View print will be cancelled if TextNote creation failed. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments of ViewPrinting event.</param> public void AppViewPrinting(object sender, Autodesk.Revit.DB.Events.ViewPrintingEventArgs e) { // Setup log file if it still is empty if (null == m_eventsLog) { SetupLogFiles(); } // // header information Trace.WriteLine(System.Environment.NewLine + "View Print Start: ------------------------"); // // Dump the events arguments DumpEventArguments(e); // // Create TextNote for current view, cancel the event if TextNote creation failed bool faileOccur = false; // Reserves whether failure occurred when create TextNote try { String strText = String.Format("Printer Name: {0}{1}User Name: {2}", e.Document.PrintManager.PrinterName, System.Environment.NewLine, System.Environment.UserName); // // Use non-debug compile symbol to write constant text note #if !(Debug || DEBUG) strText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; #endif //now event framework will not provide transaction, user need start by self(2009/11/18) Transaction eventTransaction = new Transaction(e.Document, "External Tool"); eventTransaction.Start(); TextNote newTextNote = e.Document.Create.NewTextNote( e.View, // View new Autodesk.Revit.DB.XYZ (0, 0, 0), // origin new Autodesk.Revit.DB.XYZ (1.0, 0.0, 0.0), // baseVec new Autodesk.Revit.DB.XYZ (0.0, 1.0, 0.0), // upVec 1.0, // lineWidth Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_CENTER, // textAlign strText ); eventTransaction.Commit(); // // Check to see whether TextNote creation succeeded if(null != newTextNote) { Trace.WriteLine("Create TextNote element successfully..."); m_newTextNoteId = new ElementId(newTextNote.Id.IntegerValue); } else { faileOccur = true; } } catch (System.Exception ex) { faileOccur = true; Trace.WriteLine("Exception occurred when creating TextNote, print will be cancelled, ex: " + ex.Message); } finally { // Cancel the TextNote creation when failure occurred, meantime the event is cancellable if(faileOccur && e.Cancellable) { e.Cancel(); } } }
public StructuralAssetElement(DB.Document doc, DB.ElementId id) : base(doc, id) { }
void handleMessage(MessageBuffer buf, int msgType,Document doc,UIDocument uidoc, UIApplication app) { // create Avatar object if not present /* if (avatarObject == null) { createAvatar(doc,uidoc); }*/ switch ((MessageTypes)msgType) { case MessageTypes.Resend: { Autodesk.Revit.DB.FilteredElementCollector collector = new Autodesk.Revit.DB.FilteredElementCollector(uidoc.Document); COVER.Instance.SendGeometry(collector.WhereElementIsNotElementType().GetElementIterator(), app); ElementClassFilter FamilyFilter = new ElementClassFilter(typeof(FamilySymbol)); FilteredElementCollector FamilyCollector = new FilteredElementCollector(uidoc.Document); ICollection<Element> AllFamilies = FamilyCollector.WherePasses(FamilyFilter).ToElements(); foreach (FamilySymbol Fmly in AllFamilies) { COVER.Instance.sendFamilySymbolParameters(Fmly); } } break; case MessageTypes.SetParameter: { int elemID = buf.readInt(); int paramID = buf.readInt(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); foreach (Autodesk.Revit.DB.Parameter para in elem.Parameters) { if (para.Id.IntegerValue == paramID) { switch (para.StorageType) { case Autodesk.Revit.DB.StorageType.Double: double d = buf.readDouble(); try { para.Set(d); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } d = para.AsDouble(); break; case Autodesk.Revit.DB.StorageType.ElementId: //find out the name of the element int tmpid = buf.readInt(); Autodesk.Revit.DB.ElementId eleId = new Autodesk.Revit.DB.ElementId(tmpid); try { para.Set(eleId); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; case Autodesk.Revit.DB.StorageType.Integer: try { para.Set(buf.readInt()); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; case Autodesk.Revit.DB.StorageType.String: try { para.Set(buf.readString()); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; default: try { para.SetValueString(buf.readString()); } catch { Autodesk.Revit.UI.TaskDialog.Show("Double", "para.Set failed"); } break; } } } } break; case MessageTypes.SetTransform: { int elemID = buf.readInt(); double x = buf.readDouble(); double y = buf.readDouble(); double z = buf.readDouble(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(x, y, z); Autodesk.Revit.DB.LocationCurve ElementPosCurve = elem.Location as Autodesk.Revit.DB.LocationCurve; if (ElementPosCurve != null) ElementPosCurve.Move(translationVec); Autodesk.Revit.DB.LocationPoint ElementPosPoint = elem.Location as Autodesk.Revit.DB.LocationPoint; if (ElementPosPoint != null) ElementPosPoint.Move(translationVec); } break; case MessageTypes.UpdateView: { int elemID = buf.readInt(); double ex = buf.readDouble(); double ey = buf.readDouble(); double ez = buf.readDouble(); double dx = buf.readDouble(); double dy = buf.readDouble(); double dz = buf.readDouble(); double ux = buf.readDouble(); double uy = buf.readDouble(); double uz = buf.readDouble(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); Autodesk.Revit.DB.View3D v3d = (Autodesk.Revit.DB.View3D)elem; Autodesk.Revit.DB.ViewOrientation3D ori = new Autodesk.Revit.DB.ViewOrientation3D(new Autodesk.Revit.DB.XYZ(ex, ey, ez), new Autodesk.Revit.DB.XYZ(ux, uy, uz), new Autodesk.Revit.DB.XYZ(dx, dy, dz)); v3d.SetOrientation(ori); } break; case MessageTypes.NewAnnotation: { int labelNumber = buf.readInt(); double x = buf.readDouble(); double y = buf.readDouble(); double z = buf.readDouble(); double h = buf.readDouble(); double p = buf.readDouble(); double r = buf.readDouble(); string labelText = buf.readString(); Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(x, y, z); Autodesk.Revit.DB.View view = document.ActiveView; ElementId currentTextTypeId = document.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); Autodesk.Revit.DB.TextNote tn = Autodesk.Revit.DB.TextNote.Create(document, view.Id, translationVec, labelText, currentTextTypeId); // send back revit ID corresponding to this annotationID // the mapping of annotationIDs to Revit element IDs is done in OpenCOVER MessageBuffer mb = new MessageBuffer(); mb.add(labelNumber); mb.add(tn.Id.IntegerValue); sendMessage(mb.buf, MessageTypes.NewAnnotationID); } break; case MessageTypes.ChangeAnnotation: { int elemID = buf.readInt(); double x = buf.readDouble(); double y = buf.readDouble(); double z = buf.readDouble(); double h = buf.readDouble(); double p = buf.readDouble(); double r = buf.readDouble(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); Autodesk.Revit.DB.TextNote tn = elem as Autodesk.Revit.DB.TextNote; if (tn != null) { Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(x, y, z); tn.Coord = translationVec; } } break; case MessageTypes.SetView: { int currentView = buf.readInt(); List<View3D> views = new List<View3D>( new FilteredElementCollector(doc) .OfClass(typeof(View3D)) .Cast<View3D>() .Where<View3D>(v => v.CanBePrinted && !v.IsTemplate)); int n = 0; foreach (View3D v in views) { if (n == currentView) { try { uidoc.ActiveView = v; } catch (Autodesk.Revit.Exceptions.ArgumentNullException e) { Console.WriteLine("Exception information: {0}", e); } catch (Autodesk.Revit.Exceptions.ArgumentException e) { Console.WriteLine("Exception information: {0}", e); } catch (Autodesk.Revit.Exceptions.InvalidOperationException e) { Console.WriteLine("Exception information: {0}", e); } break; } n++; } } break; case MessageTypes.ChangeAnnotationText: { int elemID = buf.readInt(); string labelText = buf.readString(); Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(elemID); Autodesk.Revit.DB.Element elem = document.GetElement(id); Autodesk.Revit.DB.TextNote tn = elem as Autodesk.Revit.DB.TextNote; if (tn != null) { tn.Text = labelText; } } break; case MessageTypes.AvatarPosition: { double ex = buf.readDouble(); double ey = buf.readDouble(); double ez = buf.readDouble(); double dx = buf.readDouble(); double dy = buf.readDouble(); double dz = buf.readDouble(); Level currentLevel = getLevel(doc, ez); string lev = ""; if (currentLevel != null) { lev = currentLevel.Name; } Room testRaum = null; Room currentRoom = null; try { XYZ point = new XYZ(ex, ey, ez); currentRoom = doc.GetRoomAtPoint(point); if (currentRoom == null && (currentLevel != null)) { point = new XYZ(ex, ey, currentLevel.ProjectElevation); currentRoom = doc.GetRoomAtPoint(point); if (currentRoom == null) { testRaum = getRoom(doc, ex, ey, ez); currentRoom = testRaum; } } } catch { } if (currentRoom != null) { string nr = currentRoom.Number; string name = currentRoom.Name; double area = currentRoom.Area; MessageBuffer mb = new MessageBuffer(); mb.add(nr); mb.add(name); mb.add(area); mb.add(lev); sendMessage(mb.buf, MessageTypes.RoomInfo); } else { string nr = "-1"; string name = "No Room"; double area = 0.0; MessageBuffer mb = new MessageBuffer(); mb.add(nr); mb.add(name); mb.add(area); mb.add(lev); sendMessage(mb.buf, MessageTypes.RoomInfo); } if (avatarObject != null) { /* Autodesk.Revit.DB.LocationCurve ElementPosCurve = avatarObject.Location as Autodesk.Revit.DB.LocationCurve; Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(ex, ey, ez); ElementPosCurve.Move(translationVec);*/ } } break; } }
public static Element FromElementId(DB.Document doc, DB.ElementId id) { if (doc is null || id is null) { return(default);
/// <summary> /// constructor of class /// </summary> /// <param name="pathRein"></param> public PathReinProperties(Autodesk.Revit.DB.Structure.PathReinforcement pathRein) { m_pathRein = pathRein; m_layoutRule = (LayoutRule)GetParameter("Layout Rule").AsInteger(); m_face = (Face)GetParameter("Face").AsInteger(); m_numberOfBars = m_pathRein.get_Parameter( BuiltInParameter.PATH_REIN_NUMBER_OF_BARS).AsInteger(); m_barSpacing = m_pathRein.get_Parameter( BuiltInParameter.PATH_REIN_SPACING).AsValueString(); m_primaryBarLength = m_pathRein.get_Parameter( BuiltInParameter.PATH_REIN_LENGTH_1).AsValueString(); m_primaryBarType = GetParameter("Primary Bar - Type").AsElementId(); }