示例#1
1
        /// <summary>
        /// Obtains the facing direction of the window.
        /// </summary>
        /// <param name="wall">The window.</param>
        /// <returns>A normalized XYZ direction vector.</returns>
        protected XYZ GetWindowDirection(FamilyInstance window)
        {
            Options options = new Options();

            // Extract the geometry of the window.
            GeometryElement geomElem = window.get_Geometry(options);

            foreach (GeometryObject geomObj in geomElem.Objects)
            {
                // We expect there to be one main Instance in each window.  Ignore the rest of the geometry.
                GeometryInstance instance = geomObj as GeometryInstance;
                if (instance != null)
                {
                    // Obtain the Instance's transform and the nominal facing direction (Y-direction).
                    Transform t = instance.Transform;
                    XYZ facingDirection = t.BasisY;

                    // If the window is flipped in one direction, but not the other, the transform is left handed.
                    // The Y direction needs to be reversed to obtain the facing direction.
                    if ((window.FacingFlipped && !window.HandFlipped) || (!window.FacingFlipped && window.HandFlipped))
                        facingDirection = -facingDirection;

                    // Because the need to perform this operation on instances is so common,
                    // the Revit API exposes this calculation directly as the FacingOrientation property
                    // as shown in GetWindowDirectionAlternate()

                    return facingDirection;
                }
            }
            return XYZ.BasisZ;
        }
示例#2
0
文件: DoorFamily.cs 项目: AMEE/revit
 /// <summary>
 ///  construct function.
 /// </summary>
 /// <param name="doorFamily"> one door family</param>
 /// <param name="app">Revit application</param>
 public DoorFamily(Family doorFamily, UIApplication app)
 {
     m_app         = app;
      m_family      = doorFamily;
      // one door instance which belongs to this family and neither flipped nor mirrored.
      m_oneInstance = CreateOneInstanceWithThisFamily();
 }
        /// <summary>
        /// Returns a reference to the FAMILY parameter (as a simple Parameter data type) on the given instance
        /// for the parameter with the given name.  Will return the parameter
        /// whether it is an instance or type parameter.
        /// Returns null if no parameter on the instance was found.
        /// </summary>
        /// <param name="nestedFamilyInstance">An instance of a nested family file</param>
        /// <param name="parameterName">The name of the desired parameter to get a reference to</param>
        /// <remarks>
        /// Even though the data type returned is the more generic Parameter type, it will
        /// actually be for the data of the internal FamilyParameter object.
        /// </remarks>
        /// <returns></returns>
        public static Parameter GetFamilyParameter(
            FamilyInstance nestedFamilyInstance,
            string parameterName)
        {
            // Following good SOA practices, verify the
              // incoming parameters before attempting to proceed.

              if( nestedFamilyInstance == null )
              {
            throw new ArgumentNullException(
              "nestedFamilyInstance" );
              }

              if( string.IsNullOrEmpty( parameterName ) )
              {
            throw new ArgumentNullException(
              "parameterName" );
              }

              Parameter oResult = null;

              //See if the parameter is an Instance parameter
              oResult = nestedFamilyInstance.get_Parameter(
            parameterName );

              // No?  See if it's a Type parameter
              if( oResult == null )
              {
            oResult = nestedFamilyInstance.Symbol.get_Parameter(
              parameterName );
              }
              return oResult;
        }
示例#4
0
文件: ProfileBeam.cs 项目: AMEE/revit
        Matrix4 m_MatrixZaxis = null; //transform points to plane whose normal is Zaxis of beam

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="beam">beam to create opening on</param>
        /// <param name="commandData">object which contains reference to Revit Application</param>
        public ProfileBeam(FamilyInstance beam, ExternalCommandData commandData)
            : base(commandData)
        {
            m_data = beam;
            List<List<Edge>> faces = GetFaces(m_data);
            m_points = GetNeedPoints(faces);
            m_to2DMatrix = GetTo2DMatrix();
            m_moveToCenterMatrix = ToCenterMatrix();
        }
示例#5
0
        RebarBarType m_verticalType = null; //type of the vertical rebar

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructor of the ColumnFramReinMaker
        /// </summary>
        /// <param name="commandData">the ExternalCommandData reference</param>
        /// <param name="hostObject">the host column</param>
        public ColumnFramReinMaker(ExternalCommandData commandData, FamilyInstance hostObject)
            : base(commandData, hostObject)
        {
            //create a new options for current project
             Options geoOptions = commandData.Application.Application.Create.NewGeometryOptions();
             geoOptions.ComputeReferences = true;

             //create a ColumnGeometrySupport instance
             m_geometry = new ColumnGeometrySupport(hostObject, geoOptions);
        }
示例#6
0
 /*
  * Initialize beacon object from FamilyInstance and LocationPoint
  *
  */
 public Beacon(FamilyInstance fi, LocationPoint lp)
 {
     this.categoryName = fi.Category.Name;
     this.beaconType = fi.Name;
     this.elementId = fi.Id;
     // Stores as feet internally so convert to meters
     this.xLoc = Utilities.feetToMeters(lp.Point.X);
     this.yLoc = Utilities.feetToMeters(lp.Point.Y);
     this.zLoc = Utilities.feetToMeters(lp.Point.Z);
 }
示例#7
0
 public override bool Recognization(FamilyInstance fi)
 {
     _fi = fi;
     if (TryGetFIFloor(_doc))
     {
         --_floor;
         if (_floor < 0) return false;
         else return true;
     }
     else return false;
 }
示例#8
0
        /// <summary>
        /// Retrieve the family instance data to store in 
        /// the external database for the given component
        /// and return it as a dictionary in a JSON 
        /// formatted string.
        /// Obsolete, replaced by GetInstanceData method.
        /// </summary>
        string GetComponentDataJson(
            FamilyInstance a,
            Transform geoTransform)
        {
            Document doc = a.Document;
              FamilySymbol symbol = a.Symbol;

              XYZ location = Util.GetLocation( a );

              XYZ geolocation = geoTransform.OfPoint(
            location );

              string properties = Util.GetPropertiesJson(
            a.GetOrderedParameters() );

              // /a/src/web/CompHoundWeb/model/instance.js
              // _id         : UniqueId // suppress automatic generation
              // project    : String
              // path       : String
              // family     : String
              // symbol     : String
              // level      : String
              // x          : Number
              // y          : Number
              // z          : Number
              // easting    : Number // Geo2d?
              // northing   : Number
              // properties : String // json dictionary of instance properties and values

              string s = string.Format(
            "\"_id\": \"{0}\", "
            + "\"project\": \"{1}\", "
            + "\"path\": \"{2}\", "
            + "\"family\": \"{3}\", "
            + "\"symbol\": \"{4}\", "
            + "\"level\": \"{5}\", "
            + "\"x\": \"{6}\", "
            + "\"y\": \"{7}\", "
            + "\"z\": \"{8}\", "
            + "\"easting\": \"{9}\", "
            + "\"northing\": \"{10}\", "
            + "\"properties\": \"{11}\"",
            a.UniqueId, doc.Title, doc.PathName,
            symbol.FamilyName, symbol.Name,
            doc.GetElement( a.LevelId ).Name,
            Util.RealString( location.X ),
            Util.RealString( location.Y ),
            Util.RealString( location.Z ),
            Util.RealString( geolocation.X ),
            Util.RealString( geolocation.Y ),
            properties );

              return "{" + s + "}";
        }
    public JtPlacement2dInt( FamilyInstance fi )
    {
      LocationPoint lp = fi.Location as LocationPoint;

      Debug.Assert( null != lp,
        "expected valid family instanace location point" );

      Translation = new Point2dInt( lp.Point );

      Rotation = Util.ConvertRadiansToDegrees( lp.Rotation );

      SymbolId = fi.Symbol.UniqueId;
    }
示例#10
0
文件: CorbelFrame.cs 项目: AMEE/revit
        /// <summary>
        /// Constructor to initialize the fields.
        /// </summary>
        /// <param name="corbel">Corbel family instance</param>
        /// <param name="profile">Trapezoid profile</param>
        /// <param name="path">Extrusion Line</param>
        /// <param name="hostDepth">Corbel Host Depth</param>
        /// <param name="hostTopCorverDistance">Corbel Host cover distance</param>
        public CorbelFrame(FamilyInstance corbel, Trapezoid profile,
                Line path, double hostDepth, double hostTopCorverDistance)
        {
            m_profile = profile;
            m_extrusionLine = path;
            m_corbel = corbel;
            m_hostDepth = hostDepth;
            m_hostCoverDistance = hostTopCorverDistance;

            // Get the cover distance of corbel from CommonCoverType.
            RebarHostData rebarHost = RebarHostData.GetRebarHostData(m_corbel);
            m_corbelCoverDistance = rebarHost.GetCommonCoverType().CoverDistance;
        }
示例#11
0
        double m_columnWidth; //the width of the column

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor for the ColumnGeometrySupport
        /// </summary>
        /// <param name="element">the column which the rebars are placed on</param>
        /// <param name="geoOptions">the geometry option</param>
        public ColumnGeometrySupport(FamilyInstance element, Options geoOptions)
            : base(element, geoOptions)
        {
            // assert the host element is a column
            if (!element.StructuralType.Equals(StructuralType.Column))
            {
                throw new Exception("ColumnGeometrySupport can only work for column instance.");
            }

            // Get the length, width and height of the column.
            m_columnHeight = GetDrivingLineLength();
            m_columnLength = GetColumnLength();
            m_columnWidth = GetColumnWidth();
        }
示例#12
0
        double m_beamWidth; //the width of the beam

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="element">the beam which the rebars are placed on</param>
        /// <param name="geoOptions">the geometry option</param>
        public BeamGeometrySupport(FamilyInstance element, Options geoOptions)
            : base(element, geoOptions)
        {
            // assert the host element is a beam
            if (!element.StructuralType.Equals(StructuralType.Beam))
            {
                throw new Exception("BeamGeometrySupport can only work for beam instance.");
            }

            // Get the length, width and height of the beam.
            m_beamLength = GetDrivingLineLength();
            m_beamWidth = GetBeamWidth();
            m_beamHeight = GetBeamHeight();
        }
示例#13
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        /// <param name="e">Accepts generic element (after processing) as input</param>
        public LightFixture(Element e, FamilyInstance fi)
        {
            // Set properties initially based on passed FamilyInstance
            CandlePower = e.get_Parameter(BuiltInParameter.FBX_LIGHT_LIMUNOUS_INTENSITY).AsDouble();
            Lumens = e.get_Parameter(BuiltInParameter.FBX_LIGHT_LIMUNOUS_FLUX).AsDouble();
            Efficacy = e.get_Parameter(BuiltInParameter.FBX_LIGHT_EFFICACY).AsDouble();
            LightLossFactor = e.get_Parameter(BuiltInParameter.FBX_LIGHT_TOTAL_LIGHT_LOSS).AsDouble();
            CoefficientOfUtilization = e.get_Parameter(BuiltInParameter.RBS_ELEC_CALC_COEFFICIENT_UTILIZATION).AsDouble();

            Elevation = fi.get_Parameter(BuiltInParameter.INSTANCE_ELEVATION_PARAM).AsDouble();

            LocationPoint = fi.Location as LocationPoint;

            // Future
            // TODO: Get photometric file and parse IES to provide correct
        }
示例#14
0
文件: Properties.cs 项目: AMEE/revit
 /// <summary>
 /// get this family instance's properties to display.
 /// </summary>
 /// <param name="f">a In-Place family instance</param>
 public Properties(FamilyInstance f)
 {
     m_ID = f.Id.IntegerValue;
     m_Name = f.Name;
     m_Family = f.Symbol.Family.Name;
     m_Type = f.Symbol.Name;
     m_StructuralType = f.StructuralType.ToString();
     try
     {
         m_StructuralUsage = f.StructuralUsage.ToString();
     }
     catch(Exception)
     {
         m_StructuralUsage = null;
     }
     m_Material = f.StructuralMaterialType.ToString();
 }
        /// <summary>
        /// Returns a reference to the FAMILY parameter (as a simple Parameter data type) on the given instance
        /// for the parameter with the given name.  Will return the parameter
        /// whether it is an instance or type parameter.
        /// Returns null if no parameter on the instance was found.
        /// </summary>
        /// <param name="nestedFamilyInstance">An instance of a nested family file</param>
        /// <param name="parameterName">The name of the desired parameter to get a reference to</param>
        /// <remarks>
        /// Even though the data type returned is the more generic Parameter type, it will
        /// actually be for the data of the internal FamilyParameter object.
        /// </remarks>
        /// <returns></returns>
        public static Parameter GetFamilyParameter(
            FamilyInstance nestedFamilyInstance,
            string parameterName)
        {
            // Following good SOA practices, verify the
              // incoming parameters before attempting to proceed.

              if( nestedFamilyInstance == null )
              {
            throw new ArgumentNullException(
              "nestedFamilyInstance" );
              }

              if( string.IsNullOrEmpty( parameterName ) )
              {
            throw new ArgumentNullException(
              "parameterName" );
              }

              Parameter oResult = null;

              // See if the parameter is an Instance parameter

              //oResult = nestedFamilyInstance.get_Parameter( parameterName ); // 2014

              Debug.Assert( 2 > nestedFamilyInstance.GetParameters( parameterName ).Count,
            "ascertain that there are not more than one parameter of the given name" );

              oResult = nestedFamilyInstance.LookupParameter( parameterName ); // 2015

              // No?  See if it's a Type parameter

              if( oResult == null )
              {
            //oResult = nestedFamilyInstance.Symbol.get_Parameter( parameterName ); // 2014

            Debug.Assert( 2 > nestedFamilyInstance.Symbol.GetParameters( parameterName ).Count,
              "ascertain that there are not more than one parameter of the given name" );

            oResult = nestedFamilyInstance.Symbol.LookupParameter( parameterName ); // 2015
              }
              return oResult;
        }
示例#16
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);
        }
示例#17
0
        public static IOpening ToSAM_Opening(this FamilyInstance familyInstance, ConvertSettings convertSettings)
        {
            if (familyInstance == null)
            {
                return(null);
            }

            IOpening result = convertSettings?.GetObject <IOpening>(familyInstance.Id);

            if (result != null)
            {
                return(result);
            }

            if (Core.Revit.Query.Simplified(familyInstance))
            {
                result = Core.Revit.Query.IJSAMObjects <IOpening>(familyInstance)?.FirstOrDefault();
                if (result != null)
                {
                    convertSettings?.Add(familyInstance.Id, result);
                    return(result);
                }
            }

            Point3D point3D_Location = Geometry.Revit.Query.LocationPoint3D(familyInstance);

            if (point3D_Location == null)
            {
                List <Solid> solids = Core.Revit.Query.Solids(familyInstance, new Options());
                solids?.RemoveAll(x => x.Volume == 0);
                if (solids == null || solids.Count == 0)
                {
                    return(null);
                }

                if (solids.Count > 1)
                {
                    solids.Sort((x, y) => y.Volume.CompareTo(x.Volume));
                }

                point3D_Location = solids[0].ComputeCentroid()?.ToSAM();
            }

            if (point3D_Location == null)
            {
                return(null);
            }

            OpeningType openingType = ToSAM_OpeningType(familyInstance.Symbol, convertSettings);

            if (openingType == null)
            {
                return(null);
            }

            BuiltInCategory builtInCategory_Host = BuiltInCategory.INVALID;

            HostObject hostObject = familyInstance.Host as HostObject;

            if (hostObject != null)
            {
                builtInCategory_Host = (BuiltInCategory)hostObject.Category.Id.IntegerValue;
            }

            Vector3D axisX  = null;
            Vector3D normal = null;
            Vector3D axisY  = null;

            if (builtInCategory_Host == BuiltInCategory.OST_Roofs)
            {
                axisX  = familyInstance.HandOrientation.ToSAM_Vector3D(false);
                axisY  = familyInstance.FacingOrientation.ToSAM_Vector3D(false);
                normal = Geometry.Spatial.Query.AxisY(axisY, axisX);
            }
            else
            {
                axisX  = familyInstance.HandOrientation.ToSAM_Vector3D(false);
                normal = familyInstance.FacingOrientation.ToSAM_Vector3D(false);
                axisY  = Geometry.Spatial.Query.AxisY(normal, axisX);
            }


            Geometry.Spatial.Plane plane = Geometry.Spatial.Create.Plane(point3D_Location, axisX, axisY);
            if (!plane.Normal.SameHalf(normal))
            {
                plane.FlipZ(false);
            }

            List <Face3D> face3Ds = Geometry.Revit.Convert.ToSAM_Geometries <Face3D>(familyInstance);

            if (face3Ds == null || face3Ds.Count == 0)
            {
                return(null);
            }

            List <Point2D> point2Ds = new List <Point2D>();

            foreach (Face3D face3D_Temp in face3Ds)
            {
                IClosedPlanar3D closedPlanar3D = face3D_Temp.GetExternalEdge3D();
                if (closedPlanar3D is ICurvable3D)
                {
                    List <ICurve3D> curve3Ds = ((ICurvable3D)closedPlanar3D).GetCurves();
                    foreach (ICurve3D curve3D in curve3Ds)
                    {
                        ICurve3D curve3D_Temp = plane.Project(curve3D);
                        point2Ds.Add(plane.Convert(curve3D_Temp.GetStart()));
                    }
                }
            }

            if (point2Ds == null || point2Ds.Count == 0)
            {
                return(null);
            }

            Rectangle2D rectangle2D = Geometry.Planar.Create.Rectangle2D(point2Ds);

            result = Analytical.Create.Opening(openingType, new Face3D(plane, rectangle2D));
            result.UpdateParameterSets(familyInstance);

            convertSettings?.Add(familyInstance.Id, result);

            return(result);
        }
示例#18
0
        private string CalculateDoorOperationStyle(FamilyInstance currElem, Transform trf)
        {
            int    leftPosYArcCount     = 0;
            int    leftNegYArcCount     = 0;
            int    rightPosYArcCount    = 0;
            int    rightNegYArcCount    = 0;
            int    fullCircleCount      = 0;
            int    leftHalfCircleCount  = 0;
            int    rightHalfCircleCount = 0;
            double allowance            = 0.0001;

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

            FamilySymbol famSymbol = currElem.Symbol;

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

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

            Transform doorWindowTrf = ExporterIFCUtils.GetTransformForDoorOrWindow(currElem, famSymbol, FlippedX, FlippedY);

            IList <Curve> origArcs = GeometryUtil.get2DArcOrLineFromSymbol(currElem, allCurveType: false, inclArc: true);

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

            BoundingBoxXYZ doorBB = GetBoundingBoxFromSolids(currElem);
            XYZ            bbMin  = doorWindowTrf.OfPoint(doorBB.Min);
            XYZ            bbMax  = doorWindowTrf.OfPoint(doorBB.Max);

            // Reorganize the bbox min and max after transform
            double xmin = bbMin.X, xmax = bbMax.X, ymin = bbMin.Y, ymax = bbMax.Y, zmin = bbMin.Z, zmax = bbMax.Z;

            if (bbMin.X > bbMax.X)
            {
                xmin = bbMax.X;
                xmax = bbMin.X;
            }
            if (bbMin.Y > bbMax.Y)
            {
                ymin = bbMax.Y;
                ymax = bbMin.Y;
            }
            if (bbMin.Z > bbMax.Z)
            {
                zmin = bbMax.Z;
                zmax = bbMin.Z;
            }
            bbMin = new XYZ(xmin - tolForArcCenter, ymin - tolForArcCenter, zmin - tolForArcCenter);
            bbMax = new XYZ(xmax + tolForArcCenter, ymax + tolForArcCenter, zmax + tolForArcCenter);

            IList <XYZ>        arcCenterLocations = new List <XYZ>();
            SortedSet <double> arcRadii = new SortedSet <double>();

            foreach (Arc arc in origArcs)
            {
                Arc trfArc = arc.CreateTransformed(doorWindowTrf) as Arc;

                // Filter only Arcs that is on XY plane and at the Z=0 of the Door/Window transform
                if (!(MathUtil.IsAlmostEqual(Math.Abs(trfArc.Normal.Z), 1.0) /*&& MathUtil.IsAlmostEqual(Math.Abs(trfArc.Center.Z), Math.Abs(doorWindowTrf.Origin.Z))*/))
                {
                    continue;
                }

                // Filter only Arcs that have center within the bounding box
                if (trfArc.Center.X > bbMax.X || trfArc.Center.X < bbMin.X || trfArc.Center.Y > bbMax.Y || trfArc.Center.Y < bbMin.Y)
                {
                    continue;
                }

                if (!trfArc.IsBound)
                {
                    fullCircleCount++;
                }
                else
                {
                    double angleOffOfXY = 0;
                    XYZ    v1           = CorrectNearlyZeroValueToZero((trfArc.GetEndPoint(0) - trfArc.Center).Normalize());
                    XYZ    v2           = CorrectNearlyZeroValueToZero((trfArc.GetEndPoint(1) - trfArc.Center).Normalize());
                    angleOffOfXY = Math.Acos(v1.DotProduct(v2));

                    if ((Math.Abs(angleOffOfXY) > (60.0 / 180.0) * Math.PI && Math.Abs(angleOffOfXY) < (240.0 / 180.0) * Math.PI) &&
                        ((v1.Y > 0.0 && v2.Y < 0.0) || (v1.Y < 0.0 && v2.Y > 0.0)))       // Consider the opening swing between -30 to +30 up to -120 to +120 degree, where Y axes must be at the opposite sides
                    {
                        if (trfArc.Center.X >= -tolForArcCenter && trfArc.Center.X <= tolForArcCenter)
                        {
                            leftHalfCircleCount++;
                        }
                        else
                        {
                            rightHalfCircleCount++;
                        }
                    }
                    else if ((Math.Abs(angleOffOfXY) > (30.0 / 180.0) * Math.PI && Math.Abs(angleOffOfXY) < (170.0 / 180.0) * Math.PI) &&
                             (MathUtil.IsAlmostEqual(Math.Abs(v1.X), 1.0, allowance) || MathUtil.IsAlmostEqual(Math.Abs(v2.X), 1.0, allowance)))  // Consider the opening swing between 30 to 170 degree, beginning at X axis
                    {
                        XYZ yDir;
                        if (MathUtil.IsAlmostEqual(Math.Abs(v1.Y), Math.Abs(Math.Sin(angleOffOfXY)), 0.01))
                        {
                            yDir = v1;
                        }
                        else
                        {
                            yDir = v2;
                        }

                        // if the Normal is pointing to -Z, it is flipped. Flip the Y if it is
                        if (MathUtil.IsAlmostEqual(trfArc.Normal.Z, -1.0))
                        {
                            yDir = yDir.Negate();
                        }

                        // Check the center location in the X-direction to determine LEFT/RIGHT
                        if (trfArc.Center.X >= -tolForArcCenter && trfArc.Center.X <= tolForArcCenter)
                        {
                            // on the LEFT
                            if ((yDir.Y > 0.0 && trfArc.YDirection.Y > 0.0) || (yDir.Y < 0.0 && trfArc.YDirection.Y < 0.0))
                            {
                                leftPosYArcCount++;
                            }
                            else if ((yDir.Y > 0.0 && trfArc.YDirection.Y < 0.0) || (yDir.Y < 0.0 && trfArc.YDirection.Y > 0.0))
                            {
                                leftNegYArcCount++;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            // on the RIGHT
                            if ((yDir.Y > 0.0 && trfArc.YDirection.Y > 0.0) || (yDir.Y < 0.0 && trfArc.YDirection.Y < 0.0))
                            {
                                rightPosYArcCount++;
                            }
                            else if ((yDir.Y > 0.0 && trfArc.YDirection.Y < 0.0) || (yDir.Y < 0.0 && trfArc.YDirection.Y > 0.0))
                            {
                                rightNegYArcCount++;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    else
                    {
                        continue;
                    }

                    // Collect all distinct Arc Center if it is counted as the door opening, to ensure that for cases that there are more than 2 leafs, it is not worngly labelled
                    bool foundExisting = false;
                    foreach (XYZ existingCenter in arcCenterLocations)
                    {
                        if ((trfArc.Center.X > existingCenter.X - tolForArcCenter) && (trfArc.Center.X <= existingCenter.X + tolForArcCenter) &&
                            (trfArc.Center.Y > existingCenter.Y - tolForArcCenter) && (trfArc.Center.Y <= existingCenter.Y + tolForArcCenter))
                        {
                            foundExisting = true;
                            break;
                        }
                    }
                    if (!foundExisting)
                    {
                        arcCenterLocations.Add(trfArc.Center);
                        arcRadii.Add(trfArc.Radius);
                    }
                }
            }

            // When only full circle(s) exists
            if (fullCircleCount > 0 &&
                rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftPosYArcCount == 0 && leftNegYArcCount == 0 && rightPosYArcCount == 0 && rightNegYArcCount == 0)
            {
                return("REVOLVING");
            }

            // There are more than 2 arc centers, no IFC Door operation type fits this, return NOTDEFINED
            if (arcCenterLocations.Count > 2)
            {
                return("NOTDEFINED");
            }

            // When half circle arc(s) exists
            if (leftHalfCircleCount > 0 && fullCircleCount == 0)
            {
                if (rightHalfCircleCount == 0 && leftPosYArcCount == 0 && leftNegYArcCount == 0 && rightPosYArcCount == 0 && rightNegYArcCount == 0)
                {
                    return("DOUBLE_SWING_LEFT");
                }

                if ((rightHalfCircleCount > 0 || (rightPosYArcCount > 0 && rightNegYArcCount > 0)) && leftPosYArcCount == 0 && leftNegYArcCount == 0)
                {
                    return("DOUBLE_DOOR_DOUBLE_SWING");
                }
            }

            if (rightHalfCircleCount > 0 && fullCircleCount == 0)
            {
                if (leftHalfCircleCount == 0 && leftPosYArcCount == 0 && leftNegYArcCount == 0 && rightPosYArcCount == 0 && rightNegYArcCount == 0)
                {
                    return("DOUBLE_SWING_RIGHT");
                }

                if ((leftHalfCircleCount > 0 || (leftPosYArcCount > 0 && leftNegYArcCount > 0)) && rightPosYArcCount == 0 && rightNegYArcCount == 0)
                {
                    return("DOUBLE_DOOR_DOUBLE_SWING");
                }
            }

            // When only 90-degree arc(s) exists
            if (leftPosYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftNegYArcCount == 0 && rightPosYArcCount == 0 && rightNegYArcCount == 0)
            {
                // if the arc is less than 50%of the boundingbox, treat this to be a door with partially fixed panel
                if (arcRadii.Max < (bbMax.X - bbMin.X) * 0.5)
                {
                    if (ExporterCacheManager.ExportOptionsCache.ExportAsOlderThanIFC4)
                    {
                        return("NOTDEFINED");
                    }
                    else
                    {
                        return("SWING_FIXED_LEFT");
                    }
                }
                else
                {
                    return("SINGLE_SWING_LEFT");
                }
            }

            if (rightPosYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftNegYArcCount == 0 && leftPosYArcCount == 0 && rightNegYArcCount == 0)
            {
                // if the arc is less than 50%of the boundingbox, treat this to be a door with partially fixed panel
                if (arcRadii.Max < (bbMax.X - bbMin.X) * 0.5)
                {
                    if (ExporterCacheManager.ExportOptionsCache.ExportAsOlderThanIFC4)
                    {
                        return("NOTDEFINED");
                    }
                    else
                    {
                        return("SWING_FIXED_RIGHT");
                    }
                }
                else
                {
                    return("SINGLE_SWING_RIGHT");
                }
            }

            if (leftPosYArcCount > 0 && leftNegYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && rightPosYArcCount == 0 && rightNegYArcCount == 0)
            {
                return("DOUBLE_SWING_LEFT");
            }

            if (rightPosYArcCount > 0 && rightNegYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftNegYArcCount == 0 && leftPosYArcCount == 0)
            {
                return("DOUBLE_SWING_RIGHT");
            }

            if (leftPosYArcCount > 0 && rightPosYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftNegYArcCount == 0 && rightNegYArcCount == 0)
            {
                return("DOUBLE_DOOR_SINGLE_SWING");
            }

            if (leftPosYArcCount > 0 && rightPosYArcCount > 0 && leftNegYArcCount > 0 && rightNegYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0)
            {
                return("DOUBLE_DOOR_DOUBLE_SWING");
            }

            if (leftPosYArcCount > 0 && rightNegYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftNegYArcCount == 0 && rightPosYArcCount == 0)
            {
                return("DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_RIGHT");
            }

            if (leftNegYArcCount > 0 && rightPosYArcCount > 0 &&
                fullCircleCount == 0 && rightHalfCircleCount == 0 && leftHalfCircleCount == 0 && leftPosYArcCount == 0 && rightNegYArcCount == 0)
            {
                return("DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_LEFT");
            }

            return("NOTDEFINED");
        }
示例#19
0
        /// <summary>
        /// Adds openings to an element.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="elementHandles">The parent handles.</param>
        /// <param name="curveLoops">The parent CurveLoops.</param>
        /// <param name="element">The element.</param>
        /// <param name="lcs">The local coordinate system.</param>
        /// <param name="scaledWidth">The width.</param>
        /// <param name="range">The range.</param>
        /// <param name="setter">The placement setter.</param>
        /// <param name="localPlacement">The local placement.</param>
        /// <param name="localWrapper">The wrapper.</param>
        public static void AddOpeningsToElement(ExporterIFC exporterIFC,
                                                IList <IFCAnyHandle> elementHandles, IList <CurveLoop> curveLoops, Element element,
                                                Transform lcs, double scaledWidth, IFCRange range, PlacementSetter setter,
                                                IFCAnyHandle localPlacement, ProductWrapper localWrapper)
        {
            if (lcs == null && ((curveLoops?.Count ?? 0) > 0))
            {
                // assumption: first curve loop defines the plane.
                Plane hostObjPlane = curveLoops[0].HasPlane() ? curveLoops[0].GetPlane(): null;

                if (hostObjPlane != null)
                {
                    lcs = GeometryUtil.CreateTransformFromPlane(hostObjPlane);
                }
            }

            IList <IFCOpeningData> openingDataList = ExporterIFCUtils.GetOpeningData(exporterIFC,
                                                                                     element, lcs, range);
            IFCFile file = exporterIFC.GetFile();

            int openingIndex = 0;

            foreach (IFCOpeningData openingData in openingDataList)
            {
                openingIndex++;

                Element openingElem = element.Document.GetElement(openingData.OpeningElementId);
                if (openingElem == null)
                {
                    openingElem = element;
                }

                bool           currentWallIsHost = false;
                FamilyInstance openingFInst      = openingElem as FamilyInstance;
                if (openingFInst != null && openingFInst.Host != null)
                {
                    if (openingFInst.Host.Id == element.Id)
                    {
                        currentWallIsHost = true;
                    }
                }

                // Don't export the opening if WallSweep category has been turned off.
                // This is currently restricted to WallSweeps because the element responsible for the opening could be a variety of things,
                // including a line as part of the elevation profile of the wall.
                // As such, we will restrict which element types we check for CanExportElement.
                if ((openingElem is WallSweep) &&
                    (!ElementFilteringUtil.CanExportElement(exporterIFC, openingElem, true)))
                {
                    continue;
                }

                IList <IFCExtrusionData> extrusionDataList = openingData.GetExtrusionData();
                IFCAnyHandle             parentHandle      = FindParentHandle(elementHandles, curveLoops, extrusionDataList);

                string            predefinedType;
                IFCExportInfoPair exportType = ExporterUtil.GetProductExportType(exporterIFC,
                                                                                 openingElem, out predefinedType);
                bool exportingDoorOrWindow = (exportType.ExportInstance == IFCEntityType.IfcDoor ||
                                              exportType.ExportType == IFCEntityType.IfcDoorType ||
                                              exportType.ExportInstance == IFCEntityType.IfcWindow ||
                                              exportType.ExportType == IFCEntityType.IfcWindowType);

                bool isDoorOrWindowOpening = IsDoorOrWindowOpening(openingElem, element,
                                                                   exportingDoorOrWindow);

                if (isDoorOrWindowOpening && currentWallIsHost)
                {
                    DoorWindowDelayedOpeningCreator delayedCreator =
                        DoorWindowDelayedOpeningCreator.Create(exporterIFC, openingData, scaledWidth,
                                                               element.Id, parentHandle, setter.LevelId);
                    if (delayedCreator != null)
                    {
                        ExporterCacheManager.DoorWindowDelayedOpeningCreatorCache.Add(delayedCreator);
                        continue;
                    }
                }

                IList <Solid> solids     = openingData.GetOpeningSolids();
                int           solidIndex = 0;
                foreach (Solid solid in solids)
                {
                    solidIndex++;

                    using (IFCExtrusionCreationData extrusionCreationData = new IFCExtrusionCreationData())
                    {
                        extrusionCreationData.SetLocalPlacement(ExporterUtil.CreateLocalPlacement(file, localPlacement, null));
                        extrusionCreationData.ReuseLocalPlacement = true;

                        string openingGUID = CreateOpeningGUID(openingElem, range, openingIndex, solidIndex);

                        CreateOpening(exporterIFC, parentHandle, element, openingElem, openingGUID, solid, scaledWidth, openingData.IsRecess, extrusionCreationData,
                                      setter, localWrapper);
                    }
                }

                foreach (IFCExtrusionData extrusionData in extrusionDataList)
                {
                    solidIndex++;

                    if (extrusionData.ScaledExtrusionLength < MathUtil.Eps())
                    {
                        extrusionData.ScaledExtrusionLength = scaledWidth;
                    }

                    string openingGUID = CreateOpeningGUID(openingElem, range, openingIndex, solidIndex);

                    CreateOpening(exporterIFC, parentHandle, localPlacement, element, openingElem,
                                  openingGUID, extrusionData, lcs, openingData.IsRecess, setter, localWrapper);
                }
            }
        }
示例#20
0
        /// <summary>
        /// This method parses geometry information of given Corbel to construct the CorbelFrame.
        /// </summary>
        /// <param name="corbel">Given corbel family instance to parse</param>
        /// <returns>CorbelFrame object</returns>
        public static CorbelFrame ParseCorbelGeometry(FamilyInstance corbel)
        {
            // Get Corbel Host information.
            Element   corbelHost     = corbel.Host;
            Reference corbelHostFace = corbel.HostFace;

            PlanarFace hostPlane  = corbelHost.GetGeometryObjectFromReference(corbelHostFace) as PlanarFace;
            XYZ        hostNormal = GetNormalOutside(hostPlane);

            // Extract the faces in Corbel parallel with Corbel host face.
            Solid      corbelSolid      = GetElementSolid(corbel);
            PlanarFace corbelTopFace    = null;
            PlanarFace corbelBottomFace = null;

            foreach (Face face in corbelSolid.Faces)
            {
                PlanarFace planarFace = face as PlanarFace;
                XYZ        normal     = GetNormalOutside(planarFace);
                if (normal.IsAlmostEqualTo(hostNormal))
                {
                    corbelTopFace = planarFace;
                }
                else if (normal.IsAlmostEqualTo(-hostNormal))
                {
                    corbelBottomFace = planarFace;
                }
            }

            // Extract the faces in Corbel Host parallel with Corbel host face.
            Solid      hostSolid      = GetElementSolid(corbelHost);
            PlanarFace hostTopFace    = null;
            PlanarFace hostBottomFace = hostPlane;

            foreach (Face face in hostSolid.Faces)
            {
                PlanarFace planarFace = face as PlanarFace;
                XYZ        normal     = GetNormalOutside(planarFace);
                if (normal.IsAlmostEqualTo(-hostNormal))
                {
                    hostTopFace = planarFace;
                }
            }

            // Parse the side faces to find out the Trapezoid face.
            Edge       topEdge        = null;
            Edge       leftEdge       = null;
            Edge       bottomEdge     = null;
            Edge       rightEdge      = null;
            PlanarFace trapezoidFace  = null;
            int        foundEdgeIndex = -1;
            bool       foundTrapezoid = false;
            EdgeArray  bottomEdges    = corbelBottomFace.EdgeLoops.get_Item(0);

            foreach (Edge edge in bottomEdges)
            {
                bottomEdge = edge;
                foundEdgeIndex++;
                foundTrapezoid = IsTrapezoid(hostNormal, corbelBottomFace, bottomEdge,
                                             out trapezoidFace, out topEdge, out leftEdge, out rightEdge);
                if (foundTrapezoid)
                {
                    break;
                }
            }

            // Check to see if the Trapezoid faces was found.
            if (!foundTrapezoid)
            {
                // Throw if no any trapezoid face in corbel.
                throw new Exception("Didn't find the trapezoid face in corbel [Id:" + corbel.Id + "].");
            }

            Edge depthEdge = bottomEdges.get_Item((foundEdgeIndex + 1) % bottomEdges.Size);

            double hostDepth = GetDistance(hostTopFace, hostBottomFace);

            // Compute the host face cover distance.
            RebarHostData corbelHostData = RebarHostData.GetRebarHostData(corbelHost);
            // Get CoverType of the given host face
            RebarCoverType coverType = corbelHostData.GetCoverType(hostTopFace.Reference);

            // if the host face don't have a CoverType, then try to get the common CoverType.
            if (coverType == null)
            {
                coverType = corbelHostData.GetCommonCoverType();
            }
            // Get the Cover Distance
            double coverDistance = coverType.CoverDistance;

            // Construct the CorbelFrame from the given parsed trapezoid information.
            return(ConstructCorbelFrame(
                       corbel, depthEdge,
                       leftEdge, bottomEdge, rightEdge, topEdge,
                       corbel.Document, trapezoidFace,
                       hostDepth, coverDistance));
        }
示例#21
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var symbol  = (FamilySymbol)((Value.Container)args[0]).Item;
            var curves  = ((Value.List)args[1]).Item;
            var targets = ((Value.List)args[2]).Item;

            if (curves.Count() != targets.Count())
            {
                throw new Exception("The number of curves and the number of up vectors must be the same.");
            }

            var data = curves.Zip(targets, (first, second) => new Tuple <Curve, XYZ>((Curve)((Value.Container)first).Item, (XYZ)((Value.Container)second).Item));

            var instData = new List <FamilyInstanceCreationData>();

            int count = 0;

            foreach (var pair in data)
            {
                var curve  = pair.Item1;
                var target = pair.Item2;

                //calculate the desired rotation
                //we do this by finding the angle between the z axis
                //and vector between the start of the beam and the target point
                //both projected onto the start plane of the beam.

                XYZ zAxis = new XYZ(0, 0, 1);
                XYZ yAxis = new XYZ(0, 1, 0);

                //flatten the beam line onto the XZ plane
                //using the start's z coordinate
                XYZ start  = curve.get_EndPoint(0);
                XYZ end    = curve.get_EndPoint(1);
                XYZ newEnd = new XYZ(end.X, end.Y, start.Z); //drop end point to plane

                ////use the x axis of the curve's transform
                ////as the normal of the start plane
                //XYZ planeNormal = (curve.get_EndPoint(0) - curve.get_EndPoint(1)).Normalize();

                //catch the case where the end is directly above
                //the start, creating a normal with zero length
                //in that case, use the Z axis
                XYZ planeNormal = newEnd.IsAlmostEqualTo(start) ? zAxis : (newEnd - start).Normalize();

                XYZ target_project = target - target.DotProduct(planeNormal) * planeNormal;
                XYZ z_project      = zAxis - zAxis.DotProduct(planeNormal) * planeNormal;

                //double gamma = target_project.AngleTo(z_project);
                double gamma = target.AngleOnPlaneTo(zAxis.IsAlmostEqualTo(planeNormal) ? yAxis : zAxis, planeNormal);

                FamilyInstance instance = null;
                if (this.Elements.Count > count)
                {
                    if (dynUtils.TryGetElement(this.Elements[count], out instance))
                    {
                        if (instance.Symbol != symbol)
                        {
                            instance.Symbol = symbol;
                        }

                        //update the curve
                        var locCurve = instance.Location as LocationCurve;
                        locCurve.Curve = curve;
                    }
                    else
                    {
                        var beamData = new FamilyInstanceCreationData(curve, symbol, dynRevitSettings.DefaultLevel, StructuralType.Beam)
                        {
                            RotateAngle = gamma
                        };
                        instData.Add(beamData);
                    }
                }
                else
                {
                    var beamData = new FamilyInstanceCreationData(curve, symbol, dynRevitSettings.DefaultLevel, StructuralType.Beam)
                    {
                        RotateAngle = gamma
                    };
                    instData.Add(beamData);
                }

                count++;
            }

            //trim the elements collection
            foreach (var e in this.Elements.Skip(count))
            {
                this.DeleteElement(e);
            }

            FSharpList <Value> results = FSharpList <Value> .Empty;

            if (instData.Any())
            {
                var ids = dynRevitSettings.Doc.Document.Create.NewFamilyInstances2(instData);

                //add our batch-created instances ids'
                //to the elements collection
                ids.ToList().ForEach(x => Elements.Add(x));
            }

            //add all of the instances
            results = Elements.Aggregate(results, (current, id) => FSharpList <Value> .Cons(Value.NewContainer(dynRevitSettings.Doc.Document.GetElement(id)), current));
            results.Reverse();

            return(Value.NewContainer(results));
        }
示例#22
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);

                    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);

                    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

                    // 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);
            }
        }
示例#23
0
 private void AssignGuid(FamilyInstance fi, Guid guid, Schema instanceSchema, int run, string nickName)
 {
     Entity entity = null;
     try
     {
         entity = fi.GetEntity(instanceSchema);
     }
     catch (Exception ex)
     {
         Debug.Write("Error", ex.Message);
     }
     try
     {
         if (!entity.IsValid())
         {
             entity = new Entity(instanceSchema);
         }
         Field field = instanceSchema.GetField("InstanceID");
         entity.Set<string>(field, guid.ToString());
         field = instanceSchema.GetField("RunID");
         entity.Set<int>(field, run);
         field = instanceSchema.GetField("NickName");
         entity.Set<string>(field, nickName);
         fi.SetEntity(entity);
     }
     catch (Exception ex)
     {
         TaskDialog.Show("Error", ex.Message);
     }
 }
示例#24
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
        }
    }
示例#25
0
        /// <summary>
        /// Checks if element is external.
        /// </summary>
        /// <remarks>
        /// An element is considered external if either:
        ///   <li> A special Yes/No parameter "IsExternal" is applied to it or its type and it's value is set to "yes".</li>
        ///   <li> The element itself has information about being an external element.</li>
        /// All other elements are internal.
        /// </remarks>
        /// <param name="element">The element.</param>
        /// <returns>True if the element is external, false otherwise.</returns>
        public static bool IsElementExternal(Element element)
        {
            if (element == null)
            {
                return(false);
            }

            Document document = element.Document;

            // Look for a parameter "IsExternal", potentially localized.
            {
                ElementId elementId = element.Id;

                bool?maybeIsExternal = null;
                if (!ExporterCacheManager.IsExternalParameterValueCache.TryGetValue(elementId, out maybeIsExternal))
                {
                    int    intIsExternal          = 0;
                    string localExternalParamName = PropertySetEntryUtil.GetLocalizedIsExternal(ExporterCacheManager.LanguageType);
                    if ((localExternalParamName != null) && (ParameterUtil.GetIntValueFromElementOrSymbol(element, localExternalParamName, out intIsExternal) != null))
                    {
                        maybeIsExternal = (intIsExternal != 0);
                    }

                    if (!maybeIsExternal.HasValue && (ExporterCacheManager.LanguageType != LanguageType.English_USA))
                    {
                        string externalParamName = PropertySetEntryUtil.GetLocalizedIsExternal(LanguageType.English_USA);
                        if (ParameterUtil.GetIntValueFromElementOrSymbol(element, externalParamName, out intIsExternal) != null)
                        {
                            maybeIsExternal = (intIsExternal != 0);
                        }
                    }

                    ExporterCacheManager.IsExternalParameterValueCache.Add(new KeyValuePair <ElementId, bool?>(elementId, maybeIsExternal));
                }

                if (maybeIsExternal.HasValue)
                {
                    return(maybeIsExternal.Value);
                }
            }

            // Many element types have the FUNCTION_PARAM parameter.  If this is set, use its value.
            ElementType elementType = document.GetElement(element.GetTypeId()) as ElementType;
            int         elementFunction;

            if ((elementType != null) && ParameterUtil.GetIntValueFromElement(elementType, BuiltInParameter.FUNCTION_PARAM, out elementFunction) != null)
            {
                // Note that the WallFunction enum value is the same for many different kinds of objects.
                return(elementFunction != ((int)WallFunction.Interior));
            }

            // Specific element types that know if they are external or not if the built-in parameter isn't set.
            // Categories are used, and not types, to also support in-place families

            // Roofs are always external
            ElementId categoryId = element.Category.Id;

            if (categoryId == new ElementId(BuiltInCategory.OST_Roofs) ||
                categoryId == new ElementId(BuiltInCategory.OST_MassExteriorWall))
            {
                return(true);
            }

            // Mass interior walls are always internal
            if (categoryId == new ElementId(BuiltInCategory.OST_MassInteriorWall))
            {
                return(false);
            }

            // Family instances may be hosted on an external element
            if (element is FamilyInstance)
            {
                FamilyInstance familyInstance     = element as FamilyInstance;
                Element        familyInstanceHost = familyInstance.Host;
                if (familyInstanceHost == null)
                {
                    Reference familyInstanceHostReference = familyInstance.HostFace;
                    if (familyInstanceHostReference != null)
                    {
                        familyInstanceHost = document.GetElement(familyInstanceHostReference);
                    }
                }

                if (familyInstanceHost != null)
                {
                    return(IsElementExternal(familyInstanceHost));
                }
            }

            return(false);
        }
示例#26
0
        /// <summary>
        /// Find all child nodes of the specified element node
        /// </summary>
        /// <param name="elementNode">The specified element node to be analyzed</param>
        private void AppendChildren(TreeNode elementNode)
        {
            List <TreeNode> nodes = elementNode.ChildNodes;
            ConnectorSet    connectors;
            //
            // Get connector manager
            Element        element = GetElementById(elementNode.Id);
            FamilyInstance fi      = element as FamilyInstance;

            if (fi != null)
            {
                connectors = fi.MEPModel.ConnectorManager.Connectors;
            }
            else
            {
                MEPCurve mepCurve = element as MEPCurve;
                connectors = mepCurve.ConnectorManager.Connectors;
            }

            // Find connected connector for each connector
            foreach (Connector connector in connectors)
            {
                MEPSystem mepSystem = connector.MEPSystem;
                // Ignore the connector does not belong to any MEP System or belongs to another different MEP system
                if (mepSystem == null || !mepSystem.Id.IntegerValue.Equals(m_system.Id.IntegerValue))
                {
                    continue;
                }

                //
                // Get the direction of the TreeNode object
                if (elementNode.Parent == null)
                {
                    if (connector.IsConnected)
                    {
                        elementNode.Direction = connector.Direction;
                    }
                }
                else
                {
                    // If the connector is connected to the input connector, they will have opposite flow directions.
                    // Then skip it.
                    if (connector.IsConnectedTo(elementNode.InputConnector))
                    {
                        elementNode.Direction = connector.Direction;
                        continue;
                    }
                }

                // Get the connector connected to current connector
                Connector connectedConnector = GetConnectedConnector(connector);
                if (connectedConnector != null)
                {
                    TreeNode node = new TreeNode(m_document, connectedConnector.Owner.Id);
                    node.InputConnector = connector;
                    node.Parent         = elementNode;
                    nodes.Add(node);
                }
            }

            nodes.Sort(delegate(TreeNode t1, TreeNode t2)
            {
                return(t1.Id.IntegerValue > t2.Id.IntegerValue ? 1 : (t1.Id.IntegerValue < t2.Id.IntegerValue ? -1 : 0));
            }
                       );
        }
示例#27
0
        /// <summary>
        /// Get the open connector of the system if the system has no base equipment
        /// </summary>
        /// <param name="element">An element in the system</param>
        /// <param name="inputConnector">The connector of the previous element
        /// to which the element is connected </param>
        /// <returns>The found open connector</returns>
        private Connector GetOpenConnector(Element element, Connector inputConnector)
        {
            Connector        openConnector = null;
            ConnectorManager cm            = null;

            //
            // Get the connector manager of the element
            if (element is FamilyInstance)
            {
                FamilyInstance fi = element as FamilyInstance;
                cm = fi.MEPModel.ConnectorManager;
            }
            else
            {
                MEPCurve mepCurve = element as MEPCurve;
                cm = mepCurve.ConnectorManager;
            }

            foreach (Connector conn in cm.Connectors)
            {
                // Ignore the connector does not belong to any MEP System or belongs to another different MEP system
                if (conn.MEPSystem == null || !conn.MEPSystem.Id.IntegerValue.Equals(m_system.Id.IntegerValue))
                {
                    continue;
                }

                // If the connector is connected to the input connector, they will have opposite flow directions.
                if (inputConnector != null && conn.IsConnectedTo(inputConnector))
                {
                    continue;
                }

                // If the connector is not connected, it is the open connector
                if (!conn.IsConnected)
                {
                    openConnector = conn;
                    break;
                }

                //
                // If open connector not found, then look for it from elements connected to the element
                foreach (Connector refConnector in conn.AllRefs)
                {
                    // Ignore non-EndConn connectors and connectors of the current element
                    if (refConnector.ConnectorType != ConnectorType.End ||
                        refConnector.Owner.Id.IntegerValue.Equals(conn.Owner.Id.IntegerValue))
                    {
                        continue;
                    }

                    // Ignore connectors of the previous element
                    if (inputConnector != null && refConnector.Owner.Id.IntegerValue.Equals(inputConnector.Owner.Id.IntegerValue))
                    {
                        continue;
                    }

                    openConnector = GetOpenConnector(refConnector.Owner, conn);
                    if (openConnector != null)
                    {
                        return(openConnector);
                    }
                }
            }

            return(openConnector);
        }
示例#28
0
        /// <summary>
        /// Dump the node into XML file
        /// </summary>
        /// <param name="writer">XmlWriter object</param>
        public void DumpIntoXML(XmlWriter writer)
        {
            // Write node information
            Element        element = GetElementById(m_Id);
            FamilyInstance fi      = element as FamilyInstance;

            if (fi != null)
            {
                MEPModel mepModel = fi.MEPModel;
                String   type     = String.Empty;
                if (mepModel is MechanicalEquipment)
                {
                    type = "MechanicalEquipment";
                    writer.WriteStartElement(type);
                }
                else if (mepModel is MechanicalFitting)
                {
                    MechanicalFitting mf = mepModel as MechanicalFitting;
                    type = "MechanicalFitting";
                    writer.WriteStartElement(type);
                    writer.WriteAttributeString("Category", element.Category.Name);
                    writer.WriteAttributeString("PartType", mf.PartType.ToString());
                }
                else
                {
                    type = "FamilyInstance";
                    writer.WriteStartElement(type);
                    writer.WriteAttributeString("Category", element.Category.Name);
                }

                writer.WriteAttributeString("Name", element.Name);
                writer.WriteAttributeString("Id", element.Id.IntegerValue.ToString());
                writer.WriteAttributeString("Direction", m_direction.ToString());
                writer.WriteEndElement();
            }
            else
            {
                String type = element.GetType().Name;

                writer.WriteStartElement(type);
                writer.WriteAttributeString("Name", element.Name);
                writer.WriteAttributeString("Id", element.Id.IntegerValue.ToString());
                writer.WriteAttributeString("Direction", m_direction.ToString());
                writer.WriteEndElement();
            }

            foreach (TreeNode node in m_childNodes)
            {
                if (m_childNodes.Count > 1)
                {
                    writer.WriteStartElement("Path");
                }

                node.DumpIntoXML(writer);

                if (m_childNodes.Count > 1)
                {
                    writer.WriteEndElement();
                }
            }
        }
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.UI.UIApplication revit = commandData.Application;
            UIDocument project = revit.ActiveUIDocument;

            // Find the selection of beams in Revit
            ElementSet selection = new ElementSet();

            foreach (ElementId elementId in project.Selection.GetElementIds())
            {
                selection.Insert(project.Document.GetElement(elementId));
            }
            foreach (Autodesk.Revit.DB.Element e in selection)
            {
                FamilyInstance m = e as FamilyInstance;
                if (null != m)
                {
                    if (StructuralType.Beam == m.StructuralType)
                    {
                        // Store all the beams the user selected in Revit
                        m_beamCollection.Add(e);
                    }
                }
            }
            if (0 == m_beamCollection.Count)
            {
                message = "Can not find any beams.";
                return(Autodesk.Revit.UI.Result.Failed);
            }

            // Make sure all the beams have horizontal analytical line
            if (!CheckBeamHorizontal())
            {
                message = m_errorInformation;
                return(Autodesk.Revit.UI.Result.Failed);
            }

            // Search all the wall types in the Revit
            FilteredElementCollector filteredElementCollector = new FilteredElementCollector(project.Document);

            filteredElementCollector.OfClass(typeof(WallType));
            m_wallTypeCollection = filteredElementCollector.Cast <WallType>().ToList <WallType>();

            // Show the dialog for the user select the wall style
            using (CreateWallsUnderBeamsForm displayForm = new CreateWallsUnderBeamsForm(this))
            {
                if (DialogResult.OK != displayForm.ShowDialog())
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }

            // Create the walls which along and under the path of the beams.
            if (!BeginCreate(project.Document))
            {
                message = m_errorInformation;
                return(Autodesk.Revit.UI.Result.Failed);
            }

            // If everything goes right, return succeeded.
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
示例#30
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);
        }
示例#31
0
        /***************************************************/

        public static IEnumerable <IBHoMObject> FromRevit(this FamilyInstance familyInstance, Discipline discipline, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            switch (discipline)
            {
            case Discipline.Structural:
                if (typeof(BH.oM.Structure.Elements.Bar).BuiltInCategories().Contains((BuiltInCategory)familyInstance.Category.Id.IntegerValue))
                {
                    return(familyInstance.BarsFromRevit(settings, refObjects).Cast <IBHoMObject>());
                }
                else
                {
                    return(null);
                }

            case Discipline.Physical:
            case Discipline.Architecture:
                if (typeof(BH.oM.Physical.Elements.Window).BuiltInCategories().Contains((BuiltInCategory)familyInstance.Category.Id.IntegerValue))
                {
                    return new List <IBHoMObject> {
                               familyInstance.WindowFromRevit(settings, refObjects)
                    }
                }
                ;
                if (typeof(BH.oM.Physical.Elements.Door).BuiltInCategories().Contains((BuiltInCategory)familyInstance.Category.Id.IntegerValue))
                {
                    return new List <IBHoMObject> {
                               familyInstance.DoorFromRevit(settings, refObjects)
                    }
                }
                ;
                if (typeof(BH.oM.Physical.Elements.Column).BuiltInCategories().Contains((BuiltInCategory)familyInstance.Category.Id.IntegerValue) || familyInstance.StructuralType == StructuralType.Column)
                {
                    return new List <IBHoMObject> {
                               familyInstance.ColumnFromRevit(settings, refObjects)
                    }
                }
                ;
                if (typeof(BH.oM.Physical.Elements.Bracing).BuiltInCategories().Contains((BuiltInCategory)familyInstance.Category.Id.IntegerValue) || familyInstance.StructuralType == StructuralType.Brace)
                {
                    return new List <IBHoMObject> {
                               familyInstance.BracingFromRevit(settings, refObjects)
                    }
                }
                ;
                if (typeof(BH.oM.Physical.Elements.Beam).BuiltInCategories().Contains((BuiltInCategory)familyInstance.Category.Id.IntegerValue))
                {
                    return new List <IBHoMObject> {
                               familyInstance.BeamFromRevit(settings, refObjects)
                    }
                }
                ;
                else
                {
                    return(null);
                }

            case Discipline.Environmental:
                return(new List <IBHoMObject> {
                    familyInstance.EnvironmentPanelFromRevit(settings, refObjects)
                });

            default:
                return(null);
            }
        }
        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";
        }
示例#33
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);
        }
        private void CalculateDoorWindowInformation(ExporterIFC exporterIFC, FamilyInstance famInst, 
            ElementId overrideLevelId, Transform trf)
        {
            IFCFile file = exporterIFC.GetFile();

            if (ExportingDoor)
            {
                string doorOperationType = null;

                Element doorType = famInst.Document.GetElement(famInst.GetTypeId());
                if (doorType != null)
                    ParameterUtil.GetStringValueFromElement(doorType, BuiltInParameter.DOOR_OPERATION_TYPE, out doorOperationType);

                DoorOperationTypeString = "NOTDEFINED";
                if (!string.IsNullOrWhiteSpace(doorOperationType))
                {
                    Type enumType = null;
                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                        enumType = typeof(Toolkit.IFC4.IFCDoorStyleOperation);
                    else
                        enumType = typeof(Toolkit.IFCDoorStyleOperation);

                    foreach (Enum ifcDoorStyleOperation in Enum.GetValues(enumType))
                    {
                        string enumAsString = ifcDoorStyleOperation.ToString();
                        if (NamingUtil.IsEqualIgnoringCaseSpacesAndUnderscores(enumAsString, doorOperationType))
                        {
                            DoorOperationTypeString = enumAsString;
                            break;
                        }
                    }
                }

                if (DoorOperationTypeString == "NOTDEFINED")
                {
                    // We are going to try to guess the hinge placement.
                    DoorOperationTypeString = CalculateDoorOperationStyle(famInst);
                }
                
                if (FlippedX ^ FlippedY)
                    DoorOperationTypeString = ReverseDoorStyleOperation(DoorOperationTypeString);

                if (String.Compare(DoorOperationTypeString, "USERDEFINED", true) == 0)
                {
                    string userDefinedOperationType;
                    ParameterUtil.GetStringValueFromElementOrSymbol(doorType, "UserDefinedOperationType", out userDefinedOperationType);
                    if (!string.IsNullOrEmpty(userDefinedOperationType))
                        UserDefinedOperationType = userDefinedOperationType;
                    else
                        DoorOperationTypeString = "NOTDEFINED";         //re-set to NotDefined if operation type is set to UserDefined but the userDefinedOperationType parameter is empty!
                }
            }

            if (HasRealWallHost)
            {
                // do hingeside calculation
                Wall wall = HostObject as Wall;
                PosHingeSide = true;

                BoundingBoxXYZ famBBox = null;
                Options options = GeometryUtil.GetIFCExportGeometryOptions();
                GeometryElement geomElement = famInst.GetOriginalGeometry(options);
                if (geomElement != null)
                    famBBox = geomElement.GetBoundingBox();

                if (famBBox != null)
                {
                    XYZ bboxCtr = trf.OfPoint((famBBox.Min + famBBox.Max) / 2.0);

                    Curve curve = WallExporter.GetWallAxis(wall);

                    XYZ wallZDir = WallExporter.GetWallHeightDirection(wall);

                    // famInst.HostParameter will fail if FamilyPlacementType is WorkPlaneBased, regardless of whether or not the reported host is a Wall.
                    // In this case, just use the start parameter of the curve.
                    bool hasHostParameter = famInst.Symbol.Family.FamilyPlacementType != FamilyPlacementType.WorkPlaneBased;
                    double param = hasHostParameter ? famInst.HostParameter : curve.GetEndParameter(0);

                    Transform wallTrf = curve.ComputeDerivatives(param, false);
                    XYZ wallOrig = wallTrf.Origin;
                    XYZ wallXDir = wallTrf.BasisX;
                    XYZ wallYDir = wallZDir.CrossProduct(wallXDir);

                    double eps = MathUtil.Eps();

                    bboxCtr -= wallOrig;
                    PosHingeSide = (bboxCtr.DotProduct(wallYDir) > -eps);

                    XYZ famInstYDir = trf.BasisY;
                    FlippedSymbol = (PosHingeSide != (wallYDir.DotProduct(famInstYDir) > -eps));
                }
            }
        }
示例#35
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            if (!args[0].IsList)
            {
                throw new Exception("A list of UVs is required to place the Adaptive Component.");
            }

            FSharpList <Value> uvs = ((Value.List)args[0]).Item;

            var faceRef = ((Value.Container)args[1]).Item as Reference;
            var f       = faceRef == null
                         ? (Face)((Value.Container)args[1]).Item
                         : (Face)dynRevitSettings.Doc.Document.GetElement(faceRef.ElementId).GetGeometryObjectFromReference(faceRef);

            var fs = (FamilySymbol)((Value.Container)args[2]).Item;

            FamilyInstance ac = null;

            //if the adapative component already exists, then move the points
            if (Elements.Any())
            {
                //mutate
                //...we attempt to fetch it from the document...
                if (dynUtils.TryGetElement(this.Elements[0], out ac))
                {
                    ac.Symbol = fs;
                }
                else
                {
                    //create
                    ac          = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(dynRevitSettings.Doc.Document, fs);
                    Elements[0] = ac.Id;
                }
            }
            else
            {
                //create
                ac = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(dynRevitSettings.Doc.Document, fs);
                Elements.Add(ac.Id);
            }

            if (ac == null)
            {
                throw new Exception("An adaptive component could not be found or created.");
            }

            IList <ElementId> placePointIds = new List <ElementId>();

            placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(ac);

            if (placePointIds.Count() != uvs.Count())
            {
                throw new Exception("The input list of UVs does not have the same number of values required by the adaptive component.");
            }

            // Set the position of each placement point
            int i = 0;

            foreach (ElementId id in placePointIds)
            {
                var uv    = (UV)((Value.Container)uvs.ElementAt(i)).Item;
                var point = dynRevitSettings.Doc.Document.GetElement(id) as ReferencePoint;
                var peref = dynRevitSettings.Revit.Application.Create.NewPointOnFace(f.Reference, uv);
                point.SetPointElementReference(peref);
                i++;
            }

            return(Value.NewContainer(ac));
        }
示例#36
0
        protected void AddObjectsToTree(FamilyInstance elem, TreeNodeCollection curNodes)
        {
            Autodesk.Revit.DB.Options geomOp = m_app.Create.NewGeometryOptions();
             geomOp.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!
             TreeNode tmpNode;

             // add geometry with the View set to null.
             TreeNode rootNode1 = new TreeNode("View = null");
             curNodes.Add(rootNode1);

             tmpNode = new TreeNode("Detail Level = Undefined");
             geomOp.DetailLevel = ViewDetailLevel.Undefined;
             tmpNode.Tag = elem.GetOriginalGeometry(geomOp);
             rootNode1.Nodes.Add(tmpNode);

             tmpNode = new TreeNode("Detail Level = Coarse");
             geomOp.DetailLevel = ViewDetailLevel.Coarse;
             tmpNode.Tag = elem.GetOriginalGeometry(geomOp);
             rootNode1.Nodes.Add(tmpNode);

             tmpNode = new TreeNode("Detail Level = Medium");
             geomOp.DetailLevel = ViewDetailLevel.Medium;
             tmpNode.Tag = elem.GetOriginalGeometry(geomOp);
             rootNode1.Nodes.Add(tmpNode);

             tmpNode = new TreeNode("Detail Level = Fine");
             geomOp.DetailLevel = ViewDetailLevel.Fine;
             tmpNode.Tag = elem.GetOriginalGeometry(geomOp);
             rootNode1.Nodes.Add(tmpNode);

             // SOFiSTiK FS
             // add model geometry including geometry objects not set as Visible.
             {
            Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions();
            opts.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!;
            opts.IncludeNonVisibleObjects = true;

            TreeNode rootNode = new TreeNode("View = null - Including geometry objects not set as Visible");
            curNodes.Add(rootNode);

            tmpNode = new TreeNode("Detail Level = Undefined");
            opts.DetailLevel = ViewDetailLevel.Undefined;
            tmpNode.Tag = elem.GetOriginalGeometry(opts);
            rootNode.Nodes.Add(tmpNode);

            tmpNode = new TreeNode("Detail Level = Coarse");
            opts.DetailLevel = ViewDetailLevel.Coarse;
            tmpNode.Tag = elem.GetOriginalGeometry(opts);
            rootNode.Nodes.Add(tmpNode);

            tmpNode = new TreeNode("Detail Level = Medium");
            opts.DetailLevel = ViewDetailLevel.Medium;
            tmpNode.Tag = elem.GetOriginalGeometry(opts);
            rootNode.Nodes.Add(tmpNode);

            tmpNode = new TreeNode("Detail Level = Fine");
            opts.DetailLevel = ViewDetailLevel.Fine;
            tmpNode.Tag = elem.GetOriginalGeometry(opts);
            rootNode.Nodes.Add(tmpNode);
             }

             // now add geometry with the View set to the current view
             if (elem.Document.ActiveView != null)
             {
            Options geomOp2 = m_app.Create.NewGeometryOptions();
            geomOp2.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!;
            geomOp2.View = elem.Document.ActiveView;

            TreeNode rootNode2 = new TreeNode("View = Document.ActiveView");
            rootNode2.Tag = elem.GetOriginalGeometry(geomOp2);
            curNodes.Add(rootNode2);

            // SOFiSTiK FS
            // add model geometry including geometry objects not set as Visible.
            {
               Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions();
               opts.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!;
               opts.IncludeNonVisibleObjects = true;
               opts.View = elem.Document.ActiveView;

               TreeNode rootNode = new TreeNode("View = Document.ActiveView - Including geometry objects not set as Visible");
               curNodes.Add(rootNode);

               rootNode.Tag = elem.GetOriginalGeometry(opts);
            }
             }
        }
示例#37
0
 /// <summary>
 /// Parse the geometry of given Corbel and create a CorbelFrame if the corbel is slopped,
 /// otherwise exception thrown.
 /// </summary>
 /// <param name="corbel">Corbel to parse</param>
 /// <returns>A created CorbelFrame</returns>
 public static CorbelFrame Parse(FamilyInstance corbel)
 {
     // This just delegates a call to GeometryUtil class.
     return(GeometryUtil.ParseCorbelGeometry(corbel));
 }
        /// <summary>
        /// Gets level offset for extruded columns.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="familyInstance">
        /// The family instance.
        /// </param>
        /// <param name="overrideLevelId">
        /// The level id.
        /// </param>
        /// <param name="extraParams">
        /// The extrusion creation data.
        /// </param>
        static XYZ GetLevelOffsetForExtrudedColumns(ExporterIFC exporterIFC,
            FamilyInstance familyInstance, ElementId overrideLevelId, IFCExtrusionCreationData extraParams)
        {
            IFCFamilyInstanceExtrusionExportResults results = ExporterIFCUtils.ExportFamilyInstanceAsExtrusion(exporterIFC, familyInstance, false, overrideLevelId, extraParams);
            IFCAnyHandle extrusionHandle = results.GetExtrusionHandle();
            XYZ levelOffset = (!IFCAnyHandleUtil.IsNullOrHasNoValue(extrusionHandle)) ? results.ExtraOffset : XYZ.Zero;

            extrusionHandle.Delete();

            return levelOffset;
        }
示例#39
0
        private void CalculateDoorWindowInformation(ExporterIFC exporterIFC, FamilyInstance famInst,
                                                    ElementId overrideLevelId, Transform trf)
        {
            IFCFile file = exporterIFC.GetFile();

            if (ExportingDoor)
            {
                string doorOperationType = null;

                Element doorType = famInst.Document.GetElement(famInst.GetTypeId());
                if (doorType != null)
                {
                    // Look at the "Operation" override first, then the built-in parameter.
                    ParameterUtil.GetStringValueFromElementOrSymbol(doorType, "Operation", out doorOperationType);
                    if (string.IsNullOrWhiteSpace(doorOperationType))
                    {
                        ParameterUtil.GetStringValueFromElement(doorType, BuiltInParameter.DOOR_OPERATION_TYPE, out doorOperationType);
                    }
                }

                DoorOperationTypeString = "NOTDEFINED";
                if (!string.IsNullOrWhiteSpace(doorOperationType))
                {
                    Type enumType = null;
                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                    {
                        enumType = typeof(Toolkit.IFC4.IFCDoorStyleOperation);
                    }
                    else
                    {
                        enumType = typeof(Toolkit.IFCDoorStyleOperation);
                    }

                    foreach (Enum ifcDoorStyleOperation in Enum.GetValues(enumType))
                    {
                        string enumAsString = ifcDoorStyleOperation.ToString();
                        if (NamingUtil.IsEqualIgnoringCaseSpacesAndUnderscores(enumAsString, doorOperationType))
                        {
                            DoorOperationTypeString = enumAsString;
                            break;
                        }
                    }
                }

                if (DoorOperationTypeString == "NOTDEFINED")
                {
                    // We are going to try to guess the hinge placement.
                    DoorOperationTypeString = CalculateDoorOperationStyle(famInst, trf);
                }
                else
                {
                    if (FlippedX ^ FlippedY)
                    {
                        DoorOperationTypeString = ReverseDoorStyleOperation(DoorOperationTypeString);
                    }
                }

                if (String.Compare(DoorOperationTypeString, "USERDEFINED", true) == 0)
                {
                    string userDefinedOperationType;
                    ParameterUtil.GetStringValueFromElementOrSymbol(doorType, "UserDefinedOperationType", out userDefinedOperationType);
                    if (!string.IsNullOrEmpty(userDefinedOperationType))
                    {
                        UserDefinedOperationType = userDefinedOperationType;
                    }
                    else
                    {
                        DoorOperationTypeString = "NOTDEFINED";   //re-set to NotDefined if operation type is set to UserDefined but the userDefinedOperationType parameter is empty!
                    }
                }
            }

            if (HasRealWallHost)
            {
                // do hingeside calculation
                Wall wall = HostObject as Wall;
                PosHingeSide = true;

                BoundingBoxXYZ  famBBox     = null;
                Options         options     = GeometryUtil.GetIFCExportGeometryOptions();
                GeometryElement geomElement = famInst.GetOriginalGeometry(options);
                if (geomElement != null)
                {
                    famBBox = geomElement.GetBoundingBox();
                }

                if (famBBox != null)
                {
                    XYZ bboxCtr = trf.OfPoint((famBBox.Min + famBBox.Max) / 2.0);

                    Curve curve = WallExporter.GetWallAxis(wall);

                    XYZ wallZDir = WallExporter.GetWallHeightDirection(wall);

                    // famInst.HostParameter will fail if FamilyPlacementType is WorkPlaneBased, regardless of whether or not the reported host is a Wall.
                    // In this case, just use the start parameter of the curve.
                    bool   hasHostParameter = famInst.Symbol.Family.FamilyPlacementType != FamilyPlacementType.WorkPlaneBased;
                    double param            = hasHostParameter ? famInst.HostParameter : curve.GetEndParameter(0);

                    Transform wallTrf  = curve.ComputeDerivatives(param, false);
                    XYZ       wallOrig = wallTrf.Origin;
                    XYZ       wallXDir = wallTrf.BasisX;
                    XYZ       wallYDir = wallZDir.CrossProduct(wallXDir);

                    double eps = MathUtil.Eps();

                    bboxCtr     -= wallOrig;
                    PosHingeSide = (bboxCtr.DotProduct(wallYDir) > -eps);

                    XYZ famInstYDir = trf.BasisY;
                    FlippedSymbol = (PosHingeSide != (wallYDir.DotProduct(famInstYDir) > -eps));
                }
            }
        }
        /// <summary>
        /// Exports a family instance to corresponding IFC object.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="familyInstance">
        /// The family instance to be exported.
        /// </param>
        /// <param name="geometryElement">
        /// The geometry element.
        /// </param>
        /// <param name="productWrapper">
        /// The ProductWrapper.
        /// </param>
        public static void ExportFamilyInstanceElement(ExporterIFC exporterIFC,
            FamilyInstance familyInstance, GeometryElement geometryElement, ProductWrapper productWrapper)
        {
            // Don't export family if it is invisible, or has a null geometry.
            if (familyInstance.Invisible || geometryElement == null)
                return;

            // Don't export mullions and panels if they have a host and their host is not a mass
            // as they will be exported with the host (curtain wall/roof).
            if (familyInstance.Category.Id == new ElementId(BuiltInCategory.OST_CurtainWallMullions) ||
                familyInstance.Category.Id == new ElementId(BuiltInCategory.OST_CurtainWallPanels))
            {
                Element host = familyInstance.Host;
                if (host != null && host.Category.Id != new ElementId(BuiltInCategory.OST_Mass))
                    return;
            }

            FamilySymbol familySymbol = familyInstance.Symbol;
            Family family = familySymbol.Family;
            if (family == null)
                return;

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                string ifcEnumType;
                IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, familyInstance, out ifcEnumType);

                if (exportType == IFCExportType.DontExport)
                    return;

                if (ExportFamilyInstanceAsStandardElement(exporterIFC, familyInstance, geometryElement, exportType, ifcEnumType, productWrapper))
                {
                    tr.Commit();
                    return;
                }

                // If we are exporting a column, we may need to split it into parts by level.  Create a list of ranges.
                IList<ElementId> levels = new List<ElementId>();
                IList<IFCRange> ranges = new List<IFCRange>();

                // We will not split walls and columns if the assemblyId is set, as we would like to keep the original wall
                // associated with the assembly, on the level of the assembly.
                bool splitColumn = (exportType == IFCExportType.ExportColumnType) && (ExporterCacheManager.ExportOptionsCache.WallAndColumnSplitting) &&
                    (familyInstance.AssemblyInstanceId == ElementId.InvalidElementId);
                if (splitColumn)
                {
                    LevelUtil.CreateSplitLevelRangesForElement(exporterIFC, exportType, familyInstance, out levels, out ranges);
                }

                int numPartsToExport = ranges.Count;
                if (numPartsToExport == 0)
                {
                    ExportFamilyInstanceAsMappedItem(exporterIFC, familyInstance, exportType, ifcEnumType, productWrapper,
                       ElementId.InvalidElementId, null, null);
                }
                else
                {
                    for (int ii = 0; ii < numPartsToExport; ii++)
                    {
                        ExportFamilyInstanceAsMappedItem(exporterIFC, familyInstance, exportType, ifcEnumType, productWrapper,
                          levels[ii], ranges[ii], null);
                    }

                    if (ExporterCacheManager.DummyHostCache.HasRegistered(familyInstance.Id))
                    {
                        List<KeyValuePair<ElementId, IFCRange>> levelRangeList = ExporterCacheManager.DummyHostCache.Find(familyInstance.Id);
                        foreach (KeyValuePair<ElementId, IFCRange> levelRange in levelRangeList)
                        {
                            ExportFamilyInstanceAsMappedItem(exporterIFC, familyInstance, exportType, ifcEnumType, productWrapper, levelRange.Key, levelRange.Value, null);
                        }
                    }
                }

                tr.Commit();
            }
        }
示例#41
0
        /// <summary>
        /// update door instances information: Left/Right information, related rooms information.
        /// </summary>
        /// <param name="creFilter">One element filter utility object.</param>
        /// <param name="doc">Revit project.</param>
        /// <param name="onlyUpdateSelect">
        /// true means only update selected doors' information otherwise false.
        /// </param>
        /// <param name="showUpdateResultMessage">
        /// this parameter is used for invoking this method in Application's events (document save and document saveAs).
        /// update door infos in Application level events should not show unnecessary messageBox.
        /// </param>
        public static Autodesk.Revit.UI.Result UpdateDoorsInfo(Document doc, bool onlyUpdateSelect,
                                                               bool showUpdateResultMessage, ref string message)
        {
            if ((!AssignedAllRooms(doc)) && showUpdateResultMessage)
            {
                TaskDialogResult dialogResult = TaskDialog.Show("Door Swing", "One or more eligible areas of this level " +
                                                                "have no assigned room(s). Doors bounding these areas " +
                                                                "will be designated as external doors. Proceed anyway?",
                                                                TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No);

                if (TaskDialogResult.No == dialogResult)
                {
                    message = "Update cancelled. Please assign rooms for all eligible areas first.";
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }
            }

            // begin update door parameters.
            IEnumerator iter;
            int         doorCount             = 0;
            bool        checkSharedParameters = false;

            if (onlyUpdateSelect) // update doors in select elements
            {
                UIDocument newUIdoc = new UIDocument(doc);
                ElementSet es       = new ElementSet();
                foreach (ElementId elementId in newUIdoc.Selection.GetElementIds())
                {
                    es.Insert(newUIdoc.Document.GetElement(elementId));
                }
                iter = es.GetEnumerator();
            }
            else // update all doors in current Revit project.
            {
                ElementClassFilter    familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
                ElementCategoryFilter doorsCategoryfilter  = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
                LogicalAndFilter      doorInstancesFilter  = new LogicalAndFilter(familyInstanceFilter, doorsCategoryfilter);
                iter = new FilteredElementCollector(doc).WherePasses(doorInstancesFilter).GetElementIterator();
            }

            iter.Reset();
            while (iter.MoveNext())
            {
                // find door instance
                FamilyInstance door = iter.Current as FamilyInstance;

                if (onlyUpdateSelect)
                {
                    if (null == door)
                    {
                        continue;
                    }

                    if (null == door.Category)
                    {
                        continue;
                    }

                    if (!door.Category.Name.Equals("Doors"))
                    {
                        continue;
                    }
                }

                // check if has needed parameters.
                if (!checkSharedParameters)
                {
                    checkSharedParameters = true;

                    if (!(door.Symbol.ParametersMap.Contains("BasalOpening") &&
                          door.ParametersMap.Contains("InstanceOpening") &&
                          door.ParametersMap.Contains("Internal Door")))
                    {
                        message = "Cannot update door parameters. Please customize door opening expression first.";
                        return(Autodesk.Revit.UI.Result.Failed);
                    }
                }

                // get one door.
                doorCount++;

                // update one door's Opening parameter value.
                if (UpdateOpeningFeatureOfOneDoor(door) == Autodesk.Revit.UI.Result.Failed)
                {
                    message = "Cannot update door parameters. Please customize door opening expression first.";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // update one door's from/to room.
                UpdateFromToRoomofOneDoor(door, false);

                // update one door's internalDoor flag
                UpdateInternalDoorFlagFeatureofOneDoor(door);
            }

            if (showUpdateResultMessage)
            {
                if (onlyUpdateSelect)
                {
                    Autodesk.Revit.UI.TaskDialog.Show("Door Swing", "Updated all selected doors of " + doc.Title +
                                                      " (" + doorCount + " doors).\r\n (Selection may " +
                                                      "include miscellaneous elements.)");
                }
                else
                {
                    Autodesk.Revit.UI.TaskDialog.Show("Door Swing", "Updated all doors of " + doc.Title + " (" +
                                                      doorCount + " doors).");
                }
            }

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
示例#42
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            doc = uidoc.Document;
            Selection sel = uidoc.Selection;

            try
            {
                IList <FamilyWithImage> allBeamsInfo = Utils.GetInformation.GetAllBeamFamilies(doc);

                if (allBeamsInfo.Count < 1)
                {
                    message = Properties.Messages.BeamsForBuilding_NoBeamFamilyLoaded;
                    return(Result.Failed);
                }

                BeamsFromEntireBuildingUI currentUI = new BeamsFromEntireBuildingUI(this, allBeamsInfo);

                currentUI.ShowDialog();

                if (currentUI.DialogResult == false)
                {
                    return(Result.Cancelled);
                }

                FamilyWithImage currentFamilyWithImage = currentUI.CurrentFamilyWithImage;
                Family          currentFamily          = doc.GetElement(new ElementId(currentFamilyWithImage.FamilyID)) as Family;
                //for now we will set the symbol for the first beam of that family
                //later on we will duplicate it and check if it exist or not
                ElementId         fsID       = currentFamily.GetFamilySymbolIds().First();
                FamilySymbol      fs         = doc.GetElement(fsID) as FamilySymbol;
                double            beamHeight = Utils.ConvertM.cmToFeet(currentUI.BeamHeight);
                double            beamWidth  = Utils.ConvertM.cmToFeet(currentUI.BeamWidth);
                bool              createBeamsInIntermediateLevels = currentUI.CreateBeamsInIntermediateLevels;
                bool              ignoreStandardLevels            = currentUI.GroupAndDuplicateLevels;
                bool              isLinked                 = currentUI.IsLinked;
                double            minWallWidth             = Utils.ConvertM.cmToFeet(currentUI.MinWallWidth);
                IList <LevelInfo> allLevelInfo             = currentUI.LevelInfoList;
                string            standardLevelName        = currentUI.StandardLevelName;
                bool              pickStandardLevelsByName = currentUI.PickStandardLevelsByName;
                bool              isCaseSensitive          = currentUI.IsCaseSensitive;
                bool              isJoinBeams              = (bool)currentUI.checkJoinBeams.IsChecked;

                //Will be set if needed
                int            linkedInstanceID     = -1;
                Transform      linkedInstanceTransf = null;
                IList <string> listOfNames          = new List <string>();
                listOfNames.Add(standardLevelName);

                if (isLinked == false)
                {
                    currentDoc = doc;
                }
                else
                {
                    RevitLinkInstance rvtInstance = doc.GetElement(new ElementId(currentUI.SelectedRevitLinkInfo.Id)) as RevitLinkInstance;
                    currentDoc           = rvtInstance.GetLinkDocument();
                    linkedInstanceTransf = rvtInstance.GetTotalTransform();
                    linkedInstanceID     = currentUI.SelectedRevitLinkInfo.Id;
                }

                if (pickStandardLevelsByName)
                {
                    foreach (LevelInfo currentLevelInfo in allLevelInfo)
                    {
                        if (LevelNameContainsString(currentLevelInfo.levelName, listOfNames, isCaseSensitive))
                        {
                            currentLevelInfo.isStandardLevel = true;
                        }
                    }
                }

                string       beamWidthInCm       = Math.Round(Utils.ConvertM.feetToCm(beamWidth)).ToString();
                string       beamHeigthInCm      = Math.Round(Utils.ConvertM.feetToCm(beamHeight)).ToString();
                string       newTypeName         = beamWidthInCm + " x " + beamHeigthInCm + "cm";
                FamilySymbol currentFamilySymbol = null;

                using (Transaction t = new Transaction(doc, Properties.Messages.BeamsForBuilding_Transaction))
                {
                    t.Start();

                    if (!Utils.FindElements.thisTypeExist(newTypeName, currentFamily.Name, BuiltInCategory.OST_StructuralFraming, doc))
                    {
                        currentFamilySymbol = fs.Duplicate(newTypeName) as FamilySymbol;

                        Parameter parameterB = currentFamilySymbol.LookupParameter("b");
                        Parameter parameterH = currentFamilySymbol.LookupParameter("h");

                        //TODO check for code like this that can throw exceptions
                        parameterB.Set(beamWidth);
                        parameterH.Set(beamHeight);
                    }
                    else
                    {
                        currentFamilySymbol = Utils.FindElements.findElement(newTypeName, currentFamily.Name, BuiltInCategory.OST_StructuralFraming, doc) as FamilySymbol;
                    }

                    currentFamilySymbol.Activate();
                    bool isThisTheFirstStandardLevel = true;

                    foreach (LevelInfo currentLevelInfo in allLevelInfo)
                    {
                        if (currentLevelInfo == null)
                        {
                            continue;
                        }

                        if (!currentLevelInfo.willBeNumbered)
                        {
                            continue;
                        }

                        Level currentLevel = currentDoc.GetElement(new ElementId(currentLevelInfo.levelId)) as Level;

                        XYZ minPoint = new XYZ(-9999, -9999, currentLevel.ProjectElevation - 0.1);
                        XYZ maxPoint = new XYZ(9999, 9999, currentLevel.ProjectElevation + 0.1);

                        Outline levelOutLine = new Outline(minPoint, maxPoint);
                        BoundingBoxIntersectsFilter levelBBIntersect = new BoundingBoxIntersectsFilter(levelOutLine, 0.05);
                        BoundingBoxIsInsideFilter   levelBBInside    = new BoundingBoxIsInsideFilter(levelOutLine, 0.05);

                        LogicalOrFilter levelInsideOrIntersectFilter = new LogicalOrFilter(levelBBInside, levelBBIntersect);

                        IList <Element> wallsThatIntersectsCurrentLevel = new FilteredElementCollector(currentDoc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType()
                                                                          .WherePasses(levelInsideOrIntersectFilter).ToList();

                        if (currentLevelInfo.isStandardLevel && ignoreStandardLevels)
                        {
                            if (isThisTheFirstStandardLevel)
                            {
                                isThisTheFirstStandardLevel = false;
                            }
                            else
                            {
                                continue;
                            }
                        }

                        foreach (Element currentWallElment in wallsThatIntersectsCurrentLevel)
                        {
                            Wall currentWall = currentWallElment as Wall;

                            //wall is valid?
                            if (currentWall == null)
                            {
                                continue;
                            }

                            if (currentWall.Width < minWallWidth)
                            {
                                continue;
                            }

                            if (!createBeamsInIntermediateLevels)
                            {
                                if (currentWallElment.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId() != currentLevel.Id &&
                                    currentWallElment.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId() != currentLevel.Id)
                                {
                                    continue;
                                }
                            }

                            LocationCurve wallLocationCurve = currentWall.Location as LocationCurve;

                            //we need to verify if this wall has locationCurve
                            if (wallLocationCurve == null)
                            {
                                continue;
                            }

                            Curve wallCurve = ((currentWall.Location) as LocationCurve).Curve;

                            if (isLinked)
                            {
                                wallCurve = wallCurve.CreateTransformed(linkedInstanceTransf);
                            }

                            double wallBaseOffset = currentWall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble();

                            Level wallBaseLevel = currentDoc.GetElement(currentWall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId()) as Level;

                            double wallBaseTotalHeight = wallBaseLevel.ProjectElevation + wallBaseOffset;

                            double wallTotalHeight = currentWall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).AsDouble();

                            if (wallTotalHeight < beamHeight)
                            {
                                continue;
                            }

                            double levelHeight           = currentLevel.ProjectElevation;
                            Level  currentLevelInProject = null;

                            if (isLinked)
                            {
                                levelHeight += linkedInstanceTransf.Origin.Z;

                                IList <Level> allLevelsInProject = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level)).Cast <Level>().ToList();

                                foreach (Level levelCanditate in allLevelsInProject)
                                {
                                    if (Math.Abs(levelHeight - levelCanditate.ProjectElevation) <= 0.1)
                                    {
                                        currentLevelInProject = levelCanditate;
                                        break;
                                    }
                                }

                                if (currentLevelInProject == null)
                                {
                                    currentLevelInProject = Level.Create(doc, levelHeight);
                                }
                            }
                            else
                            {
                                currentLevelInProject = currentLevel;
                            }

                            FamilyInstance currentBeamInstance = doc.Create.NewFamilyInstance(wallCurve, currentFamilySymbol, currentLevelInProject, Autodesk.Revit.DB.Structure.StructuralType.Beam);

                            AdjustBeamParameters(currentBeamInstance, currentLevelInProject);

                            doc.Regenerate();
                            Utils.CheckFamilyInstanceForIntersection.CheckForDuplicatesAndIntersectingBeams(currentBeamInstance, doc);
                        }
                    }

                    if (isJoinBeams)
                    {
                        IList <FamilyInstance> allBeamsInstances = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming)
                                                                   .OfClass(typeof(FamilyInstance)).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList();

                        foreach (FamilyInstance currentBeam in allBeamsInstances)
                        {
                            Utils.CheckFamilyInstanceForIntersection.JoinBeamToWalls(currentBeam, doc);
                        }
                    }


                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
            }
            return(Result.Succeeded);
        }
示例#43
0
 private void SetParameters(FamilyInstance fi, IEnumerable<RevitParameter> parameters, Document doc)
 {
     foreach (RevitParameter rp in parameters)
     {
         try
         {
             Parameter p = fi.LookupParameter(rp.ParameterName);
             switch (rp.StorageType)
             {
                 case "Double":
                     if (p.Definition.ParameterType == ParameterType.Area)
                         p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), areaDUT));
                     else if (p.Definition.ParameterType == ParameterType.Volume)
                         p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), volumeDUT));
                     else if (p.Definition.ParameterType == ParameterType.Length)
                         p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), lengthDUT));
                     else
                         p.Set(Convert.ToDouble(rp.Value));
                     break;
                 case "Integer":
                     p.Set(Convert.ToInt32(rp.Value));
                     break;
                 case "String":
                     p.Set(rp.Value);
                     break;
                 case "ElementId":
                     try
                     {
                         int idInt = Convert.ToInt32(rp.Value);
                         ElementId elemId = new ElementId(idInt);
                         Element elem = doc.GetElement(elemId);
                         if (elem != null)
                         {
                             //TaskDialog.Show("Test:", "Param: " + p.Definition.Name + "\nID: " + elemId.IntegerValue.ToString());
                             p.Set(elemId);
                         }
                     }
                     catch
                     {
                         try
                         {
                             p.Set(p.Definition.ParameterType == ParameterType.Material
                                 ? GetMaterial(rp.Value, doc)
                                 : new ElementId(Convert.ToInt32(rp.Value)));
                         }
                         catch (Exception ex)
                         {
                             //TaskDialog.Show(p.Definition.Name, ex.Message);
                         }
                     }
                     break;
                 default:
                     p.Set(rp.Value);
                     break;
             }
         }
         catch
         {
             try
             {
                 Parameter p = fi.Symbol.LookupParameter(rp.ParameterName);
                 switch (rp.StorageType)
                 {
                     case "Double":
                         if (p.Definition.ParameterType == ParameterType.Area)
                             p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), areaDUT));
                         else if (p.Definition.ParameterType == ParameterType.Volume)
                             p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), volumeDUT));
                         else if (p.Definition.ParameterType == ParameterType.Length)
                             p.Set(UnitUtils.ConvertToInternalUnits(Convert.ToDouble(rp.Value), lengthDUT));
                         else
                             p.Set(Convert.ToDouble(rp.Value));
                         break;
                     case "Integer":
                         p.Set(Convert.ToInt32(rp.Value));
                         break;
                     case "String":
                         p.Set(rp.Value);
                         break;
                     case "ElementId":
                        try
                         {
                             int idInt = Convert.ToInt32(rp.Value);
                             ElementId elemId = new ElementId(idInt);
                             Element elem = doc.GetElement(elemId);
                             if (elem != null)
                             {
                                 //TaskDialog.Show("Test:", "Param: " + p.Definition.Name + "\nID: " + elemId.IntegerValue.ToString());
                                 p.Set(elemId);
                             }
                         }
                         catch
                         {
                             try
                             {
                                 p.Set(p.Definition.ParameterType == ParameterType.Material
                                     ? GetMaterial(rp.Value, doc)
                                     : new ElementId(Convert.ToInt32(rp.Value)));
                             }
                             catch (Exception ex)
                             {
                                 //TaskDialog.Show(p.Definition.Name, ex.Message);
                             }
                         }
                         break;
                     default:
                         p.Set(rp.Value);
                         break;
                 }
             }
             catch (Exception ex)
             {
                 TaskDialog.Show("Error", ex.Message);
             }
         }
     }
 }
示例#44
0
        /// <summary>
        /// Doors related rooms: update doors' geometry according to its To/From room information.
        /// </summary>
        /// <param name="creFilter">One element filter utility object.</param>
        /// <param name="doc">Revit project.</param>
        /// <param name="onlyUpdateSelect">
        /// true means only update selected doors' information else false.
        /// </param>
        public static void UpdateDoorsGeometry(Document doc, bool onlyUpdateSelect)
        {
            IEnumerator iter;
            int         doorCount = 0;

            if (onlyUpdateSelect) // update doors in select elements
            {
                UIDocument newUIdoc = new UIDocument(doc);
                ElementSet es       = new ElementSet();
                foreach (ElementId elementId in newUIdoc.Selection.GetElementIds())
                {
                    es.Insert(newUIdoc.Document.GetElement(elementId));
                }
                iter = es.GetEnumerator();
            }
            else // update all doors in current Revit document
            {
                ElementClassFilter    familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
                ElementCategoryFilter doorsCategoryfilter  = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
                LogicalAndFilter      doorInstancesFilter  = new LogicalAndFilter(familyInstanceFilter, doorsCategoryfilter);
                iter = new FilteredElementCollector(doc).WherePasses(doorInstancesFilter).GetElementIterator();
            }

            iter.Reset();
            while (iter.MoveNext())
            {
                // find door instance
                FamilyInstance door = iter.Current as FamilyInstance;

                if (onlyUpdateSelect)
                {
                    if (null == door)
                    {
                        continue;
                    }

                    if (null == door.Category)
                    {
                        continue;
                    }

                    if (!door.Category.Name.Equals("Doors"))
                    {
                        continue;
                    }
                }

                // find one door.
                doorCount++;

                // update one door.
                UpdateFromToRoomofOneDoor(door, true);
                doc.Regenerate();
            }

            if (onlyUpdateSelect)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Door Swing", "Updated all selected doors (" + doorCount +
                                                  " doors).\r\n (Selection may include miscellaneous elements.)");
            }
            else
            {
                Autodesk.Revit.UI.TaskDialog.Show("Door Swing", "Updated all doors of this project (" +
                                                  doorCount + " doors).");
            }
        }
示例#45
0
        public static FamilySymbol RequestFamilySymbolByInstanceSelection(string message, ref FamilyInstance fi)
        {
            var doc = DocumentManager.Instance.CurrentUIDocument;

            try
            {
                //FamilySymbol fs = null;

                Selection choices = doc.Selection;

                choices.Elements.Clear();

                //MessageBox.Show(message);
                DynamoLogger.Instance.Log(message);

                Reference fsRef = doc.Selection.PickObject(ObjectType.Element);

                if (fsRef != null)
                {
                    fi = doc.Document.GetElement(fsRef) as FamilyInstance;

                    if (fi != null)
                    {
                        return fi.Symbol;
                    }
                    return null;
                }
                return null;
            }
            catch (Exception ex)
            {
                DynamoLogger.Instance.Log(ex);
                return null;
            }
        }
示例#46
0
        /// <summary>
        /// Update doors' Left/Right information.
        /// </summary>
        /// <param name="door">one door instance.</param>
        private static Autodesk.Revit.UI.Result UpdateOpeningFeatureOfOneDoor(FamilyInstance door)
        {
            // flag whether the opening value should switch from its corresponding family's basic opening value.
            bool switchesOpeningValueFlag = false;

            // When the door is being mirrored once, the door switches its direction;
            // When the door is being flipped once, the door switches its direction.
            // When the door is being mirrored and flipped, the door's direction remains the same.
            if (door.FacingFlipped ^ door.HandFlipped)
            {
                switchesOpeningValueFlag = true;
            }

            // get door's Opening parameter which indicates whether the door is Left or Right.
            Parameter openingParam = door.ParametersMap.get_Item("InstanceOpening");

            // country's standard Left/Right opening for this door type.
            String basalOpeningValue = door.Symbol.ParametersMap.get_Item("BasalOpening").AsString();

            string rightOpeningValue; // actual opening value of the door.

            if (switchesOpeningValueFlag)
            {
                if (DoorSwingResource.LeftDoor.Equals(basalOpeningValue))
                {
                    rightOpeningValue = DoorSwingResource.RightDoor;
                }
                else if (DoorSwingResource.RightDoor.Equals(basalOpeningValue))
                {
                    rightOpeningValue = DoorSwingResource.LeftDoor;
                }
                else if (DoorSwingResource.TwoLeafActiveLeafLeft.Equals(basalOpeningValue))
                {
                    rightOpeningValue = DoorSwingResource.TwoLeafActiveLeafRight;
                }
                else if (DoorSwingResource.TwoLeafActiveLeafRight.Equals(basalOpeningValue))
                {
                    rightOpeningValue = DoorSwingResource.TwoLeafActiveLeafLeft;
                }
                else if (DoorSwingResource.TwoLeaf.Equals(basalOpeningValue))
                {
                    rightOpeningValue = DoorSwingResource.TwoLeaf;
                }
                else if (DoorSwingResource.Undefined.Equals(basalOpeningValue))
                {
                    rightOpeningValue = DoorSwingResource.Undefined;
                }
                else
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }
            else
            {
                if (OpeningTypes.Contains(basalOpeningValue))
                {
                    rightOpeningValue = basalOpeningValue;
                }
                else
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }

            // update door's Opening param.
            openingParam.Set(rightOpeningValue);
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
        private void Initialize(bool isDoor, bool isWindow, FamilyInstance famInst, HostObject hostObject)
        {
            HostObject = hostObject;
            InsertInstance = famInst;

            ExportingDoor = isDoor;
            if (isDoor) 
		        PreDefinedType = "DOOR";

            ExportingWindow = isWindow;
            if (isWindow) 
		        PreDefinedType = "WINDOW";

            FlippedSymbol = false;

            DoorOperationTypeString = "NOTDEFINED";
            WindowPartitioningTypeString = "NOTDEFINED";

            FlippedX = (famInst == null) ? false : famInst.HandFlipped;
            FlippedY = (famInst == null) ? false : famInst.FacingFlipped;

            Wall wall = (hostObject == null) ? null : hostObject as Wall;
            Curve centerCurve = WallExporter.GetWallAxis(wall);
            HasRealWallHost = ((wall != null) && (centerCurve != null) && ((centerCurve is Line) || (centerCurve is Arc)));
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp         = commandData.Application;
            UIDocument    uidoc         = uiapp.ActiveUIDocument;
            Document      doc           = uidoc.Document;
            Result        commandResult = Result.Succeeded;
            Categories    cats          = doc.Settings.Categories;

            ElementId catDoorsId = cats.get_Item(
                BuiltInCategory.OST_Doors).Id;

            ElementId catWindowsId = cats.get_Item(
                BuiltInCategory.OST_Windows).Id;

            try
            {
                List <ElementId> selectedIds = uidoc.Selection
                                               .GetElementIds().ToList();

                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("Cmd: GetOpeningProfiles");

                    List <ElementId> newIds = new List <ElementId>();

                    foreach (ElementId selectedId in selectedIds)
                    {
                        Wall wall = doc.GetElement(selectedId) as Wall;

                        if (wall != null)
                        {
                            List <PlanarFace> faceList = new List <PlanarFace>();

                            List <ElementId> insertIds = wall.FindInserts(
                                true, false, false, false).ToList();

                            foreach (ElementId insertId in insertIds)
                            {
                                Element elem = doc.GetElement(insertId);

                                if (elem is FamilyInstance)
                                {
                                    FamilyInstance inst = elem as FamilyInstance;

                                    CategoryType catType = inst.Category
                                                           .CategoryType;

                                    Category cat = inst.Category;

                                    if (catType == CategoryType.Model &&
                                        (cat.Id == catDoorsId ||
                                         cat.Id == catWindowsId))
                                    {
                                        faceList.AddRange(
                                            GetWallOpeningPlanarFaces(
                                                wall, insertId));
                                    }
                                }
                                else if (elem is Opening)
                                {
                                    faceList.AddRange(
                                        GetWallOpeningPlanarFaces(
                                            wall, insertId));
                                }
                            }

                            foreach (PlanarFace face in faceList)
                            {
                                //Plane facePlane = new Plane(
                                //  face.ComputeNormal( UV.Zero ),
                                //  face.Origin ); // 2016

                                Plane facePlane = Plane.CreateByNormalAndOrigin(
                                    face.ComputeNormal(UV.Zero),
                                    face.Origin); // 2017

                                SketchPlane sketchPlane
                                    = SketchPlane.Create(doc, facePlane);

                                foreach (CurveLoop curveLoop in
                                         face.GetEdgesAsCurveLoops())
                                {
                                    foreach (Curve curve in curveLoop)
                                    {
                                        ModelCurve modelCurve = doc.Create
                                                                .NewModelCurve(curve, sketchPlane);

                                        newIds.Add(modelCurve.Id);
                                    }
                                }
                            }
                        }
                    }

                    if (newIds.Count > 0)
                    {
                        View activeView = uidoc.ActiveGraphicalView;
                        activeView.IsolateElementsTemporary(newIds);
                    }
                    trans.Commit();
                }
            }

            #region Exception Handling

            catch (Autodesk.Revit.Exceptions
                   .ExternalApplicationException e)
            {
                message = e.Message;
                Debug.WriteLine(
                    "Exception Encountered (Application)\n"
                    + e.Message + "\nStack Trace: "
                    + e.StackTrace);

                commandResult = Result.Failed;
            }
            catch (Autodesk.Revit.Exceptions
                   .OperationCanceledException e)
            {
                Debug.WriteLine("Operation cancelled. "
                                + e.Message);

                message = "Operation cancelled.";

                commandResult = Result.Succeeded;
            }
            catch (Exception e)
            {
                message = e.Message;
                Debug.WriteLine(
                    "Exception Encountered (General)\n"
                    + e.Message + "\nStack Trace: "
                    + e.StackTrace);

                commandResult = Result.Failed;
            }

            #endregion

            return(commandResult);
        }
        public static DoorWindowInfo CreateWindow(ExporterIFC exporterIFC, FamilyInstance famInst,  HostObject hostObj,
            ElementId overrideLevelId, Transform trf)
        {
            DoorWindowInfo doorWindowInfo = new DoorWindowInfo();
            doorWindowInfo.Initialize(false, true, famInst, hostObj);
            doorWindowInfo.CalculateDoorWindowInformation(exporterIFC, famInst, overrideLevelId, trf);

            return doorWindowInfo;
        }
示例#50
0
        protected override void PopulateDbRow(Element element, DataRow row)
        {
            FamilyInstance familyInstance = element as FamilyInstance;

            base.SetDbRowIDAndHostId(familyInstance, familyInstance.Host, row);
        }
        /// <summary>
        /// This method takes an instance of a nested family and links a parameter on it to
        /// a parameter on the given host family instance.  This allows a change at the host
        /// level to automatically be sent down and applied to the nested family instance.
        /// </summary>
        /// <param name="hostFamilyDocument">The host family document to have one of its parameters be linked to a parameter on the given nested family instance</param>
        /// <param name="nestedFamilyInstance">The nested family whose parameter should be linked to a parameter on the host family</param>
        /// <param name="nestedFamilyParameterName">The name of the parameter on the nested family to link to the host family parameter</param>
        /// <param name="hostFamilyParameterNameToLink">The name of the parameter on the host family to link to a parameter on the given nested family instance</param>
        public static void LinkNestedFamilyParameterToHostFamilyParameter(
            Document hostFamilyDocument,
            FamilyInstance nestedFamilyInstance,
            string nestedFamilyParameterName,
            string hostFamilyParameterNameToLink)
        {
            // Following good SOA practices, verify the incoming
              // parameters before attempting to proceed.

              ValidateFamilyDocument( hostFamilyDocument ); // Throws an exception if is not valid family doc

              if( nestedFamilyInstance == null )
              {
            throw new ArgumentNullException(
              "nestedFamilyInstance" );
              }

              if( string.IsNullOrEmpty( nestedFamilyParameterName ) )
              {
            throw new ArgumentNullException(
              "nestedFamilyParameterName" );
              }

              if( string.IsNullOrEmpty( hostFamilyParameterNameToLink ) )
              {
            throw new ArgumentNullException(
              "hostFamilyParameterNameToLink" );
              }

              Parameter oNestedFamilyParameter
            = GetFamilyParameter( nestedFamilyInstance,
              nestedFamilyParameterName );

              if( oNestedFamilyParameter == null )
              {
            throw new Exception( "Parameter '"
              + nestedFamilyParameterName
              + "' was not found on the nested family '"
              + nestedFamilyInstance.Symbol.Name + "'" );
              }

              FamilyParameter oHostFamilyParameter
            = hostFamilyDocument.FamilyManager.get_Parameter(
              hostFamilyParameterNameToLink );

              if( oHostFamilyParameter == null )
              {
            throw new Exception( "Parameter '"
              + hostFamilyParameterNameToLink
              + "' was not found on the host family." );
              }

              hostFamilyDocument.FamilyManager
            .AssociateElementParameterToFamilyParameter(
              oNestedFamilyParameter, oHostFamilyParameter );
        }
        //Mass >> Room/Area/Floor
        private bool TransferToRoom(Dictionary <Element, FamilyInstance> mapDictionary)
        {
            try
            {
                foreach (Element mainElement in mapDictionary.Keys)
                {
                    FamilyInstance massInstance = mapDictionary[mainElement];

                    foreach (string paramName in defDictionary.Keys)
                    {
                        ExternalDefinition extDefinition = defDictionary[paramName] as ExternalDefinition;

#if RELEASE2013 || RELEASE2014
                        Parameter mainParameter = mainElement.get_Parameter(paramName);
                        Parameter massParameter = massInstance.get_Parameter("Mass_" + paramName);
#elif RELEASE2015 || RELEASE2016
                        Parameter mainParameter = mainElement.LookupParameter(paramName);
                        Parameter massParameter = massInstance.LookupParameter("Mass_" + paramName);
#endif

                        if (null != mainParameter && null != massParameter && !mainParameter.IsReadOnly)
                        {
                            using (Transaction trans = new Transaction(m_doc))
                            {
                                trans.Start("Set Parameter");
                                switch (mainParameter.StorageType)
                                {
                                case StorageType.Double:
                                    mainParameter.Set(massParameter.AsDouble());
                                    break;

                                case StorageType.Integer:
                                    mainParameter.Set(massParameter.AsInteger());
                                    break;

                                case StorageType.String:
                                    mainParameter.Set(massParameter.AsString());
                                    break;
                                }
                                trans.Commit();
                            }
                        }
                        else if (null != mainParameter && null == massParameter) //create Mass Parameter
                        {
                            Family   family    = massInstance.Symbol.Family;
                            Document familyDoc = m_doc.EditFamily(family);

                            if (null != familyDoc && familyDoc.IsFamilyDocument)
                            {
                                using (Transaction fTrans = new Transaction(familyDoc))
                                {
                                    fTrans.Start("Add Parameter");
                                    FamilyParameter fParam = familyDoc.FamilyManager.AddParameter(extDefinition, BuiltInParameterGroup.INVALID, true);
                                    switch (fParam.StorageType)
                                    {
                                    case StorageType.Double:
                                        familyDoc.FamilyManager.Set(fParam, mainParameter.AsDouble());
                                        break;

                                    case StorageType.Integer:
                                        familyDoc.FamilyManager.Set(fParam, mainParameter.AsInteger());
                                        break;

                                    case StorageType.String:
                                        familyDoc.FamilyManager.Set(fParam, mainParameter.AsString());
                                        break;
                                    }

                                    familyDoc.LoadFamily(m_doc, new FamilyOption());
                                    fTrans.Commit();
                                }
                                familyDoc.Close(true);
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to transfer data from Mass to " + massCategory.ToString() + "\n" + ex.Message, "Form_DataTrnasfer:TransferToRoom", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }
        }
示例#53
0
 /// <summary>
 /// Obtains a special snapshot of the geometry of an in-place wall element suitable for export.
 /// </summary>
 /// <param name="famInstWallElem">
 /// The in-place wall instance.
 /// </param>
 /// <returns>
 /// The in-place wall geometry.
 /// </returns>
 static GeometryElement GetGeometryFromInplaceWall(FamilyInstance famInstWallElem)
 {
     return ExporterIFCUtils.GetGeometryFromInplaceWall(famInstWallElem);
 }
示例#54
0
        AddObjectsToTree(FamilyInstance elem, TreeNodeCollection curNodes)
        {
            Autodesk.Revit.DB.Options geomOp = m_app.Create.NewGeometryOptions();
            geomOp.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!
            TreeNode tmpNode;

            // add geometry with the View set to null.
            TreeNode rootNode1 = new TreeNode("View = null");

            curNodes.Add(rootNode1);

            tmpNode            = new TreeNode("Detail Level = Undefined");
            geomOp.DetailLevel = ViewDetailLevel.Undefined;
            tmpNode.Tag        = elem.GetOriginalGeometry(geomOp);
            rootNode1.Nodes.Add(tmpNode);

            tmpNode            = new TreeNode("Detail Level = Coarse");
            geomOp.DetailLevel = ViewDetailLevel.Coarse;
            tmpNode.Tag        = elem.GetOriginalGeometry(geomOp);
            rootNode1.Nodes.Add(tmpNode);

            tmpNode            = new TreeNode("Detail Level = Medium");
            geomOp.DetailLevel = ViewDetailLevel.Medium;
            tmpNode.Tag        = elem.GetOriginalGeometry(geomOp);
            rootNode1.Nodes.Add(tmpNode);

            tmpNode            = new TreeNode("Detail Level = Fine");
            geomOp.DetailLevel = ViewDetailLevel.Fine;
            tmpNode.Tag        = elem.GetOriginalGeometry(geomOp);
            rootNode1.Nodes.Add(tmpNode);

            // SOFiSTiK FS
            // add model geometry including geometry objects not set as Visible.
            {
                Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions();
                opts.ComputeReferences        = false; // Not allowed for GetOriginalGeometry()!;
                opts.IncludeNonVisibleObjects = true;

                TreeNode rootNode = new TreeNode("View = null - Including geometry objects not set as Visible");
                curNodes.Add(rootNode);

                tmpNode          = new TreeNode("Detail Level = Undefined");
                opts.DetailLevel = ViewDetailLevel.Undefined;
                tmpNode.Tag      = elem.GetOriginalGeometry(opts);
                rootNode.Nodes.Add(tmpNode);

                tmpNode          = new TreeNode("Detail Level = Coarse");
                opts.DetailLevel = ViewDetailLevel.Coarse;
                tmpNode.Tag      = elem.GetOriginalGeometry(opts);
                rootNode.Nodes.Add(tmpNode);

                tmpNode          = new TreeNode("Detail Level = Medium");
                opts.DetailLevel = ViewDetailLevel.Medium;
                tmpNode.Tag      = elem.GetOriginalGeometry(opts);
                rootNode.Nodes.Add(tmpNode);

                tmpNode          = new TreeNode("Detail Level = Fine");
                opts.DetailLevel = ViewDetailLevel.Fine;
                tmpNode.Tag      = elem.GetOriginalGeometry(opts);
                rootNode.Nodes.Add(tmpNode);
            }

            // now add geometry with the View set to the current view
            if (elem.Document.ActiveView != null)
            {
                Options geomOp2 = m_app.Create.NewGeometryOptions();
                geomOp2.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!;
                geomOp2.View = elem.Document.ActiveView;

                TreeNode rootNode2 = new TreeNode("View = Document.ActiveView");
                rootNode2.Tag = elem.GetOriginalGeometry(geomOp2);
                curNodes.Add(rootNode2);

                // SOFiSTiK FS
                // add model geometry including geometry objects not set as Visible.
                {
                    Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions();
                    opts.ComputeReferences        = false; // Not allowed for GetOriginalGeometry()!;
                    opts.IncludeNonVisibleObjects = true;
                    opts.View = elem.Document.ActiveView;

                    TreeNode rootNode = new TreeNode("View = Document.ActiveView - Including geometry objects not set as Visible");
                    curNodes.Add(rootNode);

                    rootNode.Tag = elem.GetOriginalGeometry(opts);
                }
            }
        }
        /// <summary>
        /// Exports a family instance as a mapped item.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="familyInstance">
        /// The family instance to be exported.
        /// </param>
        /// <param name="exportType">
        /// The export type.
        /// </param>
        /// <param name="ifcEnumType">
        /// The string value represents the IFC type.
        /// </param>
        /// <param name="wrapper">
        /// The ProductWrapper.
        /// </param>
        /// <param name="overrideLevelId">
        /// The level id.
        /// </param>
        /// <param name="range">
        /// The range of this family instance to be exported.
        /// </param>
        public static void ExportFamilyInstanceAsMappedItem(ExporterIFC exporterIFC,
            FamilyInstance familyInstance, IFCExportType exportType, string ifcEnumType,
            ProductWrapper wrapper, ElementId overrideLevelId, IFCRange range, IFCAnyHandle parentLocalPlacement)
        {
            bool exportParts = PartExporter.CanExportParts(familyInstance);
            bool isSplit = range != null;
            if (exportParts && !PartExporter.CanExportElementInPartExport(familyInstance, isSplit ? overrideLevelId : familyInstance.Level.Id, isSplit))
                return;

            Document doc = familyInstance.Document;
            IFCFile file = exporterIFC.GetFile();

            FamilySymbol familySymbol = ExporterIFCUtils.GetOriginalSymbol(familyInstance);
            if (familySymbol == null)
                return;

            ProductWrapper familyProductWrapper = ProductWrapper.Create(wrapper);
            double scale = exporterIFC.LinearScale;
            Options options = GeometryUtil.GetIFCExportGeometryOptions();

            IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle();

            HostObject hostElement = familyInstance.Host as HostObject; //hostElement could be null
            ElementId categoryId = CategoryUtil.GetSafeCategoryId(familySymbol);

            //string emptyString = "";
            string familyName = familySymbol.Name;
            string objectType = familyName;

            // A Family Instance can have its own copy of geometry, or use the symbol's copy with a transform.
            // The routine below tells us whether to use the Instance's copy or the Symbol's copy.
            bool useInstanceGeometry = ExporterIFCUtils.UsesInstanceGeometry(familyInstance);

            IList<IFCExtrusionData> cutPairOpeningsForColumns = new List<IFCExtrusionData>();
            using (IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData())
            {
                Transform trf = familyInstance.GetTransform();

                // Extra information if we are exporting a door or a window.
                IFCDoorWindowInfo doorWindowInfo = null;
                if (exportType == IFCExportType.ExportDoorType)
                    doorWindowInfo = IFCDoorWindowInfo.CreateDoorInfo(exporterIFC, familyInstance, familySymbol, hostElement, overrideLevelId, trf);
                else if (exportType == IFCExportType.ExportWindowType)
                    doorWindowInfo = IFCDoorWindowInfo.CreateWindowInfo(exporterIFC, familyInstance, familySymbol, hostElement, overrideLevelId, trf);

                FamilyTypeInfo typeInfo = new FamilyTypeInfo();
                XYZ extraOffset = XYZ.Zero;

                bool flipped = doorWindowInfo != null ? doorWindowInfo.IsSymbolFlipped : false;
                FamilyTypeInfo currentTypeInfo = ExporterCacheManager.TypeObjectsCache.Find(familySymbol.Id, flipped);
                bool found = currentTypeInfo.IsValid();

                Family family = familySymbol.Family;

                // TODO: this code to be removed by ExtrusionAnalyzer code.
                bool trySpecialColumnCreation = ((exportType == IFCExportType.ExportColumnType) && (!family.IsInPlace));
                IList<GeometryObject> geomObjects = new List<GeometryObject>();
                Transform brepOffsetTransform = null;

                Transform doorWindowTrf = Transform.Identity;
                // We will create a new mapped type if:
                // 1.  We are exporting part of a column or in-place wall (range != null), OR
                // 2.  We are using the instance's copy of the geometry (that it, it has unique geometry), OR
                // 3.  We haven't already created the type.
                bool creatingType = ((range != null) || useInstanceGeometry || !found);
                if (creatingType)
                {
                    IFCAnyHandle bodyRepresentation = null;
                    IFCAnyHandle planRepresentation = null;

                    // If we are using the instance geometry, ignore the transformation.
                    if (useInstanceGeometry)
                        trf = Transform.Identity;

                    // TODO: this code to be removed by ExtrusionAnalyzer code.
                    if (trySpecialColumnCreation)
                    {
                        XYZ rangeOffset = trf.Origin;
                        IFCFamilyInstanceExtrusionExportResults results;

                        results = ExporterIFCUtils.ExportFamilyInstanceAsExtrusion(exporterIFC, familyInstance, useInstanceGeometry, range, overrideLevelId, extraParams);

                        bodyRepresentation = results.GetExtrusionHandle();
                        extraOffset = results.ExtraOffset;
                        cutPairOpeningsForColumns = results.GetCutPairOpenings();

                        if (!IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepresentation))
                        {
                            typeInfo.MaterialIds.Add(results.MaterialId);
                            // add in level for real columns, not in-place ones.
                            Element actualLevel =
                               (overrideLevelId == ElementId.InvalidElementId) ? familyInstance.Level : doc.GetElement(overrideLevelId);
                            if (actualLevel != null)
                            {
                                IFCLevelInfo levelInfo = exporterIFC.GetLevelInfo(actualLevel.Id);
                                double nonStoryLevelOffset = LevelUtil.GetNonStoryLevelOffsetIfAny(exporterIFC, actualLevel as Level);
                                if (range != null)
                                {
                                    rangeOffset = new XYZ(rangeOffset.X, rangeOffset.Y, levelInfo.Elevation + nonStoryLevelOffset);
                                }
                            }
                        }

                        rangeOffset += extraOffset;
                        trf.Origin = rangeOffset;
                    }

                    IFCAnyHandle dummyPlacement = null;
                    if (doorWindowInfo != null)
                    {
                        doorWindowTrf = ExporterIFCUtils.GetTransformForDoorOrWindow(familyInstance, familySymbol, doorWindowInfo);
                    }
                    else
                    {
                        dummyPlacement = IFCInstanceExporter.CreateLocalPlacement(file, null, ExporterUtil.CreateAxis2Placement3D(file));
                        extraParams.SetLocalPlacement(dummyPlacement);
                    }

                    bool needToCreate2d = ExporterCacheManager.ExportOptionsCache.ExportAnnotations;
                    bool needToCreate3d = IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepresentation);

                    if (needToCreate2d || needToCreate3d)
                    {
                        using (IFCTransformSetter trfSetter = IFCTransformSetter.Create())
                        {
                            if (doorWindowInfo != null)
                            {
                                trfSetter.Initialize(exporterIFC, doorWindowTrf);
                            }

                            GeometryElement exportGeometry =
                               useInstanceGeometry ? familyInstance.get_Geometry(options) : familySymbol.get_Geometry(options);
                            if (exportGeometry == null)
                                return;

                            if (needToCreate3d)
                            {
                                SolidMeshGeometryInfo solidMeshCapsule = null;

                                if (range == null)
                                {
                                    solidMeshCapsule = GeometryUtil.GetSolidMeshGeometry(exportGeometry, Transform.Identity);
                                }
                                else
                                {
                                    solidMeshCapsule = GeometryUtil.GetClippedSolidMeshGeometry(exportGeometry, range);
                                }

                                IList<Solid> solids = solidMeshCapsule.GetSolids();
                                IList<Mesh> polyMeshes = solidMeshCapsule.GetMeshes();

                                if (range != null && (solids.Count == 0 && polyMeshes.Count == 0))
                                    return; // no proper split geometry

                                geomObjects = FamilyExporterUtil.RemoveSolidsAndMeshesSetToDontExport(doc, exporterIFC, solids, polyMeshes);
                                if (geomObjects.Count == 0 && (solids.Count > 0 || polyMeshes.Count > 0))
                                    return;

                                bool tryToExportAsExtrusion = (!exporterIFC.ExportAs2x2 || (exportType == IFCExportType.ExportColumnType));

                                if (exportType == IFCExportType.ExportColumnType)
                                {
                                    extraParams.PossibleExtrusionAxes = IFCExtrusionAxes.TryZ;

                                    if (ExporterCacheManager.ExportOptionsCache.ExportAs2x3CoordinationView2 &&
                                        solids.Count > 0)
                                    {
                                        LocationPoint point = familyInstance.Location as LocationPoint;
                                        XYZ orig = XYZ.Zero;
                                        if (point != null)
                                            orig = point.Point;

                                        Plane plane = new Plane(XYZ.BasisX, XYZ.BasisY, orig);
                                        bool completelyClipped = false;
                                        HashSet<ElementId> materialIds = null;
                                        bodyRepresentation = ExtrusionExporter.CreateExtrusionWithClipping(exporterIFC, familyInstance,
                                            categoryId, solids, plane, XYZ.BasisZ, null, out completelyClipped, out materialIds);
                                        typeInfo.MaterialIds = materialIds;
                                    }
                                }
                                else
                                {
                                    extraParams.PossibleExtrusionAxes = IFCExtrusionAxes.TryXYZ;
                                }

                                BodyData bodyData = null;
                                if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepresentation))
                                {
                                    BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(tryToExportAsExtrusion);
                                    if (geomObjects.Count > 0)
                                    {
                                        bodyData = BodyExporter.ExportBody(familyInstance.Document.Application, exporterIFC, familyInstance, categoryId, ElementId.InvalidElementId,
                                            geomObjects, bodyExporterOptions, extraParams);
                                        typeInfo.MaterialIds = bodyData.MaterialIds;
                                    }
                                    else
                                    {
                                        IList<GeometryObject> exportedGeometries = new List<GeometryObject>();
                                        exportedGeometries.Add(exportGeometry);
                                        bodyData = BodyExporter.ExportBody(familyInstance.Document.Application, exporterIFC, familyInstance, categoryId, ElementId.InvalidElementId,
                                            exportedGeometries, bodyExporterOptions, extraParams);
                                    }
                                    bodyRepresentation = bodyData.RepresentationHnd;
                                    brepOffsetTransform = bodyData.BrepOffsetTransform;
                                }

                                if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepresentation))
                                {
                                    extraParams.ClearOpenings();
                                    return;
                                }
                            }

                            // By default: if exporting IFC2x3 or later, export 2D plan rep of family, if it exists, unless we are exporting Coordination View V2.
                            // This default can be overridden in the export options.
                            if (needToCreate2d)
                            {
                                XYZ curveOffset = new XYZ(0, 0, 0);
                                if (brepOffsetTransform != null)
                                    curveOffset = -brepOffsetTransform.Origin / scale;

                                HashSet<IFCAnyHandle> curveSet = new HashSet<IFCAnyHandle>();
                                {
                                    Transform planeTrf = doorWindowTrf.Inverse;
                                    Plane plane = new Plane(planeTrf.get_Basis(0), planeTrf.get_Basis(1), planeTrf.Origin);
                                    XYZ projDir = new XYZ(0, 0, 1);

                                    IFCGeometryInfo IFCGeometryInfo = IFCGeometryInfo.CreateCurveGeometryInfo(exporterIFC, plane, projDir, true);
                                    ExporterIFCUtils.CollectGeometryInfo(exporterIFC, IFCGeometryInfo, exportGeometry, curveOffset, false);

                                    IList<IFCAnyHandle> curves = IFCGeometryInfo.GetCurves();
                                    foreach (IFCAnyHandle curve in curves)
                                        curveSet.Add(curve);

                                    if (curveSet.Count > 0)
                                    {
                                        IFCAnyHandle contextOfItems2d = exporterIFC.Get2DContextHandle();
                                        IFCAnyHandle curveRepresentationItem = IFCInstanceExporter.CreateGeometricSet(file, curveSet);
                                        HashSet<IFCAnyHandle> bodyItems = new HashSet<IFCAnyHandle>();
                                        bodyItems.Add(curveRepresentationItem);
                                        planRepresentation = RepresentationUtil.CreateGeometricSetRep(exporterIFC, familyInstance, categoryId, "Annotation",
                                           contextOfItems2d, bodyItems);
                                    }
                                }
                            }
                        }
                    }

                    if (doorWindowInfo != null)
                    {
                        typeInfo.StyleTransform = doorWindowTrf.Inverse;
                    }
                    else
                    {
                        if (!MathUtil.IsAlmostZero(extraOffset.DotProduct(extraOffset)))
                        {
                            Transform newTransform = typeInfo.StyleTransform;
                            XYZ newOrig = newTransform.Origin + extraOffset;
                            newTransform.Origin = newOrig;
                            typeInfo.StyleTransform = newTransform;
                        }
                        typeInfo.StyleTransform = ExporterIFCUtils.GetUnscaledTransform(exporterIFC, extraParams.GetLocalPlacement());
                    }

                    IFCAnyHandle origin = ExporterUtil.CreateAxis2Placement3D(file);
                    IFCAnyHandle repMap2dHnd = null;
                    IFCAnyHandle repMap3dHnd = IFCInstanceExporter.CreateRepresentationMap(file, origin, bodyRepresentation);

                    IList<IFCAnyHandle> repMapList = new List<IFCAnyHandle>();
                    repMapList.Add(repMap3dHnd);
                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(planRepresentation))
                    {
                        repMap2dHnd = IFCInstanceExporter.CreateRepresentationMap(file, origin, planRepresentation);
                        repMapList.Add(repMap2dHnd);
                    }

                    // for Door, Window
                    bool paramTakesPrecedence = false; // For Revit, this is currently always false.
                    bool sizeable = false;

                    // for many
                    HashSet<IFCAnyHandle> propertySets = new HashSet<IFCAnyHandle>();

                    string guid = GUIDUtil.CreateGUID(familySymbol);
                    string symId = NamingUtil.CreateIFCElementId(familySymbol);

                    // This covers many generic types.  If we can't find it in the list here, do custom exports.
                    IFCAnyHandle typeStyle = FamilyExporterUtil.ExportGenericType(file, exportType, ifcEnumType, guid,
                       ownerHistory, objectType, null, null, propertySets, repMapList, symId, objectType,
                       familyInstance, familySymbol);

                    // Cover special cases not covered above.
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(typeStyle))
                    {
                        switch (exportType)
                        {
                            case IFCExportType.ExportColumnType:
                                {
                                    // If we are using the instance GRep, then we have to create a generic GUID for the
                                    // column type, as they share the same ElementId.
                                    string colGUID = null;
                                    string colElemId = null;

                                    if (useInstanceGeometry)
                                        colGUID = GUIDUtil.CreateGUID();
                                    else
                                        colGUID = guid;
                                    colElemId = NamingUtil.CreateIFCElementId(familySymbol);

                                    string columnType = "Column";
                                    typeStyle = IFCInstanceExporter.CreateColumnType(file, colGUID, ownerHistory, objectType,
                                       null, null, propertySets, repMapList, colElemId,
                                       objectType, GetColumnType(familyInstance, columnType));

                                    break;
                                }
                            case IFCExportType.ExportDoorType:
                                {
                                    string constructionType = string.Empty;
                                    ParameterUtil.GetStringValueFromElementOrSymbol(familyInstance, "Construction", out constructionType);

                                    IFCAnyHandle doorLining = DoorWindowUtil.CreateDoorLiningProperties(exporterIFC, familyInstance);
                                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(doorLining))
                                        propertySets.Add(doorLining);

                                    IList<IFCAnyHandle> doorPanels = DoorWindowUtil.CreateDoorPanelProperties(exporterIFC, doorWindowInfo,
                                       familyInstance);
                                    propertySets.UnionWith(doorPanels);

                                    string doorStyleGUID = GUIDUtil.CreateGUID();
                                    string doorStyleElemId = NamingUtil.CreateIFCElementId(familySymbol);
                                    typeStyle = IFCInstanceExporter.CreateDoorStyle(file, doorStyleGUID, ownerHistory, objectType,
                                       null, null, propertySets, repMapList, doorStyleElemId,
                                       GetDoorStyleOperation(doorWindowInfo.DoorOperationType), GetDoorStyleConstruction(familyInstance, constructionType),
                                       paramTakesPrecedence, sizeable);
                                    break;
                                }
                            case IFCExportType.ExportSystemFurnitureElementType:
                                {
                                    string furnitureId = NamingUtil.CreateIFCElementId(familySymbol);
                                    typeStyle = IFCInstanceExporter.CreateSystemFurnitureElementType(file, guid, ownerHistory, objectType,
                                       null, null, propertySets, repMapList, furnitureId,
                                       objectType);
                                    break;
                                }
                            case IFCExportType.ExportWindowType:
                                {
                                    Toolkit.IFCWindowStyleOperation operationType = DoorWindowUtil.GetIFCWindowStyleOperation(familySymbol);
                                    IFCWindowStyleConstruction constructionType = DoorWindowUtil.GetIFCWindowStyleConstruction(familyInstance, "");

                                    IFCAnyHandle windowLining = DoorWindowUtil.CreateWindowLiningProperties(exporterIFC, familyInstance, null);
                                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(windowLining))
                                        propertySets.Add(windowLining);

                                    IList<IFCAnyHandle> windowPanels =
                                       DoorWindowUtil.CreateWindowPanelProperties(exporterIFC, familyInstance, null);
                                    propertySets.UnionWith(windowPanels);

                                    string windowStyleGUID = GUIDUtil.CreateGUID();
                                    string windowStyleElemId = NamingUtil.CreateIFCElementId(familySymbol);
                                    typeStyle = IFCInstanceExporter.CreateWindowStyle(file, windowStyleGUID, ownerHistory, objectType,
                                       null, null, propertySets, repMapList, windowStyleElemId,
                                       constructionType, operationType, paramTakesPrecedence, sizeable);
                                    break;
                                }
                            case IFCExportType.ExportBuildingElementProxy:
                            default:
                                {
                                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(repMap2dHnd))
                                        typeInfo.Map2DHandle = repMap2dHnd;
                                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(repMap3dHnd))
                                        typeInfo.Map3DHandle = repMap3dHnd;
                                    break;
                                }
                        }
                    }

                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(typeStyle))
                    {
                        CategoryUtil.CreateMaterialAssociations(doc, exporterIFC, typeStyle, typeInfo.MaterialIds);

                        typeInfo.Style = typeStyle;

                        if (((exportType == IFCExportType.ExportColumnType) && trySpecialColumnCreation) ||
                           (exportType == IFCExportType.ExportMemberType))
                        {
                            typeInfo.ScaledArea = extraParams.ScaledArea;
                            typeInfo.ScaledDepth = extraParams.ScaledLength;
                            typeInfo.ScaledInnerPerimeter = extraParams.ScaledInnerPerimeter;
                            typeInfo.ScaledOuterPerimeter = extraParams.ScaledOuterPerimeter;
                        }

                        ClassificationUtil.CreateUniformatClassification(exporterIFC, file, familySymbol, typeStyle);
                    }
                }
                else if (!creatingType && (trySpecialColumnCreation))
                {
                    // still need to modify instance trf for columns.
                    trf.Origin += GetLevelOffsetForExtrudedColumns(exporterIFC, familyInstance, overrideLevelId, extraParams);
                }

                if (found && !typeInfo.IsValid())
                {
                    typeInfo = currentTypeInfo;
                }

                // we'll pretend we succeeded, but we'll do nothing.
                if (!typeInfo.IsValid())
                    return;

                // add to the map, as long as we are not using range, not using instance geometry, and don't have extra openings.
                if ((range == null) && !useInstanceGeometry && (extraParams.GetOpenings().Count == 0))
                    ExporterCacheManager.TypeObjectsCache.Register(familySymbol.Id, flipped, typeInfo);

                Transform oldTrf = new Transform(trf);
                XYZ scaledMapOrigin = XYZ.Zero;

                trf = trf.Multiply(typeInfo.StyleTransform);

                // create instance.
                IList<IFCAnyHandle> shapeReps = new List<IFCAnyHandle>();
                {
                    IFCAnyHandle contextOfItems2d = exporterIFC.Get2DContextHandle();
                    IFCAnyHandle contextOfItems3d = exporterIFC.Get3DContextHandle("Body");

                    // for proxies, we store the IfcRepresentationMap directly since there is no style.
                    IFCAnyHandle style = typeInfo.Style;
                    IList<IFCAnyHandle> repMapList = !IFCAnyHandleUtil.IsNullOrHasNoValue(style) ?
                        GeometryUtil.GetRepresentationMaps(style) : null;
                    int numReps = repMapList != null ? repMapList.Count : 0;

                    IFCAnyHandle repMap2dHnd = typeInfo.Map2DHandle;
                    IFCAnyHandle repMap3dHnd = typeInfo.Map3DHandle;
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(repMap3dHnd) && (numReps > 0))
                        repMap3dHnd = repMapList[0];
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(repMap2dHnd) && (numReps > 1))
                        repMap2dHnd = repMapList[1];

                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(repMap3dHnd))
                    {
                        IList<IFCAnyHandle> representations = new List<IFCAnyHandle>();
                        representations.Add(ExporterUtil.CreateDefaultMappedItem(file, repMap3dHnd, scaledMapOrigin));
                        IFCAnyHandle shapeRep = RepresentationUtil.CreateBodyMappedItemRep(exporterIFC, familyInstance, categoryId, contextOfItems3d,
                            representations);
                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(shapeRep))
                            return;
                        shapeReps.Add(shapeRep);
                    }

                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(repMap2dHnd))
                    {
                        HashSet<IFCAnyHandle> representations = new HashSet<IFCAnyHandle>();
                        representations.Add(ExporterUtil.CreateDefaultMappedItem(file, repMap2dHnd, scaledMapOrigin));
                        IFCAnyHandle shapeRep = RepresentationUtil.CreatePlanMappedItemRep(exporterIFC, familyInstance, categoryId, contextOfItems2d,
                            representations);
                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(shapeRep))
                            return;
                        shapeReps.Add(shapeRep);
                    }
                }

                IFCAnyHandle boundingBoxRep = null;
                Transform boundingBoxTrf = (brepOffsetTransform != null) ? brepOffsetTransform.Inverse : Transform.Identity;
                if (geomObjects.Count > 0)
                    boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geomObjects, boundingBoxTrf);
                else
                {
                    boundingBoxTrf = boundingBoxTrf.Multiply(trf.Inverse);
                    boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, familyInstance.get_Geometry(options), boundingBoxTrf);
                }

                if (boundingBoxRep != null)
                    shapeReps.Add(boundingBoxRep);

                IFCAnyHandle rep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);

                IFCAnyHandle instanceHandle = null;
                using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, familyInstance, trf, null, overrideLevelId))
                {
                    string instanceGUID = GUIDUtil.CreateGUID(familyInstance);
                    string instanceName = NamingUtil.GetIFCName(familyInstance);
                    string instanceDescription = NamingUtil.GetDescriptionOverride(familyInstance, null);
                    string instanceObjectType = NamingUtil.GetObjectTypeOverride(familyInstance, objectType);
                    string instanceElemId = NamingUtil.CreateIFCElementId(familyInstance);

                    IFCAnyHandle localPlacement = setter.GetPlacement();
                    IFCAnyHandle overrideLocalPlacement = null;

                    if (parentLocalPlacement != null)
                    {
                        Transform relTrf = ExporterIFCUtils.GetRelativeLocalPlacementOffsetTransform(parentLocalPlacement, localPlacement);
                        Transform inverseTrf = relTrf.Inverse;

                        IFCAnyHandle relativePlacement = ExporterUtil.CreateAxis2Placement3D(file, inverseTrf.Origin, inverseTrf.BasisZ, inverseTrf.BasisX);
                        IFCAnyHandle plateLocalPlacement = IFCInstanceExporter.CreateLocalPlacement(file, parentLocalPlacement, relativePlacement);
                        overrideLocalPlacement = plateLocalPlacement;
                    }

                    instanceHandle = FamilyExporterUtil.ExportGenericInstance(exportType, exporterIFC, familyInstance,
                       wrapper, setter, extraParams, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType,
                       exportParts ? null : rep, instanceElemId, overrideLocalPlacement);

                    if (exportParts)
                    {
                        PartExporter.ExportHostPart(exporterIFC, familyInstance, instanceHandle, familyProductWrapper, setter, setter.GetPlacement(), overrideLevelId);
                    }

                    if (ElementFilteringUtil.IsMEPType(exportType))
                        ExporterCacheManager.MEPCache.Register(familyInstance, instanceHandle);

                    switch (exportType)
                    {
                        case IFCExportType.ExportColumnType:
                            {
                                IFCAnyHandle placementToUse = localPlacement;
                                if (!useInstanceGeometry)
                                {
                                    bool needToCreateOpenings =
                                        (cutPairOpeningsForColumns.Count != 0) || OpeningUtil.NeedToCreateOpenings(instanceHandle, extraParams);
                                    if (needToCreateOpenings)
                                    {
                                        Transform openingTrf = new Transform(oldTrf);
                                        Transform extraRot = new Transform(oldTrf);
                                        extraRot.Origin = XYZ.Zero;
                                        openingTrf = openingTrf.Multiply(extraRot);
                                        openingTrf = openingTrf.Multiply(typeInfo.StyleTransform);

                                        IFCAnyHandle openingRelativePlacement = ExporterUtil.CreateAxis2Placement3D(file, openingTrf.Origin * scale,
                                           openingTrf.get_Basis(2), openingTrf.get_Basis(0));
                                        IFCAnyHandle openingPlacement = ExporterUtil.CopyLocalPlacement(file, localPlacement);
                                        GeometryUtil.SetRelativePlacement(openingPlacement, openingRelativePlacement);
                                        placementToUse = openingPlacement;
                                    }
                                }

                                OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, familyInstance, cutPairOpeningsForColumns,
                                   exporterIFC, placementToUse, setter, wrapper);
                                OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, familyInstance, extraParams, exporterIFC,
                                   placementToUse, setter, wrapper);

                                //export Base Quantities.
                                PropertyUtil.CreateBeamColumnBaseQuantities(exporterIFC, instanceHandle, familyInstance, typeInfo);

                                PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, familyInstance, wrapper);
                                break;
                            }
                        case IFCExportType.ExportDoorType:
                        case IFCExportType.ExportWindowType:
                            {
                                double doorHeight = doorWindowInfo.OpeningHeight;
                                if (doorHeight < MathUtil.Eps())
                                    doorHeight = GetMinSymbolHeight(familySymbol);
                                double doorWidth = doorWindowInfo.OpeningWidth;
                                if (doorWidth < MathUtil.Eps())
                                    doorWidth = GetMinSymbolWidth(familySymbol);

                                double height = doorHeight * scale;
                                double width = doorWidth * scale;

                                if (IFCAnyHandleUtil.IsNullOrHasNoValue(doorWindowInfo.GetLocalPlacement()))
                                    doorWindowInfo.SetLocalPlacement(localPlacement);

                                IFCAnyHandle doorWindowOrigLocalPlacement = doorWindowInfo.GetLocalPlacement();
                                Transform relTrf = ExporterIFCUtils.GetRelativeLocalPlacementOffsetTransform(localPlacement, doorWindowOrigLocalPlacement);

                                IFCAnyHandle doorWindowRelativePlacement = ExporterUtil.CreateAxis2Placement3D(file, relTrf.Origin, relTrf.BasisZ, relTrf.BasisX);
                                IFCAnyHandle doorWindowLocalPlacement =
                                   IFCInstanceExporter.CreateLocalPlacement(file, doorWindowOrigLocalPlacement, doorWindowRelativePlacement);
                                if (exportType == IFCExportType.ExportDoorType)
                                    instanceHandle = IFCInstanceExporter.CreateDoor(file, instanceGUID, ownerHistory,
                                       instanceName, instanceDescription, instanceObjectType, doorWindowLocalPlacement,
                                       rep, instanceElemId, height, width);
                                else if (exportType == IFCExportType.ExportWindowType)
                                    instanceHandle = IFCInstanceExporter.CreateWindow(file, instanceGUID, ownerHistory,
                                       instanceName, instanceDescription, instanceObjectType, doorWindowLocalPlacement,
                                       rep, instanceElemId, height, width);
                                wrapper.AddElement(instanceHandle, setter, extraParams, true);

                                exporterIFC.RegisterSpaceBoundingElementHandle(instanceHandle, familyInstance.Id, setter.LevelId);

                                IFCAnyHandle placementToUse = doorWindowLocalPlacement;
                                if (!useInstanceGeometry)
                                {
                                    // correct the placement to the symbol space
                                    bool needToCreateOpenings = OpeningUtil.NeedToCreateOpenings(instanceHandle, extraParams);
                                    if (needToCreateOpenings)
                                    {
                                        Transform openingTrf = Transform.Identity;
                                        openingTrf.Origin = new XYZ(0, 0, setter.Offset);
                                        openingTrf = openingTrf.Multiply(doorWindowTrf);
                                        XYZ scaledOrigin = openingTrf.Origin * exporterIFC.LinearScale;
                                        IFCAnyHandle openingRelativePlacement = ExporterUtil.CreateAxis2Placement3D(file, scaledOrigin, openingTrf.BasisZ, openingTrf.BasisX);
                                        IFCAnyHandle openingLocalPlacement =
                                           IFCInstanceExporter.CreateLocalPlacement(file, doorWindowLocalPlacement, openingRelativePlacement);
                                        placementToUse = openingLocalPlacement;
                                    }
                                }
                                // only necessary when exporting as possible breps.
                                OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, familyInstance, extraParams, exporterIFC,
                                   placementToUse, setter, wrapper);
                                if (ExporterCacheManager.ExportOptionsCache.ExportBaseQuantities)
                                    ExporterIFCUtils.CreateDoorWindowBaseQuantities(exporterIFC, instanceHandle, (doorHeight * scale), (doorWidth * scale));

                                PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, familyInstance, wrapper);
                                break;
                            }
                        case IFCExportType.ExportMemberType:
                            {
                                OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, familyInstance, extraParams, exporterIFC,
                                   localPlacement, setter, wrapper);

                                //export Base Quantities.
                                PropertyUtil.CreateBeamColumnBaseQuantities(exporterIFC, instanceHandle, familyInstance, typeInfo);
                                // TODO: create PropertySet!
                                //createMemberPropertySet(exporter, pFamInst, pWrapper, extraParams);
                                PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, familyInstance, wrapper);
                                break;
                            }
                        case IFCExportType.ExportPlateType:
                            {
                                OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, familyInstance, extraParams, exporterIFC,
                                   localPlacement, setter, wrapper);

                                // TODO: create PropertySet!
                                //createPlatePropertySet(exporter, pFamInst, pWrapper, extraParams);
                                PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, familyInstance, wrapper);
                                break;
                            }
                        case IFCExportType.ExportTransportElementType:
                            {
                                IFCAnyHandle localPlacementToUse;
                                ElementId roomId = setter.UpdateRoomRelativeCoordinates(familyInstance, out localPlacementToUse);

                                instanceHandle = IFCInstanceExporter.CreateTransportElement(file, instanceGUID, ownerHistory,
                                   instanceName, instanceDescription, instanceObjectType,
                                   localPlacementToUse, rep, instanceElemId, null, null, null);

                                if (roomId == ElementId.InvalidElementId)
                                {
                                    wrapper.AddElement(instanceHandle, setter, extraParams, true);
                                }
                                else
                                {
                                    exporterIFC.RelateSpatialElement(roomId, instanceHandle);
                                    wrapper.AddElement(instanceHandle, setter, extraParams, false);
                                }

                                PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, familyInstance, wrapper);
                                break;
                            }
                        case IFCExportType.ExportBuildingElementProxy:
                        default:
                            {
                                bool isBuildingElementProxy = (exportType == IFCExportType.ExportBuildingElementProxy);

                                IFCAnyHandle localPlacementToUse;
                                ElementId roomId = setter.UpdateRoomRelativeCoordinates(familyInstance, out localPlacementToUse);

                                if (!isBuildingElementProxy)
                                {
                                    if (FamilyExporterUtil.IsDistributionControlElementSubType(exportType))
                                    {
                                        instanceHandle = IFCInstanceExporter.CreateDistributionControlElement(file, instanceGUID,
                                           ownerHistory, instanceName, instanceDescription, instanceObjectType,
                                           localPlacementToUse, rep, instanceElemId, null);

                                        if (roomId == ElementId.InvalidElementId)
                                        {
                                            wrapper.AddElement(instanceHandle, setter, extraParams, true);
                                        }
                                        else
                                        {
                                            exporterIFC.RelateSpatialElement(roomId, instanceHandle);
                                            wrapper.AddElement(instanceHandle, setter, extraParams, false);
                                        }
                                    }
                                    else if (IFCAnyHandleUtil.IsNullOrHasNoValue(instanceHandle))
                                    {
                                        isBuildingElementProxy = true;
                                    }
                                }

                                if (isBuildingElementProxy)
                                {
                                    Toolkit.IFCElementComposition proxyType = Toolkit.IFCElementComposition.Element;

                                    instanceHandle = IFCInstanceExporter.CreateBuildingElementProxy(file, instanceGUID,
                                       ownerHistory, instanceName, instanceDescription, instanceObjectType,
                                       localPlacementToUse, rep, instanceElemId, proxyType);

                                    if (roomId == ElementId.InvalidElementId)
                                    {
                                        wrapper.AddElement(instanceHandle, setter, extraParams, true);
                                    }
                                    else
                                    {
                                        exporterIFC.RelateSpatialElement(roomId, instanceHandle);
                                        wrapper.AddElement(instanceHandle, setter, extraParams, false);
                                    }
                                }

                                IFCAnyHandle placementToUse = localPlacement;
                                if (!useInstanceGeometry)
                                {
                                    bool needToCreateOpenings = OpeningUtil.NeedToCreateOpenings(instanceHandle, extraParams);
                                    if (needToCreateOpenings)
                                    {
                                        Transform openingTrf = new Transform(oldTrf);
                                        Transform extraRot = new Transform(oldTrf);
                                        extraRot.Origin = XYZ.Zero;
                                        openingTrf = openingTrf.Multiply(extraRot);
                                        openingTrf = openingTrf.Multiply(typeInfo.StyleTransform);

                                        IFCAnyHandle openingRelativePlacement = ExporterUtil.CreateAxis2Placement3D(file, openingTrf.Origin * scale,
                                           openingTrf.get_Basis(2), openingTrf.get_Basis(0));
                                        IFCAnyHandle openingPlacement = ExporterUtil.CopyLocalPlacement(file, localPlacement);
                                        GeometryUtil.SetRelativePlacement(openingPlacement, openingRelativePlacement);
                                        placementToUse = openingPlacement;
                                    }
                                }

                                OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, familyInstance, extraParams, exporterIFC,
                                   placementToUse, setter, wrapper);
                                PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, familyInstance, wrapper);
                                break;
                            }
                    }

                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(instanceHandle))
                    {
                        if (doorWindowInfo != null)
                        {
                            if (!IFCAnyHandleUtil.IsNullOrHasNoValue(doorWindowInfo.GetOpening()))
                            {
                                string relGUID = GUIDUtil.CreateGUID();
                                IFCInstanceExporter.CreateRelFillsElement(file, relGUID, ownerHistory, null, null, doorWindowInfo.GetOpening(), instanceHandle);
                            }
                            else if (doorWindowInfo.NeedsOpening)
                            {
                                bool added = doorWindowInfo.SetDelayedFamilyInstance(instanceHandle, localPlacement, doorWindowInfo.AssignedLevelId);
                                if (added)
                                    exporterIFC.RegisterDoorWindowForOpeningUpdate(doorWindowInfo);
                                else
                                {
                                    // we need to fill a later opening.
                                    exporterIFC.RegisterDoorWindowForUncreatedOpening(familyInstance.Id, instanceHandle);
                                }
                            }
                        }

                        if (!exportParts)
                            CategoryUtil.CreateMaterialAssociations(doc, exporterIFC, instanceHandle, typeInfo.MaterialIds);

                        if (!IFCAnyHandleUtil.IsNullOrHasNoValue(typeInfo.Style))
                            ExporterCacheManager.TypeRelationsCache.Add(typeInfo.Style, instanceHandle);
                    }
                }
            }
        }
示例#56
0
文件: CMD.cs 项目: inktan/RevitApi_
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            #region UI数据交互入口
            UIApplication uiapp = commandData.Application;
            UIDocument    uIdoc = uiapp.ActiveUIDocument;
            Document      doc   = uIdoc.Document;
            #endregion

            #region 创建轴网基准线 3000mmm*3000mm 5*5
            List <Line> horizontalLines = new List <Line>();
            List <Line> verticalLines   = new List <Line>();

            double distance  = 3000;//轴网间距
            double _distance = UnitUtils.Convert(distance, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET);

            XYZ origin             = XYZ.Zero;
            XYZ horizontalXyzStart = new XYZ(-_distance, 0, 0);
            XYZ verticalXyzStart   = new XYZ(0, -_distance, 0);

            int    count          = 6;
            double distanceBuffer = _distance * count;

            XYZ horizontalXyzEnd = new XYZ(-_distance + distanceBuffer, 0, 0);
            XYZ verticalXyzEnd   = new XYZ(0, -_distance + distanceBuffer, 0);

            XYZ horizontalMoveDistance = new XYZ(0, _distance, 0);
            XYZ verticalMoveDistance   = new XYZ(_distance, 0, 0);

            for (int i = 0; i < 5; i++)
            {
                horizontalLines.Add(Line.CreateBound(horizontalXyzStart + horizontalMoveDistance * i, horizontalXyzEnd + horizontalMoveDistance * i));
                verticalLines.Add(Line.CreateBound(verticalXyzStart + verticalMoveDistance * i, verticalXyzEnd + verticalMoveDistance * i));
            }
            #endregion

            List <string> ints = new List <string>()
            {
                "1", "2", "3", "4", "5"
            };
            List <string> letters = new List <string>()
            {
                "A", "B", "C", "D", "E"
            };

            #region 基于基准线,创建轴网
            using (var craetGrids = new Transaction(doc, "创建轴网"))
            {
                craetGrids.Start();
                for (int i = 0; i < 5; i++)
                {
                    Grid gridH = Grid.Create(doc, horizontalLines[i]);
                    gridH.Name = letters[i];
                    Grid gridV = Grid.Create(doc, verticalLines[i]);
                    gridV.Name = ints[i];
                }
                craetGrids.Commit();
            }
            #endregion

            FamilySymbol columnSymbol = (new FilteredElementCollector(doc)).OfCategory(BuiltInCategory.OST_Columns).OfClass(typeof(FamilySymbol)).WhereElementIsElementType().Cast <FamilySymbol>().First();
            Level        level        = (new FilteredElementCollector(doc)).OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level)).WhereElementIsNotElementType().Cast <Level>().First();

            #region 在轴网相交的位置,放置柱子,并同时写入entity

            using (var craetGrids = new Transaction(doc, "放置柱子,并写入entity"))
            {
                craetGrids.Start();
                int i = 0;
                columnSymbol.Activate();

                verticalLines.ForEach(p0 =>
                {
                    int j = 0;
                    horizontalLines.ForEach(p1 =>
                    {
                        IntersectionResultArray intersectionResultArray = new IntersectionResultArray();
                        SetComparisonResult overLap = p0.Intersect(p1, out intersectionResultArray);

                        XYZ interSectPoint = intersectionResultArray.get_Item(0).XYZPoint;

                        FamilyInstance parkingColumn = doc.Create.NewFamilyInstance(interSectPoint, columnSymbol, level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                        SetEntityToBaseWallLoop(doc, schemaGuid, parkingColumn.Id, ints[i].ToString() + letters[j].ToString());

                        j++;
                    });
                    i++;
                });
                craetGrids.Commit();
            }

            #endregion

            return(Result.Succeeded);
            //throw new NotImplementedException();
        }
示例#57
0
 private double GetWindowHeight( FamilyInstance window )
 {
     return window.Document.GetElement( window.GetTypeId() ).get_Parameter( BuiltInParameter.WINDOW_HEIGHT ).AsDouble();
 }
示例#58
0
            /// <summary>
            /// Determine element shape from its connectors.
            /// </summary>
            /// <param name="e">Checked element</param>
            /// <param name="pe">Previous element (optional), in case badly-connected MEP system</param>
            /// <param name="ne">Next element (optional), in case you want shape chenge through flow direction only
            /// (for elements with more than one output)</param>
            /// <returns>Element shape changes</returns>
            static public string GetElementShape(
                Element e,
                Element pe = null,
                Element ne = null)
            {
                if (is_element_of_category(e,
                                           BuiltInCategory.OST_DuctCurves))
                {
                    // assuming that transition is using to change shape..

                    ConnectorManager cm = (e as MEPCurve)
                                          .ConnectorManager;

                    foreach (Connector c in cm.Connectors)
                    {
                        return(c.Shape.ToString()
                               + " 2 " + c.Shape.ToString());
                    }
                }
                else if (is_element_of_category(e,
                                                BuiltInCategory.OST_DuctFitting))
                {
                    MEPSystem system
                        = ExtractMechanicalOrPipingSystem(e);

                    FamilyInstance fi = e as FamilyInstance;
                    MEPModel       mm = fi.MEPModel;

                    ConnectorSet connectors
                        = mm.ConnectorManager.Connectors;

                    if (fi != null && mm is MechanicalFitting)
                    {
                        PartType partType
                            = (mm as MechanicalFitting).PartType;

                        if (PartType.Elbow == partType)
                        {
                            // assuming that transition is using to change shape..

                            foreach (Connector c in connectors)
                            {
                                return(c.Shape.ToString()
                                       + " 2 " + c.Shape.ToString());
                            }
                        }
                        else if (PartType.Transition == partType)
                        {
                            string[] tmp = new string[2];

                            if (system != null)
                            {
                                foreach (Connector c in connectors)
                                {
                                    if (c.Direction == FlowDirectionType.In)
                                    {
                                        tmp[0] = c.Shape.ToString();
                                    }

                                    if (c.Direction == FlowDirectionType.Out)
                                    {
                                        tmp[1] = c.Shape.ToString();
                                    }
                                }
                                return(string.Join(" 2 ", tmp));
                            }
                            else
                            {
                                int i = 0;

                                foreach (Connector c in connectors)
                                {
                                    if (pe != null)
                                    {
                                        if (is_connected_to(c, pe))
                                        {
                                            tmp[0] = c.Shape.ToString();
                                        }
                                        else
                                        {
                                            tmp[1] = c.Shape.ToString();
                                        }
                                    }
                                    else
                                    {
                                        tmp[i] = c.Shape.ToString();
                                    }
                                    ++i;
                                }

                                if (pe != null)
                                {
                                    return(string.Join(" 2 ", tmp));
                                }

                                return(string.Join("-", tmp));
                            }
                        }
                        else if (PartType.Tee == partType ||
                                 PartType.Cross == partType ||
                                 PartType.Pants == partType ||
                                 PartType.Wye == partType)
                        {
                            string from, to;
                            from = to = null;
                            List <string> unk = new List <string>();

                            if (system != null)
                            {
                                foreach (Connector c in connectors)
                                {
                                    if (c.Direction == FlowDirectionType.In)
                                    {
                                        from = c.Shape.ToString();
                                    }
                                    else
                                    {
                                        unk.Add(c.Shape.ToString());
                                    }

                                    if (ne != null && is_connected_to(c, ne))
                                    {
                                        to = c.Shape.ToString();
                                    }
                                }

                                if (to != null)
                                {
                                    return(from + " 2 " + to);
                                }

                                return(from + " 2 " + string.Join("-",
                                                                  unk.ToArray()));
                            }
                            else
                            {
                                foreach (Connector c in connectors)
                                {
                                    if (ne != null && is_connected_to(
                                            c, ne))
                                    {
                                        to = c.Shape.ToString();
                                        continue;
                                    }

                                    if (pe != null && is_connected_to(
                                            c, pe))
                                    {
                                        from = c.Shape.ToString();
                                        continue;
                                    }

                                    unk.Add(c.Shape.ToString());
                                }

                                if (to != null)
                                {
                                    return(from + " 2 " + to);
                                }

                                if (from != null)
                                {
                                    return(from + " 2 "
                                           + string.Join("-", unk.ToArray()));
                                }

                                return(string.Join("-", unk.ToArray()));
                            }
                        }
                    }
                }
                return("unknown");
            }
 public static DoorWindowInfo CreateWindow(ExporterIFC exporterIFC, FamilyInstance famInst, HostObject hostObj,
     ElementId overrideLevelId, Transform trf)
 {
     return DoorWindowInfo.CreateWindow(exporterIFC, famInst, hostObj, overrideLevelId, trf);
 }
示例#60
0
            /// <summary>
            /// Determine element shape from
            /// its MEP PartType and Size parameter.
            /// @: maciej szlek
            /// [email protected]
            /// http://maciejszlek.pl
            /// </summary>
            public static string GetElementShape(Element e)
            {
                if (is_element_of_category(e,
                                           BuiltInCategory.OST_DuctCurves))
                {
                    // simple case, no need to use regular expression

                    //string size = e.get_Parameter( "Size" ) // 2014
                    //  .AsString();

                    Debug.Assert(
                        1 == e.GetParameters("Size").Count,
                        "expected only one parameters named 'Size'");

                    string size = e.LookupParameter("Size") // 2015
                                  .AsString();

                    if (size.Split('x').Length == 2)
                    {
                        return("rectangular");
                    }
                    else if (size.Split('/').Length == 2)
                    {
                        return("oval");
                    }
                    else
                    {
                        return("round");
                    }
                }
                else if (is_element_of_category(e,
                                                BuiltInCategory.OST_DuctFitting))
                {
                    FamilyInstance fi = e as FamilyInstance;

                    if (fi != null && fi.MEPModel is MechanicalFitting)
                    {
                        string size = e.get_Parameter("Size")
                                      .AsString();

                        PartType partType = (fi.MEPModel as
                                             MechanicalFitting).PartType;

                        if (PartType.Elbow == partType ||
                            PartType.Transition == partType)
                        {
                            // more complex case

                            #region Metric only
#if METRIC_ONLY_BEFORE_REGEX_CACHE
                            if (size.Split('x').Length == 3) // could use a regex "[0-9]x[0-9]+-[0-9]+/[0-9]+" but splitting is less costly
                            {
                                return("rectangular2rectangular");
                            }
                            else if (size.Split('/').Length == 3)
                            {
                                return("oval2oval");
                            }
                            else if (
                                new Regex(@"[0-9]+x[0-9]+-[0-9]+/[0-9]+")
                                .IsMatch(size))
                            {
                                return("rectangular2oval");
                            }
                            else if (
                                new Regex(@"[0-9]+/[0-9]+-[0-9]+x[0-9]+")
                                .IsMatch(size))
                            {
                                return("oval2rectangular");
                            }
                            else if (
                                new Regex(@"[0-9]+[^0-9]-[0-9]+x[0-9]+")
                                .IsMatch(size))
                            {
                                return("round2rectangular");
                            }
                            else if (
                                new Regex(@"[0-9]+x[0-9]+-[0-9]+[^0-9]")
                                .IsMatch(size))
                            {
                                return("rectangular2round");
                            }
                            else if (
                                new Regex(@"[0-9]+[^0-9]-[0-9]+/[0-9]+")
                                .IsMatch(size))
                            {
                                return("round2oval");
                            }
                            else if (
                                new Regex(@"[0-9]+/[0-9]+-[0-9]+[^0-9]")
                                .IsMatch(size))
                            {
                                return("oval2round");
                            }
                            else if (
                                new Regex(@"[0-9]+[^0-9]-[0-9]+[^0-9]")
                                .IsMatch(size))
                            {
                                return("round2round");
                            }
                            else
                            {
                                return("other case");
                            }
#endif // METRIC_ONLY_BEFORE_REGEX_CACHE

#if METRIC_ONLY
                            if (size.Split('x').Length == 3) // could use a regex "[0-9]x[0-9]+-[0-9]+/[0-9]+" but splitting is less costly
                            {
                                return("rectangular2rectangular");
                            }
                            else if (size.Split('/').Length == 3)
                            {
                                return("oval2oval");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+x[0-9]+-[0-9]+/[0-9]+", size))
                            {
                                return("rectangular2oval");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+/[0-9]+-[0-9]+x[0-9]+", size))
                            {
                                return("oval2rectangular");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+[^0-9]-[0-9]+x[0-9]+", size))
                            {
                                return("round2rectangular");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+x[0-9]+-[0-9]+[^0-9]", size))
                            {
                                return("rectangular2round");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+[^0-9]-[0-9]+/[0-9]+", size))
                            {
                                return("round2oval");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+/[0-9]+-[0-9]+[^0-9]", size))
                            {
                                return("oval2round");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+[^0-9]-[0-9]+[^0-9]", size))
                            {
                                return("round2round");
                            }
#endif // METRIC_ONLY
                            #endregion // Metric only

                            if (size.Split('x').Length == 3) // or use Regex("[0-9]x[0-9]+-[0-9]+/[0-9]+") but splitting is less costly
                            {
                                return("rectangular2rectangular");
                            }
                            else if (size.Split('/').Length == 3) // but if in imperial units size is in fractional inches format it has to be replaced by another regular expression
                            {
                                return("oval2oval");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?x[0-9]+\"?-[0-9]+\"?/[0-9]+\"?", size))
                            {
                                return("rectangular2oval");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?/[0-9]+\"?-[0-9]+\"?x[0-9]+\"?", size))
                            {
                                return("oval2rectangular");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?[^0-9]-[0-9]+\"?x[0-9]+\"?", size))
                            {
                                return("round2rectangular");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?x[0-9]+\"?-[0-9]+\"?[^0-9]", size))
                            {
                                return("rectangular2round");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?[^0-9]-[0-9]+\"?/[0-9]+\"?", size))
                            {
                                return("round2oval");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?/[0-9]+\"?-[0-9]+\"?[^0-9]", size))
                            {
                                return("oval2round");
                            }
                            else if (_regexCache.Match(
                                         "[0-9]+\"?[^0-9]-[0-9]+\"?[^0-9]", size))
                            {
                                return("round2round");
                            }
                            else
                            {
                                return("other case");
                            }
                        }
                        // etc (for other part types)
                        else
                        {
                        }
                    }
                    // etc (for other categories)
                    else
                    {
                    }
                }
                return("unknown");
            }