Exemplo n.º 1
0
        public _3DRotate()
        {
            InitializeComponent();
            this.Content = grid;
            var        brush      = (Path)FindResource("WE");
            var        brush2     = (Path)FindResource("ER");
            Viewport3D viewport3D = new Viewport3D();

            viewport3D.Camera = new PerspectiveCamera()
            {
                Position = new Point3D(0, 0, 72), LookDirection = new Vector3D(0, 0, -1)
            };
            var material = new DiffuseMaterial()
            {
            };
            var v1 = new Viewport2DVisual3D()
            {
                Visual = brush, Material = material,
            };

            Viewport2DVisual3D.SetIsVisualHostMaterial(material, true);
            v1.Geometry = new MeshGeometry3D()
            {
                Positions = new Point3DCollection(
                    new List <Point3D>()
                {
                    new Point3D(-30, 30, 0), new Point3D(-30, -30, 0), new Point3D(30, -30, 0), new Point3D(30, 30, 0)
                }),
                TriangleIndices = new Int32Collection(new List <int>()
                {
                    0, 1, 2, 0, 2, 3
                }),
                TextureCoordinates = new PointCollection(new List <Point>()
                {
                    new Point(0, 0), new Point(0, 1), new Point(1, 1), new Point(1, 0)
                })
            };
            var material2 = new DiffuseMaterial()
            {
            };
            var v2 = new Viewport2DVisual3D()
            {
                Visual = brush2, Material = material2
            };

            Viewport2DVisual3D.SetIsVisualHostMaterial(material2, true);
            v2.Geometry = new MeshGeometry3D()
            {
                Positions = new Point3DCollection(
                    new List <Point3D>()
                {
                    new Point3D(30, 30, 0), new Point3D(30, -30, 0), new Point3D(-30, -30, 0), new Point3D(-30, 30, 0)
                }),
                TriangleIndices = new Int32Collection(new List <int>()
                {
                    0, 1, 2, 0, 2, 3
                }),
                TextureCoordinates = new PointCollection(new List <Point>()
                {
                    new Point(0, 0), new Point(0, 1), new Point(1, 1), new Point(1, 0)
                })
            };
            ContainerUIElement3D containerUIElement3D = new ContainerUIElement3D();

            viewport3D.Children.Add(containerUIElement3D);
            containerUIElement3D.Children.Add(v1);
            containerUIElement3D.Children.Add(v2);

            AxisAngleRotation3D aaa = new AxisAngleRotation3D()
            {
                Angle = 0, Axis = new Vector3D(0, 1, 0)
            };

            RegisterName("aar", aaa);

            RotateTransform3D rotate = new RotateTransform3D();

            rotate.Rotation = aaa;
            containerUIElement3D.Transform = rotate;

            ModelVisual3D modelVisual3D = new ModelVisual3D();
            var           light         = new AmbientLight()
            {
                Color = Color.FromArgb(255, 255, 255, 255),
            };

            modelVisual3D.Content = light;
            viewport3D.Children.Add(modelVisual3D);

            grid.Children.Add(viewport3D);
            grid.Background = Brushes.Yellow;
            var    i        = 0;
            Button btn_test = new Button()
            {
                Content = "test"
            };

            //grid.Children.Add(btn_test);

            grid.MouseLeftButtonDown += (sender, e) =>
            {
                DoubleAnimation da = new DoubleAnimation();
                da.Duration = new Duration(TimeSpan.FromSeconds(1));
                if (i % 2 == 1)
                {
                    da.To = 0d;
                }
                else
                {
                    da.To = 180d;
                }
                AxisAngleRotation3D aar = Application.Current.MainWindow.FindName("aar") as AxisAngleRotation3D;
                aar.BeginAnimation(AxisAngleRotation3D.AngleProperty, da);

                i++;
            };
        }
Exemplo n.º 2
0
        protected override void BeginTransition3D(
            TransitionPresenter transitionElement,
            ContentPresenter oldContent,
            ContentPresenter newContent,
            Viewport3D viewport)
        {
            Size size = transitionElement.RenderSize;

            Point   mouse2D = Mouse.GetPosition(transitionElement);
            Point3D mouse   = new Point3D(mouse2D.X, mouse2D.Y, 0.5 * size.Width);

            int xparticles = 10, yparticles = 10;

            if (size.Width > size.Height)
            {
                yparticles = (int)(xparticles * size.Height / size.Width);
            }
            else
            {
                xparticles = (int)(yparticles * size.Width / size.Height);
            }

            double   sx = 1.0 / xparticles, sy = 1.0 / yparticles;
            Vector3D u          = new Vector3D(size.Width * sx, 0, 0);
            Vector3D v          = new Vector3D(0, size.Height * sy, 0);
            Brush    cloneBrush = CreateBrush(oldContent);
            Material clone      = new DiffuseMaterial(cloneBrush);

            Vector3D[] velocities        = new Vector3D[xparticles * yparticles];
            Vector3D[] angularVelocities = new Vector3D[xparticles * yparticles];
            Point3D[]  centers           = new Point3D[xparticles * yparticles];

            Point3DCollection positions = new Point3DCollection(4 * xparticles * yparticles);
            PointCollection   textures  = new PointCollection(4 * xparticles * yparticles);
            Int32Collection   triangles = new Int32Collection(6 * xparticles * yparticles);
            int n = 0;

            for (int i = 0; i < xparticles; i++)
            {
                for (int j = 0; j < yparticles; j++)
                {
                    Point3D topleft = (Point3D)(i * u + j * v);
                    positions.Add(topleft);
                    positions.Add(topleft + u);
                    positions.Add(topleft + u + v);
                    positions.Add(topleft + v);

                    textures.Add(new Point(i * sx, j * sy));
                    textures.Add(new Point((i + 1) * sx, j * sy));
                    textures.Add(new Point((i + 1) * sx, (j + 1) * sy));
                    textures.Add(new Point(i * sx, (j + 1) * sy));


                    triangles.Add(n);
                    triangles.Add(n + 2);
                    triangles.Add(n + 1);

                    triangles.Add(n);
                    triangles.Add(n + 3);
                    triangles.Add(n + 2);

                    Vector3D f0 = positions[n] - mouse;
                    Vector3D f1 = positions[n + 1] - mouse;
                    Vector3D f2 = positions[n + 2] - mouse;
                    Vector3D f3 = positions[n + 3] - mouse;

                    f0 = f0 / f0.LengthSquared;
                    f1 = f1 / f1.LengthSquared;
                    f2 = f2 / f2.LengthSquared;
                    f3 = f3 / f3.LengthSquared;

                    velocities[n / 4] = 2 * size.Width * (f0 + f1 + f2 + f3);

                    Point3D center = centers[n / 4] = (Point3D)((i + 0.5) * u + (j + 0.5) * v);
                    angularVelocities[n / 4] = 200 * (Vector3D.CrossProduct(f0, positions[n] - center) +
                                                      Vector3D.CrossProduct(f1, positions[n + 1] - center) +
                                                      Vector3D.CrossProduct(f2, positions[n + 2] - center) +
                                                      Vector3D.CrossProduct(f3, positions[n + 3] - center));



                    n += 4;
                }
            }

            MeshGeometry3D mesh = new MeshGeometry3D();

            mesh.Positions          = positions;
            mesh.TextureCoordinates = textures;
            mesh.TriangleIndices    = triangles;

            GeometryModel3D geometryModel = new GeometryModel3D(mesh, clone);

            geometryModel.BackMaterial = clone;
            ModelVisual3D model = new ModelVisual3D();

            model.Content = geometryModel;
            viewport.Children.Add(model);



            DispatcherTimer timer        = new DispatcherTimer();
            int             t            = 0;
            double          opacityDelta = 1.0 / (Duration.TimeSpan.Seconds * 60.0);

            timer.Interval = TimeSpan.FromSeconds(1.0 / 60.0);
            timer.Tick    += delegate
            {
                t++;
                cloneBrush.Opacity = 1 - t * opacityDelta;
                if (cloneBrush.Opacity < opacityDelta)
                {
                    timer.Stop();
                    EndTransition(transitionElement, oldContent, newContent);
                    return;
                }
                mesh.Positions = null;
                AxisAngleRotation3D axisAngle = new AxisAngleRotation3D();
                RotateTransform3D   rotation  = new RotateTransform3D(axisAngle, new Point3D());
                for (int i = 0; i < positions.Count; i += 4)
                {
                    Vector3D velocity = velocities[i / 4];



                    axisAngle.Axis   = angularVelocities[i / 4];
                    axisAngle.Angle  = angularVelocities[i / 4].Length;
                    rotation.CenterX = centers[i / 4].X;
                    rotation.CenterY = centers[i / 4].Y;
                    rotation.CenterZ = centers[i / 4].Z;

                    positions[i]     = rotation.Transform(positions[i]) + velocity;
                    positions[i + 1] = rotation.Transform(positions[i + 1]) + velocity;
                    positions[i + 2] = rotation.Transform(positions[i + 2]) + velocity;
                    positions[i + 3] = rotation.Transform(positions[i + 3]) + velocity;


                    centers[i / 4] += velocity;
                }
                mesh.Positions = positions;
            };
            timer.Start();
        }
        private void AddRobotTransformations(RobotParts robotPart, Dictionary <string, Model3D> namedObjects)
        {
            try
            {
                Model3DGroup model3DGroup;

                if (robotPart == RobotParts.Main)
                {
                    model3DGroup  = namedObjects["Helper_Base"] as Model3DGroup;
                    _baseRotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 0, 1), BaseRotationSlider.Value);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_baseRotation));

                    model3DGroup  = namedObjects["Helper_Arm1"] as Model3DGroup;
                    _arm1Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(1, 0, 0), Arm1RotationSlider.Value);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_arm1Rotation));

                    model3DGroup  = namedObjects["Helper_Arm2"] as Model3DGroup;
                    _arm2Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(1, 0, 0), Arm2RotationSlider.Value);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_arm2Rotation));

                    model3DGroup  = namedObjects["Helper_Arm3"] as Model3DGroup;
                    _arm3Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(1, 0, 0), Arm3RotationSlider.Value);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_arm3Rotation));


                    // The robot tools are added to the "Helper_Extras" Model3DGroup.
                    model3DGroup = namedObjects["Helper_Extras"] as Model3DGroup;

                    // The original 3D model was created with coordinate system where Z axis is us (instead of Y up).
                    // When the model was exported to fbx, the exported added a transformation to convert the model to Y up coordinate system.
                    // If we now load another fbx file (robot tool) and add it to the last robot arm part,
                    // the tool will have the same coordinate system change transformation, but because we would add that to
                    // already transformed coordinate system, this would not work well.
                    // Therefore we need to add a transformation that will allow negate the coordinate system change transformation in the added file:

                    var matrixTransform3D = new MatrixTransform3D(new Matrix3D(1, 0, 0, 0,
                                                                               0, 0, 1, 0,
                                                                               0, -1, 0, 0,
                                                                               0, 0, 0, 1));

                    var transform3DGroup = new Transform3DGroup();
                    transform3DGroup.Children.Add(matrixTransform3D);

                    _toolRotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 0, 1), ToolRotationSlider.Value);
                    transform3DGroup.Children.Add(new RotateTransform3D(_toolRotation));

                    InsertTransformation(model3DGroup, transform3DGroup);
                }
                else if (robotPart == RobotParts.Claw)
                {
                    model3DGroup      = namedObjects["Helper_Claw_Left"] as Model3DGroup;
                    _clawLeftRotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 1, 0), 0);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_clawLeftRotation));

                    model3DGroup       = namedObjects["Helper_Claw_Right"] as Model3DGroup;
                    _clawRightRotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, -1, 0), 0);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_clawRightRotation));
                }
                else if (robotPart == RobotParts.Saw)
                {
                    model3DGroup = namedObjects["Helper_SawBlade"] as Model3DGroup;
                    _sawRotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(1, 0, 0), 0);
                    InsertTransformation(model3DGroup, new RotateTransform3D(_sawRotation));
                }
                else if (robotPart == RobotParts.Panel)
                {
                    _shownPanelGeometryModel3D = namedObjects["Robot_Panel_Screen"] as GeometryModel3D;

                    if (_shownPanelGeometryModel3D != null)
                    {
                        _shownPanelGeometryModel3D.Material = new DiffuseMaterial(Brushes.Black);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error setting robot transformations:\r\n" + ex.Message);
            }
        }
Exemplo n.º 4
0
        public EmissiveMaterialExample()
        {
            // Declare scene objects.
            Viewport3D      myViewport3D    = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;
            // The material property of GeometryModel3D specifies the material applied to the 3D object.
            // In this sample the material applied to the 3D object is made up of two materials layered
            // on top of each other - a DiffuseMaterial (gradient brush) with an EmissiveMaterial
            // layered on top (blue SolidColorBrush). The EmmisiveMaterial alters the appearance of
            // the gradient toward blue.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material that will use the gradient.
            DiffuseMaterial myDiffuseMaterial = new DiffuseMaterial(myHorizontalGradient);

            // Add this gradient to a MaterialGroup.
            MaterialGroup myMaterialGroup = new MaterialGroup();

            myMaterialGroup.Children.Add(myDiffuseMaterial);

            // Define an Emissive Material with a blue brush.
            Color c = new Color();

            c.ScA = 1;
            c.ScB = 255;
            c.ScR = 0;
            c.ScG = 0;
            EmissiveMaterial myEmissiveMaterial = new EmissiveMaterial(new SolidColorBrush(c));

            // Add the Emmisive Material to the Material Group.
            myMaterialGroup.Children.Add(myEmissiveMaterial);

            // Add the composite material to the 3D model.
            myGeometryModel.Material = myMaterialGroup;
            // Apply a transform to the object. In this sample, a rotation transform is applied,
            // rendering the 3D object rotated.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;
            myGeometryModel.Transform    = myRotateTransform3D;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;
            myViewport3D.Children.Add(myModelVisual3D);

            // Apply the viewport to the page so it will be rendered.
            this.Content = myViewport3D;
        }
Exemplo n.º 5
0
        public MultipleTransformationsExample()
        {
            // Declare scene objects.
            Viewport3D      myViewport3D    = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object. In this sample a
            // linear gradient covers the surface of the 3D object.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(myHorizontalGradient);

            myGeometryModel.Material = myMaterial;
            // Apply multiple transformations to the object. In this sample, a rotation and scale
            // transform is applied.

            // Create and apply a transformation that rotates the object.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;

            // Add the rotation transform to a Transform3DGroup
            Transform3DGroup myTransform3DGroup = new Transform3DGroup();

            myTransform3DGroup.Children.Add(myRotateTransform3D);

            // Create and apply a scale transformation that stretches the object along the local x-axis
            // by 200 percent and shrinks it along the local y-axis by 50 percent.
            ScaleTransform3D myScaleTransform3D = new ScaleTransform3D();

            myScaleTransform3D.ScaleX = 2;
            myScaleTransform3D.ScaleY = 0.5;
            myScaleTransform3D.ScaleZ = 1;

            // Add the scale transform to the Transform3DGroup.
            myTransform3DGroup.Children.Add(myScaleTransform3D);

            // Set the Transform property of the GeometryModel to the Transform3DGroup which includes
            // both transformations. The 3D object now has two Transformations applied to it.
            myGeometryModel.Transform = myTransform3DGroup;
            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;

            myViewport3D.Children.Add(myModelVisual3D);

            // Apply the viewport to the page so it will be rendered.
            this.Content = myViewport3D;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new Workshop3D instance.
        /// </summary>
        public Workshop3D()
        {
            this.Focusable = true;

            _viewport           = new Viewport3D();
            _viewport.Focusable = false;
            AddVisualChild(_viewport);

            PerspectiveCamera camera = new PerspectiveCamera();

            _viewport.Camera = camera;
            InitializeCamera();

            // INameScope ns = NameScope.GetNameScope(_viewport);
            // NameScope.SetNameScope(this, ns);

            // NameScope.SetNameScope(this, NameScope.GetNameScope(_viewport));
            // this.DataContext = _viewport.DataContext;

            DirectionalLight light1 = new DirectionalLight(Colors.White, new Vector3D(0.0, -1.0, 1.0));
            DirectionalLight light2 = new DirectionalLight(Colors.White, new Vector3D(-1.0, -1.0, -1.0));
            DirectionalLight light3 = new DirectionalLight(Colors.White, new Vector3D(1.0, -1.0, -1.0));
            DirectionalLight light4 = new DirectionalLight(Colors.White, new Vector3D(0.0, 1.0, 0.0));

            Model3DGroup mg = new Model3DGroup();

            mg.Children.Add(light1);
            mg.Children.Add(light2);
            mg.Children.Add(light3);
            mg.Children.Add(light4);
            _defaultLightingModel.Content = mg;
            _viewport.Children.Add(_defaultLightingModel);

            _rsd = new ResourceStringDecorator();
            _rsd.AssemblyName = "Perspective.Wpf";
            _rsd.BaseName     = "Controls.Strings.Workshop3D";
            AddVisualChild(_rsd);

            _commandPanel             = new StackPanel();
            _commandPanel.Focusable   = false;
            _commandPanel.Orientation = Orientation.Vertical;
            ComponentResourceKey panelStyleKey = new ComponentResourceKey(typeof(ResourceKeys), "PanelStyle");

            _commandPanel.Style   = (Style)this.FindResource(panelStyleKey);
            _commandPanel.Opacity = _opacity;
            _rsd.Child            = _commandPanel;

            ComponentResourceKey groupBoxStyleKey = new ComponentResourceKey(typeof(ResourceKeys), "GroupBoxStyle");
            Style groupBoxStyle = (Style)this.FindResource(groupBoxStyleKey);

            GroupBox gbZoom = new GroupBox();

            gbZoom.Style = groupBoxStyle;
            _commandPanel.Children.Add(gbZoom);

            // must be called after the insertion in the element tree
            // to get benefit of the ResourceManager inherited property
            gbZoom.Header = ResourceStringDecorator.InitializeValue(gbZoom, GroupBox.HeaderProperty, "FieldOfView");

            StackPanel spZoom = new StackPanel();

            gbZoom.Content = spZoom;

            _cameraZoomJoystick            = new Joystick();
            _cameraZoomJoystick.Dimensions = Dimensions.One;
            _cameraZoomJoystick.Focusable  = false;
            _cameraZoomJoystick.IsTabStop  = false;
            _cameraZoomJoystick.Startup   += new StartupEventHandler(_cameraZoomJoystick_Startup);
            _cameraZoomJoystick.Stop      += new RoutedEventHandler(_cameraZoomJoystick_Stop);
            spZoom.Children.Add(_cameraZoomJoystick);

            TextBlock     tbZoom = new TextBlock();
            SignalBinding bZoom  = new SignalBinding();

#if DN35
            // C# 3.0 : lambda expressions
            bZoom.Converting += (sender, e) =>
#else
            // C# 2.0 : anonymous methods
            bZoom.Converting += delegate(object sender, ConverterEventArgs e)
#endif
            {
                e.ConvertedValue = String.Format(e.Culture, "{0:###.0}°", e.Value);
            };

            bZoom.Source = camera;
            bZoom.Path   = new PropertyPath("FieldOfView");
            tbZoom.SetBinding(TextBlock.TextProperty, bZoom);
            spZoom.Children.Add(tbZoom);

            GroupBox gbPosition = new GroupBox();
            gbPosition.Style = groupBoxStyle;
            _commandPanel.Children.Add(gbPosition);

            // must be called after the insertion in the element tree
            // to get benefit of the ResourceManager inherited property
            gbPosition.Header = ResourceStringDecorator.InitializeValue(gbPosition, GroupBox.HeaderProperty, "Position");

            StackPanel spPosition = new StackPanel();
            gbPosition.Content = spPosition;

            _cameraPositionJoystick           = new Joystick();
            _cameraPositionJoystick.Focusable = false;
            _cameraPositionJoystick.IsTabStop = false;
            _cameraPositionJoystick.Startup  += new StartupEventHandler(_cameraPositionJoystick_Startup);
            _cameraPositionJoystick.Stop     += new RoutedEventHandler(_cameraPositionJoystick_Stop);
            spPosition.Children.Add(_cameraPositionJoystick);

            TextBlock     tbPosition = new TextBlock();
            SignalBinding bPosition  = new SignalBinding();

#if DN35
            // C# 3.0 : lambda expressions
            bPosition.Converting += (sender, e) =>
#else
            // C# 2.0 : anonymous methods
            bPosition.Converting += delegate(object sender, ConverterEventArgs e)
#endif
            {
                Point3D p = (Point3D)e.Value;
                e.ConvertedValue = String.Format(
                    e.Culture,
                    "{0:###.0}, {1:###.0}, {2:###.0}",
                    p.X, p.Y, p.Z);
            };

            bPosition.Source = camera;
            bPosition.Path   = new PropertyPath("Position");
            tbPosition.SetBinding(TextBlock.TextProperty, bPosition);
            spPosition.Children.Add(tbPosition);

            GroupBox gbLookDirection = new GroupBox();
            gbLookDirection.Style = groupBoxStyle;
            _commandPanel.Children.Add(gbLookDirection);

            // must be called after the insertion in the element tree
            // to get benefit of the ResourceManager inherited property
            gbLookDirection.Header = ResourceStringDecorator.InitializeValue(gbLookDirection, GroupBox.HeaderProperty, "LookDirection");

            StackPanel spLookDirection = new StackPanel();
            gbLookDirection.Content = spLookDirection;

            _cameraLookDirectionJoystick            = new Joystick();
            _cameraLookDirectionJoystick.Dimensions = Dimensions.Two;
            _cameraLookDirectionJoystick.Focusable  = false;
            _cameraLookDirectionJoystick.IsTabStop  = false;
            _cameraLookDirectionJoystick.Startup   += new StartupEventHandler(_cameraLookDirectionJoystick_Startup);
            _cameraLookDirectionJoystick.Stop      += new RoutedEventHandler(_cameraLookDirectionJoystick_Stop);
            spLookDirection.Children.Add(_cameraLookDirectionJoystick);

            TextBlock     tbLookDirection = new TextBlock();
            SignalBinding bLookDirection  = new SignalBinding();
#if DN35
            // C# 3.0 : lambda expressions
            bLookDirection.Converting += (sender, e) =>
#else
            // C# 2.0 : anonymous methods
            bLookDirection.Converting += delegate(object sender, ConverterEventArgs e)
#endif
            {
                Vector3D v = (Vector3D)e.Value;
                e.ConvertedValue = String.Format(
                    e.Culture,
                    "{0:N1}, {1:N1}, {2:N1}",
                    v.X, v.Y, v.Z);
            };

            bLookDirection.Source = camera;
            bLookDirection.Path   = new PropertyPath("LookDirection");
            tbLookDirection.SetBinding(TextBlock.TextProperty, bLookDirection);
            spLookDirection.Children.Add(tbLookDirection);

            // maps the Children property on the Viewport3D Children property
            SetValue(ChildrenPropertyKey, _viewport.Children);

            Duration duration = new Duration(TimeSpan.FromSeconds(2.0));

            _cameraPositionAnimation            = new Point3DAnimation();
            _cameraPositionAnimation.Duration   = duration;
            _cameraPositionAnimation.Completed += _cameraPositionAnimation_Completed;

            _cameraLookDirectionAnimation            = new Vector3DAnimation();
            _cameraLookDirectionAnimation.Duration   = duration;
            _cameraLookDirectionAnimation.Completed += _cameraLookDirectionAnimation_Completed;

            _cameraZoomAnimation                   = new DoubleAnimation();
            _cameraZoomAnimation.Duration          = duration;
            _cameraZoomAnimation.AccelerationRatio = 0.2;
            _cameraZoomAnimation.DecelerationRatio = 0.2;

            _cameraPositionRotation        = new AxisAngleRotation3D();
            _cameraPositionRotateTransform = new RotateTransform3D(_cameraPositionRotation);

            _cameraLookDirectionRotation        = new AxisAngleRotation3D();
            _cameraLookDirectionRotateTransform = new RotateTransform3D(_cameraLookDirectionRotation);

            this.Focusable = true;
        }
Exemplo n.º 7
0
        private void UpdateVisuals()
        {
            Children.Clear();
            if (WindTurbine == null)
            {
                return;
            }

            var baseTower = new TruncatedConeVisual3D
            {
                Fill   = Brushes.Yellow,
                Origin = new Point3D(0, 0, -WindTurbine.BaseHeight)
            };

            baseTower.Height     = -baseTower.Origin.Z + 2;
            baseTower.BaseRadius = baseTower.TopRadius = WindTurbine.Diameter;

            var tower = new TruncatedConeVisual3D
            {
                Fill       = Brushes.White,
                Origin     = new Point3D(0, 0, 2),
                Height     = WindTurbine.Height,
                BaseRadius = WindTurbine.Diameter
            };

            tower.TopRadius = tower.BaseRadius * (1 - WindTurbine.Height * Math.Sin(WindTurbine.ShaftAngle / 180.0 * Math.PI));

            var nacelle = new TruncatedConeVisual3D
            {
                Fill      = Brushes.White,
                Origin    = new Point3D(WindTurbine.Overhang, 0, tower.Origin.Z + tower.Height),
                Normal    = new Vector3D(-1, 0, 0),
                TopRadius = WindTurbine.NacelleDiameter
            };

            nacelle.BaseRadius = nacelle.TopRadius * 0.7;
            nacelle.Height     = WindTurbine.NacelleLength;

            Children.Add(baseTower);
            Children.Add(tower);
            Children.Add(nacelle);


            var endcap = new SphereVisual3D
            {
                Center = new Point3D(WindTurbine.Overhang - WindTurbine.NacelleLength, 0,
                                     tower.Origin.Z + tower.Height),
                Radius = nacelle.TopRadius,
                Fill   = Brushes.White
            };

            Children.Add(endcap);

            var rotor = new ModelVisual3D();

            for (int i = 0; i < WindTurbine.Blades; i++)
            {
                double angle = (double)i / WindTurbine.Blades * Math.PI * 2;

                // todo: the blade is simplified to a cone... it should be a real profile...
                var blade = new TruncatedConeVisual3D
                {
                    Origin     = nacelle.Origin,
                    Normal     = new Vector3D(0, Math.Cos(angle), Math.Sin(angle)),
                    Height     = WindTurbine.BladeLength,
                    BaseRadius = WindTurbine.BladeRootChord,
                    TopRadius  = WindTurbine.BladeTipChord,
                    Fill       = Brushes.White
                };
                rotor.Children.Add(blade);
            }

            var hub = new SphereVisual3D
            {
                Fill   = Brushes.White,
                Center = nacelle.Origin,
                Radius = WindTurbine.HubDiameter / 2
            };

            rotor.Children.Add(hub);
            Children.Add(rotor);

            var rotation       = new AxisAngleRotation3D(new Vector3D(1, 0, 0), 0);
            var rotorTransform = new RotateTransform3D(null, hub.Center)
            {
                Rotation = rotation
            };

            rotor.Transform = rotorTransform;

            var b = new Binding("RotationAngle")
            {
                Source = this
            };

            BindingOperations.SetBinding(rotation, AxisAngleRotation3D.AngleProperty, b);
        }
Exemplo n.º 8
0
        public RotationGizmo()
        {
            x    = new TorusVisual3D(innderRadius, outerRadius);
            y    = new TorusVisual3D(innderRadius, outerRadius);
            z    = new TorusVisual3D(innderRadius, outerRadius);
            xHit = new TorusVisual3D(innderRadius - selectionMargin, outerRadius + selectionMargin);
            yHit = new TorusVisual3D(innderRadius - selectionMargin, outerRadius + selectionMargin);
            zHit = new TorusVisual3D(innderRadius - selectionMargin, outerRadius + selectionMargin);

            containerX = new ContainerUIElement3D();
            containerX.Children.Add(x);
            containerX.Children.Add(xHit);
            containerY = new ContainerUIElement3D();
            containerY.Children.Add(y);
            containerY.Children.Add(yHit);
            containerZ = new ContainerUIElement3D();
            containerZ.Children.Add(z);
            containerZ.Children.Add(zHit);

            x.Material        = xMaterial;
            y.Material        = yMaterial;
            z.Material        = zMaterial;
            x.BackMaterial    = y.BackMaterial = z.BackMaterial = null;
            xHit.Material     = yHit.Material = zHit.Material = new EmissiveMaterial(Brushes.Transparent);
            xHit.BackMaterial = yHit.BackMaterial = zHit.BackMaterial = null;

            var torii      = new[] { x, y, z };
            var hits       = new[] { xHit, yHit, zHit };
            var containers = new[] { containerX, containerY, containerZ };

            for (int i = 0; i < 3; i++)
            {
                int iCopy     = i;
                var torus     = torii[i];
                var hit       = hits[i];
                var container = containers[i];
                var curMat    = torus.Material;
                container.MouseEnter += (sender, args) =>
                {
                    torus.Material = new DiffuseMaterial(Brushes.Yellow);
                };
                container.MouseLeave += (sender, args) =>
                {
                    torus.Material = curMat;
                };
                container.MouseDown += (sender, args) =>
                {
                    Mouse.Capture(container);
                    whichAxis    = iCopy + 1;
                    lastPosition = args.GetPosition(container);
                };
                container.MouseMove += (sender, args) =>
                {
                    if (whichAxis != 0)
                    {
                        Point  curPosition = args.GetPosition(container);
                        double offset      = curPosition.Y - lastPosition.Y;
                        double angle       = offset / 300 * 180;

                        Rotation3D rotation = new AxisAngleRotation3D(Transform.Transform(AXES[whichAxis - 1]), angle);
                        if (Rotated != null)
                        {
                            Rotated(rotation);
                        }

                        lastPosition = curPosition;
                    }
                };
                container.MouseUp += (sender, args) =>
                {
                    Mouse.Capture(null);
                    whichAxis = 0;
                };
            }
        }
Exemplo n.º 9
0
        private void UpdateRotation(object sender, EventArgs e)
        {
            //Clear prior values
            //find a cleaner way to do this--loop?
            QuaternionWText.Clear();
            QuaternionXText.Clear();
            QuaternionYText.Clear();
            QuaternionZText.Clear();

            M11Text.Clear();
            M21Text.Clear();
            M31Text.Clear();
            OffsetXText.Clear();
            M12Text.Clear();
            M22Text.Clear();
            M32Text.Clear();
            OffsetYText.Clear();
            M13Text.Clear();
            M23Text.Clear();
            M33Text.Clear();
            OffsetZText.Clear();
            M14Text.Clear();
            M24Text.Clear();
            M34Text.Clear();
            M44Text.Clear();

            //<SnippetMatrixTransform3DView3DN2>

            Double axisX = System.Convert.ToDouble(RotationAxisXText.Text);
            Double axisY = System.Convert.ToDouble(RotationAxisYText.Text);
            Double axisZ = System.Convert.ToDouble(RotationAxisZText.Text);
            Double angle = System.Convert.ToDouble(RotationAngleText.Text);

            Vector3D axis = new Vector3D(axisX, axisY, axisZ);

            try
            {
                myAxisAngleRotation3D = new AxisAngleRotation3D(axis, angle);
            }
            catch
            {
                MessageBox.Show("Set non-null values for the axis Vector3D.");
            }

            myRotateTransform3D.Rotation = myAxisAngleRotation3D;

            //</SnippetMatrixTransform3DView3DN2>

            //update matrix display
            //<SnippetMatrixTransform3DView3DN13>
            rotationMatrix3D = myRotateTransform3D.Value;
            M11Text.Text     = rotationMatrix3D.M11.ToString();
            //</SnippetMatrixTransform3DView3DN13>
            M21Text.Text     = rotationMatrix3D.M21.ToString();
            M31Text.Text     = rotationMatrix3D.M31.ToString();
            OffsetXText.Text = rotationMatrix3D.OffsetX.ToString();
            M12Text.Text     = rotationMatrix3D.M12.ToString();
            M22Text.Text     = rotationMatrix3D.M22.ToString();
            M32Text.Text     = rotationMatrix3D.M32.ToString();
            OffsetYText.Text = rotationMatrix3D.OffsetY.ToString();
            M13Text.Text     = rotationMatrix3D.M13.ToString();
            M23Text.Text     = rotationMatrix3D.M23.ToString();
            M33Text.Text     = rotationMatrix3D.M33.ToString();
            OffsetZText.Text = rotationMatrix3D.OffsetZ.ToString();
            M14Text.Text     = rotationMatrix3D.M14.ToString();
            M24Text.Text     = rotationMatrix3D.M24.ToString();
            M34Text.Text     = rotationMatrix3D.M34.ToString();
            M44Text.Text     = rotationMatrix3D.M44.ToString();

            myprocTransformGroup.Children.Clear();
            myprocTransformGroup.Children.Add(myRotateTransform3D);
            topModelVisual3D.Transform = myprocTransformGroup;

            //<SnippetMatrixTransform3DView3DN3>
            //convert to quaternion and update display
            try
            {
                Quaternion tempQuaternion = new Quaternion(axis, angle);
                QuaternionWText.Text = tempQuaternion.W.ToString();
                QuaternionXText.Text = tempQuaternion.X.ToString();
                QuaternionYText.Text = tempQuaternion.Y.ToString();
                QuaternionZText.Text = tempQuaternion.Z.ToString();
            }
            catch
            {
                MessageBox.Show("Set non-null values for the axis Vector3D.");
            }
            //</SnippetMatrixTransform3DView3DN3>
        }
Exemplo n.º 10
0
        private static GeometryModel3D createLineGeometryModel3D(System.Windows.Point point1, System.Windows.Point point2, AxisAngleRotation3D myAngleRotation)
        {
            MeshGeometry3D meshGeometry3D = new MeshGeometry3D();
            List <Point3D> points         = new List <Point3D>();

            points.Add(new Point3D(point1.X + 1, point1.Y + 1, 0));
            points.Add(new Point3D(point1.X, point1.Y, 6));
            points.Add(new Point3D(point2.X + 1, point2.Y + 1, 0));
            points.Add(new Point3D(point2.X, point2.Y, 6));

            points.Add(new Point3D(point1.X - 1, point1.Y - 1, 0));
            points.Add(new Point3D(point1.X, point1.Y, 6));
            points.Add(new Point3D(point2.X - 1, point2.Y - 1, 0));
            points.Add(new Point3D(point2.X, point2.Y, 6));

            meshGeometry3D.Positions = new Point3DCollection(points);
            meshGeometry3D.TriangleIndices.Add(0);
            meshGeometry3D.TriangleIndices.Add(2);
            meshGeometry3D.TriangleIndices.Add(3);
            meshGeometry3D.TriangleIndices.Add(0);
            meshGeometry3D.TriangleIndices.Add(3);
            meshGeometry3D.TriangleIndices.Add(1);


            meshGeometry3D.TriangleIndices.Add(4);
            meshGeometry3D.TriangleIndices.Add(7);
            meshGeometry3D.TriangleIndices.Add(6);
            meshGeometry3D.TriangleIndices.Add(4);
            meshGeometry3D.TriangleIndices.Add(5);
            meshGeometry3D.TriangleIndices.Add(7);


            meshGeometry3D.TriangleIndices.Add(0);
            meshGeometry3D.TriangleIndices.Add(3);
            meshGeometry3D.TriangleIndices.Add(2);
            meshGeometry3D.TriangleIndices.Add(0);
            meshGeometry3D.TriangleIndices.Add(1);
            meshGeometry3D.TriangleIndices.Add(3);


            meshGeometry3D.TriangleIndices.Add(4);
            meshGeometry3D.TriangleIndices.Add(6);
            meshGeometry3D.TriangleIndices.Add(7);
            meshGeometry3D.TriangleIndices.Add(4);
            meshGeometry3D.TriangleIndices.Add(7);
            meshGeometry3D.TriangleIndices.Add(5);

            DiffuseMaterial diffuseMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Black));

            GeometryModel3D geometryModel3D = new GeometryModel3D(meshGeometry3D, diffuseMaterial);

            RotateTransform3D rotateTransform3D = new RotateTransform3D();

            rotateTransform3D.Rotation = myAngleRotation;

            Transform3DGroup myTransform3DGroup = new Transform3DGroup();

            myTransform3DGroup.Children.Add(rotateTransform3D);

            geometryModel3D.Transform = myTransform3DGroup;

            return(geometryModel3D);
        }
Exemplo n.º 11
0
        private void AddWall(DrawingArgs e)
        {
            ModelVisual3D model = new ModelVisual3D();

            model.Content = Resources["wallModel" + e.PlayerNumber.ToString()] as Model3D;

            Transform3DGroup group = new Transform3DGroup();

            model.Transform = group;

            ScaleTransform3D scale = new ScaleTransform3D();

            if (e.From.X == e.To.X)
            {
                scale.ScaleX = 0.01;
            }
            else
            {
                scale.ScaleX = 0.02 * (Math.Abs(e.To.X - e.From.X)) + 0.01;
            }
            if (e.From.Y == e.To.Y)
            {
                scale.ScaleY = 0.01;
            }
            else
            {
                scale.ScaleY = 0.02 * (Math.Abs(e.To.Y - e.From.Y)) + 0.01;
            }
            scale.ScaleZ = 0.02;

            group.Children.Add(scale);
            RotateTransform3D rotate = new RotateTransform3D();

            group.Children.Add(rotate);
            TranslateTransform3D translate = new TranslateTransform3D();

            group.Children.Add(translate);
            double x = (e.To.X + e.From.X) / 2;
            double y = (e.To.Y + e.From.Y) / 2;

            translate.OffsetX = (x) * 0.02;
            translate.OffsetY = (y) * 0.02;

            if (Math.Abs(e.To.X - e.From.X) % 2 == 1)
            {
                translate.OffsetX += 0.01;
            }
            if (Math.Abs(e.To.Y - e.From.Y) % 2 == 1)
            {
                translate.OffsetY += 0.01;
            }

            translate.OffsetY = -translate.OffsetY;

            modelVisual3DRoot.Children.Add(model);

            //Camera animation

            if (e.PlayerNumber == 0)
            {
                AxisAngleRotation3D xRotation
                    = ((camera.Transform as Transform3DGroup).Children[0] as RotateTransform3D).Rotation as AxisAngleRotation3D;
                AxisAngleRotation3D rotation
                    = ((camera.Transform as Transform3DGroup).Children[1] as RotateTransform3D).Rotation as AxisAngleRotation3D;
                TranslateTransform3D translation
                    = (camera.Transform as Transform3DGroup).Children[2] as TranslateTransform3D;

                double offsetX = e.From.X * 0.02;
                double offsetY = e.From.Y * 0.02;

                double recul = 0.2;

                if (e.To.X != e.From.X)
                {
                    if (e.From.X < e.To.X)
                    {
                        offsetX -= recul;
                    }
                    else
                    {
                        offsetX += recul;
                    }
                }
                if (e.To.Y != e.From.Y)
                {
                    if (e.From.Y < e.To.Y)
                    {
                        offsetY -= recul;
                    }
                    else
                    {
                        offsetY += recul;
                    }
                }

                offsetY = -offsetY;

                ApplyDoubleAnimation(offsetX, new TimeSpan(0, 0, 0, 0, 300), translation, TranslateTransform3D.OffsetXProperty);
                ApplyDoubleAnimation(offsetY, new TimeSpan(0, 0, 0, 0, 300), translation, TranslateTransform3D.OffsetYProperty);
                ApplyDoubleAnimation(0.08, new TimeSpan(0, 0, 0, 0, 300), translation, TranslateTransform3D.OffsetZProperty);

                //camera.LookDirection = new Vector3D(-translate.OffsetX, -translate.OffsetY, 0);

                double angle = 0;

                switch (e.Direction)
                {
                case Direction.Down:
                    angle = 180;
                    break;

                case Direction.Left:
                    angle = 90;
                    break;

                case Direction.Right:
                    angle = 270;
                    break;

                case Direction.Up:
                    angle = 0;
                    break;
                }

                double animatedAngle = rotation.Angle;

                double tmp = Math.Floor(animatedAngle / 360);
                angle = angle + (tmp * 360);
                if (angle > animatedAngle)
                {
                    if (Math.Abs(animatedAngle - angle) > 180)
                    {
                        angle -= 360;
                    }
                }
                else
                {
                    if (Math.Abs(animatedAngle - angle) > 180)
                    {
                        angle += 360;
                    }
                }

                ApplyDoubleAnimation(-10, new TimeSpan(0, 0, 0, 0, 300), xRotation, AxisAngleRotation3D.AngleProperty);
                ApplyDoubleAnimation(angle, new TimeSpan(0, 0, 0, 0, 300), rotation, AxisAngleRotation3D.AngleProperty);
                //DoubleAnimation animRotation =
                //    new DoubleAnimation(angle, new Duration(new TimeSpan(0, 0, 0, 0, 300)));
                //rotation.ApplyAnimationClock(AxisAngleRotation3D.AngleProperty, animRotation.CreateClock());
            }
        }
Exemplo n.º 12
0
        public void BeachBallSphere()
        {
            //Title = "Beachball Sphere";

            // Create Viewport3D as content of window.
            Viewport3D viewport = new Viewport3D();

            Content = viewport;

            // Get the MeshGeometry3D from the GenerateSphere method.
            MeshGeometry3D mesh =
                GenerateSphere(new Point3D(0, 0, 0), 1, 36, 18);

            mesh.Freeze();

            // Define a brush for the sphere.
            Brush[] brushes = new Brush[6] {
                Brushes.Red, Brushes.Blue,
                Brushes.Yellow, Brushes.Orange,
                Brushes.Green, Brushes.White
            };
            DrawingGroup drawgrp = new DrawingGroup();

            for (int i = 0; i < brushes.Length; i++)
            {
                RectangleGeometry rectgeo =
                    new RectangleGeometry(new Rect(10 * i, 0, 10, 60));

                GeometryDrawing geodraw =
                    new GeometryDrawing(brushes[i], null, rectgeo);

                drawgrp.Children.Add(geodraw);
            }
            DrawingBrush drawbrsh = new DrawingBrush(drawgrp);

            drawbrsh.Freeze();

            // Define the GeometryModel3D.
            GeometryModel3D geomod = new GeometryModel3D();

            geomod.Geometry = mesh;
            geomod.Material = new DiffuseMaterial(drawbrsh);

            // Create a ModelVisual3D for the GeometryModel3D.
            ModelVisual3D modvis = new ModelVisual3D();

            modvis.Content = geomod;
            viewport.Children.Add(modvis);

            // Create another ModelVisual3D for light.
            Model3DGroup modgrp = new Model3DGroup();

            modgrp.Children.Add(new AmbientLight(Color.FromRgb(128, 128, 128)));
            modgrp.Children.Add(
                new DirectionalLight(Color.FromRgb(128, 128, 128),
                                     new Vector3D(2, -3, -1)));

            modvis         = new ModelVisual3D();
            modvis.Content = modgrp;
            viewport.Children.Add(modvis);

            // Create the camera.
            PerspectiveCamera cam = new PerspectiveCamera(new Point3D(0, 0, 8),
                                                          new Vector3D(0, 0, -1), new Vector3D(0, 1, 0), 45);

            viewport.Camera = cam;

            // Create a transform for the GeometryModel3D.
            AxisAngleRotation3D axisangle =
                new AxisAngleRotation3D(new Vector3D(1, 1, 0), 0);
            RotateTransform3D rotate = new RotateTransform3D(axisangle);

            geomod.Transform = rotate;

            // Animate the RotateTransform3D.
            DoubleAnimation anima =
                new DoubleAnimation(360, new Duration(TimeSpan.FromSeconds(5)));

            anima.RepeatBehavior = RepeatBehavior.Forever;
            axisangle.BeginAnimation(AxisAngleRotation3D.AngleProperty, anima);
        }
Exemplo n.º 13
0
        private void Rotate3DGeometry(object sender, EventArgs e)
        {
            //Delaying the rotation during start, and after every full revolution
            if (myRotationAngle == 1 && myDelayingOfRotation < myDelayingOfRotationConstant)
            {
                myDelayingOfRotation++;
                return;
            }

            if (myDelayingOfRotation >= myDelayingOfRotationConstant)
            {
                myDelayingOfRotation = 0;
            }

            //rotating 1 degrees every Tick
            myRotationAngle += 1;

            if (myRotationAngle >= 360)
            {
                myRotationAngle = 0;
            }

            this.viewport3DAboutProgram.Children.Clear();
            myModel3DGroup.Children.Clear();

            //creating Perspective camera
            PerspectiveCamera aCamera = CreateCamera();

            // Asign the camera to the viewport
            this.viewport3DAboutProgram.Camera = aCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Also, the direction of the lights affect shadowing. Note: to
            // illuminate an object from additional directions, create additional lights.
            DirectionalLight aDirectionalLight = CreateDirectionalLight();

            myModel3DGroup.Children.Add(aDirectionalLight);

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(0.5, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(0.5, 0.4, 0.0));
            myPositionCollection.Add(new Point3D(0.5, 0.4, 0.0));
            myPositionCollection.Add(new Point3D(-0.5, 0.4, 0.0));
            myPositionCollection.Add(new Point3D(-0.5, 0.2, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 1));

            GeometryModel3D aGeometryModelFrontAppName = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "CA Explorer");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();
            myPositionCollection.Add(new Point3D(-1.0, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(1.0, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(1.0, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(1.0, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, 0.0, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 1));

            GeometryModel3D aGeometryModelFrontMyName = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "Programmed by Adrian Magdina");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();
            myPositionCollection.Add(new Point3D(-0.3, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(0.3, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(0.3, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(0.3, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(-0.3, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(-0.3, -0.2, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 1));

            GeometryModel3D aGeometryModelFrontYear = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "in 2013");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();
            myPositionCollection.Add(new Point3D(-1.0, -0.4, 0.0));
            myPositionCollection.Add(new Point3D(1.0, -0.4, 0.0));
            myPositionCollection.Add(new Point3D(1.0, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(1.0, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, -0.4, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(0, 1));

            GeometryModel3D aGeometryModelFrontEMail = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "*****@*****.**");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(0.5, 0.4, 0.0));
            myPositionCollection.Add(new Point3D(0.5, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(-0.5, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(-0.5, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(-0.5, 0.4, 0.0));
            myPositionCollection.Add(new Point3D(0.5, 0.4, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));

            GeometryModel3D aGeometryModelBackAppName = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "CA Explorer");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(1.0, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(1.0, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, 0.2, 0.0));
            myPositionCollection.Add(new Point3D(1.0, 0.2, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));

            GeometryModel3D aGeometryModelBackMyName = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "Programmed by Adrian Magdina");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(0.3, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(0.3, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(-0.3, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(-0.3, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(-0.3, 0.0, 0.0));
            myPositionCollection.Add(new Point3D(0.3, 0.0, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));

            GeometryModel3D aGeometryModelBackYear = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "in 2013");

            // Create a collection of vertex positions for the MeshGeometry3D.
            myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(1.0, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(1.0, -0.4, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, -0.4, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, -0.4, 0.0));
            myPositionCollection.Add(new Point3D(-1.0, -0.2, 0.0));
            myPositionCollection.Add(new Point3D(1.0, -0.2, 0.0));

            // Create a collection of texture coordinates for the MeshGeometry3D.
            myTextureCoordinatesCollection = new PointCollection();
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));

            GeometryModel3D aGeometryModelBackEMail = CreateGeometryModel3D(myPositionCollection, myTextureCoordinatesCollection, 1.0, "*****@*****.**");

            // Apply a transform to the object. In this sample, a rotation transform is applied,
            // rendering the 3D object rotated.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis           = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle          = myRotationAngle;
            myRotateTransform3D.Rotation         = myAxisAngleRotation3d;
            aGeometryModelFrontAppName.Transform = myRotateTransform3D;
            aGeometryModelFrontMyName.Transform  = myRotateTransform3D;
            aGeometryModelFrontYear.Transform    = myRotateTransform3D;
            aGeometryModelFrontEMail.Transform   = myRotateTransform3D;
            aGeometryModelBackAppName.Transform  = myRotateTransform3D;
            aGeometryModelBackMyName.Transform   = myRotateTransform3D;
            aGeometryModelBackYear.Transform     = myRotateTransform3D;
            aGeometryModelBackEMail.Transform    = myRotateTransform3D;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(aGeometryModelFrontAppName);
            myModel3DGroup.Children.Add(aGeometryModelFrontMyName);
            myModel3DGroup.Children.Add(aGeometryModelFrontYear);
            myModel3DGroup.Children.Add(aGeometryModelFrontEMail);
            myModel3DGroup.Children.Add(aGeometryModelBackAppName);
            myModel3DGroup.Children.Add(aGeometryModelBackMyName);
            myModel3DGroup.Children.Add(aGeometryModelBackYear);
            myModel3DGroup.Children.Add(aGeometryModelBackEMail);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;

            this.viewport3DAboutProgram.Children.Add(myModelVisual3D);
        }
Exemplo n.º 14
0
        private void AdjustTextDirection()
        {
            var camera = Viewport.Camera as ProjectionCamera;

            var upVec = camera.UpDirection;

            upVec.Normalize();
            var horVec = Vector3D.CrossProduct(_up, camera.LookDirection);

            horVec.Normalize();

            ////Axis for rotate to up direction
            var axis1 = Vector3D.CrossProduct(_up, upVec);
            //Axis for rotate from textDirection to horVec.
            var axis2 = Vector3D.CrossProduct(_horDirection, horVec);

            var degree1 = Vector3D.AngleBetween(_up, upVec);
            var degree2 = Vector3D.AngleBetween(_horDirection, horVec);

            AxisAngleRotation3D aar1 = new AxisAngleRotation3D(axis1, degree1);
            AxisAngleRotation3D aar2 = new AxisAngleRotation3D(axis2, degree2);

            QuaternionRotation3D qr = new QuaternionRotation3D();

            if (axis1 != zeroVec && axis2 != zeroVec)
            {
                Quaternion q1 = new Quaternion(axis1, degree1);
                Quaternion q2 = new Quaternion(axis2, degree2);
                qr.Quaternion = q1 * q2;
            }
            else if (axis1 == zeroVec && axis2 != zeroVec)
            {
                Quaternion q2 = new Quaternion(axis2, degree2);
                qr.Quaternion = q2;
            }
            else if (axis1 != zeroVec && axis2 == zeroVec)
            {
                Quaternion q1 = new Quaternion(axis1, degree1);
                qr.Quaternion = q1;
            }
            else
            {
                return;
            }

            Transform3D transform = new RotateTransform3D(qr, _center);

            _model3D.Transform = transform;



            //Axis for rotate to up direction
            axis1 = Vector3D.CrossProduct(_up, upVec);
            //Axis for rotate from textDirection to horVec.
            axis2   = Vector3D.CrossProduct(_horDirection, horVec);
            degree1 = Vector3D.AngleBetween(_up, upVec);
            degree2 = Vector3D.AngleBetween(_horDirection, horVec);

            Transform3DGroup tg = new Transform3DGroup();

            if (axis1 != zeroVec)
            {
                Quaternion           q1         = new Quaternion(axis1, degree1);
                QuaternionRotation3D qr1        = new QuaternionRotation3D(q1);
                Transform3D          transform1 = new RotateTransform3D(qr1, _center);
                tg.Children.Add(transform1);
                uPline.Transform = transform1;
            }

            if (axis2 != zeroVec)
            {
                Quaternion           q2         = new Quaternion(axis2, degree2);
                QuaternionRotation3D qr1        = new QuaternionRotation3D(q2);
                Transform3D          transform1 = new RotateTransform3D(qr1, _center);
                tg.Children.Add(transform1);
                lookline.Transform = transform1;
            }
            //this.Transform = tg;
        }
Exemplo n.º 15
0
        protected override void BeginTransition3D(TransitionElement transitionElement, ContentPresenter oldContent, ContentPresenter newContent, Viewport3D viewport)
        {
            Brush clone = CreateBrush(transitionElement, oldContent);

            Size           size     = transitionElement.RenderSize;
            MeshGeometry3D leftDoor = CreateMesh(new Point3D(),
                                                 new Vector3D(size.Width / 2, 0, 0),
                                                 new Vector3D(0, size.Height, 0),
                                                 1,
                                                 1,
                                                 new Rect(0, 0, 0.5, 1));

            GeometryModel3D leftDoorGeometry = new GeometryModel3D();

            leftDoorGeometry.Geometry = leftDoor;
            leftDoorGeometry.Material = new DiffuseMaterial(clone);

            AxisAngleRotation3D leftRotation = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0);

            leftDoorGeometry.Transform = new RotateTransform3D(leftRotation);

            GeometryModel3D rightDoorGeometry = new GeometryModel3D();
            MeshGeometry3D  rightDoor         = CreateMesh(new Point3D(size.Width / 2, 0, 0),
                                                           new Vector3D(size.Width / 2, 0, 0),
                                                           new Vector3D(0, size.Height, 0),
                                                           1,
                                                           1,
                                                           new Rect(0.5, 0, 0.5, 1));

            rightDoorGeometry.Geometry = rightDoor;
            rightDoorGeometry.Material = new DiffuseMaterial(clone);

            AxisAngleRotation3D rightRotation = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0);

            rightDoorGeometry.Transform = new RotateTransform3D(rightRotation, size.Width, 0, 0);


            Model3DGroup doors = new Model3DGroup();

            doors.Children.Add(leftDoorGeometry);
            doors.Children.Add(rightDoorGeometry);

            ModelVisual3D model = new ModelVisual3D();

            model.Content = doors;
            viewport.Children.Add(model);

            DoubleAnimation da = new DoubleAnimation(90 - 0.5 * FieldOfView, Duration);

            leftRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, da);

            da = new DoubleAnimation(-(90 - 0.5 * FieldOfView), Duration);
            rightRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, da);

            da            = new DoubleAnimation(0, Duration);
            da.Completed += delegate
            {
                EndTransition(transitionElement, oldContent, newContent);
            };
            clone.BeginAnimation(Brush.OpacityProperty, da);
        }
        /// <summary>
        /// Reset to startup conditions
        /// </summary>
        private void Reset()
        {
            // trace file
#if DEBUG
            Trace.Write("Reset");
#endif

            // create Viewport3D and add it to CubeGrid parent
            CubeViewPort3D = new Viewport3D()
            {
                //Name = "mainViewport",
                ClipToBounds = true
            };
            CubeGrid.Children.Clear();
            CubeGrid.Children.Add(CubeViewPort3D);

            // create ModelVisual3D and add it to Viewport3D
            ModelVisual3D ModelVisual = new ModelVisual3D();
            CubeViewPort3D.Children.Add(ModelVisual);

            // create Model3DGroup with white ambiant light and attach it to ModelViual
            Model3DGroup ModelGroup = new Model3DGroup();
            ModelGroup.Children.Add(new AmbientLight(Colors.White));
            ModelVisual.Content = ModelGroup;

            // create our rubik's cube and attach it to ViewPort
            RubiksCube3D = new Cube3D();
            CubeViewPort3D.Children.Add(RubiksCube3D);

            // camera position relative to the cube
            // camera is looking directly to the cube
            double PosZ = Cube3D.CameraDistance * Math.Sin(Cube3D.CameraUpAngle);
            double Temp = Cube3D.CameraDistance * Math.Cos(Cube3D.CameraUpAngle);
            double PosX = Temp * Math.Sin(Cube3D.CameraRightAngle);
            double PosY = Temp * Math.Cos(Cube3D.CameraRightAngle);

            // create camera and attach it to ViewPort
            CubeViewPort3D.Camera = new PerspectiveCamera(new Point3D(PosX, -PosY, PosZ),
                                                          new Vector3D(-PosX, PosY, -PosZ), new Vector3D(0, 0, 1), Cube3D.CameraViewAngle);

            // full cube motion transformation group allows the program to
            // rotate the whole cube in any direction
            Transform3DGroup FullCubeMotion = new Transform3DGroup();
            RubiksCube3D.Transform = FullCubeMotion;
            FullCubeZRotation      = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 0);
            FullCubeMotion.Children.Add(new RotateTransform3D(FullCubeZRotation));
            FullCubeXRotation = new AxisAngleRotation3D(new Vector3D(1, 0, 0), 0);
            FullCubeMotion.Children.Add(new RotateTransform3D(FullCubeXRotation));
            FullCubeYRotation = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0);
            FullCubeMotion.Children.Add(new RotateTransform3D(FullCubeYRotation));

            // list of active solution steps
            NextMoves = new List <int>();

            // list of saved moves to be used by undo button
            PastMoves = new List <int>();

            // type of rotation that is active
            RotationActive = RotationActive.Idle;

            // mouse left button hit list
            HitList      = new List <BlockFace3D>();
            RotationLock = false;

            // current top and front face color
            TopFaceColor   = -1;
            FrontFaceColor = -1;
            SetUpAndFrontFace(true, 2, 0);

            // clear information labels
            ResetInfoLabels(false);
            return;
        }
Exemplo n.º 17
0
        private void Update_SparklyCount()
        {
            if (!_isVisualAdded)
            {
                return;
            }

            int count = 0;

            if (_ramDirHistory == null || _ramDirHistory.Count == 0)
            {
                count = 0;
            }
            else
            {
                count = _ramDirHistory.Count / 4;
            }

            if (count == _sparklies.Count)
            {
                return;
            }
            else if (count < _sparklies.Count)
            {
                #region Too Many

                while (count < _sparklies.Count)
                {
                    int index = StaticRandom.Next(_sparklies.Count);

                    _modelGroup.Children.Remove(_sparklies[index].Item1);
                    _sparklies.RemoveAt(index);
                }

                #endregion
            }
            else
            {
                #region Too Few

                while (_sparklies.Count < count)
                {
                    Random rand = StaticRandom.GetRandomForThread();

                    GeometryModel3D geometry = new GeometryModel3D();
                    geometry.Material     = _sparklyMaterial.Value;
                    geometry.BackMaterial = _sparklyMaterial.Value;
                    geometry.Geometry     = UtilityWPF.GetSphere_LatLon(1, rand.NextPercent(.09, .33));   // this radius will be affected by scale

                    Transform3DGroup transform = new Transform3DGroup();

                    // Translate
                    Vector3D translate = Math3D.GetRandomVector_Circular(.5, 1).ToVector2D().ToVector3D(Math1D.GetNearZeroValue(.375));
                    transform.Children.Add(new TranslateTransform3D(translate));

                    // Rotate from Z to X
                    transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), 90)));

                    // Animated rotate around X
                    AxisAngleRotation3D axisAngle = new AxisAngleRotation3D(new Vector3D(1, 0, 0), 10);
                    double angle = rand.NextDouble(180, 360);
                    if (rand.Next(2) == 0)
                    {
                        angle *= -1;
                    }
                    AnimateRotation animate = AnimateRotation.Create_Constant(axisAngle, angle);
                    transform.Children.Add(new RotateTransform3D(axisAngle));

                    // Scale
                    transform.Children.Add(_scale);

                    geometry.Transform = transform;

                    _modelGroup.Children.Add(geometry);

                    _sparklies.Add(Tuple.Create(geometry, animate));
                }

                #endregion
            }
        }
        /// <summary>
        /// Rotate one side
        /// </summary>
        /// <param name="RotateCode">Rotation code</param>
        private void RotateSide
        (
            int RotateCode
        )
        {
            // rotate code
            if (RotateCode >= 0)
            {
                PastMoves.Add(RotateCode);
            }
            // undo-take rotation code from past move list
            else
            {
                // trace
#if DEBUG
                Trace.Write("Undo");
#endif

                RotateCode = PastMoves[PastMoves.Count - 1];
                PastMoves.RemoveAt(PastMoves.Count - 1);
                switch (RotateCode % 3)
                {
                case 0:
                    RotateCode += 2;
                    break;

                case 2:
                    RotateCode -= 2;
                    break;
                }
            }

            // save rotation code
            this.RotateCode = RotateCode;

            // there are 18 rotation codes 3 for each cube face
            // RotateFace 0=white, 1=blue, 2=red, 3=green, 4=orange, 5=yellow
            int RotateFace = RotateCode / 3;

            // create a transform group
            RotateTransformGroup = new Transform3DGroup();

            // attach the transform group object to all 9 blocks of the face to be rotated
            for (int Index = 0; Index < Cube.BlocksPerFace; Index++)
            {
                RubiksCube3D.CubeFaceBlockArray[RotateFace][Index].Transform = RotateTransformGroup;
            }

            // create axis rotation for the transform group
            AxisAngleRotation3D AxisRot = new AxisAngleRotation3D(Cube3D.RotationAxis[RotateFace], 0);
            RotateTransformGroup.Children.Add(new RotateTransform3D(AxisRot));

            // start the animation
            // note: AnimationArray is an array of 3 DoubleAnnimation objects.
            // The three objects are 90Deg 0.25Sec, 180Deg 0.5Sec, -90Deg 0.25Sec
            AxisRot.BeginAnimation(AxisAngleRotation3D.AngleProperty, AnimationArray[RotateCode % 3]);

            // set rotation lock
            RotationLock = true;
            return;
        }
Exemplo n.º 19
0
        private void CameraTranslate(Direction?d)
        {
            PerspectiveCamera camera = (PerspectiveCamera)_viewport.Camera;

            if (d == null)
            {
                // Stops the animation

                // testing _cameraTranslating is not reliable
                // if (_cameraTranslating && camera.HasAnimatedProperties)

                if (camera.HasAnimatedProperties)
                {
                    Point3D currentPosition = camera.Position;
                    camera.ApplyAnimationClock(PerspectiveCamera.PositionProperty, null);
                    camera.Position = currentPosition;
                    // _cameraTranslating = false;
                }
            }
            else
            {
                Vector3D v  = camera.LookDirection;
                Vector3D vY = new Vector3D(0.0, 1.0, 0.0);
                Vector3D vRelativeHorizontalAxis = Vector3D.CrossProduct(v, vY);
                Vector3D vRelativeVerticalAxis   = Vector3D.CrossProduct(v, vRelativeHorizontalAxis);

                if (d != Direction.Forward)
                {
                    AxisAngleRotation3D rotation = new AxisAngleRotation3D();
                    switch (d)
                    {
                    case Direction.Forward | Direction.Left:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = -45.0;
                        break;

                    case Direction.Left:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = -90.0;
                        break;

                    case Direction.Backward | Direction.Left:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = -135.0;
                        break;

                    case Direction.Backward:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = 180.0;
                        break;

                    case Direction.Backward | Direction.Right:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = 135.0;
                        break;

                    case Direction.Right:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = 90.0;
                        break;

                    case Direction.Forward | Direction.Right:
                        rotation.Axis  = vRelativeVerticalAxis;
                        rotation.Angle = 45.0;
                        break;

                    case Direction.Up:
                        rotation.Axis  = vRelativeHorizontalAxis;
                        rotation.Angle = 90.0;
                        break;

                    case Direction.Down:
                        rotation.Axis  = vRelativeHorizontalAxis;
                        rotation.Angle = -90.0;
                        break;
                    }
                    RotateTransform3D transform = new RotateTransform3D(rotation);
                    v = transform.Transform(camera.LookDirection);
                }
                Point3D p = new Point3D(v.X, v.Y, v.Z);
                _cameraPositionAnimation.By = p;
                //_cameraTranslating = true;
                camera.ApplyAnimationClock(PerspectiveCamera.PositionProperty, _cameraPositionAnimation.CreateClock());
            }
        }
Exemplo n.º 20
0
        private void tmpMouseDown(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("It works!!!");
            // Declare scene objects.
            Viewport3D      myViewport3D    = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();
            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;
            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object. In this sample a
            // linear gradient covers the surface of the 3D object.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(myHorizontalGradient);

            myGeometryModel.Material = myMaterial;

            // Apply a transform to the object. In this sample, a rotation transform is applied,
            // rendering the 3D object rotated.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;
            myGeometryModel.Transform    = myRotateTransform3D;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;


            //
            myViewport3D.Children.Add(myModelVisual3D);

            // Apply the viewport to the page so it will be rendered.
            //this.Content = myViewport3D;
            Grid.SetRow(myViewport3D, 0);
            Grid.SetColumn(myViewport3D, 1);
            STLgrid.Children.Add(myViewport3D);
            //this.tabSTL.Content = myViewport3D;
        }
Exemplo n.º 21
0
        public override void CreateVertices()
        {
            my_VertexCount = (my_Steps + 1) * (my_Slices + 1);
            Matrix3D rm = CalculateRotationMatrix(InitialRotationAxis.X, InitialRotationAxis.Y, InitialRotationAxis.Z);

            my_Vertices  = new Vector3D[my_VertexCount];
            centerPoints = new Vector3D[my_Steps + 1];
            int                 count = 0;
            double              mu;
            double              x;
            double              y;
            double              z;
            Vector3D            V;
            Vector3D            V1 = new Vector3D();
            AxisAngleRotation3D Aar;
            RotateTransform3D   rotT;

            //Calculate the knot center coordinates
            for (int I = 0; I <= my_Steps; I++)
            {
                mu = I * 2.0 * Math.PI * a2 / my_Steps;
                x  = my_Size * (Math.Cos(mu) * (1 + Math.Cos(a1 * mu / a2) / 2.0));
                y  = my_Size * (Math.Sin(mu) * (1 + Math.Cos(b1 * mu / b2) / 2.0));
                z  = my_Size * (Math.Sin(c1 * mu / c2) / 2.0);
                centerPoints[I] = new Vector3D(x, y, z);
            }
            //Calculate the vertex positions at my_Diameter / 2 around the knot center coordinates
            for (int I = 0; I < my_Steps; I++)
            {
                V    = centerPoints[I + 1] - centerPoints[I];
                Aar  = new AxisAngleRotation3D(V, 360.0 / my_Slices);
                rotT = new RotateTransform3D(Aar);
                if (V.X != 0 | V.Z != 0)
                {
                    V1 = Vector3D.CrossProduct(V, new Vector3D(0, 1, 0));
                }
                else if (V.Y != 0)
                {
                    V1 = Vector3D.CrossProduct(V, new Vector3D(0, 0, 1));
                }
                V1.Normalize();
                V1 = (my_Diameter / 2.0) * V1;
                for (int J = 0; J <= my_Slices; J++)
                {
                    my_Vertices[count] = V1 + centerPoints[I];
                    V1     = rotT.Transform(V1);
                    count += 1;
                }
            }
            //Add vertices around the first knot coordinate again to close the knot.
            V    = centerPoints[1] - centerPoints[0];
            Aar  = new AxisAngleRotation3D(V, 360.0 / my_Slices);
            rotT = new RotateTransform3D(Aar);
            if (V.X != 0 | V.Z != 0)
            {
                V1 = Vector3D.CrossProduct(V, new Vector3D(0, 1, 0));
            }
            else if (V.Y != 0)
            {
                V1 = Vector3D.CrossProduct(V, new Vector3D(0, 0, 1));
            }
            V1.Normalize();
            V1 = (my_Diameter / 2.0) * V1;
            for (int J = 0; J <= my_Slices; J++)
            {
                my_Vertices[count] = V1 + centerPoints[0];
                V1     = rotT.Transform(V1);
                count += 1;
            }
            //Apply the initial rotation
            for (int I = 0; I < my_VertexCount; I++)
            {
                my_Vertices[I] = rm.Transform(my_Vertices[I]);
            }
        }
Exemplo n.º 22
0
        public ModelRotatorSample()
        {
            InitializeComponent();

            _normalMaterial   = new DiffuseMaterial(Brushes.Silver);
            _selectedMaterial = new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(150, 192, 192, 192))); // semi-transparent Silver

            _eventManager = new Ab3d.Utilities.EventManager3D(MainViewport);


            // Setup events on ModelRotatorVisual3D
            SelectedModelRotator.ModelRotateStarted += delegate(object sender, ModelRotatedEventArgs args)
            {
                if (_selectedBoxModel == null)
                {
                    return;
                }

                // When a new rotation is started, we create a new AxisAngleRotation3D with the used Axis or rotation
                // During the rotation we will adjust the angle (inside ModelRotated event handler)
                _axisAngleRotation3D = new AxisAngleRotation3D(args.RotationAxis, 0);

                // Insert the new rotate transform before the last translate transform that positions the box
                var rotateTransform3D = new RotateTransform3D(_axisAngleRotation3D);

                AddTransform(_selectedBoxModel, rotateTransform3D);
            };

            SelectedModelRotator.ModelRotated += delegate(object sender, ModelRotatedEventArgs args)
            {
                if (_selectedBoxModel == null)
                {
                    return;
                }

                _axisAngleRotation3D.Angle = args.RotationAngle;
            };

            SelectedModelRotator.ModelRotateEnded += delegate(object sender, ModelRotatedEventArgs args)
            {
                // Nothing to do here in this sample
                // The event handler is here only for description purposes
            };

            // To create custom circle 3D model, use the CreateCustomCircleModelCallback.
            // The following commented code shows how the default circle 3D model is created
            //SelectedModelRotator.CreateCustomCircleModelCallback = delegate (Vector3D normalVector3D, double innerRadius, double outerRadius, Brush circleBrush)
            //{
            //    int segmentsCount = 30;
            //    double circleHeight = outerRadius * 0.05; // Height is 20 times smaller than outer radius

            //    var tubeMesh3D = new Ab3d.Meshes.TubeMesh3D(new Point3D(0, 0, 0), normalVector3D, outerRadius, innerRadius, circleHeight, segmentsCount);

            //    var geometryModel3D = new GeometryModel3D(tubeMesh3D.Geometry, new DiffuseMaterial(circleBrush));

            //    return geometryModel3D;
            //};


            CreateRandomScene();
        }
Exemplo n.º 23
0
        // Create a DrawingVisual that contains a 3D object.
        private DrawingVisual Create3DVisualObject()
        {
            // Declare scene objects.

            // The Viewport3DVisual is used instead of the Viewport3D object because this 3D
            // object is drawn directly to the WPF visual layer. Using Viepwor3dVisual can provide
            // performance benefits over using Viewport3D although it does not support many of the
            // features that Viewport3D does.
            Viewport3DVisual myViewport3D    = new Viewport3DVisual();
            Model3DGroup     myModel3DGroup  = new Model3DGroup();
            GeometryModel3D  myGeometryModel = new GeometryModel3D();
            ModelVisual3D    myModelVisual3D = new ModelVisual3D();

            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            DirectionalLight myDirectionalLight = new DirectionalLight();

            myDirectionalLight.Color     = Colors.White;
            myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61);

            myModel3DGroup.Children.Add(myDirectionalLight);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5));
            myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 0));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(1, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 1));
            myTextureCoordinatesCollection.Add(new Point(0, 0));
            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object. In this sample a
            // linear gradient covers the surface of the 3D object.

            // Create a horizontal linear gradient with four stops.
            LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();

            myHorizontalGradient.StartPoint = new Point(0, 0.5);
            myHorizontalGradient.EndPoint   = new Point(1, 0.5);
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
            myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1.0));

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(myHorizontalGradient);

            myGeometryModel.Material = myMaterial;

            // Apply a transform to the object. In this sample, a rotation transform is applied,
            // rendering the 3D object rotated.
            RotateTransform3D   myRotateTransform3D   = new RotateTransform3D();
            AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();

            myAxisAngleRotation3d.Axis   = new Vector3D(0, 3, 0);
            myAxisAngleRotation3d.Angle  = 40;
            myRotateTransform3D.Rotation = myAxisAngleRotation3d;
            myGeometryModel.Transform    = myRotateTransform3D;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;

            // Create a rectangle to view the 3D object in.
            Rect myRectangle = new Rect();

            myRectangle.Location = new Point(10, 5);
            myRectangle.Size     = new Size(900, 900);

            myViewport3D.Children.Add(myModelVisual3D);
            myViewport3D.Viewport = myRectangle;

            DrawingVisual dv = new DrawingVisual();

            dv.Children.Add(myViewport3D);
            return(dv);
        }
Exemplo n.º 24
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //_quick = new BackdropQuick();
                //_quick.Show();
                //_quick.ValueChanged += _quick_ValueChanged;


                //NOTE: This MUST be set in loaded, or keyboard events get very flaky (even if the usercontrol has focus, something
                //inside of it must also have focus)
                lblFocusable.Focus();

                // Setting these up now so that the order stays consistent (so that semitransparency will work)

                #region Back visual

                _backVisual = new ModelVisual3D();
                if (_graphic == null)
                {
                    _backVisual.Content = GetBlankModel();
                }
                else
                {
                    _backVisual.Content = _graphic.Model;
                }

                _viewport.Children.Add(_backVisual);

                #endregion

                #region 2D panel

                DiffuseMaterial diffuse = new DiffuseMaterial(Brushes.White);
                Viewport2DVisual3D.SetIsVisualHostMaterial(diffuse, true);

                grd3D = new Grid();

                grd3D.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new GridLength(2, GridUnitType.Star)
                });
                grd3D.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new GridLength(.5, GridUnitType.Star)
                });
                grd3D.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new GridLength(1, GridUnitType.Star)
                });

                Grid.SetColumn(pnlLeft, 0);
                Grid.SetColumn(pnlDetail, 2);

                grd3D.Children.Add(pnlLeft);
                grd3D.Children.Add(pnlDetail);

                _visual2D3D          = new Viewport2DVisual3D();
                _visual2D3D.Material = diffuse;
                //_visual2D3D.Geometry = GetGeometry(_quick.CylinderNumSegments, _quick.CylinderThetaOffset, _quick.CylinderHeight, _quick.CylinderRadius, _quick.CylinderTranslate);
                _visual2D3D.Geometry  = GetGeometry(NUMSEGMENTS, THETA, HEIGHT, RADIUS, TRANSLATE);
                _visual2D3D.Visual    = grd3D;
                _visual2D3D.Transform = new TranslateTransform3D(0, 0, _cameraLength * .3);

                _viewport.IsHitTestVisible = true;

                _viewport.Children.Add(_visual2D3D);

                #endregion

                #region Detail Visual

                _detailVisual         = new ModelVisual3D();
                _detailVisual.Content = GetBlankModel();

                Transform3DGroup transform = new Transform3DGroup();

                _detailRotationInitial = new QuaternionRotation3D();
                transform.Children.Add(new RotateTransform3D(_detailRotationInitial));

                _detailRotationAnimate = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0);
                transform.Children.Add(new RotateTransform3D(_detailRotationAnimate));

                _detailTranslate = new TranslateTransform3D(0, 0, 0);       // this one is so the model can be centered on zero
                transform.Children.Add(_detailTranslate);

                _detailScale = new ScaleTransform3D(1, 1, 1);
                transform.Children.Add(_detailScale);

                transform.Children.Add(new TranslateTransform3D(_cameraLength * .1, 0, 0));     // this one is so the visual is shifted into the final place on screen

                _detailVisual.Transform = transform;

                _viewport.Children.Add(_detailVisual);

                UpdateDetailVisual();

                #endregion

                _detailAnimate = AnimateRotation.Create_Constant(_detailRotationAnimate, 30);

                chkIs3D.IsChecked = _is3DPanel;

                _isInitialized = true;

                Update2D3DPanels();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "BackdropPanel", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 25
0
        protected override void BeginTransition3D(TransitionElement transitionElement, ContentPresenter oldContent, ContentPresenter newContent, Viewport3D viewport)
        {
            Size size = transitionElement.RenderSize;

            // Create a rectangle
            MeshGeometry3D mesh = CreateMesh(new Point3D(),
                                             new Vector3D(size.Width, 0, 0),
                                             new Vector3D(0, size.Height, 0),
                                             1,
                                             1,
                                             new Rect(0, 0, 1, 1));

            GeometryModel3D geometry = new GeometryModel3D();

            geometry.Geometry = mesh;
            VisualBrush clone = new VisualBrush(oldContent);

            geometry.Material = new DiffuseMaterial(clone);

            ModelVisual3D model = new ModelVisual3D();

            model.Content = geometry;

            viewport.Children.Add(model);

            Vector3D axis;
            Point3D  center = new Point3D();

            switch (Direction)
            {
            case RotateDirection.Left:
                axis = new Vector3D(0, 1, 0);
                break;

            case RotateDirection.Right:
                axis   = new Vector3D(0, -1, 0);
                center = new Point3D(size.Width, 0, 0);
                break;

            case RotateDirection.Up:
                axis = new Vector3D(-1, 0, 0);
                break;

            default:
                axis   = new Vector3D(1, 0, 0);
                center = new Point3D(0, size.Height, 0);
                break;
            }
            AxisAngleRotation3D rotation = new AxisAngleRotation3D(axis, 0);

            model.Transform = new RotateTransform3D(rotation, center);

            DoubleAnimation da = new DoubleAnimation(0, Duration);

            clone.BeginAnimation(Brush.OpacityProperty, da);

            da            = new DoubleAnimation(90, Duration);
            da.Completed += delegate
            {
                EndTransition(transitionElement, oldContent, newContent);
            };
            rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, da);
        }
Exemplo n.º 26
0
        private DoubleAnimation Rotate(int face, double angle, double animationTime = 200)
        {
            Vector3D        axis   = RotationAxis[face];
            DoubleAnimation result = null;

            // we must update the array that contains the position of each cubelet
            var rotatedCubelets = new Model3DGroup[Size, Size, Size];

            for (int i = 0; i < Size; i++)
            {
                for (int j = 0; j < Size; j++)
                {
                    for (int k = 0; k < Size; k++)
                    {
                        rotatedCubelets[i, j, k] = cubelets[i, j, k];
                    }
                }
            }

            // positive angle is turning clockwise
            // turning face 0: (fix,*,*)

            //  2,0 2,1 2,2      2,2 1,2 0,2
            //  1,0 1,1 1,2  =>  2,1 1,1 0,1
            //  0,0 0,1 0,2      2,0 1,0 0,0

            // if angle is negative we need to rotate
            // the cubelets the other way

            int n = Size - 1;

            // this method only supports rotating the outer sides of the cube

            for (int a = 0; a < Size; a++)
            {
                for (int b = 0; b < Size; b++)
                {
                    int at = b;
                    int bt = n - a;
                    if (angle < 0)
                    {
                        at = n - b;
                        bt = a;
                    }

                    Model3DGroup group = null;
                    switch (face)
                    {
                    case 0:
                        group = rotatedCubelets[0, at, bt] = cubelets[0, a, b];
                        break;

                    case 1:
                        group = rotatedCubelets[n, bt, at] = cubelets[n, b, a];
                        break;

                    case 2:
                        group = rotatedCubelets[bt, 0, at] = cubelets[b, 0, a];
                        break;

                    case 3:
                        group = rotatedCubelets[at, n, bt] = cubelets[a, n, b];
                        break;

                    case 4:
                        group = rotatedCubelets[at, bt, 0] = cubelets[a, b, 0];
                        break;

                    case 5:
                        group = rotatedCubelets[bt, at, n] = cubelets[b, a, n];
                        break;

                    default:
                        continue;
                    }

                    var rot = new AxisAngleRotation3D {
                        Axis = axis
                    };
                    var anim = new DoubleAnimation(angle, new Duration(TimeSpan.FromMilliseconds(animationTime)))
                    {
                        AccelerationRatio = 0.3,
                        DecelerationRatio = 0.5
                    };

                    rot.BeginAnimation(AxisAngleRotation3D.AngleProperty, anim);
                    if (result == null)
                    {
                        result = anim;
                    }

                    var rott = new RotateTransform3D(rot);
                    var gt   = new Transform3DGroup();
                    gt.Children.Add(group.Transform);
                    gt.Children.Add(rott);
                    group.Transform = gt;
                }
            }
            cubelets = rotatedCubelets;

            // can subscribe to the Completed event on this
            return(result);
        }
Exemplo n.º 27
0
        // Make a transformation for rotation around an arbitrary axis.
        public static RotateTransform3D Rotate(Vector3D axis, Point3D center, double angle)
        {
            Rotation3D rotation = new AxisAngleRotation3D(axis, angle);

            return(new RotateTransform3D(rotation, center));
        }
Exemplo n.º 28
0
        private void InitializeEffect3D(Window window)
        {
            #region Viewport
            AxisAngleRotation3D angle = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0);
            ScaleTransform3D    scale = new ScaleTransform3D();
            Transform3DGroup    t3dg  = new Transform3DGroup();
            t3dg.Children.Add(scale);
            t3dg.Children.Add(new RotateTransform3D(angle));

            MeshGeometry3D mg3d = new MeshGeometry3D();
            mg3d.TriangleIndices    = new Int32Collection(new int[] { 0, 1, 2, 0, 2, 3 });
            mg3d.TextureCoordinates = new PointCollection(new Point[] { new Point(0, 0), new Point(0, 1), new Point(1, 1), new Point(1, 0), });

            Viewport2DVisual3D Viewport2d = new Viewport2DVisual3D();
            Viewport2d.Geometry = mg3d;
            Viewport2d.Material = new DiffuseMaterial(Brushes.White);
            Viewport2DVisual3D.SetIsVisualHostMaterial(Viewport2d.Material, true);
            Viewport2d.Transform = t3dg;

            Viewport3d        = new Viewport3D();
            Viewport3d.Camera = new PerspectiveCamera()
            {
                FieldOfView = 40
            };
            ModelVisual3D light1 = new ModelVisual3D();
            light1.Content = new DirectionalLight(Colors.White, new Vector3D(1, 1.733, -1));
            ModelVisual3D light2 = new ModelVisual3D();
            light2.Content = new DirectionalLight(Colors.White, new Vector3D(1, -1.733, -1));
            ModelVisual3D light3 = new ModelVisual3D();
            light3.Content = new DirectionalLight(Colors.White, new Vector3D(-2, 0, -1));
            Viewport3d.Children.Add(light1);
            Viewport3d.Children.Add(light2);
            Viewport3d.Children.Add(light3);
            Viewport3d.Children.Add(Viewport2d);
            #endregion
            #region Animation
            window.RegisterName("Viewport2d_Angle", angle);
            PropertyPath path = new PropertyPath(AxisAngleRotation3D.AngleProperty);
            DoubleAnimationUsingKeyFrames daukf = new DoubleAnimationUsingKeyFrames();
            Storyboard.SetTargetName(daukf, "Viewport2d_Angle");
            Storyboard.SetTargetProperty(daukf, path);

            SplineDoubleKeyFrame   KeyFrame1 = new SplineDoubleKeyFrame(90, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.25)), new KeySpline(0.7, 0.5, 0.3, 0.2));
            DiscreteDoubleKeyFrame KeyFrame2 = new DiscreteDoubleKeyFrame(-90, KeyTime.FromPercent(0.5));
            daukf.KeyFrames.Add(KeyFrame1);
            daukf.KeyFrames.Add(KeyFrame2);
            daukf.KeyFrames.Add(new SplineDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.5)), new KeySpline(0.2, 0.3, 0.5, 0.7)));

            Storyboard = new Storyboard();
            Storyboard.Children.Add(daukf);
            Storyboard.Completed += (sender, e) =>
            {
                try
                {
                    Viewport2d.Visual = null;
                    window.Content    = new_page;
                }
                catch { }
                finally { EffectEnable = true; }
            };

            angle.Changed += (sender, e) =>
            {
                if (angle.Angle < -70 && Viewport2d.Visual != this.new_page)
                {
                    try { Viewport2d.Visual = this.new_page; }
                    catch { }
                }

                scale.ScaleX             = scale.ScaleY
                                         = 1 - Math.Abs(Math.Sin(angle.Angle / 180 * Math.PI) / 2.75);
            };
            #endregion
            #region Effect
            setTurnStyle = (isV, isX) =>
            {
                int v = isV ? -90 : 90;
                KeyFrame1.Value = v;
                KeyFrame2.Value = -v;
                int x = isX ? 1 : 0;
                angle.Axis = new Vector3D(x, 1 - x, 0);
            };

            effectBegin = (old_page, new_page) =>
            {
                Viewport3d.Width  = old_page.Width;
                Viewport3d.Height = old_page.Height;
                this.new_page     = new_page;
                window.Content    = Viewport3d;
                Viewport2d.Visual = old_page;
                EffectEnable      = false;
                ((PerspectiveCamera)Viewport3d.Camera).Position = new Point3D(0, 0, 2.75 * old_page.Width);
                setPositions(mg3d, old_page.RenderSize);

                Storyboard.Begin(window);
            };

            EffectEnable = true;
            #endregion
        }
Exemplo n.º 29
0
        public BackwardAnimatedAxisRotator(AxisAngleRotation3D axis) : base(axis)
        {

        }
Exemplo n.º 30
0
        private void kinect_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            using (SkeletonFrame skelFrame = e.OpenSkeletonFrame())
            {
                if (skelFrame != null && masterSettings.kinectOptionsList.Count > kinectID && (masterKinectSettings.mergeSkeletons || masterKinectSettings.sendRawSkeletons))
                {
                    DateTime   now       = DateTime.UtcNow;
                    Skeleton[] skeletons = new Skeleton[skelFrame.SkeletonArrayLength];
                    skelFrame.CopySkeletonDataTo(skeletons);


                    EigenWrapper.Matrix predAccel = new EigenWrapper.Matrix(3, 1);
                    predAccel[2, 0] = 1;
                    if (accelFilterStarted)
                    {
                        predAccel = accelerationFilter.PredictAndDiscard(0);
                    }

                    if (interactStream != null)
                    {
                        Vector4 filteredAccel = new Vector4();
                        filteredAccel.W = 0;
                        filteredAccel.X = (float)predAccel[0, 0];
                        filteredAccel.Y = (float)predAccel[1, 0];
                        filteredAccel.Z = (float)predAccel[2, 0];
                        interactStream.ProcessSkeleton(skeletons, filteredAccel, skelFrame.Timestamp);

                        System.Diagnostics.Trace.WriteLine("[" + filteredAccel.X + ", " + filteredAccel.Y + ", " + filteredAccel.Z + "]");
                    }

                    //Generate the transformation matrix for the skeletons
                    double               kinectYaw                  = masterKinectSettings.kinectYaw;
                    Point3D              kinectPosition             = masterKinectSettings.kinectPosition;
                    Matrix3D             gravityBasedKinectRotation = findRotation(new Vector3D(predAccel[0, 0], predAccel[1, 0], predAccel[2, 0]), new Vector3D(0, -1, 0));
                    AxisAngleRotation3D  yawRotation                = new AxisAngleRotation3D(new Vector3D(0, 1, 0), -kinectYaw);
                    RotateTransform3D    tempTrans                  = new RotateTransform3D(yawRotation);
                    TranslateTransform3D transTrans                 = new TranslateTransform3D((Vector3D)kinectPosition);
                    Matrix3D             masterMatrix               = Matrix3D.Multiply(Matrix3D.Multiply(tempTrans.Value, gravityBasedKinectRotation), transTrans.Value);
                    skeletonTransformation = masterMatrix;

                    //Convert from Kinect v1 skeletons to KVR skeletons
                    KinectBase.KinectSkeleton[] kvrSkeletons = new KinectBase.KinectSkeleton[skeletons.Length];
                    for (int i = 0; i < kvrSkeletons.Length; i++)
                    {
                        //Set the tracking ID numbers for the hand grab data
                        int grabID = -1;
                        for (int j = 0; j < skeletonHandGrabData.Count; j++)
                        {
                            if (skeletonHandGrabData[j].skeletonTrackingID == skeletons[i].TrackingId)
                            {
                                grabID = j;
                                break;
                            }
                        }
                        if (grabID < 0)
                        {
                            skeletonHandGrabData.Add(new HandGrabInfo(skeletons[i].TrackingId));
                            grabID = skeletonHandGrabData.Count - 1;
                        }

                        kvrSkeletons[i]          = new KinectBase.KinectSkeleton();
                        kvrSkeletons[i].Position = new Point3D(skeletons[i].Position.X, skeletons[i].Position.Y, skeletons[i].Position.Z);
                        kvrSkeletons[i].SkeletonTrackingState = convertTrackingState(skeletons[i].TrackingState);
                        kvrSkeletons[i].TrackingId            = skeletons[i].TrackingId;
                        //kvrSkeletons[i].utcSampleTime = DateTime.UtcNow;
                        kvrSkeletons[i].sourceKinectID = kinectID;

                        for (int j = 0; j < skeletons[i].Joints.Count; j++)
                        {
                            KinectBase.Joint newJoint = new KinectBase.Joint();
                            newJoint.Confidence = KinectBase.TrackingConfidence.Unknown; //The Kinect 1 doesn't support the confidence property
                            newJoint.JointType  = convertJointType(skeletons[i].Joints[(JointType)j].JointType);
                            Vector4 tempQuat = skeletons[i].BoneOrientations[(JointType)j].AbsoluteRotation.Quaternion;
                            newJoint.Orientation = new Quaternion(tempQuat.X, tempQuat.Y, tempQuat.Z, tempQuat.W);
                            SkeletonPoint tempPos = skeletons[i].Joints[(JointType)j].Position;
                            newJoint.Position      = new Point3D(tempPos.X, tempPos.Y, tempPos.Z);
                            newJoint.TrackingState = convertTrackingState(skeletons[i].Joints[(JointType)j].TrackingState);
                            newJoint.utcTime       = now;
                            kvrSkeletons[i].skeleton[newJoint.JointType] = newJoint; //Skeleton doesn't need to be initialized because it is done in the KinectSkeleton constructor
                        }

                        //Get the hand states from the hand grab data array
                        kvrSkeletons[i].rightHandClosed = skeletonHandGrabData[grabID].rightHandClosed;
                        kvrSkeletons[i].leftHandClosed  = skeletonHandGrabData[grabID].leftHandClosed;
                    }

                    //Add the skeleton data to the event handler and throw the event
                    KinectBase.SkeletonEventArgs skelE = new KinectBase.SkeletonEventArgs();
                    skelE.skeletons = kvrSkeletons;
                    skelE.kinectID  = kinectID;

                    OnSkeletonChanged(skelE);
                }
            }
        }