/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> private World() { this.Flags = WorldFlags.ClearForces; this.BodyList = new List <Body>(32); this.JointList = new List <Joint>(32); }
// Start is called before the first frame update void Start() { if (DebugMode) { wf = WorldFlags.AllWF; } else { //ワールドのクリアデータを取得 wf = (WorldFlags)PlayerPrefs.GetInt("WORLD_FLAG", 0); } //フェードパネルとUIの親取得 FadeObj = GameObject.Find("FadePanel").GetComponent <FadeManager>(); //無条件解放 worlds[0].GetComponent <WorUnl>().SetUnlockFlg(true); //ワールド名設定 WorldNumText.text = "World-" + (NowSelWorld + 1).ToString(); WorldNameText.text = worlds[NowSelWorld].GetComponent <WorUnl>().GetWorldName(); //サウンド Source = GetComponent <AudioSource>(); }
public override void NetReceive(BinaryReader reader) { flags = (WorldFlags)reader.ReadInt32(); VitricBiome = ReadRectangle(reader); SquidBossArena = ReadRectangle(reader); }
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> private World() { Flags = WorldFlags.ClearForces; ControllerList = new List <Controller>(); BreakableBodyList = new List <BreakableBody>(); BodyList = new List <Body>(32); JointList = new List <Joint>(32); }
public override void Load(TagCompound tag) { VitricBiome.X = (int)tag.Get <Vector2>("VitricBiomePos").X; VitricBiome.Y = (int)tag.Get <Vector2>("VitricBiomePos").Y; VitricBiome.Width = (int)tag.Get <Vector2>("VitricBiomeSize").X; VitricBiome.Height = (int)tag.Get <Vector2>("VitricBiomeSize").Y; SquidNPCProgress = tag.GetInt("SquidNPCProgress"); SquidBossArena.X = (int)tag.Get <Vector2>("SquidBossArenaPos").X; SquidBossArena.Y = (int)tag.Get <Vector2>("SquidBossArenaPos").Y; SquidBossArena.Width = (int)tag.Get <Vector2>("SquidBossArenaSize").X; SquidBossArena.Height = (int)tag.Get <Vector2>("SquidBossArenaSize").Y; permafrostCenter = tag.GetInt("PermafrostCenter"); flags = (WorldFlags)tag.GetInt(nameof(flags)); TagCompound tag1 = tag.GetCompound(nameof(TownUpgrades)); Dictionary <string, bool> targetDict = new Dictionary <string, bool>(); foreach (KeyValuePair <string, object> pair in tag1) { targetDict.Add(pair.Key, tag1.GetBool(pair.Key)); } TownUpgrades = targetDict; PureTiles = (List <Vector2>)tag.GetList <Vector2>(nameof(PureTiles)); RiftLocation = tag.Get <Vector2>(nameof(RiftLocation)); Chungus = tag.GetFloat("Chungus"); Chungus += 0.01f; knownRecipies = (List <string>)tag.GetList <string>("Recipies"); for (int k = 0; k <= PureTiles.Count - 1; k++) { for (int i = (int)PureTiles[k].X - 16; i <= (int)PureTiles[k].X + 16; i++) { for (int j = (int)PureTiles[k].Y - 16; j <= (int)PureTiles[k].Y + 16; j++) { PurifyTransformation.RevertTile(i, j); } } } PureTiles.Clear(); foreach (Key key in KeyInventory) { Content.GUI.KeyInventory.keys.Add(new Content.GUI.KeyIcon(key, false)); } //setup overlays cathedralOverlay = new Cutaway(GetTexture("StarlightRiver/Assets/Bosses/SquidBoss/CathedralOver"), SquidBossArena.TopLeft() * 16); }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and constraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> /// <param name="velocityIterations">For the velocity constraint solver.</param> /// <param name="positionIteration">For the positionconstraint solver.</param> public void Step(float dt, int velocityIterations, int positionIteration) { int height; height = _contactManager._broadPhase.ComputeHeight(); // If new fixtures were added, we need to find the new contacts. if ((_flags & WorldFlags.NewFixture) != 0) { _contactManager.FindNewContacts(); _flags &= ~WorldFlags.NewFixture; } _flags |= WorldFlags.Locked; TimeStep step = new TimeStep(); step.Dt = dt; step.VelocityIterations = velocityIterations; step.PositionIterations = positionIteration; if (dt > 0.0f) { step.Inv_Dt = 1.0f / dt; } else { step.Inv_Dt = 0.0f; } step.DtRatio = _inv_dt0 * dt; step.WarmStarting = _warmStarting; // Update contacts. This is where some contacts are destroyed. _contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.Dt > 0.0f) { Solve(step); } // Handle TOI events. if (_continuousPhysics && step.Dt > 0.0f) { SolveTOI(step); } if (step.Dt > 0.0f) { _inv_dt0 = step.Inv_Dt; } _flags &= ~WorldFlags.Locked; }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and consraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> public void Step(float dt) { ProcessChanges(); //If there is no change in time, no need to calculate anything. if (dt == 0 || !Enabled) { return; } // If new fixtures were added, we need to find the new contacts. if ((Flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { ContactManager.FindNewContacts(); Flags &= ~WorldFlags.NewFixture; } TimeStep step; step.inv_dt = 1.0f / dt; step.dt = dt; step.dtRatio = _invDt0 * dt; //Update controllers for (int i = 0; i < ControllerList.Count; i++) { ControllerList[i].Update(dt); } // Update contacts. This is where some contacts are destroyed. ContactManager.Collide(); // Integrate velocities, solve velocity raints, and integrate positions. Solve(ref step); // Handle TOI events. if (Settings.ContinuousPhysics) { SolveTOI(ref step); } _invDt0 = step.inv_dt; if ((Flags & WorldFlags.ClearForces) != 0) { ClearForces(); } for (int i = 0; i < BreakableBodyList.Count; i++) { BreakableBodyList[i].Update(); } }
public bool GrantFlag(ServerPlayer player, FlagInstance flag) { if (flag.Owner != null || player.Info.CariedFlag != null) { return(false); } OnGrantFlag?.Invoke(player, flag); FlagEventArgs args = new FlagEventArgs(); args.Player = player; args.Flag = flag; FlagPreGrab?.Invoke(this, args); if (flag.Status == FlagStatuses.FlagNoExist) { return(false); } lock (ActiveFlags) { if (!args.Allow || flag.Owner != null) { return(false); } lock (WorldFlags) WorldFlags.Remove(flag.FlagID); lock (CarriedFlags) CarriedFlags.Add(flag.FlagID, flag); flag.Owner = player; flag.Status = FlagStatuses.FlagOnTank; flag.OwnerID = player.PlayerID; } FlagGrabbed?.Invoke(this, flag); player.Info.CariedFlag = flag; MsgGrabFlag grabMessage = new MsgGrabFlag(); grabMessage.PlayerID = player.PlayerID; grabMessage.FlagData = flag; Logger.Log2("Player " + player.Callsign + " granted flag " + flag.FlagID.ToString() + " " + flag.ToString()); Players.SendToAll(grabMessage, false); return(true); }
public override void NetReceive(BinaryReader reader) { flags = (WorldFlags)reader.ReadInt32(); VitricBiome = ReadRectangle(reader); SquidBossArena = ReadRectangle(reader); if (CutawayHandler.cutaways.Count == 0) { CreateCutaways(); } ReadNPCUpgrades(reader); }
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> /// <param name="gravity">The gravity.</param> public World(Vector2 gravity) { ContactManager = new ContactManager(); Gravity = gravity; Flags = WorldFlags.ClearForces; _queryAABBCallbackWrapper = QueryAABBCallbackWrapper; _rayCastCallbackWrapper = RayCastCallbackWrapper; Controllers = new List <Controller>(); BreakableBodyList = new List <BreakableBody>(); BodyList = new List <Body>(32); JointList = new List <Joint>(32); }
internal World(string name, WorldFlags flags) { Systems = new NoAllocReadOnlyCollection <ComponentSystemBase>(m_Systems); m_SequenceNumber = ms_NextSequenceNumber; ms_NextSequenceNumber++; // Debug.LogError("Create World "+ name + " - " + GetHashCode()); Name = name; Flags = flags; s_AllWorlds.Add(this); m_EntityManager = new EntityManager(this); m_TimeSingletonQuery = EntityManager.CreateEntityQuery(ComponentType.ReadWrite <WorldTime>(), ComponentType.ReadWrite <WorldTimeQueue>()); }
//クリアフラグとアンロックフラグのチェック private void FlgCheck(WorldFlags wf) { //World_1クリア済み if ((wf & WorldFlags.World_1) == WorldFlags.World_1) { worlds[0].GetComponent <WorUnl>().SetClearFlg(true); worlds[1].GetComponent <WorUnl>().SetUnlockFlg(true); } else { worlds[0].GetComponent <WorUnl>().SetClearFlg(false); worlds[1].GetComponent <WorUnl>().SetUnlockFlg(false); } //World_2クリア済み if ((wf & WorldFlags.World_2) == WorldFlags.World_2) { worlds[1].GetComponent <WorUnl>().SetClearFlg(true); worlds[2].GetComponent <WorUnl>().SetUnlockFlg(true); } else { worlds[1].GetComponent <WorUnl>().SetClearFlg(false); worlds[2].GetComponent <WorUnl>().SetUnlockFlg(false); } //World_3クリア済み if ((wf & WorldFlags.World_3) == WorldFlags.World_3) { worlds[2].GetComponent <WorUnl>().SetClearFlg(true); worlds[3].GetComponent <WorUnl>().SetUnlockFlg(true); } else { worlds[2].GetComponent <WorUnl>().SetClearFlg(false); worlds[3].GetComponent <WorUnl>().SetUnlockFlg(false); } //World_4クリア済み if ((wf & WorldFlags.World_4) == WorldFlags.World_4) { worlds[3].GetComponent <WorUnl>().SetClearFlg(true); } else { worlds[3].GetComponent <WorUnl>().SetClearFlg(false); } }
internal WorldUnmanagedImpl(ulong sequenceNumber, WorldFlags flags) { CurrentTime = default; #if ENABLE_UNITY_COLLECTIONS_CHECKS AllowGetSystem = true; #endif SequenceNumber = sequenceNumber; MaximumDeltaTime = 1.0f / 3.0f; Flags = flags; _unmanagedSlotByTypeHash = new UnsafeMultiHashMap <long, ushort>(32, Allocator.Persistent); _pendingDestroys = new UnsafeList <ushort>(32, Allocator.Persistent); _stateMemory = default; _stateMemory.Init(); Version = 0; ExecutingSystem = default; }
public void EditorLoadSettings() { if (!Manager.IsAwake <Mods>()) { Manager.WakeUp <Mods>("__MODS"); } Mods.Get.EditorCurrentWorldName = EditorCurrentWorldName; Mods.Get.Editor.InitializeEditor(); WorldFlags.Clear(); WorldStartupPositions.Clear(); Biomes.Clear(); Regions.Clear(); AudioProfiles.Clear(); string errorMessage = string.Empty; GameData.IO.LoadWorld(ref Settings, EditorCurrentWorldName, out errorMessage); GameData.IO.SetWorldName(Settings.Name); if (SaveFlags) { Mods.Get.Editor.LoadAvailableMods <FlagSet>(WorldFlags, "FlagSet"); } if (SaveBiomes) { Mods.Get.Editor.LoadAvailableMods <Biome>(Biomes, "Biome"); } if (SaveRegions) { Mods.Get.Editor.LoadAvailableMods <Region>(Regions, "Region"); } if (SaveAudio) { Mods.Get.Editor.LoadAvailableMods <AudioProfile>(AudioProfiles, "AudioProfile"); } if (SaveStartupPositions) { Mods.Get.Editor.LoadAvailableMods <PlayerStartupPosition>(WorldStartupPositions, "PlayerStartupPosition"); } UnityEditor.EditorUtility.SetDirty(gameObject); UnityEditor.EditorUtility.SetDirty(this); }
public WorldStruct_0001 Read(BinaryReader binaryReader) { sectionIdentifier = Section.Struct; sectionSize = binaryReader.ReadInt32(); renderWareVersion = binaryReader.ReadInt32(); long startSectionPosition = binaryReader.BaseStream.Position; if (sectionSize == 0x40) { rootIsWorldSector = binaryReader.ReadInt32(); inverseOrigin.X = binaryReader.ReadSingle(); inverseOrigin.Y = binaryReader.ReadSingle(); inverseOrigin.Z = binaryReader.ReadSingle(); numTriangles = binaryReader.ReadUInt32(); numVertices = binaryReader.ReadUInt32(); numPlaneSectors = binaryReader.ReadUInt32(); numAtomicSectors = binaryReader.ReadUInt32(); colSectorSize = binaryReader.ReadUInt32(); worldFlags = (WorldFlags)binaryReader.ReadUInt32(); boxMaximum = new Vertex3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()); boxMinimum = new Vertex3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()); } else if (sectionSize == 0x34) { rootIsWorldSector = binaryReader.ReadInt32(); inverseOrigin.X = binaryReader.ReadSingle(); inverseOrigin.Y = binaryReader.ReadSingle(); inverseOrigin.Z = binaryReader.ReadSingle(); boxMaximum = new Vertex3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()); boxMinimum = boxMaximum; numTriangles = binaryReader.ReadUInt32(); numVertices = binaryReader.ReadUInt32(); numPlaneSectors = binaryReader.ReadUInt32(); numAtomicSectors = binaryReader.ReadUInt32(); colSectorSize = binaryReader.ReadUInt32(); worldFlags = (WorldFlags)binaryReader.ReadUInt32(); } binaryReader.BaseStream.Position = startSectionPosition + sectionSize; return(this); }
public void DropFlag(ServerPlayer player) { if (player == null || player.Info.CariedFlag == null) { return; } if (player.Info.CariedFlag.Flag == FlagTypeList.Identify) { player.SendMessage(new MsgNearFlag()); // send them an empty ID message to clear out the display } FlagInstance flag = player.Info.CariedFlag; ComputeFlagDrop?.Invoke(player, flag); MsgDropFlag drop = new MsgDropFlag(); drop.FlagID = flag.FlagID; drop.PlayerID = player.PlayerID; drop.Data = flag; player.Info.CariedFlag = null; flag.Owner = null; Players.SendToAll(drop, false); lock (CarriedFlags) { if (CarriedFlags.ContainsKey(flag.FlagID)) { CarriedFlags.Remove(flag.FlagID); } } lock (WorldFlags) WorldFlags.Add(flag.FlagID, flag); FlagDropped?.Invoke(this, flag); }
public override void Initialize() { VitricBiome.X = 0; VitricBiome.Y = 0; flags = default; TownUpgrades = new Dictionary <string, bool>(); knownRecipies = new List <string>(); //Autoload NPC upgrades Mod mod = StarlightRiver.Instance; if (mod.Code != null) { foreach (Type type in mod.Code.GetTypes().Where(t => t.IsSubclassOf(typeof(TownUpgrade)))) { TownUpgrades.Add(type.Name.Replace("Upgrade", ""), false); } } PureTiles = new List <Vector2>(); }
/// <summary> /// Construct a world object. /// </summary> /// <param name="gravity">The world gravity vector.</param> /// <param name="doSleep">Improve performance by not simulating inactive bodies.</param> public World(Vec2 gravity, bool doSleep) { _destructionListener = null; _debugDraw = null; _bodyList = null; _jointList = null; _bodyCount = 0; _jointCount = 0; _warmStarting = true; _continuousPhysics = true; _allowSleep = doSleep; _gravity = gravity; _flags = 0; _inv_dt0 = 0.0f; _contactManager = new ContactManager(); }
/// <summary> /// Find TOI contacts and solve them. /// </summary> /// <param name="step">The step.</param> private void SolveTOI(ref TimeStep step) { this.Island.Reset(2 * Settings.MaxTOIContacts, Settings.MaxTOIContacts, 0, this.ContactManager); if (this._stepComplete) { for (int i = 0; i < this.BodyList.Count; i++) { this.BodyList[i].Flags &= ~BodyFlags.Island; this.BodyList[i].Sweep.Alpha0 = 0.0f; } for (int i = 0; i < this.ContactManager.ContactList.Count; i++) { Contact c = this.ContactManager.ContactList[i]; // Invalidate TOI c.Flags &= ~(ContactFlags.TOI | ContactFlags.Island); c.TOICount = 0; c.TOI = 1.0f; } } // Find TOI events and solve them. for (; ;) { // Find the first TOI. Contact minContact = null; float minAlpha = 1.0f; for (int i = 0; i < this.ContactManager.ContactList.Count; i++) { Contact c = this.ContactManager.ContactList[i]; // Is this contact disabled? if (c.Enabled == false) { continue; } // Prevent excessive sub-stepping. if (c.TOICount > Settings.MaxSubSteps) { continue; } float alpha; if ((c.Flags & ContactFlags.TOI) == ContactFlags.TOI) { // This contact has a valid cached TOI. alpha = c.TOI; } else { Fixture fA = c.FixtureA; Fixture fB = c.FixtureB; // Is there a sensor? if (fA.IsSensor || fB.IsSensor) { continue; } Body bA = fA.Body; Body bB = fB.Body; BodyType typeA = bA.BodyType; BodyType typeB = bB.BodyType; Debug.Assert(typeA == BodyType.Dynamic || typeB == BodyType.Dynamic); bool awakeA = bA.Awake && typeA != BodyType.Static; bool awakeB = bB.Awake && typeB != BodyType.Static; // Is at least one body awake? if (awakeA == false && awakeB == false) { continue; } bool collideA = (bA.IsBullet || typeA != BodyType.Dynamic) && !bA.IgnoreCCD; bool collideB = (bB.IsBullet || typeB != BodyType.Dynamic) && !bB.IgnoreCCD; // Are these two non-bullet dynamic bodies? if (collideA == false && collideB == false) { continue; } // Compute the TOI for this contact. // Put the sweeps onto the same time interval. float alpha0 = bA.Sweep.Alpha0; if (bA.Sweep.Alpha0 < bB.Sweep.Alpha0) { alpha0 = bB.Sweep.Alpha0; bA.Sweep.Advance(alpha0); } else if (bB.Sweep.Alpha0 < bA.Sweep.Alpha0) { alpha0 = bA.Sweep.Alpha0; bB.Sweep.Advance(alpha0); } Debug.Assert(alpha0 < 1.0f); // Compute the time of impact in interval [0, minTOI] this._input.ProxyA.Set(fA.Shape, c.ChildIndexA); this._input.ProxyB.Set(fB.Shape, c.ChildIndexB); this._input.SweepA = bA.Sweep; this._input.SweepB = bB.Sweep; this._input.TMax = 1.0f; TOIOutput output; TimeOfImpact.CalculateTimeOfImpact(out output, this._input); // Beta is the fraction of the remaining portion of the . float beta = output.T; if (output.State == TOIOutputState.Touching) { alpha = Math.Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); } else { alpha = 1.0f; } c.TOI = alpha; c.Flags |= ContactFlags.TOI; } if (alpha < minAlpha) { // This is the minimum TOI found so far. minContact = c; minAlpha = alpha; } } if (minContact == null || 1.0f - 10.0f * Settings.Epsilon < minAlpha) { // No more TOI events. Done! this._stepComplete = true; break; } // Advance the bodies to the TOI. Fixture fA1 = minContact.FixtureA; Fixture fB1 = minContact.FixtureB; Body bA1 = fA1.Body; Body bB1 = fB1.Body; Sweep backup1 = bA1.Sweep; Sweep backup2 = bB1.Sweep; bA1.Advance(minAlpha); bB1.Advance(minAlpha); // The TOI contact likely has some new contact points. minContact.Update(this.ContactManager); minContact.Flags &= ~ContactFlags.TOI; ++minContact.TOICount; // Is the contact solid? if (minContact.Enabled == false || minContact.IsTouching() == false) { // Restore the sweeps. minContact.Enabled = false; bA1.Sweep = backup1; bB1.Sweep = backup2; bA1.SynchronizeTransform(); bB1.SynchronizeTransform(); continue; } bA1.Awake = true; bB1.Awake = true; // Build the island this.Island.Clear(); this.Island.Add(bA1); this.Island.Add(bB1); this.Island.Add(minContact); bA1.Flags |= BodyFlags.Island; bB1.Flags |= BodyFlags.Island; minContact.Flags |= ContactFlags.Island; // Get contacts on bodyA and bodyB. Body[] bodies = { bA1, bB1 }; for (int i = 0; i < 2; ++i) { Body body = bodies[i]; if (body.BodyType == BodyType.Dynamic) { // for (ContactEdge ce = body.ContactList; ce && Island.BodyCount < Settings.MaxTOIContacts; ce = ce.Next) for (ContactEdge ce = body.ContactList; ce != null; ce = ce.Next) { Contact contact = ce.Contact; // Has this contact already been added to the island? if ((contact.Flags & ContactFlags.Island) == ContactFlags.Island) { continue; } // Only add static, kinematic, or bullet bodies. Body other = ce.Other; if (other.BodyType == BodyType.Dynamic && body.IsBullet == false && other.IsBullet == false) { continue; } // Skip sensors. if (contact.FixtureA.IsSensor || contact.FixtureB.IsSensor) { continue; } // Tentatively advance the body to the TOI. Sweep backup = other.Sweep; if ((other.Flags & BodyFlags.Island) == 0) { other.Advance(minAlpha); } // Update the contact points contact.Update(this.ContactManager); // Was the contact disabled by the user? if (contact.Enabled == false) { other.Sweep = backup; other.SynchronizeTransform(); continue; } // Are there contact points? if (contact.IsTouching() == false) { other.Sweep = backup; other.SynchronizeTransform(); continue; } // Add the contact to the island contact.Flags |= ContactFlags.Island; this.Island.Add(contact); // Has the other body already been added to the island? if ((other.Flags & BodyFlags.Island) == BodyFlags.Island) { continue; } // Add the other body to the island. other.Flags |= BodyFlags.Island; if (other.BodyType != BodyType.Static) { other.Awake = true; } this.Island.Add(other); } } } TimeStep subStep; subStep.dt = (1.0f - minAlpha) * step.dt; subStep.inv_dt = 1.0f / subStep.dt; subStep.dtRatio = 1.0f; //subStep.positionIterations = 20; //subStep.velocityIterations = step.velocityIterations; //subStep.warmStarting = false; this.Island.SolveTOI(ref subStep); // Reset island flags and synchronize broad-phase proxies. for (int i = 0; i < this.Island.BodyCount; ++i) { Body body = this.Island.Bodies[i]; body.Flags &= ~BodyFlags.Island; if (body.BodyType != BodyType.Dynamic) { continue; } body.SynchronizeFixtures(); // Invalidate all contact TOIs on this displaced body. for (ContactEdge ce = body.ContactList; ce != null; ce = ce.Next) { ce.Contact.Flags &= ~(ContactFlags.TOI | ContactFlags.Island); } } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. this.ContactManager.FindNewContacts(); if (this.EnableSubStepping) { this._stepComplete = false; break; } } }
public static RWSection[] CreateBSPFile(string FileNameForBox, ModelConverterData data) { Vertex3 Max = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z); Vertex3 Min = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z); foreach (Vertex i in data.VertexList) { if (i.Position.X > Max.X) { Max.X = i.Position.X; } if (i.Position.Y > Max.Y) { Max.Y = i.Position.Y; } if (i.Position.Z > Max.Z) { Max.Z = i.Position.Z; } if (i.Position.X < Min.X) { Min.X = i.Position.X; } if (i.Position.Y < Min.Y) { Min.Y = i.Position.Y; } if (i.Position.Z < Min.Z) { Min.Z = i.Position.Z; } } List <Vertex3> vList = new List <Vertex3>(data.VertexList.Count); foreach (Vertex v in data.VertexList) { vList.Add(new Vertex3(v.Position.X, v.Position.Y, v.Position.Z)); } List <RenderWareFile.Color> cList = new List <RenderWareFile.Color>(data.VertexList.Count); foreach (Vertex v in data.VertexList) { cList.Add(new RenderWareFile.Color(v.Color.R, v.Color.G, v.Color.B, v.Color.A)); } List <TextCoord> uvList = new List <TextCoord>(data.VertexList.Count); if (Program.levelEditor.checkBoxFlipUVs.Checked) { foreach (Vertex v in data.VertexList) { uvList.Add(new TextCoord(v.TexCoord.X, v.TexCoord.Y)); } } else { foreach (Vertex v in data.VertexList) { uvList.Add(new TextCoord(v.TexCoord.X, -v.TexCoord.Y)); } } List <RenderWareFile.Triangle> tList = new List <RenderWareFile.Triangle>(data.TriangleList.Count); foreach (Triangle t in data.TriangleList) { tList.Add(new RenderWareFile.Triangle((ushort)t.MaterialIndex, (ushort)t.vertex1, (ushort)t.vertex2, (ushort)t.vertex3)); } List <BinMesh> binMeshList = new List <BinMesh>(); int TotalNumberOfTristripIndicies = 0; if (Program.levelEditor.checkBoxTristrip.Checked) // tristrip generator { for (int i = 0; i < data.MaterialList.Count; i++) { List <Triangle> TriangleStream2 = new List <Triangle>(); foreach (Triangle f in data.TriangleList) { if (f.MaterialIndex == i) { TriangleStream2.Add(f); } } List <List <int> > indexLists = GenerateTristrips(TriangleStream2); foreach (List <int> indices in indexLists) { TotalNumberOfTristripIndicies += indices.Count(); binMeshList.Add(new BinMesh() { materialIndex = i, indexCount = indices.Count(), vertexIndices = indices.ToArray() }); } } } else //trilist generator { for (int i = 0; i < data.MaterialList.Count; i++) { List <int> indices = new List <int>(); foreach (Triangle f in data.TriangleList) { if (f.MaterialIndex == i) { indices.Add(f.vertex1); indices.Add(f.vertex2); indices.Add(f.vertex3); } } TotalNumberOfTristripIndicies += indices.Count(); binMeshList.Add(new BinMesh { materialIndex = i, indexCount = indices.Count(), vertexIndices = indices.ToArray() }); } } WorldFlags worldFlags = WorldFlags.HasOneSetOfTextCoords | WorldFlags.HasVertexColors | WorldFlags.WorldSectorsOverlap | (WorldFlags)0x00010000; worldFlags = Program.levelEditor.checkBoxTristrip.Checked ? worldFlags | WorldFlags.UseTriangleStrips : worldFlags; World_000B world = new World_000B() { worldStruct = new WorldStruct_0001() { rootIsWorldSector = 1, inverseOrigin = new Vertex3(-0f, -0f, -0f), numTriangles = (uint)data.TriangleList.Count(), numVertices = (uint)data.VertexList.Count(), numPlaneSectors = 0, numAtomicSectors = 1, colSectorSize = 0, worldFlags = worldFlags, boxMaximum = Max, boxMinimum = Min, }, materialList = new MaterialList_0008() { materialListStruct = new MaterialListStruct_0001() { materialCount = data.MaterialList.Count() }, materialList = new Material_0007[data.MaterialList.Count()] }, firstWorldChunk = new AtomicSector_0009() { atomicStruct = new AtomicSectorStruct_0001() { matListWindowBase = 0, numTriangles = data.TriangleList.Count(), numVertices = data.VertexList.Count(), boxMaximum = Max, boxMinimum = Min, collSectorPresent = 0x2F50D984, unused = 0, vertexArray = vList.ToArray(), colorArray = cList.ToArray(), uvArray = uvList.ToArray(), triangleArray = tList.ToArray() }, atomicExtension = new Extension_0003() { extensionSectionList = new List <RWSection>() { new BinMeshPLG_050E() { binMeshHeaderFlags = Program.levelEditor.checkBoxTristrip.Checked ? BinMeshHeaderFlags.TriangleStrip : BinMeshHeaderFlags.TriangleList, numMeshes = binMeshList.Count(), totalIndexCount = TotalNumberOfTristripIndicies, binMeshList = binMeshList.ToArray() } } } }, worldExtension = new Extension_0003() }; for (int i = 0; i < data.MaterialList.Count; i++) { world.materialList.materialList[i] = new Material_0007() { materialStruct = new MaterialStruct_0001() { unusedFlags = 0, color = new RenderWareFile.Color() { R = 0xFF, G = 0xFF, B = 0xFF, A = 0xFF }, unusedInt2 = 0x2DF53E84, isTextured = 1, ambient = 1f, specular = 1f, diffuse = 1f }, texture = new Texture_0006() { textureStruct = new TextureStruct_0001() { filterMode = FilterMode.FILTERLINEAR, addressModeU = AddressMode.TEXTUREADDRESSWRAP, addressModeV = AddressMode.TEXTUREADDRESSWRAP, useMipLevels = 1 }, diffuseTextureName = new String_0002() { stringString = data.MaterialList[i] }, alphaTextureName = new String_0002() { stringString = "" }, textureExtension = new Extension_0003() }, materialExtension = new Extension_0003(), }; } return(new RWSection[] { world }); }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and consraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> public void Step(float dt) { #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) _watch.Start(); #endif // If new fixtures were added, we need to find the new contacts. if ((Flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { ContactManager.FindNewContacts(); Flags &= ~WorldFlags.NewFixture; } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) NewContactsTime = _watch.ElapsedTicks; #endif Flags |= WorldFlags.Locked; TimeStep step; step.dt = dt; if (dt > 0.0f) { step.inv_dt = 1.0f / dt; } else { step.inv_dt = 0.0f; } step.dtRatio = _invDt0 * dt; // Update controllers foreach (Controller controller in Controllers) { controller.Update(dt); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) ControllersUpdateTime = _watch.ElapsedTicks - NewContactsTime; #endif // Update contacts. This is where some contacts are destroyed. ContactManager.Collide(); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) ContactsUpdateTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime); #endif // Integrate velocities, solve velocity raints, and integrate positions. if (step.dt > 0.0f) { Solve(ref step); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) SolveUpdateTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime + ContactsUpdateTime); #endif // Handle TOI events. if (Settings.ContinuousPhysics && step.dt > 0.0f) { SolveTOI(); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) ContinuousPhysicsTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime + ContactsUpdateTime + SolveUpdateTime); #endif if (step.dt > 0.0f) { _invDt0 = step.inv_dt; } if ((Flags & WorldFlags.ClearForces) != 0) { ClearForces(); } // We have to unlock the world here to support breakable bodies. Flags &= ~WorldFlags.Locked; foreach (BreakableBody breakableBody in BreakableBodyList) { breakableBody.Update(); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) BreakableBodyTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime + ContactsUpdateTime + SolveUpdateTime + ContinuousPhysicsTime); if (Settings.EnableDiagnostics) { _watch.Stop(); UpdateTime = _watch.ElapsedTicks; _watch.Reset(); } #endif }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and constraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> /// <param name="velocityIterations">For the velocity constraint solver.</param> /// <param name="positionIteration">For the positionconstraint solver.</param> public void Step(float dt, int velocityIterations, int positionIteration) { int height; height = _contactManager._broadPhase.ComputeHeight(); // If new fixtures were added, we need to find the new contacts. if ((_flags & WorldFlags.NewFixture) != 0) { _contactManager.FindNewContacts(); _flags &= ~WorldFlags.NewFixture; } _flags |= WorldFlags.Locked; TimeStep step = new TimeStep(); step.Dt = dt; step.VelocityIterations = velocityIterations; step.PositionIterations = positionIteration; if (dt > 0.0f) { step.Inv_Dt = 1.0f / dt; } else { step.Inv_Dt = 0.0f; } step.DtRatio = _inv_dt0 * dt; step.WarmStarting = _warmStarting; // Update contacts. This is where some contacts are destroyed. _contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.Dt > 0.0f) { Solve(step); } // Handle TOI events. if (_continuousPhysics && step.Dt > 0.0f) { SolveTOI(step); } if (step.Dt > 0.0f) { _inv_dt0 = step.Inv_Dt; } _flags &= ~WorldFlags.Locked; }
public static void Flag(WorldFlags flag) => flags |= flag;
/// <summary> /// Construct a world object. /// </summary> /// <param name="gravity">The world gravity vector.</param> /// <param name="doSleep">Improve performance by not simulating inactive bodies.</param> public World(Vec2 gravity, bool doSleep) { _destructionListener = null; _debugDraw = null; _bodyList = null; _jointList = null; _bodyCount = 0; _jointCount = 0; _warmStarting = true; _continuousPhysics = true; _allowSleep = doSleep; _gravity = gravity; _flags = 0; _inv_dt0 = 0.0f; _contactManager = new ContactManager(); }
/// <summary> /// construct a world object. /// </summary> /// <param name="gravity">the world gravity vector.</param> /// <param name="doSleep">improve performance by not simulating inactive bodies.</param> public World(Vector2 gravity, bool doSleep) { WarmStarting = true; ContinuousPhysics = true; _allowSleep = doSleep; Gravity = gravity; _flags = WorldFlags.ClearForces; _queryAABBCallbackWrapper = QueryAABBCallbackWrapper; _rayCastCallbackWrapper = RayCastCallbackWrapper; }
static World CreateTestWorld(WorldFlags worldFlags, string name = null) => new World(name ?? worldFlags.ToString(), worldFlags);
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> /// <param name="gravity">The gravity.</param> public World(Vector2 gravity) { ContactManager = new ContactManager(); Gravity = gravity; Flags = WorldFlags.ClearForces; _queryAABBCallbackWrapper = QueryAABBCallbackWrapper; _rayCastCallbackWrapper = RayCastCallbackWrapper; Controllers = new List<Controller>(); BreakableBodyList = new List<BreakableBody>(); BodyList = new List<Body>(32); JointList = new List<Joint>(32); }
/// <summary> /// Initializes a new instance of the <see cref="PhysicsWorld"/> class. /// </summary> private PhysicsWorld() { Flags = WorldFlags.ClearForces; ControllerList = new List<Controller>(); BreakableBodyList = new List<PhysicsBreakableBody>(); BodyList = new List<PhysicsBody>(32); JointList = new List<PhysicsJoint>(32); }
public static RWSection[] CreateBSPFromAssimp(string fileName, bool flipUVs) { PostProcessSteps pps = PostProcessSteps.Debone | PostProcessSteps.FindInstances | PostProcessSteps.FindInvalidData | PostProcessSteps.OptimizeGraph | PostProcessSteps.OptimizeMeshes | PostProcessSteps.Triangulate | PostProcessSteps.PreTransformVertices; Scene scene = new AssimpContext().ImportFile(fileName, pps); int vertexCount = scene.Meshes.Sum(m => m.VertexCount); int triangleCount = scene.Meshes.Sum(m => m.FaceCount); if (vertexCount > 65535 || triangleCount > 65536) { throw new ArgumentException("Model has too many vertices or triangles. Please import a simpler model."); } List <Vertex3> vertices = new List <Vertex3>(vertexCount); List <RenderWareFile.Color> vColors = new List <RenderWareFile.Color>(vertexCount); List <Vertex2> textCoords = new List <Vertex2>(vertexCount); List <RenderWareFile.Triangle> triangles = new List <RenderWareFile.Triangle>(triangleCount); int totalVertices = 0; foreach (var m in scene.Meshes) { foreach (Vector3D v in m.Vertices) { vertices.Add(new Vertex3(v.X, v.Y, v.Z)); } if (m.HasTextureCoords(0)) { foreach (Vector3D v in m.TextureCoordinateChannels[0]) { textCoords.Add(new Vertex2(v.X, flipUVs ? -v.Y : v.Y)); } } else { for (int i = 0; i < m.VertexCount; i++) { textCoords.Add(new Vertex2()); } } if (m.HasVertexColors(0)) { foreach (Color4D c in m.VertexColorChannels[0]) { vColors.Add(new RenderWareFile.Color( (byte)(c.R * 255), (byte)(c.G * 255), (byte)(c.B * 255), (byte)(c.A * 255))); } } else { for (int i = 0; i < m.VertexCount; i++) { vColors.Add(new RenderWareFile.Color(255, 255, 255, 255)); } } foreach (var t in m.Faces) { triangles.Add(new RenderWareFile.Triangle() { vertex1 = (ushort)(t.Indices[0] + totalVertices), vertex2 = (ushort)(t.Indices[1] + totalVertices), vertex3 = (ushort)(t.Indices[2] + totalVertices), materialIndex = (ushort)m.MaterialIndex }); } totalVertices += m.VertexCount; } if (vertices.Count != textCoords.Count || vertices.Count != vColors.Count) { throw new ArgumentException("Internal error: texture coordinate or vertex color count is different from vertex count."); } triangles = triangles.OrderBy(t => t.materialIndex).ToList(); Vertex3 Max = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z); Vertex3 Min = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z); foreach (Vertex3 i in vertices) { if (i.X > Max.X) { Max.X = i.X; } if (i.Y > Max.Y) { Max.Y = i.Y; } if (i.Z > Max.Z) { Max.Z = i.Z; } if (i.X < Min.X) { Min.X = i.X; } if (i.Y < Min.Y) { Min.Y = i.Y; } if (i.Z < Min.Z) { Min.Z = i.Z; } } BinMesh[] binMeshes = new BinMesh[scene.MaterialCount]; Material_0007[] materials = new Material_0007[scene.MaterialCount]; for (int i = 0; i < scene.MaterialCount; i++) { List <int> indices = new List <int>(triangles.Count); foreach (RenderWareFile.Triangle f in triangles) { if (f.materialIndex == i) { indices.Add(f.vertex1); indices.Add(f.vertex2); indices.Add(f.vertex3); } } binMeshes[i] = new BinMesh() { materialIndex = i, indexCount = indices.Count(), vertexIndices = indices.ToArray() }; materials[i] = new Material_0007() { materialStruct = new MaterialStruct_0001() { unusedFlags = 0, color = new RenderWareFile.Color( (byte)(scene.Materials[i].ColorDiffuse.R / 255), (byte)(scene.Materials[i].ColorDiffuse.G / 255), (byte)(scene.Materials[i].ColorDiffuse.B / 255), (byte)(scene.Materials[i].ColorDiffuse.A / 255)), unusedInt2 = 0x2DF53E84, isTextured = scene.Materials[i].HasTextureDiffuse ? 1 : 0, ambient = 1f, specular = 1f, diffuse = 1f }, texture = scene.Materials[i].HasTextureDiffuse ? new Texture_0006() { textureStruct = new TextureStruct_0001() // use wrap as default { filterMode = TextureFilterMode.FILTERLINEAR, addressModeU = scene.Materials[i].TextureDiffuse.WrapModeU == TextureWrapMode.Clamp ? TextureAddressMode.TEXTUREADDRESSCLAMP : scene.Materials[i].TextureDiffuse.WrapModeU == TextureWrapMode.Decal ? TextureAddressMode.TEXTUREADDRESSBORDER : scene.Materials[i].TextureDiffuse.WrapModeU == TextureWrapMode.Mirror ? TextureAddressMode.TEXTUREADDRESSMIRROR : TextureAddressMode.TEXTUREADDRESSWRAP, addressModeV = scene.Materials[i].TextureDiffuse.WrapModeV == TextureWrapMode.Clamp ? TextureAddressMode.TEXTUREADDRESSCLAMP : scene.Materials[i].TextureDiffuse.WrapModeV == TextureWrapMode.Decal ? TextureAddressMode.TEXTUREADDRESSBORDER : scene.Materials[i].TextureDiffuse.WrapModeV == TextureWrapMode.Mirror ? TextureAddressMode.TEXTUREADDRESSMIRROR : TextureAddressMode.TEXTUREADDRESSWRAP, useMipLevels = 1 }, diffuseTextureName = new String_0002() { stringString = Path.GetFileNameWithoutExtension(scene.Materials[i].TextureDiffuse.FilePath) }, alphaTextureName = new String_0002() { stringString = "" }, textureExtension = new Extension_0003() } : null, materialExtension = new Extension_0003(), }; } WorldFlags worldFlags = WorldFlags.HasOneSetOfTextCoords | WorldFlags.HasVertexColors | WorldFlags.WorldSectorsOverlap | (WorldFlags)0x00010000; World_000B world = new World_000B() { worldStruct = new WorldStruct_0001() { rootIsWorldSector = 1, inverseOrigin = new Vertex3(-0f, -0f, -0f), numTriangles = (uint)triangleCount, numVertices = (uint)vertexCount, numPlaneSectors = 0, numAtomicSectors = 1, colSectorSize = 0, worldFlags = worldFlags, boxMaximum = Max, boxMinimum = Min, }, materialList = new MaterialList_0008() { materialListStruct = new MaterialListStruct_0001() { materialCount = scene.MaterialCount }, materialList = materials }, firstWorldChunk = new AtomicSector_0009() { atomicSectorStruct = new AtomicSectorStruct_0001() { matListWindowBase = 0, numTriangles = triangleCount, numVertices = vertexCount, boxMaximum = Max, boxMinimum = Min, collSectorPresent = 0x2F50D984, unused = 0, vertexArray = vertices.ToArray(), colorArray = vColors.ToArray(), uvArray = textCoords.ToArray(), triangleArray = triangles.ToArray() }, atomicSectorExtension = new Extension_0003() { extensionSectionList = new List <RWSection>() { new BinMeshPLG_050E() { binMeshHeaderFlags = BinMeshHeaderFlags.TriangleList, numMeshes = binMeshes.Count(), totalIndexCount = binMeshes.Sum(b => b.indexCount), binMeshList = binMeshes } } } }, worldExtension = new Extension_0003() }; return(new RWSection[] { world }); }
/// <summary> /// Set flag to control automatic clearing of forces after each time step. /// </summary> /// <param name="flag"></param> void SetAutoClearForces(bool flag) { if (flag) { _flags |= WorldFlags.ClearForces; } else { _flags &= ~WorldFlags.ClearForces; } }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and consraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> public void Step(float dt) { if (Settings.EnableDiagnostics) { this._watch.Start(); } ProcessChanges(); if (Settings.EnableDiagnostics) { this.AddRemoveTime = this._watch.ElapsedTicks; } //If there is no change in time, no need to calculate anything. if (dt == 0 || !this.Enabled) { if (Settings.EnableDiagnostics) { this._watch.Stop(); this._watch.Reset(); } return; } // If new fixtures were added, we need to find the new contacts. if ((this.Flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { this.ContactManager.FindNewContacts(); this.Flags &= ~WorldFlags.NewFixture; } TimeStep step; step.inv_dt = 1.0f / dt; step.dt = dt; step.dtRatio = this._invDt0 * dt; if (Settings.EnableDiagnostics) { this.ControllersUpdateTime = this._watch.ElapsedTicks - this.AddRemoveTime; } // Update contacts. This is where some contacts are destroyed. this.ContactManager.Collide(); if (Settings.EnableDiagnostics) { this.ContactsUpdateTime = this._watch.ElapsedTicks - (this.AddRemoveTime + this.ControllersUpdateTime); } // Integrate velocities, solve velocity raints, and integrate positions. Solve(ref step); if (Settings.EnableDiagnostics) { this.SolveUpdateTime = this._watch.ElapsedTicks - (this.AddRemoveTime + this.ControllersUpdateTime + this.ContactsUpdateTime); } // Handle TOI events. if (Settings.ContinuousPhysics) { SolveTOI(ref step); } if (Settings.EnableDiagnostics) { this.ContinuousPhysicsTime = this._watch.ElapsedTicks - (this.AddRemoveTime + this.ControllersUpdateTime + this.ContactsUpdateTime + this.SolveUpdateTime); } this._invDt0 = step.inv_dt; if ((this.Flags & WorldFlags.ClearForces) != 0) { ClearForces(); } if (Settings.EnableDiagnostics) { this._watch.Stop(); //AddRemoveTime = 1000 * AddRemoveTime / Stopwatch.Frequency; this.UpdateTime = this._watch.ElapsedTicks; this._watch.Reset(); } }
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> private World() { Flags = WorldFlags.ClearForces; ControllerList = new List<Controller>(); BreakableBodyList = new List<BreakableBody>(); BodyList = new List<Body>(32); JointList = new List<Joint>(32); #if USE_AWAKE_BODY_SET AwakeBodySet = new HashSet<Body>(); AwakeBodyList = new List<Body>(32); #endif #if USE_ISLAND_SET IslandSet = new HashSet<Body>(); #endif #if OPTIMIZE_TOI TOISet = new HashSet<Body>(); #endif _queryAABBCallbackWrapper = QueryAABBCallbackWrapper; _rayCastCallbackWrapper = RayCastCallbackWrapper; Fluid = new FluidSystem2(new Vec2(0, -1), 5000, 150, 150); }
public static RWSection[] CreateBSPFromAssimp(string fileName, bool flipUVs, bool ignoreMeshColors) { PostProcessSteps pps = PostProcessSteps.Debone | PostProcessSteps.FindInstances | PostProcessSteps.FindInvalidData | PostProcessSteps.OptimizeGraph | PostProcessSteps.OptimizeMeshes | PostProcessSteps.Triangulate | PostProcessSteps.PreTransformVertices; Scene scene = new AssimpContext().ImportFile(fileName, pps); int vertexCount = scene.Meshes.Sum(m => m.VertexCount); int triangleCount = scene.Meshes.Sum(m => m.FaceCount); if (vertexCount > 65535 || triangleCount > 65536) { throw new ArgumentException("Model has too many vertices or triangles. Please import a simpler model."); } List <Vertex3> vertices = new List <Vertex3>(vertexCount); List <RenderWareFile.Color> vColors = new List <RenderWareFile.Color>(vertexCount); List <Vertex2> textCoords = new List <Vertex2>(vertexCount); List <RenderWareFile.Triangle> triangles = new List <RenderWareFile.Triangle>(triangleCount); int totalVertices = 0; foreach (var m in scene.Meshes) { foreach (Vector3D v in m.Vertices) { vertices.Add(new Vertex3(v.X, v.Y, v.Z)); } if (m.HasTextureCoords(0)) { foreach (Vector3D v in m.TextureCoordinateChannels[0]) { textCoords.Add(new Vertex2(v.X, flipUVs ? -v.Y : v.Y)); } } else { for (int i = 0; i < m.VertexCount; i++) { textCoords.Add(new Vertex2()); } } if (m.HasVertexColors(0)) { foreach (Color4D c in m.VertexColorChannels[0]) { vColors.Add(new RenderWareFile.Color( (byte)(c.R * 255), (byte)(c.G * 255), (byte)(c.B * 255), (byte)(c.A * 255))); } } else { for (int i = 0; i < m.VertexCount; i++) { vColors.Add(new RenderWareFile.Color(255, 255, 255, 255)); } } foreach (var t in m.Faces) { triangles.Add(new RenderWareFile.Triangle() { vertex1 = (ushort)(t.Indices[0] + totalVertices), vertex2 = (ushort)(t.Indices[1] + totalVertices), vertex3 = (ushort)(t.Indices[2] + totalVertices), materialIndex = (ushort)m.MaterialIndex }); } totalVertices += m.VertexCount; } if (vertices.Count != textCoords.Count || vertices.Count != vColors.Count) { throw new ArgumentException("Internal error: texture coordinate or vertex color count is different from vertex count."); } triangles = triangles.OrderBy(t => t.materialIndex).ToList(); Vertex3 Max = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z); Vertex3 Min = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z); foreach (Vertex3 i in vertices) { if (i.X > Max.X) { Max.X = i.X; } if (i.Y > Max.Y) { Max.Y = i.Y; } if (i.Z > Max.Z) { Max.Z = i.Z; } if (i.X < Min.X) { Min.X = i.X; } if (i.Y < Min.Y) { Min.Y = i.Y; } if (i.Z < Min.Z) { Min.Z = i.Z; } } Max = new Vertex3(MaximumBoundary, MaximumBoundary, MaximumBoundary); Min = new Vertex3(-MaximumBoundary, -MaximumBoundary, -MaximumBoundary); BinMesh[] binMeshes = new BinMesh[scene.MaterialCount]; Material_0007[] materials = new Material_0007[scene.MaterialCount]; for (int i = 0; i < scene.MaterialCount; i++) { List <int> indices = new List <int>(triangles.Count); foreach (RenderWareFile.Triangle f in triangles) { if (f.materialIndex == i) { indices.Add(f.vertex1); indices.Add(f.vertex2); indices.Add(f.vertex3); } } binMeshes[i] = new BinMesh() { materialIndex = i, indexCount = indices.Count(), vertexIndices = indices.ToArray() }; materials[i] = new Material_0007() { materialStruct = new MaterialStruct_0001() { unusedFlags = 0, color = ignoreMeshColors ? new RenderWareFile.Color(255, 255, 255, 255) : new RenderWareFile.Color( (byte)(scene.Materials[i].ColorDiffuse.R / 255), (byte)(scene.Materials[i].ColorDiffuse.G / 255), (byte)(scene.Materials[i].ColorDiffuse.B / 255), (byte)(scene.Materials[i].ColorDiffuse.A / 255)), unusedInt2 = 0x2DF53E84, isTextured = scene.Materials[i].HasTextureDiffuse ? 1 : 0, ambient = ignoreMeshColors ? 1f : scene.Materials[i].ColorAmbient.A, specular = ignoreMeshColors ? 1f : scene.Materials[i].ColorSpecular.A, diffuse = ignoreMeshColors ? 1f : scene.Materials[i].ColorDiffuse.A }, texture = scene.Materials[i].HasTextureDiffuse ? RWTextureFromAssimpMaterial(scene.Materials[i].TextureDiffuse) : null, materialExtension = new Extension_0003() { extensionSectionList = new List <RWSection>() }, }; } WorldFlags worldFlags = WorldFlags.HasOneSetOfTextCoords | WorldFlags.HasVertexColors | WorldFlags.WorldSectorsOverlap | (WorldFlags)0x00010000; World_000B world = new World_000B() { worldStruct = new WorldStruct_0001() { rootIsWorldSector = 1, inverseOrigin = new Vertex3(-0f, -0f, -0f), numTriangles = (uint)triangleCount, numVertices = (uint)vertexCount, numPlaneSectors = 0, numAtomicSectors = 1, colSectorSize = 0, worldFlags = worldFlags, boxMaximum = Max, boxMinimum = Min, }, materialList = new MaterialList_0008() { materialListStruct = new MaterialListStruct_0001() { materialCount = scene.MaterialCount }, materialList = materials }, firstWorldChunk = new AtomicSector_0009() { atomicSectorStruct = new AtomicSectorStruct_0001() { matListWindowBase = 0, numTriangles = triangleCount, numVertices = vertexCount, boxMaximum = Max, boxMinimum = Min, collSectorPresent = 0x2F50D984, unused = 0, vertexArray = vertices.ToArray(), colorArray = vColors.ToArray(), uvArray = textCoords.ToArray(), triangleArray = triangles.ToArray() }, atomicSectorExtension = new Extension_0003() { extensionSectionList = new List <RWSection>() { new BinMeshPLG_050E() { binMeshHeaderFlags = BinMeshHeaderFlags.TriangleList, numMeshes = binMeshes.Count(), totalIndexCount = binMeshes.Sum(b => b.indexCount), binMeshList = binMeshes }, new CollisionPLG_011D_Scooby() { splits = new Split_Scooby[0], startIndex_amountOfTriangles = new short[][] { new short[] { 0, (short)triangles.Count } }, triangles = TriangleRange(triangles.Count) } } } }, worldExtension = new Extension_0003() }; return(new RWSection[] { world }); }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and consraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> public void Step(float dt) { #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { _watch.Start(); } #endif // If new fixtures were added, we need to find the new contacts. if ((Flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { ContactManager.FindNewContacts(); Flags &= ~WorldFlags.NewFixture; } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { NewContactsTime = _watch.ElapsedTicks; } #endif Flags |= WorldFlags.Locked; TimeStep step; step.dt = dt; if (dt > 0.0f) { step.inv_dt = 1.0f / dt; } else { step.inv_dt = 0.0f; } step.dtRatio = _invDt0 * dt; // Update controllers foreach (Controller controller in Controllers) { controller.Update(dt); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { ControllersUpdateTime = _watch.ElapsedTicks - NewContactsTime; } #endif // Update contacts. This is where some contacts are destroyed. ContactManager.Collide(); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { ContactsUpdateTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime); } #endif // Integrate velocities, solve velocity raints, and integrate positions. if (step.dt > 0.0f) { Solve(ref step); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { SolveUpdateTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime + ContactsUpdateTime); } #endif // Handle TOI events. if (Settings.ContinuousPhysics && step.dt > 0.0f) { SolveTOI(); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { ContinuousPhysicsTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime + ContactsUpdateTime + SolveUpdateTime); } #endif if (step.dt > 0.0f) { _invDt0 = step.inv_dt; } if ((Flags & WorldFlags.ClearForces) != 0) { ClearForces(); } // We have to unlock the world here to support breakable bodies. Flags &= ~WorldFlags.Locked; foreach (BreakableBody breakableBody in BreakableBodyList) { breakableBody.Update(); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { BreakableBodyTime = _watch.ElapsedTicks - (NewContactsTime + ControllersUpdateTime + ContactsUpdateTime + SolveUpdateTime + ContinuousPhysicsTime); } if (Settings.EnableDiagnostics) { _watch.Stop(); UpdateTime = _watch.ElapsedTicks; _watch.Reset(); } #endif }
public static bool HasFlag(WorldFlags flag) => (flags & flag) != 0;
public void EditorSortFlags() { WorldFlags.Sort(); }
public static void FlipFlag(WorldFlags flag) => flags ^= flag;
/// <summary> /// Take a time step. This performs collision detection, integration, /// and consraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> public void Step(float dt) { #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { _watch.Start(); } #endif ProcessChanges(); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { AddRemoveTime = _watch.ElapsedTicks; } #endif //If there is no change in time, no need to calculate anything. if (dt == 0 || !Enabled) { #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { _watch.Stop(); _watch.Reset(); } #endif return; } // If new fixtures were added, we need to find the new contacts. if ((Flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { ContactManager.FindNewContacts(); Flags &= ~WorldFlags.NewFixture; } TimeStep step; step.inv_dt = 1.0f / dt; step.dt = dt; step.dtRatio = _invDt0 * dt; //Update controllers for (int i = 0; i < ControllerList.Count; i++) { ControllerList[i].Update(dt); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { ControllersUpdateTime = _watch.ElapsedTicks - AddRemoveTime; } #endif // Update contacts. This is where some contacts are destroyed. ContactManager.Collide(); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { ContactsUpdateTime = _watch.ElapsedTicks - (AddRemoveTime + ControllersUpdateTime); } #endif // Integrate velocities, solve velocity raints, and integrate positions. Solve(ref step); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { SolveUpdateTime = _watch.ElapsedTicks - (AddRemoveTime + ControllersUpdateTime + ContactsUpdateTime); } #endif // Handle TOI events. if (Settings.ContinuousPhysics) { SolveTOI(ref step); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { ContinuousPhysicsTime = _watch.ElapsedTicks - (AddRemoveTime + ControllersUpdateTime + ContactsUpdateTime + SolveUpdateTime); } #endif _invDt0 = step.inv_dt; if ((Flags & WorldFlags.ClearForces) != 0) { ClearForces(); } for (int i = 0; i < BreakableBodyList.Count; i++) { BreakableBodyList[i].Update(); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { _watch.Stop(); //AddRemoveTime = 1000 * AddRemoveTime / Stopwatch.Frequency; UpdateTime = _watch.ElapsedTicks; _watch.Reset(); } #endif }
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> private World() { Flags = WorldFlags.ClearForces; ControllerList = new CCRawList<Controller>(); BreakableBodyList = new CCRawList<BreakableBody>(); BodyList = new CCRawList<Body>(32); JointList = new CCRawList<Joint>(32); }
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> private World() { Flags = WorldFlags.ClearForces; ControllerList = new List<Controller>(); BreakableBodyList = new List<BreakableBody>(); BodyList = new List<Body>(32); JointList = new List<FarseerJoint>(32); #if USE_AWAKE_BODY_SET AwakeBodySet = new HashSet<Body>(); AwakeBodyList = new List<Body>(32); #endif #if USE_ISLAND_SET IslandSet = new HashSet<Body>(); #endif #if OPTIMIZE_TOI TOISet = new HashSet<Body>(); #endif }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and consraint solution. /// </summary> /// <param name="dt">The amount of time to simulate, this should not vary.</param> public void Step(float dt) { #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) _watch.Start(); #endif ProcessChanges(); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) AddRemoveTime = _watch.ElapsedTicks; #endif //If there is no change in time, no need to calculate anything. if (dt == 0 || !Enabled) { #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { _watch.Stop(); _watch.Reset(); } #endif return; } // If new fixtures were added, we need to find the new contacts. if ((Flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { ContactManager.FindNewContacts(); Flags &= ~WorldFlags.NewFixture; } TimeStep step; step.inv_dt = 1.0f/dt; step.dt = dt; step.dtRatio = _invDt0*dt; //Update controllers for (int i = 0; i < Controllers.Count; i++) { Controllers[i].Update(dt); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) ControllersUpdateTime = _watch.ElapsedTicks - AddRemoveTime; #endif // Update contacts. This is where some contacts are destroyed. ContactManager.Collide(); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) ContactsUpdateTime = _watch.ElapsedTicks - (AddRemoveTime + ControllersUpdateTime); #endif // Integrate velocities, solve velocity raints, and integrate positions. Solve(ref step); #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) SolveUpdateTime = _watch.ElapsedTicks - (AddRemoveTime + ControllersUpdateTime + ContactsUpdateTime); #endif // Handle TOI events. if (Settings.ContinuousPhysics) { SolveTOI(ref step); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) ContinuousPhysicsTime = _watch.ElapsedTicks - (AddRemoveTime + ControllersUpdateTime + ContactsUpdateTime + SolveUpdateTime); #endif _invDt0 = step.inv_dt; if ((Flags & WorldFlags.ClearForces) != 0) { ClearForces(); } for (int i = 0; i < BreakableBodyList.Count; i++) { BreakableBodyList[i].Update(); } #if (!SILVERLIGHT) if (Settings.EnableDiagnostics) { _watch.Stop(); //AddRemoveTime = 1000 * AddRemoveTime / Stopwatch.Frequency; UpdateTime = _watch.ElapsedTicks; _watch.Reset(); } #endif }
/// <summary> /// Take a time step. This performs collision detection, integration, /// and constraint solution. /// </summary> /// <param name="dt">timeStep the amount of time to simulate, this should not vary.</param> /// <param name="velocityIterations">for the velocity constraint solver.</param> /// <param name="positionIterations">for the position constraint solver.</param> public void Step(float dt, int velocityIterations, int positionIterations) { // If new fixtures were added, we need to find the new contacts. if ((_flags & WorldFlags.NewFixture) == WorldFlags.NewFixture) { _contactManager.FindNewContacts(); _flags &= ~WorldFlags.NewFixture; } _flags |= WorldFlags.Locked; TimeStep step; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0f) { step.inv_dt = 1.0f / dt; } else { step.inv_dt = 0.0f; } step.dtRatio = _inv_dt0 * dt; step.warmStarting = WarmStarting; // Update contacts. This is where some contacts are destroyed. _contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.dt > 0.0f) { Solve(ref step); } // Handle TOI events. if (ContinuousPhysics && step.dt > 0.0f) { SolveTOI(); } if (step.dt > 0.0f) { _inv_dt0 = step.inv_dt; } if ((_flags & WorldFlags.ClearForces) != 0) { ClearForces(); } _flags &= ~WorldFlags.Locked; }