/// <summary> /// Calculates an axis aligned rectangle which fully contains an arbitrarily /// transformed axis aligned rectangle. /// </summary> /// <param name="rectangle">Original bounding rectangle.</param> /// <param name="transform">World transform of the rectangle.</param> /// <returns>A new rectangle which contains the trasnformed rectangle.</returns> public static Rectangle CalculateTransformedBoundingRectangle(Rectangle rectangle, Matrix transform) { // Matrix inverseMatrix = Matrix.Invert(transform); // Get all four corners in local space leftTop = new Vector2(rectangle.Left, rectangle.Top); rightTop = new Vector2(rectangle.Right, rectangle.Top); leftBottom = new Vector2(rectangle.Left, rectangle.Bottom); rightBottom = new Vector2(rectangle.Right, rectangle.Bottom); // Transform all four corners into work space Vector2.Transform(ref leftTop, ref transform, out leftTop); Vector2.Transform(ref rightTop, ref transform, out rightTop); Vector2.Transform(ref leftBottom, ref transform, out leftBottom); Vector2.Transform(ref rightBottom, ref transform, out rightBottom); // Find the minimum and maximum extents of the rectangle in world space min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom)); max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom)); // Return that as a rectangle return new Rectangle((int)Math.Round(min.X), (int)Math.Round(min.Y), (int)Math.Round(max.X - min.X), (int)Math.Round(max.Y - min.Y)); }
/// <summary> /// Renders the specified Emitter, applying the specified transformation offset. /// </summary> public override void RenderEmitter(Emitter emitter, ref Matrix transform) { Guard.ArgumentNull("emitter", emitter); Guard.IsTrue(this.Batch == null, "SpriteBatchRenderer is not ready! Did you forget to LoadContent?"); if (emitter.ParticleTexture != null && emitter.ActiveParticlesCount > 0) { // Bail if the emitter blend mode is "None"... if (emitter.BlendMode == EmitterBlendMode.None) return; // Calculate the source rectangle and origin offset of the Particle texture... Rectangle source = new Rectangle(0, 0, emitter.ParticleTexture.Width, emitter.ParticleTexture.Height); Vector2 origin = new Vector2(source.Width / 2f, source.Height / 2f); BlendState blendState = this.GetBlendState(emitter.BlendMode); this.Batch.Begin(SpriteSortMode.Deferred, blendState); for (int i = 0; i < emitter.ActiveParticlesCount; i++) { Particle particle = emitter.Particles[i]; float scale = particle.Scale / emitter.ParticleTexture.Width; this.Batch.Draw(emitter.ParticleTexture, particle.Position, source, new Color(particle.Colour), particle.Rotation, origin, scale, SpriteEffects.None, 0f); } this.Batch.End(); } }
public static Matrix GetDiagonalMatrix() { Matrix ret = new Matrix(); for (int i = 0; i < 4; i++) ret[i, i] = 1; return ret; }
/// <summary> /// Performs the <see cref="Closing"/> operator on the given /// <see cref="Matrix"/>. /// </summary> /// <param name="src"> /// The <see cref="Matrix"/> which should be used by the /// operator. /// </param> /// <returns> The closed <see cref="Matrix"/>. </returns> public Matrix Execute (Matrix src) { Dilation dilation = new Dilation (this.se); Erosion erosion = new Erosion (this.se); return (erosion.Execute (dilation.Execute (src))); }
public override void DrawBuildings(GameTime gameTime) { base.DrawBuildings(gameTime); Model[] models = new Model[1]; models[0] = GameResources.Inst().GetTreeModel(2); foreach (Model m in models) { Matrix[] transforms = new Matrix[m.Bones.Count]; m.CopyAbsoluteBoneTransformsTo(transforms); foreach (ModelMesh mesh in m.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.Alpha = 1.0f; effect.LightingEnabled = true; effect.AmbientLightColor = GameState.MaterialAmbientColor; effect.DirectionalLight0.Direction = GameState.LightDirection; effect.DirectionalLight0.DiffuseColor = GameState.LightDiffusionColor; effect.DirectionalLight0.SpecularColor = GameState.LightSpecularColor; effect.DirectionalLight0.Enabled = true; effect.World = transforms[mesh.ParentBone.Index] * worldM; effect.View = GameState.view; effect.Projection = GameState.projection; } mesh.Draw(); } } }
public Pigeon(ContentManager con) { boundingBox = new Vector3(6, 3, 6); distance = 0; rand = new Random(); dx = (0.5-rand.NextDouble())*0.8 + 0.2; dy = rand.NextDouble()*1.5 + 0.7; dz = 0.8; x = 5.8; y = -2; z = 83.5; sx = 5.8; sy = -2; sz = 83.5; this.world = Matrix.CreateTranslation(new Vector3((float)x, (float)y, (float)z)); model = con.Load<Model>(@"models/pigeon"); isDone = false; }
public static bool LinearlyIndependent(params IVector[] vecs) { //reduce and see if there are zero rows Matrix temp = new Matrix(vecs); temp.GaussJordanEliminate(); return !temp[temp.Height - 1].IsZero(); }
protected override void InternalDraw(GameTime time, Matrix absoluteTransform, PrimitiveBatch primitiveBatch, Camera camera) { if (_mesh != null) { primitiveBatch.DrawMesh(_mesh, absoluteTransform, camera); } }
public override void Draw(Microsoft.Xna.Framework.Graphics.Texture2D ImageToProcess, RenderHelper rHelper, Microsoft.Xna.Framework.GameTime gt, PloobsEngine.Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatBuffer) { if (firstTime) { oldViewProjection = world.CameraManager.ActiveCamera.ViewProjection; firstTime = false; } effect.Parameters["attenuation"].SetValue(Attenuation); effect.Parameters["halfPixel"].SetValue(GraphicInfo.HalfPixel); effect.Parameters["InvertViewProjection"].SetValue(Matrix.Invert(world.CameraManager.ActiveCamera.ViewProjection)); effect.Parameters["oldViewProjection"].SetValue(oldViewProjection); effect.Parameters["numSamples"].SetValue(NumSamples); effect.Parameters["depth"].SetValue(rHelper[PrincipalConstants.DephRT]); effect.Parameters["extra"].SetValue(rHelper[PrincipalConstants.extra1RT]); effect.Parameters["cena"].SetValue(ImageToProcess); oldViewProjection = world.CameraManager.ActiveCamera.ViewProjection; if (useFloatBuffer) rHelper.RenderFullScreenQuadVertexPixel(effect, SamplerState.PointClamp); else rHelper.RenderFullScreenQuadVertexPixel(effect, GraphicInfo.SamplerState); }
public static void Main() { int n = 6; Matrix m = new Matrix(n); GameLogic.FillPath(m); m.PrintMatrix(); }
public static Matrix Invert3x3(Matrix matrix) { Matrix destMat = Matrix.Identity; destMat.M11 = (matrix.M22 * matrix.M33 - matrix.M32 * matrix.M23); destMat.M21 = (matrix.M31 * matrix.M23 - matrix.M21 * matrix.M33); destMat.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22); destMat.M12 = (matrix.M32 * matrix.M13 - matrix.M12 * matrix.M33); destMat.M22 = (matrix.M11 * matrix.M33 - matrix.M31 * matrix.M13); destMat.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32); destMat.M13 = (matrix.M12 * matrix.M23 - matrix.M22 * matrix.M13); destMat.M23 = (matrix.M13 * matrix.M21 - matrix.M11 * matrix.M23); destMat.M33 = (matrix.M11 * matrix.M22 - matrix.M21 * matrix.M12); double invDet = 1.0 / (matrix.M11 * destMat.M11 + matrix.M21 * destMat.M12 + matrix.M31 * destMat.M13); destMat.M11 = (float)(destMat.M11 * invDet); destMat.M12 = (float)(destMat.M12 * invDet); destMat.M13 = (float)(destMat.M13 * invDet); destMat.M21 = (float)(destMat.M21 * invDet); destMat.M22 = (float)(destMat.M22 * invDet); destMat.M23 = (float)(destMat.M23 * invDet); destMat.M31 = (float)(destMat.M31 * invDet); destMat.M32 = (float)(destMat.M32 * invDet); destMat.M33 = (float)(destMat.M33 * invDet); return destMat; }
public void Init(MyModel model, Matrix matrix, float rescaleModel = 1.0f) { Model = model; model.Rescale(rescaleModel); InstanceData.LocalMatrix = matrix; model.LoadData(); }
public void Transform(Matrix transform) { Vector2[] transformed = new Vector2[_vertices.Length]; Vector2.Transform(_vertices.ToArray(), ref transform, transformed); _transformedvertices.Clear(); _transformedvertices.vertices.InsertRange(0, transformed); }
public override void setEffect() { Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.TextureEnabled = true; effect.Alpha = 1; //trying to get lighting to work, but so far the model just shows up as pure black - it was exported with a green blinn shader //effect.EnableDefaultLighting(); //did not work effect.LightingEnabled = true; if (mesh.Name.Contains("glow")) { effect.AmbientLightColor = Vector3.One; } else { effect.DirectionalLight0.DiffuseColor = new Vector3(0.3f, 0.3f, 0.3f); //RGB is treated as a vector3 with xyz being rgb - so vector3.one is white effect.DirectionalLight0.Direction = new Vector3(0, -1, 1); effect.DirectionalLight0.SpecularColor = Vector3.One; effect.AmbientLightColor = new Vector3(0.3f, 0.3f, 0.3f); effect.EmissiveColor = new Vector3(0.3f, 0.3f, 0.3f); effect.PreferPerPixelLighting = true; } } mesh.Draw(); } }
public static Bitmap RotateToCorrentOrientation(this Bitmap bitmap, SurfaceOrientation currentOrientation) { //Calculate rotation float degrees = 0; switch (currentOrientation) { case SurfaceOrientation.Rotation180: degrees = -180; break; case SurfaceOrientation.Rotation270: degrees = 90; break; case SurfaceOrientation.Rotation90: degrees = -90; break; } //Rotate if needed if (degrees != 0) { using (Matrix mtx = new Matrix()) { mtx.PreRotate(degrees); bitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, mtx, false); } } return bitmap; }
protected static float[,] Multiply(Matrix matrix1, Matrix matrix2) { int m1rows = matrix1.rows; int m1cols = matrix1.cols; int m2rows = matrix2.rows; int m2cols = matrix2.cols; if (m1cols != m2rows) { throw new ArgumentException(); } float[,] m1 = matrix1.matrix; float[,] m2 = matrix2.matrix; float[,] m3 = new float[m1rows, m2cols]; for (int i = 0; i < m1rows; ++i) { for (int j = 0; j < m2cols; ++j) { float sum = 0; for (int it = 0; it < m1cols; ++it) { sum += m1[i, it] * m2[it, j]; } m3[i, j] = sum; } } return m3; }
public override void Draw(GraphicsDevice device, Camera camera) { game.GraphicsDevice.BlendState = BlendState.AlphaBlend; Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); game.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead; foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = mesh.ParentBone.Transform * GetWorld(); effect.View = camera.view; effect.Projection = camera.projection; effect.TextureEnabled = true; effect.Texture = tex; effect.Alpha = alpha; //trying to get lighting to work, but so far the model just shows up as pure black - it was exported with a green blinn shader //effect.EnableDefaultLighting(); //did not work effect.LightingEnabled = true; } mesh.Draw(); } }
public void Update(Vector2 target) { position = target; matrix = Matrix.Identity; matrix *= Matrix.CreateTranslation(-position.X, -position.Y, 0); matrix *= Matrix.CreateTranslation(screenHalfW, screenHalfH, 0); }
public static BoundingBox UpdateBoundingBox(this Model model, Matrix worldTransform) { // Initialize minimum and maximum corners of the bounding box to max and min values Vector3 min = new Vector3 (float.MaxValue, float.MaxValue, float.MaxValue); Vector3 max = new Vector3 (float.MinValue, float.MinValue, float.MinValue); // For each mesh of the model foreach (ModelMesh mesh in model.Meshes) { foreach (ModelMeshPart meshPart in mesh.MeshParts) { // Vertex buffer parameters int vertexStride = meshPart.VertexBuffer.VertexDeclaration.VertexStride; int vertexBufferSize = meshPart.NumVertices * vertexStride; // Get vertex data as float float[] vertexData = new float[vertexBufferSize / sizeof (float)]; meshPart.VertexBuffer.GetData<float> (vertexData); // Iterate through vertices (possibly) growing bounding box, all calculations are done in world space for (int i = 0; i < vertexBufferSize / sizeof (float); i += vertexStride / sizeof (float)) { Vector3 transformedPosition = Vector3.Transform (new Vector3 (vertexData[i], vertexData[i + 1], vertexData[i + 2]), worldTransform); min = Vector3.Min (min, transformedPosition); max = Vector3.Max (max, transformedPosition); } } } // Create and return bounding box return new BoundingBox (min, max); }
public override void Draw(GameTime gameTime) { Matrix world = Matrix.CreateRotationY(this.rotation) * Matrix.CreateTranslation(this.position + (Vector3.Up * height)); Matrix[] transforms = new Matrix[this.model.Bones.Count]; this.model.CopyAbsoluteBoneTransformsTo(transforms); GraphicsDevice.BlendState = BlendState.AlphaBlend; GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; GraphicsDevice.DepthStencilState = DepthStencilState.Default; foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = transforms[mesh.ParentBone.Index] * world; effect.View = CanyonGame.Camera.View; effect.Projection = CanyonGame.Camera.Projection; effect.Alpha = this.alpha; effect.EnableDefaultLighting(); effect.PreferPerPixelLighting = true; } mesh.Draw(); } base.Draw(gameTime); }
/// <summary> /// Load matrix from XML file /// </summary> /// <param name="fileName">file name</param> /// <returns>Loaded matrix</returns> public Matrix Load(string fileName) { XmlTextReader textReader = new XmlTextReader(fileName); Matrix matrix = new Matrix(); string fromWord = null; string toWord; float statisticValue; while (textReader.Read()) { if (textReader.NodeType == XmlNodeType.Element) { if (textReader.Name == "fromWord") { fromWord = textReader.GetAttribute("name"); } else if (textReader.Name == "toWord") { if (fromWord != null) { toWord = textReader.GetAttribute("name"); float.TryParse(textReader.GetAttribute("statisticValue"), out statisticValue); matrix.SetStatistics(fromWord, toWord, statisticValue); } } } } textReader.Close(); return matrix; }
public override void Draw(GameTime gameTime) { Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect be in mesh.Effects) { if (camera.normalLight) { be.EnableDefaultLighting(); } else { be.LightingEnabled = true; // turn on the lighting subsystem. be.DirectionalLight0.DiffuseColor = new Vector3(3f, 0f,0f); // a red light be.DirectionalLight0.Direction = new Vector3(1, 0, 0); // coming along the x-axis be.DirectionalLight1.SpecularColor = new Vector3(0, 0, 3); // with green highlights be.DirectionalLight1.DiffuseColor = new Vector3(3f, 0f, 0f); // a red light be.DirectionalLight1.Direction = new Vector3(1, 0, 0); // coming along the x-axis be.DirectionalLight2.SpecularColor = new Vector3(0, 0, 3); be.DirectionalLight2.DiffuseColor = new Vector3(3f, 0f, 0f); // a red light be.DirectionalLight2.Direction = new Vector3(1, 0, 0); // coming along the x-axis } be.Projection = camera.projection; be.View = camera.view; be.World = mesh.ParentBone.Transform * GetWorld(); ChangeEffect(be); } mesh.Draw(); } base.Draw(gameTime); }
static void Main(string[] args) { Matrix matrix = new Matrix(8); matrix.Traverse(); Console.WriteLine(matrix.ToString()); }
public static Matrix operator *(Matrix matrixA, Matrix matrixB) { Matrix resultMatrix = new Matrix(matrixA.row, matrixB.col); if (matrixA.col != matrixB.row) { Console.WriteLine("You can't multiply this two matrices!"); return resultMatrix; } else { for (int row = 0; row < resultMatrix.row; row++) { for (int col = 0; col < resultMatrix.col; col++) { int value = 0; for (int i = 0; i < matrixA.col; i++) { value = value + matrixA.matrix[row, i] * matrixB.matrix[i, col]; } resultMatrix[row, col] = value; } } return resultMatrix; } }
/// <summary> /// 与えられたデータからインスタンスを作成します /// </summary> /// <param name="EigenSystem">固有値・固有ベクトル</param> /// <param name="CoefficientMatrix">展開係数</param> /// <param name="AverageVector">平均ベクトル(Vector型から変更したので注意してね!!)</param> /// <param name="Tag">その他データ</param> public PCAData(EigenSystem EigenSystem, Matrix CoefficientMatrix, ColumnVector AverageVector, object Tag) { this.EigenSystemData = new EigenSystem(EigenSystem); this.CoefficientMatrix = new Matrix(CoefficientMatrix); this.AverageVector = new ColumnVector(AverageVector); this.Tag = (object)Tag; }
/// <summary> /// Advances the current animation position. /// </summary> public void Update(TimeSpan time, bool relativeToCurrentTime, Matrix rootTransform) { UpdateBoneTransforms(time, relativeToCurrentTime); UpdateWorldTransforms(rootTransform); UpdateSkinTransforms(); }
public void DrawBall(float aspectRatio, Vector3 cameraPosition, Model ball, float xrotation,float yrotation) { // assign random number to roid1modelPosition.x or y // Copy any parent transforms. Matrix[] transforms = new Matrix[ball.Bones.Count]; ball.CopyAbsoluteBoneTransformsTo(transforms); // Draw the model. A model can have multiple meshes, so loop. foreach (ModelMesh mesh in ball.Meshes) { // This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.World = transforms[mesh.ParentBone.Index] //* Matrix.CreateRotationZ(Roid1modelRotation) * Matrix.CreateRotationX(xrotation) * Matrix.CreateRotationY(yrotation) * Matrix.CreateTranslation(new Vector3(3750, -2750, 0)); effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up); effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f); } // Draw the mesh, using the effects set above. mesh.Draw(); } }
public override void Draw(Matrix View, Matrix Projection) { if (this.HP > 0) { base.Draw(View, Projection); } }
/// <summary> /// Generate the current bounding box of a model. /// </summary> public static BoundingBox GenerateBoundingBox(this Model model) { Vector3 min = new Vector3(float.MaxValue); Vector3 max = new Vector3(float.MinValue); Matrix[] bonesAbsolute = new Matrix[model.Bones.Count]; // MEMORYCHURN model.CopyAbsoluteBoneTransformsTo(bonesAbsolute); foreach (ModelMesh mesh in model.Meshes) { Matrix boneAbsolute = bonesAbsolute[mesh.ParentBone.Index]; foreach (ModelMeshPart part in mesh.MeshParts) { int stride = part.VertexStride; int vertexCount = part.NumVertices; byte[] vertexData = new byte[stride * vertexCount]; // MEMORYCHURN mesh.VertexBuffer.GetData(vertexData); for (int index = 0; index < vertexData.Length; index += stride) { float x = BitConverter.ToSingle(vertexData, index); float y = BitConverter.ToSingle(vertexData, index + 4); float z = BitConverter.ToSingle(vertexData, index + 8); Vector3 vertex = new Vector3(x, y, z); Vector3 vertexWorld = Vector3.Transform(vertex, boneAbsolute); if (vertexWorld.X < min.X) min.X = vertexWorld.X; if (vertexWorld.X > max.X) max.X = vertexWorld.X; if (vertexWorld.Y < min.Y) min.Y = vertexWorld.Y; if (vertexWorld.Y > max.Y) max.Y = vertexWorld.Y; if (vertexWorld.Z < min.Z) min.Z = vertexWorld.Z; if (vertexWorld.Z > max.Z) max.Z = vertexWorld.Z; } } } return new BoundingBox(min, max); }
private void btnMatrix_Click(object sender, EventArgs e) { Matrix a = new Matrix(4,4); for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) a[i, j] = (i + 1) * (j + 3); }
protected override void Update(GameTime gameTime) { base.Update(gameTime); const float RotationStep = 0.05f; if (Input.IsKeyReleased(Keys.T)) { slider.AreTicksDisplayed = !slider.AreTicksDisplayed; } if (Input.IsKeyReleased(Keys.S)) { slider.ShouldSnapToTicks = !slider.ShouldSnapToTicks; } if (Input.IsKeyReleased(Keys.R)) { slider.IsDirectionReversed = !slider.IsDirectionReversed; } if (Input.IsKeyReleased(Keys.O)) { slider.Orientation = (Orientation)(((int)slider.Orientation + 1) % 3); } if (Input.IsKeyReleased(Keys.Left)) { slider.Decrease(); } if (Input.IsKeyReleased(Keys.Right)) { slider.Increase(); } if (Input.IsKeyReleased(Keys.N)) { ResetSliderImages(); } if (Input.IsKeyPressed(Keys.V)) { slider.VerticalAlignment = (VerticalAlignment)(((int)slider.VerticalAlignment + 1) % 4); } if (Input.IsKeyPressed(Keys.H)) { slider.HorizontalAlignment = (HorizontalAlignment)(((int)slider.HorizontalAlignment + 1) % 4); } if (Input.IsKeyReleased(Keys.NumPad4)) { slider.LocalMatrix *= Matrix.RotationY(RotationStep); } if (Input.IsKeyReleased(Keys.NumPad6)) { slider.LocalMatrix *= Matrix.RotationY(-RotationStep); } if (Input.IsKeyReleased(Keys.NumPad2)) { slider.LocalMatrix *= Matrix.RotationX(RotationStep); } if (Input.IsKeyReleased(Keys.NumPad8)) { slider.LocalMatrix *= Matrix.RotationX(-RotationStep); } if (Input.IsKeyReleased(Keys.NumPad1)) { slider.LocalMatrix *= Matrix.RotationZ(RotationStep); } if (Input.IsKeyReleased(Keys.NumPad9)) { slider.LocalMatrix *= Matrix.RotationZ(-RotationStep); } if (Input.IsKeyReleased(Keys.Delete)) { slider.LocalMatrix *= Matrix.Translation(-10, 0, 0); } if (Input.IsKeyReleased(Keys.PageDown)) { slider.LocalMatrix *= Matrix.Translation(10, 0, 0); } if (Input.IsKeyReleased(Keys.Home)) { slider.LocalMatrix *= Matrix.Translation(0, -10, 0); } if (Input.IsKeyReleased(Keys.End)) { slider.LocalMatrix *= Matrix.Translation(0, 10, 0); } if (Input.IsKeyReleased(Keys.G)) { ChangeGridColumnRowNumbers(); } if (Input.IsKeyReleased(Keys.I)) { isRotatedImages = !isRotatedImages; SetSliderImages(isRotatedImages); } }
public void translate(Matrix matrix) { position = vectorMatrixMultiplication(position, matrix); Vector3 normalDirection = Vector3.Transform(Vector3.Up, Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z)); float d = position.X * normalDirection.X + position.Y * normalDirection.Y + position.Z * normalDirection.Z; _equation = new Vector4(normalDirection, d); }
/// <summary> /// Returns a matrix that transforms a normalized bridge to a bridge from 0,0,0 to the endpoint. /// </summary> /// <param name="bridgeEndPoint"></param> /// <returns></returns> public Matrix GetMatrixForEndpoint(Vector3 endpoint) { return Matrix.RotationY(MathHelper.Pi) * Matrix.Scaling(1, 1, endpoint.Length()) * Microsoft.Xna.Framework.Matrix.CreateFromQuaternion(Functions.CreateFromLookDir(Vector3.Normalize(endpoint).xna())).dx(); }
public void OneIteration(Matrix InputValue, int ExampleCount, int Iteration, bool testOnly, Matrix TargetValue, bool useTargetValue = false) { this.error = null; this.output = null; Matrix[] Z = null; Matrix[] A = null; ForwardPropagation(InputValue, out Z, out A, ExampleCount); var maxLayer = LayerCount - 1; var maxIndex = A.Length - 1; Matrix Zlast = Z[maxLayer]; // Cut first column for last layer var zx = Z[maxLayer].X; var zy = Z[maxLayer].Y; if (addBiasColumn) { Zlast = Zlast.Slice(0, 1, zx, zy); } this.output = A[maxIndex]; // Cut first column for last index of result matrix var ax = A[maxIndex].X; var ay = A[maxIndex].Y; if (addBiasColumn) { this.output = this.output.Slice(0, 1, ax, ay); } this.error = null; if (useTargetValue) { this.error = new Matrix[this.LayerCount - 1 + 1]; this.error[this.LayerCount - 1] = this.output - TargetValue; } if (testOnly) { return; } Matrix[] delta = null; BackPropagation(out delta, this.error, Zlast, Z, A); GradientDescend(A, delta, this.LearningRate); if (Iteration < 10 || ((Iteration + 1) % 100 == 0 && Iteration < 1000) || ((Iteration + 1) % 1000 == 0 && Iteration < 10000) || (Iteration + 1) % 10000 == 0) { var sMsg = "\n" + "-------" + (Iteration + 1) + "----------------" + "\n" + "Input: " + this.InputValue.ToString() + "\n" + "Output: " + this.output.ToString() + "\n"; //for (var i = 0; i <= this.LayerCount - 1; i++) { // sMsg += "Error(" + i + ")=" + this.error[i].ToString() + "\n"; // sMsg += "A(" + i + ")=" + A[i].ToString() + "\n"; //} var LastError = this.error[this.LayerCount - 1]; var averageErr = LastError.abs.average * this.ExampleCount; sMsg += "Loss: " + averageErr.ToString("0.000000") + "\n"; Debug.WriteLine(sMsg); Console.WriteLine(sMsg); } }
public Vector2 ScreenToWorld(Vector2 coords) { Vector2 worldCoords = Vector2.Transform(coords, Matrix.Invert(transform)); return(new Vector2(worldCoords.X, -worldCoords.Y)); }
public void Draw(GraphicsDeviceManager gcm, AlphaTestEffect at, BasicEffect be, RasterizerState rs) { if (Program.game.Collision < 1) return; List<VertexPositionNormalTexture> vpnt1 = new List<VertexPositionNormalTexture>(0); for (int i = 0; i < MainGame.ResourceFiles.Count + Program.game.Map.Supp.Count; i++) { Model mdl = null; if (i >= MainGame.ResourceFiles.Count) mdl = Program.game.Map.Supp[i - MainGame.ResourceFiles.Count] as Model; else mdl = MainGame.ResourceFiles[i] as Model; if (mdl == null) continue; if (mdl.Collision == null) continue; int start_ = mdl.Collision.StartEnds[0][0]; int end_ = mdl.Collision.StartEnds[0][1]; for (int j = start_; j < end_; j++) { Matrix mt = mdl.Skeleton.Bones[mdl.Skeleton.RootBone].LocalMatrix; if (Vector3.Distance(mdl.Location, Vector3.Zero) > 0) { mt = Matrix.Identity; } Vector3 v1 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][0][0]], mt) , mdl.Rotate_matrix) + mdl.Location; Vector3 v2 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][1][0]], mt), mdl.Rotate_matrix) + mdl.Location; Vector3 v3 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][2][0]], mt), mdl.Rotate_matrix) + mdl.Location; var mt_mat = Matrix.CreateFromQuaternion(mt.Rotation); Vector3 n1 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][0][1]], mt_mat); Vector3 n2 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][1][1]], mt_mat); Vector3 n3 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][2][1]], mt_mat); VertexPositionNormalTexture vp1 = new VertexPositionNormalTexture(); VertexPositionNormalTexture vp2 = new VertexPositionNormalTexture(); VertexPositionNormalTexture vp3 = new VertexPositionNormalTexture(); vp1.Position = v1; vp2.Position = v2; vp3.Position = v3; vp1.Normal = n1; vp2.Normal = n2; vp3.Normal = n3; vp1.TextureCoordinate = new Vector2(0.5f, 0.5f); vp2.TextureCoordinate = new Vector2(0.5f, 0.5f); vp3.TextureCoordinate = new Vector2(0.5f, 0.5f); vpnt1.Add(vp3); vpnt1.Add(vp2); vpnt1.Add(vp1); } } VertexPositionNormalTexture[] vpnt = new VertexPositionNormalTexture[this.indices.Count*3]; Model target = Program.game.mainCamera.Target; if (target!=null) { UpdateIndex(target.Location); int start = this.StartEnds[this.CurrIndex][0]; int end = this.StartEnds[this.CurrIndex][1]; for (int i = start; i < end; i++) { for (int j = 0; j < 3; j++) { vpnt[i * 3 + j] = new VertexPositionNormalTexture { Position = this.cols[this.indices[i][2 - j][0]], TextureCoordinate = new Vector2(0.5f, 0.5f), Normal = this.norms[this.indices[i][j][1]] }; } } } be.EnableDefaultLighting(); be.LightingEnabled = true; be.PreferPerPixelLighting = true; //be.AmbientLightColor = Color.White.ToVector3(); be.DiffuseColor = new Color(100, 100, 100,255).ToVector3(); //be.EmissiveColor = Color.White.ToVector3(); be.Texture = ResourceLoader.EmptyT2D; be.CurrentTechnique.Passes[0].Apply(); be.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vpnt, 0, vpnt.Length / 3); vpnt = vpnt1.ToArray(); be.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vpnt, 0, vpnt.Length / 3); be.LightingEnabled = false; be.PreferPerPixelLighting = false; }
/// <summary> /// Determines if there is overlap of the non-transparent pixels between two /// sprites. /// </summary> /// <param name="transformA">World transform of the first sprite.</param> /// <param name="widthA">Width of the first sprite's texture.</param> /// <param name="heightA">Height of the first sprite's texture.</param> /// <param name="dataA">Pixel color data of the first sprite.</param> /// <param name="transformB">World transform of the second sprite.</param> /// <param name="widthB">Width of the second sprite's texture.</param> /// <param name="heightB">Height of the second sprite's texture.</param> /// <param name="dataB">Pixel color data of the second sprite.</param> /// <returns>True if non-transparent pixels overlap; false otherwise</returns> public static bool IntersectPixels( Matrix transformA, int widthA, int heightA, Color[] dataA, Matrix transformB, int widthB, int heightB, Color[] dataB) { // Calculate a matrix which transforms from A's local space into // world space and then into B's local space Matrix transformAToB = transformA * Matrix.Invert(transformB); // When a point moves in A's local space, it moves in B's local space with a // fixed direction and distance proportional to the movement in A. // This algorithm steps through A one pixel at a time along A's X and Y axes // Calculate the analogous steps in B: Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, transformAToB); Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, transformAToB); // Calculate the top left corner of A in B's local space // This variable will be reused to keep track of the start of each row Vector2 yPosInB = Vector2.Transform(Vector2.Zero, transformAToB); // For each row of pixels in A for (int yA = 0; yA < heightA; yA++) { // Start at the beginning of the row Vector2 posInB = yPosInB; // For each pixel in this row for (int xA = 0; xA < widthA; xA++) { // Round to the nearest pixel int xB = (int)Math.Round(posInB.X); int yB = (int)Math.Round(posInB.Y); // If the pixel lies within the bounds of B if (0 <= xB && xB < widthB && 0 <= yB && yB < heightB) { try { // Get the colors of the overlapping pixels Color colorA = dataA[xA + yA * widthA]; Color colorB = dataB[xB + yB * widthB]; // If both pixels are not completely transparent, if (colorA.A != 0 && colorB.A != 0) { // then an intersection has been found return true; } } catch { //HUH? //throw ex; return false; } } // Move to the next pixel in the row posInB += stepX; } // Move to the next row yPosInB += stepY; } // No intersection found return false; }
public override void Collect(RenderContext context, ShadowMapRenderer shadowMapRenderer, LightShadowMapTexture lightShadowMap) { var shadow = (LightDirectionalShadowMap)lightShadowMap.Shadow; // TODO: Min and Max distance can be auto-computed from readback from Z buffer var shadowRenderView = shadowMapRenderer.CurrentView; var viewToWorld = shadowRenderView.View; viewToWorld.Invert(); // Update the frustum infos UpdateFrustum(shadowRenderView); // Computes the cascade splits var minMaxDistance = ComputeCascadeSplits(context, shadowMapRenderer, ref lightShadowMap); var direction = lightShadowMap.LightComponent.Direction; // Fake value // It will be setup by next loop Vector3 side = Vector3.UnitX; Vector3 upDirection = Vector3.UnitX; // Select best Up vector // TODO: User preference? foreach (var vectorUp in VectorUps) { if (Math.Abs(Vector3.Dot(direction, vectorUp)) < (1.0 - 0.0001)) { side = Vector3.Normalize(Vector3.Cross(vectorUp, direction)); upDirection = Vector3.Normalize(Vector3.Cross(direction, side)); break; } } int cascadeCount = lightShadowMap.CascadeCount; // Get new shader data from pool LightDirectionalShadowMapShaderData shaderData; if (cascadeCount == 1) { shaderData = shaderDataPoolCascade1.Add(); } else if (cascadeCount == 2) { shaderData = shaderDataPoolCascade2.Add(); } else { shaderData = shaderDataPoolCascade4.Add(); } lightShadowMap.ShaderData = shaderData; shaderData.Texture = lightShadowMap.Atlas.Texture; shaderData.DepthBias = shadow.BiasParameters.DepthBias; shaderData.OffsetScale = shadow.BiasParameters.NormalOffsetScale; float splitMaxRatio = (minMaxDistance.X - shadowRenderView.NearClipPlane) / (shadowRenderView.FarClipPlane - shadowRenderView.NearClipPlane); float splitMinRatio = 0; float oldSplitMinRatio = 0; for (int cascadeLevel = 0; cascadeLevel < cascadeCount; ++cascadeLevel) { oldSplitMinRatio = splitMinRatio; // Calculate frustum corners for this cascade splitMinRatio = splitMaxRatio; splitMaxRatio = cascadeSplitRatios[cascadeLevel]; var prevSplitMaxRatio = cascadeSplitRatios[cascadeLevel]; for (int j = 0; j < 4; j++) { // Calculate frustum in WS and VS float overlap = 0; if (cascadeLevel > 0 && shadow.DepthRange.IsBlendingCascades) { overlap = 0.2f * (splitMinRatio - oldSplitMinRatio); } var frustumRangeWS = frustumCornersWS[j + 4] - frustumCornersWS[j]; var frustumRangeVS = frustumCornersVS[j + 4] - frustumCornersVS[j]; cascadeFrustumCornersWS[j] = frustumCornersWS[j] + frustumRangeWS * (splitMinRatio - overlap); cascadeFrustumCornersWS[j + 4] = frustumCornersWS[j] + frustumRangeWS * splitMaxRatio; cascadeFrustumCornersVS[j] = frustumCornersVS[j] + frustumRangeVS * (splitMinRatio - overlap); cascadeFrustumCornersVS[j + 4] = frustumCornersVS[j] + frustumRangeVS * splitMaxRatio; } Vector3 cascadeMinBoundLS; Vector3 cascadeMaxBoundLS; Vector3 target; if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ViewSnapping || shadow.StabilizationMode == LightShadowMapStabilizationMode.ProjectionSnapping) { // Make sure we are using the same direction when stabilizing var boundingVS = BoundingSphere.FromPoints(cascadeFrustumCornersVS); // Compute bounding box center & radius target = Vector3.TransformCoordinate(boundingVS.Center, viewToWorld); var radius = boundingVS.Radius; //if (shadow.AutoComputeMinMax) //{ // var snapRadius = (float)Math.Ceiling(radius / snapRadiusValue) * snapRadiusValue; // Debug.WriteLine("Radius: {0} SnapRadius: {1} (snap: {2})", radius, snapRadius, snapRadiusValue); // radius = snapRadius; //} cascadeMaxBoundLS = new Vector3(radius, radius, radius); cascadeMinBoundLS = -cascadeMaxBoundLS; if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ViewSnapping) { // Snap camera to texel units (so that shadow doesn't jitter when light doesn't change direction but camera is moving) // Technique from ShaderX7 - Practical Cascaded Shadows Maps - p310-311 var shadowMapHalfSize = lightShadowMap.Size * 0.5f; float x = (float)Math.Ceiling(Vector3.Dot(target, upDirection) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float y = (float)Math.Ceiling(Vector3.Dot(target, side) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float z = Vector3.Dot(target, direction); //target = up * x + side * y + direction * R32G32B32_Float.Dot(target, direction); target = upDirection * x + side * y + direction * z; } } else { var cascadeBoundWS = BoundingBox.FromPoints(cascadeFrustumCornersWS); target = cascadeBoundWS.Center; // Computes the bouding box of the frustum cascade in light space var lightViewMatrix = Matrix.LookAtLH(cascadeBoundWS.Center, cascadeBoundWS.Center + direction, upDirection); cascadeMinBoundLS = new Vector3(float.MaxValue); cascadeMaxBoundLS = new Vector3(-float.MaxValue); for (int i = 0; i < cascadeFrustumCornersWS.Length; i++) { Vector3 cornerViewSpace; Vector3.TransformCoordinate(ref cascadeFrustumCornersWS[i], ref lightViewMatrix, out cornerViewSpace); cascadeMinBoundLS = Vector3.Min(cascadeMinBoundLS, cornerViewSpace); cascadeMaxBoundLS = Vector3.Max(cascadeMaxBoundLS, cornerViewSpace); } // TODO: Adjust orthoSize by taking into account filtering size } // Update the shadow camera var viewMatrix = Matrix.LookAtRH(target + direction * cascadeMinBoundLS.Z, target, upDirection); // View;; var projectionMatrix = Matrix.OrthoOffCenterRH(cascadeMinBoundLS.X, cascadeMaxBoundLS.X, cascadeMinBoundLS.Y, cascadeMaxBoundLS.Y, 0.0f, cascadeMaxBoundLS.Z - cascadeMinBoundLS.Z); // Projection Matrix viewProjectionMatrix; Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix); // Stabilize the Shadow matrix on the projection if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ProjectionSnapping) { var shadowPixelPosition = viewProjectionMatrix.TranslationVector * lightShadowMap.Size * 0.5f; // shouln't it be scale and not translation ? shadowPixelPosition.Z = 0; var shadowPixelPositionRounded = new Vector3((float)Math.Round(shadowPixelPosition.X), (float)Math.Round(shadowPixelPosition.Y), 0.0f); var shadowPixelOffset = new Vector4(shadowPixelPositionRounded - shadowPixelPosition, 0.0f); shadowPixelOffset *= 2.0f / lightShadowMap.Size; projectionMatrix.Row4 += shadowPixelOffset; Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix); } shaderData.ViewMatrix[cascadeLevel] = viewMatrix; shaderData.ProjectionMatrix[cascadeLevel] = projectionMatrix; // Cascade splits in light space using depth: Store depth on first CascaderCasterMatrix in last column of each row shaderData.CascadeSplits[cascadeLevel] = MathUtil.Lerp(shadowRenderView.NearClipPlane, shadowRenderView.FarClipPlane, cascadeSplitRatios[cascadeLevel]); var shadowMapRectangle = lightShadowMap.GetRectangle(cascadeLevel); var cascadeTextureCoords = new Vector4((float)shadowMapRectangle.Left / lightShadowMap.Atlas.Width, (float)shadowMapRectangle.Top / lightShadowMap.Atlas.Height, (float)shadowMapRectangle.Right / lightShadowMap.Atlas.Width, (float)shadowMapRectangle.Bottom / lightShadowMap.Atlas.Height); //// Add border (avoid using edges due to bilinear filtering and blur) //var borderSizeU = VsmBlurSize / lightShadowMap.Atlas.Width; //var borderSizeV = VsmBlurSize / lightShadowMap.Atlas.Height; //cascadeTextureCoords.X += borderSizeU; //cascadeTextureCoords.Y += borderSizeV; //cascadeTextureCoords.Z -= borderSizeU; //cascadeTextureCoords.W -= borderSizeV; float leftX = (float)lightShadowMap.Size / lightShadowMap.Atlas.Width * 0.5f; float leftY = (float)lightShadowMap.Size / lightShadowMap.Atlas.Height * 0.5f; float centerX = 0.5f * (cascadeTextureCoords.X + cascadeTextureCoords.Z); float centerY = 0.5f * (cascadeTextureCoords.Y + cascadeTextureCoords.W); // Compute receiver view proj matrix Matrix adjustmentMatrix = Matrix.Scaling(leftX, -leftY, 1.0f) * Matrix.Translation(centerX, centerY, 0.0f); // Calculate View Proj matrix from World space to Cascade space Matrix.Multiply(ref viewProjectionMatrix, ref adjustmentMatrix, out shaderData.WorldToShadowCascadeUV[cascadeLevel]); } }
/// <summary> /// Retrieve the Y scale from the matrix /// </summary> /// <param name="matrix"></param> /// <returns></returns> public static float CalculateScaleY(Matrix matrix) { return(matrix.Elements[M22]); }
public void drawOptions(SpriteBatch spriteBatch, Dictionary<string, Texture2D> texturesDictionary, Matrix transformationMatrix, SpriteFont font) { switch (currentState) { case OptionsStates.GLOBAL: spriteBatch.Draw(texturesDictionary["MainMenu1"], new Rectangle(0, 0, 1920, 1080), Color.White); break; case OptionsStates.MUSIC: spriteBatch.Draw(texturesDictionary["MainMenu2"], new Rectangle(0, 0, 1920, 1080), Color.White); break; case OptionsStates.SOUND: spriteBatch.Draw(texturesDictionary["MainMenu3"], new Rectangle(0, 0, 1920, 1080), Color.White); break; case OptionsStates.BACK: spriteBatch.Draw(texturesDictionary["MainMenu4"], new Rectangle(0, 0, 1920, 1080), Color.White); break; } spriteBatch.DrawString(font, "Sounds", new Vector2(1400, 100), Color.Black, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0); spriteBatch.DrawString(font, "Global", new Vector2(1400, 200), Color.Black, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0); globalVolumeSlider.drawSlider(spriteBatch, texturesDictionary, transformationMatrix); spriteBatch.DrawString(font, "Music", new Vector2(1400, 360), Color.Black, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0); musicVolumeSlider.drawSlider(spriteBatch, texturesDictionary, transformationMatrix); spriteBatch.DrawString(font, "Soundeffects", new Vector2(1400, 510), Color.Black, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0); soundEffectsVolumeSlider.drawSlider(spriteBatch, texturesDictionary, transformationMatrix); spriteBatch.DrawString(font, "Back", new Vector2(1400, 670), Color.Black, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0); }
public static void MonitorCollision(Model sujet, ref Vector3 pos) { var collision = Program.game.MapSet ? Program.game.Map.Links[0] as Collision : null; if (sujet.Epaisseur < 0.1) return; bool jumping = sujet.Location.Y> sujet.LowestFloor+sujet.StairHeight && pos.Y > sujet.Location.Y; Vector3 refPosBottom = pos + new Vector3(0, sujet.StairHeight, 0); Vector3 refPosTop = pos + new Vector3(0, sujet.MaxVertex.Y, 0); Vector3 inter; Vector3 shadowAngle = Vector3.Zero; Vector3 globalBone0 = sujet.GetGlobalBone(0, Vector3.Zero); globalBone0.Y = sujet.MinVertex.Y; float tallest = Single.MinValue; float smallest = Single.MaxValue; shadowAngle = Vector3.Zero; Vector3 forwardCliffStart = new Vector3(0, 10f, sujet.Epaisseur * 1.1f); Vector3 forwardCliffEnd = new Vector3(0, -10f, sujet.Epaisseur * 1.1f); forwardCliffStart = Vector3.Transform(forwardCliffStart, sujet.Rotate_matrix); forwardCliffEnd = Vector3.Transform(forwardCliffEnd, sujet.Rotate_matrix); cliffBackwards = Vector3.Transform(cliffBackwards, sujet.Rotate_matrix); bool pushed = false; sujet.Attached = false; int moreRes = 0; if (Program.game.MapSet) moreRes = Program.game.Map.Supp.Count; if ((ScenePlayer.ScenePlaying && ScenePlayer.AllowContactCollision) || !ScenePlayer.ScenePlaying) if (!sujet.NPC && sujet.cState != Model.ControlState.Cliff) for (int i = 0; i < MainGame.ResourceFiles.Count + moreRes; i++) { Model mdl = null; if (i >= MainGame.ResourceFiles.Count) mdl = Program.game.Map.Supp[i- MainGame.ResourceFiles.Count] as Model; else mdl = MainGame.ResourceFiles[i] as Model; if (mdl == null) continue; if (sujet.ResourceIndex == mdl.ResourceIndex) continue; if (mdl.Collision == null) { if (mdl.Epaisseur < 1) continue; if (mdl.NPC || sujet.Masse <= mdl.Masse) { Vector2 sujetPos = new Vector2(pos.X, pos.Z); Vector2 mdlPos = new Vector2(mdl.Location.X, mdl.Location.Z); if (sujet.Location.Y > mdl.Location.Y-mdl.StairHeight*2f && sujet.Location.Y<mdl.Location.Y+mdl.MaxVertex.Y) { float hypo = Vector2.Distance(sujetPos, mdlPos); sujetPos -= mdlPos; sujetPos /= hypo; if (hypo < (mdl.Epaisseur + sujet.Epaisseur)) { sujetPos = mdlPos + sujetPos * (mdl.Epaisseur + sujet.Epaisseur) * 1.1f; pos.X = sujetPos.X; pos.Z = sujetPos.Y; } /*else if (sujet.ResourceIndex == Program.game.mainCamera.Target.ResourceIndex && hypo < (mdl.Epaisseur + sujet.Epaisseur)*2f) { float val1 = (float)Math.Atan2(sujetPos.X, sujetPos.Y); float val2 = sujet.DestRotate + MainGame.PI; SrkBinary.MakePrincipal(ref val1); SrkBinary.MakePrincipal(ref val2); if (Math.Abs(val1-val2) < 1) { if (Program.game.mainCamera.LXY_read==0) { Program.game.mainCamera.LXY_read = 10; float cam_mdl_diff = (float)(Math.Atan2(Program.game.mainCamera.joyLY_, Program.game.mainCamera.joyLX_) + MathHelper.ToRadians(33)); Program.game.mainCamera.joyLY_ = (float)Math.Sin(cam_mdl_diff); Program.game.mainCamera.joyLX_ = (float)Math.Cos(cam_mdl_diff); } } }*/ } } } else for (int p=0;p< mdl.Collision.PolyCount; p++) { int start_ = mdl.Collision.StartEnds[p][0]; int end_ = mdl.Collision.StartEnds[p][1]; for (int j = start_; j < end_; j++) { Matrix mt = mdl.Skeleton.Bones[p].LocalMatrix; if (Vector3.Distance(mdl.Location,Vector3.Zero) > 0) mt = Matrix.Identity; Vector3 v1 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][0][0]], mt), mdl.Rotate_matrix) + mdl.Location; Vector3 v2 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][1][0]], mt), mdl.Rotate_matrix) + mdl.Location; Vector3 v3 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][2][0]], mt), mdl.Rotate_matrix) + mdl.Location; var mt_mat = Matrix.CreateFromQuaternion(mt.Rotation); Vector3 n1 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][0][1]], mt_mat); Vector3 n2 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][1][1]], mt_mat); Vector3 n3 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][2][1]], mt_mat); Vector3 normal = (n1 + n2 + n3) / 3f; if (mdl.NPC || sujet.Masse <= mdl.Masse) { bool newAttach = false; if (!ScenePlayer.ScenePlaying && normal.Y < -0.5) if (Inside(refPosTop, v1 - 10f * n1, v2 - 10f * n2, v3 - 10f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { if (normal.Y < -0.5) sujet.JumpCollisionCancel = true; Vector3 direction = refPosTop + normal * sujet.Epaisseur; if (intersect3D_RayTriangle(refPosTop, direction, v1, v2, v3, out inter) == 1) { //pos += ((inter + new Vector3(0, -height, 0))- pos)/10f; pos = (inter + new Vector3(0, -(sujet.MaxVertex.Y), 0)); if (pos.Y < sujet.LowestFloor) pos.Y = sujet.LowestFloor; refPosTop = pos + new Vector3(0, sujet.MaxVertex.Y, 0); } } if (!ScenePlayer.ScenePlaying && Math.Abs(normal.Y) < 0.5f) { if (Inside(refPosBottom, v1 - 10f * n1, v2 - 10f * n2, v3 - 10f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosBottom + normal * sujet.Epaisseur * 10f; if (jumping && normal.Y < -0.5) sujet.JumpCollisionCancel = true; if (intersect3D_RayTriangle(refPosBottom, direction, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3, out inter) == 1) { pos.X = inter.X; pos.Z = inter.Z; refPosBottom = pos + new Vector3(0, sujet.StairHeight, 0); } } if (Inside(refPosTop, v1 - 20f * n1, v2 - 20f * n2, v3 - 20f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosTop + normal * sujet.Epaisseur * 10f; if (intersect3D_RayTriangle(refPosTop, direction, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3, out inter) == 1) { pos.X = inter.X; pos.Z = inter.Z; refPosTop = pos + new Vector3(0, sujet.MaxVertex.Y, 0); } } } else if (normal.Y > 0.5) { if (intersect3D_RayTriangle(pos + globalBone0 + new Vector3(0, 50000, 0), pos + globalBone0 + new Vector3(0, -50000, 0), v1, v2, v3, out inter) == 1) { if (Math.Abs(inter.Y-pos.Y)<sujet.StairHeight) { if (inter.Y < smallest) { smallest = inter.Y; } if (inter.Y <= sujet.Location.Y + sujet.StairHeight * 1.5f && inter.Y > tallest) { shadowAngle = new Vector3( 0, (float)Math.Atan2(normal.Z, normal.Y), (float)Math.Atan2(-normal.X, normal.Y)); tallest = inter.Y; } } } } if (tallest > Single.MinValue / 2f) { if (tallest < sujet.Location.Y + sujet.StairHeight * 1.5f) { sujet.LowestFloor = tallest; newAttach = true; } } else if (smallest < Single.MaxValue / 2f) { if (smallest < sujet.Location.Y + sujet.StairHeight * 1.5f) { sujet.LowestFloor = smallest; newAttach = true; } } if (newAttach && Math.Abs(pos.Y-sujet.LowestFloor)<1) { if (collision!=null) collision.AttachTo(mdl, sujet); } /*if (!ScenePlayer.ScenePlaying && Math.Abs(normal.Y) < 0.5f) { if (Inside(refPosBottom, v1 - 20f * n1, v2 - 20f * n2, v3 - 20f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosBottom + normal * sujet.Epaisseur * 10f; if (intersect3D_RayTriangle(refPosBottom, direction, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3, out inter) == 1) { pushed = true; pos.X = inter.X; pos.Z = inter.Z; refPosBottom = pos + new Vector3(0, sujet.StairHeight, 0); } } if (Inside(refPosTop, v1 - 20f * n1, v2 - 20f * n2, v3 - 20f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosTop + normal * sujet.Epaisseur * 10f; if (intersect3D_RayTriangle(refPosTop, direction, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3, out inter) == 1) { pushed = true; pos.X = inter.X; pos.Z = inter.Z; refPosTop = pos + new Vector3(0, sujet.MaxVertex.Y, 0); } } }*/ } } } } sujet.ShadowMatrixSurface = Matrix.CreateFromYawPitchRoll(shadowAngle.X, shadowAngle.Y, shadowAngle.Z); bool cliff = sujet.cState == Model.ControlState.Cliff || sujet.cState == Model.ControlState.UnCliff; if (collision == null) return; collision.UpdateIndex(sujet.Location); int start = collision.StartEnds[collision.CurrIndex][0]; int end = collision.StartEnds[collision.CurrIndex][1]; for (int i = start; i < end; i++) { Vector3 v1 = collision.cols[collision.indices[i][0][0]]; Vector3 v2 = collision.cols[collision.indices[i][1][0]]; Vector3 v3 = collision.cols[collision.indices[i][2][0]]; Vector3 n1 = collision.norms[collision.indices[i][0][1]]; Vector3 n2 = collision.norms[collision.indices[i][1][1]]; Vector3 n3 = collision.norms[collision.indices[i][2][1]]; Vector3 normal = (n1 + n2 + n3) / 3f; if (!cliff && !ScenePlayer.ScenePlaying && normal.Y < -0.5) if (Inside(refPosTop, v1 - 20f * n1, v2 - 20f * n2, v3 - 20f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosTop + normal * sujet.Epaisseur; if (intersect3D_RayTriangle(refPosTop, direction, v1, v2, v3, out inter) == 1) { //pos += ((inter + new Vector3(0, -height, 0))- pos)/10f; pos = (inter + new Vector3(0, -(sujet.MaxVertex.Y), 0)); if (pos.Y < sujet.LowestFloor) pos.Y = sujet.LowestFloor; refPosTop = pos + new Vector3(0, sujet.MaxVertex.Y, 0); } } if (!cliff && !ScenePlayer.ScenePlaying && Math.Abs(normal.Y) < 0.5f) { if (Inside(refPosBottom, v1-20f*n1, v2 - 20f * n2, v3 - 20f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosBottom + normal * sujet.Epaisseur * 10f; if (jumping && normal.Y < -0.5) sujet.JumpCollisionCancel = true; if (intersect3D_RayTriangle(refPosBottom, direction, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3, out inter) == 1) { pos = (inter + new Vector3(0, -sujet.StairHeight, 0)); refPosBottom = pos + new Vector3(0, sujet.StairHeight, 0); } } if (Inside(refPosTop, v1 - 20f * n1, v2 - 20f * n2, v3 - 20f * n3, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3)) { Vector3 direction = refPosTop + normal * sujet.Epaisseur * 10f; if (intersect3D_RayTriangle(refPosTop, direction, v1 + sujet.Epaisseur * n1, v2 + sujet.Epaisseur * n2, v3 + sujet.Epaisseur * n3, out inter) == 1) { pos = (inter + new Vector3(0, -(sujet.MaxVertex.Y), 0)); if (pos.Y < sujet.LowestFloor) pos.Y = sujet.LowestFloor; refPosTop = pos + new Vector3(0, sujet.MaxVertex.Y, 0); } } } else if (normal.Y>0.5) { if (!cliff && !ScenePlayer.ScenePlaying && sujet.cState == Model.ControlState.Fall && !sujet.CliffCancel && (sujet.Links.Count == 0 || sujet.Links[0].ResourceIndex != 39)) { if (intersect3D_RayTriangle(refPosTop + forwardCliffStart, refPosTop + forwardCliffEnd, v1, v2, v3, out inter) == 1 && inter.Y > refPosTop.Y + forwardCliffEnd.Y) { Vector3 coin = inter; int ordre = 0; /* V1V2 V2V3 V3V1*/ float nearest = Single.MaxValue; Vector3 va_vb = v1 * 1f; Vector3 step_va_vb = (v2 - v1) / Vector3.Distance(v2, v1); while (Vector3.Distance(va_vb, v2) > sujet.Epaisseur * 2f) { va_vb += step_va_vb; float dist2d = MainGame.Vector3Distance2D(va_vb, refPosTop); if (dist2d < nearest) { coin = va_vb * 1f; nearest = dist2d; ordre = 0; } } va_vb = v2 * 1f; step_va_vb = (v3 - v2) / Vector3.Distance(v3, v2); while (Vector3.Distance(va_vb, v3) > sujet.Epaisseur * 2f) { va_vb += step_va_vb; float dist2d = MainGame.Vector3Distance2D(va_vb, refPosTop); if (dist2d < nearest) { coin = va_vb * 1f; nearest = dist2d; ordre = 1; } } va_vb = v3 * 1f; step_va_vb = (v1 - v3) / Vector3.Distance(v1, v3); while (Vector3.Distance(va_vb, v1) > sujet.Epaisseur * 2f) { va_vb += step_va_vb; float dist2d = MainGame.Vector3Distance2D(va_vb, refPosTop); if (dist2d < nearest) { coin = va_vb *1f; nearest = dist2d; ordre = 2; } } float angle = 0; if (ordre == 0) { Vector3 v1v2Base = v2 - v1; v1v2Base /= Vector3.Distance(Vector3.Zero, v1v2Base); angle = (float)Math.Atan2(v1v2Base.X, v1v2Base.Z); } if (ordre == 1) { Vector3 v2v3Base = v3 - v2; v2v3Base /= Vector3.Distance(Vector3.Zero, v2v3Base); angle = (float)Math.Atan2(v2v3Base.X, v2v3Base.Z); } if (ordre == 2) { Vector3 v3v1Base = v1 - v3; v3v1Base /= Vector3.Distance(Vector3.Zero, v3v1Base); angle = (float)Math.Atan2(v3v1Base.X, v3v1Base.Z); } if (coin.Y > sujet.LowestFloor + sujet.MaxVertex.Y) { float newDest = angle + MainGame.PI / 2f; SrkBinary.MakePrincipal(ref newDest); sujet.DestRotate = newDest; sujet.Rotate = sujet.DestRotate; sujet.cState = Model.ControlState.Cliff; //Program.game.cursors[0].Position = coin; /*try { string[] input = File.ReadAllLines("data.txt"); cliffBackwards.X = MainGame.SingleParse(input[0]); cliffBackwards.Y = MainGame.SingleParse(input[1]); cliffBackwards.Z = MainGame.SingleParse(input[2]); cliffBackwards = Vector3.Transform(cliffBackwards, rotYMat); } catch { }*/ /*string[] text = File.ReadAllLines(@"D:\Desktop\KHDebug\KHDebug\bin\DesktopGL\AnyCPU\Debug\Content\Models\P_EX100\Joints.txt"); text = text[9].Split(':')[1].Split(','); sujet.CliffPosition.X = MainGame.SingleParse(text[0]); sujet.CliffPosition.Y = MainGame.SingleParse(text[1]); sujet.CliffPosition.Z = MainGame.SingleParse(text[2]);*/ cliffBackwards = Vector3.Transform(sujet.CliffPosition, sujet.Rotate_matrix); pos = coin - cliffBackwards; sujet.locBlock = 10; sujet.loc = pos; sujet.locAction = sujet.loc; return; } } } if (intersect3D_RayTriangle(pos + globalBone0+new Vector3(0, 50000, 0), pos + globalBone0 + new Vector3(0, -50000, 0), v1, v2, v3, out inter) ==1) { if (Single.IsNaN(sujet.LastLand.X)) { if (inter.Y < smallest) { smallest = inter.Y; } if (inter.Y <= sujet.Location.Y + sujet.StairHeight * 1.5f && inter.Y > tallest) { shadowAngle = new Vector3( 0, (float)Math.Atan2(normal.Z, normal.Y), (float)Math.Atan2(-normal.X, normal.Y)); tallest = inter.Y; } } } } if (tallest > Single.MinValue / 2f) { if (tallest <sujet.Location.Y + sujet.StairHeight * 1.5f) sujet.LowestFloor = tallest; } else if (smallest < Single.MaxValue / 2f) { if (smallest < sujet.Location.Y + sujet.StairHeight * 1.5f) sujet.LowestFloor = smallest; } } sujet.ShadowMatrixSurface = Matrix.CreateFromYawPitchRoll(shadowAngle.X, shadowAngle.Y, shadowAngle.Z); if (pushed && pos.Y<sujet.LowestFloor) { pos.Y = sujet.LowestFloor; } }
public Vector3 GetCameraCollisionIntersect(Vector3 old_, Vector3 new_, bool try2) { Vector3 output = NaNoutput; Vector3 inter = Vector3.Zero; float closest = Single.MaxValue; UpdateIndex(Program.game.mainCamera.RealPosition); int start_ = this.StartEnds[this.CurrIndex][0]; int end_ = this.StartEnds[this.CurrIndex][1]; for (int i = start_; i < end_; i++) { Vector3 v1 = cols[this.indices[i][0][0]]; Vector3 v2 = cols[this.indices[i][1][0]]; Vector3 v3 = cols[this.indices[i][2][0]]; Vector3 n1 = norms[this.indices[i][0][1]]; Vector3 n2 = norms[this.indices[i][1][1]]; Vector3 n3 = norms[this.indices[i][2][1]]; Vector3 normal = (n1 + n2 + n3) / 3f; if (try2) { Vector3 middleSolo = ((v1 + v2 + v3) / 3f); Vector3 middle = middleSolo - old_; float distMiddle = Vector3.Distance(Vector3.Zero, middle); Vector3 middlep1 = middle / distMiddle; Vector3 toNew = new_ - old_; float distToNew = Vector3.Distance(Vector3.Zero, toNew); Vector3 toNewp1 = toNew / distToNew; Vector3 movedMiddle = old_ + toNewp1 * distMiddle; movedMiddle = (movedMiddle - middleSolo) * 0.1f; if (Vector3.Distance(Vector3.Zero, movedMiddle) < 3) { v1 += movedMiddle; v2 += movedMiddle; v3 += movedMiddle; } } if (intersect3D_RayTriangle(old_, new_, v1, v2, v3, out inter) != 0) { float dist = Vector3.Distance(old_, inter); if (dist > 0 && dist < closest && dist < Vector3.Distance(old_, new_)) { if (normal.Y > 0.5f) output = inter + normal * 60f; else output = inter + normal * 30f; closest = dist; } } } for (int i = 0; i < /*MainGame.ResourceFiles.Count +*/ Program.game.Map.Supp.Count; i++) { Model mdl = /*if (i >= MainGame.ResourceFiles.Count) mdl = Program.game.Map.Supp[i - MainGame.ResourceFiles.Count] as Model; else mdl = MainGame.ResourceFiles[i] as Model;*/ Program.game.Map.Supp[i] as Model; if (mdl == null) continue; if (mdl.Collision == null) continue; Model target = Program.game.mainCamera.Target; if (target != null && target.ResourceIndex == mdl.ResourceIndex) continue; start_ = mdl.Collision.StartEnds[0][0]; end_ = mdl.Collision.StartEnds[0][1]; for (int j = start_; j < end_; j++) { Matrix mt = mdl.Skeleton.Bones[mdl.Skeleton.RootBone].LocalMatrix; if (Vector3.Distance(mdl.Location, Vector3.Zero) > 0) mt = Matrix.Identity; Vector3 v1 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][0][0]], mt), mdl.Rotate_matrix) + mdl.Location; Vector3 v2 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][1][0]], mt), mdl.Rotate_matrix) + mdl.Location; Vector3 v3 = Vector3.Transform( Vector3.Transform(mdl.Collision.cols[mdl.Collision.indices[j][2][0]], mt), mdl.Rotate_matrix) + mdl.Location; var mt_mat = Matrix.CreateFromQuaternion(mt.Rotation); Vector3 n1 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][0][1]], mt_mat); Vector3 n2 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][1][1]], mt_mat); Vector3 n3 = Vector3.Transform(mdl.Collision.norms[mdl.Collision.indices[j][2][1]], mt_mat); Vector3 normal = (n1 + n2 + n3) / 3f; if (try2) { Vector3 middleSolo = ((v1 + v2 + v3) / 3f); Vector3 middle = middleSolo - old_; float distMiddle = Vector3.Distance(Vector3.Zero, middle); Vector3 middlep1 = middle / distMiddle; Vector3 toNew = new_ - old_; float distToNew = Vector3.Distance(Vector3.Zero, toNew); Vector3 toNewp1 = toNew / distToNew; Vector3 movedMiddle = old_ + toNewp1 * distMiddle; movedMiddle = (movedMiddle - middleSolo) * 0.1f; if (Vector3.Distance(Vector3.Zero, movedMiddle) < 3) { v1 += movedMiddle; v2 += movedMiddle; v3 += movedMiddle; } } if (intersect3D_RayTriangle(old_, new_, v1, v2, v3, out inter) != 0) { float dist = Vector3.Distance(old_, inter); if (dist > 0 && dist < closest && dist < Vector3.Distance(old_, new_)) { output = inter + normal * 30f; closest = dist; } } } } if (!try2 && Single.IsNaN(output.X)) { return GetCameraCollisionIntersect(old_, new_, true); } return output; }
public void Multiply(Matrix matrix) { }
public void Multiply(Matrix matrix, MatrixOrder order) { }
public void DrawTest11() { slider.LocalMatrix = Matrix.Translation(20, 30, 0) * Matrix.RotationYawPitchRoll(-0.1f, -0.2f, 0.3f); }
public Bone() { Transform = Matrix.Identity; }
public IMatrix GetTransform(LinearGradientBrush widget) { return(((EtoGradient)widget.ControlObject).Transform.ToEto() ?? Matrix.Create()); }
public GraphicsResource(int effect, String modelfile) { effectType = effect; modelFile = modelfile; this.transform = Matrix.Identity; }
public override HitResult CheckHit(SETItem item, Vector3 Near, Vector3 Far, Viewport Viewport, Matrix Projection, Matrix View, MatrixStack transform) { transform.Push(); transform.NJTranslate(item.Position); transform.NJRotateObject(item.Rotation); HitResult result = model.CheckHit(Near, Far, Viewport, Projection, View, transform, meshes); transform.Pop(); return(result); }
public GraphicsResource(int effect, String modelfile, Matrix transform) { effectType = effect; modelFile = modelfile; this.transform = transform; }
public void Update(GameTime gameTime) { if (velocity != Vector2.Zero) { WorldLocation += velocity; RepositionCamera(); } bool mouseInBounds = InputHandler.MouseRectangle.Intersects(GeneralArea); if (!mouseInBounds || !InputHandler.RightButtonIsClicked()) { if (scrolling) { deSquareerating = velocity * 50; } velocity = (float)gameTime.ElapsedGameTime.TotalSeconds * deSquareerating; if (!mouseInBounds) { ReduceVector(ref deSquareerating, 100f); } else { ReduceVector(ref deSquareerating, 2000f); } scrolling = false; return; } if (InputHandler.RightButtonIsClicked() && !scrolling) { Vector2 CurrentMousePosition = Vector2.Transform(InputHandler.MousePosition, Matrix.Invert(camera.GetTransformation())); scrolling = true; initialPos = CurrentMousePosition; } else if (InputHandler.RightButtonIsClicked() && scrolling) { Vector2 CurrentMousePosition = Vector2.Transform(InputHandler.MousePosition, Matrix.Invert(camera.GetTransformation())); velocity = initialPos - CurrentMousePosition; initialPos = CurrentMousePosition; } }
public abstract void drawSelectionFrame(SpriteBatch sb, Matrix matrix, Color color);
public void BuildMap(EyeableBorderObjInfo[] objInfos, Rectanglef mapBorder, float spaceForTank) { #region 对每一个BorderObj生成逻辑坐标上的凸包点集,并向外扩展 borderLines = new List <Segment>(); convexs = new List <GuardConvex>(); foreach (EyeableBorderObjInfo obj in objInfos) { if (obj.ConvexHall == null || obj.IsDisappeared || obj.ConvexHall.Points == null) { continue; } Matrix matrix = obj.EyeableInfo.CurTransMatrix; GraphPoint <NaviPoint>[] convexHall; List <VisiBordPoint> bordPoints = obj.ConvexHall.Points; if (bordPoints.Count > 2) { List <GraphPoint <NaviPoint> > list = new List <GraphPoint <NaviPoint> >(); for (int i = 0; i < bordPoints.Count; i++) { Vector2 lastPos = Vector2.Transform(ConvertHelper.PointToVector2(bordPoints[i - 1 < 0 ? bordPoints.Count - 1 : i - 1].p), matrix); Vector2 curPos = Vector2.Transform(ConvertHelper.PointToVector2(bordPoints[i].p), matrix); Vector2 nextPos = Vector2.Transform(ConvertHelper.PointToVector2(bordPoints[(i + 1) % bordPoints.Count].p), matrix); Vector2 v1 = curPos - lastPos; Vector2 v2 = curPos - nextPos; float ang = MathTools.AngBetweenVectors(v1, v2); if (ang >= MathHelper.PiOver2) { float halfDes = (float)(spaceForTank / Math.Sin(ang)); Vector2 delta = halfDes * Vector2.Normalize(v1) + halfDes * Vector2.Normalize(v2); list.Add(new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[i].index, curPos + delta), new List <GraphPath <NaviPoint> >())); } else { v1.Normalize(); v2.Normalize(); Vector2 cenV = Vector2.Normalize(v1 + v2); Vector2 vertiV = new Vector2(cenV.Y, -cenV.X); float ang2 = MathHelper.PiOver4 - 0.25f * ang; float vertiL = (float)(spaceForTank * Math.Tan(ang2)); list.Add(new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[i].index, curPos + spaceForTank * cenV + vertiL * vertiV), new List <GraphPath <NaviPoint> >())); list.Add(new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[i].index, curPos + spaceForTank * cenV - vertiL * vertiV), new List <GraphPath <NaviPoint> >())); } // 添加borderLine borderLines.Add(new Segment(curPos, nextPos)); } convexHall = list.ToArray(); convexs.Add(new GuardConvex(convexHall)); } else if (bordPoints.Count == 2) { convexHall = new GraphPoint <NaviPoint> [4]; Vector2 startPos = Vector2.Transform(ConvertHelper.PointToVector2(bordPoints[0].p), matrix); Vector2 endPos = Vector2.Transform(ConvertHelper.PointToVector2(bordPoints[1].p), matrix); Vector2 dir = endPos - startPos; dir.Normalize(); Vector2 normal = new Vector2(dir.Y, -dir.X); convexHall[0] = new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[0].index, startPos - dir * spaceForTank), new List <GraphPath <NaviPoint> >()); convexHall[1] = new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[0].index, startPos + spaceForTank * normal), new List <GraphPath <NaviPoint> >()); convexHall[2] = new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[1].index, endPos + spaceForTank * normal), new List <GraphPath <NaviPoint> >()); convexHall[3] = new GraphPoint <NaviPoint>( new NaviPoint(obj, bordPoints[1].index, endPos + dir * spaceForTank), new List <GraphPath <NaviPoint> >()); //if (float.IsNaN( convexHall[0].value.Pos.X ) || float.IsNaN( convexHall[1].value.Pos.X )) //{ //} // 添加borderLine borderLines.Add(new Segment(startPos, endPos)); convexs.Add(new GuardConvex(convexHall)); } } #endregion #region 得到警戒线 guardLines = new List <Segment>(); foreach (GuardConvex convex in convexs) { for (int i = 0; i < convex.points.Length; i++) { guardLines.Add(new Segment(convex[i].value.Pos, convex[(i + 1) % convex.Length].value.Pos)); //if (float.IsNaN( convex[i].value.Pos.X )) //{ //} } } mapBorder = new Rectanglef(mapBorder.X + spaceForTank, mapBorder.Y + spaceForTank, mapBorder.Width - 2 * spaceForTank, mapBorder.Height - 2 * spaceForTank); guardLines.Add(new Segment(mapBorder.UpLeft, mapBorder.UpRight)); guardLines.Add(new Segment(mapBorder.UpRight, mapBorder.DownRight)); guardLines.Add(new Segment(mapBorder.DownRight, mapBorder.DownLeft)); guardLines.Add(new Segment(mapBorder.DownLeft, mapBorder.UpLeft)); #endregion #region 检查凸包内部连线是否和警戒线相交,如不相交则连接该连线并计算权值 foreach (GuardConvex convex in convexs) { for (int i = 0; i < convex.Length; i++) { // 检查连线是否超出边界 if (!mapBorder.Contains(convex[i].value.Pos)) { continue; } Segment link = new Segment(convex[i].value.Pos, convex[(i + 1) % convex.Length].value.Pos); bool isCross = false; foreach (Segment guardLine in guardLines) { if (link.Equals(guardLine)) { continue; } if (Segment.IsCross(link, guardLine)) { isCross = true; break; } } if (!isCross) { float weight = Vector2.Distance(convex[i].value.Pos, convex[(i + 1) % convex.Length].value.Pos); //if (float.IsNaN( weight )) //{ //} GraphPoint <NaviPoint> .Link(convex[i], convex[(i + 1) % convex.Length], weight); } } } #endregion #region 检查凸包之间连线是否与警戒线以及边界线相交,如不相交则连接并计算权值 for (int i = 0; i < convexs.Count - 1; i++) { for (int j = i + 1; j < convexs.Count; j++) { foreach (GraphPoint <NaviPoint> p1 in convexs[i].points) { // 检查连线是否超出边界 if (!mapBorder.Contains(p1.value.Pos)) { continue; } foreach (GraphPoint <NaviPoint> p2 in convexs[j].points) { Segment link = new Segment(p1.value.Pos, p2.value.Pos); bool isCross = false; foreach (Segment guardLine in guardLines) { if (Segment.IsCross(link, guardLine)) { isCross = true; break; } } if (!isCross) { foreach (Segment borderLine in borderLines) { if (Segment.IsCross(link, borderLine)) { isCross = true; break; } } } if (!isCross) { float weight = Vector2.Distance(p1.value.Pos, p2.value.Pos); //if (float.IsNaN( weight )) //{ //} GraphPoint <NaviPoint> .Link(p1, p2, weight); } } } } } #endregion #region 整理导航图 List <GraphPoint <NaviPoint> > points = new List <GraphPoint <NaviPoint> >(); foreach (GuardConvex convex in convexs) { foreach (GraphPoint <NaviPoint> p in convex.points) { points.Add(p); } } naviGraph = points.ToArray(); #endregion }
/// <summary> /// Updates the camera's transformation matrix. /// </summary> private void UpdateTransformation() { this.transformation = Matrix.Identity * this.matrixPosition * this.matrixRotation * this.matrixZoom * this.matrixOrigin; }
private void tryPlaceObject() { if (!TW.Graphics.Mouse.LeftMouseJustPressed) { return; } Grid = new UnionGrid(grid, HermiteDataGrid.FromIntersectableGeometry(10, 20, Matrix.Translation(RaycastedPoint), PlaceableObjectGrid)); Grid = HermiteDataGrid.CopyGrid(grid); }
/// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient <see cref="Matrix{T}"/>, <c>A</c>.</param> /// <param name="input">The solution <see cref="Vector{T}"/>, <c>b</c>.</param> /// <param name="result">The result <see cref="Vector{T}"/>, <c>x</c>.</param> public void Solve(Matrix<float> matrix, Vector<float> input, Vector<float> result) { // If we were stopped before, we are no longer // We're doing this at the start of the method to ensure // that we can use these fields immediately. _hasBeenStopped = false; // Parameters checks if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (input == null) { throw new ArgumentNullException("input"); } if (result == null) { throw new ArgumentNullException("result"); } if (result.Count != input.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (input.Count != matrix.RowCount) { throw new ArgumentException(Resources.ArgumentMatrixDimensions); } // Initialize the solver fields // Set the convergence monitor if (_iterator == null) { _iterator = Iterator.CreateDefault(); } if (_preconditioner == null) { _preconditioner = new UnitPreconditioner(); } _preconditioner.Initialize(matrix); // Compute r_0 = b - Ax_0 for some initial guess x_0 // In this case we take x_0 = vector // This is basically a SAXPY so it could be made a lot faster Vector<float> residuals = new DenseVector(matrix.RowCount); CalculateTrueResidual(matrix, residuals, result, input); // Choose r~ (for example, r~ = r_0) var tempResiduals = residuals.Clone(); // create seven temporary vectors needed to hold temporary // coefficients. All vectors are mangled in each iteration. // These are defined here to prevent stressing the garbage collector Vector<float> vecP = new DenseVector(residuals.Count); Vector<float> vecPdash = new DenseVector(residuals.Count); Vector<float> nu = new DenseVector(residuals.Count); Vector<float> vecS = new DenseVector(residuals.Count); Vector<float> vecSdash = new DenseVector(residuals.Count); Vector<float> temp = new DenseVector(residuals.Count); Vector<float> temp2 = new DenseVector(residuals.Count); // create some temporary float variables that are needed // to hold values in between iterations float currentRho = 0; float alpha = 0; float omega = 0; var iterationNumber = 0; while (ShouldContinue(iterationNumber, result, input, residuals)) { // rho_(i-1) = r~^T r_(i-1) // dotproduct r~ and r_(i-1) var oldRho = currentRho; currentRho = tempResiduals.DotProduct(residuals); // if (rho_(i-1) == 0) // METHOD FAILS // If rho is only 1 ULP from zero then we fail. if (currentRho.AlmostEqual(0, 1)) { // Rho-type breakdown throw new Exception("Iterative solver experience a numerical break down"); } if (iterationNumber != 0) { // beta_(i-1) = (rho_(i-1)/rho_(i-2))(alpha_(i-1)/omega(i-1)) var beta = (currentRho / oldRho) * (alpha / omega); // p_i = r_(i-1) + beta_(i-1)(p_(i-1) - omega_(i-1) * nu_(i-1)) nu.Multiply(-omega, temp); vecP.Add(temp, temp2); temp2.CopyTo(vecP); vecP.Multiply(beta, vecP); vecP.Add(residuals, temp2); temp2.CopyTo(vecP); } else { // p_i = r_(i-1) residuals.CopyTo(vecP); } // SOLVE Mp~ = p_i // M = preconditioner _preconditioner.Approximate(vecP, vecPdash); // nu_i = Ap~ matrix.Multiply(vecPdash, nu); // alpha_i = rho_(i-1)/ (r~^T nu_i) = rho / dotproduct(r~ and nu_i) alpha = currentRho * 1 / tempResiduals.DotProduct(nu); // s = r_(i-1) - alpha_i nu_i nu.Multiply(-alpha, temp); residuals.Add(temp, vecS); // Check if we're converged. If so then stop. Otherwise continue; // Calculate the temporary result. // Be careful not to change any of the temp vectors, except for // temp. Others will be used in the calculation later on. // x_i = x_(i-1) + alpha_i * p^_i + s^_i vecPdash.Multiply(alpha, temp); temp.Add(vecSdash, temp2); temp2.CopyTo(temp); temp.Add(result, temp2); temp2.CopyTo(temp); // Check convergence and stop if we are converged. if (!ShouldContinue(iterationNumber, temp, input, vecS)) { temp.CopyTo(result); // Calculate the true residual CalculateTrueResidual(matrix, residuals, result, input); // Now recheck the convergence if (!ShouldContinue(iterationNumber, result, input, residuals)) { // We're all good now. return; } // Continue the calculation iterationNumber++; continue; } // SOLVE Ms~ = s _preconditioner.Approximate(vecS, vecSdash); // temp = As~ matrix.Multiply(vecSdash, temp); // omega_i = temp^T s / temp^T temp omega = temp.DotProduct(vecS) / temp.DotProduct(temp); // x_i = x_(i-1) + alpha_i p^ + omega_i s^ temp.Multiply(-omega, residuals); residuals.Add(vecS, temp2); temp2.CopyTo(residuals); vecSdash.Multiply(omega, temp); result.Add(temp, temp2); temp2.CopyTo(result); vecPdash.Multiply(alpha, temp); result.Add(temp, temp2); temp2.CopyTo(result); // for continuation it is necessary that omega_i != 0.0 // If omega is only 1 ULP from zero then we fail. if (omega.AlmostEqual(0, 1)) { // Omega-type breakdown throw new Exception("Iterative solver experience a numerical break down"); } if (!ShouldContinue(iterationNumber, result, input, residuals)) { // Recalculate the residuals and go round again. This is done to ensure that // we have the proper residuals. // The residual calculation based on omega_i * s can be off by a factor 10. So here // we calculate the real residual (which can be expensive) but we only do it if we're // sufficiently close to the finish. CalculateTrueResidual(matrix, residuals, result, input); } iterationNumber++; } }
//Calculate how far a pivot is away from a plane in direction ax private float getDistanceTillBoundry(Vector3 pivot, Vector3 ax) { //Apply the rotation of the plane on the vector ax ax = Vector3.Transform(ax, Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z)); //Determen the limits of the plane Vector3 min = position - scale * ax; Vector3 max = position + scale * ax; //Determen the distance from point to plane limit Vector3 distanceTillMinVector = Physics.getDistanceBetweenPoint(min, pivot, ax); Vector3 distanceTillMaxVector = Physics.getDistanceBetweenPoint(max, pivot, ax); float distanceTillMin = distanceTillMinVector.X + distanceTillMinVector.Y + distanceTillMinVector.Z; float distanceTillMax = distanceTillMaxVector.X + distanceTillMaxVector.Y + distanceTillMaxVector.Z; float distanceTillBoundry; if (Math.Sign(distanceTillMin) != Math.Sign(distanceTillMax) || distanceTillMin.Equals(Vector3.Zero) || distanceTillMax.Equals(Vector3.Zero)) //Determen if a plane is between or on the plane limits { distanceTillBoundry = 0; } else { if (Math.Abs(distanceTillMin) < Math.Abs(distanceTillMax)) { distanceTillBoundry = -distanceTillMin; } else { distanceTillBoundry = -distanceTillMax; } } return(distanceTillBoundry); }
public Plane(Vector3 position, Vector3 rotation, float scale, GraphicsDevice device) : base(position, rotation, scale, device) { Vector3 normalDirection = Vector3.Transform(Vector3.Up, Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z)); float d = position.X * normalDirection.X + position.Y * normalDirection.Y + position.Z * normalDirection.Z; _equation = new Vector4(normalDirection, d); }
public override void GetCascadeViewParameters(LightShadowMapTexture shadowMapTexture, int cascadeIndex, out Matrix view, out Matrix projection) { var shaderData = (LightDirectionalShadowMapShaderData)shadowMapTexture.ShaderData; view = shaderData.ViewMatrix[cascadeIndex]; projection = shaderData.ProjectionMatrix[cascadeIndex]; }
/// <summary> /// Build a bridge with given number planks in the Z direction /// Normalized to unit length /// </summary> /// <param name="numPlanks"></param> /// <returns></returns> public IMesh BuildMesh(int numPlanks) { // Currently straight var ret = factory.CreateEmptyDynamicMesh(); var endSticksZ = numPlanks - 0.2f; for (int i = 0; i < numPlanks; i++) { MeshBuilder.AppendMeshTo(plank, ret, Matrix.Translation(0, 0, 0.4f + i * 1f)); } MeshBuilder.AppendMeshTo(stick, ret, Matrix.RotationY(MathHelper.Pi) * Matrix.RotationY(-MathHelper.PiOver2) * Matrix.Translation(-0.9f, 0, 0)); MeshBuilder.AppendMeshTo(stick, ret, Matrix.RotationY(MathHelper.Pi) * Matrix.Translation(0.9f, 0, 0)); MeshBuilder.AppendMeshTo(stick, ret, Matrix.RotationY(-MathHelper.PiOver2) * Matrix.Translation(-0.9f, 0, endSticksZ)); MeshBuilder.AppendMeshTo(stick, ret, Matrix.Translation(0.9f, 0, endSticksZ)); MeshBuilder.AppendMeshTo(rope, ret, Matrix.Translation(-0.9f, 0, 5) * Matrix.Scaling(1, 1, endSticksZ / 10f)); MeshBuilder.AppendMeshTo(rope, ret, Matrix.Translation(0.9f, 0, 5) * Matrix.Scaling(1, 1, endSticksZ / 10f)); foreach (var part in ret.GetCoreData().Parts) { part.ObjectMatrix = part.ObjectMatrix * Matrix.Scaling(1, 1, 1f / endSticksZ).xna(); } return ret; }