public WooState() { _Rotation = new Matrix3(); _Rotation.MakeIdentity(); int idx = 0; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 0; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; _MengerPattern[idx++] = 1; }
// Reference : Oliver K. Smith: Eigenvalues of a symmetric 3 × 3 matrix. Commun. ACM 4(4): 168 (1961) // find the eigenvalues of a 3x3 symmetric matrix //NOTE: I'm doing some post-processing on them to turn them into singular values Vector3 getEigenvalues(Matrix3 mat) { var m = (mat.trace()) / 3; var K = mat - (Matrix3.I()*m); // K = mat - I*tr(mat) var q = K.determinant() / 2; var tempForm = K*K; var p = tempForm.sumCells() / 6; // NB in Smith's paper he uses phi = (1/3)*arctan(sqrt(p*p*p - q*q)/q), which is equivalent to below: var phi = (1/3)*Mathf.Acos(q/Mathf.Sqrt(p*p*p)); if (Mathf.Abs(q) >= Mathf.Abs(Mathf.Sqrt(p*p*p))) { phi = 0; } if (phi < 0) { phi = phi + Mathf.PI/3; } var eig1 = m + 2*Mathf.Sqrt(p)*Mathf.Cos(phi); var eig2 = m - Mathf.Sqrt(p)*(Mathf.Cos(phi) + Mathf.Sqrt(3)*Mathf.Sin(phi)); var eig3 = m - Mathf.Sqrt(p)*(Mathf.Cos(phi) - Mathf.Sqrt(3)*Mathf.Sin(phi)); // return a singular values vector return new Vector3(Mathf.Sqrt(Mathf.Abs(eig1)), Mathf.Sqrt(Mathf.Abs(eig2)), Mathf.Sqrt(Mathf.Abs(eig3))); }
public Fractal(Vector3 centre, Vector3 scale, Matrix3 rotation, double distanceMinimum, double distanceScale, Vector3 distanceOffset, int distanceIterations, Vector3 distanceExtents, double stepSize, List<FractalIteration> fractalIterations, int fractalIterationCount, int colourIterationCount, int deMode) { _Material = new Material(); _Position = new Vector3(); _Scale = new Vector3(); _Rotation = new Matrix3(); _Position = centre; _Scale = scale; _Rotation = rotation; _DistanceMinimum = distanceMinimum; _DistanceScale = distanceScale; _DistanceOffset = distanceOffset; _DistanceIterations = distanceIterations; _DistanceExtents = distanceExtents; _StepSize = stepSize; _FractalIterations = fractalIterations; _FractalIterationCount = fractalIterationCount; _ColourIterationCount = colourIterationCount; _DEMode = deMode; }
public void RunTests() { Matrix3 a, b; DXMtx dxa, dxb; a = new Matrix3(3, 1, 2, 1, 1, 2, 2, 3, 1); b = new Matrix3(4, 2, 1, 3, 1, 2, 2, 1, 2); dxa = new DXMtx(); dxb = new DXMtx(); dxa.M11 = 3; dxa.M12 = 1; dxa.M13 = 2; dxa.M21 = 1; dxa.M22 = 1; dxa.M23 = 2; dxa.M31 = 2; dxa.M32 = 3; dxa.M33 = 1; dxb.M11 = 4; dxb.M12 = 2; dxb.M13 = 1; dxb.M21 = 3; dxb.M22 = 1; dxb.M23 = 2; dxb.M31 = 2; dxb.M32 = 1; dxb.M33 = 2; Roll = 45; Yaw = 10; Pitch = 30; TestAdd(a, b, dxa, dxb); TestSub(a, b, dxa, dxb); TestMul(a, b, dxa, dxb); TestTranspose(a, dxa); TestInvert(a, dxa); TestRotations(); PrintResults(a, b); }
public void AdditionTest_Success() { Matrix3 a = new Matrix3(new double[,] { {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0} }); Matrix3 b = new Matrix3(new double[,] { {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0} }); Matrix3 result = a + b; Matrix3 expected = new Matrix3(new double[,] { {2.0, 4.0, 6.0}, {8.0, 10.0, 12.0}, {14.0, 16.0, 18.0} }); Assert.AreEqual(expected, result); }
public Distance(Vector3 centre, Vector3 scale, Matrix3 rotation, string distanceFunction, double distanceMinimum, double distanceScale, Vector3 distanceOffset, int distanceIterations, Vector3 distanceExtents, double stepSize) { _Material = new Material(); _Position = new Vector3(); _Scale = new Vector3(); _Rotation = new Matrix3(); _Position = centre; _Scale = scale; _Rotation = rotation; _DistanceFunction = distanceFunction; _DistanceMinimum = distanceMinimum; _DistanceScale = distanceScale; _DistanceOffset = distanceOffset; _DistanceIterations = distanceIterations; _DistanceExtents = distanceExtents; _StepSize = stepSize; }
public void TransformNormalize(Matrix3 m) { float[] result = m.VectorMultiply (new float[] { X, Y, Z, W }); X = result [0] / result [3]; Y = result [1] / result [3]; Z = result [2]; W = 1; }
public void ProjectOnto(ref Matrix3 transform, ref Vector2 axisNormal, out Vector2 projection) { Vector2 halfWidth, halfHeight; CalculateExtents(ref transform, out halfWidth, out halfHeight); halfWidth -= transform.Origin; halfHeight -= transform.Origin; projection.X = Vector2.Dot(halfWidth, axisNormal); projection.Y = Vector2.Dot(halfHeight, axisNormal); }
public SurfacePoint(Vector3 position, Triangle face, Vector3 barycentricCoords, float surfaceOffset, Matrix3 orientationMatrix) { Position = position; Face = face; BarycentricCoords = barycentricCoords; SurfaceOffset = surfaceOffset; Psi = 0; OriginalMatrix = orientationMatrix; }
public Cylinder(Vector3 centre, Vector3 scale, Matrix3 rotation) { _Material = new Material(); _Position = new Vector3(); _Scale = new Vector3(); _Rotation = new Matrix3(); _Position = centre; _Scale = scale; _Rotation = rotation; }
public override void CalculateAABB(ref Matrix3 transform, out AABB aabb) { Vector2 halfWidth, halfHeight; CalculateExtents(ref transform, out halfWidth, out halfHeight); Vector2 halfWidthOther, halfHeightOther; CalculateOtherExtents(ref transform, out halfWidthOther, out halfHeightOther); aabb.Min = Vector2.Min(halfWidth, halfWidthOther) + Vector2.Min(halfHeight, halfHeightOther) - transform.Origin; aabb.Max = Vector2.Max(halfWidth, halfWidthOther) + Vector2.Max(halfHeight, halfHeightOther) - transform.Origin; }
public void Constructor_FromFlatArray_Empty_Success() { double[] empty = new double[0]; Matrix3 mat = new Matrix3(empty); Assert.AreEqual(0.0, mat[0, 0], Epsilon); Assert.AreEqual(0.0, mat[1, 0], Epsilon); Assert.AreEqual(0.0, mat[1, 2], Epsilon); Assert.AreEqual(0.0, mat[2, 2], Epsilon); }
public virtual void FreeLookAt(Vector3 targetAbsRef, Vector3 upRelRef) { //Vector v1 = new Vector3(0, 0, -1); //Vector moveV = _staticModel.Position - vector; //Vector v2 = moveV.RotateBy(_staticModel.Orientation.W, 0, 1, 0); /*Vector forward = lookAt.Normalized(); Vector right = Vector::Cross(up.Normalized(), forward); Vector up = Vector::Cross(forward, right);*/ Vector3 forward ; if (_mainModel.IsChild) { //Normalizing target and transforming it to local system forward = Geometric.Quaternion_Rotate(_mainModel.ParentModel.Orientation.Inverted(), targetAbsRef.Normalized()) - _mainModel.ParentModel.Position; } else { //Normalizing target.. local system is the same as world system forward = targetAbsRef.Normalized(); } //Normalizing upVector (we are assuming it is expressed in local system) Vector3 eye = _mainModel.PositionRelative.Normalized(); Vector3 up = upRelRef.Normalized(); //Insert manual imprecision to avoid singularity if( Vector3.Dot(forward,up) == 1 ) { forward.X += 0.001f; forward.Y += 0.001f; forward.Z += 0.001f; } //float angle = (float)Math.Acos( Vector3.DotProduct(current,targetAbsRef) ); //Vector3 rotAxis = Vector3.CrossProduct(current, forward).Normalize(); //Vector3 right = Vector3.CrossProduct(forward, up); Matrix4 lookAt_result = Matrix4.LookAt( eye.X, eye.Y, eye.Z, forward.X, forward.Y, forward.Z, up.X, up.Y, up.Z ); Matrix3 targetRelOrientation_matrix = new Matrix3(lookAt_result); Quaternion targetRelOrientation_quaternion = Quaternion.FromMatrix(targetRelOrientation_matrix); /* Quaternion targetRelOrientation_quaternion = new Quaternion(); targetRelOrientation_quaternion.W = (float)Math.Sqrt((double)(1.0f + right.X + up.Y + forward.Z)) * 0.5f; float w4_recip = 1.0f / (4.0f * targetRelOrientation_quaternion.W); targetRelOrientation_quaternion.X = (forward.Y - up.Z) * w4_recip; targetRelOrientation_quaternion.Y = (right.Z - forward.X) * w4_recip; targetRelOrientation_quaternion.Z = (up.X - right.Y) * w4_recip; */ _mainModel.OrientationRelative = Quaternion.Slerp(_mainModel.OrientationRelative, targetRelOrientation_quaternion, Game.DeltaTime * 0.001f); }
public static Vector3 Transform(Vector3 vector, Matrix3 matrix) { Matrix4 mat = Matrix4.Identity; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { mat[i, j] = matrix[i, j]; } } return Vector3.Transform(vector, mat); }
public static Func<Vector3, bool> OutsideBox(double length, double width, double height, Vector3 center, Matrix3 orientation) { if (!orientation.IsOrthoganol) throw new ArgumentException(nameof(orientation) + "must be orthoganol."); return pos => { Vector3 r = (pos - center).Rotate(orientation.InverseMatrix()); if (Math.Abs(r.X) > length) return true; if (Math.Abs(r.Y) > width) return true; if (Math.Abs(r.Z) > height) return true; return false; }; }
public Menger(Vector3 centre, Vector3 scale, Matrix3 rotation, int iterations, int[] pattern) { _Material = new Material(); _Position = new Vector3(); _Scale = new Vector3(); _Rotation = new Matrix3(); _Position = centre; _Scale = scale; _Rotation = rotation; _Iterations = iterations; for(int i=0;i<27;i++) _Pattern[i] = pattern[i]; }
public override List<Matrix3> GetMatrices() { Debug.Assert(Controls.Count == 9); var m = Controls; Matrix3 mat = new Matrix3( m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8] ); return new List<Matrix3> { mat }; }
public Physics() { RandomClass = new Random(); windSim = new windSimulation(); angularVelocityStar = new Matrix3(); angularVelocity = new Vector3(); forceI = new Vector3(); totalForce = new Vector3(0.0f, 0.0f, 0.0f); torque = new Vector3(0.0f, 0.0f, 0.0f); }
public void Constructor_FromFlatArray_Success() { double[] input = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; Matrix3 mat = new Matrix3(input); Assert.AreEqual(1.0, mat[0, 0], Epsilon); Assert.AreEqual(4.0, mat[1, 0], Epsilon); Assert.AreEqual(9.0, mat[2, 2], Epsilon); }
public override List<Matrix3> GetMatrices() { var numKnots = NumKnots(); var knots = new List<Matrix3>(numKnots); for (var i = 0; i < numKnots; i++) { var mat = new Matrix3( (float)KnotsControls[numKnots + i * 3 + 0] * ControlScales[0] + ControlOffsets[0], 0, 0, 0, (float)KnotsControls[numKnots + i * 3 + 1] * ControlScales[1] + ControlOffsets[1], 0, 0, 0, (float)KnotsControls[numKnots + i * 3 + 2] * ControlScales[2] + ControlOffsets[2] ); knots.Add(mat); } return knots; }
public override void display() { ClearDisplay(); if (current_mesh != null) { MatrixStack modelMatrix = new MatrixStack(); using (PushStack pushstack = new PushStack(modelMatrix)) { modelMatrix.Translate(Camera.g_camTarget); modelMatrix.Translate(0f, 0f, 0f); modelMatrix.Scale(15.0f, 15.0f, 15.0f); modelMatrix.Rotate(axis, angle); angle = angle + 1f; GL.UseProgram(currentProgram.theProgram); Matrix4 mm = modelMatrix.Top(); if (noWorldMatrix) { Matrix4 cm2 = Matrix4.Mult(mm, cm); GL.UniformMatrix4(currentProgram.modelToCameraMatrixUnif, false, ref cm2); if (currentProgram.normalModelToCameraMatrixUnif != 0) { Matrix3 normalModelToCameraMatrix = Matrix3.Identity; Matrix4 applyMatrix = Matrix4.Mult(Matrix4.Identity, Matrix4.CreateTranslation(dirToLight)); normalModelToCameraMatrix = new Matrix3(applyMatrix); normalModelToCameraMatrix.Invert(); GL.UniformMatrix3(currentProgram.normalModelToCameraMatrixUnif, false, ref normalModelToCameraMatrix); //Matrix4 cameraToClipMatrix = Matrix4.Identity; //GL.UniformMatrix4(currentProgram.cameraToClipMatrixUnif, false, ref cameraToClipMatrix); } //Matrix4 cameraToClipMatrix = Matrix4.Identity; //GL.UniformMatrix4(currentProgram.cameraToClipMatrixUnif, false, ref cameraToClipMatrix); } else { GL.UniformMatrix4(currentProgram.modelToWorldMatrixUnif, false, ref mm); } } current_mesh.Render(); GL.UseProgram(0); } }
public override void CalculateAABB(ref Matrix3 transform, out AABB aabb) { float farthestX, farthestY; farthestX = farthestY = 0; for (int i = 0; i < Vertices.Length; i++) { // calculate the new aabb float vertexDistanceX = Math.Abs(Vertices[i].X); float vertexDistanceY = Math.Abs(Vertices[i].Y); if (vertexDistanceX > farthestX) farthestX = vertexDistanceX; if (vertexDistanceY > farthestY) farthestY = vertexDistanceY; } aabb.Min = transform.Origin - new Vector2(farthestX, farthestY); aabb.Max = transform.Origin + new Vector2(farthestX, farthestY); }
public override List<Matrix3> GetMatrices() { var numKnots = NumKnots(); var knots = new List<Matrix3>(numKnots); for (var i = 0; i < numKnots; i++) { var scale = (float)KnotsControls[numKnots + i] * ControlScale + ControlOffset; var mat = new Matrix3( scale, 0, 0, 0, scale, 0, 0, 0, scale ); knots.Add(mat); } return knots; }
public void Render(List<int> samplers, Matrix4 baseMat) { baseMat = Matrix4.Mult(baseMat, m_nodeTm.GetMatrix()); Matrix4 objMat = baseMat * m_objTm.GetMatrix(); m_pProg.UseProgram(); GL.UniformMatrix4(m_pProg.GetMatrixLoc(), false, ref objMat); if(m_pProg.GetNormalMatLoc() != -1) { Matrix3 normMat = new Matrix3(Matrix4.Transpose(Matrix4.Invert(objMat))); GL.UniformMatrix3(m_pProg.GetNormalMatLoc(), false, ref normMat); } //std::for_each(m_binders.begin(), m_binders.end(), BindBinder(m_pProg->GetProgram())); foreach(StateBinder sb in m_binders) { BindBinder bindBinder = new BindBinder(m_pProg.GetProgram()); bindBinder.StateBinder(sb); } for(int texIx = 0; texIx < m_texBindings.Count; ++texIx) { TextureBinding binding = m_texBindings[texIx]; GL.ActiveTexture(TextureUnit.Texture0 + binding.texUnit); GL.BindTexture(binding.pTex.GetTextureType(), binding.pTex.GetTexture()); GL.BindSampler(binding.texUnit, samplers[(int)binding.sampler]); } m_pMesh.Render(); for(int texIx = 0; texIx < m_texBindings.Count; ++texIx) { TextureBinding binding = m_texBindings[texIx]; GL.ActiveTexture(TextureUnit.Texture0 + binding.texUnit); GL.BindTexture(binding.pTex.GetTextureType(), 0); GL.BindSampler(binding.texUnit, 0); } foreach(StateBinder sb in m_binders) { UnbindBinder unbindBinder = new UnbindBinder(m_pProg.GetProgram()); unbindBinder.StateBinder(sb); } GL.UseProgram(0); }
public void Draw(Vector3 cameraPos, Vector3 gor) { //GL.LoadIdentity(); Vector3 look = position - cameraPos; look = Vector3.Normalize(look); // side pa up Vector3 S = Vector3.Cross(look, gor); Vector3 U = Vector3.Cross(look, S); // nastaumo matriko iz katere se dobi quaternion iz katerga nardim matriko pogleda Matrix3 a123 = new Matrix3(); a123.Row2 = look; a123.Row1 = U; a123.Row0 = S; a123 = Matrix3.Transpose(a123); //treba popravt .... bbMat = Matrix4.CreateFromQuaternion(Quaternion.FromMatrix(a123)); Vector3 right = new Vector3(); Vector3 up = new Vector3(); right[0] = bbMat.Row0.X; right[1] = bbMat.Row0.Y; right[2] = bbMat.Row0.Z; up[0] = bbMat.Row1.X; up[1] = bbMat.Row1.Y; up[2] = bbMat.Row1.Z; // za quad Vector3 a = position - (right + up) * 50; Vector3 b = position + (right - up) * 50; Vector3 c = position + (right + up) * 50; Vector3 d = position - (right - up) * 50; // IZRIS GL.BindTexture(TextureTarget.Texture2D, image); GL.Begin(BeginMode.Quads); GL.TexCoord2(0, 0); GL.Vertex3(a); GL.TexCoord2(0, 1); GL.Vertex3(b); GL.TexCoord2(1, 1); GL.Vertex3(c); GL.TexCoord2(1, 0); GL.Vertex3(d); GL.End(); }
public void PrintResults(Matrix3 a, Matrix3 b) { Console.WriteLine("Matrix 3 Tests:"); Console.WriteLine("A: {0}\nB: {1}", a, b); Console.WriteLine("A + B: {0} ({1}) -- {2}", AdditionResults[0], AdditionResults[1], Passed(AdditionResults[0] == AdditionResults[1])); Console.WriteLine("A - B: {0} ({1}) -- {2}", SubtractionResults[0], SubtractionResults[1], Passed(SubtractionResults[0] == SubtractionResults[1])); Console.WriteLine("A * B: {0} ({1}) -- {2}", MultiplyResults[0], MultiplyResults[1], Passed(MultiplyResults[0] == MultiplyResults[1])); Console.WriteLine("A^T: {0} ({1}) -- {2}", TransposeResults[0], TransposeResults[1], Passed(TransposeResults[0] == TransposeResults[1])); Console.WriteLine("A^-1: {0} ({1}) -- {2}", InverseResults[0], InverseResults[1], Passed(InverseResults[0] == InverseResults[1])); Console.WriteLine("Basic rotation results -- {2}\n{0}\n{1}", BasicRotations[0], BasicRotations[1], Passed(BasicRotations[0] == BasicRotations[1])); Console.WriteLine("Euler rotation results -- {2}\n{0}\n{1}", EulerRotations[0], EulerRotations[1], Passed(EulerRotations[0] == EulerRotations[1])); Console.WriteLine("AxisAngle rotation results -- {2}\n{0}\n{1}", AxisAngleRotations[0], AxisAngleRotations[1], Passed(AxisAngleRotations[0] == AxisAngleRotations[1])); Console.WriteLine("Quaternion rotation results -- {2}\n{0}\n{1}", QuaternionRotations[0], QuaternionRotations[1], Passed(QuaternionRotations[0] == QuaternionRotations[1])); Console.WriteLine("Basic == Euler: {0}", Passed(BasicRotations[0] == EulerRotations[0])); Console.WriteLine("Basic == AxisAngle {0}", Passed(BasicRotations[0] == AxisAngleRotations[0])); Console.WriteLine("Basic == Quaternion {0}", Passed(BasicRotations[0] == QuaternionRotations[0])); }
public override void Draw(DrawEventArgs e) { shader.Use(); /* Calculate Model/View/Projection matrix */ Matrix4.Mult(ref this.modelMatrix, ref e.ModelMatrix, out mvp); Matrix3 m = new Matrix3(mvp); shader.SetMatrix3("model", ref m); // TODO: Mat4 instead? Matrix4.Mult(ref mvp, ref e.Camera.ViewProjection, out mvp); shader.SetMatrix("mvp", ref mvp); /* Normal matrix */ m.Invert(); m.Transpose(); shader.SetMatrix3("G", ref m); mesh.DrawElements(this.triangles * 3, DrawElementsType.UnsignedShort); base.Draw(e); }
public override List<Matrix3> GetMatrices() { Debug.Assert(Components() == 9); var numKnots = NumKnots(); var knots = new List<Matrix3>(numKnots); for (var i = 0; i < numKnots; i++) { var mat = new Matrix3( (float)KnotsControls[numKnots + i * 9 + 0] * ControlScaleOffsets[0] + ControlScaleOffsets[9 + 0], (float)KnotsControls[numKnots + i * 9 + 1] * ControlScaleOffsets[1] + ControlScaleOffsets[9 + 1], (float)KnotsControls[numKnots + i * 9 + 2] * ControlScaleOffsets[2] + ControlScaleOffsets[9 + 2], (float)KnotsControls[numKnots + i * 9 + 3] * ControlScaleOffsets[3] + ControlScaleOffsets[9 + 3], (float)KnotsControls[numKnots + i * 9 + 4] * ControlScaleOffsets[4] + ControlScaleOffsets[9 + 4], (float)KnotsControls[numKnots + i * 9 + 5] * ControlScaleOffsets[5] + ControlScaleOffsets[9 + 5], (float)KnotsControls[numKnots + i * 9 + 6] * ControlScaleOffsets[6] + ControlScaleOffsets[9 + 6], (float)KnotsControls[numKnots + i * 9 + 7] * ControlScaleOffsets[7] + ControlScaleOffsets[9 + 7], (float)KnotsControls[numKnots + i * 9 + 8] * ControlScaleOffsets[8] + ControlScaleOffsets[9 + 8] ); knots.Add(mat); } return knots; }
public SVO(Vector3 centre, Vector3 scale, Matrix3 rotation, string distanceFunction, double distanceMinimum, double distanceScale, Vector3 distanceOffset, double stepSize, int depth) { _Material = new Material(); _Position = new Vector3(); _Scale = new Vector3(); _Rotation = new Matrix3(); _Position = centre; _Scale = scale; _Rotation = rotation; _DistanceFunction = distanceFunction; _DistanceMinimum = distanceMinimum; _DistanceScale = distanceScale; _DistanceOffset = distanceOffset; _StepSize = stepSize; _Depth = depth; }
private static EntityObject ProcessArc(Arc arc, Matrix3 trans, Vector3 pos) { arc.Center = trans * arc.Center + pos; arc.Normal = trans * arc.Normal; return(arc); }
public void SetScale(float x, float y) { _scale = Matrix3.CreateScale(new Vector2(x, y)); }
public void Viewport_Paint() { if (SurfaceMesh != null) { Vector3[] Bounds = SurfaceMesh.BoundingBoxCorners; Matrix4 ViewMatrix = Viewport.Camera.GetView(); float MinDist = float.MaxValue; float MaxDist = -float.MaxValue; foreach (var corner in Bounds) { float Dist = -Vector3.Transform(corner, ViewMatrix).Z; MinDist = Math.Min(MinDist, Dist); MaxDist = Math.Max(MaxDist, Dist); } MainWindow.Options.Viewport.Camera.ClipNear = Math.Max(1f, MinDist / 2); MainWindow.Options.Viewport.Camera.ClipFar = Math.Max(2f, MaxDist * 2); } MeshProgram.Use(); { MeshProgram.SetUniform("worldViewProjMatrix", MainWindow.Options.Viewport.Camera.GetViewProj()); MeshProgram.SetUniform("surfaceOffset", (float)SurfaceOffset * MainWindow.Options.PixelScale.X); if (TomogramTexture != null) { MeshProgram.SetUniform("useVolume", 1f); MeshProgram.SetUniform("volScale", OpenGLHelper.Reciprocal(TomogramTexture.Scale)); MeshProgram.SetUniform("volOffset", TomogramTexture.Offset); MeshProgram.SetUniform("texSize", OpenGLHelper.Reciprocal(TomogramTexture.Size)); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture3D, TomogramTexture.Handle); } else { MeshProgram.SetUniform("useVolume", 0f); } GL.ActiveTexture(TextureUnit.Texture1); GL.BindTexture(TextureTarget.Texture2D, SelectionTexture.Handle); float TraceStart = TraceDepthOffset; float TraceLength = TraceDepth; MeshProgram.SetUniform("traceParams", new Vector2(TraceStart, TraceLength)); MeshProgram.SetUniform("traceSharpening", (float)TraceSharpening / 100f); float RangeMin = (float)Math.Min(OutputRangeMin, OutputRangeMax), RangeMax = (float)Math.Max(OutputRangeMin, OutputRangeMax); MeshProgram.SetUniform("normalizeParams", new Vector2(RangeMin, RangeMax - RangeMin)); Vector3 LightDirection = MainWindow.Options.Viewport.Camera.GetDirection(); MeshProgram.SetUniform("lightDirection", LightDirection); MeshProgram.SetUniform("lightIntensity", OutputLight / 100f); if (SurfaceMesh != null) { SurfaceMesh.Draw(); } } // Draw point groups. There are 3 options for depiction: // - Boxes with custom size // - Same mesh for every point in a group, e. g. protein map from EMDB // - Individual mesh for every point in a group, e. g. isosurface within its enclosed volume { List <PointGroup> AllGroups = new List <PointGroup>(PointGroups); AllGroups.Add(PreviewGroup); foreach (PointGroup group in AllGroups.Where(g => g.IsVisible && g.Points.Count > 0)) { if (group.Depiction == PointDepiction.Box) { // Draw orientation gizmos PointGizmoProgram.Use(); PointGizmoProgram.SetUniform("worldViewProjMatrix", MainWindow.Options.Viewport.Camera.GetViewProj()); GL.LineWidth(10f); PointGizmoProgram.SetUniform("cubeSize", (float)group.Size * MainWindow.Options.PixelScale.X); group.PointCloud.Draw(); // Draw boxes PointProgram.Use(); PointProgram.SetUniform("worldViewProjMatrix", MainWindow.Options.Viewport.Camera.GetViewProj()); // Draw back faces first, then front, to ensure correct transparency (locally) GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); PointProgram.SetUniform("cubeSize", (float)group.Size * MainWindow.Options.PixelScale.X); group.PointCloud.Draw(); GL.CullFace(CullFaceMode.Back); PointProgram.SetUniform("cubeSize", (float)group.Size * MainWindow.Options.PixelScale.X); group.PointCloud.Draw(); GL.Disable(EnableCap.CullFace); } else if (group.Depiction == PointDepiction.Mesh) { PointModelProgram.Use(); PointModelProgram.SetUniform("modelColor", ColorHelper.ColorToVector(group.Color, true)); PointModelProgram.SetUniform("cameraDirection", Viewport.Camera.GetDirection()); foreach (var point in group.Points) { PointModelProgram.SetUniform("isSelected", point.IsSelected ? 1f : 0f); Vector3 Offset = point.TransformedMatrix.Column2 * (float)group.DepictionMeshOffset; PointModelProgram.SetUniform("worldViewProjMatrix", Matrix4.CreateTranslation(point.Position + Offset) * MainWindow.Options.Viewport.Camera.GetViewProj()); PointModelProgram.SetUniform("rotationMatrix", Matrix3.Transpose(point.TransformedMatrix)); group.DepictionMesh?.Draw(); } } else if (group.Depiction == PointDepiction.LocalSurface) { PointModelProgram.Use(); PointModelProgram.SetUniform("modelColor", ColorHelper.ColorToVector(group.Color, true)); PointModelProgram.SetUniform("cameraDirection", Viewport.Camera.GetDirection()); foreach (var point in group.Points) { PointModelProgram.SetUniform("isSelected", point.IsSelected ? 1f : 0f); PointModelProgram.SetUniform("worldViewProjMatrix", Matrix4.CreateTranslation(point.Position) * MainWindow.Options.Viewport.Camera.GetViewProj()); PointModelProgram.SetUniform("rotationMatrix", Matrix3.Identity); point.DepictionMesh?.Draw(); } // Also draw the orientation stick if (KeyboardHelper.CtrlDown()) { PointGizmoProgram.Use(); PointGizmoProgram.SetUniform("worldViewProjMatrix", MainWindow.Options.Viewport.Camera.GetViewProj()); GL.LineWidth(10f); PointGizmoProgram.SetUniform("cubeSize", (float)group.Size * MainWindow.Options.PixelScale.X); group.PointCloud.Draw(); } } } } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Matrix3 obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
/// <summary> /// Transfers the current value to the GPU /// at the specified uniform location. /// </summary> internal void Set() { if (Value == null) { return; } switch (UniformType) { case ActiveUniformType.Bool: GL.Uniform1(Location, (bool)Value ? 1 : 0); break; case ActiveUniformType.Int: GL.Uniform1(Location, (int)Value); break; case ActiveUniformType.Float: GL.Uniform1(Location, (float)Value); break; case ActiveUniformType.BoolVec2: case ActiveUniformType.IntVec2: case ActiveUniformType.FloatVec2: GL.Uniform2(Location, (Vector2)Value); break; case ActiveUniformType.FloatMat2: { Matrix2 mat = (Matrix2)Value; GL.UniformMatrix2(Location, false, ref mat); } break; case ActiveUniformType.BoolVec3: case ActiveUniformType.IntVec3: case ActiveUniformType.FloatVec3: GL.Uniform3(Location, (Vector3)Value); break; case ActiveUniformType.FloatMat3: { Matrix3 mat = (Matrix3)Value; GL.UniformMatrix3(Location, false, ref mat); } break; case ActiveUniformType.BoolVec4: case ActiveUniformType.IntVec4: case ActiveUniformType.FloatVec4: GL.Uniform4(Location, (Vector4)Value); break; case ActiveUniformType.FloatMat4: { Matrix4 mat = (Matrix4)Value; GL.UniformMatrix4(Location, false, ref mat); } break; case ActiveUniformType.Sampler2D: GL.Uniform1(Location, (int)Value); break; } }
public void Draw(Matrix4 model, Matrix4 view, Matrix4 projection) { if (!Visible) { return; } if (DepthTestFlag) { GL.Enable(EnableCap.DepthTest); } else { GL.Disable(EnableCap.DepthTest); } if (CullFaceFlag) { GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode); } else { GL.Disable(EnableCap.CullFace); } if (BlendingFlag) { GL.Enable(EnableCap.Blend); GL.BlendFuncSeparate(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha, BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha); GL.BlendEquationSeparate(BlendEquationMode.FuncAdd, BlendEquationMode.FuncAdd); } else { GL.Disable(EnableCap.Blend); } if (shader != null) { shader.Use(); if (texture != null) { texture.Bind(); shader.SetSamplerUniform(0, 0); } else { GL.BindTexture(TextureTarget.Texture2D, 0); } // Set up uniforms: Matrix4 mv = model * view; Matrix3 mvIT = new Matrix3(mv); mvIT.Invert(); mvIT.Transpose(); shader.SetUniformMatrix3("mvIT", mvIT); shader.SetUniformMatrix4("modelView", mv); shader.SetUniformMatrix4("projection", projection); shader.SetUniformMatrix4("model", model); shader.SetUniformMatrix4("view", view); foreach (var uniform in uniforms) { uniform.SetUniform(shader); } } vertexBuffer.Bind(shader); if (indexBuffer != null) { indexBuffer.Bind(); GL.DrawElements(PrimitiveType, indexBuffer.Size(), DrawElementsType.UnsignedInt, 0); } else { GL.DrawArrays(PrimitiveType, 0, vertexBuffer.Size); } GL.BindVertexArray(0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); }
public void setUniformMatrix(int location, Matrix3 matrix) { setUniformMatrix(location, matrix, false); }
/// <summary> /// Moves, scales, and/or rotates the current entity given a 3x3 transformation matrix and a translation vector. /// </summary> /// <param name="transformation">Transformation matrix.</param> /// <param name="translation">Translation vector.</param> /// <remarks> /// Non-uniform and zero scaling local to the dimension entity are not supported.<br /> /// The transformation will not be applied if the resulting reference lines are parallel.<br /> /// Matrix3 adopts the convention of using column vectors to represent a transformation matrix. /// </remarks> public override void TransformBy(Matrix3 transformation, Vector3 translation) { Vector3 newNormal = transformation * this.Normal; if (Vector3.Equals(Vector3.Zero, newNormal)) { newNormal = this.Normal; } Matrix3 transOW = MathHelper.ArbitraryAxis(this.Normal); Matrix3 transWO = MathHelper.ArbitraryAxis(newNormal).Transpose(); Vector3 v = transOW * new Vector3(this.StartFirstLine.X, this.StartFirstLine.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; Vector2 newStart1 = new Vector2(v.X, v.Y); double newElevation = v.Z; v = transOW * new Vector3(this.EndFirstLine.X, this.EndFirstLine.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; Vector2 newEnd1 = new Vector2(v.X, v.Y); v = transOW * new Vector3(this.StartSecondLine.X, this.StartSecondLine.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; Vector2 newStart2 = new Vector2(v.X, v.Y); v = transOW * new Vector3(this.EndSecondLine.X, this.EndSecondLine.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; Vector2 newEnd2 = new Vector2(v.X, v.Y); Vector2 dir1 = newEnd1 - newStart1; Vector2 dir2 = newEnd2 - newStart2; if (Vector2.AreParallel(dir1, dir2)) { Debug.Assert(false, "The transformation cannot be applied, the resulting reference lines are parallel."); return; } v = transOW * new Vector3(this.ArcDefinitionPoint.X, this.ArcDefinitionPoint.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; Vector2 newArcDefPoint = new Vector2(v.X, v.Y); if (this.TextPositionManuallySet) { v = transOW * new Vector3(this.textRefPoint.X, this.textRefPoint.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; this.textRefPoint = new Vector2(v.X, v.Y); } v = transOW * new Vector3(this.defPoint.X, this.defPoint.Y, this.Elevation); v = transformation * v + translation; v = transWO * v; this.defPoint = new Vector2(v.X, v.Y); this.StartFirstLine = newStart1; this.EndFirstLine = newEnd1; this.StartSecondLine = newStart2; this.EndSecondLine = newEnd2; this.ArcDefinitionPoint = newArcDefPoint; this.Elevation = newElevation; this.Normal = newNormal; this.SetDimensionLinePosition(newArcDefPoint); }
private static EntityObject ProcessCircle(Circle circle, Matrix3 trans, Vector3 pos) { circle.Center = trans * circle.Center + pos; circle.Normal = trans * circle.Normal; return(circle); }
private void tickTimer_Tick(object sender, EventArgs e) { Vector3 moveDir = Vector3.Zero; float deltaTime = 0.016f; bool invalidate = false; float moveSpeed = 25; float shiftMultiplier = 3; float nonShiftMultiplier = 0.5f; if (wKey) { moveDir.Y += (ModifierKeys == Keys.Shift ? shiftMultiplier : nonShiftMultiplier) * deltaTime * moveSpeed; invalidate = true; } if (sKey) { moveDir.Y -= (ModifierKeys == Keys.Shift ? shiftMultiplier : nonShiftMultiplier) * deltaTime * moveSpeed; invalidate = true; } if (aKey) { moveDir.X -= (ModifierKeys == Keys.Shift ? shiftMultiplier : nonShiftMultiplier) * deltaTime * moveSpeed; invalidate = true; } if (dKey) { moveDir.X += (ModifierKeys == Keys.Shift ? shiftMultiplier : nonShiftMultiplier) * deltaTime * moveSpeed; invalidate = true; } if (eKey) { moveDir.Z += (ModifierKeys == Keys.Shift ? shiftMultiplier : nonShiftMultiplier) * deltaTime * moveSpeed; invalidate = true; } if (qKey) { moveDir.Z -= (ModifierKeys == Keys.Shift ? shiftMultiplier : nonShiftMultiplier) * deltaTime * moveSpeed; invalidate = true; } if (rMouse) { yaw -= (Cursor.Position.X - lastMouseX) * cSpeed * 0.016f; pitch -= (Cursor.Position.Y - lastMouseY) * cSpeed * 0.016f; pitch = MathHelper.Clamp(pitch, MathHelper.DegreesToRadians(-89.9f), MathHelper.DegreesToRadians(89.9f)); invalidate = true; } Matrix3 rot = Matrix3.CreateRotationX(pitch) * Matrix3.CreateRotationZ(yaw); Vector3 forward = Vector3.Transform(Vector3.UnitY, rot); cPosition += Vector3.Transform(moveDir, rot); cTarget = cPosition + forward; lastMouseX = Cursor.Position.X; lastMouseY = Cursor.Position.Y; if (invalidate) { glControl1.Invalidate(); } }
private static Ellipse ProcessEllipse(Ellipse ellipse, Matrix3 trans, Vector3 pos) { ellipse.Center = trans * ellipse.Center + pos; ellipse.Normal = trans * ellipse.Normal; return(ellipse); }
/// <summary> /// Populates <see cref="Vertices"/> and <see cref="Normals"/>. /// </summary> protected virtual void UpdateVertices() { Vertices.Clear(); Normals.Clear(); float cornerRadius = CornerRadius; // Sides RectangleF rect = DrawRectangle; Vector2[] corners = { rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft }; const int amount_side_steps = 2; for (int i = 0; i < 4; ++i) { Vector2 a = corners[i]; Vector2 b = corners[(i + 1) % 4]; Vector2 diff = b - a; float length = diff.Length; Vector2 dir = diff / length; float usableLength = Math.Max(length - 2 * cornerRadius, 0); Vector2 normal = (b - a).PerpendicularRight.Normalized(); for (int j = 0; j < amount_side_steps; ++j) { Vertices.Add(a + dir * (cornerRadius + j * usableLength / (amount_side_steps - 1))); Normals.Add(normal); } } const int amount_corner_steps = 10; if (cornerRadius > 0) { // Rounded corners Vector2[] offsets = { new Vector2(cornerRadius, cornerRadius), new Vector2(-cornerRadius, cornerRadius), new Vector2(-cornerRadius, -cornerRadius), new Vector2(cornerRadius, -cornerRadius), }; for (int i = 0; i < 4; ++i) { Vector2 a = corners[i]; float startTheta = (i - 1) * (float)Math.PI / 2; for (int j = 0; j < amount_corner_steps; ++j) { float theta = startTheta + j * (float)Math.PI / (2 * (amount_corner_steps - 1)); Vector2 normal = new Vector2((float)Math.Sin(theta), (float)Math.Cos(theta)); Vertices.Add(a + offsets[i] + normal * cornerRadius); Normals.Add(normal); } } } // To simulation space Matrix3 mat = DrawInfo.Matrix * ScreenToSimulationSpace; Matrix3 normMat = mat.Inverted(); normMat.Transpose(); // Remove translation normMat.M31 = normMat.M32 = normMat.M13 = normMat.M23 = 0; Vector2 translation = Vector2Extensions.Transform(Vector2.Zero, normMat); for (int i = 0; i < Vertices.Count; ++i) { Vertices[i] = Vector2Extensions.Transform(Vertices[i], mat); Normals[i] = (Vector2Extensions.Transform(Normals[i], normMat) - translation).Normalized(); } }
/// <param name="x">Position on the x axis</param> /// <param name="y">Position on the y axis</param> /// <param name="rayColor">The color of the symbol that will appear when drawn to raylib</param> /// <param name="icon">The symbol that will appear when drawn</param> /// <param name="color">The color of the symbol that will appear when drawn to the console</param> public Actor(float x, float y, Color rayColor, char icon = ' ', ConsoleColor color = ConsoleColor.White) : this(x, y, icon, color) { _localTransform = new Matrix3(); _rayColor = rayColor; }
public void Load() { this.VertexData = new float[this.Spokes * this.RadiusResolution * 6 * DATA_PER_VERTEX]; this.TextureData = new byte[this.Spokes * this.RadiusResolution * 4]; int DataIndex = 0; void AddPoint(Vector3 point, int spoke, int seg, bool isStart, Vector3 normal) { this.VertexData[DataIndex++] = point.X; this.VertexData[DataIndex++] = point.Y; this.VertexData[DataIndex++] = point.Z; this.VertexData[DataIndex++] = ((float)seg / this.RadiusResolution) + (0.5F / this.RadiusResolution); this.VertexData[DataIndex++] = ((float)spoke / this.Spokes) + (0.5F / this.Spokes); this.VertexData[DataIndex++] = isStart ? 0F : 1F; this.VertexData[DataIndex++] = normal.X; this.VertexData[DataIndex++] = normal.Y; this.VertexData[DataIndex++] = normal.Z; } GL.ClearColor(0.0F, 0.0F, 0.0F, 1.0F); GL.Enable(EnableCap.DepthTest); this.Shader = new Shader("Radar.vert", "Radar.frag"); this.Shader.Use(); GL.BindTexture(TextureTarget.Texture2D, 0); this.LocationTexture = GL.GenTexture(); GL.Uniform1(this.Shader.GetUniformLocation("tex"), 0); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, this.LocationTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, this.RadiusResolution, this.Spokes, 0, PixelFormat.Rgba, PixelType.UnsignedByte, this.TextureData); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToBorder); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToBorder); this.Projection = Matrix4.CreatePerspectiveFieldOfView(MathF.PI / 2, 1, 0.01F, 10F); this.LocationProjection = this.Shader.GetUniformLocation("projection"); GL.UniformMatrix4(this.LocationProjection, true, ref this.Projection); this.LocationFrontOffset = this.Shader.GetUniformLocation("frontOffset"); GL.Uniform1(this.Shader.GetUniformLocation("falloffAfter"), this.FalloffAfter); // only set once this.VertexBufferHandle = GL.GenBuffer(); this.VertexArrayHandle = GL.GenVertexArray(); Matrix3 ViewRotation = this.Use3DView ? Matrix3.CreateRotationX(MathF.PI * -0.3F) : Matrix3.Identity; Vector3 ViewOffset = this.Use3DView ? ((Vector3.UnitZ * -1.3F) + (Vector3.UnitY * 0.3F)) : (Vector3.UnitZ * -1); Vector3 NormalVec = new(0, 2, 0); // Generate geometry for (int Spoke = 0; Spoke < this.Spokes; Spoke++) { for (int Seg = 0; Seg < RadiusResolution; Seg++) { float RotStart = MathF.PI * 2 * Spoke / this.Spokes; float RotEnd = MathF.PI * 2 * (Spoke + 1) / this.Spokes; float RadIn = ((float)Seg / RadiusResolution * 0.9F) + 0.1F; float RadOut = ((float)(Seg + 1) / RadiusResolution * 0.9F) + 0.1F; float StartX = MathF.Cos(RotStart); float StartY = MathF.Sin(RotStart); float EndX = MathF.Cos(RotEnd); float EndY = MathF.Sin(RotEnd); const float Z = 0F; // RadIn/RadOut is in range [0..1] premade for linear interpolation Vector3 InnerNormal = NormalVec * RadIn; Vector3 OuterNormal = NormalVec * RadOut; AddPoint((new Vector3(StartX * RadIn, StartY * RadIn, Z) * ViewRotation) + ViewOffset, Spoke, Seg, true, InnerNormal); // In bottom AddPoint((new Vector3(StartX * RadOut, StartY * RadOut, Z) * ViewRotation) + ViewOffset, Spoke, Seg, true, OuterNormal); // Out bottom AddPoint((new Vector3(EndX * RadOut, EndY * RadOut, Z) * ViewRotation) + ViewOffset, Spoke, Seg, false, OuterNormal); // Out top AddPoint((new Vector3(StartX * RadIn, StartY * RadIn, Z) * ViewRotation) + ViewOffset, Spoke, Seg, true, InnerNormal); // In bottom AddPoint((new Vector3(EndX * RadOut, EndY * RadOut, Z) * ViewRotation) + ViewOffset, Spoke, Seg, false, OuterNormal); // Out top AddPoint((new Vector3(EndX * RadIn, EndY * RadIn, Z) * ViewRotation) + ViewOffset, Spoke, Seg, false, InnerNormal); // In top } } GL.BindVertexArray(this.VertexArrayHandle); GL.BindBuffer(BufferTarget.ArrayBuffer, this.VertexBufferHandle); GL.BufferData(BufferTarget.ArrayBuffer, VertexData.Length * sizeof(float), VertexData, BufferUsageHint.DynamicDraw); GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, DATA_PER_VERTEX * sizeof(float), 0); GL.EnableVertexAttribArray(0); GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, DATA_PER_VERTEX * sizeof(float), 3 * sizeof(float)); GL.EnableVertexAttribArray(1); GL.VertexAttribPointer(2, 1, VertexAttribPointerType.Float, false, DATA_PER_VERTEX * sizeof(float), 5 * sizeof(float)); GL.EnableVertexAttribArray(2); GL.VertexAttribPointer(3, 3, VertexAttribPointerType.Float, false, DATA_PER_VERTEX * sizeof(float), 6 * sizeof(float)); GL.EnableVertexAttribArray(3); this.SetupDone = true; }
public void SingularValueComposition(Matrix3 rkL, Vector3 rkS, Matrix3 rkR) { OgrePINVOKE.Matrix3_SingularValueComposition(swigCPtr, Matrix3.getCPtr(rkL), Vector3.getCPtr(rkS), Matrix3.getCPtr(rkR)); if (OgrePINVOKE.SWIGPendingException.Pending) { throw OgrePINVOKE.SWIGPendingException.Retrieve(); } }
/// <summary> /// Moves, scales, and/or rotates the current entity given a 3x3 transformation matrix and a translation vector. /// </summary> /// <param name="transformation">Transformation matrix.</param> /// <param name="translation">Translation vector.</param> /// <remarks>Matrix3 adopts the convention of using column vectors to represent a transformation matrix.</remarks> public override void TransformBy(Matrix3 transformation, Vector3 translation) { bool mirrorShape; Vector3 newPosition = transformation * this.Position + translation; Vector3 newNormal = transformation * this.Normal; if (Vector3.Equals(Vector3.Zero, newNormal)) { newNormal = this.Normal; } Matrix3 transOW = MathHelper.ArbitraryAxis(this.Normal); Matrix3 transWO = MathHelper.ArbitraryAxis(newNormal); transWO = transWO.Transpose(); List <Vector2> uv = MathHelper.Transform( new[] { Vector2.UnitX *this.WidthFactor *this.Size, new Vector2(this.Size * Math.Tan(this.ObliqueAngle * MathHelper.DegToRad), this.Size) }, this.Rotation * MathHelper.DegToRad, CoordinateSystem.Object, CoordinateSystem.World); Vector3 v; v = transOW * new Vector3(uv[0].X, uv[0].Y, 0.0); v = transformation * v; v = transWO * v; Vector2 newUvector = new Vector2(v.X, v.Y); v = transOW * new Vector3(uv[1].X, uv[1].Y, 0.0); v = transformation * v; v = transWO * v; Vector2 newVvector = new Vector2(v.X, v.Y); double newRotation = Vector2.Angle(newUvector) * MathHelper.RadToDeg; double newObliqueAngle = Vector2.Angle(newVvector) * MathHelper.RadToDeg; if (Vector2.CrossProduct(newUvector, newVvector) < 0) { newRotation += 180; newObliqueAngle = 270 - (newRotation - newObliqueAngle); if (newObliqueAngle >= 360) { newObliqueAngle -= 360; } mirrorShape = true; } else { newObliqueAngle = 90 + (newRotation - newObliqueAngle); mirrorShape = false; } // the oblique angle is defined between -85 and 85 degrees if (newObliqueAngle > 180) { newObliqueAngle = 180 - newObliqueAngle; } if (newObliqueAngle < -85) { newObliqueAngle = -85; } else if (newObliqueAngle > 85) { newObliqueAngle = 85; } // the height must be greater than zero, the cos is always positive between -85 and 85 double newHeight = newVvector.Modulus() * Math.Cos(newObliqueAngle * MathHelper.DegToRad); newHeight = MathHelper.IsZero(newHeight) ? MathHelper.Epsilon : newHeight; // the width factor is defined between 0.01 and 100 double newWidthFactor = newUvector.Modulus() / newHeight; if (newWidthFactor < 0.01) { newWidthFactor = 0.01; } else if (newWidthFactor > 100) { newWidthFactor = 100; } this.Position = newPosition; this.Normal = newNormal; this.Rotation = newRotation; this.Size = newHeight; this.WidthFactor = mirrorShape ? -newWidthFactor : newWidthFactor; this.ObliqueAngle = mirrorShape ? -newObliqueAngle : newObliqueAngle; }
public DrawInfo(Matrix3?matrix = null, Matrix3?matrixInverse = null) { Matrix = matrix ?? Matrix3.Identity; MatrixInverse = matrixInverse ?? Matrix3.Identity; }
public void setUniformMatrix(int location, Matrix3 matrix, bool transpose) { checkManaged(); GL.UniformMatrix3(location, transpose, ref matrix); }
public void Rotate(float radians) { _rotation *= Matrix3.CreateRotation(radians); }
public void SetTranslation(Vector2 position) { _translation = Matrix3.CreateTranslation(position); }
public static void TensorProduct(Vector3 rkU, Vector3 rkV, Matrix3 rkProduct) { OgrePINVOKE.Matrix3_TensorProduct(Vector3.getCPtr(rkU), Vector3.getCPtr(rkV), Matrix3.getCPtr(rkProduct)); if (OgrePINVOKE.SWIGPendingException.Pending) { throw OgrePINVOKE.SWIGPendingException.Retrieve(); } }
public void SetRotation(float radians) { _rotation = Matrix3.CreateRotation(radians); }
private void DrawLightsAndFov(Box2 worldBounds, IEye eye) { if (!_lightManager.Enabled) { return; } UpdateOcclusionGeometry(eye.Position.MapId); DrawFov(worldBounds, eye); var map = _eyeManager.CurrentMap; GL.BindFramebuffer(FramebufferTarget.Framebuffer, LightRenderTarget.ObjectHandle.Handle); var converted = Color.FromSrgb(new Color(0.1f, 0.1f, 0.1f)); GL.ClearColor(converted.R, converted.G, converted.B, 1); GL.Clear(ClearBufferMask.ColorBufferBit); var(lightW, lightH) = GetLightMapSize(); GL.Viewport(0, 0, lightW, lightH); _lightShader.Use(); GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.One); var lastRange = float.NaN; var lastPower = float.NaN; var lastColor = new Color(float.NaN, float.NaN, float.NaN, float.NaN); Texture lastMask = null; foreach (var component in _componentManager.GetAllComponents <PointLightComponent>()) { if (!component.Enabled || component.Owner.Transform.MapID != map) { continue; } var transform = component.Owner.Transform; var lightPos = transform.WorldMatrix.Transform(component.Offset); var lightBounds = Box2.CenteredAround(lightPos, Vector2.One * component.Radius * 2); if (!lightBounds.Intersects(worldBounds)) { continue; } Texture mask = null; var rotation = Angle.Zero; if (component.Mask != null) { mask = component.Mask; rotation = component.Rotation; if (component.MaskAutoRotate) { rotation += transform.WorldRotation; } } var maskTexture = mask ?? Texture.White; if (lastMask != maskTexture) { var maskHandle = _loadedTextures[((ClydeTexture)maskTexture).TextureId].OpenGLObject; GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, maskHandle.Handle); lastMask = maskTexture; _lightShader.SetUniformTexture("lightMask", TextureUnit.Texture0); } if (!FloatMath.CloseTo(lastRange, component.Radius)) { lastRange = component.Radius; _lightShader.SetUniform("lightRange", lastRange); } if (!FloatMath.CloseTo(lastPower, component.Energy)) { lastPower = component.Energy; _lightShader.SetUniform("lightPower", lastPower); } if (lastColor != component.Color) { lastColor = component.Color; _lightShader.SetUniform("lightColor", lastColor); } _lightShader.SetUniform("lightCenter", lightPos); var offset = new Vector2(component.Radius, component.Radius); Matrix3 matrix; if (mask == null) { matrix = Matrix3.Identity; } else { // Only apply rotation if a mask is said, because else it doesn't matter. matrix = Matrix3.CreateRotation(rotation); } (matrix.R0C2, matrix.R1C2) = lightPos; _drawQuad(-offset, offset, ref matrix, _lightShader); } GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); GL.Viewport(0, 0, ScreenSize.X, ScreenSize.Y); _lightingReady = true; }
public Matrix3 Metric(Coords3D <SphericalCoords> coords) => Matrix3.DiagMatrix(1, Math.Pow(coords.FirstComponent * Math.Sin(coords.ThirdComponent), 2), Math.Pow(coords.FirstComponent, 2));
public static void SetUniform(int shader, ActiveUniformType type, int location, object value) { if (shader == currentShader) { FlushCurrentBatch(); } switch (type) { case ActiveUniformType.Bool: GL.Uniform1(location, (bool)value ? 1 : 0); break; case ActiveUniformType.Int: GL.Uniform1(location, (int)value); break; case ActiveUniformType.Float: GL.Uniform1(location, (float)value); break; case ActiveUniformType.BoolVec2: case ActiveUniformType.IntVec2: case ActiveUniformType.FloatVec2: GL.Uniform2(location, (Vector2)value); break; case ActiveUniformType.FloatMat2: { Matrix2 mat = (Matrix2)value; GL.UniformMatrix2(location, false, ref mat); break; } case ActiveUniformType.BoolVec3: case ActiveUniformType.IntVec3: case ActiveUniformType.FloatVec3: GL.Uniform3(location, (Vector3)value); break; case ActiveUniformType.FloatMat3: { Matrix3 mat = (Matrix3)value; GL.UniformMatrix3(location, false, ref mat); break; } case ActiveUniformType.BoolVec4: case ActiveUniformType.IntVec4: case ActiveUniformType.FloatVec4: GL.Uniform4(location, (Vector4)value); break; case ActiveUniformType.FloatMat4: { Matrix4 mat = (Matrix4)value; GL.UniformMatrix4(location, false, ref mat); break; } case ActiveUniformType.Sampler2D: GL.Uniform1(location, (int)value); break; } }
/// <summary> /// Assigns a blittable value to the specified variable. All values are copied and converted into /// a shared internal format. /// /// Supported base types are <see cref="float"/>, <see cref="Vector2"/>, <see cref="Vector3"/>, /// <see cref="Vector4"/>, <see cref="Matrix3"/>, <see cref="Matrix4"/>, <see cref="int"/>, /// <see cref="Point2"/> and <see cref="bool"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="value"></param> public void Set <T>(string name, T value) where T : struct { if (string.IsNullOrEmpty(name)) { ThrowInvalidName(); } float[] rawData; if (typeof(T) == typeof(float)) { float typedValue = (float)(object)value; this.EnsureUniformData(name, 1, out rawData); rawData[0] = typedValue; } else if (typeof(T) == typeof(Vector2)) { Vector2 typedValue = (Vector2)(object)value; this.EnsureUniformData(name, 2, out rawData); rawData[0] = typedValue.X; rawData[1] = typedValue.Y; } else if (typeof(T) == typeof(Vector3)) { Vector3 typedValue = (Vector3)(object)value; this.EnsureUniformData(name, 3, out rawData); rawData[0] = typedValue.X; rawData[1] = typedValue.Y; rawData[2] = typedValue.Z; } else if (typeof(T) == typeof(Vector4)) { Vector4 typedValue = (Vector4)(object)value; this.EnsureUniformData(name, 4, out rawData); rawData[0] = typedValue.X; rawData[1] = typedValue.Y; rawData[2] = typedValue.Z; rawData[3] = typedValue.W; } else if (typeof(T) == typeof(Matrix3)) { Matrix3 typedValue = (Matrix3)(object)value; this.EnsureUniformData(name, 9, out rawData); rawData[0] = typedValue.Row0.X; rawData[1] = typedValue.Row0.Y; rawData[2] = typedValue.Row0.Z; rawData[3] = typedValue.Row1.X; rawData[4] = typedValue.Row1.Y; rawData[5] = typedValue.Row1.Z; rawData[6] = typedValue.Row2.X; rawData[7] = typedValue.Row2.Y; rawData[8] = typedValue.Row2.Z; } else if (typeof(T) == typeof(Matrix4)) { Matrix4 typedValue = (Matrix4)(object)value; this.EnsureUniformData(name, 16, out rawData); rawData[0] = typedValue.Row0.X; rawData[1] = typedValue.Row0.Y; rawData[2] = typedValue.Row0.Z; rawData[3] = typedValue.Row0.W; rawData[4] = typedValue.Row1.X; rawData[5] = typedValue.Row1.Y; rawData[6] = typedValue.Row1.Z; rawData[7] = typedValue.Row1.W; rawData[8] = typedValue.Row2.X; rawData[9] = typedValue.Row2.Y; rawData[10] = typedValue.Row2.Z; rawData[11] = typedValue.Row2.W; rawData[12] = typedValue.Row3.X; rawData[13] = typedValue.Row3.Y; rawData[14] = typedValue.Row3.Z; rawData[15] = typedValue.Row3.W; } else if (typeof(T) == typeof(ColorRgba)) { ColorRgba typedValue = (ColorRgba)(object)value; this.EnsureUniformData(name, 4, out rawData); rawData[0] = (float)typedValue.R / 255.0f; rawData[1] = (float)typedValue.G / 255.0f; rawData[2] = (float)typedValue.B / 255.0f; rawData[3] = (float)typedValue.A / 255.0f; } else if (typeof(T) == typeof(ColorHsva)) { ColorHsva typedValue = (ColorHsva)(object)value; this.EnsureUniformData(name, 4, out rawData); rawData[0] = typedValue.H; rawData[1] = typedValue.S; rawData[2] = typedValue.V; rawData[3] = typedValue.A; } else if (typeof(T) == typeof(int)) { int typedValue = (int)(object)value; this.EnsureUniformData(name, 1, out rawData); rawData[0] = typedValue; } else if (typeof(T) == typeof(Point2)) { Point2 typedValue = (Point2)(object)value; this.EnsureUniformData(name, 2, out rawData); rawData[0] = typedValue.X; rawData[1] = typedValue.Y; } else if (typeof(T) == typeof(bool)) { bool typedValue = (bool)(object)value; this.EnsureUniformData(name, 1, out rawData); rawData[0] = typedValue ? 1.0f : 0.0f; } else { ThrowUnsupportedValueType <T>(); } this.UpdateHash(); }
public static ShaderDefinition.mat4 ToMatrix3F(this Matrix3 v) { _storage.F3X3 = v; return(null); }
/// <summary> /// Retrieves a copy of the values that are assigned the specified variable. If the internally /// stored type does not match the specified type, it will be converted before returning. /// /// Supported base types are <see cref="float"/>, <see cref="Vector2"/>, <see cref="Vector3"/>, /// <see cref="Vector4"/>, <see cref="Matrix3"/>, <see cref="Matrix4"/>, <see cref="int"/>, /// <see cref="Point2"/> and <see cref="bool"/>. /// </summary> public bool TryGet <T>(string name, out T[] value) where T : struct { value = null; if (string.IsNullOrEmpty(name)) { return(false); } float[] rawData; if (!this.TryGetInternal(name, out rawData)) { return(false); } if (typeof(T) == typeof(float)) { if (rawData.Length < 1) { return(false); } float[] result = new float[rawData.Length / 1]; for (int i = 0; i < result.Length; i++) { result[i] = rawData[i]; } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(Vector2)) { if (rawData.Length < 2) { return(false); } Vector2[] result = new Vector2[rawData.Length / 2]; for (int i = 0; i < result.Length; i++) { result[i].X = rawData[i * 2 + 0]; result[i].Y = rawData[i * 2 + 1]; } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(Vector3)) { if (rawData.Length < 3) { return(false); } Vector3[] result = new Vector3[rawData.Length / 3]; for (int i = 0; i < result.Length; i++) { result[i].X = rawData[i * 3 + 0]; result[i].Y = rawData[i * 3 + 1]; result[i].Z = rawData[i * 3 + 2]; } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(Vector4)) { if (rawData.Length < 4) { return(false); } Vector4[] result = new Vector4[rawData.Length / 4]; for (int i = 0; i < result.Length; i++) { result[i].X = rawData[i * 4 + 0]; result[i].Y = rawData[i * 4 + 1]; result[i].Z = rawData[i * 4 + 2]; result[i].W = rawData[i * 4 + 3]; } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(Matrix3)) { if (rawData.Length < 9) { return(false); } Matrix3[] result = new Matrix3[rawData.Length / 9]; for (int i = 0; i < result.Length; i++) { result[i].Row0.X = rawData[i * 9 + 0]; result[i].Row0.Y = rawData[i * 9 + 1]; result[i].Row0.Z = rawData[i * 9 + 2]; result[i].Row1.X = rawData[i * 9 + 3]; result[i].Row1.Y = rawData[i * 9 + 4]; result[i].Row1.Z = rawData[i * 9 + 5]; result[i].Row2.X = rawData[i * 9 + 6]; result[i].Row2.Y = rawData[i * 9 + 7]; result[i].Row2.Z = rawData[i * 9 + 8]; } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(Matrix4)) { if (rawData.Length < 16) { return(false); } Matrix4[] result = new Matrix4[rawData.Length / 16]; for (int i = 0; i < result.Length; i++) { result[i].Row0.X = rawData[i * 16 + 0]; result[i].Row0.Y = rawData[i * 16 + 1]; result[i].Row0.Z = rawData[i * 16 + 2]; result[i].Row0.W = rawData[i * 16 + 3]; result[i].Row1.X = rawData[i * 16 + 4]; result[i].Row1.Y = rawData[i * 16 + 5]; result[i].Row1.Z = rawData[i * 16 + 6]; result[i].Row1.W = rawData[i * 16 + 7]; result[i].Row2.X = rawData[i * 16 + 8]; result[i].Row2.Y = rawData[i * 16 + 9]; result[i].Row2.Z = rawData[i * 16 + 10]; result[i].Row2.W = rawData[i * 16 + 11]; result[i].Row3.X = rawData[i * 16 + 12]; result[i].Row3.Y = rawData[i * 16 + 13]; result[i].Row3.Z = rawData[i * 16 + 14]; result[i].Row3.W = rawData[i * 16 + 15]; } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(ColorRgba)) { if (rawData.Length < 4) { return(false); } ColorRgba[] result = new ColorRgba[rawData.Length / 4]; for (int i = 0; i < result.Length; i++) { result[i] = new ColorRgba( rawData[i * 4 + 0], rawData[i * 4 + 1], rawData[i * 4 + 2], rawData[i * 4 + 3]); } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(ColorHsva)) { if (rawData.Length < 4) { return(false); } ColorHsva[] result = new ColorHsva[rawData.Length / 4]; for (int i = 0; i < result.Length; i++) { result[i] = new ColorHsva( rawData[i * 4 + 0], rawData[i * 4 + 1], rawData[i * 4 + 2], rawData[i * 4 + 3]); } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(int)) { if (rawData.Length < 1) { return(false); } int[] result = new int[rawData.Length / 1]; for (int i = 0; i < result.Length; i++) { result[i] = MathF.RoundToInt(rawData[i]); } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(Point2)) { if (rawData.Length < 2) { return(false); } Point2[] result = new Point2[rawData.Length / 2]; for (int i = 0; i < result.Length; i++) { result[i].X = MathF.RoundToInt(rawData[i * 2 + 0]); result[i].Y = MathF.RoundToInt(rawData[i * 2 + 1]); } value = (T[])(object)result; return(true); } else if (typeof(T) == typeof(bool)) { if (rawData.Length < 1) { return(false); } bool[] result = new bool[rawData.Length / 1]; for (int i = 0; i < result.Length; i++) { result[i] = rawData[i] != 0.0f; } value = (T[])(object)result; return(true); } else { ThrowUnsupportedValueType <T>(); return(false); } }
public TextBlobMesh(TextBlob textBlob, float scale, Matrix3 matrix) { this.textBlob = textBlob; this.scale = scale; this.matrix = matrix; }
public static extern void GeomCopyRotation(IntPtr geom, out Matrix3 R);
/// <summary> /// Moves, scales, and/or rotates the current entity given a 3x3 transformation matrix and a translation vector. /// </summary> /// <param name="transformation">Transformation matrix.</param> /// <param name="translation">Translation vector.</param> /// <remarks> /// Non-uniform scaling is not supported, it would require to decompose each line into independent Text entities. /// When the current MText entity does not belong to a DXF document, the text will be mirrored by default when a symmetry is performed; /// otherwise, the drawing variable MirrText will be used. /// </remarks> public override void TransformBy(Matrix3 transformation, Vector3 translation) { bool mirrText = this.Owner == null ? DefaultMirrText : this.Owner.Record.Owner.Owner.DrawingVariables.MirrText; Vector3 newPosition = transformation * this.Position + translation; Vector3 newNormal = transformation * this.Normal; if (Vector3.Equals(Vector3.Zero, newNormal)) { newNormal = this.Normal; } Matrix3 transOW = MathHelper.ArbitraryAxis(this.Normal); Matrix3 transWO = MathHelper.ArbitraryAxis(newNormal); transWO = transWO.Transpose(); List <Vector2> uv = MathHelper.Transform(new[] { Vector2.UnitX, Vector2.UnitY }, this.Rotation * MathHelper.DegToRad, CoordinateSystem.Object, CoordinateSystem.World); Vector3 v; v = transOW * new Vector3(uv[0].X, uv[0].Y, 0.0); v = transformation * v; v = transWO * v; Vector2 newUvector = new Vector2(v.X, v.Y); // the MText entity does not support non-uniform scaling double scale = newUvector.Modulus(); v = transOW * new Vector3(uv[1].X, uv[1].Y, 0.0); v = transformation * v; v = transWO * v; Vector2 newVvector = new Vector2(v.X, v.Y); double newRotation = Vector2.Angle(newUvector) * MathHelper.RadToDeg; if (mirrText) { if (Vector2.CrossProduct(newUvector, newVvector) < 0.0) { newRotation += 180; newNormal = -newNormal; } } else { if (Vector2.CrossProduct(newUvector, newVvector) < 0.0) { if (Vector2.DotProduct(newUvector, uv[0]) < 0.0) { newRotation += 180; switch (this.AttachmentPoint) { case MTextAttachmentPoint.TopLeft: this.AttachmentPoint = MTextAttachmentPoint.TopRight; break; case MTextAttachmentPoint.TopRight: this.AttachmentPoint = MTextAttachmentPoint.TopLeft; break; case MTextAttachmentPoint.MiddleLeft: this.AttachmentPoint = MTextAttachmentPoint.MiddleRight; break; case MTextAttachmentPoint.MiddleRight: this.AttachmentPoint = MTextAttachmentPoint.MiddleLeft; break; case MTextAttachmentPoint.BottomLeft: this.AttachmentPoint = MTextAttachmentPoint.BottomRight; break; case MTextAttachmentPoint.BottomRight: this.AttachmentPoint = MTextAttachmentPoint.BottomLeft; break; } } else { switch (this.AttachmentPoint) { case MTextAttachmentPoint.TopLeft: this.AttachmentPoint = MTextAttachmentPoint.BottomLeft; break; case MTextAttachmentPoint.TopCenter: this.attachmentPoint = MTextAttachmentPoint.BottomCenter; break; case MTextAttachmentPoint.TopRight: this.AttachmentPoint = MTextAttachmentPoint.BottomRight; break; case MTextAttachmentPoint.BottomLeft: this.AttachmentPoint = MTextAttachmentPoint.TopLeft; break; case MTextAttachmentPoint.BottomCenter: this.attachmentPoint = MTextAttachmentPoint.TopCenter; break; case MTextAttachmentPoint.BottomRight: this.AttachmentPoint = MTextAttachmentPoint.TopRight; break; } } } } double newHeight = this.Height * scale; newHeight = MathHelper.IsZero(newHeight) ? MathHelper.Epsilon : newHeight; this.Position = newPosition; this.Normal = newNormal; this.Rotation = newRotation; this.Height = newHeight; this.RectangleWidth *= scale; }