/// <summary> /// The top level command. /// </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) { // Set reference to the document and then check if this command is run on the inclueded "ResultsInRevit.rvt" file document = commandData.Application.ActiveUIDocument.Document; String outputDocumentPathName = commandData.Application.ActiveUIDocument.Document.PathName + ".ECTesting.txt"; Autodesk.Revit.UI.Result res = Result.Failed; if (document.Title != "ResultsInRevit.rvt") { // Report error if this is a wrong file Autodesk.Revit.UI.TaskDialog.Show("Wrong Revit file", "Cannot use :\n" + document.PathName + "\n\nPlease use attached " + "\"ResultsInRevit.rvt\" file."); } else { // Go ahead and read some results from elements otherwise try { // Set ElementIds for Revit elements and loads used in this example. ElementIds are hardcoded ElementId loadCaseId1 = new ElementId(37232); ElementId loadCaseId2 = new ElementId(37234); ElementId combinationId = new ElementId(261966); ElementId [] loadCaseIds = new ElementId[] { loadCaseId1, loadCaseId2, combinationId }; ResultsPackage resultsPackage = null; try { // Get results package resultsPackage = GetResultsPackage(document); } catch { Autodesk.Revit.UI.TaskDialog.Show("Cannot get result package.", "\nTry to store results first."); } // Read Results from the created result package and store them in the textfile using (System.IO.StreamWriter writer = new System.IO.StreamWriter(outputDocumentPathName, false)) { writer.WriteLine(ReadLinearResults(resultsPackage, linearElementId, loadCaseIds)); writer.WriteLine(ReadArbitraryLinearResults(resultsPackage, linearElementId)); writer.WriteLine(ReadSurfaceResults(resultsPackage, surfaceElementId, loadCaseIds)); writer.WriteLine(ReadArbitrarySurfaceResults(resultsPackage, surfaceElementId)); } res = Result.Succeeded; } catch (Exception ex) { Autodesk.Revit.UI.TaskDialog.Show("Failed to read results from Revit", ex.Message.ToString()); } } return(res); }
/// <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 returnCode = Autodesk.Revit.UI.Result.Cancelled; Transaction tran = new Transaction(commandData.Application.ActiveUIDocument.Document, "Initialize Command"); tran.Start(); try { // one instance of DoorSwingData class. DoorSwingData databuffer = new DoorSwingData(commandData.Application); using (InitializeForm initForm = new InitializeForm(databuffer)) { // Show UI DialogResult dialogResult = initForm.ShowDialog(); if (DialogResult.OK == dialogResult) { databuffer.DeleteTempDoorInstances(); // update door type's opening feature based on family's actual geometry and // country's standard. databuffer.UpdateDoorFamiliesOpeningFeature(); // update each door instance's Opening feature and internal door flag returnCode = DoorSwingData.UpdateDoorsInfo(commandData.Application.ActiveUIDocument.Document, false, true, ref message); } } } catch (Exception ex) { // if there is anything wrong, give error information and return failed. message = ex.Message; returnCode = Autodesk.Revit.UI.Result.Failed; } if (Autodesk.Revit.UI.Result.Succeeded == returnCode) { tran.Commit(); } else { tran.RollBack(); } return(returnCode); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="cmdData">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="msg">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="eleSet">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 cmdData, ref string msg, ElementSet eleSet) { Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded; try { ElementsBatchCreation elementsBatchCreation = new ElementsBatchCreation(cmdData); elementsBatchCreation.CreateElements(); } catch (Exception) { msg = "Batch creation failed"; res = Autodesk.Revit.UI.Result.Failed; } return(res); }
/// <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) { Autodesk.Revit.UI.Result returnCode = Autodesk.Revit.UI.Result.Succeeded; Autodesk.Revit.UI.UIApplication app = commandData.Application; UIDocument doc = app.ActiveUIDocument; Transaction tran = new Transaction(doc.Document, "Update Geometry Command"); tran.Start(); try { ElementSet elementSet = new ElementSet(); foreach (ElementId elementId in doc.Selection.GetElementIds()) { elementSet.Insert(doc.Document.GetElement(elementId)); } if (elementSet.IsEmpty) { DoorSwingData.UpdateDoorsGeometry(doc.Document, false); } else { DoorSwingData.UpdateDoorsGeometry(doc.Document, true); } returnCode = Autodesk.Revit.UI.Result.Succeeded; } catch (Exception ex) { // if there is anything wrong, give error information and return failed. message = ex.Message; returnCode = Autodesk.Revit.UI.Result.Failed; } if (Autodesk.Revit.UI.Result.Succeeded == returnCode) { tran.Commit(); } else { tran.RollBack(); } return(returnCode); }
/// <summary> /// The top level command. /// </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) { Autodesk.Revit.UI.Result retVal = Autodesk.Revit.UI.Result.Succeeded; Document doc = commandData.Application.ActiveUIDocument.Document; // Check if this is the Revit file that is included in this example and display warning if not if (doc.Title != "ResultsInRevit.rvt") { Autodesk.Revit.UI.TaskDialog.Show("Wrong Revit file", "Cannot use :\n" + doc.PathName + "\n\nPlease use attached " + "\"ResultsInRevit.rvt\" file."); retVal = Autodesk.Revit.UI.Result.Failed; } Transaction trans = new Transaction(doc); try { trans.SetName("ResultsInRevit_Transaction"); trans.Start(); // Create new instance of empty result builder ResultsPackageBuilder resultsPackageBuilder = createResultsPackageBuilder(doc); // Add analitical results to the linear element for two load cases AddLinearResults(resultsPackageBuilder, linearElementId, new ElementId[] { loadCaseId1, loadCaseId2 }); // Add some arbitrary results to the same element AddArbitraryLinearResults(resultsPackageBuilder, linearElementId); // Add analitical results to the surface element for the same load cases AddSurfaceResults(doc, resultsPackageBuilder, surfaceElementId, new ElementId[] { loadCaseId1, loadCaseId2 }); // Add arbitrary results to the surface element AddArbitrarySurfaceResults(doc, resultsPackageBuilder, surfaceElementId); // End adding and close transaction resultsPackageBuilder.Finish(); trans.Commit(); } catch (Exception ex) { // Rollback transaction and display warning if there were any problems trans.RollBack(); Autodesk.Revit.UI.TaskDialog.Show("Failed to write results to Revit", ex.Message.ToString()); retVal = Autodesk.Revit.UI.Result.Failed; } return(retVal); }
/// <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) { // set out default result to failure. Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed; m_application = commandData.Application.Application; m_document = commandData.Application.ActiveUIDocument.Document; f = m_document.FamilyCreate; extrusions = new Extrusion[5]; m_combineElements = new CombinableElementArray(); m_transaction = new Transaction(m_document, "External Tool"); m_transaction.Start(); if (m_document.OwnerFamily.FamilyCategory.Name != m_document.Settings.Categories.get_Item(BuiltInCategory.OST_MechanicalEquipment).Name) // FamilyCategory.Name is not "Mechanical Equipment". { message = "Please make sure you opened a template of Mechanical Equipment."; return(retRes); } try { CreateExtrusions(); m_document.Regenerate(); CreateConnectors(); m_document.Regenerate(); m_document.CombineElements(m_combineElements); m_document.Regenerate(); } catch (Exception x) { m_transaction.RollBack(); message = x.Message; return(retRes); } m_transaction.Commit(); retRes = Autodesk.Revit.UI.Result.Succeeded; return(retRes); }
/// <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) { Autodesk.Revit.UI.Result returnCode = Autodesk.Revit.UI.Result.Succeeded; Autodesk.Revit.UI.UIApplication app = commandData.Application; UIDocument doc = app.ActiveUIDocument; Transaction tran = new Transaction(doc.Document, "Update Parameters Command"); tran.Start(); try { if (doc.Selection.Elements.IsEmpty) { returnCode = DoorSwingData.UpdateDoorsInfo(doc.Document, false, true, ref message); } else { returnCode = DoorSwingData.UpdateDoorsInfo(doc.Document, true, true, ref message); } } catch (Exception ex) { // if there is anything wrong, give error information and return failed. message = ex.Message; returnCode = Autodesk.Revit.UI.Result.Failed; } if (Autodesk.Revit.UI.Result.Succeeded == returnCode) { tran.Commit(); } else { tran.RollBack(); } return(returnCode); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="cmdData">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="msg">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="eleSet">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 cmdData, ref string msg, ElementSet eleSet) { Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded; try { Properties props = new Properties("../revit_properties.ini"); string pathToSteerSuite = props.get("SteerSuitePath"); string path = Environment.GetEnvironmentVariable("PATH"); path += System.IO.Path.PathSeparator.ToString() + pathToSteerSuite; Environment.SetEnvironmentVariable("PATH", path); Autodesk.Revit.UI.Selection.Selection sel; sel = cmdData.Application.ActiveUIDocument.Selection; UIApplication uiApp = cmdData.Application; Document doc = uiApp.ActiveUIDocument.Document; SimWorld world = new SimWorld(); // Find all Wall instances in the document by using category filter ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); // Apply the filter to the elements in the active document // Use shortcut WhereElementIsNotElementType() to find wall instances only FilteredElementCollector collector = new FilteredElementCollector(doc); IList <Element> walls = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); String prompt = "The walls in the current document are:\n"; const double _feet_to_meters = 0.3048; foreach (Element e in walls) { BoundingBoxXYZ bbox = e.get_BoundingBox(null); List <Solid> solids = new List <Solid>(); Options options = new Options(); options.DetailLevel = ViewDetailLevel.Fine; GeometryElement geomElem = e.get_Geometry(options); String dat = ""; foreach (GeometryObject geomObj in geomElem) { if (geomObj is Solid) { Solid solid = (Solid)geomObj; if (solid.Faces.Size > 0 && solid.Volume > 0.0) { dat += "Faces: " + solid.Faces.ToString(); // solid.Faces.get_Item(0). solids.Add(solid); } // Single-level recursive check of instances. If viable solids are more than // one level deep, this example ignores them. } /* * else if (geomObj is GeometryInstance) * { * GeometryInstance geomInst = (GeometryInstance)geomObj; * GeometryElement instGeomElem = geomInst.GetInstanceGeometry(); * foreach (GeometryObject instGeomObj in instGeomElem) * { * if (instGeomObj is Solid) * { * Solid solid = (Solid)instGeomObj; * if (solid.Faces.Size > 0 && solid.Volume > 0.0) * { * solids.Add(solid); * } * } * } * }*/ } bbox.Min = bbox.Min * _feet_to_meters; bbox.Max = bbox.Max * _feet_to_meters; prompt += bbox.Min.X + ", " + bbox.Max.X + "," + bbox.Min.Z + ", " + bbox.Max.Z + "," + bbox.Min.Y + ", " + bbox.Max.Y + "\n"; world.addObstacle(bbox.Min.X, bbox.Max.X, bbox.Min.Z, bbox.Max.Z, bbox.Min.Y, bbox.Max.Y); } SteerSuite steersuite = new SteerSuite(); steersuite.init(world); // steersuite.simulate(); CMAOptimize steerFunc = new CMAOptimize(world, steersuite); steerFunc.optimize(); steersuite.finish(); System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt"); file.WriteLine(prompt); file.Close(); } catch (Exception ex) { TaskDialog.Show("MoveLinear", ex.Message); res = Autodesk.Revit.UI.Result.Failed; } finally { } return(res); }
/// <summary> /// Implement this method to implement the external application which should be called when /// Revit starts before a file or default template is actually loaded. /// </summary> /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully started. /// Cancelled can be used to signify that the user cancelled the external operation at /// some point. /// If false is returned then Revit should inform the user that the external application /// failed to load and the release the internal reference.</returns> public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { m_application = application; Autodesk.Revit.UI.Result rc = Autodesk.Revit.UI.Result.Failed; string[] lines = null; int n = 0; int k = 0; try { // Check whether the file contains samples' list exists // If not, return failure string filename = m_fileNameStem; if (!GetFilepath(ref filename)) { ErrorMsg(m_fileNameStem + " not found."); return(rc); } // Read all lines from the file lines = ReadAllLinesWithInclude(filename); // Remove comments lines = RemoveComments(lines); // Add default pulldown menus of samples to Revit m_panelRvtSamples = application.CreateRibbonPanel("RvtSamples"); int i = 0; List <PulldownButtonData> pdData = new List <PulldownButtonData>(3); foreach (string category in Enum.GetNames(typeof(DefaultPulldownMenus))) { if ((i + 1) % 3 == 1) { pdData.Clear(); } // // Prepare PulldownButtonData for add stacked buttons operation // string displayName = GetDisplayNameByEnumName(category); List <SampleItem> sampleItems = new List <SampleItem>(); m_defaultMenus.Add(category, sampleItems); PulldownButtonData data = new PulldownButtonData(displayName, displayName); pdData.Add(data); // // Add stacked buttons to RvtSamples panel and set their display names and images // if ((i + 1) % 3 == 0) { IList <RibbonItem> addedButtons = m_panelRvtSamples.AddStackedItems(pdData[0], pdData[1], pdData[2]); foreach (RibbonItem item in addedButtons) { String name = item.ItemText; string enumName = GetEnumNameByDisplayName(name); PulldownButton button = item as PulldownButton; button.Image = new BitmapImage( new Uri(Path.Combine(s_assemblyDirectory, "Icons\\" + enumName + ".ico"), UriKind.Absolute)); button.ToolTip = Properties.Resource.ResourceManager.GetString(enumName); m_pulldownButtons.Add(name, button); } } i++; } // // Add sample items to the pulldown buttons // n = lines.GetLength(0); k = 0; while (k < n) { AddSample(lines, n, ref k); } AddSamplesToDefaultPulldownMenus(); AddCustomizedPulldownMenus(); rc = Autodesk.Revit.UI.Result.Succeeded; } catch (Exception e) { string s = string.Format("{0}: n = {1}, k = {2}, lines[k] = {3}", e.Message, n, k, (k < n ? lines[k] : "eof")); ErrorMsg(s); } return(rc); }
/// <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> /// Implement this method as an external command for Revit. /// </summary> /// <param name="cmdData">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="msg">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="eleSet">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 cmdData, ref string msg, ElementSet eleSet) { Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded; Transaction trans = new Transaction(cmdData.Application.ActiveUIDocument.Document, "Revit.SDK.Samples.MoveLinear"); trans.Start(); try { System.Collections.IEnumerator iter; Autodesk.Revit.UI.Selection.Selection sel; sel = cmdData.Application.ActiveUIDocument.Selection; ElementSet elemSet; elemSet = new ElementSet(); foreach (ElementId elementId in sel.GetElementIds()) { elemSet.Insert(cmdData.Application.ActiveUIDocument.Document.GetElement(elementId)); } //Check whether user has selected only one element if (0 == elemSet.Size) { TaskDialog.Show("MoveLinear", "Please select an element"); trans.Commit(); return(res); } if (1 < elemSet.Size) { TaskDialog.Show("MoveLinear", "Please select only one element"); trans.Commit(); return(res); } iter = elemSet.ForwardIterator(); iter.MoveNext(); Autodesk.Revit.DB.Element element; element = (Autodesk.Revit.DB.Element)iter.Current; if (element != null) { Autodesk.Revit.DB.LocationCurve lineLoc; lineLoc = element.Location as LocationCurve; if (null == lineLoc) { TaskDialog.Show("MoveLinear", "Please select an element which based on a Line"); trans.Commit(); return(res); } Autodesk.Revit.DB.Line line; //get start point via "get_EndPoint(0)" Autodesk.Revit.DB.XYZ newStart = new XYZ( lineLoc.Curve.GetEndPoint(0).X + 100, lineLoc.Curve.GetEndPoint(0).Y, lineLoc.Curve.GetEndPoint(0).Z); //get end point via "get_EndPoint(1)" Autodesk.Revit.DB.XYZ newEnd = new XYZ( lineLoc.Curve.GetEndPoint(1).X, lineLoc.Curve.GetEndPoint(1).Y + 100, lineLoc.Curve.GetEndPoint(1).Z); //get a new line and use it to move current element //with property "Autodesk.Revit.DB.LocationCurve.Curve" line = Line.CreateBound(newStart, newEnd); lineLoc.Curve = line; } } catch (Exception ex) { TaskDialog.Show("MoveLinear", ex.Message); res = Autodesk.Revit.UI.Result.Failed; } finally { } trans.Commit(); return(res); }
/// <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) { // set out default result to failure. Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed; Autodesk.Revit.UI.UIApplication app = commandData.Application; // get the elements selected // The current selection can be retrieved from the active // document via the selection object ElementSet seletion = new ElementSet(); foreach (ElementId elementId in app.ActiveUIDocument.Selection.GetElementIds()) { seletion.Insert(app.ActiveUIDocument.Document.GetElement(elementId)); } // we need to make sure that only one element is selected. if (seletion.Size == 1) { // we need to get the first and only element in the selection. Do this by getting // an iterator. MoveNext and then get the current element. ElementSetIterator it = seletion.ForwardIterator(); it.MoveNext(); Element element = it.Current as Element; // Next we need to iterate through the parameters of the element, // as we iterating, we will store the strings that are to be displayed // for the parameters in a string list "parameterItems" List <string> parameterItems = new List <string>(); ParameterSet parameters = element.Parameters; foreach (Parameter param in parameters) { if (param == null) { continue; } // We will make a string that has the following format, // name type value // create a StringBuilder object to store the string of one parameter // using the character '\t' to delimit parameter name, type and value StringBuilder sb = new StringBuilder(); // the name of the parameter can be found from its definition. sb.AppendFormat("{0}\t", param.Definition.Name); // Is the parameter shared? sb.AppendFormat(param.IsShared.ToString() + "\t"); // Revit parameters can be one of 5 different internal storage types: // double, int, string, Autodesk.Revit.DB.ElementId and None. // if it is double then use AsDouble to get the double value // then int AsInteger, string AsString, None AsStringValue. // Switch based on the storage type switch (param.StorageType) { case Autodesk.Revit.DB.StorageType.Double: // append the type and value sb.AppendFormat("double\t{0}", param.AsDouble()); break; case Autodesk.Revit.DB.StorageType.ElementId: // for element ids, we will try and retrieve the element from the // document if it can be found we will display its name. sb.Append("Element\t"); // using ActiveDocument.GetElement(the element id) to // retrieve the element from the active document Autodesk.Revit.DB.ElementId elemId = new ElementId(param.AsElementId().IntegerValue); Element elem = app.ActiveUIDocument.Document.GetElement(elemId); // if there is an element then display its name, // otherwise display the fact that it is not set sb.Append(elem != null ? elem.Name : "Not set"); break; case Autodesk.Revit.DB.StorageType.Integer: // append the type and value sb.AppendFormat("int\t{0}", param.AsInteger()); break; case Autodesk.Revit.DB.StorageType.String: // append the type and value sb.AppendFormat("string\t{0}", param.AsString()); break; case Autodesk.Revit.DB.StorageType.None: // append the type and value sb.AppendFormat("none\t{0}", param.AsValueString()); break; default: break; } // add the completed line to the string list parameterItems.Add(sb.ToString()); } // Create our dialog, passing it the parameters array for display. PropertiesForm propertiesForm = new PropertiesForm(parameterItems.ToArray()); propertiesForm.StartPosition = FormStartPosition.CenterParent; propertiesForm.ShowDialog(); retRes = Autodesk.Revit.UI.Result.Succeeded; } else { message = "Please select only one element"; } return(retRes); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="cmdData">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="msg">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="eleSet">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 cmdData, ref string msg, ElementSet eleSet) { Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded; try { System.Collections.IEnumerator iter; Autodesk.Revit.UI.Selection.Selection sel; sel = cmdData.Application.ActiveUIDocument.Selection; ElementSet elemSet; elemSet = sel.Elements; //Check whether user has selected only one element if (0 == elemSet.Size) { MessageBox.Show("Please select an element", "MoveLinear"); return(res); } if (1 < elemSet.Size) { MessageBox.Show("Please select only one element", "MoveLinear"); return(res); } iter = elemSet.ForwardIterator(); iter.MoveNext(); Autodesk.Revit.DB.Element element; element = (Autodesk.Revit.DB.Element)iter.Current; if (element != null) { Autodesk.Revit.DB.LocationCurve lineLoc; lineLoc = element.Location as LocationCurve; if (null == lineLoc) { MessageBox.Show("Please select an element which based on a Line", "MoveLinear"); return(res); } Autodesk.Revit.DB.Line line; //get start point via "get_EndPoint(0)" Autodesk.Revit.DB.XYZ newStart = new XYZ( lineLoc.Curve.get_EndPoint(0).X + 100, lineLoc.Curve.get_EndPoint(0).Y, lineLoc.Curve.get_EndPoint(0).Z); //get end point via "get_EndPoint(1)" Autodesk.Revit.DB.XYZ newEnd = new XYZ( lineLoc.Curve.get_EndPoint(1).X, lineLoc.Curve.get_EndPoint(1).Y + 100, lineLoc.Curve.get_EndPoint(1).Z); //get a new line and use it to move current element //with property "Autodesk.Revit.DB.LocationCurve.Curve" line = cmdData.Application.Application.Create.NewLineBound(newStart, newEnd); lineLoc.Curve = line; } } catch (Exception ex) { MessageBox.Show(ex.Message, "MoveLinear"); res = Autodesk.Revit.UI.Result.Failed; } finally { } return(res); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="cmdData">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="msg">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="eleSet">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 cmdData, ref string msg, ElementSet eleSet) { Autodesk.Revit.UI.Result res = Autodesk.Revit.UI.Result.Succeeded; try { Properties props = new Properties("../revit_properties.ini"); string pathToSteerSuite = props.get("SteerSuitePath"); string path = Environment.GetEnvironmentVariable("PATH"); path += System.IO.Path.PathSeparator.ToString() + pathToSteerSuite; Environment.SetEnvironmentVariable("PATH", path); Autodesk.Revit.UI.Selection.Selection sel; sel = cmdData.Application.ActiveUIDocument.Selection; UIApplication uiApp = cmdData.Application; Document doc = uiApp.ActiveUIDocument.Document; // Find all Wall instances in the document by using category filter ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); // Apply the filter to the elements in the active document // Use shortcut WhereElementIsNotElementType() to find wall instances only FilteredElementCollector collector = new FilteredElementCollector(doc); // IList<ElementId> verts_refs = new List<ElementId>(); IList <XYZ> verts = new List <XYZ>(); IList <List <int> > edges = new List <List <int> >(); IList <Element> walls = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); String prompt = ""; const double _feet_to_meters = 0.3048; foreach (Element e in walls) { BoundingBoxXYZ bbox = e.get_BoundingBox(null); Autodesk.Revit.DB.LocationCurve lineLoc; lineLoc = e.Location as LocationCurve; List <Solid> solids = new List <Solid>(); Options options = new Options(); options.DetailLevel = ViewDetailLevel.Fine; GeometryElement geomElem = e.get_Geometry(options); String dat = ""; /* * foreach (GeometryObject geomObj in geomElem) * { * if (geomObj is Solid) * { * Solid solid = (Solid)geomObj; * * if (solid.Faces.Size > 0 && solid.Volume > 0.0) * { * dat += "Faces: " + solid.Faces.ToString(); * // solid.Faces.get_Item(0). * * solids.Add(solid); * } * // Single-level recursive check of instances. If viable solids are more than * // one level deep, this example ignores them. * } * /* * else if (geomObj is GeometryInstance) * { * GeometryInstance geomInst = (GeometryInstance)geomObj; * GeometryElement instGeomElem = geomInst.GetInstanceGeometry(); * foreach (GeometryObject instGeomObj in instGeomElem) * { * if (instGeomObj is Solid) * { * Solid solid = (Solid)instGeomObj; * if (solid.Faces.Size > 0 && solid.Volume > 0.0) * { * solids.Add(solid); * } * } * } * } * }*/ List <int> edge_ = new List <int>(); Reference ref_ = lineLoc.Curve.GetEndPointReference(0); // TaskDialog.Show("ElementID", "" + ref_); Autodesk.Revit.DB.XYZ origin = lineLoc.Curve.GetEndPoint(0); bool contains = false; int or = 0, ed = 0; for (int i = 0; i < verts.Count; i++) { XYZ p = verts[i]; double l = Math.Sqrt(Math.Pow((p.X - origin.X), 2) + Math.Pow((p.Y - origin.Y), 2) + Math.Pow((p.Z - origin.Z), 2)); if (l < 0.001) { contains = true; or = i; break; } } Autodesk.Revit.DB.XYZ end = lineLoc.Curve.GetEndPoint(1); if (!contains) { or = verts.Count; verts.Add(origin); // prompt += "<" + origin.X + ", " + origin.Z + ", " + origin.Y + ">\n"; } contains = false; for (int i = 0; i < verts.Count; i++) { XYZ p = verts[i]; double l = Math.Sqrt(Math.Pow((p.X - end.X), 2) + Math.Pow((p.Y - end.Y), 2) + Math.Pow((p.Z - end.Z), 2)); if (l < 0.001) { contains = true; ed = i; break; } } if (!contains) { ed = verts.Count; verts.Add(end); // prompt += "<" + end.X + ", " + end.Z + ", " + end.Y + ">\n"; } // Autodesk.Revit.DB.XYZ origin = lineLoc.Curve.GetEndPoint(0); // Autodesk.Revit.DB.XYZ end = lineLoc.Curve.GetEndPoint(1); // Reference ref_ = lineLoc.Curve.GetEndPointReference(0); bbox.Min = bbox.Min * _feet_to_meters; bbox.Max = bbox.Max * _feet_to_meters; edge_.Add(or); edge_.Add(ed); edges.Add(edge_); // prompt += "<" + origin.X + ", " + origin.Z + ", " + origin.Y + "> - " + // "<" + end.X + ", " + end.Z + ", " + end.Y + ">\n"; // prompt += bbox.Min.X + ", " + bbox.Max.X + "," + bbox.Min.Z + ", " + bbox.Max.Z + "," + // bbox.Min.Y + ", " + bbox.Max.Y + "\n"; } foreach (XYZ p in verts) { // converted axis here XYZ po = p * _feet_to_meters; prompt += "v " + po.X + " " + po.Z + " " + po.Y + "\n"; } prompt += "\n"; foreach (List <int> edge_ in edges) { prompt += "e " + edge_[0] + " " + edge_[1] + "\n"; } System.IO.StreamWriter file = new System.IO.StreamWriter(pathToSteerSuite + "test.txt"); file.WriteLine(prompt); file.Close(); /* * if (element != null) * { * Autodesk.Revit.DB.LocationCurve lineLoc; * lineLoc = element.Location as LocationCurve; * * if (null == lineLoc) * { * TaskDialog.Show("MoveLinear", "Please select an element which based on a Line"); * return res; * } * * Autodesk.Revit.DB.Line line; * //get start point via "get_EndPoint(0)" * Autodesk.Revit.DB.XYZ newStart = new XYZ( * lineLoc.Curve.GetEndPoint(0).X + 15, * lineLoc.Curve.GetEndPoint(0).Y, * lineLoc.Curve.GetEndPoint(0).Z); * //get end point via "get_EndPoint(1)" * Autodesk.Revit.DB.XYZ newEnd = new XYZ( * lineLoc.Curve.GetEndPoint(1).X + 15, * lineLoc.Curve.GetEndPoint(1).Y, * lineLoc.Curve.GetEndPoint(1).Z); * * * //get a new line and use it to move current element * //with property "Autodesk.Revit.DB.LocationCurve.Curve" * line = Line.CreateBound(newStart, newEnd); * lineLoc.Curve = line; * } */ } catch (Exception ex) { TaskDialog.Show("MoveLinear", ex.Message); res = Autodesk.Revit.UI.Result.Failed; } finally { } return(res); }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // set out default result to failure. Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Succeeded; Autodesk.Revit.UI.UIApplication app = commandData.Application; // get the elements selected // The current selection can be retrieved from the active // document via the selection object ElementSet seletion = new ElementSet(); foreach (ElementId elementId in app.ActiveUIDocument.Selection.GetElementIds()) { seletion.Insert(app.ActiveUIDocument.Document.GetElement(elementId)); } List <string> parametergroup = new List <string>(); List <ParamTree> All_Elem = new List <ParamTree>(); int n = seletion.Size; //迭代器 ElementSetIterator it = seletion.ForwardIterator(); //遍历所有选中的元素; for (int i = 0; i < n; i++) { //每次迭代下一个元素; it.MoveNext(); Element element = it.Current as Element; ParameterSet parameters = element.Parameters;//获取单个元素的全部属性; ParameterSet parameters2 = GetParamSet(element); foreach (Parameter param in parameters) { if (param == null) { continue; //如果参数没有,继续下一个 } parametergroup = GetParameterGroup(parametergroup, param); } foreach (Parameter param in parameters2) { if (param == null) { continue; //如果参数没有,继续下一个 } parametergroup = GetParameterGroup(parametergroup, param); } ParamTree tree = MakeParamTree(element, parametergroup); All_Elem.Add(tree); } CreateJsonFile(CreateJson(All_Elem)); retRes = Autodesk.Revit.UI.Result.Succeeded; return(retRes); }