Example #1
0
        public ApplicationPlaceholderObject TopographyToNative(Topography speckleSurface)
        {
            var docObj = GetExistingElementByApplicationId(((Base)speckleSurface).applicationId);

            var pts = new List <XYZ>();

            for (int i = 0; i < speckleSurface.displayMesh.vertices.Count; i += 3)
            {
                var point = new Geometry.Point(speckleSurface.displayMesh.vertices[i], speckleSurface.displayMesh.vertices[i + 1], speckleSurface.displayMesh.vertices[i + 2], speckleSurface.displayMesh.units);
                pts.Add(PointToNative(point));
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var revitSurface = TopographySurface.Create(Doc, pts);

            if (speckleSurface is RevitTopography rt)
            {
                SetInstanceParameters(revitSurface, rt);
            }
            //Report.Log($"Created Topography {revitSurface.Id}");
            return(new ApplicationPlaceholderObject {
                applicationId = ((Base)speckleSurface).applicationId, ApplicationGeneratedId = revitSurface.UniqueId, NativeObject = revitSurface
            });
        }
Example #2
0
        // This is to support raw geometry being sent to Revit (eg from rhino, gh, autocad...)
        public List <ApplicationPlaceholderObject> ModelCurveToNative(ICurve speckleLine)
        {
            // if it comes from GH it doesn't have an applicationId, the use the hash id
            if ((speckleLine as Base).applicationId == null)
            {
                (speckleLine as Base).applicationId = (speckleLine as Base).id;
            }

            var docObj = GetExistingElementByApplicationId((speckleLine as Base).applicationId);

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            try
            {
                return(ModelCurvesFromEnumerator(CurveToNative(speckleLine).GetEnumerator(), speckleLine));
            }
            catch (Exception e)
            {
                // use display value if curve fails (prob a closed, periodic curve or a non-planar nurbs)
                return(ModelCurvesFromEnumerator(CurveToNative(((Geometry.Curve)speckleLine).displayValue).GetEnumerator(),
                                                 speckleLine));
            }
        }
Example #3
0
        public List <ApplicationPlaceholderObject> ModelCurveToNative(ModelCurve speckleCurve)
        {
            var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var curves          = CurveToNative(speckleCurve.baseCurve);
            var placeholders    = new List <ApplicationPlaceholderObject>();
            var curveEnumerator = curves.GetEnumerator();

            while (curveEnumerator.MoveNext() && curveEnumerator.Current != null)
            {
                var           baseCurve  = curveEnumerator.Current as DB.Curve;
                DB.ModelCurve revitCurve = Doc.Create.NewModelCurve(baseCurve, NewSketchPlaneFromCurve(baseCurve, Doc));

                var lineStyles  = revitCurve.GetLineStyleIds();
                var lineStyleId = lineStyles.FirstOrDefault(x => Doc.GetElement(x).Name == speckleCurve.lineStyle);
                if (lineStyleId != null)
                {
                    revitCurve.LineStyle = Doc.GetElement(lineStyleId);
                }
                placeholders.Add(new ApplicationPlaceholderObject()
                {
                    applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
                });
                //Report.Log($"Created ModelCurve {revitCurve.Id}");
            }

            return(placeholders);
        }
Example #4
0
        public ApplicationPlaceholderObject ModelCurveToNative(ModelCurve speckleCurve)
        {
            var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId);

            //TODO: support poliline/polycurve lines
            var baseCurve = CurveToNative(speckleCurve.baseCurve).get_Item(0);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            DB.ModelCurve revitCurve = Doc.Create.NewModelCurve(baseCurve, NewSketchPlaneFromCurve(baseCurve));

            var lineStyles  = revitCurve.GetLineStyleIds();
            var lineStyleId = lineStyles.FirstOrDefault(x => Doc.GetElement(x).Name == speckleCurve.lineStyle);

            if (lineStyleId != null)
            {
                revitCurve.LineStyle = Doc.GetElement(lineStyleId);
            }

            return(new ApplicationPlaceholderObject()
            {
                applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
            });
        }
Example #5
0
        public static TopographySurface ToNative(this Topography mySurface)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(mySurface.ApplicationId, mySurface.Type);

            var pts = new List <XYZ>();

            for (int i = 0; i < mySurface.Vertices.Count; i += 3)
            {
                pts.Add(new XYZ(mySurface.Vertices[i] * Scale, mySurface.Vertices[i + 1] * Scale, mySurface.Vertices[i + 2] * Scale));
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);

                // TODO: Can't start a transaction here as we have started a global transaction for the creation of all objects.
                // TODO: Let each individual ToNative method handle its own transactions. It's a big change, so will leave for later.

                //var srf = (TopographySurface) docObj;

                //using( TopographyEditScope e = new TopographyEditScope( Doc, "Speckle Topo Edit" ) )
                //{
                //  e.Start(srf.Id);
                //  srf.DeletePoints( srf.GetPoints() );
                //  srf.AddPoints( pts );
                //  e.Commit( null );
                //}
                //return srf;
            }

            return(TopographySurface.Create(Doc, pts));
        }
Example #6
0
        // This is to support raw geometry being sent to Revit (eg from rhino, gh, autocad...)
        public List <ApplicationPlaceholderObject> ModelCurveToNative(ICurve speckleLine)
        {
            // if it comes from GH it doesn't have an applicationId, the use the hash id
            if ((speckleLine as Base).applicationId == null)
            {
                (speckleLine as Base).applicationId = (speckleLine as Base).id;
            }

            var docObj = GetExistingElementByApplicationId((speckleLine as Base).applicationId);

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var placeholders    = new List <ApplicationPlaceholderObject>();
            var curveEnumerator = CurveToNative(speckleLine).GetEnumerator();

            while (curveEnumerator.MoveNext() && curveEnumerator.Current != null)
            {
                var curve = curveEnumerator.Current as DB.Curve;
                // Curves must be bound in order to be valid model curves
                if (!curve.IsBound)
                {
                    curve.MakeBound(speckleLine.domain.start ?? 0, speckleLine.domain.end ?? Math.PI * 2);
                }
                DB.ModelCurve revitCurve = Doc.Create.NewModelCurve(curve, NewSketchPlaneFromCurve(curve, Doc));
                placeholders.Add(new ApplicationPlaceholderObject()
                {
                    applicationId = (speckleLine as Base).applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
                });
            }

            return(placeholders);
        }
Example #7
0
        public List <ApplicationPlaceholderObject> AlignmentToNative(Alignment alignment)
        {
            var docObj = GetExistingElementByApplicationId(alignment.applicationId);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var curves          = CurveToNative(alignment.curves);
            var placeholders    = new List <ApplicationPlaceholderObject>();
            var curveEnumerator = curves.GetEnumerator();

            while (curveEnumerator.MoveNext() && curveEnumerator.Current != null)
            {
                var           baseCurve  = curveEnumerator.Current as DB.Curve;
                DB.ModelCurve revitCurve = Doc.Create.NewModelCurve(baseCurve, NewSketchPlaneFromCurve(baseCurve, Doc));
                var           lineStyles = revitCurve.GetLineStyleIds().First();
                placeholders.Add(new ApplicationPlaceholderObject()
                {
                    applicationId = alignment.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
                });
            }
            return(placeholders);
        }
Example #8
0
        public List <ApplicationPlaceholderObject> RoomToNative(Room speckleRoom)
        {
            var revitRoom = GetExistingElementByApplicationId(speckleRoom.applicationId) as DB.Room;
            var level     = LevelToNative(speckleRoom.level);


            //TODO: support updating rooms
            if (revitRoom != null)
            {
                Doc.Delete(revitRoom.Id);
            }

            revitRoom = Doc.Create.NewRoom(level, new UV(speckleRoom.center.x, speckleRoom.center.y));

            revitRoom.Name   = speckleRoom.name;
            revitRoom.Number = speckleRoom.number;

            SetInstanceParameters(revitRoom, speckleRoom);

            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject
                {
                    applicationId          = speckleRoom.applicationId,
                    ApplicationGeneratedId = revitRoom.UniqueId,
                    NativeObject           = revitRoom
                }
            };

            return(placeholders);
        }
Example #9
0
        public ApplicationPlaceholderObject RoomBoundaryLineToNative(RoomBoundaryLine speckleCurve)
        {
            var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId);

            //TODO: support poliline/polycurve lines
            var baseCurve = CurveToNative(speckleCurve.baseCurve as ICurve);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            try
            {
                var res = Doc.Create.NewRoomBoundaryLines(NewSketchPlaneFromCurve(baseCurve.get_Item(0)), baseCurve, Doc.ActiveView).get_Item(0);
                return(new ApplicationPlaceholderObject()
                {
                    applicationId = speckleCurve.applicationId, ApplicationGeneratedId = res.UniqueId, NativeObject = res
                });
            }
            catch (Exception)
            {
                ConversionErrors.Add(new Error("Room boundary line creation failed", $"View is not valid for room boundary line creation."));
                throw;
            }
        }
Example #10
0
        public static Autodesk.Revit.DB.DirectShape ToNative(this SpeckleElementsClasses.DirectShape myDs)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(myDs.ApplicationId, myDs.Type);

            //can't edit existing DS
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            IList <GeometryObject> mesh = (IList <GeometryObject>)SpeckleCore.Converter.Deserialise(obj: (SpeckleMesh)myDs.directShapeMesh, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo", "SpeckleElementsRevit", "SpeckleStructuralRevit" });

            var cat = BuiltInCategory.OST_GenericModel;
            var bic = BuiltInCategories.GetFromCategory(myDs.category);

            BuiltInCategory.TryParse(bic, out cat);
            var catId = Doc.Settings.Categories.get_Item(cat).Id;

            var ds = Autodesk.Revit.DB.DirectShape.CreateElement(Doc, catId);

            ds.ApplicationId     = myDs.ApplicationId;
            ds.ApplicationDataId = Guid.NewGuid().ToString();
            ds.SetShape(mesh);
            ds.Name = myDs.directShapeName;

            SetElementParams(ds, myDs.parameters);

            return(ds);
        }
Example #11
0
        public ApplicationPlaceholderObject RoomBoundaryLineToNative(RoomBoundaryLine speckleCurve)
        {
            var docObj    = GetExistingElementByApplicationId(speckleCurve.applicationId);
            var baseCurve = CurveToNative(speckleCurve.baseCurve);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            try
            {
                var revitCurve = Doc.Create.NewRoomBoundaryLines(NewSketchPlaneFromCurve(baseCurve.get_Item(0), Doc), baseCurve, Doc.ActiveView).get_Item(0);
                Report.Log($"Created RoomBoundaryLine {revitCurve.Id}");
                return(new ApplicationPlaceholderObject()
                {
                    applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
                });
            }
            catch (Exception)
            {
                throw (new Exception("Room boundary line creation failed\nView is not valid for room boundary line creation."));
            }
        }
        public ApplicationPlaceholderObject TopographyToNative(Topography speckleSurface)
        {
            var docObj = GetExistingElementByApplicationId(((Base)speckleSurface).applicationId);

            var pts = new List <XYZ>();

            for (int i = 0; i < speckleSurface.baseGeometry.vertices.Count; i += 3)
            {
                pts.Add(new XYZ(
                            ScaleToNative(speckleSurface.baseGeometry.vertices[i], speckleSurface.baseGeometry.units),
                            ScaleToNative(speckleSurface.baseGeometry.vertices[i + 1], speckleSurface.baseGeometry.units),
                            ScaleToNative(speckleSurface.baseGeometry.vertices[i + 2], speckleSurface.baseGeometry.units)));
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var revitSurface = TopographySurface.Create(Doc, pts);

            if (speckleSurface is RevitTopography rt)
            {
                SetInstanceParameters(revitSurface, rt);
            }

            return(new ApplicationPlaceholderObject {
                applicationId = ((Base)speckleSurface).applicationId, ApplicationGeneratedId = revitSurface.UniqueId, NativeObject = revitSurface
            });
        }
Example #13
0
        // This is to support raw geometry being sent to Revit (eg from rhino, gh, autocad...)
        public ApplicationPlaceholderObject DirectShapeToNative(Mesh mesh, BuiltInCategory cat = BuiltInCategory.OST_GenericModel)
        {
            // if it comes from GH it doesn't have an applicationId, the use the hash id
            if (mesh.applicationId == null)
            {
                mesh.applicationId = mesh.id;
            }

            var docObj = GetExistingElementByApplicationId(mesh.applicationId);

            //just create new one
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var converted = new List <GeometryObject>();
            var rMesh     = MeshToNative(mesh);

            converted.AddRange(rMesh);

            var catId = Doc.Settings.Categories.get_Item(cat).Id;

            var revitDs = DB.DirectShape.CreateElement(Doc, catId);

            revitDs.ApplicationId     = mesh.applicationId;
            revitDs.ApplicationDataId = Guid.NewGuid().ToString();
            revitDs.SetShape(converted);
            revitDs.Name = "Mesh " + mesh.applicationId;

            return(new ApplicationPlaceholderObject {
                applicationId = mesh.applicationId, ApplicationGeneratedId = revitDs.UniqueId, NativeObject = revitDs
            });
        }
        public ApplicationPlaceholderObject DirectShapeToNative(DirectShape speckleDs)
        {
            var docObj = GetExistingElementByApplicationId(speckleDs.applicationId);

            //just create new one
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var converted = new List <GeometryObject>();

            speckleDs.baseGeometries.ToList().ForEach(b =>
            {
                switch (b)
                {
                case Brep brep:
                    try
                    {
                        var solid = BrepToNative(brep);
                        converted.Add(solid);
                    }
                    catch (Exception e)
                    {
                        var mesh = MeshToNative(brep.displayValue);
                        converted.AddRange(mesh);
                    }
                    break;

                case Mesh mesh:
                    var rMesh = MeshToNative(mesh);
                    converted.AddRange(rMesh);
                    break;

                default:
                    ConversionErrors.Add(new Error("Incompatible geometry type",
                                                   $"Type ${b.GetType()} is not supported in DirectShape conversions."));
                    break;
                }
            });

            BuiltInCategory cat;
            var             bic = RevitUtils.GetBuiltInCategory(speckleDs.category);

            BuiltInCategory.TryParse(bic, out cat);
            var catId = Doc.Settings.Categories.get_Item(cat).Id;

            var revitDs = DB.DirectShape.CreateElement(Doc, catId);

            revitDs.ApplicationId     = speckleDs.applicationId;
            revitDs.ApplicationDataId = Guid.NewGuid().ToString();
            revitDs.SetShape(converted);
            revitDs.Name = speckleDs.name;
            SetInstanceParameters(revitDs, speckleDs);

            return(new ApplicationPlaceholderObject {
                applicationId = speckleDs.applicationId, ApplicationGeneratedId = revitDs.UniqueId, NativeObject = revitDs
            });
        }
        public List <ApplicationPlaceholderObject> DuctToNative(BuiltElements.Duct speckleDuct)
        {
            var baseLine   = LineToNative(speckleDuct.baseLine);
            XYZ startPoint = baseLine.GetEndPoint(0);
            XYZ endPoint   = baseLine.GetEndPoint(1);

            Autodesk.Revit.DB.Level level;

            var speckleRevitDuct = speckleDuct as RevitDuct;

            level = LevelToNative(speckleRevitDuct != null ? speckleRevitDuct.level : LevelFromCurve(baseLine));

            var ductType     = GetElementType <DB.DuctType>(speckleDuct);
            var systemFamily = (speckleDuct is RevitDuct rd) ? rd.systemName : "";

            List <ElementType> types = new FilteredElementCollector(Doc).WhereElementIsElementType()
                                       .OfClass(typeof(MechanicalSystemType)).ToElements().Cast <ElementType>().ToList();
            var system = types.FirstOrDefault(x => x.Name == systemFamily);

            if (system == null)
            {
                system = types.FirstOrDefault();
                Report.LogConversionError(new Exception($"Duct type {systemFamily} not found; replaced with {system.Name}"));
            }

            var docObj = GetExistingElementByApplicationId(((Base)speckleDuct).applicationId);


            // deleting instead of updating for now!
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            DB.Duct duct = DB.Duct.Create(Doc, system.Id, ductType.Id, level.Id, startPoint, endPoint);

            if (speckleRevitDuct != null)
            {
                TrySetParam(duct, BuiltInParameter.RBS_CURVE_HEIGHT_PARAM, speckleRevitDuct.height, speckleRevitDuct.units);
                TrySetParam(duct, BuiltInParameter.RBS_CURVE_WIDTH_PARAM, speckleRevitDuct.width, speckleRevitDuct.units);
                TrySetParam(duct, BuiltInParameter.RBS_CURVE_DIAMETER_PARAM, speckleRevitDuct.diameter, speckleRevitDuct.units);
                TrySetParam(duct, BuiltInParameter.CURVE_ELEM_LENGTH, speckleRevitDuct.length, speckleRevitDuct.units);
                TrySetParam(duct, BuiltInParameter.RBS_VELOCITY, speckleRevitDuct.velocity, speckleRevitDuct.units);
                //Report.Log($"Created Duct {duct.Id}");
                SetInstanceParameters(duct, speckleRevitDuct);
            }

            var placeholders = new List <ApplicationPlaceholderObject>
            {
                new ApplicationPlaceholderObject
                {
                    applicationId = speckleDuct.applicationId, ApplicationGeneratedId = duct.UniqueId, NativeObject = duct
                }
            };

            return(placeholders);
        }
Example #16
0
        public ApplicationPlaceholderObject AdaptiveComponentToNative(AdaptiveComponent speckleAc)
        {
            var docObj = GetExistingElementByApplicationId(speckleAc.applicationId);

            string familyName = speckleAc["family"] as string != null ? speckleAc["family"] as string : "";

            DB.FamilySymbol   familySymbol = GetElementType <DB.FamilySymbol>(speckleAc);
            DB.FamilyInstance revitAc      = null;

            //try update existing
            if (docObj != null)
            {
                try
                {
                    var revitType = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                    // if family changed, tough luck. delete and let us create a new one.
                    if (familyName != revitType.FamilyName)
                    {
                        Doc.Delete(docObj.Id);
                    }
                    else
                    {
                        revitAc = (DB.FamilyInstance)docObj;

                        // check for a type change
                        if (speckleAc.type != null && speckleAc.type != revitType.Name)
                        {
                            revitAc.ChangeTypeId(familySymbol.Id);
                        }
                    }
                }
                catch
                {
                    //something went wrong, re-create it
                }
            }

            //create family instance
            if (revitAc == null)
            {
                revitAc = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(Doc, familySymbol);
            }

            SetAdaptivePoints(revitAc, speckleAc.basePoints);
            AdaptiveComponentInstanceUtils.SetInstanceFlipped(revitAc, speckleAc.flipped);

            SetInstanceParameters(revitAc, speckleAc);

            return(new ApplicationPlaceholderObject {
                applicationId = speckleAc.applicationId, ApplicationGeneratedId = revitAc.UniqueId, NativeObject = revitAc
            });
        }
Example #17
0
        public static Autodesk.Revit.DB.Floor ToNative(this SpeckleElementsClasses.Floor mySlab)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(mySlab.ApplicationId, mySlab.Type);

            //if( stateObj != null && Convert.ToBoolean( stateObj.Properties[ "userModified" ] ) == false && docObj != null )
            //{
            //  return docObj as Autodesk.Revit.DB.Floor;
            //}

            var slabCurves = new CurveArray();
            var segments   = GetSegmentList(mySlab.baseCurve);

            foreach (var x in segments)
            {
                slabCurves.Append(x);
            }

            if (mySlab.level == null)
            {
                mySlab.level = new SpeckleElementsClasses.Level()
                {
                    createView = true, elevation = segments[0].GetEndPoint(0).Z / Scale
                }
            }
            ;

            // NOTE: I have not found a way to edit a slab outline properly, so whenever we bake, we renew the element.
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            if (mySlab.floorType == null)
            {
                var myNullTypeFloor = Doc.Create.NewFloor(slabCurves, false);

                SetElementParams(myNullTypeFloor, mySlab.parameters);
                return(myNullTypeFloor);
            }

            FloorType type = (FloorType)GetElementByClassAndName(typeof(Autodesk.Revit.DB.FloorType), mySlab.floorType);

            var fltype = GetElementByName(typeof(FloorType), mySlab.floorType);

            var myTypeBasedFloor = Doc.Create.NewFloor(slabCurves, type, ((Autodesk.Revit.DB.Level)mySlab.level.ToNative()), false);

            SetElementParams(myTypeBasedFloor, mySlab.parameters);
            return(myTypeBasedFloor);
        }
Example #18
0
        /// <summary>
        /// Add text to the current cell
        /// </summary>
        /// <param name="inText">Text of the cell</param>
        /// <returns>id of the created pdf object</returns>
        public int AddText(string inText)
        {
            while (inText.Length > 0 && Char.IsWhiteSpace(inText[inText.Length - 1]))
            {
                inText = inText.Remove(inText.Length - 1, 1);
            }

            string theRect = mDoc.Rect.String;

            mDoc.Rect.Inset(CellPadding, CellPadding);
            PageNumber = RowTop.PageNr;
            int id = mDoc.AddText(inText);

            int theDrawn = 0;

            if (id > 0)
            {
                theDrawn = mDoc.GetInfoInt(id, "Characters");
            }
            if (theDrawn < inText.Length)
            {
                if (id != 0)
                {
                    mDoc.Delete(id);
                }
                if (mRowPositions.Length >= 2)
                {
                    mRowPositions[mRowPositions.Length - 1].Bottom.PosY
                        = mRowPositions[mRowPositions.Length - 2].Bottom.PosY;
                }

                MoveRowToNextPage();
                mDoc.Rect.String = theRect;
                mDoc.Rect.Top    = RowTop.PosY;
                AddText(inText);
            }
            else
            {
                XRect drawnRect = new XRect();
                drawnRect.String = SaveRowObject(id, inText);

                PagePos thePos = new PagePos(this);
                thePos.PosY = (double)(mDoc.Pos.Y - mDoc.FontSize);
                if (thePos < RowBottom)
                {
                    RowBottom = thePos;
                }

                mDoc.Rect.String = theRect;
            }

            return(id);
        }
        // This is to support raw geometry being sent to Revit (eg from rhino, gh, autocad...)
        public ApplicationPlaceholderObject DirectShapeToNative(Brep brep, BuiltInCategory cat = BuiltInCategory.OST_GenericModel)
        {
            // if it comes from GH it doesn't have an applicationId, the use the hash id
            if (brep.applicationId == null)
            {
                brep.applicationId = brep.id;
            }

            var docObj = GetExistingElementByApplicationId(brep.applicationId);

            //just create new one
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var catId   = Doc.Settings.Categories.get_Item(cat).Id;
            var revitDs = DB.DirectShape.CreateElement(Doc, catId);

            revitDs.ApplicationId     = brep.applicationId;
            revitDs.ApplicationDataId = Guid.NewGuid().ToString();
            revitDs.Name = "Brep " + brep.applicationId;

            try
            {
                var solid = BrepToNative(brep);
                if (solid == null)
                {
                    throw new SpeckleException("Could not convert brep to native");
                }
                revitDs.SetShape(new List <GeometryObject> {
                    solid
                });
            }
            catch (Exception e)
            {
                ConversionErrors.Add(new Exception(e.Message));
                var mesh = MeshToNative(brep.displayMesh);
                revitDs.SetShape(mesh);
            }

            return(new ApplicationPlaceholderObject {
                applicationId = brep.applicationId, ApplicationGeneratedId = revitDs.UniqueId, NativeObject = revitDs
            });
        }
Example #20
0
        public ApplicationPlaceholderObject SpaceSeparationLineToNative(SpaceSeparationLine speckleCurve)
        {
            var docObj    = GetExistingElementByApplicationId(speckleCurve.applicationId);
            var baseCurve = CurveToNative(speckleCurve.baseCurve);

            // try update existing (update model curve geometry curve based on speckle curve)
            if (docObj != null)
            {
                try
                {
                    var  docCurve    = docObj as DB.ModelCurve;
                    var  revitGeom   = docCurve.GeometryCurve;
                    var  speckleGeom = baseCurve.get_Item(0);
                    bool fullOverlap = speckleGeom.Intersect(revitGeom) == SetComparisonResult.Equal;
                    if (!fullOverlap)
                    {
                        docCurve.SetGeometryCurve(speckleGeom, false);
                    }
                    Report.Log($"Updated SpaceSeparationLine {docCurve.Id}");
                    return(new ApplicationPlaceholderObject()
                    {
                        applicationId = speckleCurve.applicationId, ApplicationGeneratedId = docCurve.UniqueId, NativeObject = docCurve
                    });
                }
                catch
                {
                    //delete and try to create new line as fallback
                    Doc.Delete(docObj.Id);
                }
            }

            try
            {
                var res = Doc.Create.NewSpaceBoundaryLines(NewSketchPlaneFromCurve(baseCurve.get_Item(0), Doc), baseCurve, Doc.ActiveView).get_Item(0);
                Report.Log($"Created SpaceSeparationLine {res.Id}");
                return(new ApplicationPlaceholderObject()
                {
                    applicationId = speckleCurve.applicationId, ApplicationGeneratedId = res.UniqueId, NativeObject = res
                });
            }
            catch (Exception)
            {
                throw (new Exception("Space separation line creation failed\nView is not valid for space separation line creation."));
            }
        }
Example #21
0
        public List <ApplicationPlaceholderObject> DetailCurveToNative(DetailCurve speckleCurve)
        {
            var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var placeholders = new List <ApplicationPlaceholderObject>();
            var crvEnum      = CurveToNative(speckleCurve.baseCurve).GetEnumerator();

            while (crvEnum.MoveNext() && crvEnum.Current != null)
            {
                var            baseCurve  = crvEnum.Current as DB.Curve;
                DB.DetailCurve revitCurve = null;
                try
                {
                    revitCurve = Doc.Create.NewDetailCurve(Doc.ActiveView, baseCurve);
                }
                catch (Exception)
                {
                    throw (new Exception($"Detail curve creation failed\nView is not valid for detail curve creation."));
                }

                var lineStyles  = revitCurve.GetLineStyleIds();
                var lineStyleId = lineStyles.FirstOrDefault(x => Doc.GetElement(x).Name == speckleCurve.lineStyle);
                if (lineStyleId != null)
                {
                    revitCurve.LineStyle = Doc.GetElement(lineStyleId);
                }
                placeholders.Add(new ApplicationPlaceholderObject()
                {
                    applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
                });
                Report.Log($"Created DetailCurve {revitCurve.Id}");
            }

            return(placeholders);
        }
Example #22
0
        // This is to support raw geometry being sent to Revit (eg from rhino, gh, autocad...)
        public ApplicationPlaceholderObject ModelCurveToNative(ICurve speckleLine)
        {
            // if it comes from GH it doesn't have an applicationId, the use the hash id
            if ((speckleLine as Base).applicationId == null)
            {
                (speckleLine as Base).applicationId = (speckleLine as Base).id;
            }

            var docObj    = GetExistingElementByApplicationId((speckleLine as Base).applicationId);
            var baseCurve = CurveToNative(speckleLine).get_Item(0);

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            DB.ModelCurve revitCurve = Doc.Create.NewModelCurve(baseCurve, NewSketchPlaneFromCurve(baseCurve));
            return(new ApplicationPlaceholderObject()
            {
                applicationId = (speckleLine as Base).applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
            });
        }
Example #23
0
        public ApplicationPlaceholderObject DetailCurveToNative(DetailCurve speckleCurve)
        {
            var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId);

            //TODO: support polybline/polycurve lines
            var baseCurve = CurveToNative(speckleCurve.baseCurve).get_Item(0);

            //delete and re-create line
            //TODO: check if can be modified
            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }
            DB.DetailCurve revitCurve = null;
            try
            {
                revitCurve = Doc.Create.NewDetailCurve(Doc.ActiveView, baseCurve);
            }
            catch (Exception)
            {
                ConversionErrors.Add(new Error("Detail curve creation failed", $"View is not valid for detail curve creation."));
                throw;
            }

            var lineStyles  = revitCurve.GetLineStyleIds();
            var lineStyleId = lineStyles.FirstOrDefault(x => Doc.GetElement(x).Name == speckleCurve.lineStyle);

            if (lineStyleId != null)
            {
                revitCurve.LineStyle = Doc.GetElement(lineStyleId);
            }
            return(new ApplicationPlaceholderObject()
            {
                applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve
            });
        }
Example #24
0
        public async Task RemoveBlankPages()
        {
            //ImageOperation op = null;
            for (int i = theDoc.PageCount; i > 0; i--)
            {
                theDoc.PageNumber = i;

                //get the pdf content
                //op = new ImageOperation(theDoc);
                //op.PageContents.AddPages();
                //var imageCollection = op.GetImageProperties();
                string textContent = theDoc.GetText("Text");

                //delete the page if it is blank
                //&& imageCollection.Count == 0)
                if (string.IsNullOrEmpty(textContent))
                {
                    theDoc.Delete(theDoc.Page);
                }
            }
            await Task.FromResult(0);

            return;
        }
Example #25
0
        public static Opening ToNative(this Shaft myShaft)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(myShaft.ApplicationId, myShaft.Type);

            var shaftCurves = new CurveArray();
            var segments    = GetSegmentList(myShaft.baseCurve);

            foreach (var x in segments)
            {
                shaftCurves.Append(x);
            }

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            var bottomLevel = myShaft.bottomLevel.ToNative();
            var topLevel    = myShaft.topLevel.ToNative();

            var revitShaft = Doc.Create.NewOpening(bottomLevel, topLevel, shaftCurves);

            return(revitShaft);
        }
        protected Doc ItemAnalysisToPdfDoc(PdfRenderSettings settings = null)
        {
            if (settings == null) settings = new PdfRenderSettings();

            StringWriter sw = new StringWriter();
            HtmlTextWriter w = new HtmlTextWriter(sw);
            reportHeaderDiv.Controls.Add(LoadPDFHeaderInfo());
            barGraphLevelsContainerDiv.Controls.Add(LoadBarGraphLevels());
            barGraphPDFContainerDiv.Controls.Add(LoadBarGraphs());
            contentDiv.RenderControl(w);
            string result_html = sw.GetStringBuilder().ToString();

            int topOffset = settings.HeaderHeight > 0 ? settings.HeaderHeight : 0;
            int bottomOffset = settings.FooterHeight > 0 ? settings.FooterHeight : 0;

            Doc doc = new Doc();
            doc.HtmlOptions.HideBackground = true;
            doc.HtmlOptions.PageCacheEnabled = false;
            doc.HtmlOptions.UseScript = true;
            doc.HtmlOptions.Timeout = 36000;
            doc.HtmlOptions.BreakZoneSize = 100;    // I experiemented with this being 99% instead of 100%, but you end up with passages getting cut off in unflattering ways. This may lead to more blank space... but I think it's the lessor of evils
            doc.HtmlOptions.ImageQuality = 70;

            doc.MediaBox.String = "0 0 " + settings.PageWidth + " " + settings.PageHeight;
            doc.Rect.String = settings.LeftMargin + " " + (0 + bottomOffset).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + (settings.PageHeight - topOffset).ToString();
            doc.HtmlOptions.AddTags = true;
            doc.SetInfo(0, "ApplyOnLoadScriptOnceOnly", "1");

            List<int> forms = new List<int>();

            int theID = doc.AddImageHtml(result_html);

            while (true)
            {
                if (!doc.Chainable(theID))
                    break;
                doc.Page = doc.AddPage();
                theID = doc.AddImageToChain(theID);
                string[] tagIds = doc.HtmlOptions.GetTagIDs(theID);
                if (tagIds.Length > 0 && tagIds[0] == "test_header")
                    forms.Add(doc.PageNumber);					// By using GetTagIDs to find if a test header ended up on this page, we can determine whether the page needs a header

                if (settings.PossibleForcedBreaks)
                {		// only want to take the performance hit if there's a change we're forcing breaks
                    if (String.IsNullOrEmpty(doc.GetText("Text")))
                    {		// WSH Found situation where after I added page break always for multi-form, one test that was already breaking properly, added an extra page that was blank between forms. Almost like some amount of HTML had been put there, even though it wasn't any real text. By checking to make sure there is some actual text on page, we can avoid that problem
                        doc.Delete(doc.Page);
                    }
                }
            }

            if (settings.HeaderHeight > 0 && !String.IsNullOrEmpty(settings.HeaderText))
            {
                /*HttpServerUtility Server = HttpContext.Current.Server;
                headerText = Server.HtmlDecode(headerText);*/
                Doc headerDoc = new Doc();

                headerDoc.MediaBox.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                headerDoc.Rect.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                headerDoc.VPos = 0.5;
                int headerID = headerDoc.AddImageHtml(settings.HeaderText);

                if (!String.IsNullOrEmpty(settings.HeaderText))
                {
                    int form_ref = 0;
                    for (int i = 1; i <= doc.PageCount; i++)
                    {
                        if (form_ref < forms.Count && forms[form_ref] == i)
                        {
                            form_ref++;
                        }
                        else
                        {
                            if (i > 1 || settings.ShowHeaderOnFirstPage)
                            {
                                doc.PageNumber = i;
                                doc.Rect.String = settings.LeftMargin + " " + (settings.PageHeight - settings.HeaderHeight).ToString() + " " + (settings.PageWidth - settings.RightMargin).ToString() + " " + settings.PageHeight;	//LEFT, BOTTOM,WIDTH, HEIGHT
                                doc.VPos = 0.5;

                                theID = doc.AddImageDoc(headerDoc, 1, null);
                                theID = doc.AddImageToChain(theID);
                            }
                        }
                    }
                }
            }

            for (int i = 1; i <= doc.PageCount; i++)
            {
                doc.PageNumber = i;
                doc.Flatten();
            }
            return doc;
        }
Example #27
0
        public List <ApplicationPlaceholderObject> GridLineToNative(GridLine speckleGridline)
        {
            var revitGrid = GetExistingElementByApplicationId(speckleGridline.applicationId) as Grid;
            var curve     = CurveToNative(speckleGridline.baseLine).get_Item(0);

            //delete and re-create line
            //TODO: check if can be modified
            if (revitGrid != null)
            {
                if (revitGrid.IsCurved)
                {
                    Doc.Delete(revitGrid.Id); //not sure how to modify arc grids
                }
                else
                {
                    //dim's magic from 1.0
                    var oldStart = revitGrid.Curve.GetEndPoint(0);
                    var oldEnd   = revitGrid.Curve.GetEndPoint(1);

                    var newStart = curve.GetEndPoint(0);
                    var newEnd   = curve.GetEndPoint(1);

                    var translate = newStart.Subtract(oldStart);
                    ElementTransformUtils.MoveElement(Doc, revitGrid.Id, translate);

                    var currentDirection = revitGrid.Curve.GetEndPoint(0).Subtract(revitGrid.Curve.GetEndPoint(1)).Normalize();
                    var newDirection     = newStart.Subtract(newEnd).Normalize();

                    var angle = newDirection.AngleTo(currentDirection);

                    if (angle > 0.00001)
                    {
                        var crossProd = newDirection.CrossProduct(currentDirection).Z;
                        ElementTransformUtils.RotateElement(Doc, revitGrid.Id, Autodesk.Revit.DB.Line.CreateUnbound(newStart, XYZ.BasisZ), crossProd < 0 ? angle : -angle);
                    }

                    try
                    {
                        revitGrid.SetCurveInView(DatumExtentType.Model, Doc.ActiveView, Line.CreateBound(newStart, newEnd));
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Failed to set grid endpoints.");
                    }
                }
            }

            //create the grid
            if (revitGrid == null)
            {
                if (curve is Arc a)
                {
                    revitGrid = Grid.Create(Doc, a);
                }
                else if (curve is Line l)
                {
                    revitGrid = Grid.Create(Doc, l);
                }
                else
                {
                    throw new Speckle.Core.Logging.SpeckleException("Curve type not supported for Grid: " + curve.GetType().FullName);
                }
            }

            //name must be unique, too much faff
            //revitGrid.Name = speckleGridline.label;

            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject
                {
                    applicationId          = speckleGridline.applicationId,
                    ApplicationGeneratedId = revitGrid.UniqueId,
                    NativeObject           = revitGrid
                }
            };


            return(placeholders);
        }
Example #28
0
        public String gerarRelatorioPDF(string cdaEmpCadastro, string cpfCnpj, string cdaQuestionarioEmpresa, string protocolo, string estado, string categoria, Boolean comentarios, Int32 programaId, Int32 turmaId, Int32 avaliador, Int32 intro, Boolean EnviaEmail, Page page)
        {
            if (avaliador == 0)
            {
                new BllQuestionarioEmpresa().AlterarSomenteFlagLeitura(StringUtils.ToInt(cdaQuestionarioEmpresa), true);
            }

            Session.Timeout      = 13000;
            Server.ScriptTimeout = 13000;

            string caminhoFisicoRelatorios = ConfigurationManager.AppSettings["caminhoFisicoRelatorios"];
            string caminhoPaginaRelatorio  = ConfigurationManager.AppSettings["caminhoPaginaRelatorio"];

            try
            {
                string[] files = Directory.GetFiles(caminhoFisicoRelatorios);
                foreach (string file in files)
                {
                    if (!File.GetCreationTime(file).ToShortDateString().Equals(DateTime.Now.ToShortDateString()))
                    {
                        File.Delete(file);
                    }
                }
            }
            catch { }
            string c = "";

            try
            {
                int chave = 0;
                if (comentarios)
                {
                    chave = 1;
                }

                //if (programaId == 3)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2008"];
                //}
                //else if (programaId == 4)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2009"];
                //}
                //else if (programaId == 7)
                //{
                //    caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorioAutoavaliacao"];
                //}

                Doc theDoc = new Doc();
                theDoc.SetInfo(0, "License", "bc8b5c07da69df2b6c476901f513aa8b89ff6d8ce56a16797802be20da7348078ab9ae58bd6c483b");
                theDoc.HtmlOptions.Timeout = 30000000;


                String link = this.getDominio(page) + caminhoPaginaRelatorio + "?CDA_EMP_CADASTRO=" + cdaEmpCadastro + "&TX_CPF_CNPJ=" + cpfCnpj + "&Chave=" + chave + "&Avaliador=" + avaliador + "&Intro=" + intro + "&CEA_QUESTIONARIO_EMPRESA=" + cdaQuestionarioEmpresa + "&Protocolo=" + protocolo + "&turmaId=" + turmaId + "&programaId=" + programaId;

                if (estado != null)
                {
                    link = link + "&naoMostraComentarioJuiz=1";
                }
                else if (page.Request["naoMostraComentarioJuiz"] != null && page.Request["naoMostraComentarioJuiz"].Equals("1"))
                {
                    link = link + "&naoMostraComentarioJuiz=1";
                }
                int theID = theDoc.AddImageUrl(link, true, 1000, true);
                while (true)
                {
                    theDoc.FrameRect();
                    if (!theDoc.Chainable(theID))
                    {
                        break;
                    }
                    theDoc.Page = theDoc.AddPage();
                    theID       = theDoc.AddImageToChain(theID);
                }

                for (int i = 1; i <= theDoc.PageCount; i++)
                {
                    theDoc.PageNumber = i;
                    theDoc.Flatten();
                }

                String ArquivoNome = protocolo + "_" + DateTime.Now.Ticks + ".pdf";
                String CaminhoPDF  = caminhoFisicoRelatorios + ArquivoNome;

                CaminhoPDF = Server.MapPath(CaminhoPDF);

                theDoc.Save(CaminhoPDF);
                theDoc.HtmlOptions.PageCacheClear();
                theDoc.Clear();

                theDoc.Delete(theID);
                theDoc.Dispose();

                theDoc = null;
                GC.Collect();


                Thread.Sleep(5000);

                if (EnviaEmail)
                {
                    //WebUtils.EnviaEmail(Request.QueryString["EmailContato"], "Relatório de AutoAvaliação", new System.Text.StringBuilder(), CaminhoPDF);
                    return(CaminhoPDF);
                    //ClientScript.RegisterClientScriptBlock(Page.GetType(), "closeWindow", "window.close();", true);
                }
                else
                {
                    //Response.Redirect(getDominio(this.Page) + "/Relatorios/" + ArquivoNome);
                    //return null;
                    return("/Relatorios/" + ArquivoNome);
                }
            }
            catch (Exception ex)
            {
                //Response.Write(ex.ToString());
                throw ex;
            }
            return(null);
        }
Example #29
0
        //TODO: delete temp family after creation
        //TODO: allow updates to family..?

        //NOTE: FaceWalls cannot be updated, as well we can't seem to get their base face easily so they are ToNatvie only
        public List <ApplicationPlaceholderObject> FaceWallToNative(RevitFaceWall speckleWall)
        {
            if (speckleWall.surface == null)
            {
                throw new Speckle.Core.Logging.SpeckleException("Only surface based FaceWalls are currently supported.");
            }

            // Cannot update revit wall to new mass face
            FaceWall revitWall = GetExistingElementByApplicationId(speckleWall.applicationId) as DB.FaceWall;

            if (revitWall != null)
            {
                Doc.Delete(revitWall.Id);
            }

            var famPath = Path.Combine(Doc.Application.FamilyTemplatePath, @"Conceptual Mass\Metric Mass.rft");

            if (!File.Exists(famPath))
            {
                ConversionErrors.Add(new Error {
                    message = $"Could not find file Metric Mass.rft"
                });
                return(null);
            }

            var    tempMassFamilyPath = CreateMassFamily(famPath, speckleWall.surface, speckleWall.applicationId);
            Family fam;

            Doc.LoadFamily(tempMassFamilyPath, new FamilyLoadOption(), out fam);
            var symbol = Doc.GetElement(fam.GetFamilySymbolIds().First()) as FamilySymbol;

            symbol.Activate();

            try
            {
                File.Delete(tempMassFamilyPath);
            }
            catch
            {
            }

            var mass = Doc.Create.NewFamilyInstance(XYZ.Zero, symbol, DB.Structure.StructuralType.NonStructural);
            // NOTE: must set a schedule level!
            // otherwise the wall creation will fail with "Could not create a face wall."
            var level = new FilteredElementCollector(Doc)
                        .WhereElementIsNotElementType()
                        .OfCategory(BuiltInCategory.OST_Levels) // this throws a null error if user tries to recieve stream in a file with no levels
                        .ToElements().FirstOrDefault();

            if (level == null) // create a new level at 0 if no levels could be retrieved from doc
            {
                level = Level.Create(Doc, 0);
            }

            TrySetParam(mass, BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM, level);

            //must regenerate before getting the elem geometry
            Doc.Regenerate();
            Reference faceRef = GetFaceRef(mass);

            var wallType = GetElementType <WallType>(speckleWall);

            if (!FaceWall.IsWallTypeValidForFaceWall(Doc, wallType.Id))
            {
                ConversionErrors.Add(new Error {
                    message = $"Wall type not valid for face wall ${speckleWall.applicationId}."
                });
                return(null);
            }

            revitWall = null;
            try
            {
                revitWall = DB.FaceWall.Create(Doc, wallType.Id, GetWallLocationLine(speckleWall.locationLine), faceRef);
            }
            catch (Exception e)
            { }

            if (revitWall == null)
            {
                ConversionErrors.Add(new Error {
                    message = $"Failed to create face wall ${speckleWall.applicationId}."
                });
                return(null);
            }

            Doc.Delete(mass.Id);

            SetInstanceParameters(revitWall, speckleWall);

            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject
                {
                    applicationId          = speckleWall.applicationId,
                    ApplicationGeneratedId = revitWall.UniqueId,
                    NativeObject           = revitWall
                }
            };

            var hostedElements = SetHostedElements(speckleWall, revitWall);

            placeholders.AddRange(hostedElements);

            return(placeholders);
        }
Example #30
0
        public ApplicationPlaceholderObject OpeningToNative(BuiltElements.Opening speckleOpening)
        {
            var baseCurves = CurveToNative(speckleOpening.outline);

            var docObj = GetExistingElementByApplicationId(speckleOpening.applicationId);

            if (docObj != null)
            {
                Doc.Delete(docObj.Id);
            }

            DB.Opening revitOpening = null;

            switch (speckleOpening)
            {
            case RevitWallOpening rwo:
            {
                if (CurrentHostElement as Wall == null)
                {
                    throw new Exception($"Hosted wall openings require a host wall");
                }
                var points = (rwo.outline as Polyline).points.Select(x => PointToNative(x)).ToList();
                revitOpening = Doc.Create.NewOpening(CurrentHostElement as Wall, points[0], points[2]);
                break;
            }

            case RevitVerticalOpening rvo:
            {
                if (CurrentHostElement == null)
                {
                    throw new Exception($"Hosted vertical openings require a host family");
                }
                revitOpening = Doc.Create.NewOpening(CurrentHostElement, baseCurves, true);
                break;
            }

            case RevitShaft rs:
            {
                var bottomLevel = LevelToNative(rs.bottomLevel);
                var topLevel    = LevelToNative(rs.topLevel);
                revitOpening = Doc.Create.NewOpening(bottomLevel, topLevel, baseCurves);
                TrySetParam(revitOpening, BuiltInParameter.WALL_USER_HEIGHT_PARAM, rs.height);

                break;
            }

            default:
                ConversionErrors.Add(new Error("Cannot create Opening", "Opening type not supported"));
                throw new Exception("Opening type not supported");
            }


            if (speckleOpening is RevitOpening ro)
            {
                SetInstanceParameters(revitOpening, ro);
            }

            return(new ApplicationPlaceholderObject {
                NativeObject = revitOpening, applicationId = speckleOpening.applicationId, ApplicationGeneratedId = revitOpening.UniqueId
            });
        }
Example #31
0
        //TODO: might need to clean this up and split the ConversionLog.Addic by beam, FI, etc...
        public List <ApplicationPlaceholderObject> FamilyInstanceToNative(BuiltElements.Revit.FamilyInstance speckleFi)
        {
            DB.FamilySymbol familySymbol = GetElementType <FamilySymbol>(speckleFi);
            XYZ             basePoint    = PointToNative(speckleFi.basePoint);

            DB.Level          level          = LevelToNative(speckleFi.level);
            DB.FamilyInstance familyInstance = null;
            var isUpdate = false;
            //try update existing
            var docObj = GetExistingElementByApplicationId(speckleFi.applicationId);

            if (docObj != null)
            {
                try
                {
                    var revitType = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                    // if family changed, tough luck. delete and let us create a new one.
                    if (familySymbol.FamilyName != revitType.FamilyName)
                    {
                        Doc.Delete(docObj.Id);
                    }
                    else
                    {
                        familyInstance = (DB.FamilyInstance)docObj;

                        //NOTE: updating an element location is quite buggy in Revit!
                        //Let's say the first time an element is created its base point/curve is @ 10m and the Level is @ 0m
                        //the element will be created @ 0m
                        //but when this element is updated (let's say with no changes), it will jump @ 10m (unless there is a level change)!
                        //to avoid this behavior we're always setting the previous location Z coordinate when updating an element
                        //this means the Z coord of an element will only be set by its Level
                        //and by additional parameters as sill height, base offset etc
                        (familyInstance.Location as LocationPoint).Point = new XYZ(basePoint.X, basePoint.Y, (familyInstance.Location as LocationPoint).Point.Z);

                        // check for a type change
                        if (speckleFi.type != null && speckleFi.type != revitType.Name)
                        {
                            familyInstance.ChangeTypeId(familySymbol.Id);
                        }

                        TrySetParam(familyInstance, BuiltInParameter.FAMILY_LEVEL_PARAM, level);
                        TrySetParam(familyInstance, BuiltInParameter.FAMILY_BASE_LEVEL_PARAM, level);
                    }
                    isUpdate = true;
                }
                catch
                {
                    //something went wrong, re-create it
                }
            }

            //create family instance
            if (familyInstance == null)
            {
                //If the current host element is not null, it means we're coming from inside a nested conversion.
                if (CurrentHostElement != null)
                {
                    familyInstance = Doc.Create.NewFamilyInstance(basePoint, familySymbol, CurrentHostElement, level, StructuralType.NonStructural);
                }
                //Otherwise, proceed as normal.
                else
                {
                    familyInstance = Doc.Create.NewFamilyInstance(basePoint, familySymbol, level, StructuralType.NonStructural);
                }
            }

            //required for face flipping to work!
            Doc.Regenerate();

            if (familyInstance.CanFlipHand && speckleFi.handFlipped != familyInstance.HandFlipped)
            {
                familyInstance.flipHand();
            }

            if (familyInstance.CanFlipFacing && speckleFi.facingFlipped != familyInstance.FacingFlipped)
            {
                familyInstance.flipFacing();
            }

            // NOTE: do not check for the CanRotate prop as it doesn't work (at least on some families I tried)!
            // some point based families don't have a rotation, so keep this in a try catch
            try
            {
                if (speckleFi.rotation != (familyInstance.Location as LocationPoint).Rotation)
                {
                    var axis = DB.Line.CreateBound(new XYZ(basePoint.X, basePoint.Y, 0), new XYZ(basePoint.X, basePoint.Y, 1000));
                    (familyInstance.Location as LocationPoint).Rotate(axis, speckleFi.rotation - (familyInstance.Location as LocationPoint).Rotation);
                }
            }
            catch { }

            SetInstanceParameters(familyInstance, speckleFi);

            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject
                {
                    applicationId          = speckleFi.applicationId,
                    ApplicationGeneratedId = familyInstance.UniqueId,
                    NativeObject           = familyInstance
                }
            };

            Report.Log($"{(isUpdate ? "Updated" : "Created")} FamilyInstance ({familyInstance.Category.Name}) {familyInstance.Id}");
            return(placeholders);
        }
        //Method to remove blank pages from the pdf
        protected void RemoveBlankPages(Doc pdf)
        {
            for (int i = pdf.PageCount; i > 0; i--)
            {
                pdf.PageNumber = i;

                //get the pdf content
                string textContent = pdf.GetText("Text");

                //delete the page if it is blank
                if (string.IsNullOrEmpty(textContent))
                { pdf.Delete(pdf.Page); }
            }
        }