Example #1
0
        public static void RotateDirectShape(DirectShape shape, Room room, out bool perpendicularSwitch)
        {
            perpendicularSwitch = false;
            try
            {
                Line   axis  = null;
                double angle = FindRotationAngle(room, out axis);
                if (angle == 0 || angle == Math.PI)
                {
                    return;
                }

                //longest curve is more close to Y axis
                if (angle > 0.25 * Math.PI && angle < 0.75 * Math.PI)
                {
                    perpendicularSwitch = true;
                }
                if (angle > 1.25 * Math.PI && angle < 1.75 * Math.PI)
                {
                    perpendicularSwitch = true;
                }
                ElementTransformUtils.RotateElement(shape.Document, shape.Id, axis, angle);
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiapp = commandData.Application;
            var uidoc = uiapp.ActiveUIDocument;
            var doc   = uidoc.Document;

            const double scale  = 0.2;
            const double length = 4.0 * Math.PI;
            const int    steps  = 8;

            var profile = CreateProfile(scale);

            var profiles = Enumerable
                           .Range(0, steps + 1)
                           .Select(x => x * length / steps)
                           .Select(CreateSinusTransform)
                           .Select(x => profile.CreateTransformed(x))
                           .ToList();

            using (var transaction = new Transaction(doc, "create loft form with sinus path"))
            {
                transaction.Start();

                var solid = GeometryCreationUtilities.CreateLoftGeometry(profiles,
                                                                         new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId));

                var directShape = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));

                directShape.AppendShape(new GeometryObject[] { solid });

                transaction.Commit();
            }

            return(Result.Succeeded);
        }
Example #3
0
        public static DirectShape CreateRoomDirectShape(Room room)
        {
            DirectShape roomShape = null;

            try
            {
                List <GeometryObject> geoList = new List <GeometryObject>();
                var solidGeometries           = from geoObj in room.ClosedShell
                                                where geoObj.GetType() == typeof(Solid) && (geoObj as Solid).Volume != 0
                                                select geoObj;
                if (solidGeometries.Any())
                {
                    geoList = solidGeometries.ToList();
                }

                ElementId categoryId = new ElementId((int)BuiltInCategory.OST_Mass);
                if (DirectShape.IsValidCategoryId(categoryId, room.Document))
                {
#if RELEASE2015 || RELEASE2016
                    roomShape = DirectShape.CreateElement(room.Document, categoryId, "Measure", room.UniqueId);
#else
                    roomShape = DirectShape.CreateElement(room.Document, categoryId);
#endif
                }
                roomShape.SetShape(geoList);
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
            return(roomShape);
        }
Example #4
0
        /// <summary>
        /// 将楼梯中所有与选择的表面相同方向的面上都生成面层
        /// </summary>
        /// <param name="docTran">  </param>
        /// <param name="elem"> 用来生成面层的单元。此函数会搜索此单元中所有与 baseFace 同法向的面,并进行面层的绘制 </param>
        /// <param name="pickedFace"> 楼梯中用来生成面层的那个面</param>
        /// <param name="faceOp"> 生成面层的选项</param>
        /// <param name="transf"> </param>
        /// <returns></returns>
        private IList <DirectShape> ExtendToFacesWithSameNormal(Transaction docTran, Element elem, PlanarFace pickedFace, FaceOptions faceOp, Transform transf)
        {
            IList <DirectShape> directShapes = new List <DirectShape>();

            // 值中的false 表示solid 是 Family中的solid,后期还要再进行一次transform才能变换 Familyinstance 所对应的位置
            Dictionary <Solid, bool> solids = GeoHelper.GetSolidsInModel(elem, GeoHelper.SolidVolumnConstraint.Positive);

            foreach (Solid solid in solids.Keys)
            {
                foreach (Face face in solid.Faces)
                {
                    if ((face is PlanarFace))
                    {
                        PlanarFace planarFace = (PlanarFace)face;

                        if (GeoHelper.IsSameDirection(planarFace.FaceNormal, transf.OfVector(pickedFace.FaceNormal)))
                        {
                            DirectShape ds = ConstructSurfaceFromPlanarFace(docTran, planarFace, faceOp, Transform.Identity);

                            if (ds != null)
                            {
                                directShapes.Add(ds);
                            }
                        }
                    }
                }
            }

            return(directShapes);
        }
Example #5
0
        /// <summary>
        /// 获取面层对象的标识符。正常情况下,此参数的值应该是一个常数“CMIE_面层”
        /// </summary>
        /// <param name="ds">  </param>
        /// <param name="wallFace"> 如果此函数返回 true,返回面层对象,如果此函数返回False,则此参数返回 null </param>
        /// <returns>如果没有找到此参数,则返回false。</returns>
        public static bool IsWallFace(DirectShape ds, out WallFace wallFace)
        {
            if (ds == null)
            {
                wallFace = null;
                return(false);
            }
            Parameter pa = ds.get_Parameter(FaceWallParameters.sp_FaceIdTag_guid);

            if (pa == null)
            {
                wallFace = null;
                return(false);
            }

            string idTag = pa.AsString();

            if (idTag == null || !pa.AsString().Equals(FaceWallParameters.FaceIdentificaion))
            {
                wallFace = null;
                return(false);
            }
            wallFace = new WallFace(ds);
            return(true);
        }
Example #6
0
        /// <summary>
        /// 生成常规模型,记得开启事务!!!
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="transientSolid"></param>
        /// <param name="isOpenTrans">是否在方法内部开启事务,如果为false,请手动在方法外部开启事务</param>
        /// <param name="dsName"></param>
        /// <returns></returns>
        /// <remarks>生成Solid不需要开启事务,但是DirectShape一定要开启事务</remarks>
        public static ElementId CreateDirectShape(Document doc, Solid transientSolid, bool isOpenTrans = false, String dsName = "")
        {
            ElementId catId = new ElementId(BuiltInCategory.OST_GenericModel);  //常规模型

            Transaction tr = null;

            if (isOpenTrans)
            {
                tr = new Transaction(doc, "DirectShape");
                tr.Start();
                //DirectShape ds = DirectShape.CreateElement(doc, catId);
                //SetShape(ds, transientSolid);
                //if (!String.IsNullOrEmpty(dsName))
                //    ds.Name = dsName;
            }

            // 需要开启事务
            DirectShape ds = DirectShape.CreateElement(doc, catId);

            SetShape(ds, transientSolid);
            if (!String.IsNullOrEmpty(dsName))
            {
                ds.Name = dsName;
            }

            tr?.Commit();
            tr?.Dispose();
            return(ds.Id);
        }
Example #7
0
        /// <summary>
        /// Create a DirectShape, and set its options accordingly.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="categoryId">The category of the DirectShape.</param>
        /// <param name="dataGUID">The GUID of the data creating the DirectShape.</param>
        /// <param name="geomObjs">The list of geometries to add to the DirectShape.</param>
        /// <param name="id">The id of the IFCEntity object creating the DirectShape.</param>
        /// <returns>The DirectShape.</returns>
        static public DirectShape CreateElement(Document doc, ElementId categoryId, string dataGUID, IList <GeometryObject> geomObjs, int id, IFCEntityType entityType)
        {
            string      appGUID     = Importer.ImportAppGUID();
            DirectShape directShape = DirectShape.CreateElement(doc, GetDSValidCategoryId(doc, categoryId, id));

            directShape.ApplicationId     = appGUID;
            directShape.ApplicationDataId = dataGUID;

            // Note: we use the standard options for the DirectShape that is created.  This includes but is not limited to:
            // Referenceable: true.
            // Room Bounding: if applicable, user settable.

            if (IFCImportFile.TheFile.Options.UseStreamlinedOptions)
            {
                // Disable referencing for performance purposes.
                DirectShapeOptions options = directShape.GetOptions();
                options.ReferencingOption = DirectShapeReferencingOption.NotReferenceable;
                directShape.SetOptions(options);
            }

            // This is used in some places to create something not related to an IFCEntity
            if (!Importer.TheProcessor.CreateOrUpdateElement(id, dataGUID, entityType.ToString(),
                                                             categoryId.IntegerValue, geomObjs))
            {
                if (geomObjs != null)
                {
                    directShape?.SetShape(geomObjs);
                }
            }

            return(directShape);
        }
Example #8
0
        public Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            // RhinoCommon code
            var sphere = new Sphere(Point3d.Origin, 12 * Revit.ModelUnits);
            var brep   = sphere.ToBrep();
            var mp     = MeshingParameters.Default;

            mp.MinimumEdgeLength = Revit.VertexTolerance;
            var meshes = Rhino.Geometry.Mesh.CreateFromBrep(brep, mp);

            // Revit code
            var uiApp = data.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            using (var trans = new Transaction(doc))
            {
                if (trans.Start(MethodBase.GetCurrentMethod().DeclaringType.Name) == TransactionStatus.Started)
                {
                    var categoryId = new ElementId(BuiltInCategory.OST_GenericModel);

                    var ds = DirectShape.CreateElement(doc, categoryId);
                    ds.Name = "Sphere";
                    foreach (var geometryList in meshes.ToHost().ToList())
                    {
                        ds.AppendShape(geometryList);
                    }

                    trans.Commit();
                }
            }

            return(Result.Succeeded);
        }
Example #9
0
        public static void CreateSphereDirectShape(Document doc, XYZ center, float radius, string name)
        {
            List <Curve> profile = new List <Curve>();

            // first create sphere with 2' radius
            XYZ profile00    = center;
            XYZ profilePlus  = center + new XYZ(0, radius, 0);
            XYZ profileMinus = center - new XYZ(0, radius, 0);

            profile.Add(Line.CreateBound(profilePlus, profileMinus));
            profile.Add(Arc.Create(profileMinus, profilePlus, center + new XYZ(radius, 0, 0)));

            CurveLoop    curveLoop = CurveLoop.Create(profile);
            SolidOptions options   = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);

            Frame frame  = new Frame(center, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY);
            Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curveLoop }, 0, 2 * Math.PI, options);

            using (Transaction t = new Transaction(doc, "Create sphere direct shape"))
            {
                t.Start();
                DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
                ds.SetShape(new GeometryObject[] { sphere });
                ds.Name = name;
                t.Commit();
            }
        }
Example #10
0
        // Create a DirectShape Sphere
        static public void CreateSphereDirectShape(Document doc)
        {
            List <Curve> profile = new List <Curve>();

            // first create sphere with 2' radius
            XYZ    center = XYZ.Zero;
            double radius = 2.0;
            //XYZ profile00 = center;
            XYZ profilePlus  = center + new XYZ(0, radius, 0);
            XYZ profileMinus = center - new XYZ(0, radius, 0);

            profile.Add(Line.CreateBound(profilePlus, profileMinus));
            profile.Add(Arc.Create(profileMinus, profilePlus, center + new XYZ(radius, 0, 0)));

            CurveLoop    curveLoop = CurveLoop.Create(profile);
            SolidOptions options   = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);

            Frame frame = new Frame(center, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY);

            if (Frame.CanDefineRevitGeometry(frame) == true)
            {
                Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curveLoop }, 0, 2 * Math.PI, options);
                using (Transaction t = new Transaction(doc, "Create sphere direct shape"))
                {
                    t.Start();
                    // create direct shape and assign the sphere shape
                    DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));

                    ds.ApplicationId     = "Application id";
                    ds.ApplicationDataId = "Geometry object id";
                    ds.SetShape(new GeometryObject[] { sphere });
                    t.Commit();
                }
            }
        }
Example #11
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            Solid box    = Box();
            Solid sphere = Sphere();

            Solid unionSolid     = BooleanOperationsUtils.ExecuteBooleanOperation(box, sphere, BooleanOperationsType.Union);
            Solid intersectSolid = BooleanOperationsUtils.ExecuteBooleanOperation(box, sphere, BooleanOperationsType.Intersect);
            Solid diffSolid      = BooleanOperationsUtils.ExecuteBooleanOperation(box, sphere, BooleanOperationsType.Difference);

            //Use DirectShape to visualise geometries
            using (Transaction t = new Transaction(doc, "Transaction"))
            {
                t.Start();
                GeometryObject[] unionGeomObj = new GeometryObject[] { unionSolid };
                GeometryObject[] interGeomObj = new GeometryObject[] { intersectSolid };
                GeometryObject[] diffGeomObj  = new GeometryObject[] { diffSolid };
                DirectShape      ds1          = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
                ds1.SetShape(unionGeomObj);
                DirectShape ds2 = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
                ds2.SetShape(interGeomObj);
                DirectShape ds3 = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
                ds3.SetShape(diffGeomObj);
                t.Commit();
            }

            return(Result.Succeeded);
        }
        public static DirectShape CreateDirectShape(
            Document doc,
            Solid transientSolid,
            string dsName)
        {
            ElementId catId = new ElementId(
                BuiltInCategory.OST_GenericModel);

            AddInId addInId = doc.Application.ActiveAddInId;

            DirectShape ds
                = DirectShape.CreateElement(doc, catId,
                                            addInId.GetGUID().ToString(), "");

            if (ds.IsValidGeometry(transientSolid))
            {
                ds.SetShape(new GeometryObject[] {
                    transientSolid
                });
            }
            else
            {
                TessellatedShapeBuilderResult result
                    = GetTessellatedSolid(doc, transientSolid);

                ds.SetShape(result.GetGeometricalObjects());
            }

            ds.Name = dsName;

            return(ds);
        }
        /// <summary>
        /// creates a DirectShape instance of which shape is Sphere.
        /// Sphere is defined by its center and radius.
        /// </summary>
        /// <param name="document">The Revit document where the instance to be drawn</param>
        /// <param name="name">The name of this instance</param>
        /// <param name="center">Position of the center</param>
        /// <param name="radius">Radius of the circle</param>
        /// <param name="line_color">Outline color of Circle</param>
        /// <param name="surface_transparency">Surface transparency; ranged from 0 (transparent) to 100 (opaque)</param>
        public DirectSphere(Document document, string name, XYZ center, double radius, Color line_color, int surface_transparency) : base(document, name)
        {
            m_shape_type = ShapeTypes.Sphere;
            Center       = center;
            Radius       = radius;

            XYZ top    = center + radius * XYZ.BasisZ;
            XYZ bottom = center - radius * XYZ.BasisZ;
            XYZ right  = center + radius * XYZ.BasisX;

            Frame frame = new Frame(center, XYZ.BasisX, XYZ.BasisY, XYZ.BasisZ);

            List <Curve> profile = new List <Curve>();

            profile.Add(Line.CreateBound(top, bottom));
            profile.Add(Arc.Create(bottom, top, right));

            CurveLoop    curve_loop = CurveLoop.Create(profile);
            SolidOptions options    = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);

            if (Frame.CanDefineRevitGeometry(frame) == true)
            {
                Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curve_loop }, 0, 2 * Math.PI, options);
                using (Transaction t = new Transaction(document, "Create sphere direct shape."))
                {
                    t.Start();
                    DirectShape shape = DirectShape.CreateElement(document, new ElementId(BuiltInCategory.OST_GenericModel));
                    shape.SetShape(new GeometryObject[] { sphere });
                    shape.SetName(name);
                    m_element_id = shape.Id;
                    document.ActiveView.SetElementOverrides(shape.Id, new OverrideGraphicSettings().SetProjectionLineColor(line_color).SetSurfaceTransparency(surface_transparency));
                    t.Commit();
                }
            }
        }
Example #14
0
        /// <summary>
        ///     Creates a new DirectShape.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="parm"></param>
        /// <param name="opt"></param>
        /// <returns></returns>
        public static DirectShape CreateDirectShape(this Document doc, DirectShapeParameter parm, SolidOptions opt = null)
        {
            if (doc is null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (parm is null)
            {
                throw new ArgumentNullException(nameof(parm));
            }

            var solid = CreateExtrusionGeometry(parm.Profile.ToList(), parm.Direction, parm.Distance);

            if (opt != null)
            {
                solid = CreateExtrusionGeometry(parm.Profile.ToList(), parm.Direction, parm.Distance, opt);
            }

            var result = DirectShape.CreateElement(doc, new ElementId(parm.Category));

            result?.AppendShape(new List <GeometryObject> {
                solid
            });

            return(result);
        }
Example #15
0
        /// <summary>
        /// Create a DirectShape, and set its options accordingly.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="categoryId">The category of the DirectShape.</param>
        /// <param name="dataGUID">The GUID of the data creating the DirectShape.</param>
        /// <param name="geomObjs">The list of geometries to add to the DirectShape.</param>
        /// <param name="id">The id of the IFCEntity object creating the DirectShape.</param>
        /// <returns>The DirectShape.</returns>
        static public DirectShape CreateElement(Document doc, ElementId categoryId, string dataGUID, IList <GeometryObject> geomObjs, int id)
        {
            string      appGUID     = Importer.ImportAppGUID();
            DirectShape directShape = DirectShape.CreateElement(doc, GetDSValidCategoryId(doc, categoryId, id));

            directShape.ApplicationId     = appGUID;
            directShape.ApplicationDataId = dataGUID;

            // Note: we use the standard options for the DirectShape that is created.  This includes but is not limited to:
            // Referenceable: true.
            // Room Bounding: if applicable, user settable.

            if (IFCImportFile.TheFile.Options.UseStreamlinedOptions)
            {
                // Disable referencing for performance purposes.
                DirectShapeOptions options = directShape.GetOptions();
                options.ReferencingOption = DirectShapeReferencingOption.NotReferenceable;
                directShape.SetOptions(options);
            }


            if (directShape != null && geomObjs != null)
            {
                directShape.SetShape(geomObjs);
            }

            return(directShape);
        }
        public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            if (!DirectShape.IsSupportedDocument(data.Application.ActiveUIDocument.Document))
            {
                message = "Active document can't support DirectShape functionality.";
                return(Result.Failed);
            }

            using
            (
                var openFileDialog = new OpenFileDialog()
            {
                Filter = "Rhino 3D models (*.3dm)|*.3dm",
                FilterIndex = 1,
                RestoreDirectory = true
            }
            )
            {
                switch (openFileDialog.ShowDialog(ModalForm.OwnerWindow))
                {
                case DialogResult.OK:
                    return(Import3DMFile
                           (
                               openFileDialog.FileName,
                               data.Application.ActiveUIDocument.Document,
                               CommandGrasshopperBake.ActiveBuiltInCategory
                           ));

                case DialogResult.Cancel: return(Result.Cancelled);
                }
            }

            return(Result.Failed);
        }
        public void ByName_NonexistentName()
        {
            var mat  = DocumentManager.Instance.ElementsOfType <Autodesk.Revit.DB.Material>().First();
            var line = Line.ByStartPointEndPoint(Point.Origin(), Point.ByCoordinates(1.0, 2.0, 3.0));

            Assert.Throws(typeof(ArgumentException), () => DirectShape.ByGeometry(line, Category.ByName("OST_GenericModel"), Material.ByName(mat.Name), name: "noshape"));
        }
Example #18
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user canceled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _dbdocument = commandData.Application.ActiveUIDocument.Document;


            try
            {
                using (Autodesk.Revit.DB.Transaction tr = new Autodesk.Revit.DB.Transaction(_dbdocument, "CreateNURBS"))
                {
                    tr.Start();

                    DirectShape myDirectShape = DirectShape.CreateElement(_dbdocument, new ElementId(BuiltInCategory.OST_GenericModel));
                    myDirectShape.ApplicationId     = "TestCreateNURBS";
                    myDirectShape.ApplicationDataId = "NURBS";

                    if (null != myDirectShape)
                    {
                        myDirectShape.SetShape(CreateNurbsSurface());
                    }
                    tr.Commit();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
        public void ByMeshNameCategoryMaterial_ValidInput()
        {
            var p1 = Point.ByCoordinates(0.0, 0.0, 0.0);
            var p2 = Point.ByCoordinates(1.0, 1.0, 0);
            var p3 = Point.ByCoordinates(2.0, 0, 0);

            var index1 = IndexGroup.ByIndices(0, 1, 2);

            var mesh = Mesh.ByPointsFaceIndices(new List <Point>()
            {
                p1, p2, p3
            }, new List <IndexGroup>()
            {
                index1
            });
            var mat = DocumentManager.Instance.ElementsOfType <Autodesk.Revit.DB.Material>().First();

            var ds = DirectShape.ByMesh(mesh, Category.ByName("OST_GenericModel"), Material.ByName(mat.Name), "a mesh");

            Assert.NotNull(ds);
            Assert.AreEqual("a mesh", ds.Name);
            Assert.AreEqual((mesh.Tags.LookupTag(ds.InternalElement.Id.ToString()) as DirectShapeState).materialId, mat.Id.IntegerValue);
            BoundingBoxCentroid(ds).DistanceTo(Point.Origin()).ShouldBeApproximately(0);
            mesh.Dispose();
        }
Example #20
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            Rhino.Geometry.Mesh mesh
        )
        {
            var element = PreviousElement(doc, Iteration);

            try
            {
                if (mesh == null)
                {
                    throw new NullReferenceException($"Parameter '{Params.Input[0].Name}' not set to an instance of a Mesh.");
                }

                if (!mesh.IsValidWithLog(out var log))
                {
                    foreach (var line in log.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, line);
                    }

                    throw new Exception($"Parameter '{Params.Input[0].Name}' not set to a valid Mesh.");
                }

                var scaleFactor = 1.0 / Revit.ModelUnits;
                if (scaleFactor != 1.0)
                {
                    mesh.Scale(scaleFactor);
                }

                var shape = new List <GeometryObject>();

                foreach (var geometry in mesh.ToHost().SelectMany(x => x.ToDirectShapeGeometry()))
                {
                    // DirectShape only accepts those types and no nulls
                    switch (geometry)
                    {
                    case Point p: shape.Add(p); break;

                    case Curve c: shape.Add(c); break;

                    case Solid s: shape.Add(s); break;

                    case Mesh m: shape.Add(m); break;
                    }
                }

                var ds = element as DirectShape ?? CopyParametersFrom(DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)), element);
                ds.SetShape(shape);
                element = ds;

                ReplaceElement(doc, DA, Iteration, element);
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                ReplaceElement(doc, DA, Iteration, null);
            }
        }
Example #21
0
 private bool CreateRoomMass(SpatialElement room)
 {
     if (!SpatialElementGeometryCalculator.CanCalculateGeometry(room))
     {
         return(false);
     }
     try
     {
         SpatialElementGeometryResults results;
         using (var calculator = new SpatialElementGeometryCalculator(doc))
         {
             results = calculator.CalculateSpatialElementGeometry(room);
         }
         using (Solid roomSolid = results.GetGeometry())
         {
             var         eid       = new ElementId(BuiltInCategory.OST_Mass);
             DirectShape roomShape = DirectShape.CreateElement(doc, eid);
             if (roomShape != null && roomSolid.Volume > 0 && roomSolid.Faces.Size > 0)
             {
                 var geomObj = new GeometryObject[] { roomSolid };
                 if (geomObj.Length > 0)
                 {
                     roomShape.SetShape(geomObj);
                     CopyAllRoomParametersToMasses(room, roomShape);
                     return(true);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
     return(false);
 }
Example #22
0
        void ReconstructDirectShapeByCurve
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Curve curve
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            ThrowIfNotValid(nameof(curve), curve);

            if (element is DirectShape ds)
            {
            }
            else
            {
                ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
            }

            var shape = curve.
                        ToHostMultiple(scaleFactor).
                        SelectMany(x => x.ToDirectShapeGeometry());

            ds.SetShape(shape.ToList());

            ReplaceElement(ref element, ds);
        }
Example #23
0
        static void ActiveUIApplication_ViewActivated(object sender, Autodesk.Revit.UI.Events.ViewActivatedEventArgs e)
        {
            var directShapeCategories = Enum.GetValues(typeof(BuiltInCategory)).Cast <BuiltInCategory>().
                                        Where(categoryId => DirectShape.IsValidCategoryId(new ElementId(categoryId), e.CurrentActiveView.Document)).
                                        Select(categoryId => Autodesk.Revit.DB.Category.GetCategory(e.CurrentActiveView.Document, categoryId));

            foreach (var group in directShapeCategories.GroupBy(x => x.CategoryType).OrderBy(x => x.Key.ToString()))
            {
                foreach (var category in group.OrderBy(x => x.Name))
                {
                    var comboBoxMemberData = new ComboBoxMemberData(((BuiltInCategory)category.Id.IntegerValue).ToString(), category.Name)
                    {
                        GroupName = group.Key.ToString()
                    };
                    var item = categoriesComboBox.AddItem(comboBoxMemberData);

                    if ((BuiltInCategory)category.Id.IntegerValue == BuiltInCategory.OST_GenericModel)
                    {
                        categoriesComboBox.Current = item;
                    }
                }
            }

            Revit.ApplicationUI.ViewActivated -= ActiveUIApplication_ViewActivated;
        }
Example #24
0
        /// <summary>
        /// need open transaction.
        /// </summary>
        public static void CreateDirectShape(this Document _doc, IEnumerable <GeometryObject> _geometry, XYZ _translation)
        {
            DirectShape ds = DirectShape.CreateElement(_doc, new ElementId(BuiltInCategory.OST_GenericModel));

            ds.SetShape(_geometry.ToList());
            ElementTransformUtils.MoveElement(ds.Document, ds.Id, _translation);
        }
Example #25
0
        /// <summary>
        /// Creates or populates Revit elements based on the information contained in this class.
        /// </summary>
        /// <param name="doc">The document.</param>
        protected override void Create(Document doc)
        {
            // If we created an element above, then we will set the shape of it to be the same of the shapes of the contained spaces.
            IList <GeometryObject> geomObjs = new List <GeometryObject>();

            foreach (IFCObjectDefinition objDef in RelatedObjects)
            {
                if (!(objDef is IFCSpace))
                {
                    continue;
                }

                // This lets us create a copy of the space geometry with the Zone graphics style.
                IList <IFCSolidInfo> solids = IFCElement.CloneElementGeometry(doc, objDef as IFCProduct, this, false);
                if (solids != null)
                {
                    foreach (IFCSolidInfo solidGeom in solids)
                    {
                        geomObjs.Add(solidGeom.GeometryObject);
                    }
                }
            }

            DirectShape zoneElement = IFCElementUtil.CreateElement(doc, CategoryId, GlobalId, geomObjs);

            if (zoneElement != null)
            {
                CreatedElementId = zoneElement.Id;
                CreatedGeometry  = geomObjs;
            }

            base.Create(doc);
        }
        //https://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            Solid s1 = Command.CreateSphereAt(new XYZ(0, 0, 15), 15);

            Solid s2 = Command.CreateSphereAt(new XYZ(0, 0, 32.5), 10);

            Solid s3 = Command.CreateSphereAt(new XYZ(0, 0, 47.5), 5);



            Transaction buildASnowman = new Transaction(doc, "Build a Snowman");

            buildASnowman.Start();
            var ds1 = DirectShape.CreateElement(doc, new ElementId(-2000151));

            ds1.SetShape(new GeometryObject[] { s1, s2, s3 });

            buildASnowman.Commit();
            return(Result.Succeeded);
        }
Example #27
0
        public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            // RhinoCommon code
            var sphere = new Sphere(Point3d.Origin, 12 * Revit.ModelUnits);
            var brep   = sphere.ToBrep();
            var meshes = Rhino.Geometry.Mesh.CreateFromBrep(brep, MeshingParameters.Default);

            // Revit code
            var uiApp = data.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            using (var trans = new Transaction(doc, MethodBase.GetCurrentMethod().DeclaringType.FullName))
            {
                if (trans.Start() == TransactionStatus.Started)
                {
                    var categoryId = new ElementId(BuiltInCategory.OST_GenericModel);

                    var ds = DirectShape.CreateElement(doc, categoryId);
                    ds.Name = "Sphere";

                    foreach (var shape in meshes.ConvertAll(ShapeEncoder.ToShape))
                    {
                        if (shape?.Length > 0)
                        {
                            ds.AppendShape(shape);
                        }
                    }

                    trans.Commit();
                }
            }

            return(Result.Succeeded);
        }
Example #28
0
        // https://forums.autodesk.com/t5/revit-api-forum/3d-model-line/m-p/5966920/highlight/true#M13466
        //        public bool Create3DModelLine(XYZ p, XYZ q, XYZ planeOrigin)
        //        {
        //			Document doc = this.ActiveUIDocument.Document;
        //            //Document doc = DocumentInterface.getInstance().GetDoc();
        //            bool lresResult = false;
        //
        //
        //
        //            using (Transaction tr = new Transaction(doc, "Create3DModelLine"))
        //            {
        //              // Create a plane to draw on.
        //              Plane plane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, planeOrigin);
        //              SketchPlane skPlane = SketchPlane.Create(doc, plane);
        //
        //                tr.Start();
        //                try
        //                {
        //                    Line line = Line.CreateBound(p, q);
        //                    ModelCurve mCurve = null;
        //                    mCurve = doc.Create.NewModelCurve(line, skPlane);
        //                    tr.Commit();
        //                    lresResult = true;
        //                }
        //                catch (Autodesk.Revit.Exceptions.ExternalApplicationException ex)
        //                {
        //                    tr.RollBack();
        //                    throw (ex);
        //                    //MessageBox.Show(ex.Source + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Message);
        //                }
        //            }
        //            return lresResult;
        //        }


        public void AddQuarterCyliderAtDoor()
        {
            Document          doc = this.ActiveUIDocument.Document;
            IList <ElementId> ids = GetUserSelectedElements("Select Door", "", null);

            //TaskDialog.Show("Test", ids.Count.ToString());

            foreach (var elementId in ids)
            {
                var element = doc.GetElement(elementId);

                FamilyInstance doorInstance = element as FamilyInstance;
                if (doorInstance == null)
                {
                    continue;
                }

                // First create a instance of the false mass family that we have imported for height checking.
                var insertionPoint = (doorInstance.Location as LocationPoint).Point;
                //doorInstance.GetSweptProfile();

                DirectShape drshape = GetTurningRadiusWithKneeAndToeClearanceDirectShape(insertionPoint);
                //DirectShape drshape = getDirectShapeArc(insertionPoint, 2, Math.PI, 4);
            }
        }
Example #29
0
        void ReconstructDirectShapeByPoint
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Point3d point
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            ThrowIfNotValid(nameof(point), point);

            if (element is DirectShape ds)
            {
            }
            else
            {
                ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
            }

            ds.SetShape(new List <GeometryObject> {
                Point.Create((point * scaleFactor).ToHost())
            });

            ReplaceElement(ref element, ds);
        }
Example #30
0
        public static void CreateUI(RibbonPanel ribbonPanel)
        {
            var items = ribbonPanel.AddStackedItems
                        (
                new ComboBoxData("Category"),
                new PulldownButtonData("cmdRhinoInside.GrasshopperPlayer", "Grasshopper Player")
                        );

            categoriesComboBox = items[0] as Autodesk.Revit.UI.ComboBox;
            if (categoriesComboBox != null)
            {
                categoriesComboBox.ToolTip = "Category where Grasshopper Player will place geometry.";
            }

            mruPullDownButton = items[1] as Autodesk.Revit.UI.PulldownButton;
            if (mruPullDownButton != null)
            {
                mruPullDownButton.ToolTip    = "Loads and evals a Grasshopper definition";
                mruPullDownButton.Image      = ImageBuilder.LoadBitmapImage("RhinoInside.Resources.GrasshopperPlayer.png", true);
                mruPullDownButton.LargeImage = ImageBuilder.LoadBitmapImage("RhinoInside.Resources.GrasshopperPlayer.png");
                mruPullDownButton.SetContextualHelp(new ContextualHelp(ContextualHelpType.Url, "https://github.com/mcneel/rhino.inside/blob/master/Autodesk/Revit/README.md#sample-4"));

                mruPullDownButton.AddPushButton(typeof(Browse), "Browse...", "Browse for a Grasshopper definition to evaluate", typeof(Availability));
            }

            EventHandler <IdlingEventArgs> BuildDirectShapeCategoryList = null;

            Revit.ApplicationUI.Idling += BuildDirectShapeCategoryList = (sender, args) =>
            {
                var doc = (sender as UIApplication)?.ActiveUIDocument.Document;
                if (doc == null)
                {
                    return;
                }

                var directShapeCategories = Enum.GetValues(typeof(BuiltInCategory)).Cast <BuiltInCategory>().
                                            Where(categoryId => DirectShape.IsValidCategoryId(new ElementId(categoryId), doc)).
                                            Select(categoryId => Autodesk.Revit.DB.Category.GetCategory(doc, categoryId));

                foreach (var group in directShapeCategories.GroupBy(x => x.CategoryType).OrderBy(x => x.Key.ToString()))
                {
                    foreach (var category in group.OrderBy(x => x.Name))
                    {
                        var comboBoxMemberData = new ComboBoxMemberData(((BuiltInCategory)category.Id.IntegerValue).ToString(), category.Name)
                        {
                            GroupName = group.Key.ToString()
                        };
                        var item = categoriesComboBox.AddItem(comboBoxMemberData);

                        if ((BuiltInCategory)category.Id.IntegerValue == BuiltInCategory.OST_GenericModel)
                        {
                            categoriesComboBox.Current = item;
                        }
                    }
                }

                Revit.ApplicationUI.Idling -= BuildDirectShapeCategoryList;
            };
        }
Example #31
0
 /// <summary>
 /// Delete the element used for solid validation, if it exists.
 /// </summary>
 public static void DeleteSolidValidator()
 {
     if (m_SolidValidator != null)
     {
         IFCImportFile.TheFile.Document.Delete(SolidValidator.Id);
         m_SolidValidator = null;
     }
 }