Ejemplo n.º 1
0
        /// <summary>
        /// create column of certain type in given position
        /// </summary>
        /// <param name="point2D">2D coordinate of the column</param>
        /// <param name="columnType">specified type of the column</param>
        /// <param name="baseLevel">base level of the column</param>
        /// <param name="topLevel">top level of the colunm</param>
        private FamilyInstance NewColumn(Autodesk.Revit.DB.UV point2D, Level baseLevel, Level topLevel)
        {
            //create column of specified type with certain level and start point
            Autodesk.Revit.DB.XYZ point = new Autodesk.Revit.DB.XYZ(point2D.U, point2D.V, 0);

            FamilyInstance column =
                m_docCreator.NewFamilyInstance(point, m_data.ColumnSymbol, baseLevel, StructuralType.Column);

            //set baselevel & toplevel of the column
            SetParameter(column, BuiltInParameter.FAMILY_TOP_LEVEL_PARAM, topLevel.Id);
            SetParameter(column, BuiltInParameter.FAMILY_BASE_LEVEL_PARAM, baseLevel.Id);
            SetParameter(column, BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM, 0.0);
            SetParameter(column, BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM, 0.0);
            return(column);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create one temporary door instance with this family.
        /// </summary>
        /// <returns>the created door.</returns>
        private FamilyInstance CreateOneInstanceWithThisFamily()
        {
            Autodesk.Revit.DB.Document          doc    = m_app.ActiveUIDocument.Document;
            Autodesk.Revit.Creation.Document    creDoc = doc.Create;
            Autodesk.Revit.Creation.Application creApp = m_app.Application.Create;

            // get one level. A project has at least one level.
            Level level = new FilteredElementCollector(doc).OfClass(typeof(Level)).FirstElement() as Level;

            // create one wall as door's host
            Line wallCurve = creApp.NewLineBound(new Autodesk.Revit.DB.XYZ(0, 0, 0), new Autodesk.Revit.DB.XYZ(100, 0, 0));
            Wall host      = creDoc.NewWall(wallCurve, level, false);

            doc.Regenerate();

            // door symbol.
            FamilySymbolSetIterator doorSymbolIter = m_family.Symbols.ForwardIterator();

            doorSymbolIter.MoveNext();
            FamilySymbol doorSymbol = doorSymbolIter.Current as FamilySymbol;

            // create the door
            FamilyInstance createdFamilyInstance = creDoc.NewFamilyInstance(new Autodesk.Revit.DB.XYZ(0, 0, 0), doorSymbol, host, level,
                                                                            StructuralType.NonStructural);

            doc.Regenerate();

            return(createdFamilyInstance);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create one temporary door instance with this family.
        /// </summary>
        /// <returns>the created door.</returns>
        private FamilyInstance CreateOneInstanceWithThisFamily()
        {
            Autodesk.Revit.DB.Document          doc    = m_app.ActiveUIDocument.Document;
            Autodesk.Revit.Creation.Document    creDoc = doc.Create;
            Autodesk.Revit.Creation.Application creApp = m_app.Application.Create;

            // get one level. A project has at least one level.
            Level level = new FilteredElementCollector(doc).OfClass(typeof(Level)).FirstElement() as Level;

            // create one wall as door's host
            Line wallCurve = Line.CreateBound(new Autodesk.Revit.DB.XYZ(0, 0, 0), new Autodesk.Revit.DB.XYZ(100, 0, 0));
            Wall host      = Wall.Create(doc, wallCurve, level.Id, false);

            doc.Regenerate();

            // door symbol.
            List <FamilySymbol> ffs = new List <FamilySymbol>();

            foreach (ElementId elementId in m_family.GetFamilySymbolIds())
            {
                ffs.Add((FamilySymbol)(m_app.ActiveUIDocument.Document.GetElement(elementId)));
            }
            FamilySymbol doorSymbol = ffs[0];

            // create the door
            FamilyInstance createdFamilyInstance = creDoc.NewFamilyInstance(new Autodesk.Revit.DB.XYZ(0, 0, 0), doorSymbol, host, level,
                                                                            StructuralType.NonStructural);

            doc.Regenerate();

            return(createdFamilyInstance);
        }
Ejemplo n.º 4
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            IWin32Window revit_window
                = new JtWindowHandle(
                      ComponentManager.ApplicationWindow);

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            PlaceInstancesForm f
                = new PlaceInstancesForm(doc);

            if ((DialogResult.OK == f.ShowDialog(revit_window)) &&
                (null != f.Points))
            {
                using (Transaction t = new Transaction(
                           doc))
                {
                    t.Start("Place Instances");

                    Autodesk.Revit.Creation.Document
                        creation_doc = doc.Create;

                    StructuralType st
                        = StructuralType.NonStructural;

                    foreach (XYZ p in f.Points)
                    {
                        creation_doc.NewFamilyInstance(
                            p, f.Type, st);
                    }

                    t.Commit();
                }
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 5
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Hello World
            //TaskDialog.Show("VL title", "VL says Hello Revit");

            var uiApp = commandData.Application;
            var app   = commandData.Application.Application;
            var uiDoc = commandData.Application.ActiveUIDocument;
            var doc   = commandData.Application.ActiveUIDocument.Document;


            #region 放置类型为"0762*2032 mm"的门
            //首先通过类型过滤出 类型为门的族类型,找到名称相同的
            string       doorTypeName = "0762*2032 mm";
            FamilySymbol doorType     = null;
            var          filter       = new LogicalAndFilter(
                new ElementCategoryFilter(BuiltInCategory.OST_Doors),
                new ElementClassFilter(typeof(FamilySymbol))
                );
            var  collector   = new FilteredElementCollector(doc).WherePasses(filter);
            bool symbolFound = collector.FirstOrDefault(c => c.Name == doorTypeName) != null;
            //如果没有则通过文件加载族
            if (symbolFound)
            {
                doorType = collector.FirstOrDefault(c => c.Name == doorTypeName) as FamilySymbol;
            }
            else
            {
                string file = @"familyFilePath";
                Family family;
                if (doc.LoadFamily(file, out family))
                {
                    var validType = family.GetValidTypes().FirstOrDefault(c =>
                    {
                        var symbol = (doc.GetElement(c) as FamilySymbol);
                        if (symbol != null && symbol.Name == doorTypeName)
                        {
                            return(true);
                        }
                        return(false);
                    });
                    if (validType != null)
                    {
                        doorType    = doc.GetElement(validType) as FamilySymbol;
                        symbolFound = true;
                    }
                }
            }
            //使用族类型创建门 线性的门是有着LocationCurve的且LocationCurve.Curve为Line的元素
            Wall wall = null;
            if (doorType != null)
            {
                Element element = new FilteredElementCollector(doc)
                                  .WherePasses(new ElementClassFilter(typeof(Wall)))
                                  .FirstOrDefault(c =>
                {
                    var locationCurve = c.Location as LocationCurve;
                    if (locationCurve != null)
                    {
                        var line = locationCurve.Curve as Line;
                        if (line != null)
                        {
                            return(true);
                        }
                        return(false);
                    }
                    return(false);
                });
                if (element != null)
                {
                    wall = element as Wall;
                }
            }
            //在墙的中心创建一个门
            if (wall != null)
            {
                var            line          = (wall.Location as LocationCurve).Curve as Line;
                var            wallLevel     = doc.GetElement(wall.LevelId) as Level;
                XYZ            midPoint      = (line.GetEndPoint(0) + line.GetEndPoint(1)) / 2;
                var            structureType = Autodesk.Revit.DB.Structure.StructuralType.NonStructural;
                FamilyInstance door          = doc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, structureType);
            }
            #endregion

            #region  制墙类型
            var wallElementId = 1111;
            wall = doc.GetElement(new ElementId(wallElementId)) as Wall;
            if (wall != null)
            {
                var         wallType       = wall.WallType;
                ElementType duplicatedType = wallType.Duplicate(wall.Name + "duplicated");
            }
            #endregion

            #region 元素移动
            VLTransactionHelper.DelegateTransaction(doc, "创建一根柱子", () =>
            {
                //Revit文档的创建句柄
                Autodesk.Revit.Creation.Document creator = doc.Create;
                XYZ origin              = new XYZ(0, 0, 0);
                Level level             = doc.GetElement(new ElementId(12122)) as Level;
                FamilySymbol columnType = doc.GetElement(new ElementId(12123)) as FamilySymbol;
                var structureType       = Autodesk.Revit.DB.Structure.StructuralType.Column;
                FamilyInstance column   = creator.NewFamilyInstance(origin, columnType, level, structureType);
                XYZ newPlace            = new XYZ(10, 20, 30);
                ElementTransformUtils.MoveElement(doc, column.Id, newPlace);
                return(true);
            });
            #endregion

            #region ElementTransformUtils
            //ElementTransformUtils.CopyElement();
            //ElementTransformUtils.CopyElements();
            //ElementTransformUtils.MirrorElement();
            //ElementTransformUtils.MirrorElements();
            //ElementTransformUtils.MoveElement();
            //ElementTransformUtils.MoveElements();
            //ElementTransformUtils.RotateElement();
            //ElementTransformUtils.RotateElements();
            #endregion

            #region 元素旋转
            VLTransactionHelper.DelegateTransaction(doc, "ElementTransformUtils旋转方法", () =>
            {
                LocationCurve wallLine = wall.Location as LocationCurve;
                XYZ p1    = wallLine.Curve.GetEndPoint(0);
                XYZ p2    = new XYZ(p1.X, p1.Y, 30);
                Line axis = Line.CreateBound(p1, p2);
                ElementTransformUtils.RotateElement(doc, wall.Id, axis, Math.PI / 3);//逆时针60°
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "LocationCurve,LocationPoint,自带的旋转方法", () =>
            {
                LocationCurve locationCurve = wall.Location as LocationCurve;//线性坐标自带线
                if (locationCurve != null)
                {
                    Curve curve = locationCurve.Curve;
                    var start   = curve.GetEndPoint(0);
                    Line axis   = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationCurve.Rotate(axis, Math.PI);//PI=180°
                }
                LocationPoint locationPoint = wall.Location as LocationPoint;
                if (locationPoint != null)
                {
                    var start = locationPoint.Point;
                    Line axis = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationPoint.Rotate(axis, Math.PI);
                }
                return(true);
            });
            #endregion

            #region 元素镜像
            VLTransactionHelper.DelegateTransaction(doc, "元素镜像", () =>
            {
                Plane plane = new Plane(XYZ.BasisX, XYZ.Zero);
                if (ElementTransformUtils.CanMirrorElement(doc, wall.Id))
                {
                    ElementTransformUtils.MirrorElement(doc, wall.Id, plane);
                }
                return(true);
            });
            #endregion

            #region 元素删除
            //var deleteElements = Document.Delete(@ElementIds);
            #endregion

            #region 元素组合
            VLTransactionHelper.DelegateTransaction(doc, "元素组合", () =>
            {
                List <ElementId> elementIds = new List <ElementId>()
                {
                    new ElementId(1000),
                    new ElementId(1001),
                    new ElementId(1002),
                };
                Group group = doc.Create.NewGroup(elementIds);
                return(true);
            });
            #endregion

            #region 元素编辑
            VLTransactionHelper.DelegateTransaction(doc, "创建参照平面", () =>
            {
                XYZ bubbleEnd = new XYZ(0, 5, 5);
                XYZ freeEnd   = new XYZ(5, 5, 5);
                XYZ cutVector = XYZ.BasisY;
                View view     = doc.ActiveView;
                ReferencePlane referencePlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVector, view);
                referencePlane.Name           = "MyReferencePlane";
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "创建参照线,由模型线-转>参照线", () =>
            {
                ModelCurve modelCurve = doc.GetElement(new ElementId(1000)) as ModelCurve;//ModelCurve模型线
                modelCurve.ChangeToReferenceLine();
                //modelCurve.IsReferenceLine;
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "通过标高创建草图平面,然后在草图平面创建模型线", () =>
            {
                Level level             = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).FirstOrDefault() as Level;
                Line line               = Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 0));
                SketchPlane sketchPlane = SketchPlane.Create(doc, level.Id);
                ModelCurve modelLine    = doc.FamilyCreate.NewModelCurve(line, sketchPlane);
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "使用拉身体获取相应的草图平面", () =>
            {
                Extrusion extrusion         = doc.GetElement(new ElementId(11212)) as Extrusion;
                SketchPlane sketchPlane     = extrusion.Sketch.SketchPlane;
                CurveArrArray sketchProfile = extrusion.Sketch.Profile;
                return(true);
            });
            #endregion

            #region 族
            string       tagName   = "梁平法_集中标_左对齐";
            FamilySymbol tagSymbol = null;
            //查找族类型
            var symbols = new FilteredElementCollector(doc)
                          .WherePasses(new ElementClassFilter(typeof(FamilySymbol)))
                          .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_StructuralFramingTags));
            var targetSymbol = symbols.FirstOrDefault(c => c.Name == tagName);
            if (targetSymbol != null)
            {
                tagSymbol = targetSymbol as FamilySymbol;
            }
            //空时加载族类型
            if (tagSymbol == null)
            {
                var    symbolFile = @"E:\WorkingSpace\Tasks\0526标注\梁平法_集中标_左对齐.rfa";
                Family family;
                if (doc.LoadFamily(symbolFile, out family))
                {
                    foreach (ElementId typeId in family.GetValidTypes())
                    {
                        var validType = doc.GetElement(typeId) as FamilySymbol;
                        if (validType != null && validType.Name == tagName)
                        {
                            tagSymbol = validType;
                            break;
                        }
                    }
                }
                else
                {
                    TaskDialogShow("加载族文件失败");
                }
            }
            //如果上述两者获取到了对应的族
            if (tagSymbol != null)
            {
                //doc.Create.NewFamilyInstance(, tagSymbol);
            }
            #endregion

            #region 建筑建模

            VLTransactionHelper.DelegateTransaction(doc, "修改标高的基面", () =>
            {
                var levelId         = 111;
                Level level         = doc.GetElement(new ElementId(levelId)) as Level;
                LevelType levelType = doc.GetElement(level.GetTypeId()) as LevelType;


                return(true);
            });


            #endregion

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            Autodesk.Revit.Creation.Application createApp
                = app.Application.Create;

            Autodesk.Revit.Creation.Document createDoc
                = doc.Create;

            // Determine the wall endpoints:

            double length = 5 * MeterToFeet;

            XYZ [] pts = new XYZ[2];

            pts[0] = XYZ.Zero;
            pts[1] = new XYZ(length, 0, 0);

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

            Level levelBottom = null;
            Level levelTop    = null;

            if (!GetBottomAndTopLevels(doc,
                                       ref levelBottom, ref levelTop))
            {
                message = "Unable to determine "
                          + "wall bottom and top levels";

                return(Result.Failed);
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Wall, Door and Tag");

                // Create a wall:

                BuiltInParameter topLevelParam
                    = BuiltInParameter.WALL_HEIGHT_TYPE;

                ElementId topLevelId = levelTop.Id;

                //Line line = createApp.NewLineBound( pts[0], pts[1] ); // 2013
                Line line = Line.CreateBound(pts[0], pts[1]); // 2014

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

                Wall wall = Wall.Create( // 2013
                    doc, line, levelBottom.Id, false);

                Parameter param = wall.get_Parameter(
                    topLevelParam);

                param.Set(topLevelId);

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

                //double wallThickness = wall.WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011

                double wallThickness = wall.WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012

                // Add door to wall;
                // note that the NewFamilyInstance method
                // does not automatically add a door tag,
                // like the UI command does:

                FamilySymbol doorSymbol = GetFirstFamilySymbol(
                    doc, BuiltInCategory.OST_Doors);

                if (null == doorSymbol)
                {
                    message = "No door symbol found.";
                    return(Result.Failed);
                }

                XYZ midpoint = Util.Midpoint(pts[0], pts[1]);

                FamilyInstance door = createDoc
                                      .NewFamilyInstance(
                    midpoint, doorSymbol, wall, levelBottom,
                    StructuralType.NonStructural);

                // Create door tag:

                View view = doc.ActiveView;

                double tagOffset = 3 * wallThickness;

                midpoint += tagOffset * XYZ.BasisY;

                // 2011: TagOrientation.TAG_HORIZONTAL

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

                // Create and assign new door tag type:

                FamilySymbol doorTagType
                    = GetFirstFamilySymbol(
                          doc, BuiltInCategory.OST_DoorTags);

                doorTagType = doorTagType.Duplicate(
                    "New door tag type") as FamilySymbol;

                tag.ChangeTypeId(doorTagType.Id);

                // Demonstrate changing name of
                // family instance and family symbol:

                door.Name        = door.Name + " modified";
                door.Symbol.Name = door.Symbol.Name + " modified";

                t.Commit();
            }

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Result        rc  = Result.Failed;
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            // Check whether the family we are interested in is loaded:

#if _2010
            List <Element> symbols      = new List <Element>();
            Filter         filterFamily = creApp.Filter.NewFamilyFilter(_family_name);
            doc.get_Elements(filterFamily, symbols);

            // the family filter returns both the symbols and the family itself:

            Family f = null;
            foreach (Element e in symbols)
            {
                if (e is Family)
                {
                    f = e as Family;
                }
                else if (e is FamilySymbol)
                {
                    FamilySymbol s = e as FamilySymbol;
                    Debug.Print("Family name={0}, symbol name={1}", s.Family.Name, s.Name);
                }
            }
#endif // _2010

            Family f = Util.GetFirstElementOfTypeNamed(
                doc, typeof(Family), _family_name) as Family;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Beam Type and Instance");
                // If the family was not already loaded, then do so:

                if (null == f)
                {
                    if (!doc.LoadFamily(_path, out f))
                    {
                        message = "Unable to load '" + _path + "'.";
                    }
                }

                if (null != f)
                {
                    Debug.Print("Family name={0}", f.Name);

                    // Pick a symbol for duplication, any one will do,
                    // we select the first:

                    FamilySymbol s = null;

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

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

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

                    // Duplicate the existing symbol:

                    ElementType s1 = s.Duplicate("Nuovo simbolo");
                    s = s1 as FamilySymbol;

                    // Analyse the symbol parameters:

                    foreach (Parameter param in s.Parameters)
                    {
                        Debug.Print("Parameter name={0}, value={1}", param.Definition.Name, param.AsValueString());
                    }

                    // Define new dimensions for our new type;
                    // the specified parameter name is case sensitive:

                    //s.get_Parameter( "b" ).Set( Util.MmToFoot( 500 ) ); // 2014
                    //s.get_Parameter( "h" ).Set( Util.MmToFoot( 1000 ) ); // 2014

                    s.LookupParameter("b").Set(Util.MmToFoot(500));  // 2015
                    s.LookupParameter("h").Set(Util.MmToFoot(1000)); // 2015

                    // we can change the symbol name at any time:

                    s.Name = "Nuovo simbolo due";

                    // insert an instance of our new symbol:

                    Autodesk.Revit.Creation.Application creApp = app.Application.Create;
                    Autodesk.Revit.Creation.Document    creDoc = doc.Create;

                    // It is possible to insert a beam,
                    // which normally uses a location line,
                    // by specifying only a location point:

                    //XYZ p = XYZ.Zero;
                    //doc.Create.NewFamilyInstance( p, s, nonStructural );

                    XYZ  p    = XYZ.Zero;
                    XYZ  q    = creApp.NewXYZ(30, 20, 20); // feet
                    Line line = Line.CreateBound(p, q);

                    // Specifying a non-structural type here means no beam
                    // is created, and results in a null family instance:

                    FamilyInstance fi = creDoc.NewFamilyInstance(
                        line, s, null, stBeam);

                    // This creates a visible family instance,
                    // but the resulting beam has no location line
                    // and behaves strangely, e.g. cannot be selected:
                    //FamilyInstance fi = doc.Create.NewFamilyInstance(
                    //  p, s, q, null, nonStructural );

                    //List<Element> levels = new List<Element>();
                    //doc.get_Elements( typeof( Level ), levels );
                    //Debug.Assert( 0 < levels.Count,
                    //  "expected at least one level in model" );
                    //Level level = levels[0] as Level;
                    //fi = doc.Create.NewFamilyInstance(
                    //  line, s, level, nonStructural );

                    rc = Result.Succeeded;
                }
                t.Commit();
            }
            return(rc);
        }
Ejemplo n.º 8
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                WaitCursor    waitCursor = new WaitCursor();
                UIApplication app        = commandData.Application;
                Document      doc        = app.ActiveUIDocument.Document;
                Autodesk.Revit.Creation.Application createApp = app.Application.Create;
                Autodesk.Revit.Creation.Document    createDoc = doc.Create;

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

                    // Determine the four corners of the rectangular house:

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

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

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

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

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

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

                    BuiltInParameter topLevelParam
                        = BuiltInParameter.WALL_HEIGHT_TYPE;

                    Line      line;
                    Wall      wall;
                    Parameter param;

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

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

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

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

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

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

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

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

                    FamilySymbol door
                        = doorSymbols[0] as FamilySymbol;

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

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

                    midpoint.Z = levelMiddle.Elevation;

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

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

                    Level levelBottom = null;
                    Level levelTop    = null;

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

                    // Create the walls:

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

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

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

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

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

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

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

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

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

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

                    door.Activate(); // 2016

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

                    midpoint += tagOffset * XYZ.BasisY;

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

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

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

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

                    window.Activate(); // 2016

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

                    p += tagOffset * XYZ.BasisY;

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

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

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

                    q += tagOffset * XYZ.BasisY;

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

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

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

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

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

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

                        profile.Append(line);
                    }

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

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

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

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

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

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

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

                    ModelCurveArray modelCurves
                        = new ModelCurveArray();

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

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

                    doc.Regenerate();

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

                    double slope = 0.3;

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

                    // Add a room and a room tag:

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

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

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

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

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

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

                    t.Commit();

                    return(Result.Succeeded);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 9
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = commandData.Application.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            View   acview   = uidoc.ActiveView;
            UIView acuiview = uidoc.ActiveUiview();


            Transaction ts = new Transaction(doc, "******");

            try
            {
                ts.Start();

                //获取revit文档的创建句柄
                Autodesk.Revit.Creation.Document creater = doc.Create;

                //创建一根柱子: 使用给点的位置(坐标原点),柱子的类型和标高(高度为0)
                XYZ origin = new XYZ(0, 0, 0);

                //获得level
                Level level = null;
                if (acview.ViewType == ViewType.FloorPlan)
                {
                    level = acview.GenLevel;
                }

                if (level == null)
                {
                    MessageBox.Show("未找到楼层");
                    return(Result.Cancelled);
                }

                //获取symbol
                var symbol = doc.TCollector <FamilySymbol>()
                             .Where(m => m.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns).First();

                if (symbol == null)
                {
                    MessageBox.Show("未找到柱子的族符号");
                    return(Result.Cancelled);
                }

                //创建柱子
                FamilyInstance colum = creater.NewFamilyInstance(origin, symbol, level,
                                                                 Autodesk.Revit.DB.Structure.StructuralType.Column);


                // 把柱子移动到新的位置
                XYZ newPlace = new XYZ(100, 100, 100);
                ElementTransformUtils.MoveElement(doc, colum.Id, newPlace);


                ts.Commit();
            }

            catch (Exception)
            {
                if (ts.GetStatus() == TransactionStatus.Started)
                {
                    ts.RollBack();
                }
            }

            return(Result.Succeeded);
        }