コード例 #1
0
ファイル: CSAModel.cs プロジェクト: wzfxue/Revit
        /// <summary>
        /// 按XY的点的Z轴旋转
        /// </summary>
        /// <param name="point"></param>
        /// <param name="xyz"></param>
        /// <param name="verticalVector"></param>
        public static void RotateByXY(this LocationPoint point, XYZ xyz, XYZ verticalVector)
        {
            Line axis = Line.CreateBound(xyz, xyz.Add(new XYZ(0, 0, 10)));

            if (verticalVector.X > VLConstraintsForCSA.MiniValueForXYZ)
            {
                point.Rotate(axis, 2 * Math.PI - verticalVector.AngleTo(new XYZ(0, 1, verticalVector.Z)));
            }
            else
            {
                point.Rotate(axis, verticalVector.AngleTo(new XYZ(0, 1, verticalVector.Z)));
            }
        }
コード例 #2
0
ファイル: FamilyInstance_.cs プロジェクト: inktan/RevitApi_
        /// <summary>
        /// 旋转族实例, 旋转轴线段方向为Z轴正方向,当前测试为顺时针旋转-不包含事务
        /// </summary>
        public static void Rotate(this FamilyInstance fs, double _angle)
        {
            LocationPoint _point = fs.Location as LocationPoint;

            if (_point != null)
            {
                XYZ  aa    = _point.Point;
                XYZ  cc    = _point.Point + new XYZ(0, 0, 1);
                Line _axis = Line.CreateBound(aa, cc);
                _point.Rotate(_axis, _angle);
            }
        }
コード例 #3
0
ファイル: FamilyInstance_.cs プロジェクト: inktan/RevitApi_
 /// <summary>
 /// 旋转族实例, 旋转轴线段方向为Z轴正方向,当前测试为顺时针旋转-包含事务
 /// </summary>
 public static void RotateWithTrans(this FamilyInstance fs, Document doc, double _angle)
 {
     using (Transaction _rotateTrans = new Transaction(doc))
     {
         _rotateTrans.Start("_rotateTrans");
         LocationPoint _point = fs.Location as LocationPoint;
         if (_point != null)
         {
             XYZ  aa    = _point.Point;
             XYZ  cc    = _point.Point + new XYZ(0, 0, 1);
             Line _axis = Line.CreateBound(aa, cc);
             _point.Rotate(_axis, _angle);
         }
         _rotateTrans.Commit();
     }
 }
コード例 #4
0
 /// <summary>
 /// 旋转族实例
 /// </summary>
 private void RotateFamilyInstances(List <FamilyInstance> parkingplaceInstances, double _angle)
 {
     using (Transaction _rotateTrans = new Transaction(doc))
     {
         _rotateTrans.Start("_rotateTrans");
         foreach (FamilyInstance fs in parkingplaceInstances)
         {
             LocationPoint _point = fs.Location as LocationPoint;
             if (_point != null)
             {
                 XYZ  aa    = _point.Point;
                 XYZ  cc    = new XYZ(aa.X, aa.Y, aa.Z + 10);
                 Line _axis = Line.CreateBound(aa, cc);
                 _point.Rotate(_axis, _angle);
             }
         }
         _rotateTrans.Commit();
     }
 }
コード例 #5
0
        bool LocationRotate(Element element)
        {
            bool rotated = false;
            // Rotate the element via its location curve.
            LocationPoint location = element.Location as LocationPoint;
            LocationCurve curve    = element.Location as LocationCurve;

            if (null != curve)
            {
                Curve line = curve.Curve;
                XYZ   aa   = line.GetEndPoint(0);
                XYZ   cc   = new XYZ(aa.X, aa.Y, aa.Z + 10);
                Line  axis = Line.CreateBound(aa, cc);
                rotated = curve.Rotate(axis, Math.PI / 2.0);
            }
            else if (null != location)
            {
                XYZ  aa   = location.Point;
                XYZ  cc   = new XYZ(aa.X, aa.Y, aa.Z + 10);
                Line axis = Line.CreateBound(aa, cc);
                rotated = location.Rotate(axis, Math.PI / 2.0);
            }
            return(rotated);
        }
コード例 #6
0
ファイル: MyExternalCommand.cs プロジェクト: wzfxue/Revit
        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);
        }
コード例 #7
0
        /// <summary>
        /// The function set value to rotation of the beams and braces
        /// and rotate columns.
        /// </summary>
        public void RotateElement()
        {
            Transaction transaction = new Transaction(m_revit.ActiveUIDocument.Document, "RotateElement");

            transaction.Start();
            try
            {
                ElementSet selection = new ElementSet();
                foreach (ElementId elementId in m_revit.ActiveUIDocument.Selection.GetElementIds())
                {
                    selection.Insert(m_revit.ActiveUIDocument.Document.GetElement(elementId));
                }
                foreach (Autodesk.Revit.DB.Element e in selection)
                {
                    FamilyInstance familyComponent = e as FamilyInstance;
                    if (familyComponent == null)
                    {
                        //is not a familyInstance
                        continue;
                    }
                    // if be familyInstance,judge the types of familyInstance
                    if (StructuralType.Beam == familyComponent.StructuralType ||
                        StructuralType.Brace == familyComponent.StructuralType)
                    {
                        // selection is a beam or Brace
                        ParameterSetIterator paraIterator = familyComponent.Parameters.ForwardIterator();
                        paraIterator.Reset();

                        while (paraIterator.MoveNext())
                        {
                            object    para            = paraIterator.Current;
                            Parameter objectAttribute = para as Parameter;
                            //set generic property named "Cross-Section Rotation"
                            if (objectAttribute.Definition.Name.Equals(AngleDefinitionName))
                            {
                                Double originDegree = objectAttribute.AsDouble();
                                double rotateDegree = m_receiveRotationTextBox * Math.PI / 180;
                                if (!m_isAbsoluteChecked)
                                {
                                    // absolute rotation
                                    rotateDegree += originDegree;
                                }
                                objectAttribute.Set(rotateDegree);
                                // relative rotation
                            }
                        }
                    }
                    else if (StructuralType.Column == familyComponent.StructuralType)
                    {
                        // rotate a column
                        Autodesk.Revit.DB.Location columnLocation = familyComponent.Location;
                        // get the location object
                        LocationPoint         pointLocation = columnLocation as LocationPoint;
                        Autodesk.Revit.DB.XYZ insertPoint   = pointLocation.Point;
                        // get the location point
                        double temp = pointLocation.Rotation;
                        //existing rotation
                        Autodesk.Revit.DB.XYZ directionPoint = new Autodesk.Revit.DB.XYZ(0, 0, 1);
                        // define the vector of axis
                        Line   rotateAxis   = Line.CreateUnbound(insertPoint, directionPoint);
                        double rotateDegree = m_receiveRotationTextBox * Math.PI / 180;
                        // rotate column by rotate method
                        if (m_isAbsoluteChecked)
                        {
                            rotateDegree -= temp;
                        }
                        bool rotateResult = pointLocation.Rotate(rotateAxis, rotateDegree);
                        if (rotateResult == false)
                        {
                            TaskDialog.Show("Revit", "Rotate Failed.");
                        }
                    }
                }

                transaction.Commit();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Revit", "Rotate failed! " + ex.Message);
                transaction.RollBack();
            }
        }
コード例 #8
0
ファイル: CopyRebar.cs プロジェクト: snoly/EiBreRebarUtils
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application app = commandData.Application.Application;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            bool SourceIsWallFoundation = false;
            Reference ref1 = null;
            IList<Reference> ref2List = new List<Reference>();

            try
            {
                ref1 = uidoc.Selection.PickObject(ObjectType.Element, new RebarHostSelectionFilter(), "Pick a rebar host to copy from");
                ref2List = uidoc.Selection.PickObjects(ObjectType.Element, new RebarHostSelectionFilter(), "Pick a rebar host to copy to");
            }
            catch(Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                TaskDialog.Show("Rebar Copy command cancelled", "Click finish in top left corner to complete the command");
                return Result.Cancelled;
            }

            using (Transaction t1 = new Transaction(doc, "Copy rebar"))
            {
                t1.Start();
                foreach (Reference ref2 in ref2List)
                {
                    Element sourceHost = doc.GetElement(ref1.ElementId);
                    Element targetHost = doc.GetElement(ref2.ElementId);
                    ICollection<ElementId> elementIdToBeDeleted = new List<ElementId>();
                    WallFoundation sourceWallFoundation = null;
                    WallFoundation targetWallFoundation = null;
                    //Workaround for wall foundations: They have no location lines, but are completely dependent on their walls. So by copiing the host wall, both the wall foundation and the rebars follows along
                    if (sourceHost is WallFoundation && targetHost is WallFoundation)
                    {
                        SourceIsWallFoundation = true;
                        sourceWallFoundation = (WallFoundation)sourceHost;
                        sourceHost = doc.GetElement(sourceWallFoundation.WallId);
                        targetWallFoundation = (WallFoundation)targetHost;
                        targetHost = doc.GetElement(targetWallFoundation.WallId);
                    }
                    //STEP 1: Copy element to random location
                    //5000 is a random chosen number, surprisingly it matters if its copied in Y or Z direction:
                    ICollection<ElementId> copiedElements = ElementTransformUtils.CopyElement(doc, sourceHost.Id, new XYZ(0, 5000, 0));
                    Element copiedElement = doc.GetElement(copiedElements.FirstOrDefault());
                    elementIdToBeDeleted.Add(copiedElement.Id);

                    //STEP 2: Relocate copy to match the target 
                    if (copiedElement.Location is LocationCurve && targetHost.Location is LocationCurve)
                    {
                        LocationCurve locationTo = targetHost.Location as LocationCurve;
                        LocationCurve locationCopied = copiedElement.Location as LocationCurve;
                        locationCopied.Curve = locationTo.Curve;
                    }
                    else if (copiedElement.Location is LocationPoint && targetHost.Location is LocationPoint)
                    {
                        LocationPoint locationTo = targetHost.Location as LocationPoint;
                        LocationPoint locationCopied = copiedElement.Location as LocationPoint;
                        locationCopied.Point = locationTo.Point;
                        if (locationCopied.Rotation != locationTo.Rotation)
                        {
                            Transform trans1 = Transform.CreateTranslation(new XYZ(0, 0, 1));
                            XYZ origin1 = locationTo.Point;
                            XYZ endAxis = trans1.OfPoint(origin1);
                            Line axis1 = Line.CreateBound(origin1, endAxis);
                            locationCopied.Rotate(axis1, locationTo.Rotation);
                        }
                    }
                    else
                    {
                        TaskDialog.Show("Warning", "Pick two Rebar Hosts with the same location type. Only elements with locatoion lines and location points are supported. Elements such as beams, walls and slanted columns do typically have location lines. Floors and slabs are not supported.");
                        t1.RollBack();
                        return Result.Cancelled;
                    }


                    //STEP 3: Change the type of the copied element to match the target element
                    //TODO: Change types for wall foundations and change heights/offsets for walls
                    try
                    {
                        if (targetHost.GetTypeId() != copiedElement.GetTypeId())
                        {
                            copiedElement.ChangeTypeId(targetHost.GetTypeId());
                        }

                        if (targetHost is Wall && sourceHost is Wall)
                        {
                            copiedElement.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).Set(targetHost.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble());
                            copiedElement.get_Parameter(BuiltInParameter.WALL_TOP_OFFSET).Set(targetHost.get_Parameter(BuiltInParameter.WALL_TOP_OFFSET).AsDouble());
                        }

                        if (IsNotSlantedColumn(targetHost) && IsNotSlantedColumn(sourceHost))
                        {
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId());
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble());
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId());
                            copiedElement.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).Set(targetHost.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble());
                        } 
                    }
                    catch { }

                    doc.Regenerate();

                    //Step 3: Change rebar host from copied element to target element
                    IList<Rebar> copiedRebars = new List<Rebar>();

                    if (SourceIsWallFoundation)
                    {
                        //Need to find the foundation that was created by copying the wall
                        WallFoundation wallFoundation = new FilteredElementCollector(doc)
                            .OfClass(typeof(WallFoundation))
                            .WhereElementIsNotElementType().Cast<WallFoundation>()
                            .FirstOrDefault(q => q.WallId == copiedElement.Id);
                        elementIdToBeDeleted.Add(wallFoundation.Id);
                        copiedRebars = RebarHostData.GetRebarHostData(wallFoundation).GetRebarsInHost();
                        if (targetWallFoundation != null)
                        {
                            foreach (Rebar r in copiedRebars)
                            {
                                r.SetHostId(doc, targetWallFoundation.Id);
                            }
                        }

                    }
                    else
                    {
                        copiedRebars = RebarHostData.GetRebarHostData(copiedElement).GetRebarsInHost();
                        foreach (Rebar r in copiedRebars)
                        {
                            r.SetHostId(doc, targetHost.Id);
                        }
                    }

                    //Step 4: Delete the copied element
                    doc.Delete(elementIdToBeDeleted);

                }

                t1.Commit();
            }
            return Result.Succeeded;
        }
        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();

                ///通过LocationCurve或LocationPoint旋转元素

                //点选指定执行的元素, 本次按只能选择柱考虑
                Reference pickedEleReference = sel.PickObject(ObjectType.Element, "选择个墙或柱吧");
                //通过引用取到选中的元素
                Element element = doc.GetElement(pickedEleReference);

                string info = "提示如下:";
                info += "\n\t" + "1 族类别ELEM_CATEGORY_PARAM_MT" +
                        element.get_Parameter(BuiltInParameter.ELEM_CATEGORY_PARAM_MT).AsValueString();
                info += "\n\t" + "2 族类别ELEM_CATEGORY_PARAM" +
                        element.get_Parameter(BuiltInParameter.ELEM_CATEGORY_PARAM).AsValueString();
                TaskDialog.Show("提示", info);

                XYZ point1 = XYZ.Zero;
                XYZ point2 = XYZ.Zero;

                //当选择的对象是墙时:通过元素的位置来旋转元素
                if (element.get_Parameter(BuiltInParameter.ELEM_CATEGORY_PARAM_MT).AsValueString() == "墙")
                {
                    Wall          wall  = doc.GetElement(pickedEleReference) as Wall;
                    LocationCurve curve = wall.Location as LocationCurve;

                    Curve line = curve.Curve;
                    point1 = line.GetEndPoint(0);
                    point2 = new XYZ(point1.X, point1.Y, point1.Z + 10);

                    Line axis = Line.CreateBound(point1, point2);
                    curve.Rotate(axis, Math.PI / (180 / 30));
                }

                //当选择的对象是柱时:通过元素的位置点来旋转元素
                else if (element.get_Parameter(BuiltInParameter.ELEM_CATEGORY_PARAM_MT).AsValueString() == "柱")
                {
                    LocationPoint point = element.Location as LocationPoint;
                    if (null != point)
                    {
                        point1 = point.Point;
                        point2 = new XYZ(point1.X, point1.Y, point1.Z + 10);
                        Line axis = Line.CreateBound(point1, point2);
                        point.Rotate(axis, Math.PI / (180 / 30));
                    }
                }

                //当选择的对象是不是墙也不是柱时, 提示干不了.
                else
                {
                    TaskDialog.Show("提示", "哥,既不是墙,也不是柱,我没法弄啊");
                }


                ts.Commit();
            }

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

            return(Result.Succeeded);
        }
コード例 #10
0
        /// <summary>
        /// Init element by location
        /// </summary>
        /// <param name="view"></param>
        /// <param name="origin"></param>
        /// <param name="alignment"></param>
        /// <param name="text"></param>
        /// <param name="keepRotatedTextreadable"></param>
        /// <param name="rotation">in degrees</param>
        /// <param name="typeId"></param>
        private void Init(RVT.View view, RVT.XYZ origin, RVT.HorizontalTextAlignment alignment, string text, bool keepRotatedTextreadable, double rotation, ElementId typeId)
        {
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            TransactionManager.Instance.EnsureInTransaction(document);
            var element = ElementBinder.GetElementFromTrace <RVT.TextNote>(document);

            RVT.TextNoteOptions options = new TextNoteOptions()
            {
                HorizontalAlignment     = alignment,
                KeepRotatedTextReadable = keepRotatedTextreadable,
                Rotation = rotation.ToRadians(),
                TypeId   = typeId
            };

            if (element == null)
            {
                element = RVT.TextNote.Create(document, view.Id, origin, text, options);
            }
            else
            {
                if (element.HorizontalAlignment != alignment)
                {
                    element.HorizontalAlignment = alignment;
                }

                if (element.KeepRotatedTextReadable != keepRotatedTextreadable)
                {
                    element.KeepRotatedTextReadable = keepRotatedTextreadable;
                }

                if (element.Text != text)
                {
                    element.Text = text;
                }

                // if the element location is null, try to use the Coord property
                // Coord holds a point only without rotation.
                if (element.Location == null)
                {
                    if (!element.Coord.IsAlmostEqualTo(origin))
                    {
                        element.Coord = origin;
                    }
                }
                else
                {
                    // If a location point is set we can use this and extract
                    // its location and rotation
                    if (element.Location is LocationPoint)
                    {
                        LocationPoint point = (LocationPoint)element.Location;

                        if (!point.Point.IsAlmostEqualTo(origin))
                        {
                            point.Point = origin;
                        }

                        if (Math.Abs(point.Rotation - rotation.ToRadians()) <= System.Double.Epsilon)
                        {
                            point.Rotate(Line.CreateUnbound(XYZ.Zero, XYZ.BasisZ), rotation.ToRadians());
                        }
                    }
                }
            }

            RVT.TextNoteType type = (RVT.TextNoteType)document.GetElement(typeId);
            InternalSetType(text, type, origin, alignment, rotation);
            InternalSetElement(element);

            TransactionManager.Instance.TransactionTaskDone();
            ElementBinder.SetElementForTrace(this.InternalElement);
        }
コード例 #11
0
        /// <summary>
        /// Rotate Multiple Elements its own axis
        /// </summary>
        /// <param name="doc">Active Revit Document</param>
        /// <param name="ids">Collection of selected element IDs</param>
        /// <param name="angleX">Rotation angle of X axis</param>
        /// <param name="angleY">Rotation angle of Y axis</param>
        /// <param name="angleZ">Rotation angle of Z axis</param>
        public void RotateMethod(Document doc, ICollection <ElementId> ids, double angleX, double angleY, double angleZ)
        {
            if (ids != null)
            {
                foreach (var id in ids)
                {
                    Element  el  = doc.GetElement(id);
                    Location loc = el.Location;

                    if ((el.Location as LocationCurve) != null)
                    {
                        LocationCurve locationCurve = loc as LocationCurve;
                        XYZ           midPoint      = (locationCurve.Curve.GetEndPoint(0) + locationCurve.Curve.GetEndPoint(1)) / 2;

                        XYZ directionX = midPoint.Add(XYZ.BasisX);
                        XYZ directionY = midPoint.Add(XYZ.BasisY);
                        XYZ directionZ = midPoint.Add(XYZ.BasisZ);

                        Line axisX = Line.CreateBound(midPoint, directionX);
                        Line axisY = Line.CreateBound(midPoint, directionY);
                        Line axisZ = Line.CreateBound(midPoint, directionZ);

                        if (locationCurve != null && angleX > 0)
                        {
                            locationCurve.Rotate(axisX, DegreeToRadian(angleX));
                        }

                        if (locationCurve != null && angleY > 0)
                        {
                            locationCurve.Rotate(axisY, DegreeToRadian(angleY));
                        }

                        if (locationCurve != null && angleZ > 0)
                        {
                            locationCurve.Rotate(axisZ, DegreeToRadian(angleZ));
                        }
                    }

                    if (el.Location as LocationPoint != null)
                    {
                        LocationPoint locationPoint = el.Location as LocationPoint;

                        XYZ m_directionX = (locationPoint.Point.Add(XYZ.BasisX));
                        XYZ m_directionY = (locationPoint.Point.Add(XYZ.BasisY));
                        XYZ m_directionZ = (locationPoint.Point.Add(XYZ.BasisZ));

                        Line m_axisX = Line.CreateBound(locationPoint.Point, m_directionX);
                        Line m_axisY = Line.CreateBound(locationPoint.Point, m_directionY);
                        Line m_axisZ = Line.CreateBound(locationPoint.Point, m_directionZ);

                        if (locationPoint != null && angleX > 0)
                        {
                            locationPoint.Rotate(m_axisX, DegreeToRadian(angleX));
                        }

                        if (locationPoint != null && angleY > 0)
                        {
                            locationPoint.Rotate(m_axisY, DegreeToRadian(angleY));
                        }

                        if (locationPoint != null && angleZ > 0)
                        {
                            locationPoint.Rotate(m_axisZ, DegreeToRadian(angleZ));
                        }
                    }
                }
            }
            else
            {
                TaskDialog.Show("ELEMENT SELECTION", "PLEASE SELECT AT LEAST 1 ELEMENT");
            }
        }
コード例 #12
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument               uidoc      = commandData.Application.ActiveUIDocument;
            Document                 doc        = uidoc.Document;
            Level                    level      = doc.ActiveView.GenLevel;
            View                     view       = doc.ActiveView;
            FamilySymbol             symbol     = doc.GetElement(new ElementId(587194)) as FamilySymbol;
            ElementClassFilter       dimfilter  = new ElementClassFilter(typeof(Dimension));
            ElementOwnerViewFilter   viewfilter = new ElementOwnerViewFilter(view.Id);
            FilteredElementCollector collector  = new FilteredElementCollector(doc);

            collector.WherePasses(dimfilter).WherePasses(viewfilter);
            List <Dimension>             add           = new List <Dimension>();
            List <Dimension>             add2          = new List <Dimension>();
            List <DimensionSegmentArray> dimarrayarray = new List <DimensionSegmentArray>();
            ReferenceArray referarray  = new ReferenceArray();
            ReferenceArray referarray2 = new ReferenceArray();

            foreach (Element e in collector)
            {
                Dimension dim = e as Dimension;
                if (dim.NumberOfSegments > 1)
                {
                    dimarrayarray.Add(dim.Segments);
                    add2.Add(dim);
                }
                else
                {
                    add.Add(dim);
                }
            }
            if (add2.Count != 0)            //连续尺寸标注
            {
                using (Transaction trans = new Transaction(doc))
                {
                    FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();

                    FailureHandler failureHandler = new FailureHandler();

                    failureHandlingOptions.SetFailuresPreprocessor(failureHandler);

                    // 这句话是关键

                    failureHandlingOptions.SetClearAfterRollback(true);

                    trans.SetFailureHandlingOptions(failureHandlingOptions);


                    trans.Start("Start");
                    ChangeDimensionTypeStyle(add2.First <Dimension>(), doc);
                    for (int b = 0; b < add2.Count; b++)
                    {
                        referarray2 = add2.ElementAt <Dimension>(b).References;
                        foreach (Reference refer in referarray2)
                        {
                            //string re = refer.ElementReferenceType.ToString();
                            var       cu  = add2.ElementAt <Dimension>(b).Curve;
                            Dimension dim = add2.ElementAt <Dimension>(b);
                            Line      li  = cu as Line;
                            //var n = re.GetType().ToString();
                            Element el    = doc.GetElement(refer);
                            Curve   curve = null;
                            if (el.Location.GetType() != typeof(LocationCurve))
                            {
                                if (el.GetType() == typeof(Grid))
                                {
                                    curve = (el as Grid).Curve;
                                }
                                else if ((el as FamilyInstance) is FamilyInstance)
                                {
                                    FamilyInstance instance2   = el as FamilyInstance;
                                    Element        hostelement = instance2.Host;
                                    curve = GetLineFromLcPoint(GetSolid(hostelement), instance2);
                                }
                                else if (el.GetType() == typeof(Floor))
                                {
                                    Floor floor = el as Floor;
                                    Face  face  = GetGeometryFace(GetSolid(el));
                                    var   test2 = GetCurveFromFloor(face, add2[b].Curve);
                                    if (test2.Size < 2)
                                    {
                                        break;
                                    }
                                    XYZ[] xYZsn = { test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0) };
                                    Line  l3    = Line.CreateBound(test2.get_Item(0).GetEndPoint(0),
                                                                   test2.get_Item(1).GetEndPoint(0));
                                    curve = l3 as Curve;
                                }
                            }
                            else
                            {
                                curve = (el.Location as LocationCurve).Curve;
                            }

                            if (curve == null)
                            {
                                break;
                            }
                            XYZ p0 = li.Project(curve.GetEndPoint(1))
                                     .XYZPoint;
                            if (!symbol.IsActive)
                            {
                                symbol.Activate();
                            }

                            FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level,
                                                                                   Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming);
                            var    l  = GetGeometryLine(GetGeometryFace(GetSolid(instance)));
                            double an = GetAngle(li, l);
                            double rotateangle;
                            double e = 1e-12;
                            double a = Math.Round((an - Math.PI / 4), 13);
                            double c = Math.Round(Math.Abs((an - Math.PI * 3 / 2)), 13);
                            if (a != e || c != Math.Round(Math.PI * 3 / 2, 13)) //判断度数,相减做判断
                            {
                                if (an > Math.PI * 0.5)
                                {
                                    rotateangle = 0.75 * Math.PI - an;
                                }
                                else
                                {
                                    rotateangle = an + 0.25 * Math.PI;
                                }
                                LocationPoint lp = instance.Location as LocationPoint;
                                if (lp != null)
                                {
                                    Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20));
                                    lp.Rotate(line3, rotateangle);
                                    XYZ pNew = (instance.Location as LocationPoint).Point;
                                    if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z)
                                    {
                                        lp.Point = p0;
                                    }
                                    //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置
                                }
                            }
                        }
                    }
                    trans.Commit();
                }
            }                                                    //逐点标注
            if (add.Count != 0)                                  //普通尺寸标注
            {
                using (Transaction trans = new Transaction(doc)) //将本身的Dimension样式修改未无对角线样式
                {
                    FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();

                    FailureHandler failureHandler = new FailureHandler();

                    failureHandlingOptions.SetFailuresPreprocessor(failureHandler);

                    // 这句话是关键

                    failureHandlingOptions.SetClearAfterRollback(true);

                    trans.SetFailureHandlingOptions(failureHandlingOptions);


                    trans.Start("Text");
                    ChangeDimensionTypeStyle(add.First <Dimension>(), doc);
                    trans.Commit();
                }
                for (int a = 0; a < add.Count; a++)
                {
                    referarray = add.ElementAt <Dimension>(a).References;
                    if (referarray.Size == 2)
                    {
                        foreach (Reference re in referarray)
                        {
                            var       cu  = add.ElementAt <Dimension>(a).Curve;
                            Dimension dim = add.ElementAt <Dimension>(a);
                            Line      li  = cu as Line;
                            //var n = re.GetType().ToString();
                            Element el    = doc.GetElement(re);
                            Curve   curve = null;
                            using (Transaction test = new Transaction(doc, "change"))
                            {
                                FailureHandlingOptions failureHandlingOptions = test.GetFailureHandlingOptions();

                                FailureHandler failureHandler = new FailureHandler();

                                failureHandlingOptions.SetFailuresPreprocessor(failureHandler);

                                // 这句话是关键

                                failureHandlingOptions.SetClearAfterRollback(true);

                                test.SetFailureHandlingOptions(failureHandlingOptions);
                                test.Start();
                                if (el.Location.GetType() != typeof(LocationCurve))
                                {
                                    if (el.GetType() == typeof(Grid))
                                    {
                                        curve = (el as Grid).Curve;
                                    }
                                    else if ((el as FamilyInstance) is FamilyInstance)
                                    {
                                        FamilyInstance instance2   = el as FamilyInstance;
                                        Element        hostelement = instance2.Host;
                                        curve = GetLineFromLcPoint(GetSolid(hostelement), instance2);
                                    }
                                    else if (el.GetType() == typeof(Floor))
                                    {
                                        Floor floor = el as Floor;
                                        Face  face  = GetGeometryFace(GetSolid(el));
                                        var   test2 = GetCurveFromFloor(face, add[a].Curve);
                                        if (test2.Size < 2)
                                        {
                                            break;
                                        }
                                        XYZ[] xYZsn = { test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0) };
                                        Line  l     = Line.CreateBound(test2.get_Item(0).GetEndPoint(0),
                                                                       test2.get_Item(1).GetEndPoint(0));
                                        curve = l as Curve;
                                    }

                                    if (curve == null)
                                    {
                                        break;
                                    }
                                    XYZ[] xYZs = { curve.GetEndPoint(0), curve.GetEndPoint(1) };
                                    foreach (XYZ xyz in xYZs)
                                    {
                                        XYZ p0 = li.Project(xyz).XYZPoint;
                                        if (!symbol.IsActive)
                                        {
                                            symbol.Activate();
                                        }

                                        FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level,
                                                                                               Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming);
                                        var    l  = GetGeometryLine(GetGeometryFace(GetSolid(instance)));
                                        double an = GetAngle(li, l);
                                        if (an != Math.PI / 4 || an != Math.PI * 3 / 2)
                                        {
                                            LocationPoint lp = instance.Location as LocationPoint;
                                            if (lp != null)
                                            {
                                                Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20));
                                                lp.Rotate(line3, 0.25 * Math.PI + (Math.PI + an));
                                                XYZ pNew = (instance.Location as LocationPoint).Point;
                                                if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z)
                                                {
                                                    lp.Point = p0;
                                                }
                                                //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    curve = (el.Location as LocationCurve).Curve;
                                    if (doc.GetElement(referarray.get_Item(0)).Id ==
                                        doc.GetElement(referarray.get_Item(1)).Id)
                                    {
                                        var       cu4  = add.ElementAt <Dimension>(a).Curve;
                                        Dimension dim4 = add.ElementAt <Dimension>(a);
                                        Line      li4  = cu as Line;
                                        //var n = re.GetType().ToString();
                                        Element el4    = doc.GetElement(referarray.get_Item(0));
                                        Curve   curve4 = (el4.Location as LocationCurve).Curve;
                                        XYZ[]   xyzs2  = { curve4.GetEndPoint(0), curve4.GetEndPoint(1) };
                                        foreach (XYZ xyz in xyzs2)
                                        {
                                            XYZ p0 = li.Project(xyz).XYZPoint;
                                            if (!symbol.IsActive)
                                            {
                                                symbol.Activate();
                                            }

                                            FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level,
                                                                                                   Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming);
                                            var    l  = GetGeometryLine(GetGeometryFace(GetSolid(instance)));
                                            double an = GetAngle(li, l);
                                            if (an != Math.PI / 4 || an != Math.PI * 3 / 2)
                                            {
                                                LocationPoint lp = instance.Location as LocationPoint;
                                                if (lp != null)
                                                {
                                                    Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20));
                                                    lp.Rotate(line3, 0.25 * Math.PI + (Math.PI + an));
                                                    XYZ pNew = (instance.Location as LocationPoint).Point;
                                                    if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z)
                                                    {
                                                        lp.Point = p0;
                                                    }
                                                    //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        foreach (Reference refer in referarray)
                                        {
                                            //string re = refer.ElementReferenceType.ToString();
                                            var       cu3  = add.ElementAt <Dimension>(a).Curve;
                                            Dimension dim3 = add.ElementAt <Dimension>(a);
                                            Line      li3  = cu as Line;
                                            //var n = re.GetType().ToString();
                                            Element el3    = doc.GetElement(refer);
                                            Curve   curve3 = null;
                                            if (el3.Location.GetType() != typeof(LocationCurve))
                                            {
                                                if (el3.GetType() == typeof(Grid))
                                                {
                                                    curve3 = (el3 as Grid).Curve;
                                                }
                                                else if ((el3 as FamilyInstance) is FamilyInstance)
                                                {
                                                    FamilyInstance instance3   = el3 as FamilyInstance;
                                                    Element        hostelement = instance3.Host;
                                                    curve3 = GetLineFromLcPoint(GetSolid(hostelement), instance3);
                                                }
                                                else if (el3.GetType() == typeof(Floor))
                                                {
                                                    Floor floor = el3 as Floor;
                                                    Face  face  = GetGeometryFace(GetSolid(el3));
                                                    var   test2 = GetCurveFromFloor(face, add2[a].Curve);
                                                    if (test2.Size < 2)
                                                    {
                                                        break;
                                                    }
                                                    XYZ[] xYZsn = { test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0) };
                                                    Line  l4    = Line.CreateBound(test2.get_Item(0).GetEndPoint(0),
                                                                                   test2.get_Item(1).GetEndPoint(0));
                                                    curve3 = l4 as Curve;
                                                }
                                            }
                                            else
                                            {
                                                curve3 = (el3.Location as LocationCurve).Curve;
                                            }

                                            if (curve3 == null)
                                            {
                                                break;
                                            }
                                            XYZ p0 = li3.Project(curve.GetEndPoint(1))
                                                     .XYZPoint;
                                            if (!symbol.IsActive)
                                            {
                                                symbol.Activate();
                                            }

                                            FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level,
                                                                                                   Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming);
                                            var    l  = GetGeometryLine(GetGeometryFace(GetSolid(instance)));
                                            double an = GetAngle(li, l);
                                            if (an != Math.PI / 4 || an != Math.PI * 3 / 2)
                                            {
                                                LocationPoint lp = instance.Location as LocationPoint;
                                                if (lp != null)
                                                {
                                                    Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20));
                                                    lp.Rotate(line3, 0.25 * Math.PI + (Math.PI + an));
                                                    XYZ pNew = (instance.Location as LocationPoint).Point;
                                                    if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z)
                                                    {
                                                        lp.Point = p0;
                                                    }
                                                    //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置
                                                }
                                            }
                                        }
                                    }
                                }

                                test.Commit();
                            }
                        }
                    }
                }
            }         //连续标注
            return(Result.Succeeded);
        }
コード例 #13
0
        /**
         *
         * Genetic Algorithm with Revit API
         *
         * This sample is using GeneticSharp Library (github.com/giacomelli/GeneticSharp)
         * The MIT License (MIT)
         * Copyright (c) 2013 Diego Giacomelli
         */
        public void GridObjectPlacement(DesignAutomationData data)
        {
            m_doc = data.RevitDoc;
            m_app = data.RevitApp;

            InputData inputParameters = JsonConvert.DeserializeObject <InputData>(File.ReadAllText("params.json"));

            // Family Symbol
            Document familyProjectDoc = m_app.OpenDocumentFile("family.rvt");

            string    tempFamilyName      = Path.GetFileNameWithoutExtension(inputParameters.FamilyFileName) + ".rfa";
            ModelPath tempFamilyModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(tempFamilyName);

            FamilySymbol tempFamilySymbol = null;

            FilteredElementCollector familyInstanceCollector
                = new FilteredElementCollector(familyProjectDoc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_Furniture)
                  .OfClass(typeof(FamilyInstance));

            foreach (Element familyInstanceElem in familyInstanceCollector)
            {
                FamilyInstance fi = familyInstanceElem as FamilyInstance;

                Element superComponent = fi.SuperComponent;

                if (superComponent == null)
                {
                    tempFamilySymbol = fi.Symbol;

                    Family family = tempFamilySymbol.Family;

                    Document familyDoc = familyProjectDoc.EditFamily(family);

                    Family loadedFamily = familyDoc.LoadFamily(m_doc);

                    ISet <ElementId> familySymbolIds = loadedFamily.GetFamilySymbolIds();

                    foreach (ElementId familySymbolId in familySymbolIds)
                    {
                        FamilySymbol familySymbol = m_doc.GetElement(familySymbolId) as FamilySymbol;

                        m_familySymbol = familySymbol;
                    }

                    break;
                }
            }

            if (!m_familySymbol.IsActive)
            {
                using (Transaction tx = new Transaction(m_doc))
                {
                    tx.Start("Transaction Activate Family Symbol");
                    m_familySymbol.Activate();
                    tx.Commit();
                }
            }

            // Room
            m_room = m_doc.GetElement(inputParameters.RoomUniqueId) as Room;

            // Level
            m_level = m_doc.GetElement(m_room.LevelId) as Level;

            // View
            ElementId viewId = m_level.FindAssociatedPlanViewId();

            if (viewId != null)
            {
                m_view = m_doc.GetElement(viewId) as View;
            }

            // Selected Placement Method
            m_selectedPlacementMethod = int.Parse(inputParameters.GridTypeId);

            // Construct Chromosomes with 3 params, m_objectDistanceX, m_objectDistanceY, m_selectedPlacementMethod
            var chromosome = new FloatingPointChromosome(
                new double[] { double.Parse(inputParameters.DistanceXMinParam), double.Parse(inputParameters.DistanceYMinParam), double.Parse(inputParameters.DistanceWallMinParam) },
                new double[] { double.Parse(inputParameters.DistanceXMaxParam), double.Parse(inputParameters.DistanceYMaxParam), double.Parse(inputParameters.DistanceWallMaxParam) },
                new int[] { 32, 32, 32 },
                new int[] { 2, 2, 2 });

            // Population Settings
            //
            // The population size needs to be 'large enough'.
            // The question of when a population is large enough is difficult to answer.
            // Generally, it depends on the project, the number of genes, and the gene value range.
            // A good rule of thumb is to set the population size to at least 3x the number of inputs.
            // If the results don't start to converge to an answer, you may need to increase the population size.
            //
            // by www.generativedesign.org/02-deeper-dive/02-04_genetic-algorithms/02-04-02_initialization-phase
            var population = new Population(8, 12, chromosome);

            // Fitness Function Settings
            //
            // Call CreateObjectPlacementPointList() and get count of points.
            // This sample maximize a number of objects to place in a room.
            //
            // A fitness function is used to evaluate how close (or far off) a given design solution is from meeting the designer�fs goals.
            //
            // by www.generativedesign.org/02-deeper-dive/02-04_genetic-algorithms/02-04-03_evaluation-phase
            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();

                m_objectDistanceX = values[0];
                m_objectDistanceY = values[1];
                m_minimumDistanceFromObjectToWall = values[2];

                List <XYZ> objectPlacementPointList = CreateObjectPlacementPointList();

                return(objectPlacementPointList.Count);
            });

            var selection = new EliteSelection();
            var crossover = new UniformCrossover(0.5f);
            var mutation  = new FlipBitMutation();

            // Termination Condition Settings
            //
            // To finish the process in half an hour, this sample sets 2 conditions.
            var termination = new OrTermination(
                new GenerationNumberTermination(20),
                new TimeEvolvingTermination(TimeSpan.FromMinutes(10)));

            // Construct GeneticAlgorithm
            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;

            Console.WriteLine("Generation: objectDistanceX, objectDistanceY, minimumDistanceFromObjectToWall = objectCount");

            var latestFitness = 0.0;

            // Callback Function of Generation Result
            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.ToFloatingPoints();

                    m_objectDistanceX = phenotype[0];
                    m_objectDistanceY = phenotype[1];
                    m_minimumDistanceFromObjectToWall = phenotype[2];

                    Console.WriteLine(
                        "Generation {0,2}: objectDistanceX: {1}, objectDistanceY: {2}, minimumDistanceFromObjectToWall: {3} = objectCount: {4}",
                        ga.GenerationsNumber,
                        m_objectDistanceX,
                        m_objectDistanceY,
                        m_minimumDistanceFromObjectToWall,
                        bestFitness
                        );

                    List <XYZ> objectPlacementPointList = CreateObjectPlacementPointList();

                    using (Transaction tx = new Transaction(m_doc))
                    {
                        tx.Start("Transaction Create Family Instance");

                        m_view.SetCategoryHidden(new ElementId(BuiltInCategory.OST_Furniture), false);

                        foreach (XYZ point in objectPlacementPointList)
                        {
                            FamilyInstance fi = m_doc.Create.NewFamilyInstance(point, m_familySymbol, m_level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                            m_doc.Regenerate();

                            BoundingBoxXYZ fiBB = fi.get_BoundingBox(m_view);

                            double xDiff = fiBB.Max.X - fiBB.Min.X;
                            double yDiff = fiBB.Max.Y - fiBB.Min.Y;

                            if (m_objectDistanceX / m_objectDistanceY >= 1.2 && yDiff / xDiff >= 1.2)
                            {
                                LocationPoint location = fi.Location as LocationPoint;

                                if (null != location)
                                {
                                    XYZ fiLocationPoint = location.Point;

                                    XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                                    Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                                    location.Rotate(axis, Math.PI / 2.0);
                                }
                            }
                            else if (m_objectDistanceY / m_objectDistanceX >= 1.2 && xDiff / yDiff >= 1.2)
                            {
                                LocationPoint location = fi.Location as LocationPoint;

                                if (null != location)
                                {
                                    XYZ fiLocationPoint = location.Point;

                                    XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                                    Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                                    location.Rotate(axis, Math.PI / 2.0);
                                }
                            }
                        }

                        DWGExportOptions dwgOptions = new DWGExportOptions();

                        ICollection <ElementId> views = new List <ElementId>();
                        views.Add(m_view.Id);

                        m_doc.Export(Directory.GetCurrentDirectory() + "\\exportedDwgs", m_level.Name + "_" + m_room.Name + "_Gen " + ga.GenerationsNumber + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"), views, dwgOptions);

                        tx.RollBack();
                    }
                }
            };

            ga.Start();
        }
コード例 #14
0
        public List <XYZ> RemoveObjectIntersectionPoints(List <XYZ> pointsInsideRoom, List <Outline> doorsOutlineList, List <Outline> coulumnsOutlineList, List <Outline> wallsOutlineList)
        {
            List <XYZ> objectPlacementPointList = new List <XYZ>();

            using (Transaction tx = new Transaction(m_doc))
            {
                tx.Start("Transaction Temp Create Family Instance");

                foreach (XYZ centerPoint in pointsInsideRoom)
                {
                    FamilyInstance fi = m_doc.Create.NewFamilyInstance(centerPoint, m_familySymbol, m_level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                    m_doc.Regenerate();

                    BoundingBoxXYZ fiBB = fi.get_BoundingBox(m_view);

                    double xDiff = fiBB.Max.X - fiBB.Min.X;
                    double yDiff = fiBB.Max.Y - fiBB.Min.Y;

                    if (m_objectDistanceX / m_objectDistanceY >= 1.2 && yDiff / xDiff >= 1.2)
                    {
                        LocationPoint location = fi.Location as LocationPoint;

                        if (null != location)
                        {
                            XYZ fiLocationPoint = location.Point;

                            XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                            Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                            location.Rotate(axis, Math.PI / 2.0);
                        }
                    }
                    else if (m_objectDistanceY / m_objectDistanceX >= 1.2 && xDiff / yDiff >= 1.2)
                    {
                        LocationPoint location = fi.Location as LocationPoint;

                        if (null != location)
                        {
                            XYZ fiLocationPoint = location.Point;

                            XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                            Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                            location.Rotate(axis, Math.PI / 2.0);
                        }
                    }

                    m_doc.Regenerate();

                    BoundingBoxXYZ familyInstanceBB = fi.get_BoundingBox(m_view);

                    Outline familyInstanceOutline = new Outline(familyInstanceBB.Min, familyInstanceBB.Max);

                    List <Outline> obstaclesOutlineList = doorsOutlineList.Concat(coulumnsOutlineList).ToList().Concat(wallsOutlineList).ToList();

                    bool obstaclesIsIntersected = false;

                    // Intersetion check with doors, columns, walls and family instance
                    foreach (Outline obstacleOutline in obstaclesOutlineList)
                    {
                        bool intersectionResult = familyInstanceOutline.Intersects(obstacleOutline, 1);

                        if (intersectionResult)
                        {
                            obstaclesIsIntersected = true;
                        }
                    }

                    if (!obstaclesIsIntersected)
                    {
                        objectPlacementPointList.Add(centerPoint);
                    }
                }

                tx.RollBack();
            }

            return(objectPlacementPointList);
        }