private unsafe uint AddDetector(string detectorName, string dummyName, MyModelDummy dummyData) { List <Matrix> list; if (!base.m_detectors.TryGetValue(detectorName, out list)) { list = new List <Matrix>(); base.m_detectors[detectorName] = list; } Matrix matrix = dummyData.Matrix; if (base.Entity is MyCubeBlock) { float gridScale = (base.Entity as MyCubeBlock).CubeGrid.GridScale; Matrix *matrixPtr1 = (Matrix *)ref matrix; matrixPtr1.Translation *= gridScale; Matrix.Rescale(ref matrix, gridScale); } list.Add(Matrix.Invert(matrix)); uint count = (uint)this.m_detectorInteractiveObjects.Count; IMyUseObject useObject = this.CreateInteractiveObject(detectorName, dummyName, dummyData, count); if (useObject != null) { this.m_detectorInteractiveObjects.Add(count, new DetectorData(useObject, matrix, detectorName)); this.m_detectorShapeKeys[detectorName] = count; } return(count); }
public void Multiply(Matrix *m) { Matrix m2 = this; float *s1 = (float *)m, s2 = (float *)&m2; fixed(float *dPtr = _values) { int index = 0; float val; for (int b = 0; b < 16; b += 4) { for (int a = 0; a < 4; a++) { val = 0.0f; for (int x = b, y = a; y < 16; y += 4) { val += s1[x++] * s2[y]; } dPtr[index++] = val; } } } }
static void TransposeCopy(Matrix *src, Matrix *dst) { dst->M11 = src->M11; dst->M21 = src->M12; dst->M31 = src->M13; dst->M41 = src->M14; dst->M12 = src->M21; dst->M22 = src->M22; dst->M32 = src->M23; dst->M42 = src->M24; dst->M13 = src->M31; dst->M23 = src->M32; dst->M33 = src->M33; dst->M43 = src->M34; dst->M14 = src->M41; dst->M24 = src->M42; dst->M34 = src->M43; dst->M44 = src->M44; }
internal unsafe static void UpdateAlphamaskViewsConstants() { System.Diagnostics.Debug.Assert(s_viewVectorData.Length == 181, "Only supported scheme of views for now"); Matrix *viewVectors = stackalloc Matrix[s_viewVectorData.Length]; for (int i = 0; i < s_viewVectorData.Length; i++) { Matrix mm = Matrix.Identity; string[] sp = s_viewVectorData[i].Split(','); mm.M11 = Convert.ToSingle(sp[0], CultureInfo.InvariantCulture); mm.M12 = Convert.ToSingle(sp[1], CultureInfo.InvariantCulture); mm.M13 = Convert.ToSingle(sp[2], CultureInfo.InvariantCulture); mm.M21 = Convert.ToSingle(sp[3], CultureInfo.InvariantCulture); mm.M22 = Convert.ToSingle(sp[4], CultureInfo.InvariantCulture); mm.M23 = Convert.ToSingle(sp[5], CultureInfo.InvariantCulture); mm.M31 = Convert.ToSingle(sp[6], CultureInfo.InvariantCulture); mm.M32 = Convert.ToSingle(sp[7], CultureInfo.InvariantCulture); mm.M33 = Convert.ToSingle(sp[8], CultureInfo.InvariantCulture); mm = Matrix.Normalize(mm); mm = mm * Matrix.CreateRotationX(MathHelper.PiOver2); mm.Up = -mm.Up; viewVectors[i] = mm; } var mapping = MyMapping.MapDiscard(MyCommon.AlphamaskViewsConstants); for (int vectorIndex = 0; vectorIndex < s_viewVectorData.Length; ++vectorIndex) { mapping.WriteAndPosition(ref viewVectors[vectorIndex]); } mapping.Unmap(); }
internal static unsafe void ConvertToD3DMATRIX( /* in */ Matrix *matrix, /* out */ D3DMATRIX *d3dMatrix ) { *d3dMatrix = D3DMATRIXIdentity; float * pD3DMatrix = (float *)d3dMatrix; double *pMatrix = (double *)matrix; // m11 = m11 pD3DMatrix[0] = (float)pMatrix[0]; // m12 = m12 pD3DMatrix[1] = (float)pMatrix[1]; // m21 = m21 pD3DMatrix[4] = (float)pMatrix[2]; // m22 = m22 pD3DMatrix[5] = (float)pMatrix[3]; // m41 = offsetX pD3DMatrix[12] = (float)pMatrix[4]; // m42 = offsetY pD3DMatrix[13] = (float)pMatrix[5]; }
/// <summary> /// Sets the parameter's value. /// </summary> /// <param name="pValue">A pointer to the buffer that contains the value to set.</param> /// <param name="count">The number of elements in the array to set.</param> public void SetValue(Matrix *pValue, Int32 count) { SetMatrixArrayValueInternal <Matrix>((IntPtr)pValue, count, (ptr, index) => Matrix.Transpose(ref ((Matrix *)ptr)[index], out ((Matrix *)ptr)[index]), (ptr, index) => Matrix.Transpose(ref ((Matrix *)ptr)[index], out ((Matrix *)ptr)[index]), (l, c, t, v) => gl.UniformMatrix4fv(l, c, t, (Single *)v)); }
public static unsafe void Transform(Vector3 *vectors, Matrix *matrix, int count, Vector3 *result) { for (int i = 0; i < count; i++) { Vector3.Transform(ref *(vectors + i), ref *matrix, out *(result + i)); } }
protected override unsafe void UpdateDoorPosition() { if (base.m_subparts.Count != 0) { float num = (float)Math.Sqrt(1.1375000476837158); float z = base.m_currOpening * 1.75f; float num3 = base.m_currOpening * 1.570796f; if (z < num) { num3 = (float)Math.Asin((double)(z / 1.2f)); } else { float num5 = (1.75f - z) / (1.75f - num); num3 = 1.570796f - ((num5 * num5) * ((float)(1.570796012878418 - Math.Asin((double)(num / 1.2f))))); } z--; MyGridPhysics bodyA = base.CubeGrid.Physics; bool flag = !Sync.IsServer; int num4 = 0; bool flag2 = true; foreach (MyEntitySubpart subpart in base.m_subparts) { if (subpart != null) { Matrix matrix; Matrix *matrixPtr1; Matrix.CreateRotationY(flag2 ? num3 : -num3, out matrix); matrixPtr1.Translation = new Vector3(flag2 ? -1.2f : 1.2f, 0f, z); matrixPtr1 = (Matrix *)ref matrix; Matrix renderLocal = matrix * base.PositionComp.LocalMatrix; MyPhysicsComponentBase physics = subpart.Physics; if (flag && (physics != null)) { Matrix *matrixPtr2; Matrix identity = Matrix.Identity; matrixPtr2.Translation = new Vector3(flag2 ? -0.55f : 0.55f, 0f, 0f); matrixPtr2 = (Matrix *)ref identity; Matrix *matrixPtr3 = (Matrix *)ref identity; Matrix.Multiply(ref (Matrix) ref matrixPtr3, ref matrix, out identity); subpart.PositionComp.SetLocalMatrix(ref identity, null, true); } subpart.PositionComp.SetLocalMatrix(ref matrix, physics, true, ref renderLocal, true); if (((bodyA != null) && (physics != null)) && (base.m_subpartConstraintsData.Count > num4)) { bodyA.RigidBody.Activate(); physics.RigidBody.Activate(); matrix = Matrix.Invert(matrix); base.m_subpartConstraintsData[num4].SetInBodySpace(base.PositionComp.LocalMatrix, matrix, bodyA, (MyPhysicsBody)physics); } } flag2 = !flag2; num4++; } } }
private unsafe void InnerUpdateVertices(VertexPositionNormalTexture *pgpuVertices, Matrix[] boneTransforms, int startIndex, int elementCount) { fixed(Matrix *pBoneTransforms = boneTransforms) { #if USE_NATIVE_ANIMATION _cpuVertexBufferHelper.UpdateVertices((long)pBoneTransforms, (long)pgpuVertices, startIndex, elementCount); #else fixed(VertexIndicesWeightsPositionNormal *pcpuVertices = _cpuVertices) { Matrix transformSum = Matrix.Identity; var pVertex = pcpuVertices + startIndex; var pGpuVertex = pgpuVertices + startIndex; // skin all of the vertices for (int i = 0; i < elementCount; i++, pVertex++, pGpuVertex++) { int b0 = pVertex->BlendIndex0; int b1 = pVertex->BlendIndex1; int b2 = pVertex->BlendIndex2; int b3 = pVertex->BlendIndex3; float w1 = pVertex->BlendWeights.X; float w2 = pVertex->BlendWeights.Y; float w3 = pVertex->BlendWeights.Z; float w4 = pVertex->BlendWeights.W; Matrix *m1 = pBoneTransforms + b0; Matrix *m2 = pBoneTransforms + b1; Matrix *m3 = pBoneTransforms + b2; Matrix *m4 = pBoneTransforms + b3; transformSum.M11 = (m1->M11 * w1) + (m2->M11 * w2) + (m3->M11 * w3) + (m4->M11 * w4); transformSum.M12 = (m1->M12 * w1) + (m2->M12 * w2) + (m3->M12 * w3) + (m4->M12 * w4); transformSum.M13 = (m1->M13 * w1) + (m2->M13 * w2) + (m3->M13 * w3) + (m4->M13 * w4); transformSum.M21 = (m1->M21 * w1) + (m2->M21 * w2) + (m3->M21 * w3) + (m4->M21 * w4); transformSum.M22 = (m1->M22 * w1) + (m2->M22 * w2) + (m3->M22 * w3) + (m4->M22 * w4); transformSum.M23 = (m1->M23 * w1) + (m2->M23 * w2) + (m3->M23 * w3) + (m4->M23 * w4); transformSum.M31 = (m1->M31 * w1) + (m2->M31 * w2) + (m3->M31 * w3) + (m4->M31 * w4); transformSum.M32 = (m1->M32 * w1) + (m2->M32 * w2) + (m3->M32 * w3) + (m4->M32 * w4); transformSum.M33 = (m1->M33 * w1) + (m2->M33 * w2) + (m3->M33 * w3) + (m4->M33 * w4); transformSum.M41 = (m1->M41 * w1) + (m2->M41 * w2) + (m3->M41 * w3) + (m4->M41 * w4); transformSum.M42 = (m1->M42 * w1) + (m2->M42 * w2) + (m3->M42 * w3) + (m4->M42 * w4); transformSum.M43 = (m1->M43 * w1) + (m2->M43 * w2) + (m3->M43 * w3) + (m4->M43 * w4); pGpuVertex->Position.X = pVertex->Position.X * transformSum.M11 + pVertex->Position.Y * transformSum.M21 + pVertex->Position.Z * transformSum.M31 + transformSum.M41; pGpuVertex->Position.Y = pVertex->Position.X * transformSum.M12 + pVertex->Position.Y * transformSum.M22 + pVertex->Position.Z * transformSum.M32 + transformSum.M42; pGpuVertex->Position.Z = pVertex->Position.X * transformSum.M13 + pVertex->Position.Y * transformSum.M23 + pVertex->Position.Z * transformSum.M33 + transformSum.M43; pGpuVertex->Normal.X = pVertex->Normal.X * transformSum.M11 + pVertex->Normal.Y * transformSum.M21 + pVertex->Normal.Z * transformSum.M31; pGpuVertex->Normal.Y = pVertex->Normal.X * transformSum.M12 + pVertex->Normal.Y * transformSum.M22 + pVertex->Normal.Z * transformSum.M32; pGpuVertex->Normal.Z = pVertex->Normal.X * transformSum.M13 + pVertex->Normal.Y * transformSum.M23 + pVertex->Normal.Z * transformSum.M33; } } #endif } }
private unsafe void UpdateSlidingDoorsPosition() { if (base.CubeGrid.Physics != null) { Vector3 vector; bool flag = !Sync.IsServer; float x = this.m_currOpening * 0.65f; if (this.m_leftSubpart != null) { Matrix matrix; vector = new Vector3(-x, 0f, 0f); Matrix.CreateTranslation(ref vector, out matrix); Matrix renderLocal = matrix * base.PositionComp.LocalMatrix; Matrix identity = Matrix.Identity; identity.Translation = new Vector3(0.35f, 0f, 0f); Matrix *matrixPtr1 = (Matrix *)ref identity; Matrix.Multiply(ref (Matrix) ref matrixPtr1, ref matrix, out identity); this.m_leftSubpart.PositionComp.SetLocalMatrix(ref identity, flag ? null : this.m_leftSubpart.Physics, true, ref renderLocal, true); if (this.m_leftConstraintData != null) { Matrix matrix4; if (base.CubeGrid.Physics != null) { base.CubeGrid.Physics.RigidBody.Activate(); } this.m_leftSubpart.Physics.RigidBody.Activate(); vector = new Vector3(x, 0f, 0f); Matrix.CreateTranslation(ref vector, out matrix4); this.m_leftConstraintData.SetInBodySpace(base.PositionComp.LocalMatrix, matrix4, base.CubeGrid.Physics, (MyPhysicsBody)this.m_leftSubpart.Physics); } } if (this.m_rightSubpart != null) { Matrix matrix5; vector = new Vector3(x, 0f, 0f); Matrix.CreateTranslation(ref vector, out matrix5); Matrix renderLocal = matrix5 * base.PositionComp.LocalMatrix; Matrix identity = Matrix.Identity; identity.Translation = new Vector3(-0.35f, 0f, 0f); Matrix *matrixPtr2 = (Matrix *)ref identity; Matrix.Multiply(ref (Matrix) ref matrixPtr2, ref matrix5, out identity); this.m_rightSubpart.PositionComp.SetLocalMatrix(ref identity, flag ? null : this.m_rightSubpart.Physics, true, ref renderLocal, true); if (this.m_rightConstraintData != null) { if (base.CubeGrid.Physics != null) { base.CubeGrid.Physics.RigidBody.Activate(); } this.m_rightSubpart.Physics.RigidBody.Activate(); Matrix pivotB = Matrix.CreateTranslation(new Vector3(-x, 0f, 0f)); this.m_rightConstraintData.SetInBodySpace(base.PositionComp.LocalMatrix, pivotB, base.CubeGrid.Physics, (MyPhysicsBody)this.m_rightSubpart.Physics); } } } }
public void Evaluate(int SpreadMax) { if (this.FOutShader[0] == null) { this.FOutShader[0] = new DX11Resource <DX11Shader>(); } this.spmax = this.CalculateSpreadMax(); if (this.FInTechnique.IsChanged) { this.techniqueindex = this.FInTechnique[0].Index; this.techniquechanged = true; } float *src; //Cache world pointer this.FInWorld.GetMatrixPointer(out this.mworldcount, out src); this.mworld = (Matrix *)src; this.FOutLayer.SliceCount = 1; if (this.FOutLayer[0] == null) { this.FOutLayer[0] = new DX11Resource <DX11Layer>(); this.FOutShader[0] = new DX11Resource <DX11Shader>(); } if (this.FInvalidate) { if (this.FShader.IsCompiled) { this.FOutCompiled[0] = true; this.FOutTechniqueValid.SliceCount = this.FShader.TechniqueValids.Length; for (int i = 0; i < this.FShader.TechniqueValids.Length; i++) { this.FOutTechniqueValid[i] = this.FShader.TechniqueValids[i]; } } else { this.FOutCompiled[0] = false; this.FOutTechniqueValid.SliceCount = 0; } this.FInvalidate = false; } this.varmanager.ApplyUpdates(); }
internal static unsafe void ConvertFromD3DMATRIX( /* in */ D3DMATRIX *d3dMatrix, /* out */ Matrix *matrix ) { float * pD3DMatrix = (float *)d3dMatrix; double *pMatrix = (double *)matrix; // // Convert first D3DMatrix Vector // pMatrix[0] = (double)pD3DMatrix[0]; // m11 = m11 pMatrix[1] = (double)pD3DMatrix[1]; // m12 = m12 // Assert that non-affine fields are identity or NaN // // Multiplication with an affine 2D matrix (i.e., a matrix // with only _11, _12, _21, _22, _41, & _42 set to non-identity // values) containing NaN's, can cause the NaN's to propagate to // all other fields. Thus, we allow NaN's in addition to // identity values. Debug.Assert(pD3DMatrix[2] == 0.0f || Single.IsNaN(pD3DMatrix[2])); Debug.Assert(pD3DMatrix[3] == 0.0f || Single.IsNaN(pD3DMatrix[3])); // // Convert second D3DMatrix Vector // pMatrix[2] = (double)pD3DMatrix[4]; // m21 = m21 pMatrix[3] = (double)pD3DMatrix[5]; // m22 = m22 Debug.Assert(pD3DMatrix[6] == 0.0f || Single.IsNaN(pD3DMatrix[6])); Debug.Assert(pD3DMatrix[7] == 0.0f || Single.IsNaN(pD3DMatrix[7])); // // Convert third D3DMatrix Vector // Debug.Assert(pD3DMatrix[8] == 0.0f || Single.IsNaN(pD3DMatrix[8])); Debug.Assert(pD3DMatrix[9] == 0.0f || Single.IsNaN(pD3DMatrix[9])); Debug.Assert(pD3DMatrix[10] == 1.0f || Single.IsNaN(pD3DMatrix[10])); Debug.Assert(pD3DMatrix[11] == 0.0f || Single.IsNaN(pD3DMatrix[11])); // // Convert fourth D3DMatrix Vector // pMatrix[4] = (double)pD3DMatrix[12]; // m41 = offsetX pMatrix[5] = (double)pD3DMatrix[13]; // m42 = offsetY Debug.Assert(pD3DMatrix[14] == 0.0f || Single.IsNaN(pD3DMatrix[14])); Debug.Assert(pD3DMatrix[15] == 1.0f || Single.IsNaN(pD3DMatrix[15])); *((MatrixTypes *)(pMatrix + 6)) = MatrixTypes.TRANSFORM_IS_UNKNOWN; }
/// <summary> /// Render a model after applying the matrix transformations. /// </summary> /// <param name="context">The <see cref="GraphicsDevice"/> context.</param> /// <param name="world">A world transformation matrix.</param> /// <param name="view">A view transformation matrix.</param> /// <param name="projection">A projection transformation matrix.</param> /// <param name="effectOverride">An effect instance that will override all effects attached to this model. Null by default (no override)</param> /// <exception cref="System.InvalidOperationException">Mesh has no effect and effectOverride is null</exception> public unsafe void Draw(GraphicsDevice context, Matrix world, Matrix view, Matrix projection, Effect effectOverride = null) { int count = Meshes.Count; int boneCount = Bones.Count; Matrix *localSharedDrawBoneMatrices = stackalloc Matrix[boneCount]; // TODO use a global cache as BoneCount could generate a StackOverflow CopyAbsoluteBoneTransformsTo(new IntPtr(localSharedDrawBoneMatrices)); var defaultParametersContext = default(EffectDefaultParametersContext); for (int i = 0; i < count; i++) { var mesh = Meshes[i]; int index = mesh.ParentBone.Index; int effectCount = mesh.Effects.Count; if (effectOverride != null) { Matrix worldTranformed; Matrix.Multiply(ref localSharedDrawBoneMatrices[index], ref world, out worldTranformed); effectOverride.DefaultParameters.Apply(ref defaultParametersContext, ref worldTranformed, ref view, ref projection); } else { for (int j = 0; j < effectCount; j++) { var effect = mesh.Effects[j]; if (effect == null) { throw new InvalidOperationException("Mesh has no effect and effectOverride is null"); } Matrix worldTranformed; Matrix.Multiply(ref localSharedDrawBoneMatrices[index], ref world, out worldTranformed); var matrices = effect as IEffectMatrices; if (matrices == null) { effect.DefaultParameters.Apply(ref defaultParametersContext, ref worldTranformed, ref view, ref projection); } else { matrices.World = worldTranformed; matrices.View = view; matrices.Projection = projection; } } } mesh.Draw(context, effectOverride); } }
private static unsafe void ComputeCommonViewMatrices(RenderContext context, Matrix *viewMatrices, Matrix *projectionMatrices) { // there are some limitations to this technique: // both eyes view matrices must be facing the same direction // eyes don't modify input's projection's bottom and top. var commonView = context.RenderView; commonView.View = viewMatrices[0]; // near and far could be overriden by the VR device. let's take them as authority (assuming both eyes equal): // refer to http://stackoverflow.com/a/12926655/893406 float nearLeft = projectionMatrices[0].M43 / projectionMatrices[0].M33; float nearRight = projectionMatrices[1].M43 / projectionMatrices[1].M33; float farLeft = nearLeft * (-projectionMatrices[0].M33 / (-projectionMatrices[0].M33 - 1)); float farRight = nearRight * (-projectionMatrices[1].M33 / (-projectionMatrices[1].M33 - 1)); // Compute left and right var projectionLeftOfLeftEye = nearLeft * (projectionMatrices[0].M31 - 1.0f) / projectionMatrices[0].M11; var projectionRightOfRightEye = nearRight * (projectionMatrices[1].M31 + 1.0f) / projectionMatrices[1].M11; // IPD float interPupillaryDistance = (viewMatrices[0].TranslationVector - viewMatrices[1].TranslationVector).Length(); // find the center eye position according to the scheme described here: // http://computergraphics.stackexchange.com/questions/1736/vr-and-frustum-culling // tangent of theta, where theta is FOV/2 var tangentThetaLeftEye = Math.Abs(projectionLeftOfLeftEye / nearLeft); var tangentThetaRightEye = Math.Abs(projectionRightOfRightEye / nearRight); var recession = interPupillaryDistance / (tangentThetaLeftEye + tangentThetaRightEye); // left offset (`A` on the diagram of above link): var leftOffset = tangentThetaLeftEye * recession; // place the view position in between left and right: commonView.View.TranslationVector = Vector3.Lerp(viewMatrices[0].TranslationVector, viewMatrices[1].TranslationVector, leftOffset / interPupillaryDistance); // and move backward: commonView.View.M43 -= recession; // set clip planes to most conservative enclosing planes: var oldNear = commonView.NearClipPlane; commonView.NearClipPlane = Math.Min(nearRight, nearLeft) + recession; commonView.FarClipPlane = Math.Max(farLeft, farRight) + recession; // Projection: Need to extend size to cover equivalent of both eyes var bottom = context.RenderView.NearClipPlane * (context.RenderView.Projection.M32 - 1.0f) / context.RenderView.Projection.M22; var top = context.RenderView.NearClipPlane * (context.RenderView.Projection.M32 + 1.0f) / context.RenderView.Projection.M22; // adjust proportionally the parameters (l, r, u, b are defined at near, so we use nears ratio): var nearsRatio = commonView.NearClipPlane / oldNear; // recreation from scratch: Matrix.PerspectiveOffCenterRH(projectionLeftOfLeftEye * nearsRatio, projectionRightOfRightEye * nearsRatio, bottom * nearsRatio, top * nearsRatio, commonView.NearClipPlane, commonView.FarClipPlane, out commonView.Projection); // update the view projection: Matrix.Multiply(ref commonView.View, ref commonView.Projection, out commonView.ViewProjection); }
internal unsafe void ConvertIntoMatrix(Source source) { source.Lock(); Matrix *pter = (Matrix *)source.ArrayPointer; for (int i = 0; i < source.Accesor.Count; i++, pter++) { *pter = ConvertMatrix(*pter); } source.Unlock(); }
protected override void Copy(Matrix4x4[] destination, int destinationIndex, int length, int stride) { fixed(Matrix4x4 *destinationPtr = destination) { Matrix4x4 *dst = destinationPtr + destinationIndex; Matrix * src = FPData + Position; for (int i = 0; i < length; i++) { *(dst++) = (*src).ToMatrix4x4(); src += stride; } } }
protected override void Copy(Matrix4x4[] source, int sourceIndex, int length, int stride) { fixed(Matrix4x4 *sourcePtr = source) { Matrix4x4 *src = sourcePtr + sourceIndex; Matrix * dst = FPDst + Position; for (int i = 0; i < length; i++) { *dst = (*(src++)).ToSlimDXMatrix(); dst += stride; } } }
protected override void Copy(Matrix[] source, int sourceIndex, int length, int stride) { fixed(Matrix *sourcePtr = source) { Matrix *src = sourcePtr + sourceIndex; Matrix *dst = FPDst + Position; for (int i = 0; i < length; i++) { TransposeCopy(src, dst); src++; dst += stride; } } }
protected override void Copy(Matrix[] destination, int destinationIndex, int length, int stride) { fixed(Matrix *destinationPtr = destination) { Matrix *dst = destinationPtr + destinationIndex; Matrix *src = FPData + Position; for (int i = 0; i < length; i++) { TransposeCopy(src, dst); dst++; src += stride; } } }
/// <summary> /// Calculates the bounds of this model in world space. /// </summary> /// <param name="world">The world.</param> /// <returns>BoundingSphere.</returns> public unsafe BoundingSphere CalculateBounds(Matrix world) { int count = Meshes.Count; int boneCount = Bones.Count; Matrix *localSharedDrawBoneMatrices = stackalloc Matrix[boneCount]; // TODO use a global cache as BoneCount could generate a StackOverflow CopyAbsoluteBoneTransformsTo(new IntPtr(localSharedDrawBoneMatrices)); var defaultSphere = new BoundingSphere(Vector3.Zero, 0.0f); for (int i = 0; i < count; i++) { var mesh = Meshes[i]; int index = mesh.ParentBone.Index; Matrix result; Matrix.Multiply(ref localSharedDrawBoneMatrices[index], ref world, out result); var meshSphere = mesh.BoundingSphere; Vector3.TransformCoordinate(ref meshSphere.Center, ref result, out meshSphere.Center); BoundingSphere.Merge(ref defaultSphere, ref meshSphere, out defaultSphere); } return(defaultSphere); }
internal unsafe static Rect GetBoundsHelper( Pen pen, Matrix *pWorldMatrix, Point *pPoints, byte *pTypes, uint pointCount, uint segmentCount, Matrix *pGeometryMatrix, double tolerance, ToleranceType type, bool fSkipHollows) { MIL_PEN_DATA penData; double[] dashArray = null; // If the pen contributes to the bounds, populate the CMD struct bool fPenContributesToBounds = Pen.ContributesToBounds(pen); if (fPenContributesToBounds) { pen.GetBasicPenData(&penData, out dashArray); } MilMatrix3x2D geometryMatrix; if (pGeometryMatrix != null) { geometryMatrix = CompositionResourceManager.MatrixToMilMatrix3x2D(ref (*pGeometryMatrix)); } Debug.Assert(pWorldMatrix != null); MilMatrix3x2D worldMatrix = CompositionResourceManager.MatrixToMilMatrix3x2D(ref (*pWorldMatrix)); Rect bounds; fixed(double *pDashArray = dashArray) { int hr = MilCoreApi.MilUtility_PolygonBounds( &worldMatrix, (fPenContributesToBounds) ? &penData : null, (dashArray == null) ? null : pDashArray, pPoints, pTypes, pointCount, segmentCount, (pGeometryMatrix == null) ? null : &geometryMatrix, tolerance, type == ToleranceType.Relative, fSkipHollows, &bounds ); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we report that the geometry has empty bounds. bounds = Rect.Empty; } else { HRESULT.Check(hr); } } return(bounds); }
public Matrix4x4OutWriter(Matrix4x4OutStream stream, Matrix *pDst) : base(stream) { FPDst = pDst; }
private unsafe void CalculateCacheCell(MyHeightmapFace map, Cache.Cell *cell, bool compouteBounds = false) { ushort *numPtr2; ushort[] pinned numArray; int x = cell.Coord.X; int y = cell.Coord.Y; float *values = &s_Cz.M11; int linearOfft = (map.GetRowStart(y - 1) + x) - 1; if (((numArray = map.Data) == null) || (numArray.Length == 0)) { numPtr2 = null; } else { numPtr2 = numArray; } map.Get4Row(linearOfft, values, numPtr2); linearOfft += map.RowStride; map.Get4Row(linearOfft, values + (4 * 4), numPtr2); linearOfft += map.RowStride; map.Get4Row(linearOfft, values + (8 * 4), numPtr2); linearOfft += map.RowStride; map.Get4Row(linearOfft, values + (12 * 4), numPtr2); Matrix.Multiply(ref CR, ref s_Cz, out cell.Gz); Matrix.Multiply(ref cell.Gz, ref CRT, out cell.Gz); if (!compouteBounds) { cell.Max = 1f; cell.Min = 0f; } else { Matrix matrix; float positiveInfinity = float.PositiveInfinity; float negativeInfinity = float.NegativeInfinity; Matrix.Multiply(ref BInv, ref cell.Gz, out matrix); Matrix *matrixPtr1 = (Matrix *)ref matrix; Matrix.Multiply(ref (Matrix) ref matrixPtr1, ref BInvT, out matrix); float *numPtr3 = &matrix.M11; int num6 = 0; while (true) { if (num6 >= 0x10) { cell.Max = negativeInfinity; cell.Min = positiveInfinity; break; } if (negativeInfinity < numPtr3[num6 * 4]) { negativeInfinity = numPtr3[num6 * 4]; } if (positiveInfinity > numPtr3[num6 * 4]) { positiveInfinity = numPtr3[num6 * 4]; } num6++; } } numArray = null; fixed(float *numRef = null) { return; } }
static PrimitiveManager DecodePrimitivesWeighted(GeometryEntry geo, SkinEntry skin, SceneEntry scene, InfluenceManager infManager, ref string Error) { PrimitiveManager manager = DecodePrimitives(geo); MDL0BoneNode[] boneList; MDL0BoneNode bone = null; int boneCount; string[] jointStrings = null; byte * pCmd = stackalloc byte[4]; int cmdCount = skin._weightInputs.Count; float weight = 0; float * pWeights = null; Vector3 * pVert = null, pNorms = null; ushort * pVInd = (ushort *)manager._indices.Address; List <Vertex3> vertList = new List <Vertex3>(skin._weightCount); Matrix * pMatrix = null; UnsafeBuffer remap = new UnsafeBuffer(skin._weightCount * 2); ushort * pRemap = (ushort *)remap.Address; pNorms = (Vector3 *)manager._faceData[1].Address; //List<int> FixedIndices = new List<int>(); manager._vertices = vertList; //Find vertex source foreach (SourceEntry s in geo._sources) { if (s._id == geo._verticesInput._source) { pVert = (Vector3 *)((UnsafeBuffer)s._arrayData).Address; break; } } //Find joint source foreach (InputEntry inp in skin._jointInputs) { if (inp._semantic == SemanticType.JOINT) { foreach (SourceEntry src in skin._sources) { if (src._id == inp._source) { jointStrings = src._arrayData as string[]; break; } } } else if (inp._semantic == SemanticType.INV_BIND_MATRIX) { foreach (SourceEntry src in skin._sources) { if (src._id == inp._source) { pMatrix = (Matrix *)((UnsafeBuffer)src._arrayData).Address; break; } } } } Error = "There was a problem creating the list of bones for geometry entry " + geo._name; //Populate bone list boneCount = jointStrings.Length; boneList = new MDL0BoneNode[boneCount]; for (int i = 0; i < boneCount; i++) { boneList[i] = scene.FindNode(jointStrings[i])._node as MDL0BoneNode; } //Build command list foreach (InputEntry inp in skin._weightInputs) { switch (inp._semantic) { case SemanticType.JOINT: pCmd[inp._offset] = 1; break; case SemanticType.WEIGHT: pCmd[inp._offset] = 2; //Get weight source foreach (SourceEntry src in skin._sources) { if (src._id == inp._source) { pWeights = (float *)((UnsafeBuffer)src._arrayData).Address; break; } } break; default: pCmd[inp._offset] = 0; break; } } Error = "There was a problem creating vertex influences for geometry entry " + geo._name; //Build vertex list and remap table for (int i = 0; i < skin._weightCount; i++) { //Create influence int iCount = skin._weights[i].Length / cmdCount; Influence inf = new Influence(iCount); fixed(int *p = skin._weights[i]) { int *iPtr = p; for (int x = 0; x < iCount; x++) { for (int z = 0; z < cmdCount; z++, iPtr++) { if (pCmd[z] == 1) { bone = boneList[*iPtr]; } else if (pCmd[z] == 2) { weight = pWeights[*iPtr]; } } //if (bone != null) // if (bone.Name == "TopN" || bone.Name == "XRotN" || bone.Name == "YRotN" || bone.Name == "TransN" || bone.Name == "ThrowN" || bone.Name == "FacePattern") // Console.WriteLine(bone.Name); // else if (bone.Parent != null) // if (bone.Parent.Name == "FacePattern") // Console.WriteLine(bone.Name); inf._weights[x] = new BoneWeight(bone, weight); } } inf.CalcMatrix(); Error = "There was a problem creating a vertex from the geometry entry " + geo._name + ".\nMake sure that all the vertices are weighted properly."; Vertex3 v; if (inf._weights.Length > 1) { //Match with manager inf = infManager.AddOrCreate(inf); v = new Vertex3(skin._bindMatrix * pVert[i], inf); //World position } else { bone = inf._weights[0].Bone; v = new Vertex3(bone._inverseBindMatrix * skin._bindMatrix * pVert[i], bone); //Local position } ////Create Vertex, set to world position. //v = new Vertex3(skin._bindMatrix * pVert[i], inf); ////Fix single-bind vertices //v.Position = inf._weights[0].Bone._inverseBindMatrix * v.Position; ushort index = 0; while (index < vertList.Count) { if (v.Equals(vertList[index])) { break; } index++; } if (index == vertList.Count) { vertList.Add(v); } pRemap[i] = index; } Error = "There was a problem fixing normal rotations for geometry entry " + geo._name; //Remap vertex indices and fix normals for (int i = 0; i < manager._pointCount; i++, pVInd++) { * pVInd = pRemap[*pVInd]; Vertex3 v = null; if (*pVInd < vertList.Count) { v = vertList[*pVInd]; } if (v != null && v._influence != null) { if (v._influence.Weights.Length > 1) { pNorms[i] = skin._bindMatrix.GetRotationMatrix() * pNorms[i]; } else { pNorms[i] = skin._bindMatrix.GetRotationMatrix() * v._influence.Weights[0].Bone._inverseBindMatrix.GetRotationMatrix() * pNorms[i]; } } } remap.Dispose(); //manager.MergeTempData(); return(manager); }
public void Evaluate(int SpreadMax) { this.shaderupdated = false; this.spmax = this.CalculateSpreadMax(); if (FShaderCode.IsChanged || FFileName.IsChanged || FInDefines.IsChanged) { List <ShaderMacro> sms = new List <ShaderMacro>(); for (int i = 0; i < this.FInDefines.SliceCount; i++) { try { string[] s = this.FInDefines[i].Split("=".ToCharArray()); if (s.Length == 2) { ShaderMacro sm = new ShaderMacro(); sm.Name = s[0]; sm.Value = s[1]; sms.Add(sm); } } catch { } } DX11ShaderInclude FIncludeHandler = new DX11ShaderInclude(); FIncludeHandler.ParentPath = Path.GetDirectoryName(FFileName[0]); FShader = DX11Effect.FromString(FShaderCode[0], FIncludeHandler, sms.ToArray()); if (init && !ShaderCreatedByConfig) { this.SetShader(FShader, true); init = false; } else { this.SetShader(FShader, false); } // Write Shadercode & Defines into config -> needed to restore dynamic pins if (HasDynamicPins(FShader)) { configWritten = true; if (FConfigShader[0] != FShaderCode[0]) { FConfigShader[0] = FShaderCode[0]; FConfigDefines[0] = ""; for (int i = 0; i < FInDefines.SliceCount; i++) { if (i != 0) { FConfigDefines[0] += ","; } FConfigDefines[0] += this.FInDefines[i]; } } } else { if (FConfigShader[0] != "") { FConfigShader[0] = ""; FConfigDefines[0] = ""; } } } if (FShader.TechniqueNames != null && this.FInTechnique.IsChanged && FInTechnique.SliceCount > 0) { this.techniqueindex = Array.IndexOf(FShader.TechniqueNames, FInTechnique[0].Name); this.techniquechanged = true; } float *src; //Cache world pointer this.FInWorld.GetMatrixPointer(out this.mworldcount, out src); this.mworld = (Matrix *)src; this.FOutLayer.SliceCount = 1; if (this.FOutLayer[0] == null) { this.FOutLayer[0] = new DX11Resource <DX11Layer>(); } if (this.FInvalidate) { if (this.FShader.IsCompiled) { this.FOutCompiled[0] = true; this.FOutTechniqueValid.SliceCount = this.FShader.TechniqueValids.Length; for (int i = 0; i < this.FShader.TechniqueValids.Length; i++) { this.FOutTechniqueValid[i] = this.FShader.TechniqueValids[i]; } } else { this.FOutCompiled[0] = false; this.FOutTechniqueValid.SliceCount = 0; } this.FInvalidate = false; } if (this.FOutQueryable[0] == null) { this.FOutQueryable[0] = this; } }
public unsafe static void Transpose(Matrix* m, Matrix* transposed) { Transpose((M*)m, (M*)transposed); }
private static PrimitiveManager DecodePrimitivesWeighted( Matrix bindMatrix, GeometryEntry geo, SkinEntry skin, SceneEntry scene, InfluenceManager infManager, Type boneType) { PrimitiveManager manager = DecodePrimitives(geo); IBoneNode[] boneList; IBoneNode bone = null; int boneCount; string[] jointStringArray = null; string jointString = null; byte * pCmd = stackalloc byte[4]; int cmdCount = skin._weightInputs.Count; float weight = 0; float * pWeights = null; Vector3 * pVert = null, pNorms = null; ushort * pVInd = (ushort *)manager._indices.Address; List <Vertex3> vertList = new List <Vertex3>(skin._weightCount); Matrix * pMatrix = null; UnsafeBuffer remap = new UnsafeBuffer(skin._weightCount * 2); ushort * pRemap = (ushort *)remap.Address; if (manager._faceData[1] != null) { pNorms = (Vector3 *)manager._faceData[1].Address; } manager._vertices = vertList; //Find vertex source foreach (SourceEntry s in geo._sources) { if (s._id == geo._verticesInput._source) { pVert = (Vector3 *)((UnsafeBuffer)s._arrayData).Address; break; } } //Find joint source foreach (InputEntry inp in skin._jointInputs) { if (inp._semantic == SemanticType.JOINT) { foreach (SourceEntry src in skin._sources) { if (src._id == inp._source) { jointStringArray = src._arrayData as string[]; jointString = src._arrayDataString; break; } } } else if (inp._semantic == SemanticType.INV_BIND_MATRIX) { foreach (SourceEntry src in skin._sources) { if (src._id == inp._source) { pMatrix = (Matrix *)((UnsafeBuffer)src._arrayData).Address; break; } } } } Error = "There was a problem creating the list of bones for geometry entry " + geo._name; //Populate bone list boneCount = jointStringArray.Length; boneList = new IBoneNode[boneCount]; for (int i = 0; i < boneCount; i++) { NodeEntry entry = scene.FindNode(jointStringArray[i]); if (entry != null && entry._node != null) { boneList[i] = entry._node as IBoneNode; } else { //Search in reverse! foreach (NodeEntry node in scene._nodes) { if ((entry = RecursiveTestNode(jointString, node)) != null) { if (entry._node != null) { boneList[i] = entry._node as IBoneNode; } break; } } //Couldn't find the bone if (boneList[i] == null) { boneList[i] = Activator.CreateInstance(boneType) as IBoneNode; } } } //Build command list foreach (InputEntry inp in skin._weightInputs) { switch (inp._semantic) { case SemanticType.JOINT: pCmd[inp._offset] = 1; break; case SemanticType.WEIGHT: pCmd[inp._offset] = 2; //Get weight source foreach (SourceEntry src in skin._sources) { if (src._id == inp._source) { pWeights = (float *)((UnsafeBuffer)src._arrayData).Address; break; } } break; default: pCmd[inp._offset] = 0; break; } } Error = "There was a problem creating vertex influences for geometry entry " + geo._name; //Build vertex list and remap table for (int i = 0; i < skin._weightCount; i++) { //Create influence int iCount = skin._weights[i].Length / cmdCount; Influence inf = new Influence(); fixed(int *p = skin._weights[i]) { int *iPtr = p; for (int x = 0; x < iCount; x++) { for (int z = 0; z < cmdCount; z++, iPtr++) { if (pCmd[z] == 1) { bone = boneList[*iPtr]; } else if (pCmd[z] == 2) { weight = pWeights[*iPtr]; } } inf.AddWeight(new BoneWeight(bone, weight)); } } inf.CalcMatrix(); Error = "There was a problem creating a vertex from the geometry entry " + geo._name + ".\nMake sure that all the vertices are weighted properly."; Vector3 worldPos = bindMatrix * skin._bindMatrix * pVert[i]; Vertex3 v; if (inf.Weights.Count > 1) { //Match with manager inf = infManager.FindOrCreate(inf); v = new Vertex3(worldPos, inf); //World position } else { bone = inf.Weights[0].Bone; v = new Vertex3(bone.InverseBindMatrix * worldPos, bone); //Local position } ushort index = 0; while (index < vertList.Count) { if (v.Equals(vertList[index])) { break; } index++; } if (index == vertList.Count) { vertList.Add(v); } pRemap[i] = index; } Error = "There was a problem fixing normal rotations for geometry entry " + geo._name; //Remap vertex indices and fix normals for (int i = 0; i < manager._pointCount; i++, pVInd++) { *pVInd = pRemap[*pVInd]; if (pNorms != null) { Vertex3 v = null; if (*pVInd < vertList.Count) { v = vertList[*pVInd]; } if (v != null && v.MatrixNode != null) { if (v.MatrixNode.Weights.Count > 1) { pNorms[i] = (bindMatrix * skin._bindMatrix).GetRotationMatrix() * pNorms[i]; } else { pNorms[i] = (v.MatrixNode.Weights[0].Bone.InverseBindMatrix * bindMatrix * skin._bindMatrix).GetRotationMatrix() * pNorms[i]; } } } } remap.Dispose(); return(manager); }
public Matrix4x4InStreamReader(Matrix4x4InStream stream, Matrix *pData) : base(stream) { FPData = pData; }
protected override unsafe void CollectCore(RenderContext context) { var camera = context.GetCurrentCamera(); if (context.RenderView == null) { throw new NullReferenceException(nameof(context.RenderView) + " is null. Please make sure you have your camera correctly set."); } // Setup pixel formats for RenderStage using (context.SaveRenderOutputAndRestore()) { // Mark this view as requiring shadows shadowMapRenderer?.RenderViewsWithShadows.Add(context.RenderView); context.RenderOutput = new RenderOutputDescription(PostEffects != null ? PixelFormat.R16G16B16A16_Float : context.RenderOutput.RenderTargetFormat0, DepthBufferFormat, MSAALevel); CollectStages(context); if (VRSettings.Enabled && VRSettings.VRDevice != null) { Vector3 cameraPos, cameraScale; Matrix cameraRot; if (!vrSystem.PreviousUseCustomViewMatrix) { camera.Entity.Transform.WorldMatrix.Decompose(out cameraScale, out cameraRot, out cameraPos); } else { camera.ViewMatrix.Decompose(out cameraScale, out cameraRot, out cameraPos); cameraRot.Transpose(); Vector3.Negate(ref cameraPos, out cameraPos); Vector3.TransformCoordinate(ref cameraPos, ref cameraRot, out cameraPos); } if (VRSettings.IgnoreCameraRotation) { cameraRot = Matrix.Identity; } // Compute both view and projection matrices Matrix *viewMatrices = stackalloc Matrix[2]; Matrix *projectionMatrices = stackalloc Matrix[2]; for (var i = 0; i < 2; ++i) { VRSettings.VRDevice.ReadEyeParameters(i == 0 ? Eyes.Left : Eyes.Right, camera.NearClipPlane, camera.FarClipPlane, ref cameraPos, ref cameraRot, out viewMatrices[i], out projectionMatrices[i]); } // if the VRDevice disagreed with the near and far plane, we must re-discover them and follow: var near = projectionMatrices[0].M43 / projectionMatrices[0].M33; var far = near * (-projectionMatrices[0].M33 / (-projectionMatrices[0].M33 - 1)); if (Math.Abs(near - camera.NearClipPlane) > 1e-8f) { camera.NearClipPlane = near; } if (Math.Abs(near - camera.FarClipPlane) > 1e-8f) { camera.FarClipPlane = far; } // Compute a view matrix and projection matrix that cover both eyes for shadow map and culling ComputeCommonViewMatrices(context, viewMatrices, projectionMatrices); var commonView = context.RenderView; // Notify lighting system this view only purpose is for shared lighting, it is not being drawn directly. commonView.Flags |= RenderViewFlags.NotDrawn; // Collect now, and use result for both eyes CollectView(context); context.VisibilityGroup.TryCollect(commonView); for (var i = 0; i < 2; i++) { using (context.PushRenderViewAndRestore(VRSettings.RenderViews[i])) using (context.SaveViewportAndRestore()) { context.RenderSystem.Views.Add(context.RenderView); context.RenderView.SceneInstance = commonView.SceneInstance; context.RenderView.LightingView = commonView; context.ViewportState.Viewport0 = new Viewport(0, 0, VRSettings.VRDevice.ActualRenderFrameSize.Width / 2.0f, VRSettings.VRDevice.ActualRenderFrameSize.Height); //change camera params for eye camera.ViewMatrix = viewMatrices[i]; camera.ProjectionMatrix = projectionMatrices[i]; camera.UseCustomProjectionMatrix = true; camera.UseCustomViewMatrix = true; camera.Update(); //write params to view SceneCameraRenderer.UpdateCameraToRenderView(context, context.RenderView, camera); // Copy culling results context.VisibilityGroup.Copy(commonView, context.RenderView); CollectView(context); LightShafts?.Collect(context); PostEffects?.Collect(context); } } if (VRSettings.VRDevice.SupportsOverlays) { foreach (var overlay in VRSettings.Overlays) { if (overlay != null && overlay.Texture != null) { overlay.Overlay.Position = overlay.LocalPosition; overlay.Overlay.Rotation = overlay.LocalRotation; overlay.Overlay.SurfaceSize = overlay.SurfaceSize; overlay.Overlay.FollowHeadRotation = overlay.FollowsHeadRotation; } } } } else { //write params to view SceneCameraRenderer.UpdateCameraToRenderView(context, context.RenderView, camera); CollectView(context); LightShafts?.Collect(context); PostEffects?.Collect(context); } // Set depth format for shadow map render stages // TODO: This format should be acquired from the ShadowMapRenderer instead of being fixed here foreach (var shadowMapRenderStage in ShadowMapRenderStages) { shadowMapRenderStage.Output = new RenderOutputDescription(PixelFormat.None, PixelFormat.D32_Float); } } PostEffects?.Collect(context); }
public void Evaluate(int SpreadMax) { if (this.shaderupdated) { this.FOutShader[0] = new DX11Resource<DX11Shader>(); } this.shaderupdated = false; this.spmax = this.CalculateSpreadMax(); if (this.FInTechnique.IsChanged) { this.techniqueindex = this.FInTechnique[0].Index; this.techniquechanged = true; } float* src; //Cache world pointer this.FInWorld.GetMatrixPointer(out this.mworldcount, out src); this.mworld = (Matrix*)src; this.FOutLayer.SliceCount = 1; if (this.FOutLayer[0] == null) { this.FOutLayer[0] = new DX11Resource<DX11Layer>(); this.FOutShader[0] = new DX11Resource<DX11Shader>(); } if (this.FInvalidate) { if (this.FShader.IsCompiled) { this.FOutCompiled[0] = true; this.FOutTechniqueValid.SliceCount = this.FShader.TechniqueValids.Length; for (int i = 0; i < this.FShader.TechniqueValids.Length; i++) { this.FOutTechniqueValid[i] = this.FShader.TechniqueValids[i]; } } else { this.FOutCompiled[0] = false; this.FOutTechniqueValid.SliceCount = 0; } this.FInvalidate = false; } }
public RowView(Matrix *p) => _p = (float *)p;