Example #1
0
        /// <summary>
        /// Get all 3D views in current document
        /// </summary>
        private void Get3DViews()
        {
            m_view3DList = new List <Autodesk.Revit.DB.Element>();
            FilteredElementCollector collector = new FilteredElementCollector(m_document);
            var query = from elem in collector.OfClass(typeof(View3D))
                        let viewElem = elem as View3D
                                       where null != viewElem && !viewElem.IsTemplate
                                       select elem;

            m_view3DList = query.ToList <Element>();
            if (m_view3DList.Count == 0)
            {
                //View3D view3D = m_document.Create.NewView3D(new Autodesk.Revit.DB.XYZ (0, 0, 1));
                IList <Element> viewFamilyTypes = new FilteredElementCollector(m_document).OfClass(typeof(ViewFamilyType)).ToElements();
                ElementId       View3DId        = new ElementId(-1);
                foreach (Element e in viewFamilyTypes)
                {
                    if (e.Name == "3D View")
                    {
                        View3DId = e.Id;
                    }
                }
                View3D            view3D            = View3D.CreateIsometric(m_document, View3DId);
                ViewOrientation3D viewOrientation3D = new ViewOrientation3D(new XYZ(1, 1, -1), new XYZ(0, 0, 1), new XYZ(0, 1, 0));
                view3D.SetOrientation(viewOrientation3D);
                view3D.SaveOrientation();
                m_view3DList.Add(view3D);
            }
        }
Example #2
0
        public void getOrientation()
        {
            Document doc         = this.ActiveUIDocument.Document;
            View     currentView = this.ActiveUIDocument.ActiveView;

            View3D            v3D     = (currentView as View3D);
            ViewOrientation3D vOrient = v3D.GetOrientation();

            XYZ eye     = vOrient.EyePosition;
            XYZ forward = vOrient.ForwardDirection;
            XYZ up      = vOrient.UpDirection;

            String eyex = (eye.X).ToString();
            String eyey = (eye.Y).ToString();
            String eyez = (eye.Z).ToString();

            String eyeXYZ = "eye orientation is \nX: " + eyex + "\nY: " + eyey + "\nZ: " + eyez;

            String forwardx = (forward.X).ToString();
            String forwardy = (forward.Y).ToString();
            String forwardz = (forward.Z).ToString();

            String forwardXYZ = "forward orientation is\nX: " + forwardx + "\nY: " + forwardy + "\nZ: " + forwardz;

            String upx = (up.X).ToString();
            String upy = (up.Y).ToString();
            String upz = (up.Z).ToString();

            String upXYZ = "up orientation is \nX: " + upx + "\nY: " + upy + "\nZ: " + upz;

            TaskDialog.Show("View Orientation", eyeXYZ + "\n" + forwardXYZ + "\n" + upXYZ);
        }
Example #3
0
        /// <summary>
        /// Create a Revit 3D View
        /// </summary>
        /// <param name="orient"></param>
        /// <param name="name"></param>
        /// <param name="isPerspective"></param>
        /// <returns></returns>
        protected static Autodesk.Revit.DB.View3D Create3DView(ViewOrientation3D orient, string name, bool isPerspective)
        {
            // (sic) From the Dynamo legacy implementation
            var viewFam = DocumentManager.Instance.ElementsOfType <ViewFamilyType>()
                          .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);

            if (viewFam == null)
            {
                throw new Exception("There is no three dimensional view family int he document");
            }

            Autodesk.Revit.DB.View3D view;
            if (isPerspective)
            {
                view = Autodesk.Revit.DB.View3D.CreatePerspective(Document, viewFam.Id);
            }
            else
            {
                view = Autodesk.Revit.DB.View3D.CreateIsometric(Document, viewFam.Id);
            }

            view.SetOrientation(orient);
            view.SaveOrientationAndLock();


            view.Name = CreateUniqueViewName(name);

            return(view);
        }
Example #4
0
        public static View3D Create3DView(ViewOrientation3D orient, string name, bool isPerspective)
        {
            //http://adndevblog.typepad.com/aec/2012/05/viewplancreate-method.html

            IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new
                                                           FilteredElementCollector(dynRevitSettings.Doc.Document).OfClass(typeof(ViewFamilyType))
                                                           let type = elem as ViewFamilyType
                                                                      where type.ViewFamily == ViewFamily.ThreeDimensional
                                                                      select type;

            //create a new view
            View3D view = isPerspective ?
                          View3D.CreatePerspective(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id) :
                          View3D.CreateIsometric(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id);

            view.SetOrientation(orient);
            view.SaveOrientationAndLock();
            try
            {
                //will fail if name is not unique
                view.Name = name;
            }
            catch
            {
                view.Name = CreateUniqueViewName(name);
            }


            return(view);
        }
        // We need to create a 3dview because the when we open a new project file a 3d view does not exist and raytracers need 3dviews
        private View3D createView3d()
        {
            FilteredElementCollector collector0 = new FilteredElementCollector(_doc).OfClass(typeof(View3D));

            foreach (View3D item in collector0)
            {
                if (!item.IsTemplate)
                {
                    return(item);
                }
            }
            FilteredElementCollector collector1 = new FilteredElementCollector(_doc);

            collector1 = collector1.OfClass(typeof(ViewFamilyType));
            IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in collector1 let vftype = elem as ViewFamilyType where (vftype.ViewFamily == ViewFamily.ThreeDimensional) select vftype;

            using (Transaction createView3D = new Transaction(_doc))
            {
                createView3D.Start("Create 3D View");
                View3D view3D = View3D.CreateIsometric(_doc, viewFamilyTypes.First <ViewFamilyType>().Id);
                if (null != view3D)
                {
                    XYZ eye     = new XYZ(10, 10, 10);
                    XYZ up      = new XYZ(0, 1, 1);
                    XYZ forward = new XYZ(0, 1, -1);
                    ViewOrientation3D viewOrientation3D = new ViewOrientation3D(eye, up, forward);
                    view3D.SetOrientation(viewOrientation3D);
                    view3D.Name = "RayTracer View";
                }
                createView3D.Commit();
                return(view3D);
            }
        }
        /// <summary>
        /// Create perspective view with camera settings
        /// matching the Forge Viewer.
        /// </summary>
        void CreatePerspectiveViewMatchingCamera(
            Document doc,
            XYZ camera_position,
            XYZ target)
        {
            using (var trans = new Transaction(doc))
            {
                trans.Start("Map Forge Viewer Camera");

                ViewFamilyType typ
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .Cast <ViewFamilyType>()
                      .First <ViewFamilyType>(
                          x => x.ViewFamily.Equals(
                              ViewFamily.ThreeDimensional));

                // Create a new perspective 3D view

                View3D view3D = View3D.CreatePerspective(
                    doc, typ.Id);

                Random rnd = new Random();
                view3D.Name = string.Format("Camera{0}",
                                            rnd.Next());

                // By default, the 3D view uses a default
                // orientation. Change that by creating and
                // setting up a suitable ViewOrientation3D.

                //var position = new XYZ( -15.12436009332275,
                //  -8.984616232971192, 4.921260089050291 );

                var up = XYZ.BasisZ;

                //var target = new XYZ( -15.02436066552734,
                //  -8.984211875061035, 4.921260089050291 );

                var sightDir = target.Subtract(camera_position).Normalize();

                var orientation = new ViewOrientation3D(
                    camera_position, up, sightDir);

                view3D.SetOrientation(orientation);

                // Turn off the far clip plane, etc.

                view3D.LookupParameter("Far Clip Active")
                .Set(0);

                view3D.LookupParameter("Crop Region Visible")
                .Set(1);

                view3D.LookupParameter("Crop View")
                .Set(1);

                trans.Commit();
            }
        }
Example #7
0
        public void ViewCreate()
        {
            Document doc = this.ActiveUIDocument.Document;



            // get a ViewFamilyType for a 3D View. created new instance of ViewFamilYType calle 'viewFamilyType'

            ViewFamilyType viewFamilyType = (from v in new FilteredElementCollector(doc).
                                             // Creates new filteredElementCollector to select all ViewFamilyTypes
                                             OfClass(typeof(ViewFamilyType)).

                                             Cast <ViewFamilyType>()

                                             where v.ViewFamily == ViewFamily.ThreeDimensional

                                             select v).First();


            Categories categories = doc.Settings.Categories;

            Category dim = categories.get_Item(BuiltInCategory.OST_Dimensions);

            Category line = categories.get_Item(BuiltInCategory.OST_Lines);

            XYZ eye = new XYZ(100, 100, 100);

            XYZ forward = new XYZ(-1, 1, -1);

            XYZ up = new XYZ(-1, 1, 2);

            ViewOrientation3D vOrient = new ViewOrientation3D(eye, up, forward);


            using (Transaction t = new Transaction(doc, "Create view"))

            {
                t.Start();

                View3D view = View3D.CreateIsometric(doc, viewFamilyType.Id);

                view.get_Parameter(BuiltInParameter.MODEL_GRAPHICS_STYLE)
                .Set(4);


                view.SetOrientation(vOrient);

                view.HideCategoryTemporary(dim.Id);

                view.HideCategoryTemporary(line.Id);

                view.SaveOrientationAndLock();


                t.Commit();
            }
        }
        /// <summary>
        /// Return relevant 3D view information (from
        /// Revit API documentation help file  sample).
        /// </summary>
        static string GetView3dInfo(View3D view3d)
        {
            string message = "3D View: ";

            // The position of the camera and view direction.

            ViewOrientation3D ori = view3d.GetOrientation();
            XYZ peye     = ori.EyePosition;
            XYZ vforward = ori.ForwardDirection;
            XYZ vup      = ori.UpDirection;

            message += string.Format(
                "\r\nCamera position: {0}"
                + "\r\nView direction: {1}"
                + "\r\nUp direction: {2}",
                Util.PointString(peye),
                Util.PointString(vforward),
                Util.PointString(vup));

            // Identifies whether the view is a perspective view.

            if (view3d.IsPerspective)
            {
                message += "\r\nThe view is a perspective view.";
            }

            // The section box of the 3D view can cut the model.

            if (view3d.IsSectionBoxActive)
            {
                BoundingBoxXYZ sectionBox = view3d.GetSectionBox();

                // Note that the section box can be rotated
                // and transformed. So the min/max corners
                // coordinates relative to the model must be
                // computed via the transform.

                Transform trf = sectionBox.Transform;

                XYZ max = sectionBox.Max; // Maximum coordinates (upper-right-front corner of the box before transform is applied).
                XYZ min = sectionBox.Min; // Minimum coordinates (lower-left-rear corner of the box before transform is applied).

                // Transform the min and max to model coordinates

                XYZ maxInModelCoords = trf.OfPoint(max);
                XYZ minInModelCoords = trf.OfPoint(min);

                message += "\r\nView has an active section box: ";

                message += "\r\n'Maximum' coordinates: "
                           + Util.PointString(maxInModelCoords);

                message += "\r\n'Minimum' coordinates: "
                           + Util.PointString(minInModelCoords);
            }
            return(message);
        }
Example #9
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            View3D view      = null;
            var    eye       = (XYZ)((Value.Container)args[0]).Item;
            var    userUp    = (XYZ)((Value.Container)args[1]).Item;
            var    direction = (XYZ)((Value.Container)args[2]).Item;
            var    name      = ((Value.String)args[3]).Item;

            XYZ side;

            if (direction.IsAlmostEqualTo(userUp) || direction.IsAlmostEqualTo(userUp.Negate()))
            {
                side = XYZ.BasisZ.CrossProduct(direction);
            }
            else
            {
                side = userUp.CrossProduct(direction);
            }
            XYZ up = side.CrossProduct(direction);

            //need to reverse the up direction to get the
            //proper orientation - there might be a better way to handle this
            var orient = new ViewOrientation3D(eye, -up, direction);

            if (this.Elements.Any())
            {
                Element e;
                if (dynUtils.TryGetElement(this.Elements[0], typeof(View3D), out e))
                {
                    view = (View3D)e;
                    if (!view.ViewDirection.IsAlmostEqualTo(direction))
                    {
                        view.Unlock();
                        view.SetOrientation(orient);
                        view.SaveOrientationAndLock();
                    }
                    if (view.Name != null && view.Name != name)
                    {
                        view.Name = CreateUniqueViewName(name);
                    }
                }
                else
                {
                    //create a new view
                    view        = dynViewBase.Create3DView(orient, name, false);
                    Elements[0] = view.Id;
                }
            }
            else
            {
                view = Create3DView(orient, name, false);
                Elements.Add(view.Id);
            }

            return(Value.NewContainer(view));
        }
Example #10
0
        ///调整三维视图的角度
        ///
        public static void Modify3DViewDirection(View3D view)
        {
            XYZ eyePosition  = new XYZ();
            XYZ upDirection  = XYZ.BasisZ;
            XYZ forDirection = XYZ.BasisY;

            ViewOrientation3D orientation = new ViewOrientation3D(eyePosition, upDirection, forDirection);

            view.SetOrientation(orientation);
        }
Example #11
0
        public static View View3D(this Document document, XYZ eye, XYZ target, double horizontalFieldOfView, double viewRatio = 0.5625, string viewName = null, ElementId viewTemplateId = null, ViewDetailLevel viewDetailLevel = ViewDetailLevel.Coarse)
        {
            XYZ normal       = (target - eye).Normalize();
            XYZ planarEye    = new XYZ(eye.X, eye.Y, 0);
            XYZ planarTarget = new XYZ(target.X, target.Y, 0);
            XYZ planarNormal = (planarTarget - planarEye).Normalize();

            //get vertical and horizontal angle
            double verticalAngle   = (XYZ.BasisZ.AngleTo(normal) - Math.PI / 2) * (-1);
            double horizontalAngle = XYZ.BasisX.AngleOnPlaneTo(planarNormal, XYZ.BasisZ);

            //create view orientation
            ViewOrientation3D viewOrientation3D = new ViewOrientation3D(eye, CombineHorizontalWithVerticalAngles(horizontalAngle, verticalAngle + Math.PI / 2), CombineHorizontalWithVerticalAngles(horizontalAngle, verticalAngle));

            //information can be found here
            //https://knowledge.autodesk.com/support/revit-products/learn-explore/caas/CloudHelp/cloudhelp/2014/ENU/Revit/files/GUID-A7FA8DBC-830E-482D-9B66-147399524442-htm.html

            //rotate center point to the right side, representing HFOV start point
            double    angleToRotate = Math.PI / 2;
            Transform t1            = Transform.CreateRotationAtPoint(XYZ.BasisZ, angleToRotate * -1, target);
            XYZ       rotate        = target.Add((horizontalFieldOfView / 2) * (planarNormal * -1));
            XYZ       hfovLeft      = t1.OfPoint(rotate);
            XYZ       bottomLeft    = hfovLeft.Add(((viewRatio * horizontalFieldOfView) / 2) * (viewOrientation3D.UpDirection * -1));

            //for the right
            Transform t2        = Transform.CreateRotationAtPoint(XYZ.BasisZ, angleToRotate, target);
            XYZ       hfovRight = t2.OfPoint(rotate);
            XYZ       topRight  = hfovRight.Add(((viewRatio * horizontalFieldOfView) / 2) * viewOrientation3D.UpDirection);

            //lines for top and bottom
            Line topLine    = Line.CreateBound(topRight, eye);
            Line bottomLine = Line.CreateBound(bottomLeft, eye);

            // to calculate bb max/min offset we need to perform an inverse regression estimate using y=A+B/x
            double a = 0.9995538525; //constant for THIS inverse regression
            double b = -0.08573511;  //constant for THIS inverse regression
            //get line-based element's length
            double cameraLength  = planarEye.DistanceTo(planarTarget);
            double evaluateLines = a + (b / cameraLength);

            //creates plane to project point at and retrieve cropbox.min
            BH.oM.Geometry.Plane backClippingPlane = BH.Engine.Geometry.Create.Plane(BH.Revit.Engine.Core.Convert.PointFromRevit(target), BH.Revit.Engine.Core.Convert.VectorFromRevit(viewOrientation3D.ForwardDirection));
            BH.oM.Geometry.Point pointToProject    = BH.Revit.Engine.Core.Convert.PointFromRevit(bottomLine.Evaluate(evaluateLines, true));
            BH.oM.Geometry.Point bbBhomMin         = backClippingPlane.ClosestPoint(pointToProject);
            XYZ bbMin = BH.Revit.Engine.Core.Convert.ToRevit(bbBhomMin);
            XYZ bbMax = topLine.Evaluate(evaluateLines, true);

            BoundingBoxXYZ boundingBox3DCone = new BoundingBoxXYZ();

            boundingBox3DCone.Max = bbMax;
            boundingBox3DCone.Min = bbMin;

            return(View3D(document, viewName, boundingBox3DCone, viewOrientation3D, viewTemplateId, viewDetailLevel));
        }
Example #12
0
        /// <summary>
        /// returns XYZ and ZOOM/FOV value
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="viewport"></param>
        /// <returns></returns>
        public Tuple <ViewOrientation3D, double, string, string> GetViewCoordinates(Document doc, VisualizationInfo viewport)
        {
            string type = ""; //change if i force ortho mode
            double zoom = 0;  //fov or worldscale

            XYZ CameraDirection = new XYZ();
            XYZ CameraUpVector  = new XYZ();
            XYZ CameraViewPoint = new XYZ();

            //retrive the force perspective value


            // IS ORTHOGONAL
            if (viewport.OrthogonalCamera != null)
            {
                if (viewport.OrthogonalCamera.ViewToWorldScale == null || viewport.OrthogonalCamera.CameraViewPoint == null || viewport.OrthogonalCamera.CameraUpVector == null || viewport.OrthogonalCamera.CameraDirection == null)
                {
                    return(null);
                }
                type            = "OrthogonalCamera";
                zoom            = UnitUtils.ConvertToInternalUnits(viewport.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                CameraDirection = GetXYZ(viewport.OrthogonalCamera.CameraDirection.X, viewport.OrthogonalCamera.CameraDirection.Y, viewport.OrthogonalCamera.CameraDirection.Z);
                CameraUpVector  = GetXYZ(viewport.OrthogonalCamera.CameraUpVector.X, viewport.OrthogonalCamera.CameraUpVector.Y, viewport.OrthogonalCamera.CameraUpVector.Z);
                CameraViewPoint = GetXYZ(viewport.OrthogonalCamera.CameraViewPoint.X, viewport.OrthogonalCamera.CameraViewPoint.Y, viewport.OrthogonalCamera.CameraViewPoint.Z);
            }

            else if (viewport.PerspectiveCamera != null)
            {
                if (viewport.PerspectiveCamera.FieldOfView == null || viewport.PerspectiveCamera.CameraViewPoint == null || viewport.PerspectiveCamera.CameraUpVector == null || viewport.PerspectiveCamera.CameraDirection == null)
                {
                    return(null);
                }

                type = "PerspectiveCamera";
                zoom = viewport.PerspectiveCamera.FieldOfView;
                double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                double factor = z1 - z;

                CameraDirection = GetXYZ(viewport.PerspectiveCamera.CameraDirection.X, viewport.PerspectiveCamera.CameraDirection.Y, viewport.PerspectiveCamera.CameraDirection.Z);
                CameraUpVector  = GetXYZ(viewport.PerspectiveCamera.CameraUpVector.X, viewport.PerspectiveCamera.CameraUpVector.Y, viewport.PerspectiveCamera.CameraUpVector.Z);
                XYZ oldO = GetXYZ(viewport.PerspectiveCamera.CameraViewPoint.X, viewport.PerspectiveCamera.CameraViewPoint.Y, viewport.PerspectiveCamera.CameraViewPoint.Z);
                CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
            }
            else
            {
                return(null);
            }
            // CHAGE VALUES ACCORDING TO BASEPOINT
            //THIS WAS the one with DOC
            ViewOrientation3D orient3d = ConvertBasePoint(CameraViewPoint, CameraDirection, CameraUpVector, true);

            return(new Tuple <ViewOrientation3D, double, string, string>(orient3d, zoom, type, "New View"));
        }
Example #13
0
        /// <summary>
        /// Set the orientation of the view
        /// </summary>
        /// <param name="orient"></param>
        protected void InternalSetOrientation(ViewOrientation3D orient)
        {
            if (this.InternalView3D.ViewDirection.IsAlmostEqualTo(orient.ForwardDirection) &&
                this.InternalView3D.Origin.IsAlmostEqualTo(orient.EyePosition))
            {
                return;
            }

            this.InternalView3D.Unlock();
            this.InternalView3D.SetOrientation(orient);
            this.InternalView3D.SaveOrientationAndLock();
        }
 private static void CreatePerspectiveFromPlan(UIDocument uiDoc, View currentView)
 {
     var view = UserView.ActiveUIView(uiDoc, currentView);
     var eye = UserView.GetMiddleOfActiveViewWindow(view);
     var up = new XYZ(0, 1, 0);
     var forward = new XYZ(0, 0, -1);
     var viewOrientation3D = new ViewOrientation3D(eye, up, forward);
     var view3D = View3D.CreatePerspective(uiDoc.Document, UserView.Get3DViewFamilyTypes(uiDoc.Document).First().Id);
     view3D.SetOrientation(new ViewOrientation3D(viewOrientation3D.EyePosition,
         viewOrientation3D.UpDirection,
         viewOrientation3D.ForwardDirection));
     UserView.ApplySectionBoxToView(UserView.ViewExtentsBoundingBox(view), view3D);
     view3D.Name = UserView.GetNewViewName(uiDoc.Document, view3D);
     view3D.ViewTemplateId = ElementId.InvalidElementId;
     viewOrientation3D.Dispose();
 }
Example #15
0
        public DB.View ViewToNative(View3D speckleView)
        {
            // get view3d type
            ViewFamilyType viewType = new FilteredElementCollector(Doc)
                                      .WhereElementIsElementType().OfClass(typeof(ViewFamilyType))
                                      .ToElements().Cast <ViewFamilyType>()
                                      .Where(o => o.ViewFamily == ViewFamily.ThreeDimensional)
                                      .FirstOrDefault();

            // get orientation
            var up      = new XYZ(speckleView.upDirection.x, speckleView.upDirection.y, speckleView.upDirection.z).Normalize(); //unit vector
            var forward = new XYZ(speckleView.forwardDirection.x, speckleView.forwardDirection.y, speckleView.forwardDirection.z).Normalize();

            if (Math.Round(up.DotProduct(forward), 3) != 0) // will throw error if vectors are not perpendicular
            {
                return(null);
            }
            var orientation = new ViewOrientation3D(PointToNative(speckleView.origin), up, forward);

            // create view
            var docObj = GetExistingElementByApplicationId(speckleView.applicationId);

            DB.View3D view = null;
            if (speckleView.isOrthogonal)
            {
                view = DB.View3D.CreateIsometric(Doc, viewType.Id);
            }
            else
            {
                view = DB.View3D.CreatePerspective(Doc, viewType.Id);
            }

            // set props
            view.SetOrientation(orientation);
            view.SaveOrientationAndLock();

            if (view != null && view.IsValidObject)
            {
                SetInstanceParameters(view, speckleView);
            }
            view = SetViewParams(view, speckleView);

            // set name last due to duplicate name errors
            view.Name = EditViewName(speckleView.name, "SpeckleView");

            return(view);
        }
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private static void CreatePerspectiveFromSection(UIDocument udoc, View sectionView)
        {
            UIView            view    = ActiveUIView(udoc, sectionView);
            XYZ               eye     = GetMiddleOfActiveViewWindow(view);
            XYZ               up      = new XYZ(0, 0, 1);
            XYZ               forward = new XYZ(0, 0, -1);
            ViewOrientation3D v       = new ViewOrientation3D(eye, up, forward);

            using (var t = new Transaction(udoc.Document))
            {
                t.Start("Create perspective view");
                View3D np = View3D.CreatePerspective(udoc.Document, Get3DViewFamilyTypes(udoc.Document).First().Id);
                np.SetOrientation(new ViewOrientation3D(v.EyePosition, v.UpDirection, v.ForwardDirection));
                ApplySectionBoxToView(SectionViewExtentsBoundingBox(view), np);
                t.Commit();
            }
        }
        /// <summary>
        /// Prompt the user for an eye position and a
        /// view direction, the set the view orientation
        /// accordingly.
        /// </summary>
        public JumpToPosition(
            View3D view,
            IWin32Window owner_window_handle)
        {
            Document doc = view.Document;

            JumpForm form = new JumpForm();

            DialogResult rslt = form.ShowDialog(
                owner_window_handle);

            if (DialogResult.OK == rslt)
            {
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Jump to Position");

                    XYZ eye     = form.Eye;
                    XYZ forward = form.Viewdir;

                    XYZ left = Util.IsVertical(forward)
            ? -XYZ.BasisX
            : XYZ.BasisZ.CrossProduct(forward);

                    XYZ up = forward.CrossProduct(left);

                    // Setting ùp`to the Z axis, XYZ.BasisZ, throws
                    // Autodesk.Revit.Exceptions.ArgumentsInconsistentException:
                    // The vectors upDirection and forwardDirection
                    // are not perpendicular.

                    ViewOrientation3D orientation
                        = new ViewOrientation3D(eye, up, forward);

                    view.SetOrientation(orientation);

                    RefreshView(view);

                    tx.Commit();
                }
            }
        }
Example #18
0
        ViewOrientation3D GetOrientationFor(
            double yaw_degrees,
            double pitch_degrees)
        {
            // Yaw = 0 means north; rotate by 90 degrees,
            // so that north is 90 degrees instead

            if (Util.IsEqual(270, yaw_degrees) ||
                270 > yaw_degrees)
            {
                yaw_degrees += 90.0;
            }

            double angle_in_xy_plane = yaw_degrees * Math.PI / 180.0;
            double angle_up_down     = pitch_degrees * Math.PI / 180.0;

            // Eye position is arbitrary, since it is defined
            // by fitting the view to the selected element

            XYZ eye = new XYZ(
                Math.Cos(angle_in_xy_plane),
                Math.Sin(angle_in_xy_plane),
                Math.Cos(angle_up_down));

            XYZ forward = -eye;

            XYZ left = Util.IsVertical(forward)
        ? -XYZ.BasisX
        : XYZ.BasisZ.CrossProduct(forward);

            XYZ up = forward.CrossProduct(left);

            // Setting ùp`to the Z axis, XYZ.BasisZ, throws
            // Autodesk.Revit.Exceptions.ArgumentsInconsistentException:
            // The vectors upDirection and forwardDirection
            // are not perpendicular.

            ViewOrientation3D orientation
                = new ViewOrientation3D(eye, up, forward);

            return(orientation);
        }
 /// <summary>
 /// Get all 3D views in current document
 /// </summary>
 private void Get3DViews()
 {
     m_view3DList = new List<Autodesk.Revit.DB.Element>();
     FilteredElementCollector collector = new FilteredElementCollector(m_document);
     var query = from elem in collector.OfClass(typeof(View3D))
                 let viewElem = elem as View3D
                 where null != viewElem && !viewElem.IsTemplate
                 select elem;
     m_view3DList = query.ToList<Element>();
     if (m_view3DList.Count == 0)
     {
         //View3D view3D = m_document.Create.NewView3D(new Autodesk.Revit.DB.XYZ (0, 0, 1));
         IList<Element> viewFamilyTypes = new FilteredElementCollector(m_document).OfClass(typeof(ViewFamilyType)).ToElements();
         ElementId View3DId = new ElementId(-1);
         foreach (Element e in viewFamilyTypes)
         {
             if (e.Name == "3D View")
             {
                 View3DId = e.Id;
             }
         }
         View3D view3D = View3D.CreateIsometric(m_document, View3DId);
         ViewOrientation3D viewOrientation3D = new ViewOrientation3D(new XYZ(1, 1, -1), new XYZ(0, 0, 1), new XYZ(0, 1, 0));
         view3D.SetOrientation(viewOrientation3D);
         view3D.SaveOrientation();
         m_view3DList.Add(view3D);
     }
 }
Example #20
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            if (doc.ActiveView is View3D)
            {
                string filename = doc.PathName;
                if (0 == filename.Length)
                {
                    filename = doc.Title;
                }
                if (null == _output_folder_path)
                {
                    // Sometimes the command fails if the file is
                    // detached from central and not saved locally

                    try
                    {
                        _output_folder_path = Path.GetDirectoryName(
                            filename);
                    }
                    catch
                    {
                        TaskDialog.Show("Folder not found",
                                        "Please save the file and run the command again.");
                        return(Result.Failed);
                    }
                }

                // Dialog to ask the user if they want to
                // choose which parameters to export or just
                // export them all.

                TaskDialog td = new TaskDialog("Ask user to filter parameters");
                td.Title             = "Filter parameters";
                td.CommonButtons     = TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes;
                td.MainInstruction   = "Do you want to filter the parameters of the objects to be exported?";
                td.MainContent       = "Click Yes and you will be able to select parameters for each category in the next window";
                td.AllowCancellation = true;
                td.VerificationText  = "Check this to include type properties";
                TaskDialogResult tdResult = td.Show();

                if (td.WasVerificationChecked())
                {
                    includeT = true;
                }
                else
                {
                    includeT = false;
                }

                if (tdResult == TaskDialogResult.Yes)
                {
                    // Filter the properties
                    filterElementParameters(doc, includeT);
                    _filterParameters = true;
                    if (ParameterFilter.status == "cancelled")
                    {
                        ParameterFilter.status = "";
                        return(Result.Cancelled);
                    }
                }
                else
                {
                    _filterParameters = false;
                }


                ViewOrientation3D vo = ((View3D)doc.ActiveView).GetOrientation();

                // Save file

                filename = Path.GetFileName(filename) + ".js";

                if (SelectFile(ref _output_folder_path,
                               ref filename))
                {
                    filename = Path.Combine(_output_folder_path,
                                            filename);

                    ExportView3D(doc.ActiveView as View3D,
                                 filename);

                    return(Result.Succeeded);
                }
                return(Result.Cancelled);
            }
            else
            {
                Util.ErrorMsg(
                    "You must be in a 3D view to export.");
            }
            return(Result.Failed);
        }
Example #21
0
        private void AddCameraActor(
            View3D InView3D,
            CameraInfo InViewCamera
            )
        {
            // Create a new Datasmith camera actor.
            // Hash the Datasmith camera actor name to shorten it.
            string HashedName = FDatasmithFacadeElement.GetStringHash(InView3D.UniqueId);
            FDatasmithFacadeActorCamera CameraActor = new FDatasmithFacadeActorCamera(HashedName);

            CameraActor.SetLabel(InView3D.Name);

            if (InView3D.Category != null)
            {
                // Set the Datasmith camera actor layer to be the 3D view category name.
                CameraActor.SetLayer(InView3D.Category.Name);
            }

            // Gets the current non-saved orientation of the 3D view.
            ViewOrientation3D ViewOrientation = InView3D.GetOrientation();

            // Set the world position (in right-handed Z-up coordinates) of the Datasmith camera actor.
            XYZ CameraPosition = ViewOrientation.EyePosition;

            CameraActor.SetCameraPosition((float)CameraPosition.X, (float)CameraPosition.Y, (float)CameraPosition.Z);

            // Set the world rotation of the Datasmith camera actor with
            // the camera world forward and up vectors (in right-handed Z-up coordinates).
            XYZ CameraForward = ViewOrientation.ForwardDirection;
            XYZ CameraUp      = ViewOrientation.UpDirection;

            CameraActor.SetCameraRotation((float)CameraForward.X, (float)CameraForward.Y, (float)CameraForward.Z, (float)CameraUp.X, (float)CameraUp.Y, (float)CameraUp.Z);

            // When the 3D view camera is not available, an orthographic view should be assumed.
            if (InViewCamera != null)
            {
                // Compute the aspect ratio (width/height) of the Revit 3D view camera, where
                // HorizontalExtent is the distance between left and right planes on the target plane,
                // VerticalExtent is the distance between top and bottom planes on the target plane.
                float AspectRatio = (float)(InViewCamera.HorizontalExtent / InViewCamera.VerticalExtent);

                // Set the aspect ratio of the Datasmith camera.
                CameraActor.SetAspectRatio(AspectRatio);

                if (InView3D.IsPerspective)
                {
                    // Set the sensor width of the Datasmith camera.
                    CameraActor.SetSensorWidth((float)(InViewCamera.HorizontalExtent * /* millimeters per foot */ 304.8));

                    // Get the distance from eye point along view direction to target plane.
                    // This value is appropriate for perspective views only.
                    float TargetDistance = (float)InViewCamera.TargetDistance;

                    // Set the Datasmith camera focus distance.
                    CameraActor.SetFocusDistance(TargetDistance);

                    // Set the Datasmith camera focal length.
                    CameraActor.SetFocalLength(TargetDistance * /* millimeters per foot */ 304.8F);
                }
            }

            // Add the camera actor to the Datasmith scene.
            DatasmithScene.AddActor(CameraActor);

            DirectLink?.MarkForExport(InView3D);
            DirectLink?.CacheElement(RevitDocument, InView3D, new FDocumentData.FBaseElementData(CameraActor, null, DocumentDataStack.Peek()));
        }
Example #22
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            if (SaveCommand.Scale.Equals(0))
            {
                TaskDialog ts1 = new TaskDialog("Camera parameters")
                {
                    MainContent = "Please save parameters before restoring."
                };

                ts1.Show();
                return(Result.Succeeded);
            }

            // Perform restoring
            var orientation = new ViewOrientation3D(SaveCommand.EyePosition, SaveCommand.UpDirection, SaveCommand.ForwardDirection);
            var view3D      = doc.ActiveView as View3D;

            if (view3D == null || view3D.IsPerspective)
            {
                TaskDialog ts = new TaskDialog("Incorrect View selected")
                {
                    MainContent = "Please, select 3D Orthographic view."
                };

                ts.Show();
                return(Result.Succeeded);
            }

            view3D.SetOrientation(orientation);

            using (Transaction Trans = new Transaction(doc))
            {
                Trans.Start("Restoring camera parameters");
                {
                    try
                    {
                        view3D.SetOrientation(orientation);
                        double scale = SaveCommand.Scale;

                        XYZ corner1 = SaveCommand.EyePosition + SaveCommand.UpDirection * scale - uidoc.ActiveView.RightDirection * scale;
                        XYZ corner2 = SaveCommand.EyePosition - SaveCommand.UpDirection * scale + uidoc.ActiveView.RightDirection * scale;

                        uidoc.GetOpenUIViews().FirstOrDefault(t => t.ViewId == view3D.Id)?.ZoomAndCenterRectangle(corner2, corner1);
                        uidoc.UpdateAllOpenViews();

                        TaskDialog ts = new TaskDialog("View restored")
                        {
                            MainContent = "The camera parameters have been successfully restored."
                        };

                        ts.Show();

                        Trans.Commit();
                        return(Result.Succeeded);
                    }
                    catch (System.Exception)
                    {
                        Trans.RollBack();
                        return(Result.Failed);
                    }
                }
            }
        }
Example #23
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            View3D view = null;
            var eye = (XYZ)((Value.Container)args[0]).Item;
            var target = (XYZ)((Value.Container)args[1]).Item;
            var name = ((Value.String)args[2]).Item;
            var extents = ((Value.Container)args[3]).Item;
            var isolate = Convert.ToBoolean(((Value.Number)args[4]).Item);

            var globalUp = XYZ.BasisZ;
            var direction = target.Subtract(eye);
            var up = direction.CrossProduct(globalUp).CrossProduct(direction);
            var orient = new ViewOrientation3D(eye, up, direction);

            if (this.Elements.Any())
            {
                if (dynUtils.TryGetElement(this.Elements[0], out view))
                {
                    if (!view.ViewDirection.IsAlmostEqualTo(direction) || !view.Origin.IsAlmostEqualTo(eye))
                    {
                        view.Unlock();
                        view.SetOrientation(orient);
                        view.SaveOrientationAndLock();
                    }

                    if (!view.Name.Equals(name))
                        view.Name = ViewBase.CreateUniqueViewName(name);
                }
                else
                {
                    //create a new view
                    view = ViewBase.Create3DView(orient, name, isPerspective);
                    Elements[0] = view.Id;
                }
            }
            else
            {
                view = Create3DView(orient, name, isPerspective);
                Elements.Add(view.Id);
            }

            var fec = dynRevitUtils.SetupFilters(dynRevitSettings.Doc.Document);

            if (isolate)
            {
                view.CropBoxActive = true;

                var element = extents as Element;
                if (element != null)
                {
                    var e = element;

                    var all = fec.ToElements();
                    var toHide =
                        fec.ToElements().Where(x => !x.IsHidden(view) && x.CanBeHidden(view) && x.Id != e.Id).Select(x => x.Id).ToList();

                    if (toHide.Count > 0)
                        view.HideElements(toHide);

                    dynRevitSettings.Doc.Document.Regenerate();

                    Debug.WriteLine(string.Format("Eye:{0},Origin{1}, BBox_Origin{2}, Element{3}",
                        eye.ToString(), view.Origin.ToString(), view.CropBox.Transform.Origin.ToString(), (element.Location as LocationPoint).Point.ToString()));

                    //http://wikihelp.autodesk.com/Revit/fra/2013/Help/0000-API_Deve0/0039-Basic_In39/0067-Views67/0069-The_View69
                    if (isPerspective)
                    {
                        var farClip = view.get_Parameter("Far Clip Active");
                        farClip.Set(0);
                    }
                    else
                    {
                        //http://adndevblog.typepad.com/aec/2012/05/set-crop-box-of-3d-view-that-exactly-fits-an-element.html
                        var pts = new List<XYZ>();

                        ParseElementGeometry(element, pts);

                        var bounding = view.CropBox;
                        var transInverse = bounding.Transform.Inverse;
                        var transPts = pts.Select(transInverse.OfPoint).ToList();

                        //ingore the Z coordindates and find
                        //the max X ,Y and Min X, Y in 3d view.
                        double dMaxX = 0, dMaxY = 0, dMinX = 0, dMinY = 0;

                        //geom.XYZ ptMaxX, ptMaxY, ptMinX,ptMInY;
                        //coorresponding point.
                        bool bFirstPt = true;
                        foreach (var pt1 in transPts)
                        {
                            if (true == bFirstPt)
                            {
                                dMaxX = pt1.X;
                                dMaxY = pt1.Y;
                                dMinX = pt1.X;
                                dMinY = pt1.Y;
                                bFirstPt = false;
                            }
                            else
                            {
                                if (dMaxX < pt1.X)
                                    dMaxX = pt1.X;
                                if (dMaxY < pt1.Y)
                                    dMaxY = pt1.Y;
                                if (dMinX > pt1.X)
                                    dMinX = pt1.X;
                                if (dMinY > pt1.Y)
                                    dMinY = pt1.Y;
                            }
                        }

                        bounding.Max = new XYZ(dMaxX, dMaxY, bounding.Max.Z);
                        bounding.Min = new XYZ(dMinX, dMinY, bounding.Min.Z);
                        view.CropBox = bounding;
                    }
                }
                else
                {
                    var xyz = extents as BoundingBoxXYZ;
                    if (xyz != null)
                    {
                        view.CropBox = xyz;
                    }
                }

                view.CropBoxVisible = false;
            }
            else
            {
                view.UnhideElements(fec.ToElementIds());
                view.CropBoxActive = false;
            }

            return Value.NewContainer(view);
        }
Example #24
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // Save current 3D view
            var view3D = doc.ActiveView as View3D;

            if (view3D == null || view3D.IsPerspective)
            {
                TaskDialog ts = new TaskDialog("Incorrect View selected")
                {
                    MainContent = "Please, select 3D Orthographic view."
                };

                ts.Show();
                return(Result.Succeeded);
            }

            // Get viewOrientation3D
            ViewOrientation3D viewOrientation3D = view3D.GetOrientation();

            ForwardDirection = viewOrientation3D.ForwardDirection;
            UpDirection      = viewOrientation3D.UpDirection;
            var rightDirection = ForwardDirection.CrossProduct(UpDirection);

            EyePosition = viewOrientation3D.EyePosition;

            IList <UIView> views       = uidoc.GetOpenUIViews();
            UIView         currentView = views.FirstOrDefault(t => t.ViewId == view3D.Id);

            //Corners of the active UI view
            if (currentView == null)
            {
                return(Result.Succeeded);
            }

            IList <XYZ> corners = currentView.GetZoomCorners();
            XYZ         corner1 = corners[0];
            XYZ         corner2 = corners[1];

            //center of the UI view
            double x          = (corner1.X + corner2.X) / 2;
            double y          = (corner1.Y + corner2.Y) / 2;
            double z          = (corner1.Z + corner2.Z) / 2;
            XYZ    viewCenter = new XYZ(x, y, z);

            EyePosition = viewCenter;

            // Calculate diagonal vector
            XYZ diagVector = corner1 - corner2;

            double height = 0.5 * Math.Abs(diagVector.DotProduct(UpDirection));
            double width  = 0.5 * Math.Abs(diagVector.DotProduct(rightDirection));

            Scale = Math.Min(height, width);

            TaskDialog ts1 = new TaskDialog("Camera parameters")
            {
                MainContent = "Camera parameters have been successfully saved."
            };

            ts1.Show();
            return(Result.Succeeded);
        }
Example #25
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            View3D view = null;
            XYZ eye = (XYZ)((Value.Container)args[0]).Item;
            XYZ userUp = (XYZ)((Value.Container)args[1]).Item;
            XYZ direction = (XYZ)((Value.Container)args[2]).Item;

            XYZ side = new XYZ();
            if (direction.IsAlmostEqualTo(userUp) || direction.IsAlmostEqualTo(userUp.Negate()))
                side = XYZ.BasisZ.CrossProduct(direction);
            else
                side = userUp.CrossProduct(direction);
            XYZ up = side.CrossProduct(direction);

            if (this.Elements.Any())
            {
                Element e;
                if (dynUtils.TryGetElement(this.Elements[0], typeof(View3D), out e))
                {
                    view = e as View3D;
                    if (!view.ViewDirection.IsAlmostEqualTo(direction))
                    {
                        ViewOrientation3D orient = new ViewOrientation3D(eye, up, direction);
                        view.SetOrientation(orient);
                        view.SaveOrientationAndLock();
                        view.SetOrientation(orient);
                    }
                }
                else
                {
                    //create a new view
                    view = Create3DView(eye, up, direction);
                    Elements[0] = view.Id;
                }
            }
            else
            {
                view = Create3DView(eye, up, direction);
                Elements.Add(view.Id);
            }

            return Value.NewContainer(view);
        }
Example #26
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            //expand scope of command arguments
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            //make sure we are in a 3D view
            if (doc.ActiveView is View3D)
            {
                //get the name of the active file, and strip off the extension
                string filename = Path.GetFileNameWithoutExtension(doc.PathName);
                if (0 == filename.Length)
                {
                    filename = doc.Title;
                }
                if (null == _output_folder_path)
                {
                    // Sometimes the command fails if the file is
                    // detached from central and not saved locally

                    try
                    {
                        _output_folder_path = Path.GetDirectoryName(
                            filename);
                    }
                    catch
                    {
                        TaskDialog.Show("Folder not found",
                                        "Please save the file and run the command again.");
                        return(Result.Failed);
                    }
                }

                // Show Export Settings UI
                ExportOptions opt = new ExportOptions();
                opt.ShowDialog();
                if (opt.userCancelled)
                {
                    return(Result.Cancelled);
                }

                if (opt.filterParameters)
                {
                    // Filter the properties
                    filterElementParameters(doc, opt.includeTypeParameters);
                    _filterParameters = true;
                    if (ParameterFilter.status == "cancelled")
                    {
                        ParameterFilter.status = "";
                        return(Result.Cancelled);
                    }
                }
                else
                {
                    _filterParameters = false;
                }

                if (ExportOptions.includeViews)
                {
                    // get all the 3D views in the project
                    UIDocument uiDoc  = uiapp.ActiveUIDocument;
                    Document   RvtDoc = uiDoc.Document;

                    cameraNames     = new List <string>();
                    cameraPositions = new List <string>();
                    cameraTargets   = new List <string>();

                    IEnumerable <Element>    views   = null;
                    FilteredElementCollector viewCol = new FilteredElementCollector(RvtDoc);

                    viewCol.OfClass(typeof(View3D));

                    foreach (View3D camera in viewCol)
                    {
                        try
                        {
                            if (camera.IsPerspective)
                            {
                                ViewOrientation3D vo = camera.GetOrientation();
                                cameraNames.Add(camera.Name);
                                cameraPositions.Add((-vo.EyePosition.X * 304.8).ToString() + "," + (vo.EyePosition.Z * 304.8).ToString() + "," + (vo.EyePosition.Y * 304.8).ToString());
                                cameraTargets.Add((-vo.ForwardDirection.X * 304.8).ToString() + "," + (vo.ForwardDirection.Z * 304.8).ToString() + "," + (vo.ForwardDirection.Y * 304.8).ToString());
                            }
                        }
                        catch { }
                    }
                }

                // Save file
                filename = Path.GetFileName(filename) + ".json";

                //Select output location UI.
                if (SelectFile(ref _output_folder_path, ref filename))
                {
                    //export the file
                    filename = Path.Combine(_output_folder_path,
                                            filename);

                    ExportView3D(doc.ActiveView as View3D,
                                 filename);

                    //tell the user we completed successfully
                    Success s = new Success();
                    s.ShowDialog();


                    //return success
                    return(Result.Succeeded);
                }
                return(Result.Cancelled);
            }
            else
            {
                Util.ErrorMsg(
                    "You must be in a 3D view to export.");
            }
            return(Result.Failed);
        }
Example #27
0
        public static View View3D(this Document document, string viewName = null, BoundingBoxXYZ boundingBoxXyz = null, ViewOrientation3D viewOrientation3D = null, ElementId viewTemplateId = null, ViewDetailLevel viewDetailLevel = ViewDetailLevel.Coarse)
        {
            //for information about a perspective boundingbox and its orientation see here:
            //https://knowledge.autodesk.com/support/revit-products/learn-explore/caas/CloudHelp/cloudhelp/2014/ENU/Revit/files/GUID-A7FA8DBC-830E-482D-9B66-147399524442-htm.html

            View3D result = null;

            ViewFamilyType vft = Query.ViewFamilyType(document, ViewFamily.ThreeDimensional);

            result = Autodesk.Revit.DB.View3D.CreatePerspective(document, vft.Id);

            Modify.SetViewDetailLevel(result, viewDetailLevel);

            if (!string.IsNullOrEmpty(viewName))
            {
                try
                {
#if (REVIT2018 || REVIT2019)
                    result.ViewName = viewName;
#else
                    result.Name = viewName;
#endif
                }
                catch
                {
                    BH.Engine.Reflection.Compute.RecordWarning("There is already a view named '" + viewName + "'." + " It has been named '" + result.Name + "' instead.");
                }
            }

            if (viewTemplateId != null)
            {
                try
                {
                    result.ViewTemplateId = viewTemplateId;
                }
                catch (Exception)
                {
                    BH.Engine.Reflection.Compute.RecordWarning("Could not apply the View Template of Id " + viewTemplateId + "'." + ". Please check if it's a valid ElementId.");
                }
            }

            if (viewOrientation3D != null)
            {
                try
                {
                    result.SetOrientation(viewOrientation3D);
                }
                catch (Exception)
                {
                    BH.Engine.Reflection.Compute.RecordWarning("Could not set the view's orientation in 3D due to unexpected values, please report this error.");
                }
            }

            if (boundingBoxXyz != null)
            {
                try
                {
                    //transform to view coordinates previously picked points
                    BoundingBoxXYZ bb        = result.get_BoundingBox(result);
                    Transform      transform = bb.Transform;

                    bb.Max = transform.Inverse.OfPoint(boundingBoxXyz.Max);
                    bb.Min = transform.Inverse.OfPoint(boundingBoxXyz.Min);

                    result.CropBox = bb;

                    //changes the view's far clip to the the eye and target line's length (x1.5 offset)
                    result.SetParameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR, boundingBoxXyz.Min.DistanceTo(boundingBoxXyz.Max) * 1.5);
                }
                catch (Exception)
                {
                    BH.Engine.Reflection.Compute.RecordWarning("Could not set the view's bounding box due to unexpected values, please report this error.");
                }
            }

            return(result);
        }
Example #28
0
        /// <summary>
        /// Create a Revit 3D View
        /// </summary>
        /// <param name="orient"></param>
        /// <param name="name"></param>
        /// <param name="isPerspective"></param>
        /// <returns></returns>
        protected static Autodesk.Revit.DB.View3D Create3DView(ViewOrientation3D orient, string name, bool isPerspective)
        {
            // (sic) From the Dynamo legacy implementation
            var viewFam = DocumentManager.Instance.ElementsOfType<ViewFamilyType>()
                .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);

            if (viewFam == null)
            {
                throw new Exception("There is no three dimensional view family int he document");
            }

            Autodesk.Revit.DB.View3D view;
            if (isPerspective)
            {
                view = Autodesk.Revit.DB.View3D.CreatePerspective(Document, viewFam.Id);
            }
            else
            {
                view = Autodesk.Revit.DB.View3D.CreateIsometric(Document, viewFam.Id);
            }

            view.SetOrientation(orient);
            view.SaveOrientationAndLock();

            try
            {
                //will fail if name is not unique
                view.Name = name;
            }
            catch
            {
                view.Name = CreateUniqueViewName(name);
            }


            return view;
        }
Example #29
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            View3D view    = null;
            var    eye     = (XYZ)((Value.Container)args[0]).Item;
            var    target  = (XYZ)((Value.Container)args[1]).Item;
            var    name    = ((Value.String)args[2]).Item;
            var    extents = ((Value.Container)args[3]).Item;
            var    isolate = Convert.ToBoolean(((Value.Number)args[4]).Item);

            var globalUp  = XYZ.BasisZ;
            var direction = target.Subtract(eye);
            var up        = direction.CrossProduct(globalUp).CrossProduct(direction);
            var orient    = new ViewOrientation3D(eye, up, direction);

            if (this.Elements.Any())
            {
                if (dynUtils.TryGetElement(this.Elements[0], out view))
                {
                    if (!view.ViewDirection.IsAlmostEqualTo(direction) || !view.Origin.IsAlmostEqualTo(eye))
                    {
                        view.Unlock();
                        view.SetOrientation(orient);
                        view.SaveOrientationAndLock();
                    }

                    if (!view.Name.Equals(name))
                    {
                        view.Name = ViewBase.CreateUniqueViewName(name);
                    }
                }
                else
                {
                    //create a new view
                    view        = ViewBase.Create3DView(orient, name, isPerspective);
                    Elements[0] = view.Id;
                }
            }
            else
            {
                view = Create3DView(orient, name, isPerspective);
                Elements.Add(view.Id);
            }

            var fec = dynRevitUtils.SetupFilters(dynRevitSettings.Doc.Document);

            if (isolate)
            {
                view.CropBoxActive = true;

                var element = extents as Element;
                if (element != null)
                {
                    var e = element;

                    var all    = fec.ToElements();
                    var toHide =
                        fec.ToElements().Where(x => !x.IsHidden(view) && x.CanBeHidden(view) && x.Id != e.Id).Select(x => x.Id).ToList();

                    if (toHide.Count > 0)
                    {
                        view.HideElements(toHide);
                    }

                    dynRevitSettings.Doc.Document.Regenerate();

                    Debug.WriteLine(string.Format("Eye:{0},Origin{1}, BBox_Origin{2}, Element{3}",
                                                  eye.ToString(), view.Origin.ToString(), view.CropBox.Transform.Origin.ToString(), (element.Location as LocationPoint).Point.ToString()));

                    //http://wikihelp.autodesk.com/Revit/fra/2013/Help/0000-API_Deve0/0039-Basic_In39/0067-Views67/0069-The_View69
                    if (isPerspective)
                    {
                        var farClip = view.get_Parameter("Far Clip Active");
                        farClip.Set(0);
                    }
                    else
                    {
                        //http://adndevblog.typepad.com/aec/2012/05/set-crop-box-of-3d-view-that-exactly-fits-an-element.html
                        var pts = new List <XYZ>();

                        ParseElementGeometry(element, pts);

                        var bounding     = view.CropBox;
                        var transInverse = bounding.Transform.Inverse;
                        var transPts     = pts.Select(transInverse.OfPoint).ToList();

                        //ingore the Z coordindates and find
                        //the max X ,Y and Min X, Y in 3d view.
                        double dMaxX = 0, dMaxY = 0, dMinX = 0, dMinY = 0;

                        //geom.XYZ ptMaxX, ptMaxY, ptMinX,ptMInY;
                        //coorresponding point.
                        bool bFirstPt = true;
                        foreach (var pt1 in transPts)
                        {
                            if (true == bFirstPt)
                            {
                                dMaxX    = pt1.X;
                                dMaxY    = pt1.Y;
                                dMinX    = pt1.X;
                                dMinY    = pt1.Y;
                                bFirstPt = false;
                            }
                            else
                            {
                                if (dMaxX < pt1.X)
                                {
                                    dMaxX = pt1.X;
                                }
                                if (dMaxY < pt1.Y)
                                {
                                    dMaxY = pt1.Y;
                                }
                                if (dMinX > pt1.X)
                                {
                                    dMinX = pt1.X;
                                }
                                if (dMinY > pt1.Y)
                                {
                                    dMinY = pt1.Y;
                                }
                            }
                        }

                        bounding.Max = new XYZ(dMaxX, dMaxY, bounding.Max.Z);
                        bounding.Min = new XYZ(dMinX, dMinY, bounding.Min.Z);
                        view.CropBox = bounding;
                    }
                }
                else
                {
                    var xyz = extents as BoundingBoxXYZ;
                    if (xyz != null)
                    {
                        view.CropBox = xyz;
                    }
                }

                view.CropBoxVisible = false;
            }
            else
            {
                view.UnhideElements(fec.ToElementIds());
                view.CropBoxActive = false;
            }

            return(Value.NewContainer(view));
        }
Example #30
0
        /// <summary>
        /// Set the orientation of the view
        /// </summary>
        /// <param name="orient"></param>
        protected void InternalSetOrientation( ViewOrientation3D orient)
        {
            if (this.InternalView3D.ViewDirection.IsAlmostEqualTo(orient.ForwardDirection) &&
                this.InternalView3D.Origin.IsAlmostEqualTo(orient.EyePosition)) return;

            this.InternalView3D.Unlock();
            this.InternalView3D.SetOrientation(orient);
            this.InternalView3D.SaveOrientationAndLock();
        }
Example #31
0
        /// <summary>
        /// Paint a solid in a new named view
        /// </summary>
        /// <param name="s">solid</param>
        /// <param name="viewName">Given the name of view</param>
        public void PaintSolid(Solid s, String viewName)
        {
            View view;

            if (!viewNameList.Contains(viewName))
            {
                IList <Element> viewFamilyTypes = new FilteredElementCollector(m_doc).OfClass(typeof(ViewFamilyType)).ToElements();
                ElementId       View3DId        = new ElementId(-1);
                foreach (Element e in viewFamilyTypes)
                {
                    if (e.Name == "3D View")
                    {
                        View3DId = e.Id;
                    }
                }

                //view = m_doc.Create.NewView3D(new XYZ(1, 1, 1));
                view = View3D.CreateIsometric(m_doc, View3DId);
                ViewOrientation3D viewOrientation3D = new ViewOrientation3D(new XYZ(1, -1, -1), new XYZ(1, 1, 1), new XYZ(1, 1, -2));
                (view as View3D).SetOrientation(viewOrientation3D);
                (view as View3D).SaveOrientation();
                view.Name = viewName;
                viewNameList.Add(viewName);
            }
            else
            {
                view = (((new FilteredElementCollector(m_doc).
                          OfClass(typeof(View))).Cast <View>()).
                        Where(e => e.Name == viewName)).First <View>();
            }

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);
            }

            if (SchemaId != -1)
            {
                IList <int> results = sfm.GetRegisteredResults();

                if (!results.Contains(SchemaId))
                {
                    SchemaId = -1;
                }
            }

            if (SchemaId == -1)
            {
                AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid" + viewName, "Description");

                AnalysisDisplayStyle displayStyle = AnalysisDisplayStyle.CreateAnalysisDisplayStyle(
                    m_doc,
                    "Real_Color_Surface" + viewName,
                    new AnalysisDisplayColoredSurfaceSettings(),
                    new AnalysisDisplayColorSettings(),
                    new AnalysisDisplayLegendSettings());

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                SchemaId = sfm.RegisterResult(resultSchema1);
            }

            FaceArray faces = s.Faces;
            Transform trf   = Transform.Identity;

            foreach (Face face in faces)
            {
                int idx = sfm.AddSpatialFieldPrimitive(face, trf);

                IList <UV>           uvPts   = null;
                IList <ValueAtPoint> valList = null;
                ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                FieldValues vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, SchemaId);
            }
        }
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        private VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Data.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Data.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist            = TL.DistanceTo(BR) / 2; //custom value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector      = TL.Subtract(BR);
                        double customZoomValue = (ProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new IssueTracker.Data.Component[collection.Count];
                    for (var i = 0; i < collection.Count; i++)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, collection.ElementAt(i));
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        ;
                        v.Components[i] = new Case.IssueTracker.Data.Component(doc.Application.VersionName, collection.ElementAt(i).ToString(), ifcguid);
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
Example #33
0
        //<summary>
        //Generate a VisualizationInfo of the current view
        //</summary>
        //<returns></returns>
        private VisualizationInfo GenerateViewpoint()
        {
            try
            {
                var uidoc = uiapp.ActiveUIDocument;
                var doc   = uidoc.Document;

                var v = new VisualizationInfo();

                //Corners of the active UI view
                var topLeft     = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                var bottomRight = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                //It's a 2D view
                //not supported by BCF, but I store it under a custom
                //fields using 2D coordinates and sheet id
                if (uidoc.ActiveView.ViewType != ViewType.ThreeD)
                {
                    v.SheetCamera = new SheetCamera
                    {
                        SheetID = uidoc.ActiveView.Id.IntegerValue,
                        TopLeft = new Point {
                            X = topLeft.X, Y = topLeft.Y, Z = topLeft.Z
                        },
                        BottomRight = new Point {
                            X = bottomRight.X, Y = bottomRight.Y, Z = bottomRight.Z
                        }
                    };
                }
                //It's a 3d view
                else
                {
                    var    viewCenter = new XYZ();
                    var    view3D     = (View3D)uidoc.ActiveView;
                    double zoomValue  = 1;
                    // it is a orthogonal view
                    if (!view3D.IsPerspective)
                    {
                        double x = (topLeft.X + bottomRight.X) / 2;
                        double y = (topLeft.Y + bottomRight.Y) / 2;
                        double z = (topLeft.Z + bottomRight.Z) / 2;
                        //center of the UI view
                        viewCenter = new XYZ(x, y, z);

                        //vector going from BR to TL
                        XYZ diagVector = topLeft.Subtract(bottomRight);
                        //lenght of the vector
                        double dist = topLeft.DistanceTo(bottomRight) / 2;

                        //ViewToWorldScale value
                        zoomValue = dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)).ToMeters();

                        // **** CUSTOM VALUE FOR TEKLA **** //
                        // calculated sperimentally, not sure why but it works
                        //if (UserSettings.Get("optTekla") == "1")
                        //  zoomValue = zoomValue * 2.5;
                        // **** CUSTOM VALUE FOR TEKLA **** //

                        ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
                                                                          uidoc.ActiveView.UpDirection, false);

                        XYZ c  = t.EyePosition;
                        XYZ vi = t.ForwardDirection;
                        XYZ up = t.UpDirection;


                        v.OrthogonalCamera = new OrthogonalCamera
                        {
                            CameraViewPoint =
                            {
                                X = c.X.ToMeters(),
                                Y = c.Y.ToMeters(),
                                Z = c.Z.ToMeters()
                            },
                            CameraUpVector =
                            {
                                X = up.X.ToMeters(),
                                Y = up.Y.ToMeters(),
                                Z = up.Z.ToMeters()
                            },
                            CameraDirection =
                            {
                                X = vi.X.ToMeters() * -1,
                                Y = vi.Y.ToMeters() * -1,
                                Z = vi.Z.ToMeters() * -1
                            },
                            ViewToWorldScale = zoomValue
                        };
                    }
                    // it is a perspective view
                    else
                    {
                        viewCenter = uidoc.ActiveView.Origin;
                        //revit default value
                        zoomValue = 45;

                        ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
                                                                          uidoc.ActiveView.UpDirection, false);

                        XYZ c  = t.EyePosition;
                        XYZ vi = t.ForwardDirection;
                        XYZ up = t.UpDirection;

                        v.PerspectiveCamera = new PerspectiveCamera
                        {
                            CameraViewPoint =
                            {
                                X = c.X.ToMeters(),
                                Y = c.Y.ToMeters(),
                                Z = c.Z.ToMeters()
                            },
                            CameraUpVector =
                            {
                                X = up.X.ToMeters(),
                                Y = up.Y.ToMeters(),
                                Z = up.Z.ToMeters()
                            },
                            CameraDirection =
                            {
                                X = vi.X.ToMeters() * -1,
                                Y = vi.Y.ToMeters() * -1,
                                Z = vi.Z.ToMeters() * -1
                            },
                            FieldOfView = zoomValue
                        };
                    }
                }
                //COMPONENTS PART
                string versionName = doc.Application.VersionName;
                v.Components = new List <Component>();

                var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                   .WhereElementIsNotElementType()
                                   .WhereElementIsViewIndependent()
                                   .ToElementIds();
                var hiddenElems = new FilteredElementCollector(doc)
                                  .WhereElementIsNotElementType()
                                  .WhereElementIsViewIndependent()
                                  .Where(x => x.IsHidden(doc.ActiveView) ||
                                         !doc.ActiveView.IsElementVisibleInTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate, x.Id)).ToList();//would need to check how much this is affecting performance

                var selectedElems = uidoc.Selection.GetElementIds();


                //include only hidden elements and selected in the BCF
                if (visibleElems.Count() > hiddenElems.Count())
                {
                    foreach (var elem in hiddenElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem.Id)),
                            Visible           = false,
                            Selected          = false,
                            AuthoringToolId   = elem.Id.IntegerValue.ToString()
                        });
                    }
                    foreach (var elem in selectedElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
                            Visible           = true,
                            Selected          = true,
                            AuthoringToolId   = elem.IntegerValue.ToString()
                        });
                    }
                }
                //include only visigle elements
                //all the others are hidden
                else
                {
                    foreach (var elem in visibleElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
                            Visible           = true,
                            Selected          = selectedElems.Contains(elem),
                            AuthoringToolId   = elem.IntegerValue.ToString()
                        });
                    }
                }
                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error generating viewpoint", "exception: " + ex1);
            }
            return(null);
        }
Example #34
0
        public static View3D Create3DView(ViewOrientation3D orient, string name, bool isPerspective)
        {
            //http://adndevblog.typepad.com/aec/2012/05/viewplancreate-method.html

            IEnumerable<ViewFamilyType> viewFamilyTypes = from elem in new
              FilteredElementCollector(dynRevitSettings.Doc.Document).OfClass(typeof(ViewFamilyType))
                                                          let type = elem as ViewFamilyType
                                                          where type.ViewFamily == ViewFamily.ThreeDimensional
                                                          select type;

            //create a new view
            View3D view = isPerspective ?
                              View3D.CreateIsometric(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id) :
                              View3D.CreatePerspective(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id);

            view.SetOrientation(orient);
            view.SaveOrientationAndLock();
            view.Name = CreateUniqueViewName(name);

            return view;
        }
Example #35
0
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        public VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Classes.BCF2.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Classes.BCF2.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist       = TL.DistanceTo(BR) / 2; //custom sectet value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector = TL.Subtract(BR);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        //zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    //ViewOrientation3D t = new ViewOrientation3D(centerIMP, uidoc.ActiveView.UpDirection, uidoc.ActiveView.ViewDirection);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }


                    // handle section box if enabled
                    if (view3D.IsSectionBoxActive)
                    {
                        BoundingBoxXYZ sectionBox = view3D.GetSectionBox();

                        // Note that the section box can be rotated and transformed.
                        // So the min/max corners coordinates relative to the model must be computed via the transform.
                        Transform trf = sectionBox.Transform;

                        XYZ max = sectionBox.Max; //Maximum coordinates (upper-right-front corner of the box before transform is applied).
                        XYZ min = sectionBox.Min; //Minimum coordinates (lower-left-rear corner of the box before transform is applied).

                        // Transform the min and max to model coordinates
                        XYZ maxInModelCoords = trf.OfPoint(max);
                        XYZ minInModelCoords = trf.OfPoint(min);

                        // Convert to project unit
                        DisplayUnitType lengthUnitType = doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
                        maxInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(maxInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Z, lengthUnitType));
                        minInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(minInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Z, lengthUnitType));

                        // Convert to shared coordinates
                        maxInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, maxInModelCoords, false);
                        minInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, minInModelCoords, false);

                        // Add to BCF clipping planes
                        v.ClippingPlanes = BcfAdapter.GetClippingPlanesFromBoundingBox
                                           (
                            maxInModelCoords.X, maxInModelCoords.Y, maxInModelCoords.Z,
                            minInModelCoords.X, minInModelCoords.Y, minInModelCoords.Z
                                           );
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new List <IssueTracker.Classes.BCF2.Component>();
                    foreach (var eId in collection)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, eId);
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        v.Components.Add(new ARUP.IssueTracker.Classes.BCF2.Component(doc.Application.VersionName, eId.ToString(), ifcguid));
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
Example #36
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            View3D view = null;
            var eye = (XYZ)((Value.Container)args[0]).Item;
            var userUp = (XYZ)((Value.Container)args[1]).Item;
            var direction = (XYZ)((Value.Container)args[2]).Item;
            var name = ((Value.String)args[3]).Item;

            XYZ side;
            if (direction.IsAlmostEqualTo(userUp) || direction.IsAlmostEqualTo(userUp.Negate()))
                side = XYZ.BasisZ.CrossProduct(direction);
            else
                side = userUp.CrossProduct(direction);
            XYZ up = side.CrossProduct(direction);

            //need to reverse the up direction to get the
            //proper orientation - there might be a better way to handle this
            var orient = new ViewOrientation3D(eye, -up, direction);

            if (this.Elements.Any())
            {
                Element e;
                if (dynUtils.TryGetElement(this.Elements[0], typeof(View3D), out e))
                {
                    view = (View3D)e;
                    if (!view.ViewDirection.IsAlmostEqualTo(direction))
                    {
                        view.Unlock();
                        view.SetOrientation(orient);
                        view.SaveOrientationAndLock();
                    }
                    if (view.Name != null && view.Name != name)
                        view.Name = CreateUniqueViewName(name);
                }
                else
                {
                    //create a new view
                    view = dynViewBase.Create3DView(orient, name, false);
                    Elements[0] = view.Id;
                }
            }
            else
            {
                view = Create3DView(orient, name, false);
                Elements.Add(view.Id);
            }

            return Value.NewContainer(view);
        }
        /// <summary>
        /// Get geometry of family instances and show them in Revit views
        /// </summary>
        public void GetInstanceGeometry()
        {
            FilteredElementCollector instanceCollector = new FilteredElementCollector(RevitDoc);

            instanceCollector.OfClass(typeof(FamilyInstance));

            // create views by different names
            ElementId       View3DId = new ElementId(-1);
            IList <Element> elems    = new FilteredElementCollector(RevitDoc).OfClass(typeof(ViewFamilyType)).ToElements();

            foreach (Element e in elems)
            {
                ViewFamilyType v = e as ViewFamilyType;

                if (v != null && v.ViewFamily == ViewFamily.ThreeDimensional)
                {
                    View3DId = e.Id;
                    break;
                }
            }

            //View instanceView = RevitDoc.Create.NewView3D(new XYZ(1, 1, -1));
            View3D            instanceView = View3D.CreateIsometric(RevitDoc, View3DId);
            ViewOrientation3D instanceViewOrientation3D = new ViewOrientation3D(new XYZ(-30.8272352809007, -2.44391067967133, 18.1013736367246), new XYZ(0.577350269189626, 0.577350269189626, -0.577350269189626), new XYZ(0.408248290463863, 0.408248290463863, 0.816496580927726));

            instanceView.SetOrientation(instanceViewOrientation3D);
            instanceView.SaveOrientation();
            instanceView.Name = "InstanceGeometry";

            //View originalView = RevitDoc.Create.NewView3D(new XYZ(0, 1, -1));
            View3D            originalView = View3D.CreateIsometric(RevitDoc, View3DId);
            ViewOrientation3D originalViewOrientation3D = new ViewOrientation3D(new XYZ(-19.0249866627872, -5.09536632799455, 20.7528292850478), new XYZ(0, 0.707106781186547, -0.707106781186547), new XYZ(0, 0.707106781186548, 0.707106781186548));

            originalView.SetOrientation(originalViewOrientation3D);
            originalView.SaveOrientation();
            originalView.Name = "OriginalGeometry";

            //View transView = RevitDoc.Create.NewView3D(new XYZ(-1, 1, -1));
            View3D transView = View3D.CreateIsometric(RevitDoc, View3DId);
            //ViewOrientation3D transViewOrientation3D = new ViewOrientation3D(new XYZ(-7.22273804467383, -2.44391067967133, 18.1013736367246), new XYZ(-0.577350269189626, 0.577350269189626, -0.577350269189626), new XYZ(-0.408248290463863, 0.408248290463863, 0.816496580927726));
            ViewOrientation3D transViewOrientation3D = new ViewOrientation3D(new XYZ(-19.0249866627872, -5.09536632799455, 20.7528292850478), new XYZ(0, 0.707106781186547, -0.707106781186547), new XYZ(0, 0.707106781186548, 0.707106781186548));

            transView.SetOrientation(transViewOrientation3D);
            transView.SaveOrientation();
            transView.Name = "TransformedGeometry";

            foreach (FamilyInstance instance in instanceCollector)
            {
                GeometryElement instanceGeo  = instance.get_Geometry(m_options);
                GeometryElement computedGeo  = instance.GetOriginalGeometry(m_options);
                GeometryElement transformGeo = computedGeo.GetTransformed(instance.GetTransform());

                // show family instance geometry
                //foreach (GeometryObject obj in instanceGeo.Objects)
                IEnumerator <GeometryObject> Objects = instanceGeo.GetEnumerator();
                while (Objects.MoveNext())
                {
                    GeometryObject obj = Objects.Current;

                    if (obj is Solid)
                    {
                        Solid solid = obj as Solid;
                        PaintSolid(solid, instanceView);
                    }
                }

                // show geometry that is original geometry
                //foreach (GeometryObject obj in computedGeo.Objects)
                IEnumerator <GeometryObject> Objects1 = computedGeo.GetEnumerator();
                while (Objects1.MoveNext())
                {
                    GeometryObject obj = Objects1.Current;

                    if (obj is Solid)
                    {
                        Solid solid = obj as Solid;
                        PaintSolid(solid, originalView);
                    }
                }

                // show geometry that was transformed
                //foreach (GeometryObject obj in transformGeo.Objects)
                IEnumerator <GeometryObject> Objects2 = transformGeo.GetEnumerator();
                while (Objects2.MoveNext())
                {
                    GeometryObject obj = Objects2.Current;

                    if (obj is Solid)
                    {
                        Solid solid = obj as Solid;
                        PaintSolid(solid, transView);
                    }
                }
            }
            // remove original instances to view point results.
            RevitDoc.Delete(instanceCollector.ToElementIds());
        }
Example #38
0
        private static View3D Create3DView(XYZ eye, XYZ up, XYZ direction)
        {
            //http://adndevblog.typepad.com/aec/2012/05/viewplancreate-method.html

            IEnumerable<ViewFamilyType> viewFamilyTypes = from elem in new
              FilteredElementCollector(dynRevitSettings.Doc.Document).OfClass(typeof(ViewFamilyType))
                                                          let type = elem as ViewFamilyType
                                                          where type.ViewFamily == ViewFamily.ThreeDimensional
                                                          select type;

            //create a new view
            View3D view = View3D.CreateIsometric(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id);
            ViewOrientation3D orient = new ViewOrientation3D(eye, up, direction);
            view.SetOrientation(orient);
            view.SaveOrientationAndLock();
            return view;
        }