//https://stackoverflow.com/questions/18558910/direction-vector-to-rotation-matrix

        //Vector3 column1;
        //Vector3 column2;
        //Vector3 column3;


        public static Matrix3x3 makeRotationDir(Vector3 direction, Vector3 up) //  Vector3 up = 0,1,0
        {
            Matrix3x3 mat = Matrix3x3.Identity;

            Vector3 xaxis = Vector3.Cross(up, direction);

            xaxis.Normalize();

            Vector3 yaxis = Vector3.Cross(direction, xaxis);

            yaxis.Normalize();

            mat.M11 = xaxis.X;
            mat.M12 = yaxis.X;
            mat.M13 = direction.X;

            mat.M21 = xaxis.Y;
            mat.M21 = yaxis.Y;
            mat.M21 = direction.Y;

            mat.M31 = xaxis.Z;
            mat.M31 = yaxis.Z;
            mat.M31 = direction.Z;
            return(mat);
        }
Esempio n. 2
0
        /// <summary>
        /// Function to add a vertex to the list.
        /// </summary>
        /// <param name="pos">Position of the vertex.</param>
        /// <returns>The new index.</returns>
        private int AddVertex(DX.Vector3 pos)
        {
            pos.Normalize();
            _vertices.Add(pos);

            return(_index++);
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            TreeNode[] nodes = parentForm.treeViewConfiguration.Nodes.Find("Radome", false);
            nodes[0].Text = "Геометрия обтекателя";
            nodes[0].Nodes.Clear();
            for (int i = 0; i < tempRadome.Count; i++)
            {
                tempRadome[i].Lable = dataGridView1[1, i].Value.ToString();
                parentForm.AddRadomeGeometryNameToTreeView(tempRadome[i]);
            }
            Logic.Instance.RadomeComposition = tempRadome;

            if (Logic.Instance.RadomeComposition.Count > 0)
            {
                CameraManager.Instance.CameraAt(0);

                SharpDX.Vector3 eye    = CameraManager.Instance.returnCamera(0).eye;
                SharpDX.Vector3 target = CameraManager.Instance.returnCamera(0).target;
                SharpDX.Vector3 up     = CameraManager.Instance.returnCamera(0).up;

                SharpDX.Vector3 newEye = (eye - target);
                newEye.Normalize();
                newEye = SharpDX.Vector3.Multiply(newEye, (float)Logic.Instance.RadomeComposition.DiagonalSize * 3f) + target;
                CameraManager.Instance.returnCamera(0).eye = newEye;;
                CameraManager.Instance.returnCamera(0).SetView(newEye, target, up);
            }
            this.Close();
        }
Esempio n. 4
0
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3  up       = MathHelper.Convert(freelook.Up);

            sceneConstants.View        = Matrix.LookAtLH(MathHelper.Convert(freelook.Eye), MathHelper.Convert(freelook.Target), up);
            sceneConstants.Projection  = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane);
            sceneConstants.ViewInverse = Matrix.Invert(sceneConstants.View);

            Vector3 light = new Vector3(20, 30, 10);
            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Matrix lightView       = Matrix.LookAtLH(light, Vector3.Zero, up);
            Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);

            sceneConstants.LightViewProjection = lightView * lightProjection;

            DataStream data;

            _immediateContext.MapSubresource(sceneConstantsBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data);
            Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
            _immediateContext.UnmapSubresource(sceneConstantsBuffer, 0);
            data.Dispose();

            inverseProjectionVar.SetMatrix(Matrix.Invert(sceneConstants.Projection));
            inverseViewVar.SetMatrix(sceneConstants.ViewInverse);
            lightInverseViewProjectionVar.SetMatrix(Matrix.Invert(sceneConstants.LightViewProjection));
            lightPositionVar.Set(new Vector4(light, 1));
            eyePositionVar.Set(new Vector4(MathHelper.Convert(freelook.Eye), 1));
            eyeZAxisVar.Set(new Vector4(Vector3.Normalize(MathHelper.Convert(freelook.Target - freelook.Eye)), 1));

            float tanHalfFOVY = (float)Math.Tan(FieldOfView * 0.5f);

            tanHalfFOVXVar.Set(tanHalfFOVY * AspectRatio);
            tanHalfFOVYVar.Set(tanHalfFOVY);
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;

            projectionAVar.Set(projectionA);
            projectionBVar.Set(projectionB);

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);

            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            overlayViewProjectionVar.SetMatrix(overlayMatrix);
        }
Esempio n. 5
0
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3  up       = MathHelper.Convert(freelook.Up);

            sceneConstants.View        = Matrix.LookAtLH(MathHelper.Convert(freelook.Eye), MathHelper.Convert(freelook.Target), up);
            sceneConstants.Projection  = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane);
            sceneConstants.ViewInverse = Matrix.Invert(sceneConstants.View);

            Vector3 light = new Vector3(20, 30, 10);
            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Matrix lightView       = Matrix.LookAtLH(light, Vector3.Zero, up);
            Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);

            sceneConstants.LightViewProjection = lightView * lightProjection;

            using (var data = sceneConstantsBuffer.Map(MapMode.WriteDiscard))
            {
                Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
                sceneConstantsBuffer.Unmap();
            }

            effect2.GetVariableByName("InverseProjection").AsMatrix().SetMatrix(Matrix.Invert(sceneConstants.Projection));
            effect2.GetVariableByName("InverseView").AsMatrix().SetMatrix(sceneConstants.ViewInverse);
            effect2.GetVariableByName("LightInverseViewProjection").AsMatrix().SetMatrix(Matrix.Invert(sceneConstants.LightViewProjection));
            effect2.GetVariableByName("LightPosition").AsVector().Set(new Vector4(light, 1));
            effect2.GetVariableByName("EyePosition").AsVector().Set(new Vector4(MathHelper.Convert(freelook.Eye), 1));
            effect2.GetVariableByName("EyeZAxis").AsVector().Set(new Vector4(Vector3.Normalize(MathHelper.Convert(freelook.Target - freelook.Eye)), 1));

            float tanHalfFOVY = (float)Math.Tan(FieldOfView * 0.5f);

            effect2.GetVariableByName("TanHalfFOVX").AsScalar().Set(tanHalfFOVY * AspectRatio);
            effect2.GetVariableByName("TanHalfFOVY").AsScalar().Set(tanHalfFOVY);
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;

            effect2.GetVariableByName("ProjectionA").AsScalar().Set(projectionA);
            effect2.GetVariableByName("ProjectionB").AsScalar().Set(projectionB);

            Matrix overlayMatrix = Matrix.Scaling(2 * info.Width / _width, 2 * info.Height / _height, 1.0f);

            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            effect2.GetVariableByName("OverlayViewProjection").AsMatrix().SetMatrix(overlayMatrix);
        }
Esempio n. 6
0
        public void Update(StepTimer timer, DeviceResources deviceResources, SpatialPointerPose pose)
        {
            if (pose != null)
            {
                cachedResources = deviceResources;
                var headPosition = pose.Head.Position;
                //Calculate the rotation for billboarding
                SharpDX.Vector3 facingNormal = new SharpDX.Vector3(headPosition.X - position.X, headPosition.Y - position.Y, headPosition.Z - position.Z);
                facingNormal.Normalize();

                SharpDX.Vector3 xAxisRotation = new SharpDX.Vector3(facingNormal.Z, 0, -facingNormal.X);
                xAxisRotation.Normalize();
                SharpDX.Vector3 yAxisRotation = SharpDX.Vector3.Cross(facingNormal, xAxisRotation);
                yAxisRotation.Normalize();

                Matrix4x4 modelRotation = new Matrix4x4(xAxisRotation.X, xAxisRotation.Y, xAxisRotation.Z, 0,
                                                        yAxisRotation.X, yAxisRotation.Y, yAxisRotation.Z, 0,
                                                        facingNormal.X, facingNormal.Y, facingNormal.Z, 0,
                                                        0, 0, 0, 1);

                // Position the cube.
                Matrix4x4 modelTranslation = Matrix4x4.CreateTranslation(position);


                // Multiply to get the transform matrix.
                // Note that this transform does not enforce a particular coordinate system. The calling
                // class is responsible for rendering this content in a consistent manner.
                Matrix4x4 modelTransform = modelRotation * modelTranslation;

                // The view and projection matrices are provided by the system; they are associated
                // with holographic cameras, and updated on a per-camera basis.
                // Here, we provide the model transform for the sample hologram. The model transform
                // matrix is transposed to prepare it for the shader.
                this.modelConstantBufferData.model = Matrix4x4.Transpose(modelTransform);


                // Use the D3D device context to update Direct3D device-based resources.
                var context = deviceResources.D3DDeviceContext;

                // Update the model transform buffer for the hologram.
                context.UpdateSubresource(ref this.modelConstantBufferData, this.modelConstantBuffer);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Rotate the camera around the specified point.
        /// </summary>
        /// <param name="p0">
        /// The p 0.
        /// </param>
        /// <param name="p1">
        /// The p 1.
        /// </param>
        /// <param name="rotateAround">
        /// The rotate around.
        /// </param>
        /// <param name="stopOther">Stop other manipulation</param>
        public void Rotate(Vector2 p0, Vector2 p1, Point3D rotateAround, bool stopOther = true)
        {
            if (!this.Controller.IsRotationEnabled)
            {
                return;
            }
            if (stopOther)
            {
                Controller.StopZooming();
                Controller.StopPanning();
            }
            p0 = Vector2.Multiply(p0, Controller.AllowRotateXY);
            p1 = Vector2.Multiply(p1, Controller.AllowRotateXY);
            var newPos  = Camera.CameraInternal.Position;
            var newLook = Camera.CameraInternal.LookDirection;
            var newUp   = Vector3D.Normalize(Camera.CameraInternal.UpDirection);

            switch (this.Controller.CameraRotationMode)
            {
            case CameraRotationMode.Trackball:
                CameraMath.RotateTrackball(CameraMode, ref p0, ref p1, ref rotateAround, (float)RotationSensitivity,
                                           Controller.Width, Controller.Height, Camera, inv, out newPos, out newLook, out newUp);
                break;

            case CameraRotationMode.Turntable:
                var p = p1 - p0;
                CameraMath.RotateTurntable(CameraMode, ref p, ref rotateAround, (float)RotationSensitivity,
                                           Controller.Width, Controller.Height, Camera, inv, ModelUpDirection, out newPos, out newLook, out newUp);
                break;

            case CameraRotationMode.Turnball:
                CameraMath.RotateTurnball(CameraMode, ref p0, ref p1, ref rotateAround, (float)RotationSensitivity,
                                          Controller.Width, Controller.Height, Camera, inv, out newPos, out newLook, out newUp);
                break;
            }
            Camera.LookDirection = newLook;
            Camera.Position      = newPos;
            Camera.UpDirection   = newUp;
        }
Esempio n. 8
0
        public void Init(CInitializer initializer)
        {
            UpdateScheduler = new CUpdateScheduler();

            CreateLevel();
            GameConsole.Init();
            PhysicsWorld.Init(this);


            #region Sponza
            CModelAsset sponzaAsset = CImportManager.Instance.MeshImporter.LoadModelAsync("TestResources/SponzaAtrium/sponza.obj");
            m_sponzaEntity = SpawnEntity <CEntity>();
            CModelComponent modelComponent = m_sponzaEntity.AddComponent <CModelComponent>(true, true);
            m_sponzaEntity.SetWorldPosition(new Vector3(0, -5, -5));
            m_sponzaEntity.SetWorldRotation(Quaternion.RotationAxis(Axis.Up, MathUtil.DegreesToRadians(90)));
            m_sponzaEntity.SetWorldScale(new Vector3(0.03f));
            CStaticModelColliderComponent staticModelCollider = m_sponzaEntity.AddComponent <CStaticModelColliderComponent>(true, true);
            staticModelCollider.ModelAsset  = sponzaAsset;
            modelComponent.Model            = sponzaAsset;
            m_sponzaEntity.IsPhysicsStatic  = true;
            m_sponzaEntity.IsPhysicsEnabled = true;
            #endregion

            CMeshAsset cubeAsset = CImportManager.Instance.MeshImporter.LoadMeshAsync("EngineResources/DefaultMeshes/DefaultCube.obj");

            CEntity floorEntity = SpawnEntity <CEntity>();
            floorEntity.AddComponent <CSceneComponent>(true, true);
            CMeshComponent floorMesh = floorEntity.AddComponent <CMeshComponent>(true, true);
            floorMesh.Mesh       = cubeAsset;
            floorMesh.LocalScale = new Vector3(500, 1, 500);
            CBoxColliderComponent floorCollider = floorEntity.AddComponent <CBoxColliderComponent>(true, true);
            floorCollider.Height = 1;
            floorCollider.Width  = 500;
            floorCollider.Length = 500;
            floorEntity.SetLocalPosition(new Vector3(0, -15, 0));
            floorEntity.IsPhysicsStatic         = true;
            floorEntity.IsPhysicsEnabled        = true;
            floorEntity.PhysicalStatic.Material = new Material(1, 0.8f, 1f);

            #region LightSetup
            m_lightEntity = SpawnEntity <CEntity>();
            m_lightEntity.AddComponent <CSceneComponent>(true, true);

            CDirectionalLightComponent directionalLight = m_lightEntity.AddComponent <CDirectionalLightComponent>(true, true);
            directionalLight.LocalRotation = MathUtilities.CreateLookAtQuaternion(Vector3.Normalize(new Vector3(0.2f, -0.5f, 0.2f)), Axis.Up);
            directionalLight.LightColor    = Color4.White * 0.8f;

            CSpotLightComponent spotLight = m_lightEntity.AddComponent <CSpotLightComponent>(true, true);
            spotLight.ConstantAttenuation  = 0.01f;
            spotLight.LinearAttenuation    = 0.3f;
            spotLight.QuadraticAttenuation = 0.0f;
            spotLight.Enabled    = true;
            spotLight.SpotAngle  = MathUtil.DegreesToRadians(30.0f);
            spotLight.LightColor = new Color4(0.1f, 0.8f, 0.1f, 1.0f);
            spotLight.Range      = 100.0f;
            Quaternion deltaRotation = Quaternion.RotationAxis(Axis.Right, MathUtil.DegreesToRadians(10));
            spotLight.LocalRotation = deltaRotation;
            spotLight.LocalPosition = new Vector3(0, 1, -4);

            CPointLightComponent pointLight1 = m_lightEntity.AddComponent <CPointLightComponent>(true, true);
            pointLight1.ConstantAttenuation = 1;
            pointLight1.LinearAttenuation   = 0.2f;
            pointLight1.Enabled             = true;
            pointLight1.Range         = 100.0f;
            pointLight1.LightColor    = new Color4(0.8f, 0.1f, 0.1f, 1.0f);
            pointLight1.LocalPosition = new Vector3(0, 0, 3.0f);

            CPointLightComponent pointLight2 = m_lightEntity.AddComponent <CPointLightComponent>(true, true);
            pointLight2.ConstantAttenuation = 1;
            pointLight2.LinearAttenuation   = 0.4f;
            pointLight2.Enabled             = true;
            pointLight2.Range         = 100.0f;
            pointLight2.LightColor    = new Color4(0.1f, 0.1f, 0.8f, 1.0f);
            pointLight2.LocalPosition = new Vector3(0, -3, -8.0f);

            CAmbientLightComponent ambientLight = m_lightEntity.AddComponent <CAmbientLightComponent>(true, true);
            ambientLight.LightColor = Color4.White * 0.15f;
            #endregion
        }
Esempio n. 9
0
        /// <summary>
        /// Function to build the Icosphere.
        /// </summary>
        /// <param name="graphics">Graphics interface to use.</param>
        /// <param name="radius">Radius of the sphere.</param>
        /// <param name="tesselation">Tessellation factor for the sphere.</param>
        /// <param name="textureCoordinates">Texture coordinate offset and scale.</param>
        private void BuildSphere(GorgonGraphics graphics, float radius, int tesselation, DX.RectangleF textureCoordinates)
        {
            GetBaseVertices();
            List <int[]> indices = GetBaseIndices();

            for (int i = 0; i < tesselation; ++i)
            {
                var subIndices = new List <int[]>();

                foreach (int[] index in indices)
                {
                    int index0 = GetMiddlePoint(index[0], index[1]);
                    int index1 = GetMiddlePoint(index[1], index[2]);
                    int index2 = GetMiddlePoint(index[2], index[0]);

                    subIndices.Add(new []
                    {
                        index[0],
                        index0,
                        index2
                    });

                    subIndices.Add(new[]
                    {
                        index[1],
                        index1,
                        index0
                    });


                    subIndices.Add(new[]
                    {
                        index[2],
                        index2,
                        index1
                    });

                    subIndices.Add(new[]
                    {
                        index0,
                        index1,
                        index2
                    });
                }

                indices = subIndices;
                _cachedSplits.Clear();
            }

            // Perform texture coordinate calculations and vertex/normal transformations.
            const float piRecip  = 1.0f / (float)System.Math.PI;
            const float pi2Recip = 1.0f / (2.0f * (float)System.Math.PI);

            // Final list.
            var vertexList = new List <Vertex3D>();
            var indexList  = new List <int>();

            foreach (DX.Vector3 vector in _vertices)
            {
                DX.Vector3 position = vector;
                DX.Vector3 normal   = position;
                DX.Vector2 uv       = DX.Vector2.Zero;

                uv.X = ((0.5f - (position.X.ATan(position.Z) * pi2Recip)) * textureCoordinates.Width) + textureCoordinates.X;
                uv.Y = ((0.5f - (position.Y.ASin() * piRecip)) * textureCoordinates.Height) + textureCoordinates.Y;

                DX.Vector3.Multiply(ref position, radius, out position);
                DX.Vector3.TransformCoordinate(ref position, ref _orientation, out position);
                DX.Vector3.TransformCoordinate(ref normal, ref _orientation, out normal);
                normal.Normalize();

                vertexList.Add(new Vertex3D
                {
                    Position = new DX.Vector4(position, 1.0f),
                    Normal   = normal,
                    UV       = uv
                });
            }

            foreach (int[] index in indices)
            {
                for (int j = 0; j < 3; ++j)
                {
                    indexList.Add(index[j]);
                }
            }

            FixSeam(vertexList, indexList);

            using (var vertexData = GorgonNativeBuffer <Vertex3D> .Pin(vertexList.ToArray()))
                using (var indexData = GorgonNativeBuffer <int> .Pin(indexList.ToArray()))
                {
                    VertexCount   = vertexList.Count;
                    IndexCount    = indexList.Count;
                    TriangleCount = IndexCount / 3;

                    CalculateTangents(vertexData, indexData);

                    VertexBuffer = new GorgonVertexBuffer(graphics,
                                                          new GorgonVertexBufferInfo("IcoSphereVertexBuffer")
                    {
                        SizeInBytes = vertexData.SizeInBytes,
                        Usage       = ResourceUsage.Immutable
                    },
                                                          vertexData.Cast <byte>());
                    IndexBuffer = new GorgonIndexBuffer(graphics,
                                                        new GorgonIndexBufferInfo
                    {
                        Usage           = ResourceUsage.Immutable,
                        Use16BitIndices = false,
                        IndexCount      = IndexCount
                    },
                                                        indexData);
                }
        }
Esempio n. 10
0
        /// <summary>
        /// Function to process the keyboard commands.
        /// </summary>
        private static void ProcessKeys()
        {
            DX.Vector3 cameraDir = DX.Vector3.Zero;
            DX.Vector3 lookAt    = _camera.LookAt;
            lookAt.Normalize();

            if (_keyboard.KeyStates[Keys.Left] == GI.KeyState.Down)
            {
                _cameraRotation.Y -= 40.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.Right] == GI.KeyState.Down)
            {
                _cameraRotation.Y += 40.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.Up] == GI.KeyState.Down)
            {
                _cameraRotation.X -= 40.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.Down] == GI.KeyState.Down)
            {
                _cameraRotation.X += 40.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.PageUp] == GI.KeyState.Down)
            {
                _cameraRotation.Z -= 40.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.PageDown] == GI.KeyState.Down)
            {
                _cameraRotation.Z += 40.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.D] == GI.KeyState.Down)
            {
                cameraDir.X = 2.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.A] == GI.KeyState.Down)
            {
                cameraDir.X = -2.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.W] == GI.KeyState.Down)
            {
                cameraDir.Z = 2.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.S] == GI.KeyState.Down)
            {
                cameraDir.Z = -2.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.Q] == GI.KeyState.Down)
            {
                cameraDir.Y = 2.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.E] == GI.KeyState.Down)
            {
                cameraDir.Y = -2.0f * GorgonTiming.Delta;
            }

            if (_lock)
            {
                _camera.Target(_sphere.Position);
            }

            _camera.Rotation = _cameraRotation;
            _camera.Move(ref cameraDir);
        }