public static void rot12_post(out Mat3 m, float c, float s, Mat3 im) { m = im; float m01 = m.m01, m02 = m.m02, m11 = m.m11, m12 = m.m12, m21 = m.m21, m22 = m.m22; m.set(m.m00, c * m01 - s * m02, s * m01 + c * m02, m.m10, c * m11 - s * m12, s * m11 + c * m12, m.m20, c * m21 - s * m22, s * m21 + c * m22); }
public static void rot01_post(out Mat3 m, float c, float s, Mat3 im) { m = im; float m00 = m.m00, m01 = m.m01, m10 = m.m10, m11 = m.m11, m20 = m.m20, m21 = m.m21; m.set(c * m00 - s * m01, s * m00 + c * m01, m.m02, c * m10 - s * m11, s * m10 + c * m11, m.m12, c * m20 - s * m21, s * m20 + c * m21, m.m22); }
public static float solveLeastSquares(Mat3 a, Vec3 b, out Vec3 x, float svd_tol, int svd_sweeps, float pinv_tol) { Mat3 at; SMat3 ata; Vec3 atb; MatUtils.transpose(out at, a); MatUtils.mmul_ata(out ata, a); MatUtils.vmul(out atb, at, b); return Svd.solveSymmetric(ata, atb, out x, svd_tol, svd_sweeps, pinv_tol); }
public static void ToODE( ref Mat3 value, out Ode.dMatrix3 result ) { result.M00 = value.Item0.X; result.M01 = value.Item1.X; result.M02 = value.Item2.X; result.M03 = 0; result.M10 = value.Item0.Y; result.M11 = value.Item1.Y; result.M12 = value.Item2.Y; result.M13 = 0; result.M20 = value.Item0.Z; result.M21 = value.Item1.Z; result.M22 = value.Item2.Z; result.M23 = 0; }
private static float calcError(Mat3 A, Vec3 x, Vec3 b) { Vec3 vtmp; MatUtils.vmul(out vtmp, A, x); VecUtils.sub(out vtmp, b, vtmp); return VecUtils.dot(vtmp, vtmp); }
void UpdatePhysXJoint() { bool needCreate = PushedToWorld && !Broken; bool created = nativeJoint != IntPtr.Zero; if( needCreate == created ) return; if( needCreate ) { if( Math.Abs( Vec3.Dot( axis1.Direction, axis2.Direction ) ) > .095f ) { Log.Warning( "UniversalJoint: Invalid axes." ); return; } //if( Axis1.LimitsEnabled && Axis1.LimitLow > Axis1.LimitHigh ) //{ // Log.Warning( "UniversalJoint: Invalid axis1 limits (low > high)." ); // return; //} //if( Axis2.LimitsEnabled && Axis2.LimitLow > Axis2.LimitHigh ) //{ // Log.Warning( "UniversalJoint: Invalid axis2 limits (low > high)." ); // return; //} PhysXBody physXBody0 = (PhysXBody)Body1; PhysXBody physXBody1 = (PhysXBody)Body2; if( ( !physXBody0.Static || !physXBody1.Static ) && ( physXBody0.nativeBody != IntPtr.Zero && physXBody1.nativeBody != IntPtr.Zero ) ) { axis1LocalAxis = Body1.Rotation.GetInverse() * axis1.Direction; axis2LocalAxis = Body1.Rotation.GetInverse() * axis2.Direction; Mat3 axisMatrix = new Mat3( axis1.Direction, -Vec3.Cross( axis1.Direction, axis2.Direction ), axis2.Direction ) * Mat3.FromRotateByZ( MathFunctions.PI / 2 ); Quat globalAxisRotation = axisMatrix.ToQuat().GetNormalize(); //Quat globalAxisRotation = new Mat3( axis1.Direction, -Vec3.Cross( axis1.Direction, axis2.Direction ), // axis2.Direction ).ToQuat().GetNormalize(); Vec3 localPosition0 = physXBody0.Rotation.GetInverse() * ( Anchor - physXBody0.Position ); Quat localRotation0 = ( physXBody0.Rotation.GetInverse() * globalAxisRotation ).GetNormalize(); Vec3 localPosition1 = physXBody1.Rotation.GetInverse() * ( Anchor - physXBody1.Position ); Quat localRotation1 = ( physXBody1.Rotation.GetInverse() * globalAxisRotation ).GetNormalize(); nativeJoint = PhysXNativeWrapper.PhysXNativeD6Joint.Create( physXBody0.nativeBody, ref localPosition0, ref localRotation0, physXBody1.nativeBody, ref localPosition1, ref localRotation1 ); PhysXNativeD6Joint.SetMotion( nativeJoint, PhysXD6Axis.X, PhysXD6Motion.Locked ); PhysXNativeD6Joint.SetMotion( nativeJoint, PhysXD6Axis.Y, PhysXD6Motion.Locked ); PhysXNativeD6Joint.SetMotion( nativeJoint, PhysXD6Axis.Z, PhysXD6Motion.Locked ); UpdateLimits(); if( ContactsEnabled ) PhysXNativeWrapper.PhysXJoint.SetCollisionEnable( nativeJoint, true ); UpdatePhysXBreakData(); if( Scene._EnableDebugVisualization ) SetVisualizationEnable( true ); //PhysXNativeD6Joint.SetProjectionTolerances( nativeJoint, .2f, MathFunctions.PI ); //PhysXNativeWrapper.PhysXJoint.SetProjectionEnable( nativeJoint, true ); } } else { DestroyPhysXJoint(); } }
public override void OnAgentShootMissile(Agent shooterAgent, EquipmentIndex weaponIndex, Vec3 position, Vec3 velocity, Mat3 orientation, bool hasRigidBody, int forcedMissileIndex) { if (!_fireArrowEnabled) { return; } bool allowed = false; MissionWeapon weapon = shooterAgent.Equipment[weaponIndex]; switch (weapon.CurrentUsageItem.WeaponClass) { case WeaponClass.Arrow: case WeaponClass.Bolt: case WeaponClass.Bow: case WeaponClass.Crossbow: allowed = true; break; case WeaponClass.ThrowingAxe: case WeaponClass.ThrowingKnife: case WeaponClass.Javelin: allowed = FireLordConfig.AllowFireThrownWeapon; break; } if (allowed) { foreach (Mission.Missile missile in Mission.Current.Missiles) { if (!_missileParticles.ContainsKey(missile)) { MatrixFrame localFrame = new MatrixFrame(Mat3.Identity, new Vec3(0, 0, 0)); ParticleSystem particle = ParticleSystem.CreateParticleSystemAttachedToEntity( "psys_game_burning_agent", missile.Entity, ref localFrame); Light light = Light.CreatePointLight(FireLordConfig.FireArrowLightRadius); light.Intensity = FireLordConfig.FireArrowLightIntensity; light.LightColor = FireLordConfig.FireArrowLightColor; missile.Entity.AddLight(light); _missileParticles.Add(missile, particle); } } } }
public override void OnAgentShootMissile(Agent shooterAgent, EquipmentIndex weaponIndex, Vec3 position, Vec3 velocity, Mat3 orientation, bool hasRigidBody, int forcedMissileIndex) { base.OnAgentShootMissile(shooterAgent, weaponIndex, position, velocity, orientation, hasRigidBody, forcedMissileIndex); if (!IsActivated) { return; } if (PlayerAgent != null && Utils.IsPlayerAlly(shooterAgent, PlayerAgent)) { AllyFiredMissileEvent?.Invoke(shooterAgent); } }
public static void WriteRotationMatrixToPacket(Mat3 value) { GameNetworkMessage.WriteVec3ToPacket(value.s, CompressionBasic.UnitVectorCompressionInfo); GameNetworkMessage.WriteVec3ToPacket(value.f, CompressionBasic.UnitVectorCompressionInfo); GameNetworkMessage.WriteVec3ToPacket(value.u, CompressionBasic.UnitVectorCompressionInfo); }
public override void Update(Mat3 matrix, int offset) { throw new NotImplementedException(); }
public static float off(Mat3 a) { return Mathf.Sqrt((a.m01 * a.m01) + (a.m02 * a.m02) + (a.m10 * a.m10) + (a.m12 * a.m12) + (a.m20 * a.m20) + (a.m21 * a.m21)); }
public Line3 Transform(Mat3 matrix) { return(new Line3(point1.Transform(matrix), point2.Transform(matrix))); }
public static void getSymmetricSvd(SMat3 a, out SMat3 vtav, out Mat3 v, float tol, int max_sweeps) { vtav = new SMat3(); v = new Mat3(); vtav.setSymmetric(a); v.set(1, 0, 0, 0, 1, 0, 0, 0, 1); float delta = tol * MatUtils.fnorm(vtav); for (int i = 0; i < max_sweeps && MatUtils.off(vtav) > delta; ++i) { Schur2.rotate01(out vtav, out v, vtav, v); Schur2.rotate02(out vtav, out v, vtav, v); Schur2.rotate12(out vtav, out v, vtav, v); } }
public static void mmul_ata(out SMat3 mout, Mat3 a) { mout = new SMat3(a.m00 * a.m00 + a.m10 * a.m10 + a.m20 * a.m20, a.m00 * a.m01 + a.m10 * a.m11 + a.m20 * a.m21, a.m00 * a.m02 + a.m10 * a.m12 + a.m20 * a.m22, a.m01 * a.m01 + a.m11 * a.m11 + a.m21 * a.m21, a.m01 * a.m02 + a.m11 * a.m12 + a.m21 * a.m22, a.m02 * a.m02 + a.m12 * a.m12 + a.m22 * a.m22); }
public static void mmul(out Mat3 mout, Mat3 a, Mat3 b) { mout = new Mat3(a.m00 * b.m00 + a.m01 * b.m10 + a.m02 * b.m20, a.m00 * b.m01 + a.m01 * b.m11 + a.m02 * b.m21, a.m00 * b.m02 + a.m01 * b.m12 + a.m02 * b.m22, a.m10 * b.m00 + a.m11 * b.m10 + a.m12 * b.m20, a.m10 * b.m01 + a.m11 * b.m11 + a.m12 * b.m21, a.m10 * b.m02 + a.m11 * b.m12 + a.m12 * b.m22, a.m20 * b.m00 + a.m21 * b.m10 + a.m22 * b.m20, a.m20 * b.m01 + a.m21 * b.m11 + a.m22 * b.m21, a.m20 * b.m02 + a.m21 * b.m12 + a.m22 * b.m22); }
public static float fnorm(Mat3 a) { return Mathf.Sqrt((a.m00 * a.m00) + (a.m01 * a.m01) + (a.m02 * a.m02) + (a.m10 * a.m10) + (a.m11 * a.m11) + (a.m12 * a.m12) + (a.m20 * a.m20) + (a.m21 * a.m21) + (a.m22 * a.m22)); }
private static float calcError(SMat3 origA, Vec3 x, Vec3 b) { Mat3 A = new Mat3(); Vec3 vtmp; A.setSymmetric(origA); MatUtils.vmul(out vtmp, A, x); VecUtils.sub(out vtmp, b, vtmp); return VecUtils.dot(vtmp, vtmp); }
public override unsafe void Update(Mat3 matrix, ShaderVariableMapping variable) { Orbital_Video_D3D12_ConstantBuffer_Update(handle, &matrix, (uint)Marshal.SizeOf <Mat3>(), (uint)variable.offset, activeNodeIndex); }
public static void transpose(out Mat3 mout, Mat3 a) { mout = new Mat3(a.m00, a.m10, a.m20, a.m01, a.m11, a.m21, a.m02, a.m12, a.m22); }
public TransformData(Vec3 position, Vec3 rotation, Vec3 scale) { Model = Mat4.Translation(position) * Mat4.Rotation(rotation) * Mat4.Scale(scale); InverseTransposeModel = new Mat3(Model).Transpose.Inverse; }
public static void vmul(out Vec3 vout, Mat3 a, Vec3 v) { vout = new Vec3(); vout.x = (a.m00 * v.x) + (a.m01 * v.y) + (a.m02 * v.z); vout.y = (a.m10 * v.x) + (a.m11 * v.y) + (a.m12 * v.z); vout.z = (a.m20 * v.x) + (a.m21 * v.y) + (a.m22 * v.z); }
public abstract void Update(Mat3 matrix, int offset);
private Mat3(Mat3 rhs) { this.set(rhs); }
public static void Prefix(ref WorldFrame __result, ref Mission __instance, BattleSideEnum side, FormationClass formationClass, bool isReinforcement, int customAgentCount = -1, float offsetAwayFrom = 0f, bool isSpawningWithHorses = true) { int _usedSpawnPathIndex = (int)ReflectUtils.ReflectField("_usedSpawnPathIndex", __instance); //int _spawnPoints = (int)ReflectUtils.ReflectField("_spawnPoints", __instance); int _agentCount = (int)ReflectUtils.ReflectField("_agentCount", __instance); Path _usedSpawnPath = (Path)ReflectUtils.ReflectField("_usedSpawnPath", __instance); float _randomMiddlePointAddition = (float)ReflectUtils.ReflectField("_randomMiddlePointAddition", __instance); MatrixFrame[] _spawnPoints = (MatrixFrame[])ReflectUtils.ReflectField("_spawnPoints", __instance); int num; if (customAgentCount != -1) { num = customAgentCount; } else { num = _agentCount; } if (_usedSpawnPathIndex < 0) { int num2 = 0; int num3; do { num3 = ((num2 <= 20) ? (MBRandom.RandomInt(3) + 1) : ((num2 - 20) % 3 + 1)); _usedSpawnPath = __instance.Scene.GetPathWithName("spawn_path_0" + num3); num2++; }while (_usedSpawnPath == null && num2 < 24); _usedSpawnPathIndex = num3; _randomMiddlePointAddition = -0.13f + MBRandom.RandomFloat * 0.26f; } else { _usedSpawnPath = __instance.Scene.GetPathWithName("spawn_path_0" + _usedSpawnPathIndex); } if (_usedSpawnPath != null) { _usedSpawnPath.GetPoints(_spawnPoints); float totalLength = _usedSpawnPath.GetTotalLength(); float num4 = 800f / totalLength; float num5 = 0.5f + _randomMiddlePointAddition; float num6 = -1f; if (num > 0) { num6 = 0.04f + 0.08f * (float)Math.Pow((double)(num + (isReinforcement ? 25 : 0)), 0.40000000596046448); num6 *= num4; } num6 = MBMath.ClampFloat(num6, 0.15f, 1f); float num7 = 0f; if (formationClass >= FormationClass.Ranged) { Formation formation = ((side == BattleSideEnum.Attacker) ? __instance.Teams.Attacker : __instance.Teams.Defender).GetFormation(FormationClass.Infantry); num7 += formation.Depth; } if (formationClass >= FormationClass.Cavalry) { Formation formation = ((side == BattleSideEnum.Attacker) ? __instance.Teams.Attacker : __instance.Teams.Defender).GetFormation(FormationClass.Ranged); num7 += formation.Depth; } if (!isSpawningWithHorses && formationClass >= FormationClass.HorseArcher) { Formation formation = ((side == BattleSideEnum.Attacker) ? __instance.Teams.Attacker : __instance.Teams.Defender).GetFormation(FormationClass.Cavalry); num7 += formation.Depth; } float num8 = Math.Max(0f, num5 - 0.44f * num6); float num9 = Math.Min(1f, num5 + 0.44f * num6); MatrixFrame frameForDistance = _usedSpawnPath.GetFrameForDistance(totalLength * num8 - offsetAwayFrom - num7); MatrixFrame frameForDistance2 = _usedSpawnPath.GetFrameForDistance(totalLength * num9 + offsetAwayFrom + num7); MatrixFrame matrixFrame = (side == BattleSideEnum.Attacker) ? frameForDistance2 : frameForDistance; Vec2 v = ((side == BattleSideEnum.Defender) ? frameForDistance2 : frameForDistance).origin.AsVec2 - matrixFrame.origin.AsVec2; v.Normalize(); Mat3 identity = Mat3.Identity; identity.RotateAboutUp(v.RotationInRadians); WorldPosition worldPosition = new WorldPosition(__instance.Scene, UIntPtr.Zero, matrixFrame.origin, false); if (formationClass == FormationClass.NumberOfRegularFormations) { worldPosition.SetVec2(worldPosition.AsVec2 - v * 12f); } if (isSpawningWithHorses && (formationClass == FormationClass.Cavalry || formationClass == FormationClass.HorseArcher)) { WorldPosition worldPosition2 = worldPosition; float num10 = ((side == BattleSideEnum.Attacker) ? __instance.Teams.Attacker : __instance.Teams.Defender).GetFormation(FormationClass.Cavalry).Width * 0.5f; float num11 = Math.Max(((side == BattleSideEnum.Attacker) ? __instance.Teams.Attacker : __instance.Teams.Defender).GetFormation(FormationClass.Infantry).Width, ((side == BattleSideEnum.Attacker) ? __instance.Teams.Attacker : __instance.Teams.Defender).GetFormation(FormationClass.Ranged).Width) * 0.5f; worldPosition2.SetVec2(worldPosition.AsVec2 + ((formationClass == FormationClass.Cavalry) ? v.LeftVec() : v.RightVec()) * (num10 + num11)); if (worldPosition2.GetNavMesh() != UIntPtr.Zero) { worldPosition.SetVec2(worldPosition2.AsVec2); } } __result = new WorldFrame(identity, worldPosition); } if (__instance.IsFieldBattle) { GameEntity gameEntity = __instance.Scene.FindEntityWithTag("defender_" + ((formationClass != FormationClass.NumberOfRegularFormations) ? formationClass.GetName().ToLower() : "infantry")); GameEntity gameEntity2 = __instance.Scene.FindEntityWithTag("attacker_" + ((formationClass != FormationClass.NumberOfRegularFormations) ? formationClass.GetName().ToLower() : "infantry")); if (gameEntity != null && gameEntity2 != null) { Vec3 globalPosition = gameEntity.GlobalPosition; Vec3 v2 = gameEntity2.GlobalPosition - globalPosition; Vec3 arg_4E7_0 = globalPosition; float num12 = v2.Normalize(); float num13 = 1000f / num12; float num14 = 0.08f + 0.08f * (float)Math.Pow((double)(num + (isReinforcement ? 25 : 0)), 0.30000001192092896); num14 *= num13; float num15 = Math.Max(0f, 0.5f - 0.5f * num14); float num16 = Math.Min(1f, 0.5f + 0.5f * num14); Vec3 vec = arg_4E7_0 + v2 * (num12 * num15); Vec3 vec2 = arg_4E7_0 + v2 * (num12 * num16); Vec3 vec3 = (side == BattleSideEnum.Attacker) ? vec2 : vec; Vec3 vec4 = ((side == BattleSideEnum.Defender) ? vec2 : vec) - vec3; vec4.Normalize(); Mat3 identity2 = Mat3.Identity; identity2.RotateAboutUp(vec4.AsVec2.RotationInRadians); WorldPosition origin = new WorldPosition(__instance.Scene, UIntPtr.Zero, vec3, false); __result = new WorldFrame(identity2, origin); } Vec2 v3 = Vec2.Invalid; ICollection <Vec2> value = __instance.Boundaries.First <KeyValuePair <string, ICollection <Vec2> > >().Value; if (value.Count > 0) { v3 = value.Aggregate((a, b) => a + b); v3 *= 1f / (float)value.Count; } WorldPosition origin2 = new WorldPosition(__instance.Scene, UIntPtr.Zero, v3.ToVec3(0f), false); __result = new WorldFrame(Mat3.Identity, origin2); } else { SiegeMissionController expr_609 = __instance.GetMissionBehaviour <SiegeMissionController>(); if (expr_609 != null) { bool arg_614_0 = expr_609.IsSallyOut; } string text = side.ToString().ToLower() + "_" + ((formationClass != FormationClass.NumberOfRegularFormations) ? formationClass.GetName().ToLower() : "infantry"); if (isReinforcement) { text += "_reinforcement"; } GameEntity gameEntity3 = __instance.Scene.FindEntityWithTag(text); if (gameEntity3 != null) { MatrixFrame globalFrame = gameEntity3.GetGlobalFrame(); globalFrame.rotation.OrthonormalizeAccordingToForwardAndKeepUpAsZAxis(); WorldPosition origin3 = new WorldPosition(__instance.Scene, UIntPtr.Zero, globalFrame.origin, false); __result = new WorldFrame(globalFrame.rotation, origin3); } Vec2 v4 = Vec2.Invalid; ICollection <Vec2> value2 = __instance.Boundaries.First <KeyValuePair <string, ICollection <Vec2> > >().Value; if (value2.Count > 0) { v4 = value2.Aggregate((a, b) => a + b); v4 *= 1f / (float)value2.Count; } WorldPosition origin4 = new WorldPosition(__instance.Scene, UIntPtr.Zero, v4.ToVec3(0f), false); __result = new WorldFrame(Mat3.Identity, origin4); } }
public static void Set(string name, Mat3 value) { Set(name, new Shader.UniformMat3(value)); }
public static void rotate12(out SMat3 vtav, out Mat3 v, SMat3 ivtav, Mat3 iv) { vtav = ivtav; v = iv; if (vtav.m12 == 0) return; float c, s; rot12(out vtav, out c, out s, vtav, c, s); Givens.rot12_post(out v, c, s, v); }
void GetShapeSubmergedSpheres( ref Mat3 bodyRotation, Shape shape, List<SubmergedCheckItem> outSubmergedItems ) { Body body = shape.Body; Vec3 shapePosition = body.Position + bodyRotation * shape.Position; switch( shape.ShapeType ) { case Shape.Type.Box: { BoxShape boxShape = (BoxShape)shape; Quat shapeRotation = shape.Body.Rotation; if( !shape.IsIdentityTransform ) shapeRotation *= shape.Rotation; Vec3 halfD = boxShape.Dimensions * .5f; float r = Math.Min( Math.Min( halfD.X, halfD.Y ), halfD.Z ); Vec3I stepsCount = new Vec3I( 1, 1, 1 ); if( halfD.X > r * .3f ) stepsCount.X = 2; if( halfD.Y > r * .3f ) stepsCount.Y = 2; if( halfD.Z > r * .3f ) stepsCount.Z = 2; for( int z = 0; z < stepsCount.Z; z++ ) { for( int y = 0; y < stepsCount.Y; y++ ) { for( int x = 0; x < stepsCount.X; x++ ) { Vec3 localPos = Vec3.Zero; if( stepsCount.X == 2 ) localPos.X = ( x == 0 ) ? ( -halfD.X + r ) : ( halfD.X - r ); if( stepsCount.Y == 2 ) localPos.Y = ( y == 0 ) ? ( -halfD.Y + r ) : ( halfD.Y - r ); if( stepsCount.X == 2 ) localPos.Z = ( z == 0 ) ? ( -halfD.Z + r ) : ( halfD.Z - r ); Vec3 pos = shapePosition + shapeRotation * localPos; outSubmergedItems.Add( GetSphereSubmergedCoef( new Sphere( pos, r ) ) ); } } } } break; case Shape.Type.Capsule: { CapsuleShape capsuleShape = (CapsuleShape)shape; float r = capsuleShape.Radius; float l = capsuleShape.Length; Quat shapeRotation = shape.Body.Rotation; if( !shape.IsIdentityTransform ) shapeRotation *= shape.Rotation; Vec3 pos; pos = shapePosition + shapeRotation * new Vec3( 0, 0, -l * .5f ); outSubmergedItems.Add( GetSphereSubmergedCoef( new Sphere( pos, r ) ) ); pos = shapePosition + shapeRotation * new Vec3( 0, 0, l * .5f ); outSubmergedItems.Add( GetSphereSubmergedCoef( new Sphere( pos, r ) ) ); } break; case Shape.Type.Sphere: { SphereShape sphereShape = (SphereShape)shape; float r = sphereShape.Radius; outSubmergedItems.Add( GetSphereSubmergedCoef( new Sphere( shapePosition, r ) ) ); } break; case Shape.Type.Mesh: { MeshShape meshShape = (MeshShape)shape; Bounds b; if( meshShape.GetDataBounds( out b ) ) { float r = b.GetRadius(); outSubmergedItems.Add( GetSphereSubmergedCoef( new Sphere( shapePosition, r ) ) ); } } break; } }
public override int GetHashCode() { int hash = Name.GetHashCode(); if (Item != null) { hash ^= Item.GetHashCode(); } hash ^= CrewSkillId.GetHashCode(); hash ^= SkillOrange.GetHashCode(); hash ^= SkillYellow.GetHashCode(); hash ^= SkillGreen.GetHashCode(); hash ^= SkillGrey.GetHashCode(); if (Mat1 != null) { hash ^= Mat1.GetHashCode(); hash ^= Mat1Quantity; } if (Mat2 != null) { hash ^= Mat2.GetHashCode(); hash ^= Mat2Quantity.GetHashCode(); } if (Mat3 != null) { hash ^= Mat3.GetHashCode(); hash ^= Mat3Quantity.GetHashCode(); } if (Mat4 != null) { hash ^= Mat4.GetHashCode(); hash ^= Mat4Quantity.GetHashCode(); } if (Mat5 != null) { hash ^= Mat5.GetHashCode(); hash ^= Mat5Quantity.GetHashCode(); } hash ^= CraftingTime.GetHashCode(); hash ^= Subtype.GetHashCode(); if (Research1 != null) { hash ^= CraftingTimeT1.GetHashCode(); hash ^= Research1.GetHashCode(); hash ^= ResearchChance1.GetHashCode(); hash ^= ResearchQuantity1.GetHashCode(); } if (Research2 != null) { hash ^= CraftingTimeT2.GetHashCode(); hash ^= Research2.GetHashCode(); hash ^= ResearchChance2.GetHashCode(); hash ^= ResearchQuantity2.GetHashCode(); } if (Research3 != null) { hash ^= CraftingTimeT3.GetHashCode(); hash ^= Research3.GetHashCode(); hash ^= ResearchChance3.GetHashCode(); hash ^= ResearchQuantity3.GetHashCode(); } hash ^= MissionCost.GetHashCode(); if (MissionDescription != null) { hash ^= MissionDescription.GetHashCode(); } hash ^= MissionUnlockable.GetHashCode(); hash ^= MissionLight.GetHashCode(); hash ^= MissionLightCrit.GetHashCode(); hash ^= MissionDark.GetHashCode(); hash ^= MissionDarkCrit.GetHashCode(); hash ^= TrainingCost.GetHashCode(); hash ^= DisableDisassemble.GetHashCode(); hash ^= DisableCritical.GetHashCode(); hash ^= MissionFaction.GetHashCode(); if (MissionYieldDescription != null) { hash ^= MissionYieldDescription.GetHashCode(); } hash ^= Deprecated.GetHashCode(); return(hash); }
public override void TryCollide(SegmentCollider other) { if (!other.GameObject.Enabled) { return; } var realCenter = (Center + GameObject.Transform.Position); if (realCenter.Dot(other.GameObject.Transform.Position) < 0) { return; } if (other.GameObject.Transform.Position.Y > realCenter.Y) { return; } var otherRotation = other.GameObject.Transform.Rotation; var centerDistance = realCenter.Magnitude; var frontNormal = realCenter.WithY(0).Normalized; var rotMat = Mat3.Rotation(Vec3.Up * -otherRotation.Y); var closeLeft = rotMat * other.CloseLeft; var farLeft = rotMat * other.FarLeft; var closeRight = rotMat * other.CloseRight; var farRight = rotMat * other.FarRight; var leftVec = farLeft - closeLeft; var rightVec = farRight - closeRight; var leftNormal = Vec3.Up.Cross(leftVec).Normalized; var rightNormal = rightVec.Cross(Vec3.Up).Normalized; var inCloseOffset = other.Segment.Close - Radius < centerDistance; var inFarOffset = other.Segment.Far + Radius > centerDistance; var inLeftOffset = Vec3.CheckLeftRight( realCenter, closeLeft + leftNormal * Radius, farLeft) < 0; var inRightOffset = Vec3.CheckLeftRight( realCenter, closeRight + rightNormal * Radius, farRight) > 0; // Check if in offset boundary if (inCloseOffset && inFarOffset && inLeftOffset && inRightOffset) { // Check if close / far side hit var inLeft = Vec3.CheckLeftRight(realCenter, closeLeft, farLeft) < 0; var inRight = Vec3.CheckLeftRight(realCenter, closeRight, farRight) > 0; if (inCloseOffset && inFarOffset && inLeft && inRight) { var normal = frontNormal; if (Math.Abs(centerDistance - other.Segment.Close) < Math.Abs(centerDistance - other.Segment.Far)) { normal = -frontNormal; } OnCollision(other, normal); return; } // Check if left / right side hit var inClose = other.Segment.Close < centerDistance; var inFar = other.Segment.Far > centerDistance; if (inClose && inFar && inLeftOffset && inRightOffset) { var normal = rightNormal; if (farLeft.DistanceTo(realCenter) < farRight.DistanceTo(realCenter)) { normal = leftNormal; } OnCollision(other, normal); return; } // Check if corner hit var corners = new List <Vec3> { closeLeft, farLeft, closeRight, farRight }; foreach (var corner in corners) { if (corner.DistanceTo(realCenter) > Radius) { continue; } var normal = realCenter - corner; OnCollision(other, normal); return; } } lastCollider = null; }
public FormationQuerySystem(Formation formation) { FormationQuerySystem formationQuerySystem = this; this.Formation = formation; Mission mission = Mission.Current; this._formationPower = new QueryData <float>(new Func <float>(formation.GetFormationPower), 2.5f); this._formationMeleeFightingPower = new QueryData <float>(new Func <float>(formation.GetFormationMeleeFightingPower), 2.5f); this._averagePosition = new QueryData <Vec2>((Func <Vec2>)(() => { Vec2 vec2 = formation.CountOfUnitsWithoutDetachedOnes > 1 ? formation.GetAveragePositionOfUnits(true, true) : (formation.CountOfUnitsWithoutDetachedOnes > 0 ? formation.GetAveragePositionOfUnits(true, false) : formation.OrderPosition.AsVec2); float time = MBCommon.GetTime(MBCommon.TimeType.Mission); float num = time - formationQuerySystem._lastAveragePositionCalculateTime; if ((double)num > 0.0) { formationQuerySystem._currentVelocity.SetValue((vec2 - formationQuerySystem._averagePosition.GetCachedValue()) * (1f / num), time); } formationQuerySystem._lastAveragePositionCalculateTime = time; return(vec2); }), 0.05f); this._currentVelocity = new QueryData <Vec2>((Func <Vec2>)(() => { formationQuerySystem._averagePosition.Evaluate(MBCommon.GetTime(MBCommon.TimeType.Mission)); return(formationQuerySystem._currentVelocity.GetCachedValue()); }), 1f); this._estimatedDirection = new QueryData <Vec2>((Func <Vec2>)(() => { if (formation.CountOfUnitsWithoutDetachedOnes > 0) { Vec2 averagePositionOfUnits = formation.GetAveragePositionOfUnits(true, false); float num1 = 0.0f; float num2 = 0.0f; Vec2 localAveragePosition = formation.OrderLocalAveragePosition; foreach (Agent looseDetachedOne in formation.UnitsWithoutLooseDetachedOnes) { Vec2?positionOfUnitOrDefault = formation.arrangement.GetLocalPositionOfUnitOrDefault((IFormationUnit)looseDetachedOne); if (positionOfUnitOrDefault.HasValue) { Vec2 vec2 = positionOfUnitOrDefault.Value; Vec2 asVec2 = looseDetachedOne.Position.AsVec2; num1 += (float)(((double)vec2.x - (double)localAveragePosition.x) * ((double)asVec2.x - (double)averagePositionOfUnits.x) + ((double)vec2.y - (double)localAveragePosition.y) * ((double)asVec2.y - (double)averagePositionOfUnits.y)); num2 += (float)(((double)vec2.x - (double)localAveragePosition.x) * ((double)asVec2.y - (double)averagePositionOfUnits.y) - ((double)vec2.y - (double)localAveragePosition.y) * ((double)asVec2.x - (double)averagePositionOfUnits.x)); } } float num3 = 1f / (float)formation.CountOfUnitsWithoutDetachedOnes; float num4 = num1 * num3; float num5 = num2 * num3; float num6 = MathF.Sqrt((float)((double)num4 * (double)num4 + (double)num5 * (double)num5)); if ((double)num6 > 0.0) { double num7 = Math.Acos((double)MBMath.ClampFloat(num4 / num6, -1f, 1f)); Vec2 vec2_1 = Vec2.FromRotation((float)num7); Vec2 vec2_2 = Vec2.FromRotation((float)-num7); float num8 = 0.0f; float num9 = 0.0f; foreach (Agent looseDetachedOne in formation.UnitsWithoutLooseDetachedOnes) { Vec2?positionOfUnitOrDefault = formation.arrangement.GetLocalPositionOfUnitOrDefault((IFormationUnit)looseDetachedOne); if (positionOfUnitOrDefault.HasValue) { Vec2 parentUnitF1 = vec2_1.TransformToParentUnitF(positionOfUnitOrDefault.Value - localAveragePosition); Vec2 parentUnitF2 = vec2_2.TransformToParentUnitF(positionOfUnitOrDefault.Value - localAveragePosition); Vec2 asVec2 = looseDetachedOne.Position.AsVec2; num8 += (parentUnitF1 - asVec2 + averagePositionOfUnits).LengthSquared; num9 += (parentUnitF2 - asVec2 + averagePositionOfUnits).LengthSquared; } } return((double)num8 >= (double)num9 ? vec2_2 : vec2_1); } } return(new Vec2(0.0f, 1f)); }), 0.2f); this._medianPosition = new QueryData <WorldPosition>((Func <WorldPosition>)(() => { if (formation.CountOfUnitsWithoutDetachedOnes != 0) { return(formation.CountOfUnitsWithoutDetachedOnes != 1 ? formation.GetMedianAgent(true, true, formationQuerySystem.AveragePosition).GetWorldPosition() : formation.GetMedianAgent(true, false, formationQuerySystem.AveragePosition).GetWorldPosition()); } if (formation.CountOfUnits == 0) { return(formation.OrderPosition); } return(formation.CountOfUnits != 1 ? formation.GetMedianAgent(false, true, formationQuerySystem.AveragePosition).GetWorldPosition() : formation.GetFirstUnit().GetWorldPosition()); }), 0.05f); this._averageAllyPosition = new QueryData <Vec2>((Func <Vec2>)(() => { IEnumerable <Formation> source = mission.Teams.GetAlliesOf(formation.Team, true).SelectMany <TaleWorlds.MountAndBlade.Team, Formation>((Func <TaleWorlds.MountAndBlade.Team, IEnumerable <Formation> >)(t => t.FormationsIncludingSpecial)).Where <Formation>(closure_1 ?? (closure_1 = (Func <Formation, bool>)(f => f != formation))); if (source.IsEmpty <Formation>()) { return(closure_0.AveragePosition); } Vec2 zero = Vec2.Zero; int num = 0; foreach (Formation formation1 in source) { zero += formation1.GetAveragePositionOfUnits(false, false) * (float)formation1.CountOfUnits; num += formation1.CountOfUnits; } return(num == 0 ? Vec2.Invalid : zero *(1f / (float)num)); }), 5f); this._idealAverageDisplacement = new QueryData <float>((Func <float>)(() => (float)Math.Sqrt(Math.Pow((double)formation.Width / 2.0, 2.0) + Math.Pow((double)formation.Depth / 2.0, 2.0)) / 2f), 5f); this._formationIntegrityData = new QueryData <FormationQuerySystem.FormationIntegrityDataGroup>((Func <FormationQuerySystem.FormationIntegrityDataGroup>)(() => { if (formation.CountOfUnitsWithoutDetachedOnes > 0) { float num1 = 0.0f; List <IFormationUnit> allUnits = formation.arrangement.GetAllUnits(); Vec3 vec3; for (int index = 0; index < allUnits.Count; ++index) { Agent unit = allUnits[index] as Agent; double num2 = (double)num1; Vec2 globalPositionOfUnit = formation.GetCurrentGlobalPositionOfUnit(unit, false); vec3 = unit.Position; Vec2 asVec2 = vec3.AsVec2; double lengthSquared = (double)(globalPositionOfUnit - asVec2).LengthSquared; num1 = (float)(num2 + lengthSquared); } Vec2 vec2_1; for (int index = 0; index < formation.LooseDetachedUnits.Count; ++index) { Agent looseDetachedUnit = formation.LooseDetachedUnits[index]; double num2 = (double)num1; Vec2 globalPositionOfUnit = formation.GetCurrentGlobalPositionOfUnit(looseDetachedUnit, false); vec3 = looseDetachedUnit.Position; Vec2 asVec2 = vec3.AsVec2; vec2_1 = globalPositionOfUnit - asVec2; double lengthSquared = (double)vec2_1.LengthSquared; num1 = (float)(num2 + lengthSquared); } float num3 = (float)((double)num1 / (double)formation.CountOfUnitsWithoutDetachedOnes * 4.0); float num4 = 0.0f; Vec2 vec2_2 = Vec2.Zero; float num5 = 0.0f; int num6 = 0; for (int index = 0; index < allUnits.Count; ++index) { Agent unit = allUnits[index] as Agent; Vec2 globalPositionOfUnit = formation.GetCurrentGlobalPositionOfUnit(unit, false); vec3 = unit.Position; Vec2 asVec2_1 = vec3.AsVec2; vec2_1 = globalPositionOfUnit - asVec2_1; float lengthSquared = vec2_1.LengthSquared; if ((double)lengthSquared < (double)num3) { num4 += lengthSquared; Vec2 vec2_3 = vec2_2; vec3 = unit.AverageVelocity; Vec2 asVec2_2 = vec3.AsVec2; vec2_2 = vec2_3 + asVec2_2; num5 += unit.MaximumForwardUnlimitedSpeed; ++num6; } } for (int index = 0; index < formation.LooseDetachedUnits.Count; ++index) { Agent looseDetachedUnit = formation.LooseDetachedUnits[index]; Vec2 globalPositionOfUnit = formation.GetCurrentGlobalPositionOfUnit(looseDetachedUnit, false); vec3 = looseDetachedUnit.Position; Vec2 asVec2_1 = vec3.AsVec2; vec2_1 = globalPositionOfUnit - asVec2_1; float lengthSquared = vec2_1.LengthSquared; if ((double)lengthSquared < (double)num3) { num4 += lengthSquared; Vec2 vec2_3 = vec2_2; vec3 = looseDetachedUnit.AverageVelocity; Vec2 asVec2_2 = vec3.AsVec2; vec2_2 = vec2_3 + asVec2_2; num5 += looseDetachedUnit.MaximumForwardUnlimitedSpeed; ++num6; } } if (num6 > 0) { Vec2 vec2_3 = vec2_2 * (1f / (float)num6); float x = num4 / (float)num6; float num2 = num5 / (float)num6; FormationQuerySystem.FormationIntegrityDataGroup integrityDataGroup; integrityDataGroup.AverageVelocityExcludeFarAgents = vec2_3; integrityDataGroup.DeviationOfPositionsExcludeFarAgents = MathF.Sqrt(x); integrityDataGroup.AverageMaxUnlimitedSpeedExcludeFarAgents = num2; return(integrityDataGroup); } } FormationQuerySystem.FormationIntegrityDataGroup integrityDataGroup1; integrityDataGroup1.AverageVelocityExcludeFarAgents = Vec2.Zero; integrityDataGroup1.DeviationOfPositionsExcludeFarAgents = 0.0f; integrityDataGroup1.AverageMaxUnlimitedSpeedExcludeFarAgents = 0.0f; return(integrityDataGroup1); }), 1f); this._formationDispersedness = new QueryData <float>((Func <float>)(() => { if (formation.CountOfUnits == 0) { return(0.0f); } float num1 = 0.0f; int num2 = 0; foreach (IFormationUnit allUnit in formation.arrangement.GetAllUnits()) { Vec2?positionOfUnitOrDefault = formation.arrangement.GetLocalPositionOfUnitOrDefault(allUnit); if (positionOfUnitOrDefault.HasValue) { MatrixFrame m = new MatrixFrame(Mat3.Identity, new Vec3(positionOfUnitOrDefault.Value)); MatrixFrame matrixFrame; ref MatrixFrame local = ref matrixFrame; Mat3 rot = new Mat3(new Vec3(formation.Direction.RightVec()), new Vec3(formation.Direction), new Vec3(z: 1f)); WorldPosition worldPosition = formation.QuerySystem.MedianPosition; Vec3 navMeshVec3 = worldPosition.GetNavMeshVec3(); local = new MatrixFrame(rot, navMeshVec3); MatrixFrame parent = matrixFrame.TransformToParent(m); double num3 = (double)num1; worldPosition = (allUnit as Agent).GetWorldPosition(); double num4 = (double)worldPosition.GetGroundVec3().Distance(parent.origin); num1 = (float)(num3 + num4); }
public static void psuedoinverse(out Mat3 m, SMat3 d, Mat3 v, float tol) { m = new Mat3(); float d0 = pinv(d.m00, tol), d1 = pinv (d.m11, tol), d2 = pinv(d.m22, tol); m.set(v.m00 * d0 * v.m00 + v.m01 * d1 * v.m01 + v.m02 * d2 * v.m02, v.m00 * d0 * v.m10 + v.m01 * d1 * v.m11 + v.m02 * d2 * v.m12, v.m00 * d0 * v.m20 + v.m01 * d1 * v.m21 + v.m02 * d2 * v.m22, v.m10 * d0 * v.m00 + v.m11 * d1 * v.m01 + v.m12 * d2 * v.m02, v.m10 * d0 * v.m10 + v.m11 * d1 * v.m11 + v.m12 * d2 * v.m12, v.m10 * d0 * v.m20 + v.m11 * d1 * v.m21 + v.m12 * d2 * v.m22, v.m20 * d0 * v.m00 + v.m21 * d1 * v.m01 + v.m22 * d2 * v.m02, v.m20 * d0 * v.m10 + v.m21 * d1 * v.m11 + v.m22 * d2 * v.m12, v.m20 * d0 * v.m20 + v.m21 * d1 * v.m21 + v.m22 * d2 * v.m22); }
protected override void OnGetCameraTransform( out Vec3 position, out Vec3 forward, out Vec3 up, ref Degree cameraFov ) { position = Vec3.Zero; forward = Vec3.XAxis; up = Vec3.ZAxis; Unit unit = GetPlayerUnit(); if( unit == null ) return; PlayerIntellect.Instance.FPSCamera = false; //To use data about orientation the camera if the cut scene is switched on if( IsCutSceneEnabled() ) if( CutSceneManager.Instance.GetCamera( out position, out forward, out up, out cameraFov ) ) return; //To receive orientation the camera if the player is in a observe camera area if( GetActiveObserveCameraAreaCameraOrientation( out position, out forward, out up, ref cameraFov ) ) return; Vec3 cameraLookDir = PlayerIntellect.Instance.LookDirection.GetVector(); switch( GetRealCameraType() ) { case CameraType.Follow: { float fractionDistance = 0.02f; float fractionOrientation = 0.05f; Vec3 targetCamPosition = unit.Position + unit.Rotation * new Vec3(0f, -2f, .5f); //Vec3 targetCamPosition = unit.Position + unit.Rotation * new Vec3(-5f, 0f, 5f); camPosition = camPosition + fractionDistance * (targetCamPosition - camPosition); // Calculates targetCamRotation Vec3 lookAt = unit.Position - camPosition; lookAt.Normalize(); Vec3 myup = Vec3.ZAxis; Vec3 right = Vec3.Cross(lookAt, myup); right.Normalize(); myup = Vec3.Cross(right, lookAt); myup.Normalize(); Mat3 targetCamRotationMatrix = new Mat3(right, lookAt, myup); Quat targetCamRotation = targetCamRotationMatrix.ToQuat(); // camRotation = Quat.Slerp(camRotation, targetCamRotation, fractionOrientation); Vec3 targetCamForward = unit.Position - camPosition; targetCamForward.Normalize(); Vec3 camForward = camRotation * Vec3.YAxis; camForward = camForward + fractionOrientation * (targetCamForward - camForward); position = camPosition; forward = camRotation * Vec3.YAxis; up = camRotation * Vec3.ZAxis; } break; case CameraType.TPS: { float cameraDistance; float cameraCenterOffset; if( IsPlayerUnitVehicle() ) { cameraDistance = tpsVehicleCameraDistance; cameraCenterOffset = tpsVehicleCameraCenterOffset; } else { cameraDistance = tpsCameraDistance; cameraCenterOffset = tpsCameraCenterOffset; } PlayerIntellect.Instance.UpdateTransformBeforeCameraPositionCalculation(); //To calculate orientation of a TPS camera. Vec3 lookAt = unit.GetInterpolatedPosition() + new Vec3( 0, 0, cameraCenterOffset ); Vec3 cameraPos = lookAt - cameraLookDir * cameraDistance; RayCastResult[] piercingResult = PhysicsWorld.Instance.RayCastPiercing( new Ray( lookAt, cameraPos - lookAt ), (int)ContactGroup.CastOnlyContact ); foreach( RayCastResult result in piercingResult ) { bool ignore = false; MapObject obj = MapSystemWorld.GetMapObjectByBody( result.Shape.Body ); if( obj == unit ) ignore = true; if( ( lookAt - result.Position ).LengthSqr() < .001f ) ignore = true; //cut ignore objects here //.. if( !ignore ) { cameraPos = result.Position; break; } } position = cameraPos; forward = ( lookAt - position ).GetNormalize(); } break; case CameraType.FPS: { //To calculate orientation of a FPS camera. PlayerIntellect.Instance.UpdateTransformBeforeCameraPositionCalculation(); if( unit is Turret ) { //Turret specific Gun mainGun = ( (Turret)unit ).MainGun; position = mainGun.GetInterpolatedPosition(); position += unit.Type.FPSCameraOffset * mainGun.GetInterpolatedRotation(); } else if( unit is Tank ) { //Tank specific Gun mainGun = ( (Tank)unit ).MainGun; position = mainGun.GetInterpolatedPosition(); position += unit.Type.FPSCameraOffset * mainGun.GetInterpolatedRotation(); } else { //Characters, etc position = unit.GetInterpolatedPosition(); position += unit.Type.FPSCameraOffset * unit.GetInterpolatedRotation(); } forward = cameraLookDir; } break; } //To update data in player intellect about type of the camera PlayerIntellect.Instance.FPSCamera = GetRealCameraType() == CameraType.FPS; float cameraOffset; if( IsPlayerUnitVehicle() ) cameraOffset = tpsVehicleCameraCenterOffset; else cameraOffset = tpsCameraCenterOffset; PlayerIntellect.Instance.TPSCameraCenterOffset = cameraOffset; //zoom for Turret if( EngineApp.Instance.IsMouseButtonPressed( EMouseButtons.Right ) ) { if( GetPlayerUnit() as Turret != null ) if( GetRealCameraType() == CameraType.TPS ) cameraFov /= 3; } }
/// <summary>Overridden from <see cref="Engine.EntitySystem.Entity.OnPostCreate(Boolean)"/>.</summary> protected override void OnPostCreate(bool loaded) { base.OnPostCreate(loaded); if (EntitySystemWorld.Instance.IsServer()) { if (Active) { Vec3 min = Position + new Vec3(0, 0, 0); //min Vec3 max = Position + new Vec3(Type.BoxSize.X * BoxLength * Scale.X, Type.BoxSize.Y * BoxWidth * Scale.Y, Type.BoxSize.Z * BoxHeight * Scale.Z); //max Mat3 rotation = new Mat3(1, 0, 0, 0, 1, 0, 0, 0, 1); //camera.DebugGeometry.Color = new ColorValue(0, 1, 0, .5f); bounds = new Bounds(min, max); box = new Box(bounds); box.Axis = rotation * Rotation.ToMat3(); box.Center = Position + new Vec3(0, 0, ((max.Z - min.Z) / 2) + .1f); box.Expand(.1f); //camera.DebugGeometry.AddBox(box); } } SubscribeToTickEvent(); UpdateAttachedObjects(); }
public Transform(Geometry <V> geometry, Mat4 matrix) : base(geometry) { _matrix = matrix; _normalMatrix = new Mat3(_matrix).Inverse.Transposed; }
protected override void OnRender(Camera camera) { base.OnRender(camera); if ((EngineDebugSettings.DrawGameSpecificDebugGeometry || EngineApp.Instance.ApplicationType == EngineApp.ApplicationTypes.ResourceEditor || EngineApp.Instance.ApplicationType == EngineApp.ApplicationTypes.MapEditor || EngineApp.Instance.ApplicationType == EngineApp.ApplicationTypes.Simulation) && camera.Purpose == Camera.Purposes.MainCamera) { if (Active) { Vec3 min = Position + new Vec3(0, 0, 0); //min Vec3 max = Position + new Vec3(Type.BoxSize.X * BoxLength * Scale.X, Type.BoxSize.Y * BoxWidth * Scale.Y, Type.BoxSize.Z * BoxHeight * Scale.Z); //max Mat3 rotation = new Mat3(1, 0, 0, 0, 1, 0, 0, 0, 1); camera.DebugGeometry.Color = new ColorValue(0, 1, 0, .5f); bounds = new Bounds(min, max); box = new Box(bounds); box.Axis = rotation * Rotation.ToMat3(); box.Center = Position + new Vec3(0, 0, ((max.Z - min.Z) / 2) + .1f); box.Expand(.1f); camera.DebugGeometry.AddBox(box); } } }
void UpdateMapTransformGpuParameters( MapItem map ) { TransformItem transform = map.Transform; if( !transform.IsDataExists() ) return; //calculate scroll and rotate Vec2 scroll = transform.Scroll; Vec2 scale = transform.Scale; float rotate = transform.Rotate; AnimationItem animation = transform.Animation; if( animation.IsDataExists() ) { float time = GetMapTransformAnimationTime(); Vec2 animationScroll = animation.ScrollSpeed * time; Vec2 round = animation.ScrollRound; if( round.X != 0 ) { animationScroll.X = MathFunctions.Round( animationScroll.X * ( 1.0f / round.X ) ) * round.X; } if( round.Y != 0 ) { animationScroll.Y = MathFunctions.Round( animationScroll.Y * ( 1.0f / round.Y ) ) * round.Y; } scroll += animationScroll; rotate += animation.RotateSpeed * time; } scroll.X = scroll.X % 1.0f; scroll.Y = scroll.Y % 1.0f; rotate = rotate % 1.0f; //calculate matrix Mat3 matrix; { if( scale != new Vec2( 1, 1 ) ) matrix = Mat3.FromScale( new Vec3( scale.X, scale.Y, 1 ) ); else matrix = Mat3.Identity; if( rotate != 0 ) { Mat3 m; m = new Mat3( 1, 0, -.5f, 0, 1, -.5f, 0, 0, 1 ); m *= Mat3.FromRotateByZ( rotate * ( MathFunctions.PI * 2 ) ); m *= new Mat3( 1, 0, .5f, 0, 1, .5f, 0, 0, 1 ); matrix *= m; } if( scroll != Vec2.Zero ) matrix *= new Mat3( 1, 0, scroll.X, 0, 1, scroll.Y, 0, 0, 1 ); } //find gpu parameters GpuParameters mulGpuParameter; GpuParameters addGpuParameter; bool needForShadowCasterMaterial = false; { if( map == diffuse1Map ) { mulGpuParameter = GpuParameters.diffuse1MapTransformMul; addGpuParameter = GpuParameters.diffuse1MapTransformAdd; needForShadowCasterMaterial = true; } else if( map == diffuse2Map ) { mulGpuParameter = GpuParameters.diffuse2MapTransformMul; addGpuParameter = GpuParameters.diffuse2MapTransformAdd; needForShadowCasterMaterial = true; } else if( map == diffuse3Map ) { mulGpuParameter = GpuParameters.diffuse3MapTransformMul; addGpuParameter = GpuParameters.diffuse3MapTransformAdd; needForShadowCasterMaterial = true; } else if( map == diffuse4Map ) { mulGpuParameter = GpuParameters.diffuse4MapTransformMul; addGpuParameter = GpuParameters.diffuse4MapTransformAdd; needForShadowCasterMaterial = true; } else if( map == reflectionMap ) { mulGpuParameter = GpuParameters.reflectionMapTransformMul; addGpuParameter = GpuParameters.reflectionMapTransformAdd; } else if( map == emissionMap ) { mulGpuParameter = GpuParameters.emissionMapTransformMul; addGpuParameter = GpuParameters.emissionMapTransformAdd; } else if( map == specularMap ) { mulGpuParameter = GpuParameters.specularMapTransformMul; addGpuParameter = GpuParameters.specularMapTransformAdd; } else if( map == translucencyMap ) { mulGpuParameter = GpuParameters.translucencyMapTransformMul; addGpuParameter = GpuParameters.translucencyMapTransformAdd; } else if( map == normalMap ) { mulGpuParameter = GpuParameters.normalMapTransformMul; addGpuParameter = GpuParameters.normalMapTransformAdd; } else if( map == heightMap ) { mulGpuParameter = GpuParameters.heightMapTransformMul; addGpuParameter = GpuParameters.heightMapTransformAdd; } else { Log.Fatal( "ShaderBaseMaterial: Internal error (UpdateMapTransformGpuParameters)." ); return; } } //set parameters SetCustomGpuParameter( mulGpuParameter, new Vec4( matrix.Item0.X, matrix.Item0.Y, matrix.Item1.X, matrix.Item1.Y ), false, true, needForShadowCasterMaterial ); SetCustomGpuParameter( addGpuParameter, new Vec4( matrix.Item0.Z, matrix.Item1.Z, 0, 0 ), false, true, needForShadowCasterMaterial ); }
public AffineTransform3(Mat3 transform, Vec3 translation) { Transform = transform; Translation = translation; }
public override unsafe void Update(Mat3 matrix, int offset) { Orbital_Video_D3D12_ConstantBuffer_Update(handle, &matrix, (uint)Marshal.SizeOf <Mat3>(), (uint)offset, activeNodeIndex); }
public AffineTransform3(Vec3 translation) { Transform = Mat3.identity; Translation = translation; }
public void Init(string platformPath, string folder64Bit, string folder32Bit) { // pre-load native libs string libFolderBit; if (IntPtr.Size == 8) { libFolderBit = folder64Bit; } else if (IntPtr.Size == 4) { libFolderBit = folder32Bit; } else { throw new NotSupportedException("Unsupported bit size: " + IntPtr.Size.ToString()); } #if RELEASE const string config = "Release"; #else const string config = "Debug"; #endif // load api abstraction (api-instance and hardware-device) var abstractionDesc = new AbstractionDesc(AbstractionInitType.DefaultSingleGPU); abstractionDesc.supportedAPIs = new AbstractionAPI[] { AbstractionAPI.D3D12 }; abstractionDesc.deviceDescD3D12.window = window; //abstractionDesc.deviceDescD3D12.adapterIndex = 1; //abstractionDesc.deviceDescD3D12.vSyncMode = SwapChainVSyncMode.VSyncOff; abstractionDesc.nativeLibPathD3D12 = Path.Combine(platformPath, @"Shared\Orbital.Video.D3D12.Native\bin", libFolderBit, config); abstractionDesc.deviceDescVulkan.window = window; abstractionDesc.nativeLibPathVulkan = Path.Combine(platformPath, @"Shared\Orbital.Video.Vulkan.Native\bin", libFolderBit, config); if (!Abstraction.InitFirstAvaliable(abstractionDesc, out instance, out device)) { throw new Exception("Failed to init abstraction"); } // create render texture test objects renderTextureTest = new RenderTextureTest(device); // create msaa render texture if (!device.GetMaxMSAALevel(TextureFormat.Default, out var msaaLevel)) { throw new Exception("Failed to get MSAA level"); } msaaLevel = MSAALevel.Disabled; var windowSize = window.GetSize(WindowSizeType.WorkingArea); renderTextureMSAA = device.CreateRenderTexture2D(windowSize.width, windowSize.height, TextureFormat.Default, RenderTextureUsage.Discard, TextureMode.GPUOptimized, StencilUsage.Discard, DepthStencilFormat.DefaultDepth, DepthStencilMode.GPUOptimized, msaaLevel, false, MultiGPUNodeResourceVisibility.All); // create command list commandList = device.CreateRasterizeCommandList(); commandList_Compute = device.CreateComputeCommandList(); // create render pass var renderPassDesc = RenderPassDesc.CreateDefault(new Color4F(0, .2f, .4f, 1), 1); //renderPass = device.CreateRenderPass(renderPassDesc, device.swapChain.depthStencil); renderPass = renderTextureMSAA.CreateRenderPass(renderPassDesc, renderTextureMSAA.GetDepthStencil()); // create texture int textureWidth = 256, textureHeight = 256; var textureData = new byte[textureWidth * textureHeight * 4]; for (int y = 0; y != textureHeight; ++y) { for (int x = 0; x != textureWidth; ++x) { int i = (x * 4) + (y * textureWidth * 4); if (x % 16 <= 7 && y % 16 <= 7) { textureData[i + 0] = 0; textureData[i + 1] = 0; textureData[i + 2] = 0; textureData[i + 3] = 0; } else { textureData[i + 0] = 255; textureData[i + 1] = 255; textureData[i + 2] = 255; textureData[i + 3] = 255; } } } texture = device.CreateTexture2D(textureWidth, textureHeight, TextureFormat.B8G8R8A8, textureData, TextureMode.GPUOptimized, MultiGPUNodeResourceVisibility.Self); // create texture 2 textureWidth = 100; textureHeight = 100; textureData = new byte[textureWidth * textureHeight * 4]; for (int y = 0; y != textureHeight; ++y) { for (int x = 0; x != textureWidth; ++x) { int i = (x * 4) + (y * textureWidth * 4); if (x % 16 <= 7 && y % 16 <= 7) { textureData[i + 0] = 0; textureData[i + 1] = 0; textureData[i + 2] = 0; textureData[i + 3] = 0; } else { textureData[i + 0] = 255; textureData[i + 1] = 255; textureData[i + 2] = 255; textureData[i + 3] = 255; } } } texture2 = device.CreateTexture2D(textureWidth, textureHeight, TextureFormat.B8G8R8A8, textureData, TextureMode.GPUOptimized, MultiGPUNodeResourceVisibility.Self); // load shaders // TODO: load CS2X compiled ShaderEffect /*using (var stream = new FileStream("Shader.se", FileMode.Open, FileAccess.Read, FileShare.Read)) * { * shaderEffect = device.CreateShaderEffect(stream, ShaderEffectSamplerAnisotropy.Default); * }*/ using (var vsStream = new FileStream("Shaders\\Shader_D3D12.vs", FileMode.Open, FileAccess.Read, FileShare.Read)) using (var psStream = new FileStream("Shaders\\Shader_D3D12.ps", FileMode.Open, FileAccess.Read, FileShare.Read)) { var vs = new Video.D3D12.Shader((Video.D3D12.Device)device, ShaderType.VS); var ps = new Video.D3D12.Shader((Video.D3D12.Device)device, ShaderType.PS); if (!vs.Init(vsStream)) { throw new Exception("Failed to init VS shader"); } if (!ps.Init(psStream)) { throw new Exception("Failed to init PS shader"); } var desc = new ShaderEffectDesc(); desc.constantBuffers = new ShaderEffectConstantBuffer[1]; desc.constantBuffers[0] = new ShaderEffectConstantBuffer() { registerIndex = 0, usage = ShaderEffectResourceUsage.VS, variables = new ShaderVariable[2] }; desc.constantBuffers[0].variables[0] = new ShaderVariable() { name = "constrast", type = ShaderVariableType.Float }; desc.constantBuffers[0].variables[1] = new ShaderVariable() { name = "camera", type = ShaderVariableType.Float4x4 }; desc.textures = new ShaderEffectTexture[3]; desc.textures[0] = new ShaderEffectTexture() { registerIndex = 0, usage = ShaderEffectResourceUsage.PS }; desc.textures[1] = new ShaderEffectTexture() { registerIndex = 1, usage = ShaderEffectResourceUsage.PS }; desc.textures[2] = new ShaderEffectTexture() { registerIndex = 2, usage = ShaderEffectResourceUsage.PS }; desc.samplers = new ShaderEffectSampler[1]; desc.samplers[0] = new ShaderEffectSampler() { registerIndex = 0, filter = ShaderSamplerFilter.Default, anisotropy = ShaderSamplerAnisotropy.Default, addressU = ShaderSamplerAddress.Wrap, addressV = ShaderSamplerAddress.Wrap, addressW = ShaderSamplerAddress.Wrap, usage = ShaderEffectResourceUsage.PS }; shaderEffect = device.CreateShaderEffect(vs, ps, null, null, null, desc, true); } if (!shaderEffect.FindVariable("constrast", out shaderEffectVar_Constrast)) { throw new Exception("Failed to find shader effect variable"); } if (!shaderEffect.FindVariable("camera", out shaderEffectVar_Camera)) { throw new Exception("Failed to find shader effect variable"); } // create constant buffer constantBuffer = device.CreateConstantBuffer(shaderEffect.constantBufferMappings[0].size, ConstantBufferMode.Write); // create vertex buffer const float size = 1 / 2f; var rotUpAxisMat = Mat3.FromEuler(0, MathTools.DegToRad(90), 0); var rotRightAxisMat = Mat3.FromEuler(MathTools.DegToRad(90), 0, 0); var vertices = new Vertex[4 * 6]; // 4 vertices per face var indices = new ushort[6 * 6]; // 6 indices per face var colorKey = new Color4[4] { Color4.blue, Color4.red, Color4.white, Color4.white }; for (int v = 0, i = 0, r = 0; v < (4 * 4); v += 4, i += 6, ++r) // caluclate front, right, back, left faces { vertices[v + 0] = new Vertex(new Vec3(-size, -size, size), colorKey[r], new Vec2(0, 0)).Transform(rotUpAxisMat, r); vertices[v + 1] = new Vertex(new Vec3(-size, size, size), colorKey[r], new Vec2(0, 1)).Transform(rotUpAxisMat, r); vertices[v + 2] = new Vertex(new Vec3(size, size, size), colorKey[r], new Vec2(1, 1)).Transform(rotUpAxisMat, r); vertices[v + 3] = new Vertex(new Vec3(size, -size, size), colorKey[r], new Vec2(1, 0)).Transform(rotUpAxisMat, r); indices[i + 0] = (ushort)(v + 0); indices[i + 1] = (ushort)(v + 1); indices[i + 2] = (ushort)(v + 2); indices[i + 3] = (ushort)(v + 0); indices[i + 4] = (ushort)(v + 2); indices[i + 5] = (ushort)(v + 3); } colorKey = new Color4[2] { Color4.green, Color4.white }; for (int v = (4 * 4), i = (6 * 4), r = 1; v < (4 * 6); v += 4, i += 6, r = 3) // caluclate top, bottom faces { vertices[v + 0] = new Vertex(new Vec3(-size, -size, size), colorKey[r / 3], new Vec2(0, 0)).Transform(rotRightAxisMat, r); vertices[v + 1] = new Vertex(new Vec3(-size, size, size), colorKey[r / 3], new Vec2(0, 1)).Transform(rotRightAxisMat, r); vertices[v + 2] = new Vertex(new Vec3(size, size, size), colorKey[r / 3], new Vec2(1, 1)).Transform(rotRightAxisMat, r); vertices[v + 3] = new Vertex(new Vec3(size, -size, size), colorKey[r / 3], new Vec2(1, 0)).Transform(rotRightAxisMat, r); indices[i + 0] = (ushort)(v + 0); indices[i + 1] = (ushort)(v + 1); indices[i + 2] = (ushort)(v + 2); indices[i + 3] = (ushort)(v + 0); indices[i + 4] = (ushort)(v + 2); indices[i + 5] = (ushort)(v + 3); } vertexBuffer = device.CreateVertexBuffer <Vertex>(vertices, indices, VertexBufferMode.GPUOptimized); // create vertex buffer streamer var vertexBufferStreamLayout = new VertexBufferStreamLayout() { descs = new VertexBufferStreamDesc[1], elements = new VertexBufferStreamElement[3] }; vertexBufferStreamLayout.descs[0] = new VertexBufferStreamDesc() { vertexBuffer = vertexBuffer, type = VertexBufferStreamType.VertexData }; vertexBufferStreamLayout.elements[0] = new VertexBufferStreamElement() { type = VertexBufferStreamElementType.Float3, usage = VertexBufferStreamElementUsage.Position, offset = 0 }; vertexBufferStreamLayout.elements[1] = new VertexBufferStreamElement() { type = VertexBufferStreamElementType.RGBAx8, usage = VertexBufferStreamElementUsage.Color, offset = (sizeof(float) * 3) }; vertexBufferStreamLayout.elements[2] = new VertexBufferStreamElement() { type = VertexBufferStreamElementType.Float2, usage = VertexBufferStreamElementUsage.UV, offset = (sizeof(float) * 3) + 4 }; vertexBufferStreamer = device.CreateVertexBufferStreamer(vertexBufferStreamLayout); // create render state var renderStateDesc = new RenderStateDesc() { renderPass = renderPass, shaderEffect = shaderEffect, constantBuffers = new ConstantBufferBase[1], textures = new TextureBase[3], vertexBufferTopology = VertexBufferTopology.Triangle, vertexBufferStreamer = vertexBufferStreamer, triangleCulling = TriangleCulling.Back, triangleFillMode = TriangleFillMode.Solid, depthStencilDesc = DepthStencilDesc.StandardDepthTesting() }; //renderStateDesc.blendDesc.renderTargetBlendDescs = new RenderTargetBlendDesc[1] {RenderTargetBlendDesc.AlphaBlending()}; renderStateDesc.constantBuffers[0] = constantBuffer; renderStateDesc.textures[0] = texture; renderStateDesc.textures[1] = texture2; renderStateDesc.textures[2] = renderTextureTest.renderTexture; renderState = device.CreateRenderState(renderStateDesc); // create compute shader using (var csStream = new FileStream("Shaders\\Compute_D3D12.cs", FileMode.Open, FileAccess.Read, FileShare.Read)) { var csDesc = new ComputeShaderDesc() { randomAccessBuffers = new ComputeShaderRandomAccessBuffer[1] }; csDesc.randomAccessBuffers[0] = new ComputeShaderRandomAccessBuffer() { registerIndex = 0 }; computeShader = device.CreateComputeShader(csStream, csDesc); } // create compute state var computeStateDesc = new ComputeStateDesc() { computeShader = computeShader, randomAccessBuffers = new object[1] }; computeStateDesc.randomAccessBuffers[0] = renderTextureTest.renderTexture; computeState = device.CreateComputeState(computeStateDesc); // print all GPUs this abstraction supports if (!instance.QuerySupportedAdapters(false, out var adapters)) { throw new Exception("Failed: QuerySupportedAdapters"); } foreach (var adapter in adapters) { Debug.WriteLine(adapter.name); } // setup camera camera = new Camera(); }
public AffineTransform3(Quat orientation, Vec3 scale, Vec3 translation) { Transform = Mat3.FromQuaternion(orientation) * scale; Translation = translation; }
public TransformData(Mat4 model) { Model = model; InverseTransposeModel = new Mat3(model).Transpose.Inverse; }
public static float off(Mat3 a) { return(Mathf.Sqrt((a.m01 * a.m01) + (a.m02 * a.m02) + (a.m10 * a.m10) + (a.m12 * a.m12) + (a.m20 * a.m20) + (a.m21 * a.m21))); }
public Line3 Transform(Mat3 matrix) { return(new Line3(matrix.Transform(this.point1), matrix.Transform(this.point2))); }
public static float fnorm(Mat3 a) { return(Mathf.Sqrt((a.m00 * a.m00) + (a.m01 * a.m01) + (a.m02 * a.m02) + (a.m10 * a.m10) + (a.m11 * a.m11) + (a.m12 * a.m12) + (a.m20 * a.m20) + (a.m21 * a.m21) + (a.m22 * a.m22))); }
public abstract void Update(Mat3 matrix, ShaderVariableMapping variable);
public static void transpose(out Mat3 Out, Mat3 a) { Out = new Mat3(); Out.set(a.m00, a.m10, a.m20, a.m01, a.m11, a.m21, a.m02, a.m12, a.m22); }
void CreateDecalForStaticObject(ShapeTriangleID startTriangle, Vec3 pos, Vec3 normal, MapObject parentMapObject) { Shape currentShape = null; Mat4 shapeTransform = Mat4.Zero; Vec3[] shapeVertices = null; int[] shapeIndices = null; bool existsNormalsMore45Degrees = false; //find near triangles //Set<ShapeTriangleID> triangleIDs = new Set<ShapeTriangleID>(); { Sphere checkSphere = new Sphere(pos, Type.Size * .5f * 1.41f); //Sqrt(2) //Set<ShapeTriangleID> checkedTriangles = new Set<ShapeTriangleID>(); //Stack<ShapeTriangleID> trianglesForCheck = new Stack<ShapeTriangleID>( 16 ); trianglesForCheck.Push(startTriangle); while (trianglesForCheck.Count != 0) { ShapeTriangleID triangle = trianglesForCheck.Pop(); //add to checked triangles if (!checkedTriangles.AddWithCheckAlreadyContained(triangle)) { //ignore already checked triangles continue; } //get triangle points Vec3 p0, p1, p2; { if (currentShape != triangle.shape) { currentShape = triangle.shape; if (currentShape.ShapeType == Shape.Type.Mesh) { ((MeshShape)currentShape).GetData(out shapeVertices, out shapeIndices); } else if (currentShape.ShapeType == Shape.Type.HeightField) { ((HeightFieldShape)currentShape).GetVerticesAndIndices(true, out shapeVertices, out shapeIndices); } else { Log.Fatal("DecalCreator: Not supported shape type ({0}).", currentShape.ShapeType.ToString()); } shapeTransform = currentShape.Body.GetTransform(); if (!currentShape.IsIdentityTransform) { shapeTransform *= currentShape.GetTransform(); } } int index = triangle.triangleID * 3; p0 = shapeTransform * shapeVertices[shapeIndices[index + 0]]; p1 = shapeTransform * shapeVertices[shapeIndices[index + 1]]; p2 = shapeTransform * shapeVertices[shapeIndices[index + 2]]; } //cull by checkBounds if (!checkSphere.TriangleIntersection(p0, p1, p2)) { continue; } //check normal bool correctNormal = false; if (Type.SpreadType != DecalCreatorType.SpreadTypes.Directional) { Plane plane = Plane.FromPoints(p0, p1, p2); if (plane.GetSide(pos + normal) == Plane.Side.Positive) { Radian angle = MathFunctions.ACos(Vec3.Dot(normal, plane.Normal)); if (angle <= new Degree(70.0f).InRadians()) { if (!existsNormalsMore45Degrees && angle >= new Degree(45.0f).InRadians()) { existsNormalsMore45Degrees = true; } correctNormal = true; } } } else { correctNormal = true; } if (correctNormal) { //add triangle to result list triangleIDs.Add(triangle); } //add near triangles to check list { //expand vertices const float border = .001f; Vec3 center = (p0 + p1 + p2) * (1.0f / 3.0f); Vec3 diff0 = p0 - center; Vec3 diff1 = p1 - center; Vec3 diff2 = p2 - center; if (diff0 != Vec3.Zero && diff1 != Vec3.Zero && diff2 != Vec3.Zero) { p0 += diff0.GetNormalize() * border; p1 += diff1.GetNormalize() * border; p2 += diff2.GetNormalize() * border; Vec3 p01 = (p0 + p1) * .5f; Vec3 p12 = (p1 + p2) * .5f; Vec3 p20 = (p2 + p0) * .5f; //find triangles for (int n = 0; n < 3; n++) { Vec3 p = Vec3.Zero; switch (n) { case 0: p = p01; break; case 1: p = p12; break; case 2: p = p20; break; } RayCastResult[] piercingResult = PhysicsWorld.Instance.RayCastPiercing(new Ray( p + normal * .025f, -normal * .05f), (int)ContactGroup.CastOnlyCollision); foreach (RayCastResult result in piercingResult) { if (result.Shape != null) { trianglesForCheck.Push(new ShapeTriangleID( result.Shape, result.TriangleID)); } } } } } } checkedTriangles.Clear(); } if (triangleIDs.Count == 0) { return; } //calculate perpendiculars to normal Vec3 side1Normal; Vec3 side2Normal; { if (Math.Abs(normal.X) > .001f || Math.Abs(normal.Y) > .001f) { side1Normal = Mat3.FromRotateByZ(MathFunctions.PI / 2) * new Vec3(normal.X, normal.Y, 0); side1Normal.Normalize(); } else { side1Normal = new Vec3(1, 0, 0); } side2Normal = Vec3.Cross(normal, side1Normal); } //generate clip planes Plane[] clipPlanes = new Plane[6]; { float halfSize = Type.Size * .5f; if (existsNormalsMore45Degrees) { halfSize *= 1.41f; } Plane p; p = Plane.FromVectors(normal, -side2Normal, Position); clipPlanes[0] = new Plane(p.Normal, p.Distance + halfSize); p = Plane.FromVectors(normal, side2Normal, Position); clipPlanes[1] = new Plane(p.Normal, p.Distance + halfSize); p = Plane.FromVectors(normal, -side1Normal, Position); clipPlanes[2] = new Plane(p.Normal, p.Distance + halfSize); p = Plane.FromVectors(normal, side1Normal, Position); clipPlanes[3] = new Plane(p.Normal, p.Distance + halfSize); p = Plane.FromVectors(side1Normal, side2Normal, Position); clipPlanes[4] = new Plane(p.Normal, p.Distance + halfSize); //clipPlanes[ 4 ] = new Plane( p.Normal, p.Distance + halfSize * .5f ); p = Plane.FromVectors(side1Normal, -side2Normal, Position); clipPlanes[5] = new Plane(p.Normal, p.Distance + halfSize); //clipPlanes[ 5 ] = new Plane( p.Normal, p.Distance + halfSize * .5f ); } //generate vertices and indices by triangles //List<Decal.Vertex> vertices = new List<Decal.Vertex>( triangleIDs.Count * 3 ); //List<int> indices = new List<int>( triangleIDs.Count * 3 ); List <Decal.Vertex> vertices = tempVertices; List <int> indices = tempIndices; vertices.Clear(); indices.Clear(); { foreach (ShapeTriangleID triangle in triangleIDs) { Vec3 p0, p1, p2; { if (currentShape != triangle.shape) { currentShape = triangle.shape; if (currentShape.ShapeType == Shape.Type.Mesh) { ((MeshShape)currentShape).GetData(out shapeVertices, out shapeIndices); } else if (currentShape.ShapeType == Shape.Type.HeightField) { ((HeightFieldShape)currentShape).GetVerticesAndIndices(true, out shapeVertices, out shapeIndices); } else { Log.Fatal("DecalCreator: Not supported shape type ({0}).", currentShape.ShapeType.ToString()); } shapeTransform = currentShape.Body.GetTransform(); if (!currentShape.IsIdentityTransform) { shapeTransform *= currentShape.GetTransform(); } } int index = triangle.triangleID * 3; p0 = shapeTransform * shapeVertices[shapeIndices[index + 0]]; p1 = shapeTransform * shapeVertices[shapeIndices[index + 1]]; p2 = shapeTransform * shapeVertices[shapeIndices[index + 2]]; } List <Vec3> list = new List <Vec3>(); list.Add(p0); list.Add(p1); list.Add(p2); //clip by planes foreach (Plane plane in clipPlanes) { list = CutConvexPlanePolygonByPlane(list, plane); if (list == null) { break; } } //add to vertices and indices lists if (list != null) { int vertexCount = vertices.Count; Vec3 norm = Plane.FromPoints(p0, p1, p2).Normal; foreach (Vec3 p in list) { vertices.Add(new Decal.Vertex(p, norm, Vec2.Zero, Vec3.Zero)); } for (int n = 1; n < list.Count - 1; n++) { indices.Add(vertexCount); indices.Add(vertexCount + n); indices.Add(vertexCount + n + 1); } } } } triangleIDs.Clear(); if (indices.Count == 0) { return; } //calculate texCoord and Type.DepthRenderOffset { Plane planeSide1 = Plane.FromVectors(normal, side1Normal, Position); Plane planeSide2 = Plane.FromVectors(normal, side2Normal, Position); float invSize = 1.0f / Type.Size; for (int n = 0; n < vertices.Count; n++) { Decal.Vertex vertex = vertices[n]; //calculate texCoord float distance1 = planeSide1.GetDistance(vertex.position); float distance2 = planeSide2.GetDistance(vertex.position); vertex.texCoord = new Vec2(distance1 * invSize + .5f, distance2 * invSize + .5f); //add Type.DepthRenderOffset vertex.position = vertex.position + normal * Type.DepthRenderOffset; vertices[n] = vertex; } } //calculate tangent vectors { int triangleCount = indices.Count / 3; for (int nTriangle = 0; nTriangle < triangleCount; nTriangle++) { int index0 = indices[nTriangle * 3 + 0]; int index1 = indices[nTriangle * 3 + 1]; int index2 = indices[nTriangle * 3 + 2]; Decal.Vertex vertex0 = vertices[index0]; Decal.Vertex vertex1 = vertices[index1]; Decal.Vertex vertex2 = vertices[index2]; Vec3 tangent = MathUtils.CalculateTangentSpaceVector( vertex0.position, vertex0.texCoord, vertex1.position, vertex1.texCoord, vertex2.position, vertex2.texCoord); vertex0.tangent += tangent; vertex1.tangent += tangent; vertex2.tangent += tangent; vertices[index0] = vertex0; vertices[index1] = vertex1; vertices[index2] = vertex2; } for (int n = 0; n < vertices.Count; n++) { Decal.Vertex vertex = vertices[n]; if (vertex.tangent != Vec3.Zero) { vertex.tangent.Normalize(); } vertices[n] = vertex; } } //subtract decal position (make local vertices coordinates) { for (int n = 0; n < vertices.Count; n++) { Decal.Vertex vertex = vertices[n]; vertex.position -= Position; vertices[n] = vertex; } } //get material string materialName = null; { string physicsMaterialName = startTriangle.shape.MaterialName; string defaultMaterialName = ""; foreach (DecalCreatorType.MaterialItem item in Type.Materials) { if (item.PhysicsMaterialName == physicsMaterialName) { materialName = item.MaterialName; } if (string.IsNullOrEmpty(item.PhysicsMaterialName)) { defaultMaterialName = item.MaterialName; } } if (materialName == null) { materialName = defaultMaterialName; } } //create Decal Decal decal = (Decal)Entities.Instance.Create("Decal", Map.Instance); decal.Position = Position; decal.Init(this, vertices.ToArray(), indices.ToArray(), materialName, parentMapObject); decal.PostCreate(); Type.AddDecalToCreatedList(decal); decals.Add(decal); }
private void UpdateMapCamera() { //Camera with Updated Values MatrixFrame mapCamera = ComputeMapCamera(ref this._cameraTarget, this._cameraBearing, this._cameraElevation, this.CameraDistance, ref this._lastUsedIdealCameraTarget); //Bools bool positionChanged = !mapCamera.origin.NearlyEquals(this._cameraFrame.origin, 1E-05f); bool rotationChanged = !mapCamera.rotation.NearlyEquals(this._cameraFrame.rotation, 1E-05f); //IDK If I can currnetly Handle this? if (rotationChanged | positionChanged) { Game.Current.EventManager.TriggerEvent <MainMapCameraMoveEvent>(new MainMapCameraMoveEvent(rotationChanged, positionChanged)); } //Sets Camera Frame this._cameraFrame = mapCamera; float height1 = 0.0f; //Gets Height at a Position? this.Mission.Scene.GetHeightAtPoint(this._cameraFrame.origin.AsVec2, BodyFlags.CommonCollisionExcludeFlagsForMissile, ref height1); float height2 = height1 + 0.5f; ///Updates Camera Left Drag if ((double)this._cameraFrame.origin.z < (double)height2) { //Checks if ButtonDragginMode is On!!!!!! Breakpoint here if (this._leftButtonDraggingMode) { //Does some Math Magic Vec3 clickedPosition = this._clickedPosition; Vec3 vec3_1 = clickedPosition - Vec3.DotProduct(clickedPosition - this._cameraFrame.origin, this._cameraFrame.rotation.s) * this._cameraFrame.rotation.s; Vec3 va = (vec3_1 - this._cameraFrame.origin).NormalizedCopy(); Vec3 vec3_2 = vec3_1 - (this._cameraFrame.origin + new Vec3(0.0f, 0.0f, height2 - this._cameraFrame.origin.z, -1f)); Vec3 vb = vec3_2.NormalizedCopy(); Vec3 vec = Vec3.CrossProduct(va, vb); float a = vec.Normalize(); this._cameraFrame.origin.z = height2; this._cameraFrame.rotation.u = this._cameraFrame.rotation.u.RotateAboutAnArbitraryVector(vec, a); ref Mat3 local = ref this._cameraFrame.rotation; vec3_2 = Vec3.CrossProduct(this._cameraFrame.rotation.u, this._cameraFrame.rotation.s); Vec3 vec3_3 = vec3_2.NormalizedCopy(); local.f = vec3_3; this._cameraFrame.rotation.s = Vec3.CrossProduct(this._cameraFrame.rotation.f, this._cameraFrame.rotation.u); Vec3 planeNormal = -Vec3.Up; Vec3 rayDirection = -this._cameraFrame.rotation.u; float t; //Do I need idealCameraTarget? if (MBMath.GetRayPlaneIntersectionPoint(ref planeNormal, ref this._idealCameraTarget, ref this._cameraFrame.origin, ref rayDirection, out t)) { this._idealCameraTarget = this._cameraFrame.origin + rayDirection * t; this._cameraTarget = this._idealCameraTarget; } // Sets cameraElevation and CameraDistance Vec2 vec2 = this._cameraFrame.rotation.f.AsVec2; vec2 = new Vec2(vec2.Length, this._cameraFrame.rotation.f.z); this._cameraElevation = -vec2.RotationInRadians; vec3_2 = this._cameraFrame.origin - this._idealCameraTarget; this.CameraDistance = vec3_2.Length - 2f; this._targetCameraDistance = this.CameraDistance; this._additionalElevation = this._cameraElevation - CalculateCameraElevation(this.CameraDistance); this._lastUsedIdealCameraTarget = this._idealCameraTarget.AsVec2; ComputeMapCamera(ref this._cameraTarget, this._cameraBearing, this._cameraElevation, this.CameraDistance, ref this._lastUsedIdealCameraTarget); } else { float num1 = 0.4712389f; int num2 = 0; do { this._cameraElevation += (double)this._cameraFrame.origin.z < (double)height2 ? num1 : -num1; this._additionalElevation = this._cameraElevation - CalculateCameraElevation(this.CameraDistance); float val1_1 = 700f; float num3 = (Campaign.Current.UseFreeCameraAtMapScreen ? 1f : 0.3f) / val1_1; float val1_2 = 50f; float minValue = (float)-((double)val1_1 - (double)Math.Min(val1_1, Math.Max(val1_2, this.CameraDistance))) * num3; float maxValue = Math.Max(minValue + 1E-05f, 1.555088f - CalculateCameraElevation(this.CameraDistance)); this._additionalElevation = MBMath.ClampFloat(this._additionalElevation, minValue, maxValue); this._cameraElevation = this._additionalElevation + CalculateCameraElevation(this.CameraDistance); Vec2 zero = Vec2.Zero; this._cameraFrame = ComputeMapCamera(ref this._cameraTarget, this._cameraBearing, this._cameraElevation, this.CameraDistance, ref zero); this.Mission.Scene.GetHeightAtPoint(this._cameraFrame.origin.AsVec2, BodyFlags.CommonCollisionExcludeFlagsForMissile, ref height2); height2 += 0.5f; if ((double)num1 > 9.99999974737875E-05) { num1 *= 0.5f; } else { ++num2; } }while ((double)num1 > 9.99999974737875E-05 || (double)this._cameraFrame.origin.z < (double)height2 && num2 < 5); if ((double)this._cameraFrame.origin.z < (double)height2) { this._cameraFrame.origin.z = height2; Vec3 planeNormal = -Vec3.Up; Vec3 rayDirection = -this._cameraFrame.rotation.u; float t; if (MBMath.GetRayPlaneIntersectionPoint(ref planeNormal, ref this._idealCameraTarget, ref this._cameraFrame.origin, ref rayDirection, out t)) { this._idealCameraTarget = this._cameraFrame.origin + rayDirection * t; this._cameraTarget = this._idealCameraTarget; } this.CameraDistance = (this._cameraFrame.origin - this._idealCameraTarget).Length - 2f; this._lastUsedIdealCameraTarget = this._idealCameraTarget.AsVec2; ComputeMapCamera(ref this._cameraTarget, this._cameraBearing, this._cameraElevation, this.CameraDistance, ref this._lastUsedIdealCameraTarget); } } }
public UniformMat3(Mat3 matrix) { this.matrix = matrix; }
protected virtual void CreateBullet(Mode mode) { Bullet obj = (Bullet)Entities.Instance.Create(mode.typeMode.BulletType, Parent); obj.SourceUnit = GetParentUnitHavingIntellect(); obj.Position = GetFirePosition(mode.typeMode); //Correcting position at a shot in very near object (when the point of a shot inside object). { Vec3 startPos = Position; if (AttachedMapObjectParent != null) { startPos = AttachedMapObjectParent.Position; } Ray ray = new Ray(startPos, obj.Position - startPos); if (ray.Direction != Vec3.Zero) { RayCastResult[] piercingResult = PhysicsWorld.Instance.RayCastPiercing( ray, (int)ContactGroup.CastOnlyContact); foreach (RayCastResult result in piercingResult) { MapObject mapObject = MapSystemWorld.GetMapObjectByBody(result.Shape.Body); if (mapObject != null) { if (mapObject == this) { continue; } if (mapObject == this.AttachedMapObjectParent) { continue; } } obj.Position = result.Position - ray.Direction * .01f; break; } } } Quat rot = GetFireRotation(mode.typeMode); Radian dispersionAngle = mode.typeMode.DispersionAngle; if (dispersionAngle != 0) { EngineRandom random = World.Instance.Random; Mat3 matrix; matrix = Mat3.FromRotateByX(random.NextFloat() * MathFunctions.PI * 2); matrix *= Mat3.FromRotateByZ(random.NextFloat() * dispersionAngle); rot *= matrix.ToQuat(); } obj.Rotation = rot; obj.PostCreate(); //set damage coefficient float coef = obj.DamageCoefficient; Unit unit = GetParentUnitHavingIntellect(); if (unit != null && unit.BigDamageInfluence != null) { coef *= unit.BigDamageInfluence.Type.Coefficient; } obj.DamageCoefficient = coef; }
public override void Update(Mat3 matrix, ShaderVariableMapping variable) { throw new NotImplementedException(); }
public void set(Mat3 rhs) { this.set(rhs.m00, rhs.m01, rhs.m02, rhs.m10, rhs.m11, rhs.m12, rhs.m20, rhs.m21, rhs.m22); }