Exemplo n.º 1
0
        /// <summary>
        /// Private constructor that constructs a FreeForm from a user-provided
        /// solid
        /// </summary>
        /// <param name="solid"></param>
        private FreeForm(Autodesk.Revit.DB.Solid mySolid)
        {
            //Phase 1 - Check to see if the object exists and should be rebound
            var ele =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FreeFormElement>(Document);

            // mutate with new solid, if possible
            if (ele != null)
            {
                InternalSetFreeFormElement(ele);
                if (InternalSetSolid(mySolid))
                {
                    return;
                }
            }

            // recreate freeform
            TransactionManager.Instance.EnsureInTransaction(Document);

            var freeForm = FreeFormElement.Create(Document, mySolid);

            InternalSetFreeFormElement(freeForm);

            TransactionManager.Instance.TransactionTaskDone();

            ElementBinder.SetElementForTrace(this.InternalElement);
        }
Exemplo n.º 2
0
 public virtual void ApplyAttributesToFreeFormElement(FreeFormElement element)
 {
     element.MergingGroupNumber = MergingGroupNumber;
     element.FreeFormType       = FreeFormType;
     element.IsRationalForm     = IsRationalForm;
     element.DegreeU            = DegreeU;
     element.DegreeV            = DegreeV;
     element.BasicMatrixU       = BasicMatrixU;
     element.BasicMatrixV       = BasicMatrixV;
     element.StepU = StepU;
     element.StepV = StepV;
     element.CurveApproximationTechnique   = CurveApproximationTechnique;
     element.SurfaceApproximationTechnique = SurfaceApproximationTechnique;
 }
Exemplo n.º 3
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Document       document       = commandData.get_Application().get_ActiveUIDocument().get_Document();
            FileOpenDialog fileOpenDialog = new FileOpenDialog("SAT file (*.sat)|*.sat");

            ((FileDialog)fileOpenDialog).set_Title("Select SAT file to import");
            ((FileDialog)fileOpenDialog).Show();
            ModelPath selectedModelPath = ((FileDialog)fileOpenDialog).GetSelectedModelPath();

            ((FileDialog)fileOpenDialog).Dispose();
            string           userVisiblePath  = ModelPathUtils.ConvertModelPathToUserVisiblePath(selectedModelPath);
            SATImportOptions satImportOptions = new SATImportOptions();
            View             element          = new FilteredElementCollector(document).OfClass(typeof(View)).ToElements()[0] as View;

            try
            {
                using (Transaction transaction = new Transaction(document, "Import SAT"))
                {
                    transaction.Start();
                    ElementId elementId = document.Import(userVisiblePath, satImportOptions, element);
                    using (IEnumerator <GeometryObject> enumerator1 = document.GetElement(elementId).get_Geometry(new Options()).GetEnumerator())
                    {
                        while (((IEnumerator)enumerator1).MoveNext())
                        {
                            using (IEnumerator <GeometryObject> enumerator2 = (enumerator1.Current as GeometryInstance).get_SymbolGeometry().GetEnumerator())
                            {
                                while (((IEnumerator)enumerator2).MoveNext())
                                {
                                    Solid current = enumerator2.Current as Solid;
                                    FreeFormElement.Create(document, current);
                                }
                            }
                        }
                    }
                    document.Delete(elementId);
                    transaction.Commit();
                }
                return((Result)0);
            }
            catch
            {
                TaskDialog.Show("Error Importing", "Something went wrong");
                return((Result) - 1);
            }
        }
Exemplo n.º 4
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            // Retrieve all floors from the model

            var floors
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Floor))
                  .ToElements()
                  .Cast <Floor>()
                  .ToList();

            if (2 != floors.Count)
            {
                message = "Please create two intersected floors";
                return(Result.Failed);
            }

            // Retrieve the floor solids

            Options opt = new Options();

            var geometry1 = floors[0].get_Geometry(opt);
            var geometry2 = floors[1].get_Geometry(opt);

            var solid1 = geometry1.FirstOrDefault() as Solid;
            var solid2 = geometry2.FirstOrDefault() as Solid;

            // Calculate the intersection solid

            var intersectedSolid = BooleanOperationsUtils
                                   .ExecuteBooleanOperation(solid1, solid2,
                                                            BooleanOperationsType.Intersect);

            // Search for the metric mass family template file

            string template_path = DirSearch(
                app.FamilyTemplatePath,
                "Metric Mass.rft");

            // Create a new temporary family

            var family_doc = app.NewFamilyDocument(
                template_path);

            // Create a free form element
            // from the intersection solid

            using (var t = new Transaction(family_doc))
            {
                t.Start("Add Free Form Element");

                var freeFormElement = FreeFormElement.Create(
                    family_doc, intersectedSolid);

                t.Commit();
            }

            string dir = Path.GetTempPath();

            string filepath = Path.Combine(dir,
                                           "floor_intersection_family.rfa");

            SaveAsOptions sao = new SaveAsOptions()
            {
                OverwriteExistingFile = true
            };

            family_doc.SaveAs(filepath, sao);

            // Create 3D View

            var viewFamilyType
                = new FilteredElementCollector(family_doc)
                  .OfClass(typeof(ViewFamilyType))
                  .OfType <ViewFamilyType>()
                  .FirstOrDefault(x =>
                                  x.ViewFamily == ViewFamily.ThreeDimensional);

            View3D threeDView;

            using (var t = new Transaction(family_doc))
            {
                t.Start("Create 3D View");

                threeDView = View3D.CreateIsometric(
                    family_doc, viewFamilyType.Id);

                t.Commit();
            }

            // Export to SAT

            var viewSet = new List <ElementId>()
            {
                threeDView.Id
            };

            SATExportOptions exportOptions
                = new SATExportOptions();

            var res = family_doc.Export(dir,
                                        "SolidFile.sat", viewSet, exportOptions);

            return(Result.Succeeded);
        }
Exemplo n.º 5
0
        protected virtual void FreeFormElement(IObjWriterState state, FreeFormElement element, StreamWriter writer)
        {
            var writeEnd = false;

            if (element.U.Count != 0)
            {
                writeEnd = true;
                writer.Write("parm u");

                foreach (var value in element.U)
                {
                    writer.Write(" {0}", value.ToString("F6", CultureInfo.InvariantCulture));
                }

                writer.WriteLine();
            }

            if (element.V.Count != 0)
            {
                writeEnd = true;
                writer.Write("parm v");

                foreach (var value in element.V)
                {
                    writer.Write(" {0}", value.ToString("F6", CultureInfo.InvariantCulture));
                }

                writer.WriteLine();
            }

            if (element.OuterTrimmingCurves.Count != 0)
            {
                writeEnd = true;
                writer.Write("trim");

                foreach (var index in element.OuterTrimmingCurves)
                {
                    writer.Write(" {0}", index);
                }

                writer.WriteLine();
            }

            if (element.InnerTrimmingCurves.Count != 0)
            {
                writeEnd = true;
                writer.Write("hole");

                foreach (var index in element.InnerTrimmingCurves)
                {
                    writer.Write(" {0}", index);
                }

                writer.WriteLine();
            }

            if (element.SequenceCurves.Count != 0)
            {
                writeEnd = true;
                writer.Write("scrv");

                foreach (var index in element.SequenceCurves)
                {
                    writer.Write(" {0}", index);
                }

                writer.WriteLine();
            }

            if (element.SpecialPoints.Count != 0)
            {
                writeEnd = true;
                writer.Write("sp");

                foreach (var point in element.SpecialPoints)
                {
                    writer.Write(" {0}", point);
                }

                writer.WriteLine();
            }

            if (writeEnd)
            {
                writer.WriteLine("end");
            }
        }
Exemplo n.º 6
0
        protected virtual void AttributesOfFreeFormElement(IObjWriterState state, FreeFormElement element, StreamWriter writer)
        {
            if (element.MergingGroupNumber != state.MergingGroupNumber)
            {
                state.MergingGroupNumber = element.MergingGroupNumber;
                writer.WriteLine(state.MergingGroupNumber == 0 ? "mg off" : string.Format("mg {0} {1}", state.MergingGroupNumber, state.Obj.MergingGroupResolutions[state.MergingGroupNumber].ToString("F6", CultureInfo.InvariantCulture)));
            }

            switch (element.FreeFormType)
            {
            case FreeFormType.BasisMatrix:
            {
                writer.Write("cstype");

                if (element.IsRationalForm)
                {
                    writer.Write(" rat");
                }

                writer.WriteLine(" bmatrix");
                break;
            }

            case FreeFormType.Bezier:
            {
                writer.Write("cstype");

                if (element.IsRationalForm)
                {
                    writer.Write(" rat");
                }

                writer.WriteLine(" bezier");
                break;
            }

            case FreeFormType.BSpline:
            {
                writer.Write("cstype");

                if (element.IsRationalForm)
                {
                    writer.Write(" rat");
                }

                writer.WriteLine(" bspline");
                break;
            }

            case FreeFormType.Cardinal:
            {
                writer.Write("cstype");

                if (element.IsRationalForm)
                {
                    writer.Write(" rat");
                }

                writer.WriteLine(" cardinal");
                break;
            }

            case FreeFormType.Taylor:
            {
                writer.Write("cstype");

                if (element.IsRationalForm)
                {
                    writer.Write(" rat");
                }

                writer.WriteLine(" taylor");
                break;
            }
            }

            writer.WriteLine(element.DegreeV == 0
                ? string.Format("deg {0}", element.DegreeU)
                : string.Format("deg {0} {1}", element.DegreeU, element.DegreeV));

            if (element.BasicMatrixU != default)
            {
                writer.Write("bmat u");

                foreach (var value in element.BasicMatrixU)
                {
                    writer.Write(" {0}", value.ToString("F6", CultureInfo.InvariantCulture));
                }

                writer.WriteLine();
            }

            if (element.BasicMatrixV != default)
            {
                writer.Write("bmat v");

                foreach (var value in element.BasicMatrixV)
                {
                    writer.Write(" {0}", value.ToString("F6", CultureInfo.InvariantCulture));
                }

                writer.WriteLine();
            }

            writer.WriteLine(element.StepV == 1.0f
                ? string.Format("step {0}", element.StepU.ToString("F6", CultureInfo.InvariantCulture))
                : string.Format("step {0} {1}", element.StepU.ToString("F6", CultureInfo.InvariantCulture), element.StepV.ToString("F6", CultureInfo.InvariantCulture)));

            if (element.CurveApproximationTechnique != default)
            {
                if (element.CurveApproximationTechnique is ConstantParametricSubDivisionTechnique)
                {
                    var technique = (ConstantParametricSubDivisionTechnique)element.CurveApproximationTechnique;
                    writer.WriteLine("ctech cparm {0}", technique.ResolutionU.ToString("F6", CultureInfo.InvariantCulture));
                }
                else if (element.CurveApproximationTechnique is ConstantSpatialSubDivisionTechnique)
                {
                    var technique = (ConstantSpatialSubDivisionTechnique)element.CurveApproximationTechnique;
                    writer.WriteLine("ctech cspace {0}", technique.MaximumLength.ToString("F6", CultureInfo.InvariantCulture));
                }
                else if (element.CurveApproximationTechnique is CurvatureDependentSubDivisionTechnique)
                {
                    var technique = (CurvatureDependentSubDivisionTechnique)element.CurveApproximationTechnique;
                    writer.WriteLine("ctech curv {0} {1}", technique.MaximumDistance.ToString("F6", CultureInfo.InvariantCulture), technique.MaximumAngle.ToString("F6", CultureInfo.InvariantCulture));
                }
            }

            if (element.SurfaceApproximationTechnique != default)
            {
                if (element.SurfaceApproximationTechnique is ConstantParametricSubDivisionTechnique)
                {
                    var technique = (ConstantParametricSubDivisionTechnique)element.SurfaceApproximationTechnique;

                    if (technique.ResolutionU == technique.ResolutionV)
                    {
                        writer.WriteLine("stech cparmb {0}", technique.ResolutionU.ToString("F6", CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        writer.WriteLine("stech cparma {0} {1}", technique.ResolutionU.ToString("F6", CultureInfo.InvariantCulture), technique.ResolutionV.ToString("F6", CultureInfo.InvariantCulture));
                    }
                }
                else if (element.SurfaceApproximationTechnique is ConstantSpatialSubDivisionTechnique)
                {
                    var technique = (ConstantSpatialSubDivisionTechnique)element.SurfaceApproximationTechnique;
                    writer.WriteLine("stech cspace {0}", technique.MaximumLength.ToString("F6", CultureInfo.InvariantCulture));
                }
                else if (element.SurfaceApproximationTechnique is CurvatureDependentSubDivisionTechnique)
                {
                    var technique = (CurvatureDependentSubDivisionTechnique)element.SurfaceApproximationTechnique;
                    writer.WriteLine("stech curv {0} {1}", technique.MaximumDistance.ToString("F6", CultureInfo.InvariantCulture), technique.MaximumAngle.ToString("F6", CultureInfo.InvariantCulture));
                }
            }
        }
Exemplo n.º 7
0
        bool Add(Document doc, Document familyDoc, Rhino.Geometry.Brep brep)
        {
            bool isCutting = brep.SolidOrientation == Rhino.Geometry.BrepSolidOrientation.Inward;

            if (isCutting)
            {
                brep.Flip();
            }

            if (brep.ToHost() is Solid solid)
            {
                var element = FreeFormElement.Create(familyDoc, solid);

                if (isCutting)
                {
                    element.get_Parameter(BuiltInParameter.ELEMENT_IS_CUTTING).Set(1);
                    return(true);
                }
                else
                {
                    Category familySubCategory = null;
                    if
                    (
                        brep.GetUserElementId(BuiltInParameter.FAMILY_ELEM_SUBCATEGORY.ToString(), out var subCategoryId) &&
                        Autodesk.Revit.DB.Category.GetCategory(doc, subCategoryId) is Category subCategory
                    )
                    {
                        if (subCategory.Parent.Id == familyDoc.OwnerFamily.FamilyCategory.Id)
                        {
                            familySubCategory = MapCategory(doc, familyDoc, subCategoryId, true);
                        }
                        else
                        {
                            if (subCategory.Parent is null)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"'{subCategory.Name}' is not subcategory of '{familyDoc.OwnerFamily.FamilyCategory.Name}'");
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"'{subCategory.Parent.Name} : {subCategory.Name}' is not subcategory of '{familyDoc.OwnerFamily.FamilyCategory.Name}'");
                            }
                        }
                    }

                    if (familySubCategory is object)
                    {
                        element.Subcategory = familySubCategory;
                    }

                    if (brep.GetUserBoolean(BuiltInParameter.IS_VISIBLE_PARAM.ToString(), out var visible))
                    {
                        element.get_Parameter(BuiltInParameter.IS_VISIBLE_PARAM).Set(visible ? 1 : 0);
                    }

                    if (brep.GetUserInteger(BuiltInParameter.GEOM_VISIBILITY_PARAM.ToString(), out var visibility))
                    {
                        element.get_Parameter(BuiltInParameter.GEOM_VISIBILITY_PARAM).Set(visibility);
                    }

                    if
                    (
                        brep.GetUserElementId(BuiltInParameter.MATERIAL_ID_PARAM.ToString(), out var materialId) &&
                        MapMaterial(doc, familyDoc, materialId, true) is var familyMaterialId
                    )
                    {
                        element.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(familyMaterialId);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 8
0
        void ReconstructFormByGeometry
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Brep brep
        )
        {
            if (!doc.IsFamilyDocument)
            {
                throw new InvalidOperationException("This component can only run on a Family document");
            }

            brep.GetUserBoolean(BuiltInParameter.ELEMENT_IS_CUTTING.ToString(), out var cutting);

            if (brep.Faces.Count == 1 && brep.Faces[0].Loops.Count == 1 && brep.Faces[0].TryGetPlane(out var capPlane))
            {
                using (var sketchPlane = SketchPlane.Create(doc, capPlane.ToPlane()))
                    using (var referenceArray = new ReferenceArray())
                    {
                        try
                        {
                            foreach (var curve in brep.Faces[0].OuterLoop.To3dCurve().ToCurveMany())
                            {
                                referenceArray.Append(new Reference(doc.FamilyCreate.NewModelCurve(curve, sketchPlane)));
                            }

                            ReplaceElement
                            (
                                ref element,
                                doc.FamilyCreate.NewFormByCap
                                (
                                    !cutting,
                                    referenceArray
                                )
                            );

                            return;
                        }
                        catch (Autodesk.Revit.Exceptions.InvalidOperationException)
                        {
                            doc.Delete(referenceArray.OfType <Reference>().Select(x => x.ElementId).ToArray());
                        }
                    }
            }
            else if (brep.TryGetExtrusion(out var extrusion) && (extrusion.CapCount == 2 || !extrusion.IsClosed(0)))
            {
                using (var sketchPlane = SketchPlane.Create(doc, extrusion.GetProfilePlane(0.0).ToPlane()))
                    using (var referenceArray = new ReferenceArray())
                    {
                        try
                        {
                            foreach (var curve in extrusion.Profile3d(new Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.ExtrusionBottomProfile, 0)).ToCurveMany())
                            {
                                referenceArray.Append(new Reference(doc.FamilyCreate.NewModelCurve(curve, sketchPlane)));
                            }

                            ReplaceElement
                            (
                                ref element,
                                doc.FamilyCreate.NewExtrusionForm
                                (
                                    !cutting,
                                    referenceArray,
                                    extrusion.PathLineCurve().Line.Direction.ToXYZ(UnitConverter.ToHostUnits)
                                )
                            );
                            return;
                        }
                        catch (Autodesk.Revit.Exceptions.InvalidOperationException)
                        {
                            doc.Delete(referenceArray.OfType <Reference>().Select(x => x.ElementId).ToArray());
                        }
                    }
            }

            {
                var solid = brep.ToSolid();
                if (solid != null)
                {
                    if (element is FreeFormElement freeFormElement)
                    {
                        freeFormElement.UpdateSolidGeometry(solid);
                    }
                    else
                    {
                        ReplaceElement(ref element, FreeFormElement.Create(doc, solid));

                        if (doc.OwnerFamily.IsConceptualMassFamily)
                        {
                            element.get_Parameter(BuiltInParameter.FAMILY_ELEM_SUBCATEGORY).Set(new ElementId(BuiltInCategory.OST_MassForm));
                        }
                    }

                    element.get_Parameter(BuiltInParameter.ELEMENT_IS_CUTTING)?.Set(cutting ? 1 : 0);
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Failed to convert Brep to Form");
                }
            }
        }
Exemplo n.º 9
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            Rhino.Geometry.Brep brep
        )
        {
            var element = PreviousElement(doc, Iteration);

            if (!element?.Pinned ?? false)
            {
                ReplaceElement(doc, DA, Iteration, element);
            }
            else
            {
                try
                {
                    if (!Revit.ActiveDBDocument.IsFamilyDocument || !Revit.ActiveDBDocument.OwnerFamily.IsConceptualMassFamily)
                    {
                        throw new Exception("This component can only run in Conceptual Mass Family editor");
                    }

                    if (brep == null)
                    {
                        throw new Exception(string.Format("Parameter '{0}' must be valid Brep.", Params.Input[0].Name));
                    }

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

                    if (brep.Faces.Count == 1 && brep.Faces[0].Loops.Count == 1 && brep.Faces[0].TryGetPlane(out var capPlane))
                    {
                        var sketchPlane = SketchPlane.Create(doc, capPlane.ToHost());

                        var referenceArray = new ReferenceArray();
                        var loop           = brep.Faces[0].OuterLoop.To3dCurve();

                        foreach (var curve in brep.Faces[0].OuterLoop.To3dCurve().ToHost())
                        {
                            referenceArray.Append(new Reference(doc.FamilyCreate.NewModelCurve(curve, sketchPlane)));
                        }

                        element = CopyParametersFrom
                                  (
                            doc.FamilyCreate.NewFormByCap
                            (
                                brep.SolidOrientation != Rhino.Geometry.BrepSolidOrientation.Inward,
                                referenceArray
                            ),
                            element
                                  );
                    }
                    else if (brep.TryGetExtrusion(out var extrusion) && (extrusion.CapCount == 2 || !extrusion.IsClosed(0)))
                    {
                        var sketchPlane = SketchPlane.Create(doc, extrusion.GetProfilePlane(0.0).ToHost());

                        var referenceArray = new ReferenceArray();
                        foreach (var curve in extrusion.Profile3d(new Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.ExtrusionBottomProfile, 0)).ToHost())
                        {
                            referenceArray.Append(new Reference(doc.FamilyCreate.NewModelCurve(curve, sketchPlane)));
                        }

                        element = CopyParametersFrom
                                  (
                            element = doc.FamilyCreate.NewExtrusionForm
                                      (
                                brep.SolidOrientation != Rhino.Geometry.BrepSolidOrientation.Inward,
                                referenceArray, extrusion.PathLineCurve().Line.Direction.ToHost()
                                      ),
                            element
                                  );
                    }
                    else
                    {
                        var solids = brep.ToHost().ToArray();
                        if (solids.Length == 1 && (solids[0] is Solid solid))
                        {
                            if (element is FreeFormElement freeFormElement)
                            {
                                freeFormElement.UpdateSolidGeometry(solid);
                            }
                            else
                            {
                                element = CopyParametersFrom(FreeFormElement.Create(doc, solid), element);
                                element.get_Parameter(BuiltInParameter.FAMILY_ELEM_SUBCATEGORY).Set(new ElementId(BuiltInCategory.OST_MassForm));
                            }

                            element.get_Parameter(BuiltInParameter.ELEMENT_IS_CUTTING)?.Set
                            (
                                brep.SolidOrientation == Rhino.Geometry.BrepSolidOrientation.Inward ?
                                1 /*VOID*/ :
                                0 /*SOLID*/
                            );
                        }
                    }

                    ReplaceElement(doc, DA, Iteration, element);
                }
Exemplo n.º 10
0
        void ReconstructFormByGeometry
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Brep brep
        )
        {
            if (!doc.IsFamilyDocument)
            {
                throw new InvalidOperationException("This component can only run in Family editor");
            }

            var scaleFactor = 1.0 / Revit.ModelUnits;

            brep = brep.ChangeUnits(scaleFactor);

            if (brep.Faces.Count == 1 && brep.Faces[0].Loops.Count == 1 && brep.Faces[0].TryGetPlane(out var capPlane))
            {
                using (var sketchPlane = SketchPlane.Create(doc, capPlane.ToHost()))
                    using (var referenceArray = new ReferenceArray())
                    {
                        try
                        {
                            foreach (var curve in brep.Faces[0].OuterLoop.To3dCurve().ToHostMultiple())
                            {
                                referenceArray.Append(new Reference(doc.FamilyCreate.NewModelCurve(curve, sketchPlane)));
                            }

                            ReplaceElement
                            (
                                ref element,
                                doc.FamilyCreate.NewFormByCap
                                (
                                    brep.SolidOrientation != Rhino.Geometry.BrepSolidOrientation.Inward,
                                    referenceArray
                                )
                            );

                            return;
                        }
                        catch (Autodesk.Revit.Exceptions.InvalidOperationException)
                        {
                            doc.Delete(referenceArray.OfType <Reference>().Select(x => x.ElementId).ToArray());
                        }
                    }
            }
            else if (brep.TryGetExtrusion(out var extrusion) && (extrusion.CapCount == 2 || !extrusion.IsClosed(0)))
            {
                using (var sketchPlane = SketchPlane.Create(doc, extrusion.GetProfilePlane(0.0).ToHost()))
                    using (var referenceArray = new ReferenceArray())
                    {
                        try
                        {
                            foreach (var curve in extrusion.Profile3d(new Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.ExtrusionBottomProfile, 0)).ToHostMultiple())
                            {
                                referenceArray.Append(new Reference(doc.FamilyCreate.NewModelCurve(curve, sketchPlane)));
                            }

                            ReplaceElement
                            (
                                ref element,
                                doc.FamilyCreate.NewExtrusionForm
                                (
                                    brep.SolidOrientation != Rhino.Geometry.BrepSolidOrientation.Inward,
                                    referenceArray, extrusion.PathLineCurve().Line.Direction.ToHost()
                                )
                            );
                            return;
                        }
                        catch (Autodesk.Revit.Exceptions.InvalidOperationException)
                        {
                            doc.Delete(referenceArray.OfType <Reference>().Select(x => x.ElementId).ToArray());
                        }
                    }
            }

            {
                var solid = brep.ToHost();
                if (solid != null)
                {
                    if (element is FreeFormElement freeFormElement)
                    {
                        freeFormElement.UpdateSolidGeometry(solid);
                    }
                    else
                    {
                        ReplaceElement(ref element, FreeFormElement.Create(doc, solid));

                        if (doc.OwnerFamily.IsConceptualMassFamily)
                        {
                            element.get_Parameter(BuiltInParameter.FAMILY_ELEM_SUBCATEGORY).Set(new ElementId(BuiltInCategory.OST_MassForm));
                        }
                    }

                    element.get_Parameter(BuiltInParameter.ELEMENT_IS_CUTTING)?.Set
                    (
                        brep.SolidOrientation == Rhino.Geometry.BrepSolidOrientation.Inward ?
                        1 /*VOID*/ :
                        0 /*SOLID*/
                    );
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Convert a DS Solid to a Revit FamilySymbol containing
        /// Revit FreeForms via SAT Export/Import
        /// </summary>
        /// <param name="solidGeometry"></param>
        /// <param name="name"></param>
        /// <param name="category"></param>
        /// <param name="templatePath">Revit Template to use for Family Creation</param>
        /// <param name="material">Can be null for Voids</param>
        /// <param name="isVoid">Create Void</param>
        /// <param name="subcategory">Can be string.Empty for Voids</param>
        /// <returns></returns>
        public static Autodesk.Revit.DB.FamilySymbol ToRevitFamilyType(
            this Autodesk.DesignScript.Geometry.Solid solidGeometry,
            string name,
            Revit.Elements.Category category,
            string templatePath,
            Revit.Elements.Material material,
            bool isVoid,
            string subcategory = "")
        {
            // Keep the current document and close the open transaction
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            TransactionManager.Instance.ForceCloseTransaction();

            // create a temp sat file
            string tempFile = System.IO.Path.GetTempFileName() + ".sat";

            // create a temp family file
            string tempDir        = System.IO.Path.GetTempPath();
            string tempFamilyFile = System.IO.Path.Combine(tempDir, name + ".rfa");

            // scale the incoming geometry
            solidGeometry = solidGeometry.InHostUnits();

            // get a displacement vector
            Vector vector = Vector.ByTwoPoints(Autodesk.DesignScript.Geometry.BoundingBox.ByGeometry(solidGeometry).MinPoint, Autodesk.DesignScript.Geometry.Point.Origin());

            // translate the geometry to origin
            solidGeometry = solidGeometry.Translate(vector) as Autodesk.DesignScript.Geometry.Solid;

            // export geometry to SAT
            solidGeometry.ExportToSAT(tempFile);
            solidGeometry.Dispose();

            // create a new family document using the supplied template
            Autodesk.Revit.DB.Document familyDocument = document.Application.NewFamilyDocument(templatePath);

            // Get the families 3d view
            var collector = new Autodesk.Revit.DB.FilteredElementCollector(familyDocument).OfClass(typeof(Autodesk.Revit.DB.View));

            Autodesk.Revit.DB.View view = null;
            foreach (Autodesk.Revit.DB.View v in collector.ToElements())
            {
                if (!v.IsTemplate && v.ViewType == ViewType.ThreeD)
                {
                    view = v;
                }
            }

            // Open a Transaction with the FamilyDocument
            TransactionManager.Instance.EnsureInTransaction(familyDocument);

            // Import the sat file to origin in feet
            ElementId importedElementId = familyDocument.Import(tempFile, new SATImportOptions()
            {
                Placement = ImportPlacement.Origin, Unit = ImportUnit.Foot
            }, view);

            // get the solid element from the imported sat file
            var solids = GetSolidsFromElement(familyDocument.GetElement(importedElementId));

            // delete imported sat
            familyDocument.Delete(importedElementId);
            System.IO.File.Delete(tempFile);

            // Set the families category
            familyDocument.OwnerFamily.FamilyCategory = familyDocument.Settings.Categories.get_Item(category.Name);

            foreach (var solid in solids)
            {
                // Create Freeform Element
                var freeform = FreeFormElement.Create(familyDocument, solid);

                // if the geometry should be void set parameters accordingly
                if (isVoid)
                {
                    ApplyVoidSettingsToFreeForm(freeform);
                }
                else
                {
                    // Apply material if supplied
                    ApplyMaterialToFreeForm(familyDocument, material, freeform);

                    // Apply Subcategory if supplied
                    if (subcategory != string.Empty)
                    {
                        ApplySubCategoryToFreeForm(familyDocument, subcategory, freeform);
                    }
                }
            }

            // Close the FamilyDocument Transaction
            TransactionManager.Instance.ForceCloseTransaction();

            // Save Family document and load it into the project
            familyDocument.SaveAs(tempFamilyFile, new SaveAsOptions()
            {
                OverwriteExistingFile = true
            });
            var family = familyDocument.LoadFamily(document, new FamilyImportOptions());

            // close and delete family
            familyDocument.Close(false);
            System.IO.File.Delete(tempFamilyFile);

            // get first imported family symbol
            var symbols = family.GetFamilySymbolIds();

            // Restore the Project Document Transaction
            TransactionManager.Instance.EnsureInTransaction(document);

            if (symbols.Count > 0)
            {
                FamilySymbol symbol = (FamilySymbol)document.GetElement(symbols.First());

                // activate symbol
                if (!symbol.IsActive)
                {
                    symbol.Activate();
                }

                return(symbol);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 12
0
        void CommitInstance
        (
            Document doc, IGH_DataAccess DA, int Iteration,
            Rhino.Geometry.Brep brep
        )
        {
            var elements = PreviousElements(doc, Iteration).ToList();

            try
            {
                var newElements = new List <Element>();

                if (brep == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' must be valid Brep.", Params.Input[0].Name));
                }
                else
                {
                    var scaleFactor = 1.0 / Revit.ModelUnits;
                    if (scaleFactor != 1.0)
                    {
                        brep.Scale(scaleFactor);
                    }

                    int index = 0;
                    foreach (var s in brep.ToHost().Cast <Autodesk.Revit.DB.Solid>() ?? Enumerable.Empty <Autodesk.Revit.DB.Solid>())
                    {
                        var element = index < elements.Count ? elements[index] : null;
                        index++;

                        if (element?.Pinned ?? true)
                        {
                            if (doc.IsFamilyDocument)
                            {
                                if (element is FreeFormElement freeFormElement)
                                {
                                    freeFormElement.UpdateSolidGeometry(s);
                                }
                                else
                                {
                                    element = FreeFormElement.Create(doc, s);
                                }

                                element.get_Parameter(BuiltInParameter.ELEMENT_IS_CUTTING)?.Set
                                (
                                    s.Volume < 0.0 ?
                                    1 /*VOID*/ :
                                    0 /*SOLID*/
                                );
                            }
                            else
                            {
                                var ds = element as DirectShape ?? DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
                                ds.SetShape(new Solid[] { s });
                                element = ds;
                            }
                        }

                        newElements.Add(element);
                    }
                }

                elements = newElements;
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
            }
            finally
            {
                ReplaceElements(doc, DA, Iteration, elements);
            }
        }
Exemplo n.º 13
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            //Create folder dialog path
            FileOpenDialog file_dia = new FileOpenDialog("SAT file (*.sat)|*.sat");

            file_dia.Title = "Select SAT file to import";
            file_dia.Show();
            ModelPath path = file_dia.GetSelectedModelPath();

            file_dia.Dispose();

            //Convert file path to a string
            string path_str = ModelPathUtils.ConvertModelPathToUserVisiblePath(path);

            SATImportOptions satOpt = new SATImportOptions();

            FilteredElementCollector filEle = new FilteredElementCollector(doc);

            IList <Element> views = filEle.OfClass(typeof(View)).ToElements();

            View import_view = views[0] as View;

            try
            {
                using (Transaction trans = new Transaction(doc, "Import SAT"))
                {   // Start transaction, import SAT file and get the element
                    trans.Start();
                    ElementId importedElementId = doc.Import(path_str, satOpt, import_view);
                    Element   importedElement   = doc.GetElement(importedElementId);

                    //Extract geometry element from the imported element
                    Options         geoOptions       = new Options();
                    GeometryElement importedGeometry = importedElement.get_Geometry(geoOptions);


                    //Iterate through the geometry elements extracting the geometry as individual elements
                    foreach (GeometryObject geoObj in importedGeometry)
                    {
                        GeometryInstance instance = geoObj as GeometryInstance;
                        foreach (GeometryObject instObj in instance.SymbolGeometry)
                        {
                            Solid solid = instObj as Solid;
                            FreeFormElement.Create(doc, solid);
                        }
                    }

                    //Delete SAT file

                    doc.Delete(importedElementId);
                    trans.Commit();
                }

                return(Result.Succeeded);
            }

            catch
            {
                TaskDialog.Show("Error Importing", "Something went wrong");
                return(Result.Failed);
            }
        }