Example #1
0
        public DepthPlanes(ProjectionCamera camera, BoundingBox bounds, double step)
        {
            // Find closest visible point to camera
            Point3D  position  = camera.Transform.Transform(camera.Position);
            Vector3D direction = camera.Transform.Transform(camera.LookDirection);
            Point3D  lookAt    = position + (direction * camera.NearPlaneDistance);
            double   xDir      = Normalize(direction.X);
            double   yDir      = Normalize(direction.Y);
            double   zDir      = Normalize(direction.Z);

            double biggest = Math.Max(Math.Max(Math.Abs(lookAt.X), Math.Abs(lookAt.Y)), Math.Abs(lookAt.Z));

            if (xDir != 0)
            {
                planes.Add(new Plane(new Vector3D(-xDir, 0, 0), -Distance(lookAt.X, biggest, bounds.Max.X, step)));
            }
            if (yDir != 0)
            {
                planes.Add(new Plane(new Vector3D(0, -yDir, 0), -Distance(lookAt.Y, biggest, bounds.Max.Y, step)));
            }
            if (zDir != 0)
            {
                planes.Add(new Plane(new Vector3D(0, 0, -zDir), -Distance(lookAt.Z, biggest, bounds.Max.Z, step)));
            }
        }
Example #2
0
        /// <summary>
        ///   Invoked when an unhandled <see cref="E:System.Windows.Input.Mouse.MouseDown" /> attached event reaches an element in
        ///   its route that is derived from this class. Implement this method to add class handling for this event.
        /// </summary>
        /// <param name="e">
        ///   The <see cref="T:System.Windows.Input.MouseButtonEventArgs" /> that contains the event data. This event data reports
        ///   details about the mouse button that was pressed and the handled state.
        /// </param>
        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            base.OnMouseDown(e);
            ParentViewport = Visual3DHelper.GetViewport3D(this);
            Camera         = ParentViewport.Camera as ProjectionCamera;
            ProjectionCamera projectionCamera = Camera;

            if (projectionCamera != null)
            {
                HitPlaneNormal = projectionCamera.LookDirection;
            }
            CaptureMouse();
            Vector3D direction = ToWorld(Normal);

            Vector3D up             = Vector3D.CrossProduct(Camera.LookDirection, direction);
            Point3D  hitPlaneOrigin = ToWorld(Center);

            HitPlaneNormal = Vector3D.CrossProduct(up, direction);
            Point p = e.GetPosition(ParentViewport);

            Point3D?np = GetHitPlanePoint(p, hitPlaneOrigin, Normal);

            if (np == null)
            {
                return;
            }

            Point3D lp = ToLocal(np.Value);

            _lastPoint = lp;
            CaptureMouse();
        }
Example #3
0
        private static Matrix3D GetViewMatrix(ProjectionCamera camera)
        {
            Debug.Assert(camera != null,
                         "Caller needs to ensure camera is non-null.");

            // This math is identical to what you find documented for
            // D3DXMatrixLookAtRH with the exception that WPF uses a
            // LookDirection vector rather than a LookAt point.

            Vector3D zAxis = -camera.LookDirection;

            zAxis.Normalize();

            Vector3D xAxis = Vector3D.CrossProduct(camera.UpDirection, zAxis);

            xAxis.Normalize();

            Vector3D yAxis = Vector3D.CrossProduct(zAxis, xAxis);

            Vector3D position = (Vector3D)camera.Position;
            double   offsetX  = -Vector3D.DotProduct(xAxis, position);
            double   offsetY  = -Vector3D.DotProduct(yAxis, position);
            double   offsetZ  = -Vector3D.DotProduct(zAxis, position);

            return(new Matrix3D(
                       xAxis.X, yAxis.X, zAxis.X, 0,
                       xAxis.Y, yAxis.Y, zAxis.Y, 0,
                       xAxis.Z, yAxis.Z, zAxis.Z, 0,
                       offsetX, offsetY, offsetZ, 1));
        }
Example #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CameraSetting"/> class.
        /// </summary>
        /// <param name="camera">
        /// The camera.
        /// </param>
        public CameraSetting(ProjectionCamera camera)
        {
            this.Position          = camera.Position;
            this.LookDirection     = camera.LookDirection;
            this.UpDirection       = camera.UpDirection;
            this.NearPlaneDistance = camera.NearPlaneDistance;
            this.FarPlaneDistance  = camera.FarPlaneDistance;
            var pcamera = camera as PerspectiveCamera;

            if (pcamera != null)
            {
                this.FieldOfView = pcamera.FieldOfView;
            }
            else
            {
                this.FieldOfView = 45;
            }

            var ocamera = camera as OrthographicCamera;

            if (ocamera != null)
            {
                this.Width = ocamera.Width;
            }
            else
            {
                this.Width = 100;
            }
        }
Example #5
0
        /// <summary>
        /// Animates the camera position and direction
        /// </summary>
        /// <param name="camera">Camera</param>
        /// <param name="newPosition">The position to animate to</param>
        /// <param name="newDirection">The direction to animate to</param>
        /// <param name="newUpDirection">The up direction to animate to</param>
        /// <param name="animationTime">Animation time in milliseconds</param>
        public static void AnimateTo(ProjectionCamera camera, Point3D newPosition, Vector3D newDirection, Vector3D newUpDirection, double animationTime)
        {
            var fromPosition    = camera.Position;
            var fromDirection   = camera.LookDirection;
            var fromUpDirection = camera.UpDirection;

            camera.Position      = newPosition;
            camera.LookDirection = newDirection;
            camera.UpDirection   = newUpDirection;

            if (animationTime > 0)
            {
                var a1 = new Point3DAnimation(fromPosition, newPosition,
                                              new Duration(TimeSpan.FromMilliseconds(animationTime)))
                {
                    AccelerationRatio = 0.3, DecelerationRatio = 0.5, FillBehavior = FillBehavior.Stop
                };
                camera.BeginAnimation(ProjectionCamera.PositionProperty, a1);

                var a2 = new Vector3DAnimation(fromDirection, newDirection,
                                               new Duration(TimeSpan.FromMilliseconds(animationTime)))
                {
                    AccelerationRatio = 0.3, DecelerationRatio = 0.5, FillBehavior = FillBehavior.Stop
                };
                camera.BeginAnimation(ProjectionCamera.LookDirectionProperty, a2);

                var a3 = new Vector3DAnimation(fromUpDirection, newUpDirection,
                                               new Duration(TimeSpan.FromMilliseconds(animationTime)))
                {
                    AccelerationRatio = 0.3, DecelerationRatio = 0.5, FillBehavior = FillBehavior.Stop
                };
                camera.BeginAnimation(ProjectionCamera.UpDirectionProperty, a3);
            }
        }
Example #6
0
        /// <summary>
        /// For each mesh object in the viewport, this method calculates the vertex that when mapped to 2D is closest to the given 2D point on the screen
        /// </summary>
        /// <param name="pointToHitTest"> The point in screen coordinates to calculate the closest vertices for. </param>
        /// <returns> A ClosestVertexResult containing the distance to the 2D point and the closest 3D vertex point for each geometry/model </returns>
        public IEnumerable <ClosestVertexResult> FindClosestHits(Point pointToHitTest)
        {
            ProjectionCamera camera = mViewPort3D.Camera as ProjectionCamera;

            if (camera == null)
            {
                throw new InvalidOperationException("No projection camera defined. Cannot find rectangle hits.");
            }

            List <ClosestVertexResult> results = new List <ClosestVertexResult>();

            mViewPort3D.Children.Traverse <GeometryModel3D>(
                (model, transform) =>
            {
                MeshGeometry3D geometry = model.Geometry as MeshGeometry3D;
                if (geometry == null || geometry.Positions == null || geometry.TriangleIndices == null)
                {
                    return;
                }

                Point3D[] point3Ds;
                if (geometry.Positions.Count <= mMaximumVerticesPerMesh)
                {
                    point3Ds = geometry.Positions.Select(transform.Transform).ToArray();
                }
                else
                {
                    Rect3D bounds = geometry.Bounds;
                    point3Ds      = GetBoundaryPointsBoundingBox(bounds).Select(transform.Transform).ToArray();
                }

                // transform the positions of the mesh to screen coordinates
                Point[] point2Ds = mViewPort3D.Point3DtoPoint2D(point3Ds).ToArray();

                double minSquaredDistanceToPoint = double.PositiveInfinity;

                Point3D closestPoint   = point3Ds[0];
                Point closestPointIn2D = point2Ds[0];

                for (int i = 0; i < point2Ds.Length; i++)
                {
                    Point point            = point2Ds[i];
                    double xDiff           = point.X - pointToHitTest.X;
                    double yDiff           = point.Y - pointToHitTest.Y;
                    double squaredDistance = xDiff * xDiff + yDiff * yDiff;
                    if (squaredDistance < minSquaredDistanceToPoint)
                    {
                        minSquaredDistanceToPoint = squaredDistance;
                        closestPoint     = point3Ds[i];
                        closestPointIn2D = point;
                    }
                }

                ClosestVertexResult hitTestResult = new ClosestVertexResult(model, geometry, closestPoint,
                                                                            closestPointIn2D, Math.Sqrt(minSquaredDistanceToPoint));
                results.Add(hitTestResult);
            });

            return(results);
        }
Example #7
0
        public static void ZoomExtents(this ProjectionCamera camera, Rect3D bounds, double width, double height)
        {
            Vector3D diagonal = new Vector3D(bounds.SizeX, bounds.SizeY, bounds.SizeZ);
            Point3D  center   = bounds.Location + (diagonal * 0.5);
            double   radius   = diagonal.Length * 0.5;

            if (camera is PerspectiveCamera perspectiveCamera)
            {
                double disth = radius / Math.Tan(0.5 * perspectiveCamera.FieldOfView * Math.PI / 180);
                double vfov  = perspectiveCamera.GetVerticalFieldOfView(width, height);

                double   distv = radius / Math.Tan(0.5 * vfov * Math.PI / 180);
                double   dist  = Math.Max(disth, distv);
                Vector3D dir   = perspectiveCamera.LookDirection;
                dir.Normalize();
                perspectiveCamera.LookAt(center, dir * dist);
            }
            if (camera is OrthographicCamera orthographicCamera)
            {
                double newWidth = radius * 2;
                if (width > height)
                {
                    newWidth = radius * 2 * width / height;
                }
                orthographicCamera.LookAt(center, orthographicCamera.LookDirection);
                orthographicCamera.Width = newWidth;
            }
        }
Example #8
0
        /// <summary>
        /// Set the camera target point and camera distance.
        /// </summary>
        /// <param name="camera">
        /// The camera.
        /// </param>
        /// <param name="target">
        /// The target point.
        /// </param>
        /// <param name="distance">
        /// The distance to the camera.
        /// </param>
        /// <param name="animationTime">
        /// The animation time.
        /// </param>
        public static void LookAt(this ProjectionCamera camera, Point3D target, double distance, double animationTime)
        {
            Vector3D d = camera.LookDirection;

            d.Normalize();
            LookAt(camera, target, d * distance, animationTime);
        }
Example #9
0
        /// <summary>
        /// Zooms to fit the specified sphere.
        /// </summary>
        /// <param name="camera">
        /// The camera to change.
        /// </param>
        /// <param name="viewport">
        /// The viewport.
        /// </param>
        /// <param name="center">
        /// The center of the sphere.
        /// </param>
        /// <param name="radius">
        /// The radius of the sphere.
        /// </param>
        /// <param name="animationTime">
        /// The animation time.
        /// </param>
        public static void ZoomExtents(ProjectionCamera camera, Viewport3D viewport, Point3D center, double radius, double animationTime = 0)
        {
            if (camera is PerspectiveCamera)
            {
                var    pcam  = camera as PerspectiveCamera;
                double disth = radius / Math.Tan(0.5 * pcam.FieldOfView * Math.PI / 180);
                double vfov  = pcam.FieldOfView;
                if (viewport.ActualWidth > 0 && viewport.ActualHeight > 0)
                {
                    vfov *= viewport.ActualHeight / viewport.ActualWidth;
                }
                double distv = radius / Math.Tan(0.5 * vfov * Math.PI / 180);
                double dist  = Math.Max(disth, distv);
                var    dir   = camera.LookDirection;
                dir.Normalize();
                LookAt(camera, center, dir * dist, animationTime);
            }
            else if (camera is OrthographicCamera)
            {
                LookAt(camera, center, camera.LookDirection, animationTime);
                double newWidth = radius * 2;

                if (viewport.ActualWidth > viewport.ActualHeight)
                {
                    newWidth = radius * 2 * viewport.ActualWidth / viewport.ActualHeight;
                }

                AnimateWidth(camera as OrthographicCamera, newWidth, animationTime);
            }
        }
Example #10
0
    private void MouseDownHandler(object sender, MouseButtonEventArgs e)
    {
        if (!Enabled)
        {
            return;
        }
        e.Handled = true;

        if (e.ClickCount == 2)
        {
            Reset();
            return;
        }

        UIElement el = (UIElement)sender;

        _point = e.MouseDevice.GetPosition(el);
        // Initialize the center of rotation to the lookatpoint
        if (!_centered)
        {
            ProjectionCamera camera = (ProjectionCamera)_servants[0].Camera;
            _center   = (Point3D)camera.LookDirection;
            _centered = true;
        }
        _scaling = (e.RightButton == MouseButtonState.Pressed);

        el.CaptureMouse();
    }
Example #11
0
        private static Matrix3D GetViewMatrix(ProjectionCamera camera)
        {
            if (camera == null)
            {
                throw new ArgumentNullException("camera");
            }

            // This math is identical to what you find documented for
            // D3DXMatrixLookAtRH with the exception that WPF uses a
            // LookDirection vector rather than a LookAt point.

            Vector3D zAxis = -camera.LookDirection;

            zAxis.Normalize();

            Vector3D xAxis = Vector3D.CrossProduct(camera.UpDirection, zAxis);

            xAxis.Normalize();

            Vector3D yAxis = Vector3D.CrossProduct(zAxis, xAxis);

            Vector3D position = (Vector3D)camera.Position;
            double   offsetX  = -Vector3D.DotProduct(xAxis, position);
            double   offsetY  = -Vector3D.DotProduct(yAxis, position);
            double   offsetZ  = -Vector3D.DotProduct(zAxis, position);

            Matrix3D m = new Matrix3D(
                xAxis.X, yAxis.X, zAxis.X, 0,
                xAxis.Y, yAxis.Y, zAxis.Y, 0,
                xAxis.Z, yAxis.Z, zAxis.Z, 0,
                offsetX, offsetY, offsetZ, 1);

            return(m);
        }
Example #12
0
        private HitTestResultBehavior HitTestCallback(HitTestResult result)
        {
            RayMeshGeometry3DHitTestResult rayHit = result as RayMeshGeometry3DHitTestResult;
            ProjectionCamera      camera          = _viewport3D.Viewport.Camera as ProjectionCamera;
            HitTestResultBehavior result2;

            if (rayHit != null && rayHit.ModelHit != null)
            {
                Model3D  model    = rayHit.ModelHit;
                Visual3D visual3D = rayHit.VisualHit;
                if (visual3D != null)
                {
                    if (string.Compare(Convert.ToString(visual3D.GetValue(FrameworkElement.NameProperty)), "CurveVisual") != 0)
                    {
                        result2 = HitTestResultBehavior.Continue;
                        return(result2);
                    }
                }
                MeshGeometry3D mesh = rayHit.MeshHit;
                if (mesh != null)
                {
                    Point3D p  = mesh.Positions[rayHit.VertexIndex1];
                    Point3D p2 = mesh.Positions[rayHit.VertexIndex2];
                    Point3D p3 = mesh.Positions[rayHit.VertexIndex3];
                    double  x  = p.X * rayHit.VertexWeight1 + p2.X * rayHit.VertexWeight2 + p3.X * rayHit.VertexWeight3;
                    double  y  = p.Y * rayHit.VertexWeight1 + p2.Y * rayHit.VertexWeight2 + p3.Y * rayHit.VertexWeight3;
                    double  z  = p.Z * rayHit.VertexWeight1 + p2.Z * rayHit.VertexWeight2 + p3.Z * rayHit.VertexWeight3;

                    // point in local coordinates
                    Point3D localPoint = new Point3D(x, y, z);
                    Point3D p4         = localPoint;

                    // transform to global coordinates

                    // first transform the Model3D hierarchy
                    GeneralTransform3D t2 = Viewport3DHelper.GetTransform(rayHit.VisualHit, rayHit.ModelHit);
                    if (t2 != null)
                    {
                        p4 = t2.Transform(p4);
                    }

                    // then transform the Visual3D hierarchy up to the Viewport3D ancestor
                    GeneralTransform3D t3 = Viewport3DHelper.GetTransform(_viewport3D.Viewport, rayHit.VisualHit);
                    if (t3 != null)
                    {
                        p4 = t3.Transform(p4);
                    }
                    double distance = (camera.Position - p4).LengthSquared;
                    if (distance < _minimumDistance)
                    {
                        _minimumDistance = distance;
                        _nearestPt       = localPoint;
                        _nearestNormal   = Vector3D.CrossProduct(p2 - p, p3 - p);
                        _rayhit          = rayHit;
                    }
                }
            }
            result2 = HitTestResultBehavior.Continue;
            return(result2);
        }
Example #13
0
        public static Matrix3D CameraRotationTranslationMatrix(Camera camera)
        {
            ProjectionCamera projectionCamera = camera as ProjectionCamera;
            Matrix3D         matrix3D;

            if (projectionCamera != null)
            {
                Vector3D vector2   = (Vector3D)projectionCamera.Position;
                Vector3D vector3D1 = -projectionCamera.LookDirection;
                vector3D1.Normalize();
                Vector3D vector3D2 = Vector3D.CrossProduct(projectionCamera.UpDirection, vector3D1);
                vector3D2.Normalize();
                Vector3D vector1 = Vector3D.CrossProduct(vector3D1, vector3D2);
                double   offsetX = -Vector3D.DotProduct(vector3D2, vector2);
                double   offsetY = -Vector3D.DotProduct(vector1, vector2);
                double   offsetZ = -Vector3D.DotProduct(vector3D1, vector2);
                matrix3D = new Matrix3D(vector3D2.X, vector1.X, vector3D1.X, 0.0, vector3D2.Y, vector1.Y, vector3D1.Y, 0.0, vector3D2.Z, vector1.Z, vector3D1.Z, 0.0, offsetX, offsetY, offsetZ, 1.0);
            }
            else
            {
                matrix3D         = ((MatrixCamera)camera).ViewMatrix;
                matrix3D.OffsetX = 0.0;
                matrix3D.OffsetY = 0.0;
                matrix3D.OffsetZ = 0.0;
                matrix3D.M44     = 1.0;
            }
            return(matrix3D);
        }
Example #14
0
        public static double UnitsPerPixel(Viewport3D viewport, Point3D targetPoint)
        {
            double           num1             = 1.0;
            ProjectionCamera projectionCamera = viewport.Camera as ProjectionCamera;

            if (projectionCamera == null)
            {
                return(1.0);
            }
            Vector3D           vector3D           = targetPoint - projectionCamera.Position;
            PerspectiveCamera  perspectiveCamera  = projectionCamera as PerspectiveCamera;
            OrthographicCamera orthographicCamera = projectionCamera as OrthographicCamera;

            if (perspectiveCamera != null)
            {
                double fieldOfView = perspectiveCamera.FieldOfView;
                num1 = 2.0 * vector3D.Length * Math.Tan(Math.PI / 180.0 * (fieldOfView / 2.0));
            }
            else if (orthographicCamera != null)
            {
                num1 = orthographicCamera.Width;
            }
            double num2 = num1;

            if (viewport.ActualWidth > 0.0)
            {
                num2 /= viewport.ActualWidth;
            }
            return(num2);
        }
        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            Vector           delta  = (e.GetPosition(Viewport) - oldMousePos);
            BlocksViewModel  vm     = (BlocksViewModel)((FrameworkElement)sender).DataContext; // TODO: Ugly dependency on the model here!
            ProjectionCamera camera = (ProjectionCamera)Viewport.Camera;
            Vector3D         left   = Vector3D.CrossProduct(camera.LookDirection, camera.UpDirection);

            left.Normalize();
            switch (cameraDragMode)
            {
            case CameraDragMode.Pan:
                delta *= 0.01;
                Vector3D deltaMove         = Vector3D.Add(left * -delta.X, camera.UpDirection * delta.Y);
                Point3D  newCameraPosition = vm.CameraPosition.Add(deltaMove);
                vm.CameraPosition = newCameraPosition;
                Point3D newCameraAimPoint = vm.CameraAimPoint.Add(deltaMove);
                vm.CameraAimPoint = newCameraAimPoint;
                break;

            case CameraDragMode.Rotate:
                delta *= 0.01;
                Vector3D v = vm.CameraAimPoint.VectorTo(vm.CameraPosition).Cartesian2Spherical();
                v.Y -= delta.X;
                v.Z -= delta.Y;
                vm.CameraPosition = vm.CameraAimPoint.Add(v.Spherical2Cartesian());
                break;
            }
            oldMousePos = e.GetPosition(Viewport);
        }
Example #16
0
        public static Matrix3D GetWorldToLocal(ProjectionCamera camera)
        {
            Matrix3D tmp = GetLocalToWorld(camera);

            tmp.Invert();
            return(tmp);
        }
Example #17
0
        /// <summary/>
        public override void Perform()
        {
            ProjectionCamera Camera = Viewport3D.Camera as ProjectionCamera;

            switch (PropertyToAnimate)
            {
            case Properties.NearPlaneDistanceProperty:
                Camera.BeginAnimation(ProjectionCamera.NearPlaneDistanceProperty, DoubleAnimation, HandoffBehavior);
                break;

            case Properties.FarPlaneDistanceProperty:
                //DoubleAnimation cannot use FarPlaneDistance default origin value of 'Infinity'.
                //Changed it to [0-49].
                Camera.FarPlaneDistance = FarPlaneDistance % 50;
                Camera.BeginAnimation(ProjectionCamera.FarPlaneDistanceProperty, DoubleAnimation, HandoffBehavior);
                break;

            case Properties.OtherProperty:
                if (Camera is PerspectiveCamera)
                {
                    Camera.BeginAnimation(PerspectiveCamera.FieldOfViewProperty, DoubleAnimation, HandoffBehavior);
                    break;
                }
                if (Camera is OrthographicCamera)
                {
                    Camera.BeginAnimation(OrthographicCamera.WidthProperty, DoubleAnimation, HandoffBehavior);
                    break;
                }
                break;
            }
        }
Example #18
0
        /// <summary>
        /// Zooms to fit the specified bounding rectangle.
        /// </summary>
        /// <param name="camera">
        /// The camera to change.
        /// </param>
        /// <param name="viewport">
        /// The viewport.
        /// </param>
        /// <param name="bounds">
        /// The bounding rectangle.
        /// </param>
        /// <param name="animationTime">
        /// The animation time.
        /// </param>
        public static void ZoomExtents(this ProjectionCamera camera, Viewport3D viewport, Rect3D bounds, double animationTime = 0)
        {
            var    diagonal = new Vector3D(bounds.SizeX, bounds.SizeY, bounds.SizeZ);
            var    center   = bounds.Location + (diagonal * 0.5);
            double radius   = diagonal.Length * 0.5;

            ZoomExtents(camera, viewport, center, radius, animationTime);
        }
Example #19
0
 protected void ApplyProjectionCameraProperties(ProjectionCamera camera, DeterministicRandom random)
 {
     camera.Position          = Position;
     camera.LookDirection     = LookDirection;
     camera.UpDirection       = UpDirection;
     camera.NearPlaneDistance = random.NextDouble() * 10;
     camera.FarPlaneDistance  = camera.NearPlaneDistance + 500;
 }
 // Use this for initialization
 void Start()
 {
     UseProjection = CommandLineParms.Bool("UseProjection", UseProjection); // allow the command line to override it
     if (UseProjection)
     {
         _cacheOmnity = ProjectionCamera.Attach(GetMainCamera());
     }
 }
Example #21
0
        /// <summary>
        /// Fits the specified bounding rectangle in the current view.
        /// </summary>
        /// <param name="camera">The camera to change.</param>
        /// <param name="viewport">The viewport.</param>
        /// <param name="bounds">The bounding rectangle.</param>
        /// <param name="lookDirection">The look direction.</param>
        /// <param name="upDirection">The up direction.</param>
        /// <param name="animationTime">The animation time.</param>
        public static void FitView(this ProjectionCamera camera, Viewport3D viewport, Rect3D bounds, Vector3D lookDirection, Vector3D upDirection, double animationTime = 0)
        {
            var    diagonal = new Vector3D(bounds.SizeX, bounds.SizeY, bounds.SizeZ);
            var    center   = bounds.Location + (diagonal * 0.5);
            double radius   = diagonal.Length * 0.5;

            FitView(camera, viewport, center, radius, lookDirection, upDirection, animationTime);
        }
Example #22
0
        /// <summary>
        /// Changes the direction of a camera.
        /// </summary>
        /// <param name="camera">
        /// The camera.
        /// </param>
        /// <param name="newLookDirection">
        /// The new look direction.
        /// </param>
        /// <param name="newUpDirection">
        /// The new up direction.
        /// </param>
        /// <param name="animationTime">
        /// The animation time.
        /// </param>
        public static void ChangeDirection(this ProjectionCamera camera, Vector3D newLookDirection, Vector3D newUpDirection, double animationTime)
        {
            var target = camera.Position + camera.LookDirection;
            var length = camera.LookDirection.Length;

            newLookDirection.Normalize();
            LookAt(camera, target, newLookDirection * length, newUpDirection, animationTime);
        }
Example #23
0
        //public Camera Camera2 { private set; get; }

        public MainViewModel()
        {
            EffectsManager  = new DefaultEffectsManager();
            RenderTechnique = EffectsManager[DefaultRenderTechniqueNames.Blinn];
            Title           = "Shadow Map Demo";
            SubTitle        = "WPF & SharpDX";

            // setup lighting
            this.AmbientLightColor     = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            this.DirectionalLightColor = Media.Colors.White;
            //this.DirectionalLightDirection = new Vector3(-1, -1, -1);
            // this.LightDirectionTransform = CreateAnimatedTransform(-DirectionalLightDirection.ToVector3D(), new Vector3D(0, 1, -1), 24);
            this.ShadowMapResolution = new Size(2048, 2048);

            // camera setup
            this.Camera = new PerspectiveCamera {
                Position = new Point3D(0, 1, 1), LookDirection = new Vector3D(0, -1, -1), UpDirection = new Vector3D(0, 1, 0)
            };
            Camera1 = new PerspectiveCamera {
                Position = new Point3D(0, 5, 0), LookDirection = new Vector3D(0, -1, 0), UpDirection = new Vector3D(1, 0, 0)
            };

            // scene model3d
            var b1 = new MeshBuilder();

            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.25, 2, BoxFaces.All);
            Model     = b1.ToMeshGeometry3D();
            Instances = new[] { Matrix.Translation(0, 0, -1.5f), Matrix.Translation(0, 0, 1.5f) };

            var b2 = new MeshBuilder();

            b2.AddBox(new Vector3(0, 0, 0), 10, 0, 10, BoxFaces.PositiveY);
            Plane          = b2.ToMeshGeometry3D();
            PlaneTransform = new Media3D.TranslateTransform3D(-0, -2, -0);
            GrayMaterial   = PhongMaterials.Indigo;

            // lines model3d
            Lines = LineBuilder.GenerateBoundingBox(Model);
            //this.PropertyChanged += MainViewModel_PropertyChanged;
            // model trafos
            Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            RedMaterial   = PhongMaterials.Glass;
            GreenMaterial = PhongMaterials.Green;
            BlueMaterial  = PhongMaterials.Blue;
            GrayMaterial.RenderShadowMap = RedMaterial.RenderShadowMap = GreenMaterial.RenderShadowMap = BlueMaterial.RenderShadowMap = true;
            //var b3 = new MeshBuilder();
            //b3.AddBox(new Vector3(), 0.3f, 0.3f, 0.3f, BoxFaces.All);
            //b3.AddCone(new Vector3(0, 0.3f, 0), new Vector3(0, 0f, 0), 0.2f, true, 24);
            //LightCameraModel = b3.ToMesh();
            //LightCameraTransform.Children.Add(new Media3D.RotateTransform3D(new Media3D.AxisAngleRotation3D(new Vector3D(1, 0, 0), -135)));
            //LightCameraTransform.Children.Add(new Media3D.TranslateTransform3D(0, 3, 3));
            //UpdateCamera();
        }
Example #24
0
        /// <summary>
        /// Zooms the camera to the specified rectangle.
        /// </summary>
        /// <param name="camera">
        /// The camera.
        /// </param>
        /// <param name="viewport">
        /// The viewport.
        /// </param>
        /// <param name="zoomRectangle">
        /// The zoom rectangle.
        /// </param>
        public static void ZoomToRectangle(this ProjectionCamera camera, Viewport3D viewport, Rect zoomRectangle)
        {
            var topLeftRay  = Viewport3DHelper.Point2DtoRay3D(viewport, zoomRectangle.TopLeft);
            var topRightRay = Viewport3DHelper.Point2DtoRay3D(viewport, zoomRectangle.TopRight);
            var centerRay   = Viewport3DHelper.Point2DtoRay3D(
                viewport,
                new Point(
                    (zoomRectangle.Left + zoomRectangle.Right) * 0.5, (zoomRectangle.Top + zoomRectangle.Bottom) * 0.5));

            if (topLeftRay == null || topRightRay == null || centerRay == null)
            {
                // could not invert camera matrix
                return;
            }

            var u = topLeftRay.Direction;
            var v = topRightRay.Direction;
            var w = centerRay.Direction;

            u.Normalize();
            v.Normalize();
            w.Normalize();
            var perspectiveCamera = camera as PerspectiveCamera;

            if (perspectiveCamera != null)
            {
                var distance = camera.LookDirection.Length;

                // option 1: change distance
                var newDistance      = distance * zoomRectangle.Width / viewport.ActualWidth;
                var newLookDirection = newDistance * w;
                var newPosition      = perspectiveCamera.Position + ((distance - newDistance) * w);
                var newTarget        = newPosition + newLookDirection;
                LookAt(camera, newTarget, newLookDirection, 200);

                // option 2: change fov
                //    double newFieldOfView = Math.Acos(Vector3D.DotProduct(u, v));
                //    var newTarget = camera.Position + distance * w;
                //    pcamera.FieldOfView = newFieldOfView * 180 / Math.PI;
                //    LookAt(camera, newTarget, distance * w, 0);
            }

            var orthographicCamera = camera as OrthographicCamera;

            if (orthographicCamera != null)
            {
                orthographicCamera.Width *= zoomRectangle.Width / viewport.ActualWidth;
                var     oldTarget = camera.Position + camera.LookDirection;
                var     distance  = camera.LookDirection.Length;
                Point3D newTarget;
                if (centerRay.PlaneIntersection(oldTarget, w, out newTarget))
                {
                    orthographicCamera.LookDirection = w * distance;
                    orthographicCamera.Position      = newTarget - orthographicCamera.LookDirection;
                }
            }
        }
Example #25
0
 private static void ApplyLocation(ProjectionCamera target, PerspectiveCamera source)
 {
     if (target != null && source != null)
     {
         target.Position      = source.Position;
         target.LookDirection = source.LookDirection;
         target.UpDirection   = source.UpDirection;
     }
 }
Example #26
0
        /// <summary>
        /// Copies the specified camera, converts field of view/width if necessary.
        /// </summary>
        /// <param name="source">The source camera.</param>
        /// <param name="dest">The destination camera.</param>
        /// <param name="copyNearFarPlaneDistances">Copy near and far plane distances if set to <c>true</c>.</param>
        public static void Copy(this ProjectionCamera source, ProjectionCamera dest, bool copyNearFarPlaneDistances = true)
        {
            if (source == null || dest == null)
            {
                return;
            }

            dest.LookDirection = source.LookDirection;
            dest.Position      = source.Position;
            dest.UpDirection   = source.UpDirection;

            if (copyNearFarPlaneDistances)
            {
                dest.NearPlaneDistance = source.NearPlaneDistance;
                dest.FarPlaneDistance  = source.FarPlaneDistance;
            }

            var psrc  = source as PerspectiveCamera;
            var osrc  = source as OrthographicCamera;
            var pdest = dest as PerspectiveCamera;
            var odest = dest as OrthographicCamera;

            if (pdest != null)
            {
                double fov = 45;
                if (psrc != null)
                {
                    fov = psrc.FieldOfView;
                }

                if (osrc != null)
                {
                    double dist = source.LookDirection.Length;
                    fov = Math.Atan(osrc.Width / 2 / dist) * 180 / Math.PI * 2;
                }

                pdest.FieldOfView = fov;
            }

            if (odest != null)
            {
                double width = 100;
                if (psrc != null)
                {
                    double dist = source.LookDirection.Length;
                    width = Math.Tan(psrc.FieldOfView / 180 * Math.PI / 2) * dist * 2;
                }

                if (osrc != null)
                {
                    width = osrc.Width;
                }

                odest.Width = width;
            }
        }
        private void MatchCameras()
        {
            if (!this.adornedViewport.IsAttached || this.adornedViewport.ViewObject == null)
            {
                return;
            }
            Rect computedTightBounds = this.adornedViewport.GetComputedTightBounds();

            if (this.shadowAdorningContainer.Viewport != computedTightBounds)
            {
                this.shadowAdorningContainer.Viewport       = computedTightBounds;
                this.orthographicAdorningContainer.Viewport = computedTightBounds;
            }
            CameraElement camera = this.adornedViewport.Camera;

            if (camera == null)
            {
                return;
            }
            ProjectionCamera projectionCamera1 = camera.ViewObject.PlatformSpecificObject as ProjectionCamera;

            if (projectionCamera1 == null)
            {
                return;
            }
            ProjectionCamera   projectionCamera2   = (ProjectionCamera)this.shadowAdorningContainer.Camera;
            OrthographicCamera orthographicCamera1 = (OrthographicCamera)this.orthographicAdorningContainer.Camera;

            if (projectionCamera2.FarPlaneDistance != projectionCamera1.FarPlaneDistance || projectionCamera2.NearPlaneDistance != projectionCamera1.NearPlaneDistance || (projectionCamera2.LookDirection != projectionCamera1.LookDirection || projectionCamera2.Position != projectionCamera1.Position) || (projectionCamera2.UpDirection != projectionCamera1.UpDirection || projectionCamera2.Transform != projectionCamera1.Transform))
            {
                projectionCamera2.FarPlaneDistance  = projectionCamera1.FarPlaneDistance;
                projectionCamera2.NearPlaneDistance = projectionCamera1.NearPlaneDistance;
                projectionCamera2.LookDirection     = projectionCamera1.LookDirection;
                orthographicCamera1.LookDirection   = projectionCamera1.LookDirection;
                projectionCamera2.Position          = projectionCamera1.Position;
                orthographicCamera1.Position        = projectionCamera1.Position;
                projectionCamera2.UpDirection       = projectionCamera1.UpDirection;
                orthographicCamera1.UpDirection     = projectionCamera1.UpDirection;
            }
            PerspectiveCamera perspectiveCamera1 = projectionCamera1 as PerspectiveCamera;
            PerspectiveCamera perspectiveCamera2 = projectionCamera2 as PerspectiveCamera;

            if (perspectiveCamera1 != null && perspectiveCamera2 != null && perspectiveCamera1.FieldOfView != perspectiveCamera2.FieldOfView)
            {
                perspectiveCamera2.FieldOfView = perspectiveCamera1.FieldOfView;
            }
            OrthographicCamera orthographicCamera2 = projectionCamera1 as OrthographicCamera;
            OrthographicCamera orthographicCamera3 = projectionCamera2 as OrthographicCamera;

            if (orthographicCamera2 == null || orthographicCamera3 == null || orthographicCamera2.Width == orthographicCamera3.Width)
            {
                return;
            }
            orthographicCamera3.Width = orthographicCamera2.Width;
            orthographicCamera1.Width = orthographicCamera2.Width;
        }
Example #28
0
        /// <summary>
        /// Create a MatrixCamera from an existing ProjectionCamera
        /// </summary>
        /// <param name="camera">Camera</param>
        /// <param name="width">Viewport height</param>
        /// <param name="height">Viewport width</param>
        /// <returns>MatrixCamera</returns>
        public static MatrixCamera CreateMatrixCamera(ProjectionCamera camera, double width, double height)
        {
            MatrixCamera matrixCamera = new MatrixCamera(
                CreateViewMatrix(camera),
                CreateProjectionMatrix(camera, width, height, camera.NearPlaneDistance, camera.FarPlaneDistance));

            matrixCamera.Transform = camera.Transform;

            return(matrixCamera);
        }
Example #29
0
        /// <summary>
        /// Create a MatrixCamera from an existing ProjectionCamera
        /// </summary>
        /// <param name="camera">Camera</param>
        /// <param name="width">Viewport height</param>
        /// <param name="height">Viewport width</param>
        /// <param name="near">Near plane distance</param>
        /// <param name="far">Far plane distance</param>
        /// <returns>MatrixCamera</returns>
        public static MatrixCamera CreateMatrixCamera(ProjectionCamera camera, double width, double height, double near, double far)
        {
            MatrixCamera matrixCamera = new MatrixCamera(
                CreateViewMatrix(camera),
                CreateProjectionMatrix(camera, width, height, near, far));

            matrixCamera.Transform = camera.Transform;

            return(matrixCamera);
        }
Example #30
0
        private static void SetProjectionCameraParameters(Camera camera, Variation v)
        {
            ProjectionCamera c = (ProjectionCamera)camera;

            c.Position          = StringConverter.ToPoint3D(v["CameraPosition"]);
            c.LookDirection     = StringConverter.ToVector3D(v["CameraLookDirection"]);
            c.UpDirection       = StringConverter.ToVector3D(v["CameraUp"]);
            c.NearPlaneDistance = StringConverter.ToDouble(v["CameraNearPlaneDistance"]);
            c.FarPlaneDistance  = StringConverter.ToDouble(v["CameraFarPlaneDistance"]);
        }
Example #31
0
        /// <summary>
        /// Sets the properties of the specified camera to the settings stored in this object.
        /// </summary>
        /// <param name="camera">
        /// The camera.
        /// </param>
        public void UpdateCamera(ProjectionCamera camera)
        {
            camera.Position = this.Position;
            camera.LookDirection = this.LookDirection;
            camera.UpDirection = this.UpDirection;
            camera.NearPlaneDistance = this.NearPlaneDistance;
            camera.FarPlaneDistance = this.FarPlaneDistance;
            var perspectiveCamera = camera as PerspectiveCamera;
            if (perspectiveCamera != null)
            {
                perspectiveCamera.FieldOfView = this.FieldOfView;
            }

            var orthographicCamera = camera as OrthographicCamera;
            if (orthographicCamera != null)
            {
                orthographicCamera.Width = this.Width;
            }
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CameraSetting"/> class.
        /// </summary>
        /// <param name="camera">
        /// The camera.
        /// </param>
        public CameraSetting(ProjectionCamera camera)
        {
            this.Position = camera.Position;
            this.LookDirection = camera.LookDirection;
            this.UpDirection = camera.UpDirection;
            this.NearPlaneDistance = camera.NearPlaneDistance;
            this.FarPlaneDistance = camera.FarPlaneDistance;
            var pcamera = camera as PerspectiveCamera;
            if (pcamera != null)
            {
                this.FieldOfView = pcamera.FieldOfView;
            }

            var ocamera = camera as OrthographicCamera;
            if (ocamera != null)
            {
                this.Width = ocamera.Width;
            }
        }