Ejemplo n.º 1
0
        private FrameTypesMgr m_typesMgr; // object manage FamilySymbols

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="obj">FamilySymbol object</param>
        /// <param name="typesMgr">FamilySymbols' manager</param>
        public DuplicateTypeForm(object obj, FrameTypesMgr typesMgr)
        {
            InitializeComponent();

            m_copiedSymbol = obj as FamilySymbol;
            m_typesMgr = typesMgr;
        }
        // Create a data structure, attach it to a wall, populate it with data, and retrieve the data back from the wall
        public void CreateSchemeAndStoreData(FamilySymbol titleblock)
        {
            SchemaBuilder schemaBuilder = new SchemaBuilder(new Guid("1a68d420-96dd-44aa-a1de-000774a6104b"));
            schemaBuilder.SetReadAccessLevel(AccessLevel.Public); // allow anyone to read the object
            schemaBuilder.SetSchemaName("TitleBlockSettings");

            // create a field to store data
            FieldBuilder fieldBuilder_titleblockName = schemaBuilder.AddSimpleField("titleblockName", typeof(string));

            FieldBuilder fieldBuilder_cellSizeDistance_X = schemaBuilder.AddSimpleField("cellSizeDistance_X", typeof(string));
            //fieldBuilder_cellSizeDistance_X.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_lowerGap_X = schemaBuilder.AddSimpleField("lowerGap_X", typeof(string));
            //fieldBuilder_lowerGap_X.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_additionalEdge_X = schemaBuilder.AddSimpleField("additionalEdge_X", typeof(string));
            //fieldBuilder_additionalEdge_X.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_fineTune_X = schemaBuilder.AddSimpleField("fineTune_X", typeof(string));
            //fieldBuilder_fineTune_X.SetUnitType(UnitType.UT_Length);

            FieldBuilder fieldBuilder_cellSizeDistance_Y = schemaBuilder.AddSimpleField("cellSizeDistance_Y", typeof(string));
            //fieldBuilder_cellSizeDistance_Y.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_lowerGap_Y = schemaBuilder.AddSimpleField("lowerGap_Y", typeof(string));
            //fieldBuilder_lowerGap_Y.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_additionalEdge_Y = schemaBuilder.AddSimpleField("additionalEdge_Y", typeof(string));
            //fieldBuilder_additionalEdge_Y.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_fineTune_Y = schemaBuilder.AddSimpleField("fineTune_Y", typeof(string));
            //fieldBuilder_fineTune_Y.SetUnitType(UnitType.UT_Length);

            FieldBuilder fieldBuilder_cellGrid_Length = schemaBuilder.AddSimpleField("cellGrid_Length", typeof(string));
            FieldBuilder fieldBuilder_cellGrid_Height = schemaBuilder.AddSimpleField("cellGrid_Height", typeof(string));

            //fieldBuilder.SetDocumentation("store length of cell size in X direction.");

            Schema schema = schemaBuilder.Finish(); // register the Schema object
        }
 public FamilySymbol getFamilySymbol(string familyname)
 {
     foreach (FamilySymbol fs in titleBlockList)
     {
         if (familyname == fs.Name)
         {
             familySymbol = fs;
             return familySymbol;
         }
     }
     return familySymbol;
 }
 // works in Revit Structure 2009 API, but not in 2010:
 bool IsColumnRound(
     FamilySymbol symbol)
 {
     GenericFormSet solid = symbol.Family.SolidForms;
       GenericFormSetIterator i = solid.ForwardIterator();
       i.MoveNext();
       Extrusion extr = i.Current as Extrusion;
       CurveArray cr = extr.Sketch.CurveLoop;
       CurveArrayIterator i2 = cr.ForwardIterator();
       i2.MoveNext();
       String s = i2.Current.GetType().ToString();
       return s.Contains( "Arc" );
 }
Ejemplo n.º 5
0
        public static IList<Element> OfFamilyType(FamilySymbol familyType)
        {
            var instanceFilter = new ElementClassFilter(typeof(Autodesk.Revit.DB.FamilyInstance));
            var fec = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument);

            var familyInstances = fec.WherePasses(instanceFilter)
                .WhereElementIsNotElementType()
                .ToElements()
                .Cast<Autodesk.Revit.DB.FamilyInstance>()
                .Where(x => x.Symbol.IsSimilarType(familyType.InternalFamilySymbol.Id));

            var instances = familyInstances
                .Select(x => ElementSelector.ByElementId(x.Id.IntegerValue)).ToList();
            return instances;
        }
Ejemplo n.º 6
0
 /// <summary>
 /// constructor used only for object factory
 /// </summary>
 /// <param name="symbol">FamilySymbol object has parameters</param>
 private FrameTypeParameters(FamilySymbol symbol)
 {
     // iterate and initialize parameters
     foreach (Parameter para in symbol.Parameters)
     {
         if (para.Definition.Name == "h")
         {
             m_hDimension = para;
             continue;
         }
         if (para.Definition.Name == "b")
         {
             m_bDimension = para;
             continue;
         }
     }
 }
Ejemplo n.º 7
0
        private Value makeFamilyInstance(object location, FamilySymbol fs, int count)
        {
            XYZ pos = location is ReferencePoint
                          ? (location as ReferencePoint).Position
                          : (XYZ) location;

            FamilyInstance fi;

            if (this.Elements.Count > count)
            {
                if (dynUtils.TryGetElement(this.Elements[count], out fi))
                {
                    fi.Symbol = fs;
                    LocationPoint lp = fi.Location as LocationPoint;
                    lp.Point = pos;
                }
                else
                {
                    fi = this.UIDocument.Document.IsFamilyDocument
                             ? this.UIDocument.Document.FamilyCreate.NewFamilyInstance(
                                 pos, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural
                                   )
                             : this.UIDocument.Document.Create.NewFamilyInstance(
                                 pos, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural
                                   );

                    this.Elements[count] = fi.Id;
                }
            }
            else
            {
                fi = this.UIDocument.Document.IsFamilyDocument
                         ? this.UIDocument.Document.FamilyCreate.NewFamilyInstance(
                             pos, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural)
                         : this.UIDocument.Document.Create.NewFamilyInstance(
                             pos, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                this.Elements.Add(fi.Id);
            }

            return Value.NewContainer(fi);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// create beam of certain type in certain position
        /// </summary>
        /// <param name="point2D1">one point of the location line in 2D</param>
        /// <param name="point2D2">another point of the location line in 2D</param>
        /// <param name="baseLevel">the base level of the beam</param>
        /// <param name="topLevel">the top level of the beam</param>
        /// <param name="beamType">type of beam</param>
        /// <returns>nothing</returns>
        private void PlaceBeam(Autodesk.Revit.DB.UV point2D1, Autodesk.Revit.DB.UV point2D2, Level baseLevel, Level topLevel, FamilySymbol beamType)
        {
            double height = topLevel.Elevation;

            Autodesk.Revit.DB.XYZ       startPoint = new Autodesk.Revit.DB.XYZ(point2D1.U, point2D1.V, height);
            Autodesk.Revit.DB.XYZ       endPoint   = new Autodesk.Revit.DB.XYZ(point2D2.U, point2D2.V, height);
            Autodesk.Revit.DB.ElementId topLevelId = topLevel.Id;

            Line           line           = Line.CreateBound(startPoint, endPoint);
            STRUCTURALTYPE structuralType = Autodesk.Revit.DB.Structure.StructuralType.Beam;

            if (!beamType.IsActive)
            {
                beamType.Activate();
            }
            m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(line, beamType, topLevel, structuralType);
        }
Ejemplo n.º 9
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // retrieve all FamilySymbol objects of "Windows" category:

            BuiltInCategory          bic     = BuiltInCategory.OST_Windows;
            FilteredElementCollector symbols = LabUtils.GetFamilySymbols(doc, bic);

            List <string> a = new List <string>();

            foreach (FamilySymbol s in symbols)
            {
                Family fam = s.Family;

                a.Add(s.Name
                      + ", Id=" + s.Id.IntegerValue.ToString()
                      + "; Family name=" + fam.Name
                      + ", Family Id=" + fam.Id.IntegerValue.ToString());
            }
            LabUtils.InfoMsg("{0} windows family symbol{1} loaded in the model{1}", a);

            // loop through the selection set and check for
            // standard family instances of "Windows" category:

            int    iBic = (int)bic;
            string msg, content;
            ICollection <ElementId> ids = uidoc.Selection.GetElementIds();

            foreach (ElementId id in ids)
            {
                Element e = doc.GetElement(id);

                if (e is FamilyInstance &&
                    null != e.Category &&
                    e.Category.Id.IntegerValue.Equals(iBic))
                {
                    msg = "Selected window Id=" + e.Id.IntegerValue.ToString();

                    FamilyInstance inst = e as FamilyInstance;

                    #region 3.3 Retrieve the type of the family instance, and the family of the type:

                    FamilySymbol fs = inst.Symbol;

                    Family f = fs.Family;

                    #endregion // 3.3

                    content = "FamilySymbol = " + fs.Name
                              + "; Id=" + fs.Id.IntegerValue.ToString();

                    content += "\r\n  Family = " + f.Name
                               + "; Id=" + f.Id.IntegerValue.ToString();

                    LabUtils.InfoMsg(msg, content);
                }
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 10
0
        GetTitleBlocks(Document doc)
        {
            m_allTitleBlocks = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_TitleBlocks).Cast<FamilySymbol>() as List<FamilySymbol>;
            if (0 == m_allTitleBlocks.Count) {
                throw new Exception("There is no title block to generate sheet.");
            }

            foreach (FamilySymbol f in m_allTitleBlocks) {
                m_titleBlockNames.Add(f.Name);

                if (null == m_titleBlock) {
                    m_titleBlock = f;
                }
            }
        }
Ejemplo n.º 11
0
 private string getNumLamps(FamilySymbol fs)
 {
     if (fs.get_Parameter("Number of Lamps") != null)
     {
         return fs.get_Parameter("Number of Lamps").ToString();
     }
     else
     {
         // TODO:
         // Parse from IES file
         var file = fs.get_Parameter(BuiltInParameter.FBX_LIGHT_PHOTOMETRIC_FILE);
         return "1"; //for now
     }
 }
        //-----------------------------------
        public bool StorageExists(FamilySymbol titleblock)
        {
            IList<Schema> schemas = Schema.ListSchemas();

            foreach (Schema schema in schemas)
            {
                try
                {
                    Entity entity = titleblock.GetEntity(schema);
                    if (entity.IsValid())
                    {
                        return true;
                    }
                }
                catch { }

            }
            return false;
        }
Ejemplo n.º 13
0
        bool ChangeDiffuserSize(Document doc)
        {
            //
            // iterate over all air terminal families and determine
            // the min and max flow assigned to each type.
            //
            // for each family, create a list of all its symbols
            // with their respective min and max flows. collect
            // these lists in a map keyed by family name:
            //
            Dictionary <string, List <SymbMinMax> > dictFamilyToSymbols = new Dictionary <string, List <SymbMinMax> >();
            {
                WaitCursor waitCursor = new WaitCursor();
                //Category categoryAirTerminal = doc.Settings.Categories.get_Item( BuiltInCategory.OST_DuctTerminal );
                //ElementId categoryId = categoryAirTerminal.Id;
                //ElementIterator it = doc.get_Elements( typeof( Family ) );

                FilteredElementCollector collector
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(Family));

                foreach (Family family in collector)
                {
                    ISet <ElementId> symbolIds
                        = family.GetFamilySymbolIds();

                    // Family category is not implemented,
                    // so check the symbols instead:

                    bool categoryMatches = false;

                    foreach (ElementId id in symbolIds)
                    {
                        Element symbol = doc.GetElement(id);

                        // in 2008 and even 2009 beta 1,
                        // you could compare categories directly:
                        //categoryMatches = ( null != symbol.Category
                        //  && symbol.Category.Equals( categoryAirTerminal ) );

                        // in 2009, check the category id instead:

                        categoryMatches = (null != symbol.Category &&
                                           symbol.Category.Id.IntegerValue.Equals(
                                               (int)BuiltInCategory.OST_DuctTerminal));

                        break; // we only need to check the first one
                    }
                    if (categoryMatches)
                    {
                        List <SymbMinMax> familySymbols
                            = new List <SymbMinMax>();

                        foreach (ElementId id in symbolIds)
                        {
                            FamilySymbol symbol = doc.GetElement(id)
                                                  as FamilySymbol;

                            SymbMinMax a = new SymbMinMax();
                            a.Symbol = symbol;

                            a.Min = Util.GetParameterValueFromName(
                                symbol, ParameterName.MinFlow);

                            a.Max = Util.GetParameterValueFromName(
                                symbol, ParameterName.MaxFlow);

                            familySymbols.Add(a);
                        }
                        dictFamilyToSymbols.Add(
                            family.Name, familySymbols);
                    }
                }
            }
            //
            // prompt user to select which families to process:
            //
            //List<string> familyNames = new List<string>( dictFamilyToSymbols.Count );
            //foreach( string s in dictFamilyToSymbols.Keys )
            //{
            //  familyNames.Add( string.Format( "{0}({1})", s, dictFamilyToSymbols[s].Count ) );
            //}
            List <string> familyNames = new List <string>(dictFamilyToSymbols.Keys);

            familyNames.Sort();
            FamilySelector fs = new FamilySelector(familyNames);

            if (W.DialogResult.OK == fs.ShowDialog())
            {
                WaitCursor waitCursor = new WaitCursor();
                FilteredElementCollector collector = Util.GetSupplyAirTerminals(doc);
                IList <Element>          terminals = collector.ToElements();
                int    n       = terminals.Count;
                string s       = "{0} of " + n.ToString() + " terminals processed...";
                string caption = "Change Diffuser Size";
                using (ProgressForm pf = new ProgressForm(caption, s, n))
                {
                    foreach (FamilyInstance terminal in terminals)
                    {
                        string familyName = terminal.Symbol.Family.Name;
                        if (fs.IsChecked(familyName))
                        {
                            bool found = false;
                            List <SymbMinMax> familySymbols = dictFamilyToSymbols[familyName];
                            double            flow          = Util.GetTerminalFlowParameter(terminal).AsDouble();
                            foreach (SymbMinMax a in familySymbols)
                            {
                                //
                                // pick the first symbol found which matches our flow;
                                // todo: this could be improved:
                                // 1. we could sort the symbols by flow, and that would speed up the search
                                // 2. we could report an error if multiple possible assignments are availabe
                                // 3. we could improve the handling of borderline cases ... tend towards the smaller or bigger?
                                // 4. we could build in a check after building each familySymbols ArrayList to ensure
                                //    that there is no ovelap in the flows and that the entire required flow spectrum is covered
                                //
                                if (a.Min <= flow && flow <= a.Max)
                                {
                                    terminal.Symbol = a.Symbol;
                                    found           = true;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                double flowInCfm = flow * Const.SecondsPerMinute;
                                Util.ErrorMsg(string.Format("No matching flow found for {0} with flow {1}.",
                                                            Util.ElementDescription(terminal), flowInCfm));
                            }
                        }
                        pf.Increment();
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a negative block family from the geometry of the target element and boundaries.
        /// </summary>
        /// <remarks>This is the main implementation of the sample command.</remarks>
        /// <param name="targetElement">The target solid element.</param>
        /// <param name="boundaries">The selected curve element boundaries.</param>
        /// <param name="familyLoadOptions">The family load options when loading the new family.</param>
        /// <param name="familyTemplate">The family template.</param>
        public static FailureCondition CreateNegativeBlock(Element targetElement, IList <Reference> boundaries, IFamilyLoadOptions familyLoadOptions, String familyTemplate)
        {
            Document doc = targetElement.Document;

            Autodesk.Revit.ApplicationServices.Application app = doc.Application;

            // Get curve loop for boundary
            IList <Curve> curves = GetContiguousCurvesFromSelectedCurveElements(doc, boundaries);
            CurveLoop     loop   = null;

            try
            {
                loop = CurveLoop.Create(curves);
            }
            catch (Autodesk.Revit.Exceptions.ArgumentException)
            {
                // Curves are not contiguous
                return(FailureCondition.CurvesNotContigous);
            }
            List <CurveLoop> loops = new List <CurveLoop>();

            loops.Add(loop);

            // Get elevation of loop
            double elevation = curves[0].GetEndPoint(0).Z;

            // Get height for extrusion
            BoundingBoxXYZ bbox   = targetElement.get_BoundingBox(null);
            double         height = bbox.Max.Z - elevation;

            if (height <= 1e-5)
            {
                return(FailureCondition.CurveLoopAboveTarget);
            }

            height += 1;

            // Create family
            Document familyDoc = app.NewFamilyDocument(familyTemplate);

            // Create block from boundaries
            Solid block = GeometryCreationUtilities.CreateExtrusionGeometry(loops, XYZ.BasisZ, height);

            // Subtract target element
            IList <Solid> fromElement = GetTargetSolids(targetElement);

            int solidCount = fromElement.Count;

            // Merge all found solids into single one
            Solid toSubtract = null;

            if (solidCount == 1)
            {
                toSubtract = fromElement[0];
            }

            else if (solidCount > 1)
            {
                toSubtract =
                    BooleanOperationsUtils.ExecuteBooleanOperation(fromElement[0], fromElement[1], BooleanOperationsType.Union);
            }

            if (solidCount > 2)
            {
                for (int i = 2; i < solidCount; i++)
                {
                    toSubtract = BooleanOperationsUtils.ExecuteBooleanOperation(toSubtract, fromElement[i],
                                                                                BooleanOperationsType.Union);
                }
            }

            // Subtract merged solid from overall block
            try
            {
                BooleanOperationsUtils.ExecuteBooleanOperationModifyingOriginalSolid(block, toSubtract,
                                                                                     BooleanOperationsType.Difference);
            }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException)
            {
                return(FailureCondition.NoIntersection);
            }

            // Create freeform element
            using (Transaction t = new Transaction(familyDoc, "Add element"))
            {
                t.Start();
                RevitFreeFormElement element = Autodesk.Revit.DB.FreeFormElement.Create(familyDoc, block);
                t.Commit();
            }

            // Load family into document
            Family family = familyDoc.LoadFamily(doc, familyLoadOptions);

            familyDoc.Close(false);

            // Get symbol as first symbol of loaded family
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.WherePasses(new FamilySymbolFilter(family.Id));
            FamilySymbol fs = collector.FirstElement() as FamilySymbol;


            // Place instance at location of original curves
            using (Transaction t2 = new Transaction(doc, "Place instance"))
            {
                t2.Start();
                if (!fs.IsActive)
                {
                    fs.Activate();
                }
                doc.Create.NewFamilyInstance(XYZ.Zero, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                t2.Commit();
            }

            return(FailureCondition.Success);
        }
Ejemplo n.º 15
0
        private static (Pipe pipe, Element element) PlaceSupports(ExternalCommandData commandData, string name)
        {
            var app   = commandData.Application;
            var uiDoc = app.ActiveUIDocument;
            var doc   = uiDoc.Document;

            try
            {
                //Select a pipe
                var selectedPipe = Shared.BuildingCoder.BuildingCoderUtilities.SelectSingleElementOfType(uiDoc, typeof(Pipe),
                                                                                                         "Select a pipe where to place a support!", false);
                //Get end connectors
                var conQuery = (from Connector c in mp.GetALLConnectorsFromElements(selectedPipe)
                                where (int)c.ConnectorType == 1
                                select c).ToList();

                Connector c1 = conQuery.First();
                Connector c2 = conQuery.Last();

                //Define a plane by three points
                //Detect if the pipe concides with X-axis
                //If true use another axis to define point
                Plane plane;

                if (c1.Origin.Y.Equalz(c2.Origin.Y, Extensions._epx) && c1.Origin.Z.Equalz(c2.Origin.Z, Extensions._epx))
                {
                    plane = Plane.CreateByThreePoints(c1.Origin, c2.Origin, new XYZ(c1.Origin.X, c1.Origin.Y + 5, c1.Origin.Z));
                }
                else
                {
                    plane = Plane.CreateByThreePoints(c1.Origin, c2.Origin, new XYZ(c1.Origin.X + 5, c1.Origin.Y, c1.Origin.Z));
                }

                //Set view sketch plane to the be the created plane
                var sp = SketchPlane.Create(doc, plane);
                uiDoc.ActiveView.SketchPlane = sp;
                //Get a 3d point by picking a point
                XYZ point_in_3d = null;
                try
                {
                    point_in_3d = uiDoc.Selection.PickPoint(
                        "Please pick a point on the plane"
                        + " defined by the selected face");
                }
                catch (OperationCanceledException)
                {
                }

                //Get family symbol
                //FilteredElementCollector collector = new FilteredElementCollector(doc);
                //ElementParameterFilter filter = fi.ParameterValueGenericFilter(doc, BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM, name);
                //LogicalOrFilter classFilter = fi.FamSymbolsAndPipeTypes();
                //FamilySymbol familySymbol = (FamilySymbol)collector.WherePasses(classFilter).WherePasses(filter).FirstOrDefault();
                FamilySymbol familySymbol =
                    Filter.GetElements <FamilySymbol, BuiltInParameter>(doc, BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM, name).FirstOrDefault();
                if (familySymbol == null)
                {
                    throw new Exception("No SUPPORT FamilySymbol loaded in project!");
                }

                //The strange symbol activation thingie...
                //See: http://thebuildingcoder.typepad.com/blog/2014/08/activate-your-family-symbol-before-using-it.html
                if (!familySymbol.IsActive)
                {
                    familySymbol.Activate();
                    doc.Regenerate();
                }

                //Get the host pipe level
                Level level = (Level)doc.GetElement(selectedPipe.LevelId);

                //Create the support instance
                Element support = doc.Create.NewFamilyInstance(point_in_3d, familySymbol, level, StructuralType.NonStructural);

                //Get the connector from the support
                ConnectorSet connectorSetToAdd = mp.GetConnectorSet(support);
                if (connectorSetToAdd.IsEmpty)
                {
                    throw new Exception("The support family lacks a connector. Please read the documentation for correct procedure of setting up a support element.");
                }
                Connector connectorToConnect = (from Connector c in connectorSetToAdd select c).FirstOrDefault();

                //Rotate into place
                tr.RotateElementInPosition(point_in_3d, connectorToConnect, c1, support);

                //Set diameter
                Parameter nominalDiameter = support.LookupParameter("Nominal Diameter");
                nominalDiameter.Set(conQuery.First().Radius * 2);

                return((Pipe)selectedPipe, support);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 16
0
        private string CalculateDoorOperationStyle(FamilyInstance currElem)
        {
            const double smallAngle = Math.PI / 36;

            if (currElem == null)
            {
                return("NOTDEFINED");
            }

            FamilySymbol famSymbol = currElem.Symbol;

            if (famSymbol == null)
            {
                return("NOTDEFINED");
            }
            Family fam = famSymbol.Family;

            if (fam == null)
            {
                return("NOTDEFINED");
            }

            IList <Arc> origArcs = ExporterIFCUtils.GetDoor2DArcsFromFamily(fam);

            if (origArcs == null || (origArcs.Count == 0))
            {
                return("NOTDEFINED");
            }

            IList <Arc>    filteredArcs = new List <Arc>();
            IList <bool>   flippedArcs  = new List <bool>();
            IList <double> offsetAngles = new List <double>();

            foreach (Arc arc in origArcs)
            {
                XYZ zVec = arc.Normal;
                if (!MathUtil.IsAlmostEqual(Math.Abs(zVec.Z), 1.0))
                {
                    continue;
                }

                double angleOffOfXY = 0;
                bool   flipped      = false;

                if (arc.IsBound)
                {
                    flipped = MathUtil.IsAlmostEqual(Math.Abs(zVec.Z), -1.0);
                    XYZ xVec = flipped ? -arc.XDirection : arc.XDirection;
                    angleOffOfXY = Math.Atan2(xVec.Y, xVec.X);
                }

                filteredArcs.Add(arc);
                flippedArcs.Add(flipped);
                offsetAngles.Add(angleOffOfXY);
            }

            int numArcs = filteredArcs.Count;

            if (numArcs == 0)
            {
                return("NOTDEFINED");
            }

            double angleEps = ExporterCacheManager.Document.Application.AngleTolerance;

            if (numArcs == 1)
            {
                // single swing or revolving.
                if (!filteredArcs[0].IsBound)
                {
                    return("REVOLVING");
                }

                KeyValuePair <double, double> endParams = GetAdjustedEndParameters(filteredArcs[0], flippedArcs[0], offsetAngles[0]);
                if ((endParams.Value - endParams.Key) <= Math.PI + angleEps)
                {
                    if ((Math.Abs(endParams.Key) <= angleEps) || (Math.Abs(endParams.Key - Math.PI) <= angleEps))
                    {
                        return("SINGLE_SWING_LEFT");
                    }
                    if ((Math.Abs(endParams.Value - Math.PI) <= angleEps) || (Math.Abs(endParams.Value - 2.0 * Math.PI) <= angleEps))
                    {
                        return("SINGLE_SWING_RIGHT");
                    }
                }
            }
            else if (numArcs == 2)
            {
                if (filteredArcs[0].IsBound && filteredArcs[1].IsBound)
                {
                    XYZ ctrDiff = filteredArcs[1].Center - filteredArcs[0].Center;

                    bool sameX = (Math.Abs(ctrDiff.X) < ShortDist);
                    bool sameY = (Math.Abs(ctrDiff.Y) < ShortDist);

                    if (sameX ^ sameY)
                    {
                        KeyValuePair <double, double> endParams1 = GetAdjustedEndParameters(filteredArcs[0], flippedArcs[0], offsetAngles[0]);
                        double angle1 = endParams1.Value - endParams1.Key;
                        if (angle1 <= Math.PI + 2.0 * smallAngle)
                        {
                            KeyValuePair <double, double> endParams2 = GetAdjustedEndParameters(filteredArcs[1], flippedArcs[1], offsetAngles[1]);
                            double angle2 = endParams2.Value - endParams2.Key;
                            if (angle2 <= Math.PI + 2.0 * smallAngle)
                            {
                                if (sameX)
                                {
                                    if (((Math.Abs(endParams1.Value - Math.PI) < smallAngle) && (Math.Abs(endParams2.Key - Math.PI) < smallAngle)) ||
                                        ((Math.Abs(endParams1.Key - Math.PI) < smallAngle) && (Math.Abs(endParams2.Value - Math.PI) < smallAngle)))
                                    {
                                        return("DOUBLE_SWING_RIGHT");
                                    }
                                    else if (((Math.Abs(endParams1.Value - 2.0 * Math.PI) < smallAngle) && (Math.Abs(endParams2.Key) < smallAngle)) ||
                                             ((Math.Abs(endParams1.Key) < smallAngle) && (Math.Abs(endParams2.Value - 2.0 * Math.PI) < smallAngle)))
                                    {
                                        return("DOUBLE_SWING_LEFT");
                                    }
                                }
                                else // if (sameY)
                                {
                                    return("DOUBLE_DOOR_SINGLE_SWING");
                                }
                            }
                        }
                    }
                }
            }
            else if (numArcs == 4)
            {
                IList <XYZ> ctrs = new List <XYZ>();
                IList <KeyValuePair <double, double> > endParams = new List <KeyValuePair <double, double> >();
                bool canContinue = true;

                // "sort" by quadrant.
                IList <int> whichQuadrant = new List <int>();
                for (int ii = 0; ii < 4; ii++)
                {
                    whichQuadrant.Add(-1);
                }

                for (int ii = 0; (ii < 4) && canContinue; ii++)
                {
                    ctrs.Add(filteredArcs[ii].Center);
                    if (filteredArcs[ii].IsBound)
                    {
                        endParams.Add(GetAdjustedEndParameters(filteredArcs[ii], flippedArcs[ii], offsetAngles[ii]));
                        double angle = endParams[ii].Value - endParams[ii].Key;
                        if (angle > Math.PI + 2.0 * smallAngle)
                        {
                            canContinue = false;
                        }
                        else if ((Math.Abs(endParams[ii].Key) < smallAngle) && whichQuadrant[0] == -1)
                        {
                            whichQuadrant[0] = ii;
                        }
                        else if ((Math.Abs(endParams[ii].Value - Math.PI) < smallAngle) && whichQuadrant[1] == -1)
                        {
                            whichQuadrant[1] = ii;
                        }
                        else if ((Math.Abs(endParams[ii].Key - Math.PI) < smallAngle) && whichQuadrant[2] == -1)
                        {
                            whichQuadrant[2] = ii;
                        }
                        else if ((Math.Abs(endParams[ii].Value - 2.0 * Math.PI) < smallAngle) && whichQuadrant[3] == -1)
                        {
                            whichQuadrant[3] = ii;
                        }
                        else
                        {
                            canContinue = false;
                        }
                    }
                    else
                    {
                        canContinue = false;
                    }
                }

                if (canContinue)
                {
                    XYZ ctrDiff1 = ctrs[whichQuadrant[3]] - ctrs[whichQuadrant[0]];
                    XYZ ctrDiff2 = ctrs[whichQuadrant[2]] - ctrs[whichQuadrant[1]];
                    XYZ ctrDiff3 = ctrs[whichQuadrant[1]] - ctrs[whichQuadrant[0]];

                    if ((Math.Abs(ctrDiff1[0]) < ShortDist) &&
                        (Math.Abs(ctrDiff2[0]) < ShortDist) &&
                        (Math.Abs(ctrDiff3[1]) < ShortDist))
                    {
                        return("DOUBLE_DOOR_DOUBLE_SWING");
                    }
                }
            }

            return("NOTDEFINED");
        }
Ejemplo n.º 17
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            //ElementSet a = uidoc.Selection.Elements; // 2014
            ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); // 2015

            const string newWallTypeName = "NewWallType_with_Width_doubled";

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Duplicate Wall Type");

                foreach (ElementId id in ids)
                {
                    Wall wall = doc.GetElement(id) as Wall;

                    if (null != wall)
                    {
                        WallType wallType = wall.WallType;

                        WallType newWallType = wallType.Duplicate(
                            newWallTypeName) as WallType;

                        //CompoundStructureLayerArray layers = newWallType.CompoundStructure.Layers; // 2011
                        IList <CompoundStructureLayer> layers = newWallType.GetCompoundStructure().GetLayers(); // 2012

                        foreach (CompoundStructureLayer layer in layers)
                        {
                            // double each layer thickness:

                            //layer.Thickness *= 2.0; // 2011

                            layer.Width *= 2.0; // 2012
                        }
                        // assign the new wall type back to the wall:

                        wall.WallType = newWallType;

                        // only process the first wall, if one was selected:

                        break;
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);

            #region Assign colour
#if ASSIGN_COLOUR
            ElementSet elemset = doc.Selection.Elements;

            foreach (Element e in elemset)
            {
                FamilyInstance inst = e as FamilyInstance;

                // get the symbol and duplicate it:
                FamilySymbol dupSym = inst.Symbol.Duplicate(
                    "D1") as FamilySymbol;

                // access the material:
                ElementId matId = dupSym.get_Parameter(
                    "Material").AsElementId();

                Material mat = doc.GetElement(ref matId)
                               as Autodesk.Revit.Elements.Material;

                // change the color of this material:
                mat.Color = new Color(255, 0, 0);

                // assign the new symbol to the instance:
                inst.Symbol = dupSym;
#endif // ASSIGN_COLOUR
            #endregion // Assign colour
        }
    }
Ejemplo n.º 18
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            List <string>            a = new List <string>();
            FilteredElementCollector families;

            #region 3.1.a Retrieve and iterate over all Family objects in document:
            //
            // retrieve all family elements in current document:
            //
            families = new FilteredElementCollector(doc);

            families.OfClass(typeof(Family));

            foreach (Family f in families)
            {
                // Get its category name; notice that the Category property is not
                // implemented for the Family class; use FamilyCategory instead;
                // notice that that is also not always implemented; in that case,
                // use the workaround demonstrated below, looking at the contained
                // family symbols' category:

                a.Add(string.Format("Name={0}; Category={1}; FamilyCategory={2}",
                                    f.Name,
                                    ((null == f.Category) ? "?" : f.Category.Name),
                                    ((null == f.FamilyCategory) ? "?" : f.FamilyCategory.Name)));
            }
            #endregion // 3.1.a

            string msg = "{0} standard familie{1} are loaded in this model{2}";
            LabUtils.InfoMsg(msg, a);

            // Loop through the collection of families, and now look at
            // the child symbols (types) as well. These symbols can be
            // used to determine the family category.

            foreach (Family f in families)
            {
                string catName;
                bool   first = true;

                // Loop all contained symbols (types):

                //foreach( FamilySymbol s in f.Symbols ) // 2014
                foreach (ElementId id in f.GetFamilySymbolIds()) // 2015
                {
                    FamilySymbol s = doc.GetElement(id) as FamilySymbol;

                    // you can determine the family category from its first symbol.

                    if (first)
                    {
                        first = false;

                        #region 3.1.b Retrieve category name of first family symbol:
                        catName = s.Category.Name;
                        #endregion // 3.1.b

                        msg = "Family: Name=" + f.Name
                              + "; Id=" + f.Id.IntegerValue.ToString()
                              + "; Category=" + catName
                              + "\r\nContains Types:";
                    }
                    msg += "\r\n    " + s.Name + "; Id=" + s.Id.IntegerValue.ToString();
                }

                // Show the symbols for this family and allow user to proceed
                // to the next family (OK) or cancel (Cancel)

                msg += "\r\nContinue?";
                if (!LabUtils.QuestionMsg(msg))
                {
                    break;
                }
            }
            //
            // return all families whose name contains the substring "Round Duct":
            //
            IEnumerable <Family> round_duct_families
                = LabUtils.GetFamilies(doc, "Round Duct", true);

            int n = round_duct_families.Count();

            return(Result.Failed);
        }
Ejemplo n.º 19
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            FamilyInstance inst =
                LabUtils.GetSingleSelectedElementOrPrompt(
                    uidoc, typeof(FamilyInstance))
                as FamilyInstance;

            if (null == inst)
            {
                LabUtils.ErrorMsg(
                    "Selected element is not a "
                    + "standard family instance.");

                return(Result.Cancelled);
            }

            // determine selected instance category:

            Category instCat = inst.Category;

            Dictionary <string, List <FamilySymbol> >
            mapFamilyToSymbols
                = new Dictionary <string, List <FamilySymbol> >();

            {
                WaitCursor waitCursor = new WaitCursor();

                // Collect all types applicable to this category and sort them into
                // a dictionary mapping the family name to a list of its types.
                //
                // We create a collection of all loaded families for this category
                // and for each one, the list of all loaded types (symbols).
                //
                // There are many ways how to store the matching objects, but we choose
                // whatever is most suitable for the relevant UI. We could use Revit's
                // generic Map class, but it is probably more efficient to use the .NET
                // strongly-typed Dictionary with
                // KEY = Family name (String)
                // VALUE = list of corresponding FamilySymbol objects
                //
                // find all corresponding families and types:

                FilteredElementCollector families
                    = new FilteredElementCollector(doc);

                families.OfClass(typeof(Family));

                foreach (Family f in families)
                {
                    bool categoryMatches = false;

                    ISet <ElementId> ids = f.GetFamilySymbolIds(); // 2015

                    // we cannot trust f.Category or
                    // f.FamilyCategory, so grab the category
                    // from first family symbol instead:

                    //foreach( FamilySymbol sym in f.Symbols ) // 2014

                    foreach (ElementId id in ids) // 2015
                    {
                        Element symbol = doc.GetElement(id);

                        categoryMatches = symbol.Category.Id.Equals(
                            instCat.Id);

                        break;
                    }

                    if (categoryMatches)
                    {
                        List <FamilySymbol> symbols
                            = new List <FamilySymbol>();

                        //foreach( FamilySymbol sym in f.Symbols ) // 2014
                        foreach (ElementId id in ids) // 2015
                        {
                            FamilySymbol symbol = doc.GetElement(id) as FamilySymbol;

                            symbols.Add(symbol);
                        }

                        mapFamilyToSymbols.Add(f.Name, symbols);
                    }
                }
            }

            // display the form allowing the user to select
            // a family and a type, and assign this type
            // to the instance.

            Lab3_4_Form form
                = new Lab3_4_Form(mapFamilyToSymbols);

            if (System.Windows.Forms.DialogResult.OK
                == form.ShowDialog())
            {
                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Change Selected Instance Type");
                    inst.Symbol = form.cmbType.SelectedItem
                                  as FamilySymbol;
                    t.Commit();
                }

                LabUtils.InfoMsg(
                    "Successfully changed family : type to "
                    + form.cmbFamily.Text + " : "
                    + form.cmbType.Text);
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 20
0
 private static FScheme.Value setParam(FamilySymbol fi, Definition paramDef, FScheme.Value valueExpr)
 {
     var p = fi.get_Parameter(paramDef);
     if (p != null)
     {
         return _setParam(fi, p, valueExpr);
     }
     throw new Exception("Parameter \"" + paramDef.Name + "\" was not found!");
 }
Ejemplo n.º 21
0
 private static FScheme.Value getParam(FamilySymbol fi, string paramName)
 {
     var p = fi.get_Parameter(paramName);
     if (p != null)
     {
         return _getParam(fi, p);
     }
     throw new Exception("Parameter \"" + paramName + "\" was not found!");
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Check all the panels whose areas are below/above/within the range in the divided surface, mark them with different symbols
        /// </summary>
        /// <param name="ds">
        /// The divided surfaces created in the document, it contains the panels for checking
        /// </param>
        void ExamineDividedSurface(DividedSurface ds)
        {
            ElementType  sym    = ds.Document.GetElement(ds.GetTypeId()) as ElementType;
            FamilySymbol fs_min = null;
            FamilySymbol fs_max = null;
            FamilySymbol fs_mid = null;

            // get the panel types which are used to identify the panels in the divided surface
            FamilySymbol fs = sym as FamilySymbol;

            foreach (ElementId symbolId in fs.Family.GetFamilySymbolIds())
            {
                FamilySymbol symbol = (FamilySymbol)m_uiDoc.Document.GetElement(symbolId);
                if (symbol.Name == m_maxType)
                {
                    fs_max = symbol;
                }
                if (symbol.Name == m_minType)
                {
                    fs_min = symbol;
                }
                if (symbol.Name == m_midType)
                {
                    fs_mid = symbol;
                }
            }

            // find all the panels areas and compare with the range
            for (int u = 0; u < ds.NumberOfUGridlines; u++)
            {
                for (int v = 0; v < ds.NumberOfVGridlines; v++)
                {
                    GridNode gn = new GridNode(u, v);
                    if (false == ds.IsSeedNode(gn))
                    {
                        continue;
                    }

                    FamilyInstance familyinstance = ds.GetTileFamilyInstance(gn, 0);
                    if (familyinstance != null)
                    {
                        double panelArea = GetAreaOfTileInstance(familyinstance);
                        // identify the panels drop in different ranges with different types
                        if (panelArea > m_maxValue)
                        {
                            familyinstance.Symbol = fs_max;
                            m_maxCounter++;
                        }
                        else if (panelArea < m_minValue)
                        {
                            familyinstance.Symbol = fs_min;
                            m_minCounter++;
                        }
                        else
                        {
                            familyinstance.Symbol = fs_mid;
                            m_okCounter++;
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document                 doc = commandData.Application.ActiveUIDocument.Document;
            ElementFilter            elementCatgeoryFilter       = new ElementCategoryFilter(BuiltInCategory.OST_Doors); //过滤内置门类别
            ElementFilter            elementFamilyinstanceFilter = new ElementClassFilter(typeof(FamilySymbol));         //过滤族类型
            LogicalAndFilter         doorsFamilyinstances        = new LogicalAndFilter(elementCatgeoryFilter, elementFamilyinstanceFilter);
            FilteredElementCollector doors = new FilteredElementCollector(doc).WherePasses(doorsFamilyinstances);

            string       doorTypeName = "750 x 2000mm";
            FamilySymbol doorType     = null;
            bool         familyFound  = false;

            foreach (FamilySymbol door in doors)
            {
                if (door.Name == doorTypeName)
                {
                    doorType    = door;
                    familyFound = true;
                    break;
                }
            }

            if (!familyFound) //如果没有找到族文件 加载一个
            {
                string familyPath = "";
                Family family;
                bool   loadSucceed = doc.LoadFamily(familyPath, out family); //是否记载成功,成功后传出族
                if (loadSucceed)
                {
                    foreach (ElementId doorTypeID in family.GetValidTypes())
                    {
                        doorType = doc.GetElement(doorTypeID) as FamilySymbol;
                        if (doorType != null)
                        {
                            if (doorType.Name == doorTypeName)
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    TaskDialog.Show("族加载失败", "不能找到族文件");
                }
            }


            if (doorType != null)
            {
                ElementFilter            wallFilter = new ElementClassFilter(typeof(Wall));
                FilteredElementCollector filteredElementCollecter = new FilteredElementCollector(doc);
                filteredElementCollecter.WherePasses(wallFilter);
                Wall wall = null;
                Line line = null;

                foreach (Wall element in filteredElementCollecter)
                {
                    LocationCurve locationCurve = element.Location as LocationCurve;
                    if (locationCurve != null)
                    {
                        line = locationCurve.Curve as Line;
                        if (line != null)
                        {
                            wall = element;
                        }
                    }
                }

                if (wall != null)
                {
                    XYZ   midPoint  = (line.GetEndPoint(0) + line.GetEndPoint(1)) / 2;
                    Level wallLevel = doc.GetElement(wall.LevelId) as Level;
                    using (Transaction trans = new Transaction(doc))
                    {
                        trans.Start("CreateDoor");
                        FamilyInstance door = doc.Create.NewFamilyInstance(midPoint, doorType, wall, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                        TaskDialog.Show("创建成功", "图元的ID为" + door.Id);
                        trans.Commit();
                    }
                }
                else
                {
                    TaskDialog.Show("图元不存在", "没有找到符合条件的墙");
                }
            }
            else
            {
                TaskDialog.Show("族类型不存在", "没有找到族类型" + doorTypeName + "");
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 24
0
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            UIApplication uiapp  = commandData.Application;
            UIDocument    _uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application _app = uiapp.Application;
            Autodesk.Revit.DB.Document _doc = _uidoc.Document;

            BuiltInCategory bicFamilyA = BuiltInCategory.OST_DuctTerminal;
            BuiltInCategory bicFamilyB = BuiltInCategory.OST_DataDevices;
            BuiltInCategory bicFamilyC = BuiltInCategory.OST_MechanicalEquipment;
            //BuiltInCategory bicFamilyC = BuiltInCategory.OST_Sprinklers;

            ICollection <BuiltInCategory> categories = new[] { bicFamilyA, bicFamilyB, bicFamilyC };
            ElementFilter    myPCatFilter            = new ElementMulticategoryFilter(categories);
            ISelectionFilter myPickFilter            = SelFilter.GetElementFilter(myPCatFilter);

            bool       keepOnTruckn = true;
            FormMsgWPF formMsg      = new FormMsgWPF();

            formMsg.Show();

            using (TransactionGroup pickGrp = new TransactionGroup(_doc)) {
                pickGrp.Start("CmdCycleType");
                bool firstTime = true;

                //string strCats= "";
                //foreach (BuiltInCategory iCat in categories) {
                //    strCats = strCats + iCat.ToString().Replace("OST_", "") + ", ";
                //}
                string strCats = FamilyUtils.BICListMsg(categories);

                formMsg.SetMsg("Pick the " + strCats + " to check its type.", "Type Cycle:");
                while (keepOnTruckn)
                {
                    try {
                        Reference pickedElemRef = _uidoc.Selection.PickObject(ObjectType.Element, myPickFilter, "Pick the " + bicFamilyA.ToString() + " to cycle its types. (Press ESC to cancel)");
                        Element   pickedElem    = _doc.GetElement(pickedElemRef.ElementId);

                        FamilyInstance fi = pickedElem as FamilyInstance;
                        FamilySymbol   fs = fi.Symbol;

                        var famTypesIds = fs.Family.GetFamilySymbolIds().OrderBy(e => _doc.GetElement(e).Name).ToList();
                        int thisIndx    = famTypesIds.FindIndex(e => e == fs.Id);
                        int nextIndx    = thisIndx;
                        if (!firstTime)
                        {
                            nextIndx = nextIndx + 1;
                            if (nextIndx >= famTypesIds.Count)
                            {
                                nextIndx = 0;
                            }
                        }
                        else
                        {
                            firstTime = false;
                        }

                        if (pickedElem != null)
                        {
                            using (Transaction tp = new Transaction(_doc, "PlunkOMatic:SetParam")) {
                                tp.Start();
                                if (pickedElem != null)
                                {
                                    fi.Symbol = _doc.GetElement(famTypesIds[nextIndx]) as FamilySymbol;
                                    formMsg.SetMsg("Currently:\n" + fi.Symbol.Name + "\n\nPick again to cycle its types.", "Type Cycling");
                                }
                                tp.Commit();
                            }
                        }
                        else
                        {
                            keepOnTruckn = false;
                        }
                    } catch (Exception) {
                        keepOnTruckn = false;
                        //throw;
                    }
                }
                pickGrp.Assimilate();
            }

            formMsg.Close();
            return(Result.Succeeded);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Retrieve all available title blocks in the currently active document.
        /// </summary>
        /// <param name="doc">the currently active document</param>
        private void GetTitleBlocks(Document doc)
        {
            m_allTitleBlocks = doc.TitleBlocks;
            if (0 == m_allTitleBlocks.Size)
            {
                throw new InvalidOperationException("There is no title block to generate sheet.");
            }

            foreach (FamilySymbol f in m_allTitleBlocks)
            {
                AllTitleBlocksNames.Add(f.Name);

                if (null == m_titleBlock)
                {
                    m_titleBlock = f;
                }
            }
        }
Ejemplo n.º 26
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            Result        rc    = Result.Failed;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Place a New Sprinkler Instance");


                // retrieve the sprinkler family symbol:

#if _2010
                Filter filter = app.Create.Filter.NewFamilyFilter(
                    _name);

                List <Element> families = new List <Element>();
                doc.get_Elements(filter, families);
                Family family = null;

                foreach (Element e in families)
                {
                    family = e as Family;
                    if (null != family)
                    {
                        break;
                    }
                }
#endif // _2010

                Family family = Util.GetFirstElementOfTypeNamed(
                    doc, typeof(Family), _name) as Family;

                if (null == family)
                {
                    if (!doc.LoadFamily(_filename, out family))
                    {
                        message = "Unable to load '" + _filename + "'.";
                        return(rc);
                    }
                }

                FamilySymbol sprinklerSymbol = null;

                //foreach( FamilySymbol fs in family.Symbols ) // 2014

                foreach (ElementId id in
                         family.GetFamilySymbolIds()) // 2015
                {
                    sprinklerSymbol = doc.GetElement(id)
                                      as FamilySymbol;

                    break;
                }

                Debug.Assert(null != sprinklerSymbol,
                             "expected at least one sprinkler symbol"
                             + " to be defined in family");

                // pick the host ceiling:

                Element ceiling = Util.SelectSingleElement(
                    uidoc, "ceiling to host sprinkler");

                if (null == ceiling ||
                    !ceiling.Category.Id.IntegerValue.Equals(
                        (int)BuiltInCategory.OST_Ceilings))
                {
                    message = "No ceiling selected.";
                    return(rc);
                }

                //Level level = ceiling.Level;

                //XYZ p = new XYZ( 40.1432351841559, 30.09700395984548, 8.0000 );

                // these two methods cannot create the sprinkler on the ceiling:

                //FamilyInstance fi = doc.Create.NewFamilyInstance( p, sprinklerSymbol, ceiling, level, StructuralType.NonStructural );
                //FamilyInstance fi = doc.Create.NewFamilyInstance( p, sprinklerSymbol, ceiling, StructuralType.NonStructural );

                // use this overload so get the bottom face of the ceiling instead:

                // FamilyInstance NewFamilyInstance( Face face, XYZ location, XYZ referenceDirection, FamilySymbol symbol )

                // retrieve the bottom face of the ceiling:

                PlanarFace ceilingBottom
                    = GetLargestHorizontalFace(ceiling);

                if (null != ceilingBottom)
                {
                    XYZ p = PointOnFace(ceilingBottom);

                    // Create the sprinkler family instance:

                    FamilyInstance fi = doc.Create.NewFamilyInstance(
                        ceilingBottom, p, XYZ.BasisX, sprinklerSymbol);

                    rc = Result.Succeeded;
                }
                t.Commit();
            }
            return(rc);
        }
Ejemplo n.º 27
0
    PlaceColumn( Autodesk.Revit.ApplicationServices.Application rvtApp, Document rvtDoc, Autodesk.Revit.DB.XYZ point2, double angle, FamilySymbol columnType, ElementId baseLevelId, ElementId topLevelId )
    {
      Autodesk.Revit.DB.XYZ point = point2;
      // Note: Must use level-hosted NewFamilyInstance!
      Level instLevel = (Level) rvtDoc.GetElement( baseLevelId );
      Autodesk.Revit.DB.FamilyInstance column = rvtDoc.Create.NewFamilyInstance( point, columnType, instLevel, StructuralType.Column );

      if( column == null )
      {
        MessageBox.Show( "failed to create an instance of a column." );
        return;
      }

      Autodesk.Revit.DB.XYZ zVec = new Autodesk.Revit.DB.XYZ( 0, 0, 1 );


      Autodesk.Revit.DB.Line axis = Line.CreateUnbound( point, zVec );

      column.Location.Rotate( axis, angle );

      // Set the level Ids
      Parameter baseLevelParameter = column.get_Parameter( Autodesk.Revit.DB.BuiltInParameter.FAMILY_BASE_LEVEL_PARAM );
      Parameter topLevelParameter = column.get_Parameter( Autodesk.Revit.DB.BuiltInParameter.FAMILY_TOP_LEVEL_PARAM ); ;
      baseLevelParameter.Set( baseLevelId );
      topLevelParameter.Set( topLevelId );

    }
Ejemplo n.º 28
0
        /// <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 virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                Document doc = commandData.Application.ActiveUIDocument.Document;

                // get the user selection
                UIDocument uidoc = commandData.Application.ActiveUIDocument;
                ICollection <ElementId> collection = uidoc.Selection.GetElementIds();

                if (collection.Count > 0)
                {
                    // DesignToFabrication needs an ISet<ElementId>
                    ISet <ElementId> selIds = new HashSet <ElementId>();
                    foreach (ElementId id in collection)
                    {
                        selIds.Add(id);
                    }

                    // Set the in-line element type identiers to be swapped during the conversion replacing the family with a similar fabrication part
                    IDictionary <ElementId, ElementId> convertInLineIds = new Dictionary <ElementId, ElementId>();

                    // Get all family symbols
                    FilteredElementCollector familyFinder = new FilteredElementCollector(doc);
                    var families = familyFinder.OfClass(typeof(FamilySymbol)).ToElements().ToList();

                    // Get the family symbol for the damper we are going to convert
                    String fsName = "Fire Damper - Rectangular - Simple";

                    // The found family symbol
                    FamilySymbol fsDamper = null;
                    foreach (FamilySymbol family in families)
                    {
                        if (family.FamilyName == fsName)
                        {
                            fsDamper = family;
                            break;
                        }
                    }

                    // If the damper was found try to find the matching fabrication part type
                    if (fsDamper != null)
                    {
                        // Get the element type identifier for the family symbol
                        var elemFamSymId = fsDamper.Id;

                        // Get all fabrication part types
                        FilteredElementCollector fabPartTypeFinder = new FilteredElementCollector(doc);
                        var fabPartTypes = fabPartTypeFinder.OfClass(typeof(FabricationPartType)).ToElements().ToList();

                        // Get the fabrication part type for the damper we are going to convert to
                        String fptName = "Rect FD - Flange";

                        // The found fabrication part type
                        FabricationPartType fptDamper = null;
                        foreach (FabricationPartType partType in fabPartTypes)
                        {
                            if (partType.FamilyName == fptName)
                            {
                                fptDamper = partType;
                                break;
                            }
                        }

                        // The damper was found create the mapping in between the family symbol and the matching fabrication part type
                        if (fptDamper != null)
                        {
                            // Get the element type identifier for the fabricaion part type
                            var elemFabPartTypeId = fptDamper.Id;

                            // Create the mapping for the family to the fabrication part
                            convertInLineIds.Add(elemFamSymId, elemFabPartTypeId);
                        }
                    }

                    using (Transaction tr = new Transaction(doc, "Convert To Fabrication Parts"))
                    {
                        tr.Start();

                        FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(doc);

                        // get all loaded fabrication services and attempt to convert the design elements
                        // to the first loaded service
                        IList <FabricationService> allLoadedServices = config.GetAllLoadedServices();

                        DesignToFabricationConverter converter = new DesignToFabricationConverter(doc);

                        // If there is a mapping defined attempt to add it to the converter
                        if (convertInLineIds.Count() > 0)
                        {
                            // Set the mappings
                            DesignToFabricationMappingResult mappingResult = converter.SetMapForFamilySymbolToFabricationPartType(convertInLineIds);

                            if (mappingResult != DesignToFabricationMappingResult.Success)
                            {
                                if (mappingResult != DesignToFabricationMappingResult.Undefined)
                                {
                                    message = "There was a problem with the conversion. The map contained no entries.";
                                }
                                else if (mappingResult != DesignToFabricationMappingResult.InvalidFamilySymbol)
                                {
                                    message = "There was a problem with the conversion. There was an invalid Family symbol identifier or an identifier that did not exist in the mappings.";
                                }
                                else if (mappingResult != DesignToFabricationMappingResult.InvalidFabricationPartType)
                                {
                                    message = "There was a problem with the conversion. There was an invalid Fabrication part type identifier or an identifier that did not exist in the mappings.";
                                }
                                else if (mappingResult != DesignToFabricationMappingResult.UnsupportedFamilySymbol)
                                {
                                    message = "There was a problem with the conversion. Unsupported Family symbol it is expected to be either valve, strainer, damper, smoke detector, end cap, or other in line component.";
                                }
                                else if (mappingResult != DesignToFabricationMappingResult.UnsupportedFabricationPartType)
                                {
                                    message = "There was a problem with the conversion. Unsupported Fabrication part type. It is expected to be either valve, strainer, damper, smoke detector, end cap, or other in line component.";
                                }
                                return(Result.Failed);
                            }
                        }

                        DesignToFabricationConverterResult result = converter.Convert(selIds, allLoadedServices[0].ServiceId);

                        if (result != DesignToFabricationConverterResult.Success)
                        {
                            message = "There was a problem with the conversion.";
                            return(Result.Failed);
                        }

                        doc.Regenerate();

                        tr.Commit();
                    }

                    return(Result.Succeeded);
                }
                else
                {
                    // inform user they need to select at least one element
                    message = "Please select at least one element.";
                }

                return(Result.Failed);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Gets minimum height of a family symbol.
 /// </summary>
 /// <param name="symbol">
 /// The family symbol.
 /// </param>
 static double GetMinSymbolHeight(FamilySymbol symbol)
 {
     return ExporterIFCUtils.GetMinSymbolHeight(symbol);
 }
Ejemplo n.º 30
0
        public ViewPlan setup_view(ViewType vt)
        {
            IList <Level> levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast <Level>().OrderBy(l => l.Elevation).ToList();

            Transaction trans = new Transaction(doc);
            ViewFamily  vf    = ViewFamily.Invalid;

            if (vt == ViewType.FloorPlan)
            {
                vf = ViewFamily.StructuralPlan;
            }
            else if (vt == ViewType.CeilingPlan)
            {
                vf = ViewFamily.CeilingPlan;
            }

            ViewFamilyType FviewFamily = new FilteredElementCollector(doc)
                                         .OfClass(typeof(ViewFamilyType))
                                         .Cast <ViewFamilyType>()
                                         .First(x => x.ViewFamily == vf);

            ViewPlan view = new FilteredElementCollector(doc)
                            .OfClass(typeof(ViewPlan))
                            .Cast <ViewPlan>().FirstOrDefault(q
                                                              => q.Name == level.Name && q.ViewType == vt);

            // FIXME : need to filter by vf

            using (trans = new Transaction(doc))
            {
                trans.Start("View plans");
                if (view is null)
                {
                    view = ViewPlan.Create(doc, FviewFamily.Id, level.Id);
                }
                trans.Commit();
            }

            if (vt == ViewType.FloorPlan)
            {
                FilteredElementCollector col_ = new FilteredElementCollector(doc);
                col_.OfClass(typeof(FamilySymbol));
                col_.OfCategory(BuiltInCategory.OST_TitleBlocks);

                FamilySymbol fs = col_.FirstElement() as FamilySymbol;


                using (trans = new Transaction(doc))
                {
                    trans.Start("Sheet");

                    Family tf = null;
                    //Choose appropriate path
                    string tfamilyPath = @"C:\Users\John\Documents\owncloud\revit\Families\11x8 title block.rfa";
                    doc.LoadFamily(tfamilyPath, out tf);

                    // Get the available title block from document
                    FamilySymbol             FS    = null;
                    FilteredElementCollector col__ = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_TitleBlocks);
                    Element TB = null;
                    foreach (Element e in col__)
                    {
                        if (e.Name.Contains("11x8"))
                        {
                            TB = e;
                        }
                    }

                    ViewSheet viewSheet = ViewSheet.Create(doc, TB.Id);

                    UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2,
                                         (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2);

                    //viewSheet.AddView(view3D, location);
                    Viewport.Create(doc, viewSheet.Id, view.Id, new XYZ(location.U, location.V, 0));
                    viewSheet.Name = level.Name;
                    trans.Commit();
                }
            }
            return(view);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// check the number of floors is less than the number of levels
        /// create beams, columns and braces according to selected types
        /// </summary>
        /// <param name="columnObject">type of column</param>
        /// <param name="beamObject">type of beam</param>
        /// <param name="braceObject">type of brace</param>
        /// <param name="floorNumber">number of floor</param>
        /// <returns>number of floors is less than the number of levels and create successfully then return true</returns>
        public bool AddInstance(object columnObject, object beamObject, object braceObject, int floorNumber)
        {
            //whether floor number less than levels number
            if (floorNumber >= levels.Count)
            {
                TaskDialog.Show("Revit", "The number of levels must be added.");
                return(false);
            }

            FamilySymbol columnSymbol = columnObject as FamilySymbol;
            FamilySymbol beamSymbol   = beamObject as FamilySymbol;
            FamilySymbol braceSymbol  = braceObject as FamilySymbol;

            //any symbol is null then the command failed
            if (null == columnSymbol || null == beamSymbol || null == braceSymbol)
            {
                return(false);
            }

            try
            {
                for (int k = 0; k < floorNumber; k++)    //iterate levels from lower one to higher
                {
                    Level baseLevel = levels.GetByIndex(k) as Level;
                    Level topLevel  = levels.GetByIndex(k + 1) as Level;

                    int matrixXSize = m_matrixUV.GetLength(0);    //length of matrix's x range
                    int matrixYSize = m_matrixUV.GetLength(1);    //length of matrix's y range

                    //iterate coordinate both in x direction and y direction and create beams and braces
                    for (int j = 0; j < matrixYSize; j++)
                    {
                        for (int i = 0; i < matrixXSize; i++)
                        {
                            //create beams and braces in x direction
                            if (i != (matrixXSize - 1))
                            {
                                PlaceBrace(m_matrixUV[i, j], m_matrixUV[i + 1, j], baseLevel, topLevel, braceSymbol, true);
                            }
                            //create beams and braces in y direction
                            if (j != (matrixYSize - 1))
                            {
                                PlaceBrace(m_matrixUV[i, j], m_matrixUV[i, j + 1], baseLevel, topLevel, braceSymbol, false);
                            }
                        }
                    }
                    for (int j = 0; j < matrixYSize; j++)
                    {
                        for (int i = 0; i < matrixXSize; i++)
                        {
                            //create beams and braces in x direction
                            if (i != (matrixXSize - 1))
                            {
                                PlaceBeam(m_matrixUV[i, j], m_matrixUV[i + 1, j], baseLevel, topLevel, beamSymbol);
                            }
                            //create beams and braces in y direction
                            if (j != (matrixYSize - 1))
                            {
                                PlaceBeam(m_matrixUV[i, j], m_matrixUV[i, j + 1], baseLevel, topLevel, beamSymbol);
                            }
                        }
                    }
                    //place column of this level
                    foreach (Autodesk.Revit.DB.UV point2D in m_matrixUV)
                    {
                        PlaceColumn(point2D, columnSymbol, baseLevel, topLevel);
                    }
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 1. Find all family symbols in current Revit document and store them
        /// 2. Find the index of default family symbol
        /// Point("Point-based"); Line("Line-based")
        /// </summary>
        public void CheckFamilySymbol(BasedType type)
        {
            m_defaultIndex = -1;
            m_familySymbolList.Clear();

            Autodesk.Revit.DB.FilteredElementIterator familySymbolItor =
                new FilteredElementCollector(m_revitDoc.Document).OfClass(typeof(FamilySymbol)).GetElementIterator();

            String defaultSymbolName = String.Empty;

            switch (type)
            {
            case BasedType.Point:
                defaultSymbolName = "Point-based";
                break;

            case BasedType.Line:
                defaultSymbolName = "Line-based";
                break;

            default:
                break;
            }

            bool hasDefaultSymbol = false;
            int  ii = 0;

            while (familySymbolItor.MoveNext())
            {
                FamilySymbol symbol = (FamilySymbol)familySymbolItor.Current;
                if (null == symbol)
                {
                    continue;
                }

                if (!hasDefaultSymbol && 0 == String.Compare(defaultSymbolName, symbol.Name))
                {
                    hasDefaultSymbol = true;
                    m_defaultIndex   = ii;
                }

                // family symbol
                m_familySymbolList.Add(symbol);

                // family symbol name
                String familyCategoryname = String.Empty;
                if (null != symbol.Family.FamilyCategory)
                {
                    familyCategoryname = symbol.Family.FamilyCategory.Name + " : ";
                }
                m_familySymbolNameList.Add(String.Format("{0}{1} : {2}"
                                                         , familyCategoryname, symbol.Family.Name, symbol.Name));
                ii++;
            }

            if (!hasDefaultSymbol)
            {
                FamilySymbol loadedfamilySymbol = null;
                try
                {
                    m_revitDoc.Document.LoadFamilySymbol(String.Format(@"{0}.rfa", defaultSymbolName)
                                                         , defaultSymbolName
                                                         , out loadedfamilySymbol);
                }
                catch (Exception)
                {
                    TaskDialog.Show("Revit", "Can't load the prepared rfa.");
                }


                if (null == loadedfamilySymbol)
                {
                    return;
                }
                m_familySymbolList.Add(loadedfamilySymbol);

                String familyCategoryname = String.Empty;
                if (null != loadedfamilySymbol.Family.FamilyCategory)
                {
                    familyCategoryname = loadedfamilySymbol.Family.FamilyCategory.Name + ": ";
                }
                m_familySymbolNameList.Add(String.Format("{0}{1}: {2}"
                                                         , familyCategoryname, loadedfamilySymbol.Family.Name, loadedfamilySymbol.Name));
                m_defaultIndex = m_familySymbolList.Count - 1;
            }

            return;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// create brace of certain type in certain position between two adjacent columns
        /// </summary>
        /// <param name="point2D1">one point of the location line in 2D</param>
        /// <param name="point2D2">another point of the location line in 2D</param>
        /// <param name="baseLevel">the base level of the brace</param>
        /// <param name="topLevel">the top level of the brace</param>
        /// <param name="braceType">type of beam</param>
        /// <param name="isXDirection">whether the location line is in x direction</param>
        private void PlaceBrace(Autodesk.Revit.DB.UV point2D1, Autodesk.Revit.DB.UV point2D2, Level baseLevel, Level topLevel, FamilySymbol braceType, bool isXDirection)
        {
            //get the start points and end points of location lines of two braces
            double topHeight       = topLevel.Elevation;
            double baseHeight      = baseLevel.Elevation;
            double middleElevation = (topHeight + baseHeight) / 2;
            double middleHeight    = (topHeight - baseHeight) / 2;

            Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(point2D1.U, point2D1.V, middleElevation);
            Autodesk.Revit.DB.XYZ endPoint   = new Autodesk.Revit.DB.XYZ(point2D2.U, point2D2.V, middleElevation);
            Autodesk.Revit.DB.XYZ middlePoint;

            if (isXDirection)
            {
                middlePoint = new Autodesk.Revit.DB.XYZ((point2D1.U + point2D2.U) / 2, point2D2.V, topHeight);
            }
            else
            {
                middlePoint = new Autodesk.Revit.DB.XYZ(point2D2.U, (point2D1.V + point2D2.V) / 2, topHeight);
            }

            //create two brace and set their location line
            STRUCTURALTYPE structuralType = Autodesk.Revit.DB.Structure.StructuralType.Brace;

            Autodesk.Revit.DB.ElementId levelId      = topLevel.Id;
            Autodesk.Revit.DB.ElementId startLevelId = baseLevel.Id;
            Autodesk.Revit.DB.ElementId endLevelId   = topLevel.Id;

            Line line1 = Line.CreateBound(startPoint, middlePoint);

            if (!braceType.IsActive)
            {
                braceType.Activate();
            }
            FamilyInstance firstBrace = m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(line1, braceType, baseLevel, structuralType);

            Parameter referenceLevel1 = firstBrace.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM);

            if (null != referenceLevel1)
            {
                referenceLevel1.Set(levelId);
            }

            Line           line2       = Line.CreateBound(endPoint, middlePoint);
            FamilyInstance secondBrace = m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(line2, braceType, baseLevel, structuralType);

            Parameter referenceLevel2 = secondBrace.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM);

            if (null != referenceLevel2)
            {
                referenceLevel2.Set(levelId);
            }
        }
Ejemplo n.º 34
0
        //default execute method required by the IExternalCommand class
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                //call to the security check method to check for authentication
                security = SecurityLNT.Security_Check();
                if (security == false)
                {
                    return(Result.Succeeded);
                }

                //get the application data
                Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;

                //read the config file
                specificationData configFileData = UtilityMethods.ReadConfig();

                //check for discipline
                if (configFileData.discipline != "FEMS")
                {
                    TaskDialog.Show("Failed!", "Sorry! Plug-in Not intended for your discipline.");
                    return(Result.Succeeded);
                }

                //exception handled
                if (configFileData.offset == -1.0)
                {
                    MessageBox.Show("Configuration data not found!");
                    return(Result.Succeeded);
                }

                //get all data from specification file
                specList = UtilityMethods.GetFEMS_Specs(configFileData);

                //exception handled
                if (specList == null)
                {
                    MessageBox.Show("Specifications not found!");
                    return(Result.Succeeded);
                }

                //open  the active document in revit
                m_document = commandData.Application.ActiveUIDocument;

                //get the selected element set
                eleSet = m_document.Selection.Elements;

                if (eleSet.IsEmpty)
                {
                    MessageBox.Show("Please select pipes before executing the Add-in!");
                    return(Result.Succeeded);
                }

                //call to method to get the transform required
                Transform transform = UtilityMethods.GetInverseTransform(m_document.Document, commandData.Application.Application);

                if (transform == null)
                {
                    MessageBox.Show("Sorry! Couldn't find a possible transform.");
                    return(Result.Succeeded);
                }

                //get family name from config data
                FamilyName = configFileData.selectedFamily;

                //check if family exists
                family = UtilityMethods.FindElementByName(m_document.Document, typeof(Family), FamilyName) as Family;

                //if existing
                if (family == null)
                {
                    MessageBox.Show("Please load the family into the project and re-run the Add-in.");
                    return(Result.Succeeded);
                }

                //get the family symbol
                symbol = UtilityMethods.GetFamilySymbol(family);

                //exception handled
                if (family == null)
                {
                    MessageBox.Show("No family symbol for the family you specified!");
                    return(Result.Succeeded);
                }

                //create a logical filter for all the structural elements
                LogicalOrFilter filter = UtilityMethods.GetStructuralFilter();

                //if no filter is returned
                if (filter == null)
                {
                    return(Result.Succeeded);
                }

                //get the structural elements from the documents
                List <Element> structuralElements = new List <Element>();

                structuralElements = UtilityMethods.GetStructuralElements(app, filter);

                if (structuralElements == null)
                {
                    MessageBox.Show("Sorry! No structural element found");
                    return(Result.Succeeded);
                }

                //list to store all the planar botom faces of the structural elements
                List <PlanarFace> pFace = new List <PlanarFace>();

                //find and add bottom planar faces to the list
                foreach (Element e in structuralElements)
                {
                    PlanarFace pf = UtilityMethods.GetBottomFace(e);
                    if (pf != null)
                    {
                        pFace.Add(pf);
                    }
                }

                //clear the structural elements list as it is no longer required
                structuralElements.Clear();

                //control variable for removing unwanted elements from the planar faces list
                int flag = 0;

                //iterate through all the selected elements
                foreach (Element ele in eleSet)
                {
                    //check whether the selected element is of type pipe
                    if (ele is Pipe)
                    {
                        //get the location curve of the pipe
                        pipeCurve = ((LocationCurve)ele.Location).Curve;

                        //if the length of pipe curve obtained is zero skip that pipe
                        if (pipeCurve.Length == 0)
                        {
                            FailedToPlace.Add(ele.Id);
                            continue;
                        }

                        //remove unwanted planes from the list
                        if (flag == 0)
                        {
                            //remove unwanted faces from the list (this works only once)
                            pFace = UtilityMethods.GetPossiblePlanes(pFace, pipeCurve.get_EndPoint(0), transform);
                            flag  = -1;
                        }


                        //if no plane is found for intersect to work
                        if (pFace.Count == 0)
                        {
                            MessageBox.Show("Sorry! No structural element found");
                            return(Result.Succeeded);
                        }

                        //from the specification file, get the spacing corresponding to the pipe diameter
                        spacing = UtilityMethods.GetSpacing(ele, specList);

                        //check if the spacing returned is -1
                        if (spacing == -1)
                        {
                            FailedToPlace.Add(ele.Id);
                            continue;
                        }

                        //get the points for placing the family instances
                        points = UtilityMethods.GetPlacementPoints(spacing, pipeCurve,
                                                                   1000 * configFileData.offset, 1000 * configFileData.minSpacing);

                        //check if the points is null exception
                        if (points == null)
                        {
                            FailedToPlace.Add(ele.Id);
                            continue;
                        }

                        //get the pipe level
                        pipeLevel = ele.Level;

                        //iterate through all the points for placing the family instances
                        foreach (XYZ point in points)
                        {
                            try
                            {
                                //create the instances at each points
                                tempEle = m_document.Document.Create.NewFamilyInstance
                                              (point, symbol, ele, pipeLevel, StructuralType.NonStructural);
                                createdElements.Add(tempEle.Id);
                            }
                            catch
                            {
                                FailedToPlace.Add(ele.Id);
                                continue;
                            }

                            //find the rod length required
                            rodLength = UtilityMethods.ReturnLeastZ_Value(m_document.Document, pFace, point, transform);

                            if (rodLength == -1)
                            {
                                FailedToPlace.Add(ele.Id);
                                createdElements.Remove(tempEle.Id);
                                m_document.Document.Delete(tempEle.Id);
                                continue;
                            }

                            //adjust the newly created element properties based on the rodlength,
                            //orientation and dia of pipe
                            if (!UtilityMethods.AdjustElement(m_document.Document,
                                                              tempEle, point, (Pipe)ele, rodLength, pipeCurve))
                            {
                                FailedToPlace.Add(ele.Id);
                                createdElements.Remove(tempEle.Id);
                                m_document.Document.Delete(tempEle.Id);
                                continue;
                            }
                        }
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
            throw new NotImplementedException();
        }
Ejemplo n.º 35
0
 private static FScheme.Value _getParam(FamilySymbol fi, Parameter p)
 {
     if (p.StorageType == StorageType.Double)
     {
         return FScheme.Value.NewNumber(p.AsDouble());
     }
     else if (p.StorageType == StorageType.Integer)
     {
         return FScheme.Value.NewNumber(p.AsInteger());
     }
     else if (p.StorageType == StorageType.String)
     {
         return FScheme.Value.NewString(p.AsString());
     }
     else
     {
         return FScheme.Value.NewContainer(p.AsElementId());
     }
 }
Ejemplo n.º 36
0
 /// <summary>
 /// change selected beam type
 /// </summary>
 /// <param name="sender">object who sent this event</param>
 /// <param name="e">event args</param>
 private void BeamTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
 {
     // choose a new beam type for the selected beam
     m_selectedBeamType = m_beamTypes.ElementAt(this.BeamTypeComboBox.SelectedIndex);
 }
Ejemplo n.º 37
0
 private static FScheme.Value _setParam(FamilySymbol ft, Parameter p, FScheme.Value valueExpr)
 {
     if (p.StorageType == StorageType.Double)
     {
         p.Set(((FScheme.Value.Number)valueExpr).Item);
     }
     else if (p.StorageType == StorageType.Integer)
     {
         p.Set((int)((FScheme.Value.Number)valueExpr).Item);
     }
     else if (p.StorageType == StorageType.String)
     {
         p.Set(((FScheme.Value.String)valueExpr).Item);
     }
     else if (valueExpr.IsNumber)
     {
         p.Set(new ElementId((int)(valueExpr as FScheme.Value.Number).Item));
     }
     else
     {
         p.Set((ElementId)((FScheme.Value.Container)valueExpr).Item);
     }
     return FScheme.Value.NewContainer(ft);
 }
        public void Execute(UIApplication uiapp)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name);

                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("SetupRoom");

                    List <ElementId> myFEC_DataStorage = new FilteredElementCollector(doc).OfClass(typeof(DataStorage)).WhereElementIsNotElementType().Where(x => x.Name == "Room Setup Entities").Select(x => x.Id).ToList();

                    if (myFEC_DataStorage.Count != 0)
                    {
                        doc.Delete(myFEC_DataStorage);
                        List <ElementId> myFEC_RoomSetupEntities = new FilteredElementCollector(doc).WhereElementIsNotElementType().Where(x => x.LookupParameter("Comments") != null).Where(x => x.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString() == "Room Setup Entities").Select(x => x.Id).ToList();
                        doc.Delete(myFEC_RoomSetupEntities);

                        myWindow1.myWindow4.myListViewEE.ItemsSource = null;
                    }
                    else
                    {
                        Element          myLevel     = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().First();
                        List <ElementId> myFEC_Walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().Where(x => x.Name == "Exterior Glazing").Select(x => x.Id).ToList();

                        if (myFEC_Walls.Count == 0)
                        {
                            MessageBox.Show("Wall type Exterior  Glazing needs to exist.\n\r\n\rIt is contained in the default Construction template.");
                        }
                        else
                        {
                            ///                      TECHNIQUE 12 OF 19 (EE12_SetupRoom.cs)
                            ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ARRANGE FURNITURE IN A ROOM WITH GLASS WALLS ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                            ///
                            /// Interfaces and ENUM's:
                            ///     IFamilyLoadOptions
                            ///
                            /// Demonstrates classes:
                            ///     DataStorage
                            ///     FamilySymbol
                            ///
                            ///
                            /// Key methods:
                            ///     DataStorage.Create(
                            ///     doc.LoadFamily(
                            ///     doc.GetElement(myFamily.GetFamilySymbolIds().First()) as FamilySymbol;
                            ///
                            ///
                            ///
                            ///
                            ///	https://github.com/joshnewzealand/Revit-API-Playpen-CSharp


                            // Build a wall profile for the wall creation
                            XYZ           first   = new XYZ(80, 0, 0);
                            XYZ           second  = new XYZ(100, 0, 0);
                            XYZ           third   = new XYZ(100, -20, 0);
                            XYZ           fourth  = new XYZ(80, -20, 0);
                            IList <Curve> profile = new List <Curve>();

                            profile.Add(Line.CreateBound(first, second));
                            profile.Add(Line.CreateBound(second, third));
                            profile.Add(Line.CreateBound(third, fourth));
                            profile.Add(Line.CreateBound(fourth, first));

                            profile = profile.Reverse().ToList();

                            foreach (Curve c in profile)
                            {
                                Wall myWall = Wall.Create(doc, c, myFEC_Walls.First(), myLevel.Id, 10, 0, false, false);
                                myWall.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set("Room Setup Entities");

                                myWall.Pinned = true;
                                // foreach (ElementId myEleID in myWall.CurtainGrid.GetPanelIds()) doc.GetElement(myEleID).Pinned = true;

                                uidoc.RefreshActiveView();
                            }

                            DataStorage myDatastorage = DataStorage.Create(doc);
                            myDatastorage.Name = "Room Setup Entities";
                            //DatabaseMethods.writeDebug(myDatastorage.Id.IntegerValue.ToString(), true);

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(85.77, -3.08, 0); double myDouble_Rotation = 1.57 - (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 0); //Furniture Chair Executive
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(99.67, -4.58, 0); double myDouble_Rotation = 3.14 + (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 1); //Furniture Chair Viper
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(80.33, -10.83, 0); double myDouble_Rotation = 0 + (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 2); //Furniture Couch Viper
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(85.69, -1.45, 0); double myDouble_Rotation = 1.57 - (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 3); //Furniture Desk
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(95.06, -14.72, 0); double myDouble_Rotation = 1.57 - (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 4); //Furniture Table Dining Round w Chairs
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(98.67, -7.88, 0); double myDouble_Rotation = 1.57 - (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 5); //Furniture Table Night Stand
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(90.84, -9.55, 4.99); double myDouble_Rotation = 1.57 - (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 6); //Generic Adaptive Nerf Gun
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(82.95, -10.81, 0); double myDouble_Rotation = 0 + (Math.PI / 2);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 7); //Generic Model Man Sitting Eating
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(85.37, -7.71, 0); double myDouble_Rotation = 2.36 - (Math.PI);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 8); //Generic Model Man Women Construction Worker
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }

                            if (true)
                            {
                                XYZ          myXYZ_Location = new XYZ(92.97, -1.55, 0); double myDouble_Rotation = 2.36 - (Math.PI);
                                FamilySymbol myFamilySymbol = myFamilyReturn_FindInModel(doc, 9); //Generic Model Tipping Hat Man
                                PlaceAndRotateFamily(uidoc, myFamilySymbol, myXYZ_Location, myDouble_Rotation, myLevel);
                            }
                        }
                    }

                    tx.Commit();
                }
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE12_ExtensibleStorage_SetupRoom" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
        public void RetrieveData(FamilySymbol titleblock)
        {
            string[] objects = new string[9];

            Schema schema = Schema.Lookup(new Guid("1a68d420-96dd-44aa-a1de-000774a6104b"));
            // get the field from the schema
            Field field_titleblockName = schema.GetField("titleblockName");

            Field field_cellSizeDistance_X = schema.GetField("cellSizeDistance_X");
            Field field_lowerGap_X = schema.GetField("lowerGap_X");
            Field field_additionalEdge_X = schema.GetField("additionalEdge_X");
            Field field_fineTune_X = schema.GetField("fineTune_X");

            Field field_cellSizeDistance_Y = schema.GetField("cellSizeDistance_Y");
            Field field_lowerGap_Y = schema.GetField("lowerGap_Y");
            Field field_additionalEdge_Y = schema.GetField("additionalEdge_Y");
            Field field_fineTune_Y = schema.GetField("fineTune_Y");

            Field field_cellGrid_Length = schema.GetField("cellGrid_Length");
            Field field_cellGrid_Height = schema.GetField("cellGrid_Height");

            // get the data back from the titleblock
            Entity retrievedEntity = titleblock.GetEntity(schema);
            string retrievedData_titleblockName = retrievedEntity.Get<string>(schema.GetField("titleblockName"));

            string retrievedData_cellSizeDistance_X = retrievedEntity.Get<string>(schema.GetField("cellSizeDistance_X"), DisplayUnitType.DUT_DECIMAL_INCHES);
            string retrievedData_lowerGap_X = retrievedEntity.Get<string>(schema.GetField("lowerGap_X"), DisplayUnitType.DUT_DECIMAL_INCHES);
            string retrievedData_additionalEdge_X = retrievedEntity.Get<string>(schema.GetField("additionalEdge_X"), DisplayUnitType.DUT_DECIMAL_INCHES);
            string retrievedData_fineTune_X = retrievedEntity.Get<string>(schema.GetField("fineTune_X"), DisplayUnitType.DUT_DECIMAL_INCHES);

            string retrievedData_cellSizeDistance_Y = retrievedEntity.Get<string>(schema.GetField("cellSizeDistance_Y"), DisplayUnitType.DUT_DECIMAL_INCHES);
            string retrievedData_lowerGap_Y = retrievedEntity.Get<string>(schema.GetField("lowerGap_Y"), DisplayUnitType.DUT_DECIMAL_INCHES);
            string retrievedData_additionalEdge_Y = retrievedEntity.Get<string>(schema.GetField("additionalEdge_Y"), DisplayUnitType.DUT_DECIMAL_INCHES);
            string retrievedData_fineTune_Y = retrievedEntity.Get<string>(schema.GetField("fineTune_Y"), DisplayUnitType.DUT_DECIMAL_INCHES);

            //string retrievedData_cellGrid = retrievedEntity.Get<string>(schema.GetField("cellGrid"));
            string retrievedData_cellGrid_Length = retrievedEntity.Get<string>(schema.GetField("cellGrid_Length"));
            string retrievedData_cellGrid_Height = retrievedEntity.Get<string>(schema.GetField("cellGrid_Height"));

            titleblockName = retrievedData_titleblockName;

            cellSizeDistance_X = retrievedData_cellSizeDistance_X;
            lowerGap_X = retrievedData_lowerGap_X;
            additionalEdge_X = retrievedData_additionalEdge_X;
            fineTune_X = retrievedData_fineTune_X;

            cellSizeDistance_Y = retrievedData_cellSizeDistance_Y;
            lowerGap_Y = retrievedData_lowerGap_Y;
            additionalEdge_Y = retrievedData_additionalEdge_Y;
            fineTune_Y = retrievedData_fineTune_Y;

            cellGrid_Length = retrievedData_cellGrid_Length;
            cellGrid_Height = retrievedData_cellGrid_Height;
        }
Ejemplo n.º 40
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            #region//Utils
            //String Builder
            StringBuilder sb = new StringBuilder();

            //Collector
            Collector collector = new Collector();

            //UnitConvertor
            LengthUnitConverter converter = new LengthUnitConverter();

            // Application context.
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;
            #endregion

            #region//Check if we are in the Revit project , not in family one.
            if (doc.IsFamilyDocument)
            {
                Message.Display("Can't use command in family document", WindowType.Warning);
                return(Result.Cancelled);
            }
            #endregion

            #region//Get access to current view.
            var sectionView = uidoc.ActiveView;
            #endregion

            #region//Check if Dimension can be created in currently active project view.
            bool canCreateDimensionInView = false;
            switch (sectionView.ViewType)
            {
            case ViewType.FloorPlan:
                canCreateDimensionInView = false;
                break;

            case ViewType.CeilingPlan:
                canCreateDimensionInView = false;
                break;

            case ViewType.Detail:
                canCreateDimensionInView = false;
                break;

            case ViewType.Elevation:
                canCreateDimensionInView = true;
                break;

            case ViewType.Section:
                canCreateDimensionInView = true;
                break;
            }
            #endregion

            #region//Check if Dimension can be created
            if (!canCreateDimensionInView)
            {
                Message.Display("Dimension can't be created in the current view.", WindowType.Warning);
                return(Result.Cancelled);
            }
            #endregion

            #region//Check if activeView is a proper view
            if (canCreateDimensionInView)
            {
                #region//Ask user to select one generic model.
                Reference selectionReference;
                try
                {
                    selectionReference = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterByCategory("Generic Models"), "Select one generic model.");
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    return(Result.Cancelled);
                }
                #endregion

                #region//Get main window
                Element        mainWindow       = doc.GetElement(selectionReference);
                FamilyInstance mainWindowFamily = doc.GetElement(mainWindow.Id) as FamilyInstance;
                FamilySymbol   mainWindowSymbol = mainWindowFamily.Symbol;

                #region//Get directions for dimensions
                XYZ widthDirection  = sectionView.RightDirection.Normalize();
                XYZ heigthDirection = new XYZ(0, 0, 1);
                #endregion

                #region// Checks if selection isn't empty
                if (mainWindowFamily == null)
                {
                    Message.Display("You haven't selected a valid element.\nPlease selected another element.", WindowType.Error);
                    return(Result.Cancelled);
                }
                #endregion

                #region//Check if generic model is in same direction as view
                XYZ genericModelDir = GetReferenceDirection(mainWindowFamily.GetReferences(FamilyInstanceReferenceType.CenterFrontBack).First(), doc);

                if (genericModelDir.ToString() != widthDirection.ToString())
                {
                    Message.Display("The generic model isn't parallel to the active view.", WindowType.Error);
                    return(Result.Cancelled);
                }
                #endregion

                #region//Get Type parameters
                double MDK_offset_vooraanzicht = mainWindowSymbol.LookupParameter("MDK_offset_vooraanzicht").AsDouble();
                double MDK_hoogte  = mainWindowSymbol.LookupParameter("MDK_hoogte").AsDouble();
                double MDK_breedte = mainWindowSymbol.LookupParameter("MDK_breedte").AsDouble();
                string MDK_merk    = mainWindowSymbol.LookupParameter("MDK_merk").AsString();
                #endregion

                #region//Get locationpoint of selected element
                LocationPoint mainWindowLocation      = mainWindowFamily.Location as LocationPoint;
                XYZ           mainWindowLocationpoint = mainWindowLocation.Point;
                #endregion

                #region//main window references
                ReferenceArray mainWindowHeight1 = new ReferenceArray();
                ReferenceArray mainWindowHeight2 = new ReferenceArray();
                ReferenceArray mainWindowWidth1  = new ReferenceArray();
                ReferenceArray mainWindowWidth2  = new ReferenceArray();

                foreach (var e in mainWindowFamily.GetReferences(FamilyInstanceReferenceType.Top))
                {
                    mainWindowHeight1.Append(e);
                    mainWindowHeight2.Append(e);
                }

                foreach (var e in mainWindowFamily.GetReferences(FamilyInstanceReferenceType.Bottom))
                {
                    mainWindowHeight1.Append(e);
                    mainWindowHeight2.Append(e);
                }

                foreach (var e in mainWindowFamily.GetReferences(FamilyInstanceReferenceType.Left))
                {
                    mainWindowWidth1.Append(e);
                    mainWindowWidth2.Append(e);
                }

                foreach (var e in mainWindowFamily.GetReferences(FamilyInstanceReferenceType.Right))
                {
                    mainWindowWidth1.Append(e);
                    mainWindowWidth2.Append(e);
                }

                foreach (Reference reference in mainWindowFamily.GetReferences(FamilyInstanceReferenceType.WeakReference))
                {
                    string name = mainWindowFamily.GetReferenceName(reference);
                    if (name.Contains("center_tussenregel"))
                    {
                        mainWindowHeight1.Append(reference);
                    }

                    if (name.Contains("center_tussenstijl"))
                    {
                        mainWindowWidth1.Append(reference);
                    }
                }
                #endregion
                #endregion

                #region//Get DimensionType
                DimensionType windowDimension           = collector.GetLinearDimensionTypeByName(doc, "FAC - Diagonal - 2mm - Black");
                DimensionType windowFrameDimension      = collector.GetLinearDimensionTypeByName(doc, "FAC - Diagonal - 2mm - Stelkozijn");
                DimensionType doorHandleDimension       = collector.GetLinearDimensionTypeByName(doc, "FAC - Ordinate - 2mm - Krukhoogte");
                DimensionType windowFrameLevelDimension = collector.GetLinearDimensionTypeByName(doc, "FAC - Ordinate - 2mm - Stelkozijn");
                #endregion

                #region//Get base line
                List <DetailLine> detailLines = collector.GetDetailLines(doc, sectionView.Id);
                string            lineStyle   = "FAC_vloerpeil";
                Line detailLine = null;

                foreach (DetailLine dl in detailLines)
                {
                    if (dl.LineStyle.Name == lineStyle)
                    {
                        detailLine = dl.GeometryCurve as Line;
                    }
                    else
                    {
                        Message.Display("Can't find a DetailLine with the LineStyle, FAC_vloerpeil.", WindowType.Error);
                        return(Result.Cancelled);
                    }
                }
                #endregion

                #region//Get windowframe and window family!!!MDK WORDT NOG VERVANGEN DOOR FAC KAN ERROR VEROORZAKEN
                ICollection <ElementId> subComponentIds = mainWindowFamily.GetSubComponentIds();

                #region//Get windowframe family
                string         windowFrameName = "31_MDK_GM_stelkozijn_lijn";
                FamilyInstance windowFrame     = null;

                foreach (ElementId id in subComponentIds)
                {
                    if (doc.GetElement(id).Name == windowFrameName)
                    {
                        windowFrame = doc.GetElement(id) as FamilyInstance;
                    }
                }

                #region//windowframe references
                ReferenceArray windowframeWidth   = new ReferenceArray();
                ReferenceArray windowframeHeight1 = new ReferenceArray();
                ReferenceArray windowframeHeight2 = new ReferenceArray();

                foreach (var e in windowFrame.GetReferences(FamilyInstanceReferenceType.Left))
                {
                    windowframeWidth.Append(e);
                }

                foreach (var e in windowFrame.GetReferences(FamilyInstanceReferenceType.Right))
                {
                    windowframeWidth.Append(e);
                }

                windowframeHeight2.Append(detailLine.Reference);

                foreach (var e in windowFrame.GetReferences(FamilyInstanceReferenceType.Top))
                {
                    windowframeHeight1.Append(e);
                    windowframeHeight2.Append(e);
                }

                foreach (var e in windowFrame.GetReferences(FamilyInstanceReferenceType.Bottom))
                {
                    windowframeHeight1.Append(e);
                    windowframeHeight2.Append(e);
                }
                #endregion
                #endregion

                #region//Get window family
                string                windowName       = "31_FAC_GM_vak_vleugel";
                FamilyInstance        window           = null;
                List <FamilyInstance> nestedFamilyList = new List <FamilyInstance>();

                foreach (ElementId id in subComponentIds)
                {
                    FamilyInstance fInstance = doc.GetElement(id) as FamilyInstance;
                    FamilySymbol   fSymbol   = fInstance.Symbol;

                    if (fSymbol.FamilyName == windowName)
                    {
                        window = doc.GetElement(id) as FamilyInstance;
                    }
                }

                ReferenceArray doorHandleHeightLevel = new ReferenceArray();
                ReferenceArray doorHandleHeight      = new ReferenceArray();

                XYZ windowLocationPoint   = null;
                XYZ windowDimensionPoint1 = null;

                Line windowDimension1 = null;

                if (window != null)
                {
                    #region//Get locationpoint of window
                    LocationPoint windowLocation = window.Location as LocationPoint;
                    windowLocationPoint = windowLocation.Point;
                    #endregion

                    #region//Create endpoint for line creation
                    windowDimensionPoint1 = GetDistance(windowLocationPoint, widthDirection, 0, -50);
                    #endregion

                    #region//Create line for dimension
                    windowDimension1 = Line.CreateBound(windowDimensionPoint1, windowDimensionPoint1 + heigthDirection * 100);
                    #endregion

                    #region//window references
                    doorHandleHeightLevel.Append(detailLine.Reference);

                    foreach (Reference reference in window.GetReferences(FamilyInstanceReferenceType.Bottom))
                    {
                        doorHandleHeight.Append(reference);
                    }

                    foreach (Reference reference in window.GetReferences(FamilyInstanceReferenceType.WeakReference))
                    {
                        string name = window.GetReferenceName(reference);
                        if (name.Contains("krukhoogte_binnen"))
                        {
                            doorHandleHeight.Append(reference);
                            doorHandleHeightLevel.Append(reference);
                        }
                    }
                    #endregion
                }
                #endregion
                #endregion

                #region//Create endpoints for line creation
                XYZ RightDimensionPoint1 = GetDistance(mainWindowLocationpoint, widthDirection, MDK_breedte, 150);
                XYZ RightDimensionPoint2 = GetDistance(mainWindowLocationpoint, widthDirection, MDK_breedte, 300);
                XYZ RightDimensionPoint3 = GetDistance(mainWindowLocationpoint, widthDirection, MDK_breedte, 450);

                XYZ BottomDimensionPoint1 = new XYZ(mainWindowLocationpoint.X, mainWindowLocationpoint.Y, mainWindowLocationpoint.Z + MDK_offset_vooraanzicht - converter.ConvertToFeet(150));
                XYZ BottomDimensionPoint2 = new XYZ(mainWindowLocationpoint.X, mainWindowLocationpoint.Y, mainWindowLocationpoint.Z + MDK_offset_vooraanzicht - converter.ConvertToFeet(300));

                XYZ LeftDimensionPoint1 = GetDistance(mainWindowLocationpoint, widthDirection, 0, -150);
                XYZ LeftDimensionPoint2 = GetDistance(mainWindowLocationpoint, widthDirection, 0, -300);

                XYZ TopDimensionPoint1 = new XYZ(mainWindowLocationpoint.X, mainWindowLocationpoint.Y, mainWindowLocationpoint.Z + MDK_offset_vooraanzicht + MDK_hoogte + converter.ConvertToFeet(150));
                #endregion

                #region//Create line for dimension
                Line RightDimension1 = Line.CreateBound(RightDimensionPoint1, RightDimensionPoint1 + heigthDirection * 100);
                Line RightDimension2 = Line.CreateBound(RightDimensionPoint2, RightDimensionPoint2 + heigthDirection * 100);
                Line RightDimension3 = Line.CreateBound(RightDimensionPoint3, RightDimensionPoint3 + heigthDirection * 100);

                Line BottomDimension1 = Line.CreateBound(BottomDimensionPoint1, BottomDimensionPoint1 + widthDirection * 100);
                Line BottomDimension2 = Line.CreateBound(BottomDimensionPoint2, BottomDimensionPoint2 + widthDirection * 100);

                Line LeftDimension1 = Line.CreateBound(LeftDimensionPoint1, LeftDimensionPoint1 + heigthDirection * 100);
                Line LeftDimension2 = Line.CreateBound(LeftDimensionPoint2, LeftDimensionPoint2 + heigthDirection * 100);

                Line TopDimension1 = Line.CreateBound(TopDimensionPoint1, TopDimensionPoint1 + widthDirection * 100);
                #endregion

                #region//Get selection filter
                SelectionFilterElement        filter  = null;
                List <SelectionFilterElement> filters = collector.GetSelectionFilter(doc);
                string filtername = "Stelkozijn maatvoering";

                foreach (SelectionFilterElement f in filters)
                {
                    if (f.Name == filtername)
                    {
                        filter = f;
                    }
                }
                #endregion

                #region//Create Annotations
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Create Annotations");

                    #region//Create and set workplane to place dimensions on
                    Plane       plane       = Plane.CreateByNormalAndOrigin(sectionView.ViewDirection, sectionView.Origin);
                    SketchPlane sketchPlane = SketchPlane.Create(doc, plane);
                    sectionView.SketchPlane = sketchPlane;
                    #endregion

                    #region//Create Dimensions
                    doc.Create.NewDimension(sectionView, RightDimension1, mainWindowHeight1, windowDimension);
                    doc.Create.NewDimension(sectionView, BottomDimension1, mainWindowWidth1, windowDimension);

                    Dimension windowFrameHeight1 = doc.Create.NewDimension(sectionView, LeftDimension1, windowframeHeight1, windowFrameDimension);
                    Dimension windowFrameHeight2 = doc.Create.NewDimension(sectionView, LeftDimension2, windowframeHeight2, windowFrameLevelDimension);

                    Dimension windowFrameWidth = doc.Create.NewDimension(sectionView, TopDimension1, windowframeWidth, windowFrameDimension);

                    #region//Add dimension to selection filter
                    filter.AddSingle(windowFrameWidth.Id);
                    filter.AddSingle(windowFrameHeight1.Id);
                    filter.AddSingle(windowFrameHeight2.Id);
                    #endregion

                    #region//Add prefix to window frame dimension
                    foreach (DimensionSegment seg in windowFrameHeight2.Segments)
                    {
                        seg.Prefix = "vlp +";
                    }
                    #endregion

                    #region//Add height dimension 2 and/or 3
                    if (mainWindowHeight1.Size != 2)
                    {
                        doc.Create.NewDimension(sectionView, RightDimension2, mainWindowHeight2, windowDimension);
                        if (window != null)
                        {
                            Dimension doorHandleHeight1 = doc.Create.NewDimension(sectionView, RightDimension3, doorHandleHeightLevel, doorHandleDimension);
                            Dimension doorHandleHeight2 = doc.Create.NewDimension(sectionView, windowDimension1, doorHandleHeight, doorHandleDimension);

                            foreach (DimensionSegment seg in doorHandleHeight1.Segments)
                            {
                                seg.Prefix = "GH =";
                                seg.Suffix = "+ vlp";
                            }

                            foreach (DimensionSegment seg in doorHandleHeight2.Segments)
                            {
                                seg.Prefix = "GH =";
                            }
                        }
                    }
                    else
                    {
                        if (window != null)
                        {
                            Dimension doorHandleHeight1 = doc.Create.NewDimension(sectionView, RightDimension2, doorHandleHeightLevel, doorHandleDimension);
                            Dimension doorHandleHeight2 = doc.Create.NewDimension(sectionView, windowDimension1, doorHandleHeight, doorHandleDimension);

                            foreach (DimensionSegment seg in doorHandleHeight1.Segments)
                            {
                                seg.Prefix = "GH =";
                                seg.Suffix = "+ vlp";
                            }

                            foreach (DimensionSegment seg in doorHandleHeight2.Segments)
                            {
                                seg.Prefix = "GH =";
                            }
                        }
                    }
                    #endregion

                    #region//Add width dimension 2
                    if (mainWindowWidth1.Size != 2)
                    {
                        doc.Create.NewDimension(sectionView, BottomDimension2, mainWindowWidth2, windowDimension);
                    }
                    #endregion

                    #endregion
                    tx.Commit();
                }
                #endregion
            }
            #endregion

            return(Result.Succeeded);
        }
        public void StoreData(FamilySymbol titleblock)
        {
            Schema schema = Schema.Lookup(new Guid("1a68d420-96dd-44aa-a1de-000774a6104b"));
            Entity entity = new Entity(schema);

            Field field_titleblockName = schema.GetField("titleblockName");

            Field field_cellSizeDistance_X = schema.GetField("cellSizeDistance_X");
            Field field_lowerGap_X = schema.GetField("lowerGap_X");
            Field field_additionalEdge_X = schema.GetField("additionalEdge_X");
            Field field_fineTune_X = schema.GetField("fineTune_X");

            Field field_cellSizeDistance_Y = schema.GetField("cellSizeDistance_Y");
            Field field_lowerGap_Y = schema.GetField("lowerGap_Y");
            Field field_additionalEdge_Y = schema.GetField("additionalEdge_Y");
            Field field_fineTune_Y = schema.GetField("fineTune_Y");

            Field field_cellGrid_Length = schema.GetField("cellGrid_Length");
            Field field_cellGrid_Height = schema.GetField("cellGrid_Height");

            entity.Set<string>(field_titleblockName, titleblockName);

            entity.Set<string>(field_cellSizeDistance_X, cellSizeDistance_X, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_lowerGap_X, lowerGap_X, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_additionalEdge_X, additionalEdge_X, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_fineTune_X, fineTune_X, DisplayUnitType.DUT_DECIMAL_INCHES);

            entity.Set<string>(field_cellSizeDistance_Y, cellSizeDistance_Y, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_lowerGap_Y, lowerGap_Y, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_additionalEdge_Y, additionalEdge_Y, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_fineTune_Y, fineTune_Y, DisplayUnitType.DUT_DECIMAL_INCHES);

            entity.Set<string>(field_cellGrid_Length, cellGrid_Length);
            entity.Set<string>(field_cellGrid_Height, cellGrid_Height);
            titleblock.SetEntity(entity); // store the entity in the element
        }
Ejemplo n.º 42
0
        public static Autodesk.Revit.DB.FamilyInstance ToNative(this SpeckleElementsClasses.FamilyInstance myFamInst)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(myFamInst.ApplicationId, myFamInst.Type);


            // get family symbol; it's used throughout
            FamilySymbol familySymbol = GetFamilySymbolByFamilyNameAndType(myFamInst.familyName, myFamInst.familyType);

            // Freak out if we don't have a symbol.
            if (familySymbol == null)
            {
                ConversionErrors.Add(new SpeckleConversionError {
                    Message = $"Missing family: {myFamInst.familyName} {myFamInst.familyType}"
                });
                throw new RevitFamilyNotFoundException($"No such family found in the project");
            }

            if (myFamInst.basePoint == null)
            {
                ConversionErrors.Add(new SpeckleConversionError {
                    Message = $"Could not create: {myFamInst.familyName} {myFamInst.familyType}"
                });
                throw new RevitFamilyNotFoundException($"Missing base point");
            }

            // Activate the symbol yo!
            if (!familySymbol.IsActive)
            {
                familySymbol.Activate();
            }

            XYZ xyz = (XYZ)SpeckleCore.Converter.Deserialise(obj: myFamInst.basePoint, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" });


            if (docObj != null) // we have a document object already, so check if we can edit it.
            {
                var type = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                // if family changed, tough luck - delete and rewind
                if (myFamInst.familyName != type.FamilyName)
                {
                    //delete and continue crating it
                    Doc.Delete(docObj.Id);
                }
                // edit element
                else
                {
                    var existingFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)docObj;

                    // check if type changed, and try and change it
                    if (myFamInst.familyType != null && (myFamInst.familyType != type.Name))
                    {
                        existingFamilyInstance.ChangeTypeId(familySymbol.Id);
                    }

                    //update location
                    var existingLocationPoint = existingFamilyInstance.Location as LocationPoint;
                    existingLocationPoint.Point = xyz;

                    var existingRotation = existingLocationPoint.Rotation * 180 / Math.PI;

                    if (existingRotation != myFamInst.rotation)
                    {
                        var r      = (double)myFamInst.rotation;
                        XYZ point1 = new XYZ(xyz.X, xyz.Y, 0);
                        XYZ point2 = new XYZ(xyz.X, xyz.Y, 10);

                        if (existingRotation != 0)
                        {
                            r -= existingRotation;
                        }

                        Autodesk.Revit.DB.Line axis = Autodesk.Revit.DB.Line.CreateBound(point1, point2);
                        ElementTransformUtils.RotateElement(Doc, existingFamilyInstance.Id, axis, Math.PI * r / 180);
                    }



                    SetElementParams(existingFamilyInstance, myFamInst.parameters);
                    return(existingFamilyInstance);
                }
            }

            else
            {
                var myTypeBasedFamInst = Doc.Create.NewFamilyInstance(xyz, familySymbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                SetElementParams(myTypeBasedFamInst, myFamInst.parameters);

                if (myFamInst.rotation != null && myFamInst.rotation != 0)
                {
                    var r      = (double)myFamInst.rotation;
                    XYZ point1 = new XYZ(xyz.X, xyz.Y, 0);
                    XYZ point2 = new XYZ(xyz.X, xyz.Y, 10);
                    Autodesk.Revit.DB.Line axis = Autodesk.Revit.DB.Line.CreateBound(point1, point2);

                    ElementTransformUtils.RotateElement(Doc, myTypeBasedFamInst.Id, axis, Math.PI * r / 180);
                }

                return(myTypeBasedFamInst);
            }
            return(null);
        }
Ejemplo n.º 43
0
        void combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBoxItem cbi = combo.SelectedItem as ComboBoxItem;

            if (cbi != null)
            {
                fs = comboHash[cbi.Content] as FamilySymbol;
                OutPortData[0].Object = fs;

                OnDynElementReadyToBuild(EventArgs.Empty);
            }
        }
Ejemplo n.º 44
0
        public void Changefamily(Document doc, FamilySymbol familySymbol, List <FamilyInstance> listinstance)
        {
            ProgressbarWPF progressbarWPF = new ProgressbarWPF(listinstance.Count, "Loading...");

            progressbarWPF.Show();
            foreach (FamilyInstance familyInstance in listinstance)
            {
                progressbarWPF.Giatri();
                if (progressbarWPF.iscontinue == false)
                {
                    break;
                }
                Dictionary <string, string> dicparameter  = new Dictionary <string, string>();
                Dictionary <string, double> dicparameter1 = new Dictionary <string, double>();
                using (Transaction tran = new Transaction(doc, "sss"))
                {
                    tran.Start();
                    FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
                    MyPreProcessor         preproccessor = new MyPreProcessor();
                    options.SetClearAfterRollback(true);
                    options.SetFailuresPreprocessor(preproccessor);
                    List <Parameter> list1 = ParameterofDt.Getpameteryesno(doc, familyInstance);
                    List <Parameter> list2 = ParameterofDt.Getpameterdouble(doc, familyInstance);
                    foreach (var item in list1)
                    {
                        if (item != null)
                        {
                            dicparameter.Add(item.Definition.Name, item.AsValueString());
                        }
                    }
                    foreach (var item in list2)
                    {
                        if (item != null)
                        {
                            dicparameter1.Add(item.Definition.Name, item.AsDouble());
                        }
                    }
                    familyInstance.Symbol = familySymbol;
                    List <Parameter> list3 = ParameterofDt.Getpameteryesno(doc, familyInstance);
                    List <Parameter> list4 = ParameterofDt.Getpameterdouble(doc, familyInstance);
                    for (int i = 0; i < list3.Count; i++)
                    {
                        var g1 = list3[i];
                        if (g1 != null)
                        {
                            var giatri1 = g1.AsString();
                            foreach (var o in dicparameter)
                            {
                                if (o.Key == g1.Definition.Name)
                                {
                                    g1.Set(o.Value);
                                }
                            }
                        }
                    }
                    for (int i = 0; i < list4.Count; i++)
                    {
                        var g1 = list4[i];
                        if (g1 != null)
                        {
                            var giatri1 = g1.AsDouble();
                            foreach (var o in dicparameter1)
                            {
                                if (o.Key == g1.Definition.Name)
                                {
                                    g1.Set(o.Value);
                                }
                            }
                        }
                    }
                    tran.Commit(options);
                }
            }
            progressbarWPF.Close();
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Retrieve the title block to be generate by its name.
        /// </summary>
        /// <param name="name">The title block's name</param>
        public void ChooseTitleBlock(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            foreach (FamilySymbol f in m_allTitleBlocks)
            {
                if (name.Equals(f.Name))
                {
                    m_titleBlock = f;
                    return;
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// create beam of certain type in certain position
        /// </summary>
        /// <param name="point2D1">one point of the location line in 2D</param>
        /// <param name="point2D2">another point of the location line in 2D</param>
        /// <param name="baseLevel">the base level of the beam</param>
        /// <param name="topLevel">the top level of the beam</param>
        /// <param name="beamType">type of beam</param>
        /// <returns>nothing</returns>
        private void PlaceBeam(Autodesk.Revit.DB.UV point2D1, Autodesk.Revit.DB.UV point2D2, Level baseLevel, Level topLevel, FamilySymbol beamType)
        {
            double height         = topLevel.Elevation;
            Autodesk.Revit.DB.XYZ startPoint         = new Autodesk.Revit.DB.XYZ (point2D1.U, point2D1.V, height);
            Autodesk.Revit.DB.XYZ endPoint         = new Autodesk.Revit.DB.XYZ (point2D2.U, point2D2.V, height);
            Autodesk.Revit.DB.ElementId topLevelId = topLevel.Id;

            Line line = m_revit.Application.Create.NewLineBound(startPoint, endPoint);
            STRUCTURALTYPE structuralType = Autodesk.Revit.DB.Structure.StructuralType.Beam;
            m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(line, beamType, topLevel, structuralType);
        }
Ejemplo n.º 47
0
 SetTitleBlock(string name)
 {
     foreach (FamilySymbol f in m_allTitleBlocks) {
         if (name.Equals(f.Name)) {
             m_titleBlock = f;
             return;
         }
     }
 }
Ejemplo n.º 48
0
        /// <summary>
        /// create column of certain type in certain position
        /// </summary>
        /// <param name="point2D">2D coordinate of the column</param>
        /// <param name="columnType">type of column</param>
        /// <param name="baseLevel">the base level of the column</param>
        /// <param name="topLevel">the top level of the column</param>
        private void PlaceColumn(Autodesk.Revit.DB.UV point2D, FamilySymbol columnType, Level baseLevel, Level topLevel)
        {
            //create column of certain type in certain level and start point
            Autodesk.Revit.DB.XYZ point = new Autodesk.Revit.DB.XYZ (point2D.U, point2D.V, 0);
            STRUCTURALTYPE structuralType;
            structuralType = Autodesk.Revit.DB.Structure.StructuralType.Column;
            FamilyInstance column = m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(point, columnType, topLevel, structuralType);

            //set base level & top level of the column
            if (null != column)
            {
                Parameter baseLevelParameter = column.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.FAMILY_BASE_LEVEL_PARAM);
                Parameter topLevelParameter = column.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.FAMILY_TOP_LEVEL_PARAM);
                Parameter topOffsetParameter = column.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM);
                Parameter baseOffsetParameter = column.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM);

                if (null != baseLevelParameter)
                {
                    Autodesk.Revit.DB.ElementId baseLevelId;
                    baseLevelId = baseLevel.Id;
                    baseLevelParameter.Set(baseLevelId);
                }

                if (null != topLevelParameter)
                {
                    Autodesk.Revit.DB.ElementId topLevelId;
                    topLevelId = topLevel.Id;
                    topLevelParameter.Set(topLevelId);
                }

                if (null != topOffsetParameter)
                {
                    topOffsetParameter.Set(0.0);
                }

                if (null != baseOffsetParameter)
                {
                    baseOffsetParameter.Set(0.0);
                }
            }
        }
Ejemplo n.º 49
0
    FrameWall( Autodesk.Revit.ApplicationServices.Application rvtApp, Autodesk.Revit.DB.Wall wall, double spacing, FamilySymbol columnType )
    {
      Document rvtDoc = wall.Document;

      LocationCurve loc = (LocationCurve) wall.Location;
      XYZ startPt = loc.Curve.GetEndPoint( 0 );
      XYZ endPt = loc.Curve.GetEndPoint( 1 );

      UV wallVec = new UV( endPt.X - startPt.X, endPt.Y - startPt.Y );

      UV axis = new UV( 1.0, 0.0 );


      ElementId baseLevelId = wall.get_Parameter( BuiltInParameter.WALL_BASE_CONSTRAINT ).AsElementId();
      ElementId topLevelId = wall.get_Parameter( BuiltInParameter.WALL_HEIGHT_TYPE ).AsElementId();

      double wallLength = VecLength( wallVec );
      wallVec = VecNormalise( wallVec );

      int nmax = (int) ( wallLength / spacing );

      MessageBox.Show( "Wall Length = " + wallLength + "\nSpacing = " + spacing + "\nMax Number = " + nmax, "Structural Sample", MessageBoxButtons.OK, MessageBoxIcon.Information );

      double angle = VecAngle( wallVec, axis );

      XYZ loc2 = startPt;

      double dx = wallVec.U * spacing;
      double dy = wallVec.V * spacing;

      for( int i = 0; i < nmax; i++ )
      {
        PlaceColumn( rvtApp, rvtDoc, loc2, angle, columnType, baseLevelId, topLevelId );
        loc2 = new XYZ( startPt.X + dx, startPt.Y + dy, startPt.Z );
      }

      PlaceColumn( rvtApp, rvtDoc, endPt, angle, columnType, baseLevelId, topLevelId );
    }
Ejemplo n.º 50
0
        private void Stream(ArrayList data, FamilySymbol famSym)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(FamilySymbol)));

             data.Add(new Snoop.Data.Object("Family", famSym.Family));
             data.Add(new Snoop.Data.Enumerable("Material", famSym.GetMaterialIds(false)));

             MullionType mullionType = famSym as MullionType;
             if (mullionType != null)
             {
            Stream(data, mullionType);
            return;
             }

             PanelType panelType = famSym as PanelType;
             if (panelType != null)
             {
            Stream(data, panelType);
            return;
             }
        }
        /// <summary>
        /// Exports a Rebar Coupler,
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="coupler">The RebarCoupler element.</param>
        /// <param name="productWrapper">The product wrapper.</param>
        public static void ExportCoupler(ExporterIFC exporterIFC, RebarCoupler coupler, ProductWrapper productWrapper)
        {
            if (coupler == null)
            {
                return;
            }

            FamilySymbol familySymbol = ExporterCacheManager.Document.GetElement(coupler.GetTypeId()) as FamilySymbol;

            if (familySymbol == null)
            {
                return;
            }

            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            Common.Enums.IFCEntityType elementClassTypeEnum;
            if (Enum.TryParse <Common.Enums.IFCEntityType>("IfcMechanicalFastener", out elementClassTypeEnum))
            {
                if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                {
                    return;
                }
            }

            ElementId categoryId = CategoryUtil.GetSafeCategoryId(coupler);

            IFCFile       file         = exporterIFC.GetFile();
            IFCAnyHandle  ownerHistory = ExporterCacheManager.OwnerHistoryHandle;
            Options       options      = GeometryUtil.GetIFCExportGeometryOptions();;
            string        ifcEnumType;
            IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, coupler, out ifcEnumType);

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                FamilyTypeInfo currentTypeInfo = ExporterCacheManager.TypeObjectsCache.Find(coupler.GetTypeId(), false, exportType);
                bool           found           = currentTypeInfo.IsValid();
                if (!found)
                {
                    string typeGUID            = GUIDUtil.CreateGUID(familySymbol);
                    string typeName            = NamingUtil.GetIFCName(familySymbol);
                    string typeObjectType      = NamingUtil.CreateIFCObjectName(exporterIFC, familySymbol);
                    string applicableOccurance = NamingUtil.GetObjectTypeOverride(familySymbol, typeObjectType);
                    string typeDescription     = NamingUtil.GetDescriptionOverride(familySymbol, null);
                    string typeElemId          = NamingUtil.CreateIFCElementId(familySymbol);

                    HashSet <IFCAnyHandle> propertySetsOpt = new HashSet <IFCAnyHandle>();

                    GeometryElement exportGeometry = familySymbol.get_Geometry(options);

                    BodyData            bodyData            = null;
                    BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                    bodyData = BodyExporter.ExportBody(exporterIFC, coupler, categoryId, ElementId.InvalidElementId, exportGeometry, bodyExporterOptions, null);

                    List <IFCAnyHandle> repMap = new List <IFCAnyHandle>();
                    IFCAnyHandle        origin = ExporterUtil.CreateAxis2Placement3D(file);;
                    repMap.Add(IFCInstanceExporter.CreateRepresentationMap(file, origin, bodyData.RepresentationHnd));

                    IFCAnyHandle styleHandle = FamilyExporterUtil.ExportGenericType(exporterIFC, exportType, ifcEnumType, typeGUID, typeName,
                                                                                    typeDescription, applicableOccurance, propertySetsOpt, repMap, typeElemId, typeName, coupler, familySymbol);

                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(styleHandle))
                    {
                        currentTypeInfo.Style = styleHandle;
                        ExporterCacheManager.TypeObjectsCache.Register(coupler.GetTypeId(), false, exportType, currentTypeInfo);
                    }
                }

                int nCouplerQuantity = coupler.GetCouplerQuantity();
                if (nCouplerQuantity <= 0)
                {
                    return;
                }

                ISet <IFCAnyHandle> createdRebarCouplerHandles = new HashSet <IFCAnyHandle>();
                string origInstanceName = NamingUtil.GetNameOverride(coupler, NamingUtil.GetIFCName(coupler));

                for (int idx = 0; idx < nCouplerQuantity; idx++)
                {
                    string instanceGUID        = GUIDUtil.CreateSubElementGUID(coupler, idx);
                    string instanceName        = NamingUtil.GetNameOverride(coupler, origInstanceName + ": " + idx);
                    string objectType          = NamingUtil.CreateIFCObjectName(exporterIFC, coupler);
                    string instanceObjectType  = NamingUtil.GetObjectTypeOverride(coupler, objectType);
                    string instanceDescription = NamingUtil.GetDescriptionOverride(coupler, null);
                    string instanceElemId      = NamingUtil.CreateIFCElementId(coupler);
                    string instanceTag         = NamingUtil.GetTagOverride(coupler, NamingUtil.CreateIFCElementId(coupler));

                    IFCAnyHandle style = currentTypeInfo.Style;
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(style))
                    {
                        return;
                    }

                    IList <IFCAnyHandle> repMapList = GeometryUtil.GetRepresentationMaps(style);
                    if (repMapList == null)
                    {
                        return;
                    }
                    if (repMapList.Count == 0)
                    {
                        return;
                    }

                    IList <IFCAnyHandle> shapeReps        = new List <IFCAnyHandle>();
                    IFCAnyHandle         contextOfItems3d = exporterIFC.Get3DContextHandle("Body");
                    ISet <IFCAnyHandle>  representations  = new HashSet <IFCAnyHandle>();
                    representations.Add(ExporterUtil.CreateDefaultMappedItem(file, repMapList[0], XYZ.Zero));
                    IFCAnyHandle shapeRep = RepresentationUtil.CreateBodyMappedItemRep(exporterIFC, coupler, categoryId, contextOfItems3d, representations);
                    shapeReps.Add(shapeRep);

                    IFCAnyHandle productRepresentation = IFCInstanceExporter.CreateProductDefinitionShape(exporterIFC.GetFile(), null, null, shapeReps);

                    Transform trf = coupler.GetCouplerPositionTransform(idx);

                    using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, coupler, trf, null))
                    {
                        IFCAnyHandle instanceHandle = null;
                        instanceHandle = IFCInstanceExporter.CreateGenericIFCEntity(Common.Enums.IFCEntityType.IfcMechanicalFastener, file, instanceGUID, ownerHistory,
                                                                                    instanceName, instanceDescription, instanceObjectType, setter.LocalPlacement, productRepresentation, instanceTag);

                        if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                        {
                            // In IFC4 NominalDiameter and NominalLength attributes have been deprecated. PredefinedType attribute was added.
                            IFCAnyHandleUtil.SetAttribute(instanceHandle, "PredefinedType", Revit.IFC.Export.Toolkit.IFC4.IFCMechanicalFastenerType.USERDEFINED);
                        }
                        else
                        {
                            IFCAnyHandleUtil.SetAttribute(instanceHandle, "NominalDiameter", familySymbol.get_Parameter(BuiltInParameter.COUPLER_WIDTH).AsDouble());
                            IFCAnyHandleUtil.SetAttribute(instanceHandle, "NominalLength", familySymbol.get_Parameter(BuiltInParameter.COUPLER_LENGTH).AsDouble());
                        }

                        createdRebarCouplerHandles.Add(instanceHandle);

                        productWrapper.AddElement(coupler, instanceHandle, setter, null, true);
                    }
                }

                string couplerGUID = GUIDUtil.CreateGUID(coupler);

                if (nCouplerQuantity > 1)
                {
                    // Create a group to hold all of the created IFC entities, if the coupler aren't already in an assembly.
                    // We want to avoid nested groups of groups of couplers.
                    if (coupler.AssemblyInstanceId == ElementId.InvalidElementId)
                    {
                        string revitObjectType = exporterIFC.GetFamilyName();
                        string name            = NamingUtil.GetNameOverride(coupler, revitObjectType);
                        string description     = NamingUtil.GetDescriptionOverride(coupler, null);
                        string objectType      = NamingUtil.GetObjectTypeOverride(coupler, revitObjectType);

                        IFCAnyHandle rebarGroup = IFCInstanceExporter.CreateGroup(file, couplerGUID,
                                                                                  ownerHistory, name, description, objectType);

                        productWrapper.AddElement(coupler, rebarGroup);

                        IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory,
                                                                    null, null, createdRebarCouplerHandles, null, rebarGroup);
                    }
                }
                else
                {
                    // We will update the GUID of the one created element to be the element GUID.
                    // This will allow the IfcGUID parameter to be use/set if appropriate.
                    ExporterUtil.SetGlobalId(createdRebarCouplerHandles.ElementAt(0), couplerGUID);
                }

                tr.Commit();
            }
        }
Ejemplo n.º 52
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Get a lighting fixture family symbol:

            FilteredElementCollector symbols
                = Util.GetElementsOfType(doc,
                                         typeof(FamilySymbol),
                                         BuiltInCategory.OST_LightingFixtures);

            FamilySymbol sym = symbols.FirstElement()
                               as FamilySymbol;

            if (null == sym)
            {
                message = "No lighting fixture symbol found.";
                return(Result.Failed);
            }

            // Pick the ceiling:

#if _2010
            uidoc.Selection.StatusbarTip
                = "Please select ceiling to host lighting fixture";

            uidoc.Selection.PickOne();

            Element ceiling = null;

            foreach (Element e in uidoc.Selection.Elements)
            {
                ceiling = e as Element;
                break;
            }
#endif // _2010

            Reference r = uidoc.Selection.PickObject(
                ObjectType.Element,
                "Please select ceiling to host lighting fixture");

            if (null == r)
            {
                message = "Nothing selected.";
                return(Result.Failed);
            }

            // 'Autodesk.Revit.DB.Reference.Element' is
            // obsolete: Property will be removed. Use
            // Document.GetElement(Reference) instead.
            //Element ceiling = r.Element; // 2011

            Element ceiling = doc.GetElement(r) as Wall; // 2012

            // Get the level 1:

            Level level = Util.GetFirstElementOfTypeNamed(
                doc, typeof(Level), "Level 1") as Level;

            if (null == level)
            {
                message = "Level 1 not found.";
                return(Result.Failed);
            }

            // Create the family instance:

            XYZ p = app.Create.NewXYZ(-43, 28, 0);

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Place New Lighting Fixture Instance");

                FamilyInstance instLight
                    = doc.Create.NewFamilyInstance(
                          p, sym, ceiling, level,
                          StructuralType.NonStructural);

                t.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 53
0
        /// <summary>
        /// create brace of certain type in certain position between two adjacent columns
        /// </summary>
        /// <param name="point2D1">one point of the location line in 2D</param>
        /// <param name="point2D2">another point of the location line in 2D</param>
        /// <param name="baseLevel">the base level of the brace</param>
        /// <param name="topLevel">the top level of the brace</param>
        /// <param name="braceType">type of beam</param>
        /// <param name="isXDirection">whether the location line is in x direction</param>
        private void PlaceBrace(Autodesk.Revit.DB.UV point2D1, Autodesk.Revit.DB.UV point2D2, Level baseLevel, Level topLevel, FamilySymbol braceType, bool isXDirection)
        {
            //get the start points and end points of location lines of two braces
            double topHeight       = topLevel.Elevation;
            double baseHeight      = baseLevel.Elevation;
            double middleElevation = (topHeight + baseHeight) / 2;
            double middleHeight    = (topHeight - baseHeight) / 2;
            Autodesk.Revit.DB.XYZ startPoint         = new Autodesk.Revit.DB.XYZ (point2D1.U, point2D1.V, middleElevation);
            Autodesk.Revit.DB.XYZ endPoint           = new Autodesk.Revit.DB.XYZ (point2D2.U, point2D2.V, middleElevation);
            Autodesk.Revit.DB.XYZ middlePoint;

            if (isXDirection)
            {
                middlePoint = new Autodesk.Revit.DB.XYZ ((point2D1.U + point2D2.U) / 2, point2D2.V, topHeight);
            }
            else
            {
                middlePoint = new Autodesk.Revit.DB.XYZ (point2D2.U, (point2D1.V + point2D2.V) / 2, topHeight);
            }

            //create two brace and set their location line
            STRUCTURALTYPE structuralType = Autodesk.Revit.DB.Structure.StructuralType.Brace;
            Autodesk.Revit.DB.ElementId levelId             = topLevel.Id;
            Autodesk.Revit.DB.ElementId startLevelId        = baseLevel.Id;
            Autodesk.Revit.DB.ElementId endLevelId          = topLevel.Id;

            Line line1 = m_revit.Application.Create.NewLineBound(startPoint, middlePoint);
            FamilyInstance firstBrace = m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(line1, braceType, baseLevel, structuralType);

            Parameter referenceLevel1 = firstBrace.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM);
            if (null != referenceLevel1)
            {
               referenceLevel1.Set(levelId);
            }

            Line line2 = m_revit.Application.Create.NewLineBound(endPoint, middlePoint);
            FamilyInstance secondBrace = m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(line2, braceType, baseLevel, structuralType);

            Parameter referenceLevel2 = secondBrace.get_Parameter(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM);
            if (null != referenceLevel2)
            {
               referenceLevel2.Set(levelId);
            }
        }
Ejemplo n.º 54
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                WaitCursor    waitCursor = new WaitCursor();
                UIApplication app        = commandData.Application;
                Document      doc        = app.ActiveUIDocument.Document;
                Autodesk.Revit.Creation.Application createApp = app.Application.Create;
                Autodesk.Revit.Creation.Document    createDoc = doc.Create;

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Create Little House");

                    // Determine the four corners of the rectangular house:

                    double width = 7 * LabConstants.MeterToFeet;
                    double depth = 4 * LabConstants.MeterToFeet;

                    List <XYZ> corners = new List <XYZ>(4);

                    corners.Add(XYZ.Zero);
                    corners.Add(new XYZ(width, 0, 0));
                    corners.Add(new XYZ(width, depth, 0));
                    corners.Add(new XYZ(0, depth, 0));

                    #region Test creating two levels
#if CREATE_TWO_LEVELS
                    Level          levelBottom = null;
                    Level          levelMiddle = null;
                    Level          levelTop    = null;
                    List <Element> levels      = new List <Element>();

                    Filter filterType
                        = createApp.Filter.NewTypeFilter(
                              typeof(Level));

                    doc.get_Elements(filterType, levels);
                    foreach (Element e in levels)
                    {
                        if (null == levelBottom)
                        {
                            levelBottom = e as Level;
                        }
                        else if (null == levelMiddle)
                        {
                            levelMiddle = e as Level;
                        }
                        else if (null == levelTop)
                        {
                            levelTop = e as Level;
                        }
                        else
                        {
                            break;
                        }
                    }

                    BuiltInParameter topLevelParam
                        = BuiltInParameter.WALL_HEIGHT_TYPE;

                    Line      line;
                    Wall      wall;
                    Parameter param;

                    ElementId   topId = levelMiddle.Id;
                    List <Wall> walls = new List <Wall>(8);
                    for (int i = 0; i < 4; ++i)
                    {
                        line = createApp.NewLineBound(
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        wall = createDoc.NewWall(
                            line, levelBottom, false);

                        param = wall.get_Parameter(topLevelParam);
                        param.Set(ref topId);
                        walls.Add(wall);
                    }

                    topId = levelTop.Id;
                    for (int i = 0; i < 4; ++i)
                    {
                        line = createApp.NewLineBound(
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        wall = createDoc.NewWall(
                            line, levelMiddle, false);

                        param = wall.get_Parameter(topLevelParam);
                        param.Set(ref topId);
                        walls.Add(wall);
                    }

                    List <Element> doorSymbols
                        = LabUtils.GetAllFamilySymbols(
                              app, BuiltInCategory.OST_Doors);

                    Debug.Assert(
                        0 < doorSymbols.Count,
                        "expected at least one door symbol"
                        + " to be loaded into project");

                    FamilySymbol door
                        = doorSymbols[0] as FamilySymbol;

                    XYZ midpoint = LabUtils.Midpoint(
                        corners[0], corners[1]);

                    FamilyInstance inst0
                        = createDoc.NewFamilyInstance(
                              midpoint, door, walls[0], levelBottom,
                              StructuralType.NonStructural);

                    midpoint.Z = levelMiddle.Elevation;

                    FamilyInstance inst1
                        = createDoc.NewFamilyInstance(
                              midpoint, door, walls[4], levelMiddle,
                              StructuralType.NonStructural);
#endif // CREATE_TWO_LEVELS
                    #endregion // Test creating two levels

                    // Determine the levels where the walls will be located:

                    Level levelBottom = null;
                    Level levelTop    = null;

                    if (!LabUtils.GetBottomAndTopLevels(doc, ref levelBottom, ref levelTop))
                    {
                        message = "Unable to determine wall bottom and top levels";
                        return(Result.Failed);
                    }
                    Debug.Print(string.Format("Drawing walls on '{0}' up to '{1}'",
                                              levelBottom.Name, levelTop.Name));

                    // Create the walls:

                    BuiltInParameter topLevelParam = BuiltInParameter.WALL_HEIGHT_TYPE;
                    ElementId        levelBottomId = levelBottom.Id;
                    ElementId        topLevelId    = levelTop.Id;
                    List <Wall>      walls         = new List <Wall>(4);

                    for (int i = 0; i < 4; ++i)
                    {
                        Line line = Line.CreateBound(corners[i], corners[3 == i ? 0 : i + 1]);
                        //Wall wall = createDoc.NewWall( line, levelBottom, false ); // 2012
                        Wall      wall  = Wall.Create(doc, line, levelBottomId, false); // 2013
                        Parameter param = wall.get_Parameter(topLevelParam);
                        param.Set(topLevelId);
                        walls.Add(wall);
                    }

                    // Determine wall thickness for tag offset and profile growth:

                    //double wallThickness = walls[0].WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011
                    //double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012
                    double wallThickness = walls[0].WallType.Width; // simpler and more direct property available in 2012

                    // Add door and windows to the first wall;
                    // note that the NewFamilyInstance() api method does not automatically add door
                    // and window tags, like the ui command does. we add tags here by making additional calls
                    // to NewTag():

                    FamilySymbol door = LabUtils.GetFirstFamilySymbol(doc, BuiltInCategory.OST_Doors);
                    if (null == door)
                    {
                        LabUtils.InfoMsg("No door symbol found.");
                        return(Result.Failed);
                    }
                    FamilySymbol window = LabUtils.GetFirstFamilySymbol(
                        doc, BuiltInCategory.OST_Windows);

                    if (null == window)
                    {
                        LabUtils.InfoMsg("No window symbol found.");
                        return(Result.Failed);
                    }

                    XYZ    midpoint  = LabUtils.Midpoint(corners[0], corners[1]);
                    XYZ    p         = LabUtils.Midpoint(corners[0], midpoint);
                    XYZ    q         = LabUtils.Midpoint(midpoint, corners[1]);
                    double tagOffset = 3 * wallThickness;

                    //double windowHeight = 1 * LabConstants.MeterToFeet;
                    double windowHeight = levelBottom.Elevation + 0.3 * (
                        levelTop.Elevation - levelBottom.Elevation);

                    p = new XYZ(p.X, p.Y, windowHeight);
                    q = new XYZ(q.X, q.Y, windowHeight);
                    View view = doc.ActiveView;

                    door.Activate(); // 2016

                    FamilyInstance inst = createDoc.NewFamilyInstance(
                        midpoint, door, walls[0], levelBottom, StructuralType.NonStructural);

                    midpoint += tagOffset * XYZ.BasisY;

                    //IndependentTag tag = createDoc.NewTag(
                    //  view, inst, false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, midpoint ); // 2017

                    IndependentTag tag = IndependentTag.Create(
                        doc, view.Id, new Reference(inst),
                        false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, midpoint); // 2018

                    IList <FamilyPointPlacementReference> fpprefs = inst.GetFamilyPointPlacementReferences();
                    IList <Reference> refs = inst.GetReferences(FamilyInstanceReferenceType.CenterLeftRight);

                    //IndependentTag tag = IndependentTag.Create( doc,
                    //  view.Id, refs[0], false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, midpoint ); // 2018

                    window.Activate(); // 2016

                    inst = createDoc.NewFamilyInstance(p, window,
                                                       walls[0], levelBottom, StructuralType.NonStructural);

                    p += tagOffset * XYZ.BasisY;

                    //tag = createDoc.NewTag( view, inst,
                    //  false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, p ); // 2017

                    tag = IndependentTag.Create(
                        doc, view.Id, new Reference(inst),
                        false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, p); // 2018

                    inst = createDoc.NewFamilyInstance(q, window, walls[0],
                                                       levelBottom, StructuralType.NonStructural);

                    q += tagOffset * XYZ.BasisY;

                    //tag = createDoc.NewTag( view, inst,
                    //  false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.TAG_HORIZONTAL, q ); // 2011

                    //tag = createDoc.NewTag( view, inst,
                    //  false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, q ); // 2012

                    tag = IndependentTag.Create(
                        doc, view.Id, new Reference(inst),
                        false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, p); // 2018

                    // Grow the profile out by half the wall thickness,
                    // so the floor and roof do not stop halfway through the wall:

                    double w = 0.5 * wallThickness;
                    corners[0] -= w * (XYZ.BasisX + XYZ.BasisY);
                    corners[1] += w * (XYZ.BasisX - XYZ.BasisY);
                    corners[2] += w * (XYZ.BasisX + XYZ.BasisY);
                    corners[3] -= w * (XYZ.BasisX - XYZ.BasisY);
                    CurveArray profile = new CurveArray();
                    for (int i = 0; i < 4; ++i)
                    {
                        //Line line = createApp.NewLineBound( // 2013

                        Line line = Line.CreateBound( // 2014
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        profile.Append(line);
                    }

                    // Add a floor, a roof and the roof slope:

                    bool  structural = false;
                    Floor floor      = createDoc.NewFloor(
                        profile, structural);

                    List <Element> roofTypes
                        = new List <Element>(
                              LabUtils.GetElementsOfType(
                                  doc, typeof(RoofType),
                                  BuiltInCategory.OST_Roofs));

                    Debug.Assert(0 < roofTypes.Count,
                                 "expected at least one roof type"
                                 + " to be loaded into project");

                    // Ensure that we get a valid roof type.
                    // In Revit 2013, the first one encountered
                    // is sloped glazing with zero entries in
                    // its compound layers; actually, the entire
                    // compound structure is null:

                    //RoofType roofType = null;
                    //foreach( RoofType rt in roofTypes )
                    //{
                    //  CompoundStructure cs = rt.GetCompoundStructure();
                    //  if( null != cs
                    //    && 0 < cs.GetLayers().Count )
                    //  {
                    //    roofType = rt;
                    //    break;
                    //  }
                    //}

                    RoofType roofType = roofTypes
                                        .Cast <RoofType>()
                                        .FirstOrDefault <RoofType>(typ
                                                                   => null != typ.GetCompoundStructure());

                    ModelCurveArray modelCurves
                        = new ModelCurveArray();

                    FootPrintRoof roof
                        = createDoc.NewFootPrintRoof(profile,
                                                     levelTop, roofType, out modelCurves);

                    // Regenerate the model after roof creation,
                    // otherwise the calls to set_DefinesSlope and
                    // set_SlopeAngle throw the exception "Unable
                    // to access curves from the roof sketch."

                    doc.Regenerate();

                    // The argument to set_SlopeAngle is NOT an
                    // angle, it is really a slope, i.e. relation
                    // of height to distance, e.g. 0.5 = 6" / 12",
                    // 0.75  = 9" / 12", etc.

                    double slope = 0.3;

                    foreach (ModelCurve curve in modelCurves)
                    {
                        roof.set_DefinesSlope(curve, true);
                        roof.set_SlopeAngle(curve, slope);
                    }

                    // Add a room and a room tag:

                    Room room = createDoc.NewRoom(levelBottom,
                                                  new UV(0.5 * width, 0.5 * depth));

                    //RoomTag roomTag = createDoc.NewRoomTag(
                    //  room, new UV( 0.5 * width, 0.7 * depth ),
                    //  null ); // 2014

                    RoomTag roomTag = createDoc.NewRoomTag(
                        new LinkElementId(room.Id),
                        new UV(0.5 * width, 0.7 * depth),
                        null); // 2015

                    //doc.AutoJoinElements(); // todo: remove this, the transaction should perform this automatically

                    //LabUtils.InfoMsg( "Little house was created successfully." );

                    //#region Test setting BaseOffset and LimitOffset
                    //// 11334196 [Failed to set Room.BaseOffset and Room.LimitOffset properties]
                    //double h = 0.123;
                    //room.BaseOffset = -h;
                    //room.LimitOffset = h + h;
                    //#endregion // Test setting BaseOffset and LimitOffset

                    t.Commit();

                    return(Result.Succeeded);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 55
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="symbol">family symbol</param>
 public SymbolMap(FamilySymbol symbol)
 {
     m_symbol          = symbol;
     string familyName = "";
     if (null != symbol.Family)
     {
         familyName = symbol.Family.Name;
     }
     m_symbolName = familyName + " : " + symbol.Name;
 }
Ejemplo n.º 56
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            //ElementSet ss = uidoc.Selection.Elements; // 2014
            ICollection <ElementId> ids = uidoc.Selection.GetElementIds();

            Wall wall = null;

            if (0 < ids.Count)
            {
                // old pre-selection handling:

                // must be one single element only:

                if (1 != ids.Count)
                {
                    message = "Please pre-select a single wall element.";
                    return(Result.Failed);
                }

                // must be a wall:

                //ElementSetIterator it = ss.ForwardIterator();
                //it.MoveNext();
                //Element e = it.Current as Element;

                ElementId id = ids.First <ElementId>();
                Element   e  = doc.GetElement(id);

                if (!(e is Wall))
                {
                    message = "Selected element is NOT a wall.";
                    return(Result.Failed);
                }
                wall = e as Wall;
            }
            else
            {
                // new prompt for filtered selection allowing only walls:

                try
                {
                    Reference r = uidoc.Selection.PickObject(
                        ObjectType.Element, new WallSelectionFilter(),
                        "Please pick a wall");

                    //wall = r.Element as Wall; // 2011
                    wall = uidoc.Document.GetElement(r) as Wall; // 2012
                }
                catch (OperationCanceledException)
                {
                    message = "Selection cancelled.";
                    return(Result.Cancelled);
                }
            }

            // wall must be constrained to a level at the top (more on parameters later):

            Level topLev = null;

            try
            {
                ElementId id = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId();
                topLev = doc.GetElement(id) as Level;
            }
            catch (Exception)
            {
                topLev = null;
            }

            if (null == topLev)
            {
                message = "Selected wall is not constrained to a level at the top.";
                return(Result.Failed);
            }

            // get the bottom level as well (this should never fail):

            Level botLev = null;

            try
            {
                ElementId id = wall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId();
                botLev = doc.GetElement(id) as Level;
            }
            catch (Exception)
            {
                botLev = null;
            }

            if (null == botLev)
            {
                message = "Selected wall is not constrained to a level at the bottom.";
                return(Result.Failed);
            }

            // Calculate the location points for the 3 columns (assuming straight wall)
            LocationCurve locCurve = wall.Location as LocationCurve;

            XYZ ptStart = locCurve.Curve.GetEndPoint(0);
            XYZ ptEnd   = locCurve.Curve.GetEndPoint(1);
            XYZ ptMid   = 0.5 * (ptStart + ptEnd);

            List <XYZ> locations = new List <XYZ>(3);

            locations.Add(ptStart);
            locations.Add(ptMid);
            locations.Add(ptEnd);

            string        s = "{0} location{1} for the new columns in raw database coordinates, e.g. feet{2}";
            List <string> a = new List <string>();

            a.Add("Start: " + LabUtils.PointString(ptStart));
            a.Add("Mid  : " + LabUtils.PointString(ptMid));
            a.Add("End  : " + LabUtils.PointString(ptEnd));
            LabUtils.InfoMsg(s, a);

            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfCategory(BuiltInCategory.OST_Columns);
            collector.OfClass(typeof(FamilySymbol));

#if SEARCH_FOR_SPECIFIC_NAME
            // retrieve the family type for the new instances.
            // if needed, change the names to match a column
            // type available in the model:

            string family_name = "M_Wood Timber Column";
            string type_name   = "191 x 292mm";

            // LINQ query to find element with given name:
            //
            // ... note that this could also be achieved by
            // filtering for the element name parameter value.

            var column_types = from element in collector
                               //where ((FamilySymbol)element).Family.Name == family_name
                               where element.Name == type_name
                               select element;

            FamilySymbol symbol = null;

            try
            {
                symbol = column_types.Cast <FamilySymbol>().First <FamilySymbol>();
            }
            catch
            {
            }

            if (null == symbol)
            {
                message = string.Format(
                    "Cannot find type '{0}' in family '{1}' in the current model - please load it first.",
                    type_name, family_name);
                return(Result.Failed);
            }
#endif // SEARCH_FOR_SPECIFIC_NAME

            FamilySymbol symbol = collector.Cast <FamilySymbol>().First <FamilySymbol>();

            if (null == symbol)
            {
                message = "Cannot find a suitable column type.";
                return(Result.Failed);
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Insert Columns and Move Wall");

                // insert column family instances:

                foreach (XYZ p in locations)
                {
                    try
                    {
                        // Note: Currently there is a problem.
                        // If we set the type as NonStructural, it is treated as Annotation instance,
                        // and it shows only in plan view.
                        // FamilyInstance column = doc.Create.NewFamilyInstance( p, symbol, botLev, StructuralType.NonStuctural );

                        FamilyInstance column = doc.Create.NewFamilyInstance(
                            p, symbol, botLev, StructuralType.Column);

                        Parameter paramTopLevel = column.get_Parameter(
                            BuiltInParameter.FAMILY_TOP_LEVEL_PARAM);

                        ElementId id = topLev.Id;

                        paramTopLevel.Set(id);
                    }
                    catch (Exception)
                    {
                        LabUtils.ErrorMsg("Failed to create or adjust column.");
                    }
                }

                // Finally, move the wall so the columns are visible.
                // We move the wall perpendicularly to its location
                // curve by one tenth of its length:

                XYZ v = new XYZ(
                    -0.1 * (ptEnd.Y - ptStart.Y),
                    0.1 * (ptEnd.X - ptStart.X),
                    0);

                if (!wall.Location.Move(v))
                {
                    LabUtils.ErrorMsg("Failed to move the wall.");
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
        FamilyInstance CreateBeam(
            FamilySymbol familySymbol,
            Level level,
            XYZ startPt,
            XYZ endPt)
        {
            StructuralType structuralType
            = StructuralType.Beam;

              //Line line = _doc.Application.Create.NewLineBound( startPt, endPt ); // 2013
              Line line = Line.CreateBound( startPt, endPt ); // 2014

              FamilyInstance beam = _doc.Create
            .NewFamilyInstance( startPt, familySymbol,
              level, structuralType );

              LocationCurve beamCurve
            = beam.Location as LocationCurve;

              if( null != beamCurve )
              {
            beamCurve.Curve = line;
              }
              return beam;
        }
Ejemplo n.º 58
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // get the document
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // start a transaction
            using (Transaction t = new Transaction(doc, "Change Project Units"))
            {
                t.Start();

                Level level = new FilteredElementCollector(doc).OfClass(typeof(Level)).FirstOrDefault() as Level;

                // get all lines
                List <Line> lines = new List <Line>();
                FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(CurveElement)).OfCategory(BuiltInCategory.OST_Lines);
                foreach (CurveElement l in collector)
                {
                    string style = doc.GetElement(l.LookupParameter("Line Style").AsElementId()).Name;
                    if (style == "A-WALL")
                    {
                        lines.Add(l.GeometryCurve as Line);
                    }
                }

                Dictionary <string, List <LineDistance> > directions = new Dictionary <string, List <LineDistance> >();
                foreach (Line l in lines)
                {
                    XYZ vector = l.Direction;
                    //bool found = false;

                    string absoluteDirection = Math.Abs(vector.X).ToString() + Math.Abs(vector.Y).ToString() + Math.Abs(vector.Z).ToString();

                    LineDistance dist = new LineDistance();
                    dist.Line = l;

                    if (directions.ContainsKey(absoluteDirection))
                    {
                        directions[absoluteDirection].Add(dist);
                    }
                    else
                    {
                        directions[absoluteDirection] = new List <LineDistance>()
                        {
                            dist
                        };
                    }
                }

                IList <Line> wallLines = new List <Line>();
                foreach (List <LineDistance> direction in directions.Values)
                {
                    LineDistance baseline = direction[0];
                    Line         axis;
                    XYZ          axisPoint;
                    XYZ          negativeAxisPoint;
                    if (baseline.Line.Direction.X == 0 && baseline.Line.Direction.Y == 1)
                    {
                        axis              = Line.CreateUnbound(new XYZ(0, 0, 0), new XYZ(1, 0, 0));
                        axisPoint         = new XYZ(1, 0, 1);
                        negativeAxisPoint = new XYZ(-1, 0, -1);
                    }
                    else
                    {
                        axis              = Line.CreateUnbound(new XYZ(0, 0, 0), new XYZ(0, 1, 0));
                        axisPoint         = new XYZ(0, 1, 1);
                        negativeAxisPoint = new XYZ(0, -1, -1);
                    }

                    foreach (LineDistance line in direction)
                    {
                        IntersectionResultArray intersect1 = new IntersectionResultArray();
                        Line temp = line.Line.Clone() as Line;
                        temp.MakeUnbound();
                        temp.Intersect(axis, out intersect1);
                        XYZ point1 = intersect1.get_Item(0).XYZPoint;
                        line.Distance = XYZ.Zero.DistanceTo(point1);
                    }



                    direction.OrderBy(s => s.Line.GetEndPoint(0).X).ThenBy(s => s.Line.GetEndPoint(0).Y);

                    for (int i = 0; i < direction.Count - 1; i++)
                    {
                        if (direction[i].Checked)
                        {
                            continue;
                        }
                        bool added = false;
                        List <LineDistance> applicable = new List <LineDistance>();
                        for (int j = i + 1; j < direction.Count - 1; j++)
                        {
                            double diff = Math.Abs(direction[i].Distance - direction[j].Distance);
                            if (diff > 0 && diff < 1.25)
                            {
                                // check how close they are to each other
                                Line longerLine;
                                XYZ  projectPoint1;
                                XYZ  projectPoint2;
                                if (direction[i].Line.Length > direction[j].Line.Length)
                                {
                                    longerLine    = direction[i].Line.Clone() as Line;
                                    projectPoint1 = direction[j].Line.GetEndPoint(0);
                                    projectPoint2 = direction[j].Line.GetEndPoint(1);
                                }
                                else
                                {
                                    longerLine    = direction[j].Line.Clone() as Line;
                                    projectPoint1 = direction[i].Line.GetEndPoint(0);
                                    projectPoint2 = direction[i].Line.GetEndPoint(1);
                                }

                                longerLine.MakeUnbound();
                                IntersectionResult projection1 = longerLine.Project(projectPoint1);
                                IntersectionResult projection2 = longerLine.Project(projectPoint2);

                                if (Math.Abs(projection1.Distance) < 1.25 || Math.Abs(projection2.Distance) < 1.25)
                                {
                                    applicable.Add(direction[j]);
                                    direction[j].Checked = true;
                                    if (!added)
                                    {
                                        applicable.Add(direction[i]);
                                        added = true;
                                    }
                                }
                            }
                            else if (diff > 1.25)
                            {
                                break;
                            }
                        }

                        // add the longest line to the list of applicable lines
                        double longest       = 0;
                        int    longestIndex  = 0;
                        bool   lineDirection = true;

                        for (int p = 0; p < applicable.Count; p++)
                        {
                            if (applicable[p].Line.Length > longest)
                            {
                                if (applicable[p].Distance > applicable[longestIndex].Distance)
                                {
                                    lineDirection = true;
                                }
                                else
                                {
                                    lineDirection = false;
                                }
                                longest      = applicable[p].Line.Length;
                                longestIndex = p;
                            }
                        }

                        if (longest > 0)
                        {
                            applicable[longestIndex].Normal = lineDirection;
                            Line shifted = Offset(applicable[longestIndex].Line, 0.25);

                            wallLines.Add(shifted);
                        }
                    }
                }
                List <Wall> walls = new List <Wall>();
                foreach (Line c in wallLines)
                {
                    try
                    {
                        walls.Add(Wall.Create(doc, c, level.Id, false));
                    }
                    catch
                    {
                        // do nothing
                    }
                }

                // next create doors
                List <FamilyInstance> doors = new List <FamilyInstance>();

                FilteredElementCollector         doorCollector = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Doors);
                FamilySymbol                     doorType      = doorCollector.FirstOrDefault() as FamilySymbol;
                Dictionary <string, List <XYZ> > doorMap       = new Dictionary <string, List <XYZ> >();
                List <XYZ> doorLocations = new List <XYZ>();

                FilteredElementCollector dwgCollector = new FilteredElementCollector(doc).OfClass(typeof(ImportInstance));
                foreach (ImportInstance import in dwgCollector)
                {
                    if (import.LookupParameter("Name").AsString().ToLower().Contains("door"))
                    {
                        XYZ location = import.GetTransform().Origin;
                        doorLocations.Add(location);
                        // check which wall this door is closest to
                        foreach (Wall wall in walls)
                        {
                            try
                            {
                                LocationCurve wallLocation = wall.Location as LocationCurve;
                                // this assumes all walls are only about 6" thick
                                if (wallLocation.Curve.Distance(location) < 0.5)
                                {
                                    if (doorMap.ContainsKey(wall.Id.ToString()))
                                    {
                                        doorMap[wall.Id.ToString()] = new List <XYZ>()
                                        {
                                            location
                                        };
                                    }
                                    else
                                    {
                                        doorMap[wall.Id.ToString()].Add(location);
                                    }
                                }
                            } catch
                            {
                                // do nothing
                            }
                        }
                    }
                }

                // create all the walls using the default type
                foreach (string id in doorMap.Keys)
                {
                    Wall wall = doc.GetElement(id) as Wall;
                    foreach (XYZ door in doorMap[id])
                    {
                        doc.Create.NewFamilyInstance(door, doorType, wall, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                    }
                }

                t.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 59
0
 /// <summary>
 /// Gets minimum width of a family symbol.
 /// </summary>
 /// <param name="symbol">
 /// The family symbol.
 /// </param>
 static double GetMinSymbolWidth(FamilySymbol symbol)
 {
     return ExporterIFCUtils.GetMinSymbolWidth(symbol);
 }
Ejemplo n.º 60
0
        public void Execute(UIApplication uiapp)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            string FamilyPath   = Properties.Settings.Default.FamilyPath;
            string FamilySymbol = Properties.Settings.Default.FamilySymbol;
            string FamilyName   = Properties.Settings.Default.FamilyName;

            if (string.IsNullOrEmpty(FamilyPath))
            {
                FamilySymbol historySymbol = null;
                // TaskDialog.Show("History Ok", FamilySymbol);
                Family historyFamily = new FilteredElementCollector(doc)
                                       .OfClass(typeof(Family))
                                       .FirstOrDefault(e => e.Name.Equals(FamilyName)) as Family;

                ISet <ElementId> historyFamilySymbolId = historyFamily.GetFamilySymbolIds();
                foreach (ElementId id in historyFamilySymbolId)
                {
                    // Get name from buffer to compare
                    if (historyFamily.Document.GetElement(id).Name == FamilySymbol && FamilySymbol != null)
                    {
                        historySymbol = historyFamily.Document.GetElement(id) as FamilySymbol;
                    }
                }
                uidoc.PostRequestForElementTypePlacement(historySymbol);
            }

            else
            {
                FilteredElementCollector collector = new FilteredElementCollector(doc).
                                                     OfCategory(BuiltInCategory.OST_ElectricalFixtures).
                                                     OfClass(typeof(Family));

                FamilySymbol symbol = collector.FirstElement() as FamilySymbol;
                Family       family = FindFamilyByName(doc, typeof(Family), FamilyPath) as Family;

                if (null == family)
                {
                    using (var trans = new Transaction(doc, "Insert Transaction"))
                    {
                        trans.Start();
                        if (!doc.LoadFamily(FamilyPath, out family))
                        {
                            TaskDialog.Show("Loading", "Unable to load " + FamilyPath);
                        }
                        trans.Commit();
                    }
                }

                ISet <ElementId> familySymbolId = family.GetFamilySymbolIds();
                foreach (ElementId id in familySymbolId)
                {
                    // Get name from buffer to compare
                    if (family.Document.GetElement(id).Name == FamilySymbol && FamilySymbol != null)
                    {
                        symbol = family.Document.GetElement(id) as FamilySymbol;
                    }
                }
                uidoc.PostRequestForElementTypePlacement(symbol);
            }
            Tools.CollectFamilyData(doc);
            //Tools.CreateImages(doc);
        }