From 892f19a1974c0386c34ab1042fe8b5dc136a5f8c Mon Sep 17 00:00:00 2001 From: George Date: Mon, 7 Nov 2022 01:13:18 +1100 Subject: [PATCH] Removed IMapCell, moved IMap to DefaultMap and removed interface on Map.cs, and added interfaces for Height, Ramp, and Tiles properties. --- OpenRA.Game/CPos.cs | 2 +- OpenRA.Game/GameRules/WeaponInfo.cs | 10 +- OpenRA.Game/Graphics/TerrainSpriteLayer.cs | 13 +-- OpenRA.Game/Graphics/Viewport.cs | 21 ++-- OpenRA.Game/Graphics/WorldRenderer.cs | 8 +- OpenRA.Game/MPos.cs | 2 +- OpenRA.Game/Map/CellLayer.cs | 2 +- OpenRA.Game/Map/CellLayerBase.cs | 2 +- OpenRA.Game/Map/IMap.cs | 95 ++++++++++++------- OpenRA.Game/Map/IMapCell.cs | 57 ----------- OpenRA.Game/Map/IMapResource.cs | 13 --- OpenRA.Game/Map/Map.cs | 55 +---------- OpenRA.Game/Map/MapCache.cs | 2 +- OpenRA.Game/Map/MapGrid.cs | 2 +- OpenRA.Game/Map/MapPreview.cs | 11 +-- OpenRA.Game/Map/ProjectedCellLayer.cs | 2 +- OpenRA.Game/Map/ProjectedCellRegion.cs | 4 +- OpenRA.Game/ModData.cs | 6 +- OpenRA.Game/Player.cs | 2 +- OpenRA.Game/Scripting/ScriptContext.cs | 2 +- OpenRA.Game/Support/ExceptionHandler.cs | 2 +- OpenRA.Game/Traits/Player/FrozenActorLayer.cs | 2 +- OpenRA.Game/Traits/Player/Shroud.cs | 8 +- OpenRA.Game/Traits/Target.cs | 2 +- OpenRA.Game/Traits/World/ScreenMap.cs | 2 +- OpenRA.Game/World.cs | 10 +- OpenRA.Mods.Cnc/Activities/LayMines.cs | 2 +- OpenRA.Mods.Cnc/Activities/Leap.cs | 4 +- OpenRA.Mods.Cnc/Activities/LeapAttack.cs | 6 +- OpenRA.Mods.Cnc/Activities/Teleport.cs | 12 +-- OpenRA.Mods.Cnc/Traits/ConyardChronoReturn.cs | 6 +- OpenRA.Mods.Cnc/Traits/Minelayer.cs | 26 ++--- OpenRA.Mods.Cnc/Traits/PortableChrono.cs | 4 +- .../Traits/Render/WithBuildingBib.cs | 14 +-- .../Render/WithLandingCraftAnimation.cs | 8 +- .../Traits/SupportPowers/AttackOrderPower.cs | 6 +- .../Traits/SupportPowers/ChronoshiftPower.cs | 21 ++-- .../Traits/SupportPowers/DropPodsPower.cs | 10 +- .../Traits/SupportPowers/IonCannonPower.cs | 2 +- OpenRA.Mods.Cnc/Traits/TDGunboat.cs | 8 +- .../Traits/World/TSEditorResourceLayer.cs | 13 ++- .../Traits/World/TSResourceLayer.cs | 20 ++-- .../Traits/World/TSTiberiumRenderer.cs | 2 +- .../Traits/World/TSVeinsRenderer.cs | 30 +++--- .../Traits/World/WithResourceAnimation.cs | 8 +- .../ImportRedAlertLegacyMapCommand.cs | 4 +- .../UtilityCommands/ImportTSMapCommand.cs | 31 +++--- .../ImportTiberianDawnLegacyMapCommand.cs | 2 +- OpenRA.Mods.Common/AIUtils.cs | 7 +- .../Activities/Air/FallToEarth.cs | 2 +- OpenRA.Mods.Common/Activities/Air/Fly.cs | 6 +- .../Activities/Air/FlyOffMap.cs | 4 +- OpenRA.Mods.Common/Activities/Air/Land.cs | 12 +-- OpenRA.Mods.Common/Activities/Air/TakeOff.cs | 2 +- OpenRA.Mods.Common/Activities/DeliverUnit.cs | 2 +- .../Activities/FindAndDeliverResources.cs | 6 +- OpenRA.Mods.Common/Activities/Move/Move.cs | 40 ++++---- .../Activities/Move/MoveAdjacentTo.cs | 8 +- .../Activities/Move/MoveWithinRange.cs | 5 +- OpenRA.Mods.Common/Activities/Parachute.cs | 2 +- OpenRA.Mods.Common/Activities/Resupply.cs | 2 +- OpenRA.Mods.Common/Activities/UnloadCargo.cs | 2 +- OpenRA.Mods.Common/ActorExts.cs | 4 +- .../Commands/DebugVisualizationCommands.cs | 2 +- .../EditorBrushes/EditorActorBrush.cs | 2 +- .../EditorBrushes/EditorCopyPasteBrush.cs | 22 ++--- .../EditorBrushes/EditorTileBrush.cs | 39 ++++---- .../Effects/RallyPointIndicator.cs | 2 +- .../Effects/RevealShroudEffect.cs | 4 +- .../Graphics/ModelRenderable.cs | 24 ++--- OpenRA.Mods.Common/Lint/CheckActors.cs | 2 +- OpenRA.Mods.Common/Lint/CheckMapMetadata.cs | 13 ++- OpenRA.Mods.Common/Lint/CheckMapTiles.cs | 2 +- OpenRA.Mods.Common/Lint/CheckOwners.cs | 4 +- OpenRA.Mods.Common/Lint/CheckPlayers.cs | 6 +- .../Lint/CheckUnknownTraitFields.cs | 3 +- .../Lint/CheckUnknownWeaponFields.cs | 3 +- .../Lint/CheckWorldAndPlayerInherits.cs | 3 +- OpenRA.Mods.Common/MapFormats/DefaultMap.cs | 79 ++++++++++----- .../Orders/PlaceBuildingOrderGenerator.cs | 2 +- .../Orders/UnitOrderGenerator.cs | 2 +- .../Pathfinder/CellInfoLayerPool.cs | 2 +- .../Pathfinder/DensePathGraph.cs | 4 +- .../Pathfinder/HierarchicalPathFinder.cs | 12 +-- OpenRA.Mods.Common/Projectiles/Bullet.cs | 14 +-- OpenRA.Mods.Common/Projectiles/GravityBomb.cs | 2 +- OpenRA.Mods.Common/Projectiles/Missile.cs | 18 ++-- OpenRA.Mods.Common/Projectiles/NukeLaunch.cs | 2 +- .../Scripting/Global/MapGlobal.cs | 16 ++-- .../Scripting/Global/MediaGlobal.cs | 6 +- .../Scripting/Global/ReinforcementsGlobal.cs | 4 +- .../Scripting/Global/UserInterfaceGlobal.cs | 4 +- .../Properties/AircraftProperties.cs | 2 +- .../Scripting/Properties/NukeProperties.cs | 2 +- OpenRA.Mods.Common/Terrain/DefaultTerrain.cs | 12 +-- OpenRA.Mods.Common/Traits/AffectsShroud.cs | 10 +- OpenRA.Mods.Common/Traits/Air/Aircraft.cs | 82 +++++++--------- .../Traits/Air/AttackAircraft.cs | 6 +- OpenRA.Mods.Common/Traits/Air/AttackBomber.cs | 2 +- .../Traits/AppearsOnMapPreview.cs | 4 +- .../Traits/Attack/AttackBase.cs | 4 +- OpenRA.Mods.Common/Traits/AttackMove.cs | 10 +- OpenRA.Mods.Common/Traits/AutoCarryable.cs | 6 +- .../Traits/BlocksProjectiles.cs | 8 +- .../Traits/BotModules/BaseBuilderBotModule.cs | 2 +- .../BotModuleLogic/BaseBuilderQueueManager.cs | 12 +-- .../BotModuleLogic/SupportPowerDecision.cs | 12 +-- .../Traits/BotModules/HarvesterBotModule.cs | 6 +- .../Traits/BotModules/McvManagerBotModule.cs | 4 +- .../BotModules/SquadManagerBotModule.cs | 2 +- .../BotModules/Squads/States/AirStates.cs | 10 +- .../BotModules/SupportPowerBotModule.cs | 11 +-- .../ActorPreviewPlaceBuildingPreview.cs | 2 +- OpenRA.Mods.Common/Traits/Buildings/Bridge.cs | 8 +- .../Traits/Buildings/Building.cs | 14 +-- .../Traits/Buildings/BuildingInfluence.cs | 8 +- .../Traits/Buildings/BuildingUtils.cs | 8 +- OpenRA.Mods.Common/Traits/Buildings/Exit.cs | 2 +- .../FootprintPlaceBuildingPreview.cs | 10 +- .../Traits/Buildings/FreeActorWithDelivery.cs | 10 +- .../Traits/Buildings/GroundLevelBridge.cs | 2 +- .../Traits/Buildings/ProductionAirdrop.cs | 11 +-- .../Traits/Buildings/RallyPoint.cs | 8 +- .../Buildings/SequencePlaceBuildingPreview.cs | 2 +- .../Buildings/TransformsIntoAircraft.cs | 12 +-- .../Traits/Buildings/TransformsIntoMobile.cs | 12 +-- OpenRA.Mods.Common/Traits/Cargo.cs | 4 +- OpenRA.Mods.Common/Traits/Carryall.cs | 12 +-- OpenRA.Mods.Common/Traits/ChangesTerrain.cs | 9 +- .../Conditions/GrantConditionOnDeploy.cs | 8 +- .../GrantConditionOnSubterraneanLayer.cs | 4 +- .../Conditions/GrantConditionOnTerrain.cs | 6 +- .../Conditions/GrantConditionOnTileSet.cs | 2 +- OpenRA.Mods.Common/Traits/Crates/Crate.cs | 11 ++- .../Traits/Crates/DuplicateUnitCrateAction.cs | 4 +- OpenRA.Mods.Common/Traits/DamagedByTerrain.cs | 2 +- OpenRA.Mods.Common/Traits/EjectOnDeath.cs | 4 +- .../Traits/ExitsDebugOverlay.cs | 6 +- OpenRA.Mods.Common/Traits/Explodes.cs | 2 +- OpenRA.Mods.Common/Traits/Harvester.cs | 4 +- OpenRA.Mods.Common/Traits/HitShape.cs | 2 +- OpenRA.Mods.Common/Traits/Husk.cs | 16 ++-- OpenRA.Mods.Common/Traits/Immobile.cs | 2 +- .../Traits/Infantry/ScaredyCat.cs | 2 +- .../Traits/Infantry/TerrainModifiesDamage.cs | 6 +- .../Traits/IsometricSelectable.cs | 10 +- OpenRA.Mods.Common/Traits/KillsSelf.cs | 2 +- OpenRA.Mods.Common/Traits/Mobile.cs | 41 ++++---- .../Traits/Modifiers/FrozenUnderFog.cs | 4 +- .../Traits/Modifiers/HiddenUnderFog.cs | 2 +- .../Traits/Modifiers/HiddenUnderShroud.cs | 2 +- .../Traits/Palettes/PaletteFromFile.cs | 2 +- .../Traits/Palettes/PaletteFromGrayscale.cs | 2 +- .../Traits/Palettes/PaletteFromPng.cs | 2 +- .../Traits/Palettes/PaletteFromRGBA.cs | 2 +- OpenRA.Mods.Common/Traits/ParaDrop.cs | 2 +- OpenRA.Mods.Common/Traits/Parachutable.cs | 6 +- .../Traits/Player/PlaceBuilding.cs | 2 +- .../Traits/Player/PlayerRadarTerrain.cs | 15 ++- OpenRA.Mods.Common/Traits/Production.cs | 4 +- .../Traits/ProductionFromMapEdge.cs | 10 +- .../Traits/ProductionParadrop.cs | 8 +- .../Render/CustomTerrainDebugOverlay.cs | 10 +- OpenRA.Mods.Common/Traits/Render/Hovers.cs | 2 +- .../Traits/Render/LeavesTrails.cs | 10 +- .../Render/WithAircraftLandingEffect.cs | 7 +- .../Traits/Render/WithCrateBody.cs | 2 +- .../Traits/Render/WithGateSpriteBody.cs | 2 +- .../Traits/Render/WithParachute.cs | 4 +- .../Traits/Render/WithShadow.cs | 4 +- .../Traits/Render/WithSpriteBody.cs | 2 +- OpenRA.Mods.Common/Traits/RevealsMap.cs | 2 +- .../Traits/SupportPowers/AirstrikePower.cs | 8 +- .../GrantExternalConditionPower.cs | 4 +- .../Traits/SupportPowers/NukePower.cs | 2 +- .../Traits/SupportPowers/ParatroopersPower.cs | 10 +- .../SupportPowers/SelectDirectionalTarget.cs | 4 +- .../Traits/SupportPowers/SpawnActorPower.cs | 8 +- .../SupportPowers/SupportPowerManager.cs | 4 +- OpenRA.Mods.Common/Traits/Wanders.cs | 8 +- OpenRA.Mods.Common/Traits/World/ActorMap.cs | 34 ++++--- .../Traits/World/BridgeLayer.cs | 2 +- .../Traits/World/BuildableTerrainOverlay.cs | 22 +++-- .../Traits/World/CellTriggerOverlay.cs | 6 +- .../World/CliffBackImpassabilityLayer.cs | 12 +-- .../Traits/World/CrateSpawner.cs | 14 +-- .../Traits/World/CreateMapPlayers.cs | 4 +- .../Traits/World/EditorActorLayer.cs | 15 ++- .../Traits/World/EditorActorPreview.cs | 2 +- .../Traits/World/EditorCursorLayer.cs | 4 +- .../Traits/World/EditorResourceLayer.cs | 18 ++-- .../Traits/World/EditorSelectionLayer.cs | 10 +- .../Traits/World/ElevatedBridgeLayer.cs | 9 +- .../World/HierarchicalPathFinderOverlay.cs | 16 ++-- .../Traits/World/JumpjetActorLayer.cs | 19 ++-- .../Traits/World/LegacyBridgeLayer.cs | 12 +-- OpenRA.Mods.Common/Traits/World/Locomotor.cs | 34 +++---- .../Traits/World/MapStartingLocations.cs | 8 +- .../Traits/World/PathFinderOverlay.cs | 10 +- .../Traits/World/ResourceLayer.cs | 24 +++-- .../Traits/World/ResourceRenderer.cs | 4 +- .../Traits/World/ShroudRenderer.cs | 48 +++++----- .../Traits/World/SmudgeLayer.cs | 6 +- .../Traits/World/SpawnMapActors.cs | 2 +- .../Traits/World/SpawnStartingUnits.cs | 2 +- .../Traits/World/SubterraneanActorLayer.cs | 16 ++-- .../Traits/World/TerrainGeometryOverlay.cs | 20 ++-- .../Traits/World/TerrainLighting.cs | 22 ++--- .../Traits/World/TerrainRenderer.cs | 28 +++--- .../Traits/World/TerrainTunnelLayer.cs | 11 +-- OpenRA.Mods.Common/Util.cs | 8 +- .../UtilityCommands/CheckYaml.cs | 10 +- .../DumpSequenceSheetsCommand.cs | 2 +- .../UtilityCommands/ExtractMapRules.cs | 19 ++-- .../UtilityCommands/ImportLegacyMapCommand.cs | 20 ++-- .../UtilityCommands/ResizeMapCommand.cs | 9 +- .../UtilityCommands/Utilities.cs | 4 +- .../Warheads/CreateEffectWarhead.cs | 12 +-- .../Warheads/CreateResourceWarhead.cs | 8 +- .../Warheads/DestroyResourceWarhead.cs | 9 +- .../Warheads/FireClusterWarhead.cs | 10 +- .../Warheads/LeaveSmudgeWarhead.cs | 10 +- .../Logic/Editor/LayerSelectorLogic.cs | 5 +- .../Widgets/Logic/Editor/MapEditorLogic.cs | 5 +- .../Widgets/Logic/Editor/NewMapLogic.cs | 11 ++- .../Widgets/Logic/GameSaveBrowserLogic.cs | 4 +- .../Widgets/Logic/Ingame/DebugLogic.cs | 7 +- .../Logic/Ingame/GameInfoBriefingLogic.cs | 2 +- .../Widgets/Logic/Ingame/GameInfoLogic.cs | 6 +- .../Hotkeys/EditorQuickSaveHotkeyLogic.cs | 10 +- .../Widgets/Logic/Ingame/IngameMenuLogic.cs | 2 +- .../Ingame/ObserverShroudSelectorLogic.cs | 2 +- .../Logic/Ingame/ObserverStatsLogic.cs | 2 +- OpenRA.Mods.Common/Widgets/RadarWidget.cs | 41 ++++---- .../Widgets/ResourcePreviewWidget.cs | 2 +- .../Widgets/ViewportControllerWidget.cs | 6 +- .../D2kActorPreviewPlaceBuildingPreview.cs | 8 +- .../Traits/Buildings/D2kBuilding.cs | 8 +- OpenRA.Mods.D2k/Traits/Sandworm.cs | 8 +- OpenRA.Mods.D2k/Traits/SpiceBloom.cs | 12 +-- .../Traits/World/BuildableTerrainLayer.cs | 14 +-- .../UtilityCommands/D2kMapImporter.cs | 13 ++- .../Warheads/DamagesConcreteWarhead.cs | 2 +- mods/modcontent/mod.yaml | 2 + 244 files changed, 1115 insertions(+), 1221 deletions(-) delete mode 100644 OpenRA.Game/Map/IMapCell.cs delete mode 100644 OpenRA.Game/Map/IMapResource.cs diff --git a/OpenRA.Game/CPos.cs b/OpenRA.Game/CPos.cs index 41526ad7f890..ee0711a3194e 100644 --- a/OpenRA.Game/CPos.cs +++ b/OpenRA.Game/CPos.cs @@ -66,7 +66,7 @@ public override string ToString() return X + "," + Y + "," + Layer; } - public MPos ToMPos(IMapCell map) + public MPos ToMPos(IMap map) { return ToMPos(map.Grid.Type); } diff --git a/OpenRA.Game/GameRules/WeaponInfo.cs b/OpenRA.Game/GameRules/WeaponInfo.cs index 04be07f1753f..8772d0b1a106 100644 --- a/OpenRA.Game/GameRules/WeaponInfo.cs +++ b/OpenRA.Game/GameRules/WeaponInfo.cs @@ -180,7 +180,7 @@ public bool IsValidTarget(BitSet targetTypes) /// Checks if the weapon is valid against (can target) the target. public bool IsValidAgainst(in Target target, World world, Actor firedBy) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; if (target.Type == TargetType.Actor) return IsValidAgainst(target.Actor, firedBy); @@ -190,15 +190,15 @@ public bool IsValidAgainst(in Target target, World world, Actor firedBy) if (target.Type == TargetType.Terrain) { - var dat = mapCell.DistanceAboveTerrain(target.CenterPosition); + var dat = map.DistanceAboveTerrain(target.CenterPosition); if (dat > AirThreshold) return IsValidTarget(TargetTypeAir); - var cell = mapCell.CellContaining(target.CenterPosition); - if (!mapCell.Contains(cell)) + var cell = map.CellContaining(target.CenterPosition); + if (!map.Contains(cell)) return false; - var cellInfo = mapCell.GetTerrainInfo(cell); + var cellInfo = map.GetTerrainInfo(cell); if (!IsValidTarget(cellInfo.TargetTypes)) return false; diff --git a/OpenRA.Game/Graphics/TerrainSpriteLayer.cs b/OpenRA.Game/Graphics/TerrainSpriteLayer.cs index be3a4dd0f87b..d3737bbcc326 100644 --- a/OpenRA.Game/Graphics/TerrainSpriteLayer.cs +++ b/OpenRA.Game/Graphics/TerrainSpriteLayer.cs @@ -85,16 +85,14 @@ public void Update(CPos cell, ISpriteSequence sequence, PaletteReference palette public void Update(CPos cell, Sprite sprite, PaletteReference palette, float scale = 1f, float alpha = 1f, bool ignoreTint = false) { - var mapCell = (IMapCell)map; - var xyz = float3.Zero; if (sprite != null) { - var cellOrigin = mapCell.CenterOfCell(cell) - new WVec(0, 0, mapCell.Grid.Ramps[mapCell.Ramp[cell]].CenterHeightOffset); + var cellOrigin = map.CenterOfCell(cell) - new WVec(0, 0, map.Grid.Ramps[((IMapElevation)map).Ramp[cell]].CenterHeightOffset); xyz = worldRenderer.Screen3DPosition(cellOrigin) + scale * (sprite.Offset - 0.5f * sprite.Size); } - Update(cell.ToMPos(mapCell.Grid.Type), sprite, palette, xyz, scale, alpha, ignoreTint); + Update(cell.ToMPos(map.Grid.Type), sprite, palette, xyz, scale, alpha, ignoreTint); } void UpdateTint(MPos uv) @@ -115,9 +113,8 @@ void UpdateTint(MPos uv) // This is done by sampling the lighting the corners of the sprite, even though those pixels are // transparent for isometric tiles var tl = worldRenderer.TerrainLighting; - var mapCell = (IMapCell)map; - var pos = mapCell.CenterOfCell(uv.ToCPos((IMapCell)map)); - var step = mapCell.Grid.Type == MapGridType.RectangularIsometric ? 724 : 512; + var pos = map.CenterOfCell(uv.ToCPos(map)); + var step = map.Grid.Type == MapGridType.RectangularIsometric ? 724 : 512; var weights = new[] { tl.TintAt(pos + new WVec(-step, -step, 0)), @@ -180,7 +177,7 @@ public void Update(MPos uv, Sprite sprite, PaletteReference palette, in float3 p } // The vertex buffer does not have geometry for cells outside the map - if (!((IMapCell)map).Tiles.Contains(uv)) + if (!((IMapTiles)map).Tiles.Contains(uv)) return; var offset = rowStride * uv.V + 6 * uv.U; diff --git a/OpenRA.Game/Graphics/Viewport.cs b/OpenRA.Game/Graphics/Viewport.cs index 94b7bb763787..a956378ae41d 100644 --- a/OpenRA.Game/Graphics/Viewport.cs +++ b/OpenRA.Game/Graphics/Viewport.cs @@ -153,7 +153,7 @@ public ScrollDirection GetBlockedDirections() return ret; } - public Viewport(WorldRenderer wr, IMapCell map) + public Viewport(WorldRenderer wr, IMap map) { worldRenderer = wr; var grid = Game.ModData.Manifest.Get(); @@ -166,7 +166,7 @@ public Viewport(WorldRenderer wr, IMapCell map) // The full map is visible in the editor var width = map.MapSize.X * grid.TileSize.Width; var height = map.MapSize.Y * grid.TileSize.Height; - if (((IMapCell)wr.World.Map).Grid.Type == MapGridType.RectangularIsometric) + if (wr.World.Map.Grid.Type == MapGridType.RectangularIsometric) height /= 2; mapBounds = new Rectangle(0, 0, width, height); @@ -260,7 +260,8 @@ void UpdateViewportZooms(bool resetCurrentZoom = true) public CPos ViewToWorld(int2 view) { var world = worldRenderer.Viewport.ViewToWorldPx(view); - var map = (IMapCell)worldRenderer.World.Map; + var map = worldRenderer.World.Map; + var mapRamp = ((IMapElevation)map).Ramp; var candidates = CandidateMouseoverCells(world).ToList(); foreach (var uv in candidates) @@ -270,7 +271,7 @@ public CPos ViewToWorld(int2 view) var s = worldRenderer.ScreenPxPosition(p); if (Math.Abs(s.X - world.X) <= tileSize.Width && Math.Abs(s.Y - world.Y) <= tileSize.Height) { - var ramp = map.Grid.Ramps[map.Ramp.Contains(uv) ? map.Ramp[uv] : 0]; + var ramp = map.Grid.Ramps[mapRamp.Contains(uv) ? mapRamp[uv] : 0]; var pos = map.CenterOfCell(uv.ToCPos(map)) - new WVec(0, 0, ramp.CenterHeightOffset); var screen = ramp.Corners.Select(c => worldRenderer.ScreenPxPosition(pos + c)).ToArray(); if (screen.PolygonContains(world)) @@ -294,18 +295,18 @@ public CPos ViewToWorld(int2 view) } // Something is very wrong, but lets return something that isn't completely bogus and hope the caller can recover - return ((IMapCell)worldRenderer.World.Map).CellContaining(worldRenderer.ProjectedPosition(ViewToWorldPx(view))); + return worldRenderer.World.Map.CellContaining(worldRenderer.ProjectedPosition(ViewToWorldPx(view))); } /// Returns an unfiltered list of all cells that could potentially contain the mouse cursor IEnumerable CandidateMouseoverCells(int2 world) { - var mapCell = (IMapCell)worldRenderer.World.Map; + var map = worldRenderer.World.Map; var minPos = worldRenderer.ProjectedPosition(world); // Find all the cells that could potentially have been clicked - var a = mapCell.CellContaining(minPos - new WVec(1024, 0, 0)).ToMPos(mapCell.Grid.Type); - var b = mapCell.CellContaining(minPos + new WVec(512, 512 * mapCell.Grid.MaximumTerrainHeight, 0)).ToMPos(mapCell.Grid.Type); + var a = map.CellContaining(minPos - new WVec(1024, 0, 0)).ToMPos(map.Grid.Type); + var b = map.CellContaining(minPos + new WVec(512, 512 * map.Grid.MaximumTerrainHeight, 0)).ToMPos(map.Grid.Type); for (var v = b.V; v >= a.V; v--) for (var u = b.U; u >= a.U; u--) @@ -347,7 +348,7 @@ public Rectangle GetScissorBounds(bool insideBounds) { // Visible rectangle in world coordinates (expanded to the corners of the cells) var bounds = insideBounds ? VisibleCellsInsideBounds : AllVisibleCells; - var map = (IMapCell)worldRenderer.World.Map; + var map = worldRenderer.World.Map; var ctl = map.CenterOfCell(((MPos)bounds.TopLeft).ToCPos(map)) - new WVec(512, 512, 0); var cbr = map.CenterOfCell(((MPos)bounds.BottomRight).ToCPos(map)) + new WVec(512, 512, 0); @@ -362,7 +363,7 @@ public Rectangle GetScissorBounds(bool insideBounds) ProjectedCellRegion CalculateVisibleCells(bool insideBounds) { - var map = (IMapCell)worldRenderer.World.Map; + var map = worldRenderer.World.Map; // Calculate the projected cell position at the corners of the visible area var tl = (PPos)map.CellContaining(worldRenderer.ProjectedPosition(TopLeft)).ToMPos(map); diff --git a/OpenRA.Game/Graphics/WorldRenderer.cs b/OpenRA.Game/Graphics/WorldRenderer.cs index 13573aae8ad3..e3aeb5140794 100644 --- a/OpenRA.Game/Graphics/WorldRenderer.cs +++ b/OpenRA.Game/Graphics/WorldRenderer.cs @@ -48,10 +48,10 @@ public sealed class WorldRenderer : IDisposable internal WorldRenderer(ModData modData, World world) { World = world; - var mapCell = (IMapCell)World.Map; - TileSize = mapCell.Grid.TileSize; - TileScale = mapCell.Grid.Type == MapGridType.RectangularIsometric ? 1448 : 1024; - Viewport = new Viewport(this, (IMapCell)world.Map); + var map = World.Map; + TileSize = map.Grid.TileSize; + TileScale = map.Grid.Type == MapGridType.RectangularIsometric ? 1448 : 1024; + Viewport = new Viewport(this, world.Map); createPaletteReference = CreatePaletteReference; diff --git a/OpenRA.Game/MPos.cs b/OpenRA.Game/MPos.cs index d42745728e2b..4d76c814d443 100644 --- a/OpenRA.Game/MPos.cs +++ b/OpenRA.Game/MPos.cs @@ -37,7 +37,7 @@ public MPos Clamp(Rectangle r) public override string ToString() { return U + "," + V; } - public CPos ToCPos(IMapCell map) + public CPos ToCPos(IMap map) { return ToCPos(map.Grid.Type); } diff --git a/OpenRA.Game/Map/CellLayer.cs b/OpenRA.Game/Map/CellLayer.cs index 74aedbcb405b..37a80edf823e 100644 --- a/OpenRA.Game/Map/CellLayer.cs +++ b/OpenRA.Game/Map/CellLayer.cs @@ -19,7 +19,7 @@ public sealed class CellLayer : CellLayerBase { public event Action CellEntryChanged = null; - public CellLayer(IMapCell map) + public CellLayer(IMap map) : base(map) { } public CellLayer(MapGridType gridType, Size size) diff --git a/OpenRA.Game/Map/CellLayerBase.cs b/OpenRA.Game/Map/CellLayerBase.cs index 9713498fc6f6..305334f0b248 100644 --- a/OpenRA.Game/Map/CellLayerBase.cs +++ b/OpenRA.Game/Map/CellLayerBase.cs @@ -24,7 +24,7 @@ public abstract class CellLayerBase : IEnumerable protected readonly T[] Entries; protected readonly Rectangle Bounds; - public CellLayerBase(IMapCell map) + public CellLayerBase(IMap map) : this(map.Grid.Type, new Size(map.MapSize.X, map.MapSize.Y)) { } public CellLayerBase(MapGridType gridType, Size size) diff --git a/OpenRA.Game/Map/IMap.cs b/OpenRA.Game/Map/IMap.cs index 0f617e457589..f6aa77c333b5 100644 --- a/OpenRA.Game/Map/IMap.cs +++ b/OpenRA.Game/Map/IMap.cs @@ -1,45 +1,76 @@ using System; using System.Collections.Generic; -using System.IO; -using OpenRA.FileSystem; using OpenRA.Primitives; +using OpenRA.Support; +using OpenRA.Traits; namespace OpenRA { public interface IMap { - short InvalidCachedTerrainIndex { get; } - string RequiresMod { get; set; } - string Title { get; } - string Author { get; } - bool LockPreview { get; } + Dictionary ReplacedInvalidTerrainTiles { get; } + MapGrid Grid { get; } + int2 MapSize { get; } + string Tileset { get; } + Ruleset Rules { get; } + CellRegion AllCells { get; } + List AllEdgeCells { get; } + WDist CellHeightStep { get; } + CellLayer CustomTerrain { get; } + WPos ProjectedBottomRight { get; } + PPos[] ProjectedCells { get; } + WPos ProjectedTopLeft { get; } Rectangle Bounds { get; } - MapVisibility Visibility { get; } - string[] Categories { get; } - string[] Translations { get; } + int MapFormat { get; } + byte GetTerrainIndex(CPos cell); + TerrainTypeInfo GetTerrainInfo(CPos cell); + void NewSize(Size size, ITerrainInfo terrainInfo); + WVec Offset(CVec delta, int dz); + WAngle FacingBetween(CPos cell, CPos towards, WAngle fallbackfacing); + IEnumerable FindTilesInAnnulus(CPos center, int minRange, int maxRange, bool allowOutsideBounds = false); + IEnumerable FindTilesInCircle(CPos center, int maxRange, bool allowOutsideBounds = false); + CPos CellContaining(WPos pos); + PPos ProjectedCellCovering(WPos pos); + WDist DistanceAboveTerrain(WPos pos); + WPos CenterOfCell(CPos cell); + WPos CenterOfSubCell(CPos cell, SubCell subCell); + CPos ChooseClosestEdgeCell(CPos cell); + MPos ChooseClosestEdgeCell(MPos uv); + CPos ChooseClosestMatchingEdgeCell(CPos cell, Func match); + CPos ChooseRandomCell(MersenneTwister rand); + CPos ChooseRandomEdgeCell(MersenneTwister rand); + CPos Clamp(CPos cell); + MPos Clamp(MPos uv); + PPos Clamp(PPos puv); + bool Contains(CPos cell); + bool Contains(MPos uv); + bool Contains(PPos puv); + WDist DistanceToEdge(WPos pos, in WVec dir); + PPos[] ProjectedCellsCovering(MPos uv); - int2 MapSize { get; } - List PlayerDefinitions { get; set; } - List ActorDefinitions { get; set; } + event Action CellProjectionChanged; + byte ProjectedHeight(PPos puv); + void Resize(int width, int height); + void SetBounds(PPos tl, PPos br); + WRot TerrainOrientation(CPos cell); + List Unproject(PPos puv); + (Color Left, Color Right) GetTerrainColorPair(MPos uv); + byte[] SavePreview(); + } - MiniYaml RuleDefinitions { get; } - MiniYaml SequenceDefinitions { get; } - MiniYaml ModelSequenceDefinitions { get; } - MiniYaml WeaponDefinitions { get; } - MiniYaml VoiceDefinitions { get; } - MiniYaml MusicDefinitions { get; } - MiniYaml NotificationDefinitions { get; } - bool InvalidCustomRules { get; } - Exception InvalidCustomRulesException { get; } - IReadOnlyPackage Package { get; } - Ruleset Rules { get; } - string Uid { get; } - bool Exists(string filename); - bool IsExternalModFile(string filename); - Stream Open(string filename); - void Save(IReadWritePackage package); - string Translate(string key, IDictionary args = null); - bool TryGetPackageContaining(string path, out IReadOnlyPackage package, out string filename); - bool TryOpen(string filename, out Stream s); + public interface IMapElevation : IMap + { + CellLayer Ramp { get; } + CellLayer Height { get; } + } + + public interface IMapTiles : IMap + { + CellLayer Tiles { get; } + } + + public interface IMapResource : IMap + { + CellLayer Resources { get; } } } diff --git a/OpenRA.Game/Map/IMapCell.cs b/OpenRA.Game/Map/IMapCell.cs deleted file mode 100644 index b5f3591ee169..000000000000 --- a/OpenRA.Game/Map/IMapCell.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Collections.Generic; -using OpenRA.Primitives; -using OpenRA.Support; -using OpenRA.Traits; - -namespace OpenRA -{ - public interface IMapCell : IMap - { - Dictionary ReplacedInvalidTerrainTiles { get; } - MapGrid Grid { get; } - string Tileset { get; } - CellRegion AllCells { get; } - List AllEdgeCells { get; } - WDist CellHeightStep { get; } - CellLayer CustomTerrain { get; } - CellLayer Height { get; } - WPos ProjectedBottomRight { get; } - PPos[] ProjectedCells { get; } - WPos ProjectedTopLeft { get; } - CellLayer Ramp { get; } - CellLayer Tiles { get; } - byte GetTerrainIndex(CPos cell); - TerrainTypeInfo GetTerrainInfo(CPos cell); - void NewSize(Size size, ITerrainInfo terrainInfo); - WVec Offset(CVec delta, int dz); - WAngle FacingBetween(CPos cell, CPos towards, WAngle fallbackfacing); - IEnumerable FindTilesInAnnulus(CPos center, int minRange, int maxRange, bool allowOutsideBounds = false); - IEnumerable FindTilesInCircle(CPos center, int maxRange, bool allowOutsideBounds = false); - CPos CellContaining(WPos pos); - PPos ProjectedCellCovering(WPos pos); - WDist DistanceAboveTerrain(WPos pos); - WPos CenterOfCell(CPos cell); - WPos CenterOfSubCell(CPos cell, SubCell subCell); - CPos ChooseClosestEdgeCell(CPos cell); - MPos ChooseClosestEdgeCell(MPos uv); - CPos ChooseClosestMatchingEdgeCell(CPos cell, Func match); - CPos ChooseRandomCell(MersenneTwister rand); - CPos ChooseRandomEdgeCell(MersenneTwister rand); - CPos Clamp(CPos cell); - MPos Clamp(MPos uv); - PPos Clamp(PPos puv); - bool Contains(CPos cell); - bool Contains(MPos uv); - bool Contains(PPos puv); - WDist DistanceToEdge(WPos pos, in WVec dir); - PPos[] ProjectedCellsCovering(MPos uv); - byte ProjectedHeight(PPos puv); - void Resize(int width, int height); - void SetBounds(PPos tl, PPos br); - WRot TerrainOrientation(CPos cell); - List Unproject(PPos puv); - (Color Left, Color Right) GetTerrainColorPair(MPos uv); - byte[] SavePreview(); - } -} diff --git a/OpenRA.Game/Map/IMapResource.cs b/OpenRA.Game/Map/IMapResource.cs deleted file mode 100644 index 75a345c03215..000000000000 --- a/OpenRA.Game/Map/IMapResource.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using OpenRA.Primitives; -using OpenRA.Support; -using OpenRA.Traits; - -namespace OpenRA -{ - public interface IMapResource : IMap - { - CellLayer Resources { get; } - } -} diff --git a/OpenRA.Game/Map/Map.cs b/OpenRA.Game/Map/Map.cs index 6afb8f595a6c..4b397174849f 100644 --- a/OpenRA.Game/Map/Map.cs +++ b/OpenRA.Game/Map/Map.cs @@ -14,7 +14,6 @@ using System.IO; using System.Text.RegularExpressions; using OpenRA.FileSystem; -using OpenRA.Primitives; namespace OpenRA { @@ -28,53 +27,28 @@ public enum MapVisibility public interface IMapLoader : IGlobalModData { - IMap Load(ModData modData, IReadOnlyPackage package); - IMap Create(ModData modData, ITerrainInfo terrainInfo, int width, int height); + Map Load(ModData modData, IReadOnlyPackage package); + Map Create(ModData modData, ITerrainInfo terrainInfo, int width, int height); string ComputeUID(ModData modData, IReadOnlyPackage package); void UpdatePreview(ModData modData, MapPreview mapPreview, IReadOnlyPackage p, IReadOnlyPackage parent, MapClassification classification, string[] mapCompatibility, MapGridType gridType); } - public abstract class Map : IReadOnlyFileSystem, IMap + public abstract class Map : IReadOnlyFileSystem { // Standard yaml metadata public const short InvalidCachedTerrainIndex = -1; public string RequiresMod; - string IMap.RequiresMod { get => RequiresMod; set => RequiresMod = value; } public string Title; public string Author; public bool LockPreview; - public Rectangle Bounds; public MapVisibility Visibility = MapVisibility.Lobby; public string[] Categories = { "Conquest" }; public string[] Translations; - - short IMap.InvalidCachedTerrainIndex => InvalidCachedTerrainIndex; - - string IMap.Title => Title; - - string IMap.Author => Author; - - - bool IMap.LockPreview => LockPreview; - - Rectangle IMap.Bounds => Bounds; - - MapVisibility IMap.Visibility => Visibility; - - string[] IMap.Categories => Categories; - - string[] IMap.Translations => Translations; - public readonly MapGrid Grid; - public int2 MapSize { get; protected set; } - int2 IMap.MapSize => MapSize; - // Player and actor yaml. Public for access by the map importers and lint checks. public List PlayerDefinitions = new List(); public List ActorDefinitions = new List(); - List IMap.PlayerDefinitions { get => PlayerDefinitions; set => PlayerDefinitions = value; } - List IMap.ActorDefinitions { get => ActorDefinitions; set => ActorDefinitions = value; } // Custom map yaml. Public for access by the map importers and lint checks public readonly MiniYaml RuleDefinitions; @@ -84,31 +58,19 @@ public abstract class Map : IReadOnlyFileSystem, IMap public readonly MiniYaml VoiceDefinitions; public readonly MiniYaml MusicDefinitions; public readonly MiniYaml NotificationDefinitions; - MiniYaml IMap.RuleDefinitions => RuleDefinitions; - MiniYaml IMap.SequenceDefinitions => SequenceDefinitions; - MiniYaml IMap.ModelSequenceDefinitions => ModelSequenceDefinitions; - MiniYaml IMap.WeaponDefinitions => WeaponDefinitions; - MiniYaml IMap.VoiceDefinitions => VoiceDefinitions; - MiniYaml IMap.MusicDefinitions => MusicDefinitions; - MiniYaml IMap.NotificationDefinitions => NotificationDefinitions; public readonly Dictionary ReplacedInvalidTerrainTiles = new Dictionary(); - protected CVec[][] GridTilesByDistance => Grid.TilesByDistance; - public IReadOnlyPackage Package { get; protected set; } public string Uid { get; protected set; } - - public Ruleset Rules { get; protected set; } public bool InvalidCustomRules { get; protected set; } public Exception InvalidCustomRulesException { get; protected set; } // Internal data #pragma warning disable IDE1006 // Naming Styles protected readonly ModData modData; -#pragma warning restore IDE1006 // Naming Styles - protected Translation Translation; +#pragma warning restore IDE1006 // Naming Styles public abstract void Save(IReadWritePackage package); @@ -143,15 +105,6 @@ protected Map(ModData modData) // Empty rules that can be added to by the importers. // Will be dropped on save if nothing is added to it RuleDefinitions = new MiniYaml(""); - - var previewData = SavePreview(); - if (Package != toPackage || !Enumerable.SequenceEqual(previewData, Package.GetStream("map.png").ReadAllBytes())) - toPackage.Update("map.png", previewData); - } - - var binaryData = SaveBinaryData(); - if (Package != toPackage || !Enumerable.SequenceEqual(binaryData, Package.GetStream("map.bin").ReadAllBytes())) - toPackage.Update("map.bin", binaryData); } public Stream Open(string filename) diff --git a/OpenRA.Game/Map/MapCache.cs b/OpenRA.Game/Map/MapCache.cs index 6e543924cde8..583f75f84855 100644 --- a/OpenRA.Game/Map/MapCache.cs +++ b/OpenRA.Game/Map/MapCache.cs @@ -213,7 +213,7 @@ public IEnumerable EnumerateMapPackagesWithoutCaching(MapClas yield return mapPackage; } - public IEnumerable EnumerateMapsWithoutCaching(MapClassification classification = MapClassification.System) + public IEnumerable EnumerateMapsWithoutCaching(MapClassification classification = MapClassification.System) { foreach (var mapPackage in EnumerateMapPackagesWithoutCaching(classification)) yield return modData.MapLoader.Load(modData, mapPackage); diff --git a/OpenRA.Game/Map/MapGrid.cs b/OpenRA.Game/Map/MapGrid.cs index b2457738a744..6cfbc6f105da 100644 --- a/OpenRA.Game/Map/MapGrid.cs +++ b/OpenRA.Game/Map/MapGrid.cs @@ -123,7 +123,7 @@ public class MapGrid : IGlobalModData public CellRamp[] Ramps { get; } - internal readonly CVec[][] TilesByDistance; + public readonly CVec[][] TilesByDistance; public MapGrid(MiniYaml yaml) { diff --git a/OpenRA.Game/Map/MapPreview.cs b/OpenRA.Game/Map/MapPreview.cs index 37d893e7d5c9..09082ad5ead7 100644 --- a/OpenRA.Game/Map/MapPreview.cs +++ b/OpenRA.Game/Map/MapPreview.cs @@ -255,7 +255,7 @@ public MapPreview(ModData modData, string uid, MapGridType gridType, MapCache ca } // For linting purposes only! - public MapPreview(IMap map, ModData modData) + public MapPreview(Map map, ModData modData) { this.modData = modData; cache = modData.MapCache; @@ -273,17 +273,16 @@ public MapPreview(IMap map, ModData modData) innerData = new InnerData { - // TO DO: Check if this MapFormat retrieval is correct and working - MapFormat = Map.GetMapFormat(Package), + MapFormat = ((IMap)map).MapFormat, Title = map.Title, Categories = map.Categories, Author = map.Author, - TileSet = ((IMapCell)map).Tileset, + TileSet = ((IMap)map).Tileset, Players = mapPlayers, PlayerCount = mapPlayers.Players.Count(x => x.Value.Playable), SpawnPoints = spawns.ToArray(), - GridType = ((IMapCell)map).Grid.Type, - Bounds = map.Bounds, + GridType = ((IMap)map).Grid.Type, + Bounds = ((IMap)map).Bounds, Preview = null, Status = MapStatus.Available, Class = MapClassification.Unknown, diff --git a/OpenRA.Game/Map/ProjectedCellLayer.cs b/OpenRA.Game/Map/ProjectedCellLayer.cs index 457bee8ee906..7464f78fabc6 100644 --- a/OpenRA.Game/Map/ProjectedCellLayer.cs +++ b/OpenRA.Game/Map/ProjectedCellLayer.cs @@ -17,7 +17,7 @@ public sealed class ProjectedCellLayer : CellLayerBase { public int MaxIndex => Size.Width * Size.Height; - public ProjectedCellLayer(IMapCell map) + public ProjectedCellLayer(IMap map) : base(map) { } public ProjectedCellLayer(MapGridType gridType, Size size) diff --git a/OpenRA.Game/Map/ProjectedCellRegion.cs b/OpenRA.Game/Map/ProjectedCellRegion.cs index f410271a468e..e34203ff3710 100644 --- a/OpenRA.Game/Map/ProjectedCellRegion.cs +++ b/OpenRA.Game/Map/ProjectedCellRegion.cs @@ -27,7 +27,7 @@ public class ProjectedCellRegion : IEnumerable readonly MPos mapTopLeft; readonly MPos mapBottomRight; - public ProjectedCellRegion(IMapCell map, PPos topLeft, PPos bottomRight) + public ProjectedCellRegion(IMap map, PPos topLeft, PPos bottomRight) { TopLeft = topLeft; BottomRight = bottomRight; @@ -45,7 +45,7 @@ public ProjectedCellRegion(IMapCell map, PPos topLeft, PPos bottomRight) var heightOffset = map.Grid.Type == MapGridType.RectangularIsometric ? maxHeight : maxHeight / 2; // Use the map Height data array to clamp the bottom coordinate so it doesn't overflow the map - mapBottomRight = map.Height.Clamp(new MPos(bottomRight.U, bottomRight.V + heightOffset)); + mapBottomRight = ((IMapElevation)map).Height.Clamp(new MPos(bottomRight.U, bottomRight.V + heightOffset)); } public bool Contains(PPos puv) diff --git a/OpenRA.Game/ModData.cs b/OpenRA.Game/ModData.cs index 5da141f57b75..a3713e83c90b 100644 --- a/OpenRA.Game/ModData.cs +++ b/OpenRA.Game/ModData.cs @@ -164,17 +164,17 @@ public Map PrepareMap(string uid) if (MapCache[uid].Status != MapStatus.Available) throw new InvalidDataException($"Invalid map uid: {uid}"); - // TO DO: Make loader use IMap interface instead of Map + // TODO: Make loader use IMap interface instead of Map Map map; using (new Support.PerfTimer("Map")) - map = (Map)MapLoader.Load(this, MapCache[uid].Package); + map = MapLoader.Load(this, MapCache[uid].Package); // Reinitialize all our assets InitializeLoaders(map); // Load music with map assets mounted using (new Support.PerfTimer("Map.Music")) - foreach (var entry in map.Rules.Music) + foreach (var entry in ((IMap)map).Rules.Music) entry.Value.Load(map); return map; diff --git a/OpenRA.Game/Player.cs b/OpenRA.Game/Player.cs index fc6556cbd12d..2e4b6441e33b 100644 --- a/OpenRA.Game/Player.cs +++ b/OpenRA.Game/Player.cs @@ -156,7 +156,7 @@ public Player(World world, Session.Client client, PlayerReference pr, MersenneTw InternalName = pr.Name; PlayerReference = pr; - inMissionMap = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector); + inMissionMap = ((Map)world.Map).Visibility.HasFlag(MapVisibility.MissionSelector); // Real player or host-created bot if (client != null) diff --git a/OpenRA.Game/Scripting/ScriptContext.cs b/OpenRA.Game/Scripting/ScriptContext.cs index e3ca3ddcd75f..4013916ecf8b 100644 --- a/OpenRA.Game/Scripting/ScriptContext.cs +++ b/OpenRA.Game/Scripting/ScriptContext.cs @@ -201,7 +201,7 @@ public sealed class ScriptContext : IDisposable using (var loadScript = (LuaFunction)runtime.Globals["ExecuteSandboxedScript"]) { foreach (var s in scripts) - loadScript.Call(s, world.Map.Open(s).ReadAllText()).Dispose(); + loadScript.Call(s, ((Map)world.Map).Open(s).ReadAllText()).Dispose(); } } diff --git a/OpenRA.Game/Support/ExceptionHandler.cs b/OpenRA.Game/Support/ExceptionHandler.cs index c4813f02d825..45c08c3a6a86 100644 --- a/OpenRA.Game/Support/ExceptionHandler.cs +++ b/OpenRA.Game/Support/ExceptionHandler.cs @@ -38,7 +38,7 @@ public static void HandleFatalError(Exception ex) if (Game.OrderManager != null && Game.OrderManager.World != null && Game.OrderManager.World.Map != null) { var map = Game.OrderManager.World.Map; - Log.Write("exception", $"on map {map.Uid} ({map.Title} by {map.Author})."); + Log.Write("exception", $"on map {((Map)map).Uid} ({((Map)map).Title} by {((Map)map).Author})."); } Log.Write("exception", $"Date: {DateTime.UtcNow:u}"); diff --git a/OpenRA.Game/Traits/Player/FrozenActorLayer.cs b/OpenRA.Game/Traits/Player/FrozenActorLayer.cs index 240a1c0cc29c..f74429ce442a 100644 --- a/OpenRA.Game/Traits/Player/FrozenActorLayer.cs +++ b/OpenRA.Game/Traits/Player/FrozenActorLayer.cs @@ -367,7 +367,7 @@ public IEnumerable FrozenActorsInRegion(CellRegion region, bool onl public IEnumerable FrozenActorsInCircle(World world, WPos origin, WDist r, bool onlyVisible = true) { - var centerCell = ((IMapCell)world.Map).CellContaining(origin); + var centerCell = world.Map.CellContaining(origin); var cellRange = (r.Length + 1023) / 1024; var tl = centerCell - new CVec(cellRange, cellRange); var br = centerCell + new CVec(cellRange, cellRange); diff --git a/OpenRA.Game/Traits/Player/Shroud.cs b/OpenRA.Game/Traits/Player/Shroud.cs index c60e1f5d36d8..9a41e60e330e 100644 --- a/OpenRA.Game/Traits/Player/Shroud.cs +++ b/OpenRA.Game/Traits/Player/Shroud.cs @@ -95,7 +95,7 @@ public ShroudSource(SourceType type, PPos[] projectedCells) public enum CellVisibility : byte { Hidden = 0x0, Explored = 0x1, Visible = 0x2 } readonly ShroudInfo info; - readonly IMapCell map; + readonly IMap map; // Individual shroud modifier sources (type and area) readonly Dictionary sources = new Dictionary(); @@ -141,7 +141,7 @@ public bool Disabled public Shroud(Actor self, ShroudInfo info) { this.info = info; - map = (IMapCell)self.World.Map; + map = self.World.Map; passiveVisibleCount = new ProjectedCellLayer(map); visibleCount = new ProjectedCellLayer(map); @@ -233,7 +233,7 @@ void ITick.Tick(Actor self) disabledChanged = false; } - public static IEnumerable ProjectedCellsInRange(IMapCell map, WPos pos, WDist minRange, WDist maxRange, int maxHeightDelta = -1) + public static IEnumerable ProjectedCellsInRange(IMap map, WPos pos, WDist minRange, WDist maxRange, int maxHeightDelta = -1) { // Account for potential extra half-cell from odd-height terrain var r = (maxRange.Length + 1023 + 512) / 1024; @@ -257,7 +257,7 @@ public static IEnumerable ProjectedCellsInRange(IMapCell map, WPos pos, WD } } - public static IEnumerable ProjectedCellsInRange(IMapCell map, CPos cell, WDist range, int maxHeightDelta = -1) + public static IEnumerable ProjectedCellsInRange(IMap map, CPos cell, WDist range, int maxHeightDelta = -1) { return ProjectedCellsInRange(map, map.CenterOfCell(cell), WDist.Zero, range, maxHeightDelta); } diff --git a/OpenRA.Game/Traits/Target.cs b/OpenRA.Game/Traits/Target.cs index cea1b0787d06..447515f0a69e 100644 --- a/OpenRA.Game/Traits/Target.cs +++ b/OpenRA.Game/Traits/Target.cs @@ -46,7 +46,7 @@ public enum TargetType : byte { Invalid, Actor, Terrain, FrozenActor } Target(World w, CPos c, SubCell subCell) { type = TargetType.Terrain; - terrainCenterPosition = ((IMapCell)w.Map).CenterOfSubCell(c, subCell); + terrainCenterPosition = w.Map.CenterOfSubCell(c, subCell); terrainPositions = new[] { terrainCenterPosition }; cell = c; this.subCell = subCell; diff --git a/OpenRA.Game/Traits/World/ScreenMap.cs b/OpenRA.Game/Traits/World/ScreenMap.cs index 50127128047f..52852354cec7 100644 --- a/OpenRA.Game/Traits/World/ScreenMap.cs +++ b/OpenRA.Game/Traits/World/ScreenMap.cs @@ -63,7 +63,7 @@ public class ScreenMap : IWorldLoaded public ScreenMap(World world, ScreenMapInfo info) { - var size = ((IMapCell)world.Map).Grid.TileSize; + var size = world.Map.Grid.TileSize; var width = world.Map.MapSize.X * size.Width; var height = world.Map.MapSize.Y * size.Height; diff --git a/OpenRA.Game/World.cs b/OpenRA.Game/World.cs index ed5207af330d..b7d8a676067d 100644 --- a/OpenRA.Game/World.cs +++ b/OpenRA.Game/World.cs @@ -189,7 +189,7 @@ internal World(ModData modData, Map map, OrderManager orderManager, WorldType ty this.modData = modData; Type = type; OrderManager = orderManager; - Map = map; + Map = (IMap)map; if (string.IsNullOrEmpty(modData.Manifest.DefaultOrderGenerator)) throw new InvalidDataException("mod.yaml must define a DefaultOrderGenerator"); @@ -208,7 +208,7 @@ internal World(ModData modData, Map map, OrderManager orderManager, WorldType ty SharedRandom = new MersenneTwister(orderManager.LobbyInfo.GlobalSettings.RandomSeed); LocalRandom = new MersenneTwister(); - ModelCache = modData.ModelSequenceLoader.CacheModels(map, modData, map.Rules.ModelSequences); + ModelCache = modData.ModelSequenceLoader.CacheModels(map, modData, Map.Rules.ModelSequences); var worldActorType = type == WorldType.Editor ? SystemActors.EditorWorld : SystemActors.World; WorldActor = CreateActor(worldActorType.ToString(), new TypeDictionary()); @@ -233,11 +233,11 @@ internal World(ModData modData, Map map, OrderManager orderManager, WorldType ty Mod = Game.ModData.Manifest.Id, Version = Game.ModData.Manifest.Metadata.Version, - MapUid = Map.Uid, - MapTitle = Map.Title + MapUid = map.Uid, + MapTitle = map.Title }; - RulesContainTemporaryBlocker = map.Rules.Actors.Any(a => a.Value.HasTraitInfo()); + RulesContainTemporaryBlocker = Map.Rules.Actors.Any(a => a.Value.HasTraitInfo()); gameSettings = Game.Settings.Game; } diff --git a/OpenRA.Mods.Cnc/Activities/LayMines.cs b/OpenRA.Mods.Cnc/Activities/LayMines.cs index e876faec1c0d..9eda5a647ea4 100644 --- a/OpenRA.Mods.Cnc/Activities/LayMines.cs +++ b/OpenRA.Mods.Cnc/Activities/LayMines.cs @@ -79,7 +79,7 @@ public override bool Tick(Actor self) // Add a CloseEnough range of 512 to the Rearm/Repair activities in order to ensure that we're at the host actor QueueChild(new MoveAdjacentTo(self, Target.FromActor(rearmTarget))); - QueueChild(movement.MoveTo(((IMapCell)self.World.Map).CellContaining(rearmTarget.CenterPosition), ignoreActor: rearmTarget)); + QueueChild(movement.MoveTo(self.World.Map.CellContaining(rearmTarget.CenterPosition), ignoreActor: rearmTarget)); QueueChild(new Resupply(self, rearmTarget, new WDist(512))); returnToBase = true; return false; diff --git a/OpenRA.Mods.Cnc/Activities/Leap.cs b/OpenRA.Mods.Cnc/Activities/Leap.cs index ed50bd4b3fd0..6a8fe6243f47 100644 --- a/OpenRA.Mods.Cnc/Activities/Leap.cs +++ b/OpenRA.Mods.Cnc/Activities/Leap.cs @@ -53,7 +53,7 @@ protected override void OnFirstRun(Actor self) destinationSubCell = targetMobile.ToSubCell; origin = self.CenterPosition; - destination = ((IMapCell)self.World.Map).CenterOfSubCell(destinationCell, destinationSubCell); + destination = self.World.Map.CenterOfSubCell(destinationCell, destinationSubCell); length = Math.Max((origin - destination).Length / speed, 1); // First check if we are still allowed to leap @@ -100,7 +100,7 @@ public override bool Tick(Actor self) attack.DoAttack(self, target); jumpComplete = true; - QueueChild(mobile.LocalMove(self, position, ((IMapCell)self.World.Map).CenterOfSubCell(destinationCell, destinationSubCell))); + QueueChild(mobile.LocalMove(self, position, self.World.Map.CenterOfSubCell(destinationCell, destinationSubCell))); } return false; diff --git a/OpenRA.Mods.Cnc/Activities/LeapAttack.cs b/OpenRA.Mods.Cnc/Activities/LeapAttack.cs index 6cfdd420d98c..1a67f4fe438b 100644 --- a/OpenRA.Mods.Cnc/Activities/LeapAttack.cs +++ b/OpenRA.Mods.Cnc/Activities/LeapAttack.cs @@ -128,9 +128,9 @@ public override bool Tick(Actor self) // to avoid continuous facing adjustments as the target moves var targetMobile = target.Actor.TraitOrDefault(); var targetSubcell = targetMobile != null ? targetMobile.ToSubCell : SubCell.Any; - var mapCell = (IMapCell)self.World.Map; - var destination = mapCell.CenterOfSubCell(target.Actor.Location, targetSubcell); - var origin = mapCell.CenterOfSubCell(self.Location, mobile.FromSubCell); + var map = self.World.Map; + var destination = map.CenterOfSubCell(target.Actor.Location, targetSubcell); + var origin = map.CenterOfSubCell(self.Location, mobile.FromSubCell); var desiredFacing = (destination - origin).Yaw; if (mobile.Facing != desiredFacing) { diff --git a/OpenRA.Mods.Cnc/Activities/Teleport.cs b/OpenRA.Mods.Cnc/Activities/Teleport.cs index 57a3a7b958a9..c8ea59cf1221 100644 --- a/OpenRA.Mods.Cnc/Activities/Teleport.cs +++ b/OpenRA.Mods.Cnc/Activities/Teleport.cs @@ -35,7 +35,7 @@ public class Teleport : Activity bool killCargo, bool screenFlash, string sound, bool interruptable = true, bool killOnFailure = false, BitSet killDamageTypes = default) { - var max = ((IMapCell)teleporter.World.Map).Grid.MaximumTileSearchRange; + var max = teleporter.World.Map.Grid.MaximumTileSearchRange; if (maximumDistance > max) throw new InvalidOperationException($"Teleport distance cannot exceed the value of MaximumTileSearchRange ({max})."); @@ -75,7 +75,7 @@ public override bool Tick(Actor self) destination = bestCell.Value; Game.Sound.Play(SoundType.World, sound, self.CenterPosition); - Game.Sound.Play(SoundType.World, sound, ((IMapCell)self.World.Map).CenterOfCell(destination)); + Game.Sound.Play(SoundType.World, sound, self.World.Map.CenterOfCell(destination)); self.Trait().SetPosition(self, destination); self.Generation++; @@ -117,12 +117,12 @@ public override bool Tick(Actor self) CPos? ChooseBestDestinationCell(Actor self, CPos destination) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (teleporter == null) return null; - var restrictTo = maximumDistance == null ? null : mapCell.FindTilesInCircle(self.Location, maximumDistance.Value); + var restrictTo = maximumDistance == null ? null : map.FindTilesInCircle(self.Location, maximumDistance.Value); if (maximumDistance != null) destination = restrictTo.MinBy(x => (x - destination).LengthSquared); @@ -131,8 +131,8 @@ public override bool Tick(Actor self) if (pos.CanEnterCell(destination) && teleporter.Owner.Shroud.IsExplored(destination)) return destination; - var max = maximumDistance != null ? maximumDistance.Value : ((IMapCell)teleporter.World.Map).Grid.MaximumTileSearchRange; - foreach (var tile in mapCell.FindTilesInCircle(destination, max)) + var max = maximumDistance != null ? maximumDistance.Value : teleporter.World.Map.Grid.MaximumTileSearchRange; + foreach (var tile in map.FindTilesInCircle(destination, max)) { if (teleporter.Owner.Shroud.IsExplored(tile) && (restrictTo == null || restrictTo.Contains(tile)) diff --git a/OpenRA.Mods.Cnc/Traits/ConyardChronoReturn.cs b/OpenRA.Mods.Cnc/Traits/ConyardChronoReturn.cs index 2a903e1fc25d..5054730aee0a 100644 --- a/OpenRA.Mods.Cnc/Traits/ConyardChronoReturn.cs +++ b/OpenRA.Mods.Cnc/Traits/ConyardChronoReturn.cs @@ -147,8 +147,8 @@ void TriggerVortex() if (mobileInfo.CanEnterCell(self.World, null, destination)) return destination; - var max = ((IMapCell)chronosphere.World.Map).Grid.MaximumTileSearchRange; - foreach (var tile in ((IMapCell)self.World.Map).FindTilesInCircle(destination, max)) + var max = chronosphere.World.Map.Grid.MaximumTileSearchRange; + foreach (var tile in self.World.Map.FindTilesInCircle(destination, max)) if (chronosphere.Owner.Shroud.IsExplored(tile) && mobileInfo.CanEnterCell(self.World, null, tile)) return tile; @@ -192,7 +192,7 @@ void ReturnToOrigin() if (controlgroup.HasValue) self.World.ControlGroups.AddToControlGroup(a, controlgroup.Value); - Game.Sound.Play(SoundType.World, info.ChronoshiftSound, ((IMapCell)self.World.Map).CenterOfCell(destination.Value)); + Game.Sound.Play(SoundType.World, info.ChronoshiftSound, self.World.Map.CenterOfCell(destination.Value)); self.Dispose(); } diff --git a/OpenRA.Mods.Cnc/Traits/Minelayer.cs b/OpenRA.Mods.Cnc/Traits/Minelayer.cs index 910b041c1f6f..573914bedeb3 100644 --- a/OpenRA.Mods.Cnc/Traits/Minelayer.cs +++ b/OpenRA.Mods.Cnc/Traits/Minelayer.cs @@ -82,7 +82,7 @@ public Minelayer(Actor self, MinelayerInfo info) Info = info; this.self = self; - var tileset = ((IMapCell)self.World.Map).Tileset.ToLowerInvariant(); + var tileset = self.World.Map.Tileset.ToLowerInvariant(); if (self.World.Map.Rules.Sequences.HasSequence("overlay", $"{Info.TileValidName}-{tileset}")) Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", $"{Info.TileValidName}-{tileset}").GetSprite(0); else @@ -103,7 +103,7 @@ Order IIssueOrder.IssueOrder(Actor self, IOrderTargeter order, in Target target, switch (order.OrderID) { case "BeginMinefield": - var start = ((IMapCell)self.World.Map).CellContaining(target.CenterPosition); + var start = self.World.Map.CellContaining(target.CenterPosition); if (self.World.OrderGenerator is MinefieldOrderGenerator generator) generator.AddMinelayer(self); else @@ -132,7 +132,7 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) if (order.OrderString != "BeginMinefield" && order.OrderString != "PlaceMinefield" && order.OrderString != "PlaceMine") return; - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (order.OrderString == "BeginMinefield") minefieldStart = cell; else if (order.OrderString == "PlaceMine") @@ -194,15 +194,15 @@ static IEnumerable GetMinefieldCells(CPos start, CPos end, WDist depth) public bool IsCellAcceptable(Actor self, CPos cell) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; if (Info.TerrainTypes.Count == 0) return true; - var terrainType = mapCell.GetTerrainInfo(cell).Type; + var terrainType = map.GetTerrainInfo(cell).Type; return Info.TerrainTypes.Contains(terrainType); } @@ -223,7 +223,7 @@ public MinefieldOrderGenerator(Actor a, CPos xy, bool queued) this.queued = queued; minelayer = a.Trait(); - var tileset = ((IMapCell)a.World.Map).Tileset.ToLowerInvariant(); + var tileset = a.World.Map.Tileset.ToLowerInvariant(); if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileValidName}-{tileset}")) { var validSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileValidName}-{tileset}"); @@ -298,7 +298,7 @@ protected override void SelectionChanged(World world, IEnumerable selecte protected override IEnumerable Render(WorldRenderer wr, World world) { yield break; } protected override IEnumerable RenderAboveShroud(WorldRenderer wr, World world) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; var minelayer = minelayers.FirstOrDefault(m => m.IsInWorld && !m.IsDead); if (minelayer == null) yield break; @@ -316,7 +316,7 @@ protected override IEnumerable RenderAboveShroud(WorldRenderer wr, { var tile = validTile; var alpha = validAlpha; - if (!mapCell.Contains(c)) + if (!map.Contains(c)) { tile = blockedTile; alpha = blockedAlpha; @@ -338,7 +338,7 @@ protected override IEnumerable RenderAboveShroud(WorldRenderer wr, alpha = blockedAlpha; } - yield return new SpriteRenderable(tile, mapCell.CenterOfCell(c), WVec.Zero, -511, pal, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); + yield return new SpriteRenderable(tile, map.CenterOfCell(c), WVec.Zero, -511, pal, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); } } @@ -366,13 +366,13 @@ public BeginMinefieldOrderTargeter(string cursor) public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifiers, ref string cursor) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (target.Type != TargetType.Terrain) return false; - var location = mapCell.CellContaining(target.CenterPosition); - if (!mapCell.Contains(location)) + var location = map.CellContaining(target.CenterPosition); + if (!map.Contains(location)) return false; cursor = this.cursor; diff --git a/OpenRA.Mods.Cnc/Traits/PortableChrono.cs b/OpenRA.Mods.Cnc/Traits/PortableChrono.cs index 4b05035e4de8..6f85733dc49e 100644 --- a/OpenRA.Mods.Cnc/Traits/PortableChrono.cs +++ b/OpenRA.Mods.Cnc/Traits/PortableChrono.cs @@ -138,7 +138,7 @@ public void ResolveOrder(Actor self, Order order) if (!order.Queued) self.CancelActivity(); - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (maxDistance != null) self.QueueActivity(move.MoveWithinRange(order.Target, WDist.FromCells(maxDistance.Value), targetLineColor: Info.TargetLineColor)); @@ -195,7 +195,7 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier { if (modifiers.HasModifier(TargetModifiers.ForceMove)) { - var xy = ((IMapCell)self.World.Map).CellContaining(target.CenterPosition); + var xy = self.World.Map.CellContaining(target.CenterPosition); IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); diff --git a/OpenRA.Mods.Cnc/Traits/Render/WithBuildingBib.cs b/OpenRA.Mods.Cnc/Traits/Render/WithBuildingBib.cs index 293aeca5e645..4a542fa8838d 100644 --- a/OpenRA.Mods.Cnc/Traits/Render/WithBuildingBib.cs +++ b/OpenRA.Mods.Cnc/Traits/Render/WithBuildingBib.cs @@ -44,7 +44,7 @@ public IEnumerable RenderPreviewSprites(ActorPreviewInitializer i var width = bi.Dimensions.X; var bibOffset = bi.Dimensions.Y - rows; var centerOffset = bi.CenterOffset(init.World); - var mapCell = (IMapCell)init.World.Map; + var map = init.World.Map; var location = init.GetValue(CPos.Zero); for (var i = 0; i < rows * width; i++) @@ -56,9 +56,9 @@ public IEnumerable RenderPreviewSprites(ActorPreviewInitializer i // Some mods may define terrain-specific bibs var sequence = Sequence; - if (mapCell.Tiles.Contains(cell)) + if (((IMapTiles)map).Tiles.Contains(cell)) { - var terrain = mapCell.GetTerrainInfo(cell).Type; + var terrain = map.GetTerrainInfo(cell).Type; var testSequence = Sequence + "-" + terrain; if (anim.HasSequence(testSequence)) sequence = testSequence; @@ -68,7 +68,7 @@ public IEnumerable RenderPreviewSprites(ActorPreviewInitializer i anim.IsDecoration = true; // Z-order is one set to the top of the footprint - var offset = mapCell.CenterOfCell(cell) - mapCell.CenterOfCell(location) - centerOffset; + var offset = map.CenterOfCell(cell) - map.CenterOfCell(location) - centerOffset; yield return new SpriteActorPreview(anim, () => offset, () => -(offset.Y + centerOffset.Y + 512), p); } } @@ -100,7 +100,7 @@ void INotifyAddedToWorld.AddedToWorld(Actor self) var bibOffset = bi.Dimensions.Y - rows; var centerOffset = bi.CenterOffset(self.World); var location = self.Location; - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; for (var i = 0; i < rows * width; i++) { @@ -110,14 +110,14 @@ void INotifyAddedToWorld.AddedToWorld(Actor self) var cell = location + cellOffset; // Some mods may define terrain-specific bibs - var terrain = mapCell.GetTerrainInfo(cell).Type; + var terrain = map.GetTerrainInfo(cell).Type; var testSequence = info.Sequence + "-" + terrain; var sequence = anim.HasSequence(testSequence) ? testSequence : info.Sequence; anim.PlayFetchIndex(sequence, () => index); anim.IsDecoration = true; // Z-order is one set to the top of the footprint - var offset = mapCell.CenterOfCell(cell) - mapCell.CenterOfCell(location) - centerOffset; + var offset = map.CenterOfCell(cell) - map.CenterOfCell(location) - centerOffset; var awo = new AnimationWithOffset(anim, () => offset, null, -(offset.Y + centerOffset.Y + 512)); anims.Add(awo); rs.Add(awo, info.Palette); diff --git a/OpenRA.Mods.Cnc/Traits/Render/WithLandingCraftAnimation.cs b/OpenRA.Mods.Cnc/Traits/Render/WithLandingCraftAnimation.cs index 16e76b98c927..940415798c03 100644 --- a/OpenRA.Mods.Cnc/Traits/Render/WithLandingCraftAnimation.cs +++ b/OpenRA.Mods.Cnc/Traits/Render/WithLandingCraftAnimation.cs @@ -56,13 +56,13 @@ public WithLandingCraftAnimation(ActorInitializer init, WithLandingCraftAnimatio public bool ShouldBeOpen() { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; - if (move.CurrentMovementTypes != MovementType.None || mapCell.DistanceAboveTerrain(self.CenterPosition).Length > 0) + if (move.CurrentMovementTypes != MovementType.None || map.DistanceAboveTerrain(self.CenterPosition).Length > 0) return false; - return cargo.CurrentAdjacentCells.Any(c => mapCell.Contains(c) - && info.OpenTerrainTypes.Contains(mapCell.GetTerrainInfo(c).Type)); + return cargo.CurrentAdjacentCells.Any(c => map.Contains(c) + && info.OpenTerrainTypes.Contains(map.GetTerrainInfo(c).Type)); } void Open() diff --git a/OpenRA.Mods.Cnc/Traits/SupportPowers/AttackOrderPower.cs b/OpenRA.Mods.Cnc/Traits/SupportPowers/AttackOrderPower.cs index 8aa7df12827f..ce0add118d7a 100644 --- a/OpenRA.Mods.Cnc/Traits/SupportPowers/AttackOrderPower.cs +++ b/OpenRA.Mods.Cnc/Traits/SupportPowers/AttackOrderPower.cs @@ -101,12 +101,12 @@ public SelectAttackPowerTarget(Actor self, string order, SupportPowerManager man bool IsValidTarget(World world, CPos cell) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - var pos = mapCell.CenterOfCell(cell); + var pos = map.CenterOfCell(cell); var range = attack.GetMaximumRange().LengthSquared; - return mapCell.Contains(cell) && instance.Instances.Any(a => !a.IsTraitPaused && (a.Self.CenterPosition - pos).HorizontalLengthSquared < range); + return map.Contains(cell) && instance.Instances.Any(a => !a.IsTraitPaused && (a.Self.CenterPosition - pos).HorizontalLengthSquared < range); } protected override IEnumerable OrderInner(World world, CPos cell, int2 worldPixel, MouseInput mi) diff --git a/OpenRA.Mods.Cnc/Traits/SupportPowers/ChronoshiftPower.cs b/OpenRA.Mods.Cnc/Traits/SupportPowers/ChronoshiftPower.cs index b81f00849d3d..083e508fe9ac 100644 --- a/OpenRA.Mods.Cnc/Traits/SupportPowers/ChronoshiftPower.cs +++ b/OpenRA.Mods.Cnc/Traits/SupportPowers/ChronoshiftPower.cs @@ -86,11 +86,10 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag PlayLaunchSounds(); var info = (ChronoshiftPowerInfo)Info; - var targetDelta = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition) - order.ExtraLocation; + var targetDelta = self.World.Map.CellContaining(order.Target.CenterPosition) - order.ExtraLocation; foreach (var target in UnitsInRange(order.ExtraLocation)) { - var cs = target.TraitsImplementing() - .FirstEnabledConditionalTraitOrDefault(); + var cs = target.TraitsImplementing().FirstEnabledConditionalTraitOrDefault(); if (cs == null) continue; @@ -129,12 +128,12 @@ public bool SimilarTerrain(CPos xy, CPos sourceLocation) { var a = se.Current; var b = de.Current; - var mapCell = (IMapCell)Self.World.Map; + var map = Self.World.Map; if (!Self.Owner.Shroud.IsExplored(a) || !Self.Owner.Shroud.IsExplored(b)) return false; - if (mapCell.GetTerrainIndex(a) != mapCell.GetTerrainIndex(b)) + if (map.GetTerrainIndex(a) != map.GetTerrainIndex(b)) return false; } @@ -210,7 +209,7 @@ protected override IEnumerable Render(WorldRenderer wr, World world var tiles = power.CellsMatching(xy, footprint, dimensions); var palette = wr.Palette(((ChronoshiftPowerInfo)power.Info).TargetOverlayPalette); foreach (var t in tiles) - yield return new SpriteRenderable(tile, ((IMapCell)wr.World.Map).CenterOfCell(t), WVec.Zero, -511, palette, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); + yield return new SpriteRenderable(tile, wr.World.Map.CenterOfCell(t), WVec.Zero, -511, palette, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); } protected override string GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi) @@ -242,7 +241,7 @@ public SelectDestination(World world, string order, SupportPowerManager manager, dimensions = info.Dimensions; var sequences = world.Map.Rules.Sequences; - var tilesetValid = info.ValidFootprintSequence + "-" + ((IMapCell)world.Map).Tileset.ToLowerInvariant(); + var tilesetValid = info.ValidFootprintSequence + "-" + world.Map.Tileset.ToLowerInvariant(); if (sequences.HasSequence(info.FootprintImage, tilesetValid)) { var validSequence = sequences.GetSequence(info.FootprintImage, tilesetValid); @@ -303,7 +302,7 @@ protected override IEnumerable RenderAboveShroud(WorldRenderer wr, { var xy = wr.Viewport.ViewToWorld(Viewport.LastMousePos); var palette = wr.Palette(power.Info.IconPalette); - var wrMapCell = (IMapCell)wr.World.Map; + var wrMapCell = wr.World.Map; // Destination tiles var delta = xy - sourceLocation; @@ -328,8 +327,8 @@ protected override IEnumerable RenderAboveShroud(WorldRenderer wr, yield return new SpriteRenderable(tile, wrMapCell.CenterOfCell(targetCell), WVec.Zero, -511, palette, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); } - var mapCell = (IMapCell)world.Map; - var offset = mapCell.CenterOfCell(xy) - mapCell.CenterOfCell(sourceLocation); + var map = world.Map; + var offset = map.CenterOfCell(xy) - map.CenterOfCell(sourceLocation); if (unit.CanBeViewedByPlayer(manager.Self.Owner)) foreach (var r in unit.Render(wr)) yield return r.OffsetBy(offset); @@ -356,7 +355,7 @@ protected override IEnumerable Render(WorldRenderer wr, World world // Source tiles foreach (var t in power.CellsMatching(sourceLocation, footprint, dimensions)) - yield return new SpriteRenderable(sourceTile, ((IMapCell)wr.World.Map).CenterOfCell(t), WVec.Zero, -511, palette, 1f, sourceAlpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); + yield return new SpriteRenderable(sourceTile, wr.World.Map.CenterOfCell(t), WVec.Zero, -511, palette, 1f, sourceAlpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); } bool IsValidTarget(CPos xy) diff --git a/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs b/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs index e19a58a74381..b5c1e8591e5f 100644 --- a/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs +++ b/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs @@ -101,14 +101,14 @@ public void SendDropPods(Actor self, Order order, WAngle facing) var approachRotation = WRot.FromYaw(facing); var fallsToEarthInfo = actorInfo.TraitInfo(); var delta = new WVec(0, -altitude * aircraftInfo.Speed / fallsToEarthInfo.Velocity.Length, 0).Rotate(approachRotation); - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; self.World.AddFrameEndTask(w => { var target = order.Target.CenterPosition; - var targetCell = mapCell.CellContaining(target); - var podLocations = mapCell.FindTilesInCircle(targetCell, info.PodScatter) - .Where(c => aircraftInfo.LandableTerrainTypes.Contains(((IMapCell)w.Map).GetTerrainInfo(c).Type) + var targetCell = map.CellContaining(target); + var podLocations = map.FindTilesInCircle(targetCell, info.PodScatter) + .Where(c => aircraftInfo.LandableTerrainTypes.Contains(w.Map.GetTerrainInfo(c).Type) && !self.World.ActorMap.GetActorsAt(c).Any()); if (!podLocations.Any()) @@ -134,7 +134,7 @@ public void SendDropPods(Actor self, Order order, WAngle facing) var unitType = info.UnitTypes.Random(self.World.SharedRandom); var podLocation = podLocations.Random(self.World.SharedRandom); var podTarget = Target.FromCell(w, podLocation); - var location = mapCell.CenterOfCell(podLocation) - delta + new WVec(0, 0, altitude); + var location = map.CenterOfCell(podLocation) - delta + new WVec(0, 0, altitude); var pod = w.CreateActor(false, unitType, new TypeDictionary { diff --git a/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs b/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs index b361d72ae916..d096783d61f1 100644 --- a/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs +++ b/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs @@ -93,7 +93,7 @@ public void Activate(Actor self, Target target) var camera = w.CreateActor(info.CameraActor, new TypeDictionary { - new LocationInit(((IMapCell)self.World.Map).CellContaining(target.CenterPosition)), + new LocationInit(self.World.Map.CellContaining(target.CenterPosition)), new OwnerInit(self.Owner), }); diff --git a/OpenRA.Mods.Cnc/Traits/TDGunboat.cs b/OpenRA.Mods.Cnc/Traits/TDGunboat.cs index a29b57897831..44f7d36694f8 100644 --- a/OpenRA.Mods.Cnc/Traits/TDGunboat.cs +++ b/OpenRA.Mods.Cnc/Traits/TDGunboat.cs @@ -49,7 +49,7 @@ IEnumerable IActorPreviewInitInfo.ActorPreviewInits(ActorInfo ai, Act // Used to determine if actor can spawn public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All) { - return ((IMapCell)world.Map).Contains(cell); + return world.Map.Contains(cell); } } @@ -78,7 +78,7 @@ public WAngle Facing [Sync] public WPos CenterPosition { get; private set; } - public CPos TopLeft => ((IMapCell)self.World.Map).CellContaining(CenterPosition); + public CPos TopLeft => self.World.Map.CellContaining(CenterPosition); // Isn't used anyway public WAngle TurnSpeed => WAngle.Zero; @@ -127,7 +127,7 @@ void ITick.Tick(Actor self) if (cachedLocation != self.Location) { // If the actor just left the map, switch facing - if (!((IMapCell)self.World.Map).Contains(self.Location)) + if (!self.World.Map.Contains(self.Location)) Turn(); } @@ -175,7 +175,7 @@ public SubCell GetAvailableSubCell(CPos a, SubCell preferredSubCell = SubCell.An public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any) { - SetPosition(self, ((IMapCell)self.World.Map).CenterOfCell(cell)); + SetPosition(self, self.World.Map.CenterOfCell(cell)); } public void SetPosition(Actor self, WPos pos) diff --git a/OpenRA.Mods.Cnc/Traits/World/TSEditorResourceLayer.cs b/OpenRA.Mods.Cnc/Traits/World/TSEditorResourceLayer.cs index 17a85cd8379a..e090ea695c98 100644 --- a/OpenRA.Mods.Cnc/Traits/World/TSEditorResourceLayer.cs +++ b/OpenRA.Mods.Cnc/Traits/World/TSEditorResourceLayer.cs @@ -42,9 +42,9 @@ public TSEditorResourceLayer(Actor self, TSEditorResourceLayerInfo info) bool IsValidVeinNeighbour(CPos cell, CPos neighbour) { - var mapCell = (IMapCell)Map; + var mapRamp = ((IMapElevation)Map).Ramp; - if (!mapCell.Contains(neighbour)) + if (!Map.Contains(neighbour)) return false; // Cell is automatically valid if it contains a veinhole actor @@ -52,23 +52,22 @@ bool IsValidVeinNeighbour(CPos cell, CPos neighbour) return true; // Neighbour must be flat or a cardinal slope, unless the resource cell itself is a slope - if (mapCell.Ramp[cell] == 0 && mapCell.Ramp[neighbour] > 4) + if (mapRamp[cell] == 0 && mapRamp[neighbour] > 4) return false; var terrainInfo = Map.Rules.TerrainInfo; - var terrainType = terrainInfo.TerrainTypes[terrainInfo.GetTerrainInfo(mapCell.Tiles[neighbour]).TerrainType].Type; + var terrainType = terrainInfo.TerrainTypes[terrainInfo.GetTerrainInfo(((IMapTiles)Map).Tiles[neighbour]).TerrainType].Type; return info.ResourceTypes[info.VeinType].AllowedTerrainTypes.Contains(terrainType); } protected override bool AllowResourceAt(string resourceType, CPos cell) { - var mapCell = (IMapCell)Map; var mapResources = ((IMapResource)Map).Resources; if (!mapResources.Contains(cell)) return false; // Resources are allowed on flat terrain and cardinal slopes - if (mapCell.Ramp[cell] > 4) + if (((IMapElevation)Map).Ramp[cell] > 4) return false; if (!info.ResourceTypes.TryGetValue(resourceType, out var resourceInfo)) @@ -76,7 +75,7 @@ protected override bool AllowResourceAt(string resourceType, CPos cell) // Ignore custom terrain types when spawning resources in the editor var terrainInfo = Map.Rules.TerrainInfo; - var terrainType = terrainInfo.TerrainTypes[terrainInfo.GetTerrainInfo(mapCell.Tiles[cell]).TerrainType].Type; + var terrainType = terrainInfo.TerrainTypes[terrainInfo.GetTerrainInfo(((IMapTiles)Map).Tiles[cell]).TerrainType].Type; if (!resourceInfo.AllowedTerrainTypes.Contains(terrainType)) return false; diff --git a/OpenRA.Mods.Cnc/Traits/World/TSResourceLayer.cs b/OpenRA.Mods.Cnc/Traits/World/TSResourceLayer.cs index bef08970c382..333a7eb78858 100644 --- a/OpenRA.Mods.Cnc/Traits/World/TSResourceLayer.cs +++ b/OpenRA.Mods.Cnc/Traits/World/TSResourceLayer.cs @@ -74,7 +74,7 @@ void INotifyActorDisposing.Disposing(Actor self) bool IsValidResourceNeighbour(CPos cell, CPos neighbour) { - if (!((IMapCell)Map).Contains(neighbour)) + if (!Map.Contains(neighbour)) return false; // Non-vein resources are not allowed in the cardinal neighbours to @@ -84,9 +84,9 @@ bool IsValidResourceNeighbour(CPos cell, CPos neighbour) bool IsValidVeinNeighbour(CPos cell, CPos neighbour) { - var mapCell = (IMapCell)Map; + var mapRamp = ((IMapElevation)Map).Ramp; - if (!mapCell.Contains(neighbour)) + if (!Map.Contains(neighbour)) return false; // Cell is automatically valid if it contains a veinhole actor @@ -94,35 +94,35 @@ bool IsValidVeinNeighbour(CPos cell, CPos neighbour) return true; // Neighbour must be flat or a cardinal slope, unless the resource cell itself is a slope - if (mapCell.Ramp[cell] == 0 && mapCell.Ramp[neighbour] > 4) + if (mapRamp[cell] == 0 && mapRamp[neighbour] > 4) return false; // Neighbour must be have a compatible terrain type (which also implies no other resources) - var neighbourTerrain = mapCell.GetTerrainInfo(neighbour).Type; + var neighbourTerrain = Map.GetTerrainInfo(neighbour).Type; var veinInfo = info.ResourceTypes[info.VeinType]; return neighbourTerrain == veinInfo.TerrainType || veinInfo.AllowedTerrainTypes.Contains(neighbourTerrain); } protected override bool AllowResourceAt(string resourceType, CPos cell) { - var mapCell = (IMapCell)Map; + var mapRamp = ((IMapElevation)Map).Ramp; - if (!mapCell.Contains(cell)) + if (!Map.Contains(cell)) return false; // Resources are allowed on flat terrain and cardinal slopes - if (mapCell.Ramp[cell] > 4) + if (mapRamp[cell] > 4) return false; if (!info.ResourceTypes.TryGetValue(resourceType, out var resourceInfo)) return false; - if (!resourceInfo.AllowedTerrainTypes.Contains(mapCell.GetTerrainInfo(cell).Type)) + if (!resourceInfo.AllowedTerrainTypes.Contains(Map.GetTerrainInfo(cell).Type)) return false; // Ensure there is space for the vein border tiles (not needed on ramps) var check = resourceType == info.VeinType ? (Func)IsValidVeinNeighbour : IsValidResourceNeighbour; - var blockedByNeighbours = mapCell.Ramp[cell] == 0 && !Common.Util.ExpandFootprint(cell, false).All(c => check(cell, c)); + var blockedByNeighbours = mapRamp[cell] == 0 && !Common.Util.ExpandFootprint(cell, false).All(c => check(cell, c)); return !blockedByNeighbours && (resourceType == info.VeinType || !BuildingInfluence.AnyBuildingAt(cell)); } diff --git a/OpenRA.Mods.Cnc/Traits/World/TSTiberiumRenderer.cs b/OpenRA.Mods.Cnc/Traits/World/TSTiberiumRenderer.cs index f1cad5e7ac80..00ea284809ae 100644 --- a/OpenRA.Mods.Cnc/Traits/World/TSTiberiumRenderer.cs +++ b/OpenRA.Mods.Cnc/Traits/World/TSTiberiumRenderer.cs @@ -79,7 +79,7 @@ protected override void WorldLoaded(World w, WorldRenderer wr) protected override ISpriteSequence ChooseVariant(string resourceType, CPos cell) { Dictionary> variants; - switch (((IMapCell)world.Map).Ramp[cell]) + switch (((IMapElevation)world.Map).Ramp[cell]) { case 1: variants = ramp1Variants; break; case 2: variants = ramp2Variants; break; diff --git a/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs b/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs index 500803c63229..99cbf8bf38c3 100644 --- a/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs +++ b/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs @@ -57,7 +57,7 @@ void IMapPreviewSignatureInfo.PopulateMapPreviewSignatureCells(IMap map, ActorIn var veinholeCells = new HashSet(); - foreach (var kv in map.ActorDefinitions) + foreach (var kv in ((Map)map).ActorDefinitions) { var type = kv.Value.Value; if (!VeinholeActors.Contains(type)) @@ -71,8 +71,8 @@ void IMapPreviewSignatureInfo.PopulateMapPreviewSignatureCells(IMap map, ActorIn } var terrainInfo = map.Rules.TerrainInfo; - var mapCell = (IMapCell)map; - var mapResource = (IMapResource)map; + var mapResources = ((IMapResource)map).Resources; + var mapRamp = ((IMapElevation)map).Ramp; var info = terrainInfo.TerrainTypes[terrainInfo.GetTerrainIndex(terrainType)]; for (var i = 0; i < map.MapSize.X; i++) @@ -82,7 +82,7 @@ void IMapPreviewSignatureInfo.PopulateMapPreviewSignatureCells(IMap map, ActorIn var uv = new MPos(i, j); // Cell contains veins - if (mapResource.Resources[uv].Type == resourceIndex) + if (mapResources[uv].Type == resourceIndex) { destinationBuffer.Add((uv, info.Color)); continue; @@ -90,15 +90,15 @@ void IMapPreviewSignatureInfo.PopulateMapPreviewSignatureCells(IMap map, ActorIn // Cell is a vein border if it is flat and adjacent to at least one cell // that is also flat and contains veins (borders are not drawn next to slope vein cells) - var isBorder = mapCell.Ramp[uv] == 0 && Common.Util.ExpandFootprint(uv.ToCPos(mapCell), false).Any(c => + var isBorder = mapRamp[uv] == 0 && Common.Util.ExpandFootprint(uv.ToCPos(map), false).Any(c => { - if (!mapResource.Resources.Contains(c)) + if (!mapResources.Contains(c)) return false; if (veinholeCells.Contains(c)) return true; - return mapResource.Resources[c].Type == resourceIndex && mapCell.Ramp[c] == 0; + return mapResources[c].Type == resourceIndex && mapRamp[c] == 0; }); if (isBorder) @@ -176,9 +176,9 @@ public TSVeinsRenderer(Actor self, TSVeinsRendererInfo info) resourceLayer.Info.TryGetTerrainType(info.ResourceType, out var terrainType); veinRadarColor = terrainInfo.TerrainTypes[terrainInfo.GetTerrainIndex(terrainType)].Color; - var mapCell = (IMapCell)world.Map; - renderIndices = new CellLayer(mapCell); - borders = new CellLayer(mapCell); + var map = world.Map; + renderIndices = new CellLayer(map); + borders = new CellLayer(map); } void AddDirtyCell(CPos cell, string resourceType) @@ -205,7 +205,7 @@ void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) // Initialize the renderIndices with the initial map state so it is visible // through the fog with the Explored Map option enabled - foreach (var cell in ((IMapCell)w.Map).AllCells) + foreach (var cell in w.Map.AllCells) { var resource = resourceLayer.GetResource(cell); var cellIndices = CalculateCellIndices(resource, cell); @@ -222,7 +222,7 @@ int[] CalculateCellIndices(ResourceLayerContents contents, CPos cell) if (contents.Type != info.ResourceType || contents.Density == 0) return null; - var ramp = ((IMapCell)world.Map).Ramp[cell]; + var ramp = ((IMapElevation)world.Map).Ramp[cell]; switch (ramp) { case 1: return Ramp1Indices; @@ -266,13 +266,13 @@ bool HasBorder(CPos cell) return false; // Draw the vein border if this is a flat cell with veins, or a veinhole - return (((IMapCell)world.Map).Ramp[cell] == 0 && renderIndices[cell] != null) || veinholeCells.Contains(cell); + return (((IMapElevation)world.Map).Ramp[cell] == 0 && renderIndices[cell] != null) || veinholeCells.Contains(cell); } Adjacency CalculateBorders(CPos cell) { // Borders are only valid on flat cells - if (((IMapCell)world.Map).Ramp[cell] != 0) + if (((IMapElevation)world.Map).Ramp[cell] != 0) return Adjacency.None; var ret = Adjacency.None; @@ -303,7 +303,7 @@ void UpdateRenderedSprite(CPos cell, int[] indices) void UpdateBorderSprite(CPos cell) { // Borders are never drawn on ramps or in cells that contain resources - if (HasBorder(cell) || ((IMapCell)world.Map).Ramp[cell] != 0) + if (HasBorder(cell) || ((IMapElevation)world.Map).Ramp[cell] != 0) return; var adjacency = CalculateBorders(cell); diff --git a/OpenRA.Mods.Cnc/Traits/World/WithResourceAnimation.cs b/OpenRA.Mods.Cnc/Traits/World/WithResourceAnimation.cs index cccc62f8442c..b88e93531bd3 100644 --- a/OpenRA.Mods.Cnc/Traits/World/WithResourceAnimation.cs +++ b/OpenRA.Mods.Cnc/Traits/World/WithResourceAnimation.cs @@ -77,7 +77,7 @@ void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) void ITick.Tick(Actor self) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; if (--ticks > 0) return; @@ -85,10 +85,10 @@ void ITick.Tick(Actor self) var cells = new HashSet(); foreach (var uv in worldRenderer.Viewport.AllVisibleCells.CandidateMapCoords) { - if (!mapCell.Contains(uv)) + if (!map.Contains(uv)) return; - var cell = uv.ToCPos(mapCell); + var cell = uv.ToCPos(map); var type = resourceRenderer.GetRenderedResourceType(cell); if (type != null && info.Types.Contains(type)) cells.Add(cell); @@ -97,7 +97,7 @@ void ITick.Tick(Actor self) var ratio = Common.Util.RandomInRange(world.LocalRandom, info.Ratio); var positions = cells.Shuffle(world.LocalRandom) .Take(Math.Max(1, cells.Count * ratio / 100)) - .Select(x => mapCell.CenterOfCell(x)); + .Select(x => map.CenterOfCell(x)); foreach (var position in positions) world.AddFrameEndTask(w => w.Add(new SpriteEffect(position, w, info.Image, info.Sequences.Random(w.LocalRandom), info.Palette))); diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs index 714b8eae9100..e3a1784d247c 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs @@ -78,7 +78,7 @@ void UnpackTileData(MemoryStream ms) for (var j = 0; j < MapSize; j++) for (var i = 0; i < MapSize; i++) - ((IMapCell)Map).Tiles[new CPos(i, j)] = new TerrainTile(types[i, j], ms.ReadUInt8()); + ((IMapTiles)Map).Tiles[new CPos(i, j)] = new TerrainTile(types[i, j], ms.ReadUInt8()); } static readonly string[] OverlayActors = new string[] @@ -239,7 +239,7 @@ public override void ReadPacks(IniFile file, string filename) public override void ReadActors(IniFile file) { base.ReadActors(file); - LoadActors(file, "SHIPS", Players, Map); + LoadActors(file, "SHIPS", Players, (IMap)Map); } public override void SaveWaypoint(int waypointNumber, ActorReference waypointReference) diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs index ee64467066b3..6f38ab4e6980 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs @@ -333,7 +333,7 @@ static void UnpackLCW(byte[] src, byte[] dest, byte[] temp) } } - static void ReadTiles(IMapCell map, IniFile file, int2 fullSize) + static void ReadTiles(IMap map, IniFile file, int2 fullSize) { var terrainInfo = (ITemplatedTerrainInfo)Game.ModData.DefaultTerrainInfo[map.Tileset]; var mapSection = file.GetSection("IsoMapPack5"); @@ -360,20 +360,19 @@ static void ReadTiles(IMapCell map, IniFile file, int2 fullSize) var mapCell = new MPos(dx / 2, dy); var cell = mapCell.ToCPos(map); - if (map.Tiles.Contains(cell)) + if (((IMapTiles)map).Tiles.Contains(cell)) { if (!terrainInfo.Templates.ContainsKey(tilenum)) tilenum = subtile = 0; - map.Tiles[cell] = new TerrainTile(tilenum, subtile); - map.Height[cell] = z; + ((IMapTiles)map).Tiles[cell] = new TerrainTile(tilenum, subtile); + ((IMapElevation)map).Height[cell] = z; } } } static void ReadOverlay(IMap map, IniFile file, int2 fullSize) { - var mapCell = (IMapCell)map; var mapResource = (IMapResource)map; var overlaySection = file.GetSection("OverlayPack"); @@ -387,7 +386,7 @@ static void ReadOverlay(IMap map, IniFile file, int2 fullSize) var overlayDataPack = new byte[1 << 18]; UnpackLCW(overlayDataCompressed, overlayDataPack, temp); - var overlayIndex = new CellLayer((IMapCell)map); + var overlayIndex = new CellLayer((IMap)map); overlayIndex.Clear(0xFF); for (var y = 0; y < fullSize.Y; y++) @@ -408,7 +407,7 @@ static void ReadOverlay(IMap map, IniFile file, int2 fullSize) } } - foreach (var cell in mapCell.AllCells) + foreach (var cell in map.AllCells) { var overlayType = overlayPack[overlayIndex[cell]]; if (overlayType == 0xFF) @@ -459,7 +458,7 @@ static void ReadOverlay(IMap map, IniFile file, int2 fullSize) ar.Add(new HealthInit(health)); } - map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save())); + ((Map)map).ActorDefinitions.Add(new MiniYamlNode("Actor" + ((Map)map).ActorDefinitions.Count, ar.Save())); continue; } @@ -492,7 +491,7 @@ static void ReadOverlay(IMap map, IniFile file, int2 fullSize) } } - static void ReadWaypoints(IMapCell map, IniFile file, int2 fullSize) + static void ReadWaypoints(IMap map, IniFile file, int2 fullSize) { var waypointsSection = file.GetSection("Waypoints", true); foreach (var kv in waypointsSection) @@ -510,11 +509,11 @@ static void ReadWaypoints(IMapCell map, IniFile file, int2 fullSize) new OwnerInit("Neutral") }; - map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save())); + ((Map)map).ActorDefinitions.Add(new MiniYamlNode("Actor" + ((Map)map).ActorDefinitions.Count, ar.Save())); } } - static void ReadTerrainActors(IMapCell map, IniFile file, int2 fullSize) + static void ReadTerrainActors(IMap map, IniFile file, int2 fullSize) { var terrainSection = file.GetSection("Terrain", true); foreach (var kv in terrainSection) @@ -536,11 +535,11 @@ static void ReadTerrainActors(IMapCell map, IniFile file, int2 fullSize) if (!map.Rules.Actors.ContainsKey(name)) Console.WriteLine($"Ignoring unknown actor type: `{name}`"); else - map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save())); + ((Map)map).ActorDefinitions.Add(new MiniYamlNode("Actor" + ((Map)map).ActorDefinitions.Count, ar.Save())); } } - static void ReadActors(IMapCell map, IniFile file, string type, int2 fullSize) + static void ReadActors(IMap map, IniFile file, string type, int2 fullSize) { var structuresSection = file.GetSection(type, true); foreach (var kv in structuresSection) @@ -596,7 +595,7 @@ static void ReadActors(IMapCell map, IniFile file, string type, int2 fullSize) if (!map.Rules.Actors.ContainsKey(name)) Console.WriteLine($"Ignoring unknown actor type: `{name}`"); else - map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save())); + ((Map)map).ActorDefinitions.Add(new MiniYamlNode("Actor" + ((Map)map).ActorDefinitions.Count, ar.Save())); } } @@ -640,7 +639,7 @@ static void ReadLighting(IMap map, IniFile file) if (lightingNodes.Count > 0) { - map.RuleDefinitions.Nodes.Add(new MiniYamlNode("^BaseWorld", new MiniYaml("", new List() + ((Map)map).RuleDefinitions.Nodes.Add(new MiniYamlNode("^BaseWorld", new MiniYaml("", new List() { new MiniYamlNode("TerrainLighting", new MiniYaml("", lightingNodes)) }))); @@ -680,7 +679,7 @@ static void ReadLamps(IMap map, IniFile file) if (lightingNodes.Count > 0) { - map.RuleDefinitions.Nodes.Add(new MiniYamlNode(lamp, new MiniYaml("", new List() + ((Map)map).RuleDefinitions.Nodes.Add(new MiniYamlNode(lamp, new MiniYaml("", new List() { new MiniYamlNode("TerrainLightSource", new MiniYaml("", lightingNodes)) }))); diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs index 0cdacbc687ae..6b395c040253 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs @@ -64,7 +64,7 @@ void UnpackTileData(Stream ms) { var type = ms.ReadUInt8(); var index = ms.ReadUInt8(); - ((IMapCell)Map).Tiles[new CPos(i, j)] = new TerrainTile(type, index); + ((IMapTiles)Map).Tiles[new CPos(i, j)] = new TerrainTile(type, index); } } } diff --git a/OpenRA.Mods.Common/AIUtils.cs b/OpenRA.Mods.Common/AIUtils.cs index dcb2217ad040..e4e4af9ee338 100644 --- a/OpenRA.Mods.Common/AIUtils.cs +++ b/OpenRA.Mods.Common/AIUtils.cs @@ -25,13 +25,12 @@ public static class AIUtils public static bool IsAreaAvailable(World world, Player player, IMap map, int radius, HashSet terrainTypes) { var cells = world.ActorsHavingTrait().Where(a => a.Owner == player); - var mapCell = (IMapCell)map; // TODO: Properly check building foundation rather than 3x3 area. - return cells.Select(a => mapCell.FindTilesInCircle(a.Location, radius) - .Count(c => mapCell.Contains(c) && terrainTypes.Contains(mapCell.GetTerrainInfo(c).Type) && + return cells.Select(a => map.FindTilesInCircle(a.Location, radius) + .Count(c => map.Contains(c) && terrainTypes.Contains(map.GetTerrainInfo(c).Type) && Util.AdjacentCells(world, Target.FromCell(world, c)) - .All(ac => mapCell.Contains(ac) && terrainTypes.Contains(mapCell.GetTerrainInfo(ac).Type)))) + .All(ac => map.Contains(ac) && terrainTypes.Contains(map.GetTerrainInfo(ac).Type)))) .Any(availableCells => availableCells > 0); } diff --git a/OpenRA.Mods.Common/Activities/Air/FallToEarth.cs b/OpenRA.Mods.Common/Activities/Air/FallToEarth.cs index eb00365bd44e..ceef49f654a0 100644 --- a/OpenRA.Mods.Common/Activities/Air/FallToEarth.cs +++ b/OpenRA.Mods.Common/Activities/Air/FallToEarth.cs @@ -35,7 +35,7 @@ public FallToEarth(Actor self, FallsToEarthInfo info) public override bool Tick(Actor self) { - if (((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition).Length <= 0) + if (self.World.Map.DistanceAboveTerrain(self.CenterPosition).Length <= 0) { if (info.ExplosionWeapon != null) { diff --git a/OpenRA.Mods.Common/Activities/Air/Fly.cs b/OpenRA.Mods.Common/Activities/Air/Fly.cs index a017780d4583..a6db206372f5 100644 --- a/OpenRA.Mods.Common/Activities/Air/Fly.cs +++ b/OpenRA.Mods.Common/Activities/Air/Fly.cs @@ -62,7 +62,7 @@ public Fly(Actor self, in Target t, WPos? initialTargetPosition = null, Color? t public static void FlyTick(Actor self, Aircraft aircraft, WAngle desiredFacing, WDist desiredAltitude, in WVec moveOverride, bool idleTurn = false) { - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(aircraft.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(aircraft.CenterPosition); var move = aircraft.Info.CanSlide ? aircraft.FlyStep(desiredFacing) : aircraft.FlyStep(aircraft.Facing); if (moveOverride != WVec.Zero) move = moveOverride; @@ -104,7 +104,7 @@ public static void FlyTick(Actor self, Aircraft aircraft, WAngle desiredFacing, // Should only be used for vertical-only movement, usually VTOL take-off or land. Terrain-induced altitude changes should always be handled by FlyTick. public static bool VerticalTakeOffOrLandTick(Actor self, Aircraft aircraft, WAngle desiredFacing, WDist desiredAltitude, bool idleTurn = false) { - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(aircraft.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(aircraft.CenterPosition); var move = WVec.Zero; var turnSpeed = idleTurn ? aircraft.IdleTurnSpeed ?? aircraft.TurnSpeed : aircraft.TurnSpeed; @@ -129,7 +129,7 @@ public override bool Tick(Actor self) if (aircraft.ForceLanding) Cancel(self); - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(aircraft.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(aircraft.CenterPosition); var isLanded = dat <= aircraft.LandAltitude; // HACK: Prevent paused (for example, EMP'd) aircraft from taking off. diff --git a/OpenRA.Mods.Common/Activities/Air/FlyOffMap.cs b/OpenRA.Mods.Common/Activities/Air/FlyOffMap.cs index b04847c4df9e..012d33e41cfc 100644 --- a/OpenRA.Mods.Common/Activities/Air/FlyOffMap.cs +++ b/OpenRA.Mods.Common/Activities/Air/FlyOffMap.cs @@ -46,7 +46,7 @@ protected override void OnFirstRun(Actor self) } // VTOLs must take off first if they're not at cruise altitude - if (aircraft.Info.VTOL && ((IMapCell)self.World.Map).DistanceAboveTerrain(aircraft.CenterPosition) != aircraft.Info.CruiseAltitude) + if (aircraft.Info.VTOL && self.World.Map.DistanceAboveTerrain(aircraft.CenterPosition) != aircraft.Info.CruiseAltitude) QueueChild(new TakeOff(self)); QueueChild(new FlyForward(self)); @@ -61,7 +61,7 @@ public override bool Tick(Actor self) if (IsCanceling) return true; - if (!((IMapCell)self.World.Map).Contains(self.Location) && --endingDelay < 0) + if (!self.World.Map.Contains(self.Location) && --endingDelay < 0) ChildActivity.Cancel(self); return TickChild(self); diff --git a/OpenRA.Mods.Common/Activities/Air/Land.cs b/OpenRA.Mods.Common/Activities/Air/Land.cs index a9a9d140c061..bc389924db8f 100644 --- a/OpenRA.Mods.Common/Activities/Air/Land.cs +++ b/OpenRA.Mods.Common/Activities/Air/Land.cs @@ -76,7 +76,7 @@ protected override void OnFirstRun(Actor self) public override bool Tick(Actor self) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (IsCanceling || target.Type == TargetType.Invalid) { @@ -90,7 +90,7 @@ public override bool Tick(Actor self) var continueLanding = shouldLand && self.CurrentActivity.IsCanceling && self.CurrentActivity.NextActivity == null; if (!continueLanding) { - var dat = mapCell.DistanceAboveTerrain(aircraft.CenterPosition); + var dat = map.DistanceAboveTerrain(aircraft.CenterPosition); if (dat > aircraft.LandAltitude && dat < aircraft.Info.CruiseAltitude) { QueueChild(new TakeOff(self)); @@ -109,7 +109,7 @@ public override bool Tick(Actor self) // Reevaluate target position in case the target has moved. targetPosition = target.CenterPosition + offset; - landingCell = mapCell.CellContaining(targetPosition); + landingCell = map.CellContaining(targetPosition); // We are already at the landing location. if ((targetPosition - pos).LengthSquared == 0) @@ -131,7 +131,7 @@ public override bool Tick(Actor self) { target = Target.FromCell(self.World, newLocation.Value); targetPosition = target.CenterPosition + offset; - landingCell = mapCell.CellContaining(targetPosition); + landingCell = map.CellContaining(targetPosition); } } @@ -239,7 +239,7 @@ public override bool Tick(Actor self) // Final descent. if (aircraft.Info.VTOL) { - var landAltitude = mapCell.DistanceAboveTerrain(targetPosition) + aircraft.LandAltitude; + var landAltitude = map.DistanceAboveTerrain(targetPosition) + aircraft.LandAltitude; if (Fly.VerticalTakeOffOrLandTick(self, aircraft, aircraft.Facing, landAltitude)) return false; @@ -257,7 +257,7 @@ public override bool Tick(Actor self) return true; } - var landingAlt = mapCell.DistanceAboveTerrain(targetPosition) + aircraft.LandAltitude; + var landingAlt = map.DistanceAboveTerrain(targetPosition) + aircraft.LandAltitude; Fly.FlyTick(self, aircraft, d.Yaw, landingAlt); return false; diff --git a/OpenRA.Mods.Common/Activities/Air/TakeOff.cs b/OpenRA.Mods.Common/Activities/Air/TakeOff.cs index 6673bc2cbe72..8da4ebb30fd0 100644 --- a/OpenRA.Mods.Common/Activities/Air/TakeOff.cs +++ b/OpenRA.Mods.Common/Activities/Air/TakeOff.cs @@ -53,7 +53,7 @@ public override bool Tick(Actor self) return true; } - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(aircraft.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(aircraft.CenterPosition); if (dat < aircraft.Info.CruiseAltitude) { // If we're a VTOL, rise before flying forward diff --git a/OpenRA.Mods.Common/Activities/DeliverUnit.cs b/OpenRA.Mods.Common/Activities/DeliverUnit.cs index 9ba096962a87..a6d481131da9 100644 --- a/OpenRA.Mods.Common/Activities/DeliverUnit.cs +++ b/OpenRA.Mods.Common/Activities/DeliverUnit.cs @@ -86,7 +86,7 @@ protected override void OnFirstRun(Actor self) var localOffset = carryall.CarryableOffset.Rotate(body.QuantizeOrientation(self.Orientation)); var targetPosition = self.CenterPosition + body.LocalToWorld(localOffset); - var targetLocation = ((IMapCell)self.World.Map).CellContaining(targetPosition); + var targetLocation = self.World.Map.CellContaining(targetPosition); carryall.Carryable.Trait().SetPosition(carryall.Carryable, targetLocation, SubCell.FullCell); carryall.Carryable.Trait().Facing = facing.Facing; diff --git a/OpenRA.Mods.Common/Activities/FindAndDeliverResources.cs b/OpenRA.Mods.Common/Activities/FindAndDeliverResources.cs index dd5f3c07f303..1af04fc48f5d 100644 --- a/OpenRA.Mods.Common/Activities/FindAndDeliverResources.cs +++ b/OpenRA.Mods.Common/Activities/FindAndDeliverResources.cs @@ -177,8 +177,8 @@ public override bool Tick(Actor self) var searchRadiusSquared = searchRadius * searchRadius; - var mapCell = (IMapCell)self.World.Map; - var procPos = procLoc.HasValue ? (WPos?)mapCell.CenterOfCell(procLoc.Value) : null; + var map = self.World.Map; + var procPos = procLoc.HasValue ? (WPos?)map.CenterOfCell(procLoc.Value) : null; var harvPos = self.CenterPosition; // Find any harvestable resources: @@ -198,7 +198,7 @@ public override bool Tick(Actor self) // This reduces the tendency for harvesters to move in straight lines if (procPos.HasValue && harvInfo.ResourceRefineryDirectionPenalty > 0 && harv.CanHarvestCell(loc)) { - var pos = mapCell.CenterOfCell(loc); + var pos = map.CenterOfCell(loc); // Calculate harv-cell-refinery angle (cosine rule) var b = pos - procPos.Value; diff --git a/OpenRA.Mods.Common/Activities/Move/Move.cs b/OpenRA.Mods.Common/Activities/Move/Move.cs index f0d51d41a678..27c10dc5f9a3 100644 --- a/OpenRA.Mods.Common/Activities/Move/Move.cs +++ b/OpenRA.Mods.Common/Activities/Move/Move.cs @@ -157,7 +157,7 @@ public override bool Tick(Actor self) if (nextCell == null) return false; - var firstFacing = ((IMapCell)self.World.Map).FacingBetween(mobile.FromCell, nextCell.Value.Cell, mobile.Facing); + var firstFacing = self.World.Map.FacingBetween(mobile.FromCell, nextCell.Value.Cell, mobile.Facing); if (mobile.Info.CanMoveBackward && self.World.WorldTick - startTicks < mobile.Info.BackwardDuration && Math.Abs(firstFacing.Angle - mobile.Facing.Angle) > 256) firstFacing = new WAngle(firstFacing.Angle + 512); @@ -172,18 +172,18 @@ public override bool Tick(Actor self) mobile.SetLocation(mobile.FromCell, mobile.FromSubCell, nextCell.Value.Cell, nextCell.Value.SubCell); - var mapCell = (IMapCell)self.World.Map; - var from = (mobile.FromCell.Layer == 0 ? mapCell.CenterOfCell(mobile.FromCell) : + var map = self.World.Map; + var from = (mobile.FromCell.Layer == 0 ? map.CenterOfCell(mobile.FromCell) : self.World.GetCustomMovementLayers()[mobile.FromCell.Layer].CenterOfCell(mobile.FromCell)) + - mapCell.Grid.OffsetOfSubCell(mobile.FromSubCell); + map.Grid.OffsetOfSubCell(mobile.FromSubCell); var to = Util.BetweenCells(self.World, mobile.FromCell, mobile.ToCell) + - (mapCell.Grid.OffsetOfSubCell(mobile.FromSubCell) + mapCell.Grid.OffsetOfSubCell(mobile.ToSubCell)) / 2; + (map.Grid.OffsetOfSubCell(mobile.FromSubCell) + map.Grid.OffsetOfSubCell(mobile.ToSubCell)) / 2; WRot? toTerrainOrientation = null; var margin = mobile.Info.TerrainOrientationAdjustmentMargin.Length; if (margin >= 0) - toTerrainOrientation = WRot.SLerp(mapCell.TerrainOrientation(mobile.FromCell), mapCell.TerrainOrientation(mobile.ToCell), 1, 2); + toTerrainOrientation = WRot.SLerp(map.TerrainOrientation(mobile.FromCell), map.TerrainOrientation(mobile.ToCell), 1, 2); var movingOnGroundLayer = mobile.FromCell.Layer == 0 && mobile.ToCell.Layer == 0; QueueChild(new MoveFirstHalf(this, from, to, mobile.Facing, mobile.Facing, null, toTerrainOrientation, margin, carryoverProgress, movingOnGroundLayer)); @@ -412,7 +412,7 @@ abstract class MovePart : Activity public override bool Tick(Actor self) { var mobile = Move.mobile; - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; // Only move by a full speed step if we didn't already move this tick. // If we did, we limit the move to any carried-over leftover progress. @@ -450,13 +450,13 @@ public override bool Tick(Actor self) // Smoothly interpolate over terrain orientation changes if (FromTerrainOrientation.HasValue && progress < terrainOrientationMargin) { - var currentCellOrientation = mapCell.TerrainOrientation(mobile.FromCell); + var currentCellOrientation = map.TerrainOrientation(mobile.FromCell); var orientation = WRot.SLerp(FromTerrainOrientation.Value, currentCellOrientation, progress, terrainOrientationMargin); mobile.SetTerrainRampOrientation(orientation); } else if (ToTerrainOrientation.HasValue && Distance - progress < terrainOrientationMargin) { - var currentCellOrientation = mapCell.TerrainOrientation(mobile.FromCell); + var currentCellOrientation = map.TerrainOrientation(mobile.FromCell); var orientation = WRot.SLerp(ToTerrainOrientation.Value, currentCellOrientation, Distance - progress, terrainOrientationMargin); mobile.SetTerrainRampOrientation(orientation); } @@ -479,42 +479,42 @@ class MoveFirstHalf : MovePart WRot? fromTerrainOrientation, WRot? toTerrainOrientation, int terrainOrientationMargin, int carryoverProgress, bool movingOnGroundLayer) : base(move, from, to, fromFacing, toFacing, fromTerrainOrientation, toTerrainOrientation, terrainOrientationMargin, carryoverProgress, movingOnGroundLayer) { } - static bool IsTurn(Mobile mobile, CPos nextCell, IMapCell mapCell) + static bool IsTurn(Mobile mobile, CPos nextCell, IMap map) { // Some actors with a limited number of sprite facings should never move along curved trajectories. if (mobile.Info.AlwaysTurnInPlace) return false; // Tight U-turns should be done in place instead of making silly looking loops. - var nextFacing = mapCell.FacingBetween(nextCell, mobile.ToCell, mobile.Facing); - var currentFacing = mapCell.FacingBetween(mobile.ToCell, mobile.FromCell, mobile.Facing); + var nextFacing = map.FacingBetween(nextCell, mobile.ToCell, mobile.Facing); + var currentFacing = map.FacingBetween(mobile.ToCell, mobile.FromCell, mobile.Facing); var delta = (nextFacing - currentFacing).Angle; return delta != 0 && (delta < 384 || delta > 640); } protected override MovePart OnComplete(Actor self, Mobile mobile, Move parent) { - var mapCell = (IMapCell)self.World.Map; - var fromSubcellOffset = mapCell.Grid.OffsetOfSubCell(mobile.FromSubCell); - var toSubcellOffset = mapCell.Grid.OffsetOfSubCell(mobile.ToSubCell); + var map = self.World.Map; + var fromSubcellOffset = map.Grid.OffsetOfSubCell(mobile.FromSubCell); + var toSubcellOffset = map.Grid.OffsetOfSubCell(mobile.ToSubCell); var nextCell = parent.PopPath(self); if (nextCell != null) { - if (!mobile.IsTraitPaused && !mobile.IsTraitDisabled && IsTurn(mobile, nextCell.Value.Cell, mapCell)) + if (!mobile.IsTraitPaused && !mobile.IsTraitDisabled && IsTurn(mobile, nextCell.Value.Cell, map)) { - var nextSubcellOffset = mapCell.Grid.OffsetOfSubCell(nextCell.Value.SubCell); + var nextSubcellOffset = map.Grid.OffsetOfSubCell(nextCell.Value.SubCell); WRot? nextToTerrainOrientation = null; var margin = mobile.Info.TerrainOrientationAdjustmentMargin.Length; if (margin >= 0) - nextToTerrainOrientation = WRot.SLerp(mapCell.TerrainOrientation(mobile.ToCell), mapCell.TerrainOrientation(nextCell.Value.Cell), 1, 2); + nextToTerrainOrientation = WRot.SLerp(map.TerrainOrientation(mobile.ToCell), map.TerrainOrientation(nextCell.Value.Cell), 1, 2); var ret = new MoveFirstHalf( Move, Util.BetweenCells(self.World, mobile.FromCell, mobile.ToCell) + (fromSubcellOffset + toSubcellOffset) / 2, Util.BetweenCells(self.World, mobile.ToCell, nextCell.Value.Cell) + (toSubcellOffset + nextSubcellOffset) / 2, mobile.Facing, - mapCell.FacingBetween(mobile.ToCell, nextCell.Value.Cell, mobile.Facing), + map.FacingBetween(mobile.ToCell, nextCell.Value.Cell, mobile.Facing), ToTerrainOrientation, nextToTerrainOrientation, margin, @@ -529,7 +529,7 @@ protected override MovePart OnComplete(Actor self, Mobile mobile, Move parent) parent.path.Add(nextCell.Value.Cell); } - var toPos = mobile.ToCell.Layer == 0 ? mapCell.CenterOfCell(mobile.ToCell) : + var toPos = mobile.ToCell.Layer == 0 ? map.CenterOfCell(mobile.ToCell) : self.World.GetCustomMovementLayers()[mobile.ToCell.Layer].CenterOfCell(mobile.ToCell); var ret2 = new MoveSecondHalf( diff --git a/OpenRA.Mods.Common/Activities/Move/MoveAdjacentTo.cs b/OpenRA.Mods.Common/Activities/Move/MoveAdjacentTo.cs index 6a8019b82a82..e7c74a9fd2b3 100644 --- a/OpenRA.Mods.Common/Activities/Move/MoveAdjacentTo.cs +++ b/OpenRA.Mods.Common/Activities/Move/MoveAdjacentTo.cs @@ -32,7 +32,7 @@ public class MoveAdjacentTo : Activity public MoveAdjacentTo(Actor self, in Target target, WPos? initialTargetPosition = null, Color? targetLineColor = null) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; this.target = target; this.targetLineColor = targetLineColor; @@ -45,12 +45,12 @@ public MoveAdjacentTo(Actor self, in Target target, WPos? initialTargetPosition || target.Type == TargetType.FrozenActor || target.Type == TargetType.Terrain) { lastVisibleTarget = Target.FromPos(target.CenterPosition); - lastVisibleTargetLocation = mapCell.CellContaining(target.CenterPosition); + lastVisibleTargetLocation = map.CellContaining(target.CenterPosition); } else if (initialTargetPosition.HasValue) { lastVisibleTarget = Target.FromPos(initialTargetPosition.Value); - lastVisibleTargetLocation = mapCell.CellContaining(initialTargetPosition.Value); + lastVisibleTargetLocation = map.CellContaining(initialTargetPosition.Value); } } @@ -82,7 +82,7 @@ public override bool Tick(Actor self) if (!targetIsHiddenActor && target.Type == TargetType.Actor) { lastVisibleTarget = Target.FromTargetPositions(target); - lastVisibleTargetLocation = ((IMapCell)self.World.Map).CellContaining(target.CenterPosition); + lastVisibleTargetLocation = self.World.Map.CellContaining(target.CenterPosition); } // Target is equivalent to checkTarget variable in other activities diff --git a/OpenRA.Mods.Common/Activities/Move/MoveWithinRange.cs b/OpenRA.Mods.Common/Activities/Move/MoveWithinRange.cs index 623ad45e470d..0021fb37bffe 100644 --- a/OpenRA.Mods.Common/Activities/Move/MoveWithinRange.cs +++ b/OpenRA.Mods.Common/Activities/Move/MoveWithinRange.cs @@ -50,9 +50,8 @@ protected override bool ShouldRepath(Actor self, CPos targetLocation) protected override IEnumerable CandidateMovementCells(Actor self) { - var mapCell = (IMapCell)map; - return mapCell.FindTilesInAnnulus(lastVisibleTargetLocation, minCells, maxCells) - .Where(c => Mobile.CanStayInCell(c) && AtCorrectRange(mapCell.CenterOfSubCell(c, Mobile.FromSubCell))); + return map.FindTilesInAnnulus(lastVisibleTargetLocation, minCells, maxCells) + .Where(c => Mobile.CanStayInCell(c) && AtCorrectRange(map.CenterOfSubCell(c, Mobile.FromSubCell))); } bool AtCorrectRange(WPos origin) diff --git a/OpenRA.Mods.Common/Activities/Parachute.cs b/OpenRA.Mods.Common/Activities/Parachute.cs index ca8068968815..d276c68b39f0 100644 --- a/OpenRA.Mods.Common/Activities/Parachute.cs +++ b/OpenRA.Mods.Common/Activities/Parachute.cs @@ -31,7 +31,7 @@ public Parachute(Actor self) protected override void OnFirstRun(Actor self) { - groundLevel = ((IMapCell)self.World.Map).CenterOfCell(self.Location).Z; + groundLevel = self.World.Map.CenterOfCell(self.Location).Z; foreach (var np in self.TraitsImplementing()) np.OnParachute(self); } diff --git a/OpenRA.Mods.Common/Activities/Resupply.cs b/OpenRA.Mods.Common/Activities/Resupply.cs index e41f360a0e90..189aa28a9ca8 100644 --- a/OpenRA.Mods.Common/Activities/Resupply.cs +++ b/OpenRA.Mods.Common/Activities/Resupply.cs @@ -131,7 +131,7 @@ public override bool Tick(Actor self) } else if (activeResupplyTypes != 0 && aircraft == null && !isCloseEnough) { - var targetCell = ((IMapCell)self.World.Map).CellContaining(host.Actor.CenterPosition); + var targetCell = self.World.Map.CellContaining(host.Actor.CenterPosition); QueueChild(move.MoveWithinRange(host, closeEnough, targetLineColor: moveInfo.GetTargetLineColor())); // HACK: Repairable needs the actor to move to host center. diff --git a/OpenRA.Mods.Common/Activities/UnloadCargo.cs b/OpenRA.Mods.Common/Activities/UnloadCargo.cs index dec35f6628e0..1c45160d05b7 100644 --- a/OpenRA.Mods.Common/Activities/UnloadCargo.cs +++ b/OpenRA.Mods.Common/Activities/UnloadCargo.cs @@ -83,7 +83,7 @@ protected override void OnFirstRun(Actor self) } else if (mobile != null) { - var cell = ((IMapCell)self.World.Map).Clamp(((IMapCell)this.self.World.Map).CellContaining(destination.CenterPosition)); + var cell = self.World.Map.Clamp(self.World.Map.CellContaining(destination.CenterPosition)); QueueChild(new Move(self, cell, unloadRange)); } diff --git a/OpenRA.Mods.Common/ActorExts.cs b/OpenRA.Mods.Common/ActorExts.cs index 35196c95f55f..b86565d6e2a9 100644 --- a/OpenRA.Mods.Common/ActorExts.cs +++ b/OpenRA.Mods.Common/ActorExts.cs @@ -26,12 +26,12 @@ public static bool IsAtGroundLevel(this Actor self) if (!self.IsInWorld) return false; - var map = (IMapCell)self.World.Map; + var map = self.World.Map; if (!map.Contains(self.Location)) return false; - return ((IMapCell)map).DistanceAboveTerrain(self.CenterPosition).Length == 0; + return map.DistanceAboveTerrain(self.CenterPosition).Length == 0; } public static bool AppearsFriendlyTo(this Actor self, Actor toActor) diff --git a/OpenRA.Mods.Common/Commands/DebugVisualizationCommands.cs b/OpenRA.Mods.Common/Commands/DebugVisualizationCommands.cs index ba797184d504..374eb49cb98e 100644 --- a/OpenRA.Mods.Common/Commands/DebugVisualizationCommands.cs +++ b/OpenRA.Mods.Common/Commands/DebugVisualizationCommands.cs @@ -66,7 +66,7 @@ public void WorldLoaded(World w, WorldRenderer wr) foreach (var command in commandHandlers) { - if (command.Key == "depth-buffer" && !((IMapCell)w.Map).Grid.EnableDepthBuffer) + if (command.Key == "depth-buffer" && !w.Map.Grid.EnableDepthBuffer) continue; console.RegisterCommand(command.Key, this); diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs index 02e10b921296..5e47512d60b3 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs @@ -59,7 +59,7 @@ public bool HandleMouseInput(MouseInput mi) { // Check the actor is inside the map var actor = editorCursor.Actor; - if (!actor.Footprint.All(c => ((IMapCell)world.Map).Tiles.Contains(c.Key))) + if (!actor.Footprint.All(c => ((IMapTiles)world.Map).Tiles.Contains(c.Key))) return true; var action = new AddActorAction(editorLayer, actor.Export()); diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs index 378d64b67bdc..4a41c660b242 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs @@ -94,7 +94,7 @@ public bool HandleMouseInput(MouseInput mi) { if (mi.Event != MouseInputEvent.Down) break; - var gridType = ((IMapCell)worldRenderer.World.Map).Grid.Type; + var gridType = worldRenderer.World.Map.Grid.Type; var source = CellRegion.BoundingRegion(gridType, new[] { start, end }); Copy(source, cell - end); break; @@ -109,11 +109,11 @@ public bool HandleMouseInput(MouseInput mi) void Copy(CellRegion source, CVec offset) { - var mapCell = (IMapCell)worldRenderer.World.Map; - var gridType = mapCell.Grid.Type; + var map = worldRenderer.World.Map; + var gridType = map.Grid.Type; var mapResource = (IMapResource)worldRenderer.World.Map; - var mapTiles = mapCell.Tiles; - var mapHeight = mapCell.Height; + var mapTiles = ((IMapTiles)map).Tiles; + var mapHeight = ((IMapElevation)map).Height; var mapResources = mapResource.Resources; var dest = new CellRegion(gridType, source.TopLeft + offset, source.BottomRight + offset); @@ -149,7 +149,7 @@ void Copy(CellRegion source, CVec offset) } } - var action = new CopyPasteEditorAction(copyFilters, worldRenderer.World.Map, tiles, previews, editorLayer, dest); + var action = new CopyPasteEditorAction(copyFilters, (Map)worldRenderer.World.Map, tiles, previews, editorLayer, dest); editorActionManager.Add(action); } @@ -193,7 +193,7 @@ class CopyPasteEditorAction : IEditorAction readonly Queue removedActors = new Queue(); readonly Queue addedActorPreviews = new Queue(); - public CopyPasteEditorAction(MapCopyFilters copyFilters, IMap map, + public CopyPasteEditorAction(MapCopyFilters copyFilters, Map map, Dictionary tiles, Dictionary previews, EditorActorLayer editorLayer, CellRegion dest) { @@ -203,11 +203,9 @@ class CopyPasteEditorAction : IEditorAction this.editorLayer = editorLayer; this.dest = dest; - var mapCell = (IMapCell)map; - var mapResource = (IMapResource)map; - mapTiles = mapCell.Tiles; - mapHeight = mapCell.Height; - mapResources = mapResource.Resources; + mapTiles = ((IMapTiles)map).Tiles; + mapHeight = ((IMapElevation)map).Height; + mapResources = ((IMapResource)map).Resources; Text = $"Copied {tiles.Count} tiles"; } diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs index 0114163a9bdd..d97e10baeda3 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs @@ -116,7 +116,7 @@ void FloodFillWithBrush(CPos cell) if (!map.Contains(cell)) return; - var mapTiles = ((IMapCell)map).Tiles; + var mapTiles = ((IMapTiles)map).Tiles; var replace = mapTiles[cell]; if (replace.Type == Template) @@ -127,8 +127,8 @@ void FloodFillWithBrush(CPos cell) bool PlacementOverlapsSameTemplate(TerrainTemplateInfo template, CPos cell) { - var mapCell = (IMapCell)world.Map; - var mapTiles = mapCell.Tiles; + var map = world.Map; + var mapTiles = ((IMapTiles)map).Tiles; var i = 0; for (var y = 0; y < template.Size.Y; y++) { @@ -183,9 +183,8 @@ public void Execute() public void Do() { - var mapCell = (IMapCell)map; - var mapTiles = mapCell.Tiles; - var mapHeight = mapCell.Height; + var mapTiles = ((IMapTiles)map).Tiles; + var mapHeight = ((IMapElevation)map).Height; var baseHeight = mapHeight.Contains(cell) ? mapHeight[cell] : (byte)0; var i = 0; @@ -203,7 +202,7 @@ public void Do() undoTiles.Enqueue(new UndoTile(c, mapTiles[c], mapHeight[c])); mapTiles[c] = new TerrainTile(template, index); - mapHeight[c] = (byte)(baseHeight + terrainTemplate[index].Height).Clamp(0, ((IMapCell)map).Grid.MaximumTerrainHeight); + mapHeight[c] = (byte)(baseHeight + terrainTemplate[index].Height).Clamp(0, map.Grid.MaximumTerrainHeight); } } } @@ -211,9 +210,8 @@ public void Do() public void Undo() { - var mapCell = (IMapCell)map; - var mapTiles = mapCell.Tiles; - var mapHeight = mapCell.Height; + var mapTiles = ((IMapTiles)map).Tiles; + var mapHeight = ((IMapElevation)map).Height; while (undoTiles.Count > 0) { @@ -254,15 +252,14 @@ public void Execute() public void Do() { - var mapCell = (IMapCell)map; var queue = new Queue(); - var touched = new CellLayer((IMapCell)map); - var mapTiles = mapCell.Tiles; + var touched = new CellLayer(map); + var mapTiles = ((IMapTiles)map).Tiles; var replace = mapTiles[cell]; Action maybeEnqueue = newCell => { - if (mapCell.Contains(cell) && !touched[newCell]) + if (map.Contains(cell) && !touched[newCell]) { queue.Enqueue(newCell); touched[newCell] = true; @@ -276,7 +273,7 @@ public void Do() for (var x = 0; x < terrainTemplate.Size.X; x++) { var c = cellToCheck + new CVec(x, y); - if (!mapCell.Contains(c) || mapTiles[c].Type != replace.Type) + if (!map.Contains(c) || mapTiles[c].Type != replace.Type) return false; } } @@ -321,9 +318,8 @@ public void Do() public void Undo() { - var mapCell = (IMapCell)map; - var mapTiles = mapCell.Tiles; - var mapHeight = mapCell.Height; + var mapTiles = ((IMapTiles)map).Tiles; + var mapHeight = ((IMapElevation)map).Height; while (undoTiles.Count > 0) { @@ -336,9 +332,8 @@ public void Undo() void PaintSingleCell(CPos cellToPaint) { - var mapCell = (IMapCell)map; - var mapTiles = mapCell.Tiles; - var mapHeight = mapCell.Height; + var mapTiles = ((IMapTiles)map).Tiles; + var mapHeight = ((IMapElevation)map).Height; var baseHeight = mapHeight.Contains(cellToPaint) ? mapHeight[cellToPaint] : (byte)0; var i = 0; @@ -356,7 +351,7 @@ void PaintSingleCell(CPos cellToPaint) undoTiles.Enqueue(new UndoTile(c, mapTiles[c], mapHeight[c])); mapTiles[c] = new TerrainTile(template, index); - mapHeight[c] = (byte)(baseHeight + terrainTemplate[index].Height).Clamp(0, mapCell.Grid.MaximumTerrainHeight); + mapHeight[c] = (byte)(baseHeight + terrainTemplate[index].Height).Clamp(0, map.Grid.MaximumTerrainHeight); } } } diff --git a/OpenRA.Mods.Common/Effects/RallyPointIndicator.cs b/OpenRA.Mods.Common/Effects/RallyPointIndicator.cs index 2f37ac0d017d..bfaa80303ce9 100644 --- a/OpenRA.Mods.Common/Effects/RallyPointIndicator.cs +++ b/OpenRA.Mods.Common/Effects/RallyPointIndicator.cs @@ -66,7 +66,7 @@ void UpdateTargetLineNodes(World world) cachedLocations = new List(rp.Path); targetLineNodes.Clear(); foreach (var c in cachedLocations) - targetLineNodes.Add(((IMapCell)world.Map).CenterOfCell(c)); + targetLineNodes.Add(world.Map.CenterOfCell(c)); if (targetLineNodes.Count == 0) return; diff --git a/OpenRA.Mods.Common/Effects/RevealShroudEffect.cs b/OpenRA.Mods.Common/Effects/RevealShroudEffect.cs index f0f8d26904c5..a71da9ec5b65 100644 --- a/OpenRA.Mods.Common/Effects/RevealShroudEffect.cs +++ b/OpenRA.Mods.Common/Effects/RevealShroudEffect.cs @@ -52,12 +52,12 @@ void AddCellsToPlayerShroud(Player p, PPos[] uv) PPos[] ProjectedCells(World world) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; var range = revealRadius; if (range == WDist.Zero) return NoCells; - return Shroud.ProjectedCellsInRange(mapCell, pos, WDist.Zero, range).ToArray(); + return Shroud.ProjectedCellsInRange(map, pos, WDist.Zero, range).ToArray(); } public void Tick(World world) diff --git a/OpenRA.Mods.Common/Graphics/ModelRenderable.cs b/OpenRA.Mods.Common/Graphics/ModelRenderable.cs index de1b7485990c..85e8d210c2ee 100644 --- a/OpenRA.Mods.Common/Graphics/ModelRenderable.cs +++ b/OpenRA.Mods.Common/Graphics/ModelRenderable.cs @@ -131,8 +131,8 @@ public FinalizedModelRenderable(WorldRenderer wr, ModelRenderable model) this.model = model; var draw = model.models.Where(v => v.IsVisible); - var mapCell = (IMapCell)wr.World.Map; - var groundOrientation = mapCell.TerrainOrientation(mapCell.CellContaining(model.pos)); + var map = wr.World.Map; + var groundOrientation = map.TerrainOrientation(map.CellContaining(model.pos)); renderProxy = Game.Renderer.WorldModelRenderer.RenderAsync( wr, draw, model.camera, model.scale, groundOrientation, model.lightSource, model.lightAmbientColor, model.lightDiffuseColor, @@ -141,11 +141,11 @@ public FinalizedModelRenderable(WorldRenderer wr, ModelRenderable model) public void Render(WorldRenderer wr) { - var mapCell = (IMapCell)wr.World.Map; - var groundPos = model.pos - new WVec(0, 0, mapCell.DistanceAboveTerrain(model.pos).Length); - var tileScale = mapCell.Grid.Type == MapGridType.RectangularIsometric ? 1448f : 1024f; + var map = wr.World.Map; + var groundPos = model.pos - new WVec(0, 0, map.DistanceAboveTerrain(model.pos).Length); + var tileScale = map.Grid.Type == MapGridType.RectangularIsometric ? 1448f : 1024f; - var groundZ = mapCell.Grid.TileSize.Height * (groundPos.Z - model.pos.Z) / tileScale; + var groundZ = map.Grid.TileSize.Height * (groundPos.Z - model.pos.Z) / tileScale; var pxOrigin = wr.Screen3DPosition(model.pos); // HACK: We don't have enough texture channels to pass the depth data to the shader @@ -154,9 +154,10 @@ public void Render(WorldRenderer wr) // HACK: The previous hack isn't sufficient for the ramp type that is half flat and half // sloped towards the camera. Offset it by another half cell to avoid clipping. - var cell = mapCell.CellContaining(model.pos); - if (mapCell.Ramp.Contains(cell) && mapCell.Ramp[cell] == 7) - pxOrigin += new float3(0, 0, 0.5f * mapCell.Grid.TileSize.Height); + var cell = map.CellContaining(model.pos); + var mapRamp = ((IMapElevation)map).Ramp; + if (mapRamp.Contains(cell) && mapRamp[cell] == 7) + pxOrigin += new float3(0, 0, 0.5f * map.Grid.TileSize.Height); var shadowOrigin = pxOrigin - groundZ * (new float2(renderProxy.ShadowDirection, 1)); @@ -182,8 +183,9 @@ public void Render(WorldRenderer wr) public void RenderDebugGeometry(WorldRenderer wr) { - var groundPos = model.pos - new WVec(0, 0, ((IMapCell)wr.World.Map).DistanceAboveTerrain(model.pos).Length); - var groundZ = ((IMapCell)wr.World.Map).Grid.TileSize.Height * (groundPos.Z - model.pos.Z) / 1024f; + var map = wr.World.Map; + var groundPos = model.pos - new WVec(0, 0, map.DistanceAboveTerrain(model.pos).Length); + var groundZ = map.Grid.TileSize.Height * (groundPos.Z - model.pos.Z) / 1024f; var pxOrigin = wr.Screen3DPosition(model.pos); var shadowOrigin = pxOrigin - groundZ * (new float2(renderProxy.ShadowDirection, 1)); diff --git a/OpenRA.Mods.Common/Lint/CheckActors.cs b/OpenRA.Mods.Common/Lint/CheckActors.cs index 55e61ca5dfbb..89fef880dd19 100644 --- a/OpenRA.Mods.Common/Lint/CheckActors.cs +++ b/OpenRA.Mods.Common/Lint/CheckActors.cs @@ -18,7 +18,7 @@ public class CheckActors : ILintMapPass { public void Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - var actorTypes = map.ActorDefinitions.Select(a => a.Value.Value); + var actorTypes = ((Map)map).ActorDefinitions.Select(a => a.Value.Value); foreach (var actor in actorTypes) if (!map.Rules.Actors.Keys.Contains(actor.ToLowerInvariant())) emitError($"Actor {actor} is not defined by any rule."); diff --git a/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs b/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs index 8e67f782f634..348b27d9b612 100644 --- a/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs +++ b/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs @@ -10,17 +10,17 @@ #endregion using System; -using OpenRA.Server; using OpenRA.Mods.Common.MapFormats; +using OpenRA.Server; namespace OpenRA.Mods.Common.Lint { public class CheckMapMetadata : ILintMapPass, ILintServerMapPass { - void ILintMapPass.Run(Action emitError, Action emitWarning, ModData modData, IMap map) + void ILintMapPass.Run(Action emitError, Action emitWarning, ModData modData, IMap imap) { - var defaultMap = map as DefaultMap; - Run(emitError, map.Author, map.Title, map.Categories, defaultMap.MapFormat); + var map = (Map)imap; + Run(emitError, map.Author, map.Title, map.Categories, (imap as DefaultMap).MapFormat); } void ILintServerMapPass.Run(Action emitError, Action emitWarning, ModData modData, MapPreview mapPreview, Ruleset mapRules) @@ -30,9 +30,8 @@ void ILintServerMapPass.Run(Action emitError, Action emitWarning void Run(Action emitError, string author, string title, string[] categories, int mapFormat) { - if (mapFormat != DefaultMap.SupportedMapFormat) - emitError("Map format {0} does not match the supported version {1}." - .F(mapFormat, DefaultMap.SupportedMapFormat)); + if (mapFormat < DefaultMap.SupportedMapFormat) + emitError($"Map format {mapFormat} does not match the supported version {DefaultMap.CurrentMapFormat}."); if (author == null) emitError("Map does not define a valid author."); diff --git a/OpenRA.Mods.Common/Lint/CheckMapTiles.cs b/OpenRA.Mods.Common/Lint/CheckMapTiles.cs index 4ca99da40954..6b4e089fdb4d 100644 --- a/OpenRA.Mods.Common/Lint/CheckMapTiles.cs +++ b/OpenRA.Mods.Common/Lint/CheckMapTiles.cs @@ -17,7 +17,7 @@ public class CheckMapTiles : ILintMapPass { public void Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - foreach (var kv in ((IMapCell)map).ReplacedInvalidTerrainTiles) + foreach (var kv in map.ReplacedInvalidTerrainTiles) emitError($"Cell {kv.Key} references invalid terrain tile {kv.Value}."); } } diff --git a/OpenRA.Mods.Common/Lint/CheckOwners.cs b/OpenRA.Mods.Common/Lint/CheckOwners.cs index 7bf72dbf329d..c59f352469d6 100644 --- a/OpenRA.Mods.Common/Lint/CheckOwners.cs +++ b/OpenRA.Mods.Common/Lint/CheckOwners.cs @@ -19,7 +19,7 @@ public class CheckOwners : ILintMapPass { public void Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - var playerNames = new MapPlayers(map.PlayerDefinitions).Players.Values + var playerNames = new MapPlayers(((Map)map).PlayerDefinitions).Players.Values .Select(p => p.Name) .ToHashSet(); @@ -28,7 +28,7 @@ public void Run(Action emitError, Action emitWarning, ModData mo .Where(a => a.Value.HasTraitInfo()) .ToDictionary(a => a.Key, a => a.Value.TraitInfo()); - foreach (var kv in map.ActorDefinitions) + foreach (var kv in ((Map)map).ActorDefinitions) { var actorReference = new ActorReference(kv.Value.Value, kv.Value.ToDictionary()); var ownerInit = actorReference.GetOrDefault(); diff --git a/OpenRA.Mods.Common/Lint/CheckPlayers.cs b/OpenRA.Mods.Common/Lint/CheckPlayers.cs index 40ce0886ce87..2b35232f6cf8 100644 --- a/OpenRA.Mods.Common/Lint/CheckPlayers.cs +++ b/OpenRA.Mods.Common/Lint/CheckPlayers.cs @@ -22,15 +22,15 @@ public class CheckPlayers : ILintMapPass, ILintServerMapPass { void ILintMapPass.Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - var players = new MapPlayers(map.PlayerDefinitions); + var players = new MapPlayers(((Map)map).PlayerDefinitions); var spawns = new List(); - foreach (var kv in map.ActorDefinitions.Where(d => d.Value.Value == "mpspawn")) + foreach (var kv in ((Map)map).ActorDefinitions.Where(d => d.Value.Value == "mpspawn")) { var s = new ActorReference(kv.Value.Value, kv.Value.ToDictionary()); spawns.Add(s.Get().Value); } - Run(emitError, emitWarning, players, map.Visibility, map.Rules.Actors[SystemActors.World], spawns.ToArray()); + Run(emitError, emitWarning, players, ((Map)map).Visibility, map.Rules.Actors[SystemActors.World], spawns.ToArray()); } void ILintServerMapPass.Run(Action emitError, Action emitWarning, ModData modData, MapPreview map, Ruleset mapRules) diff --git a/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs b/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs index 788da1ee0608..eebd4af6a19b 100644 --- a/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs +++ b/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs @@ -26,8 +26,7 @@ void ILintPass.Run(Action emitError, Action emitWarning, ModData void ILintMapPass.Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - // TO DO: Make this use IMap instead of Map - CheckMapYaml(emitError, modData, (Map)map, map.RuleDefinitions); + CheckMapYaml(emitError, modData, (Map)map, ((Map)map).RuleDefinitions); } void ILintServerMapPass.Run(Action emitError, Action emitWarning, ModData modData, MapPreview map, Ruleset mapRules) diff --git a/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs b/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs index 6d5b225afd96..872ef772b702 100644 --- a/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs +++ b/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs @@ -27,8 +27,7 @@ void ILintPass.Run(Action emitError, Action emitWarning, ModData void ILintMapPass.Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - // TO DO: Make this use IMap instead of Map - CheckMapYaml(emitError, emitWarning, modData, (Map)map, map.WeaponDefinitions); + CheckMapYaml(emitError, emitWarning, modData, (Map)map, ((Map)map).WeaponDefinitions); } void ILintServerMapPass.Run(Action emitError, Action emitWarning, ModData modData, MapPreview map, Ruleset mapRules) diff --git a/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs b/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs index a6ef061e4722..e04740f66439 100644 --- a/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs +++ b/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs @@ -31,8 +31,7 @@ void ILintPass.Run(Action emitError, Action emitWarning, ModData void ILintMapPass.Run(Action emitError, Action emitWarning, ModData modData, IMap map) { - // TO DO: Make this use IMap instead of Map - CheckMapYaml(emitError, modData, (Map)map, map.RuleDefinitions); + CheckMapYaml(emitError, modData, (Map)map, ((Map)map).RuleDefinitions); } void ILintServerMapPass.Run(Action emitError, Action emitWarning, ModData modData, MapPreview map, Ruleset mapRules) diff --git a/OpenRA.Mods.Common/MapFormats/DefaultMap.cs b/OpenRA.Mods.Common/MapFormats/DefaultMap.cs index fd0343035962..0f661724253c 100644 --- a/OpenRA.Mods.Common/MapFormats/DefaultMap.cs +++ b/OpenRA.Mods.Common/MapFormats/DefaultMap.cs @@ -29,12 +29,12 @@ public class DefaultMapLoader : IMapLoader public readonly string Type; public readonly IReadOnlyDictionary Metadata; - public IMap Load(ModData modData, IReadOnlyPackage package) + public Map Load(ModData modData, IReadOnlyPackage package) { return new DefaultMap(modData, package); } - public IMap Create(ModData modData, ITerrainInfo terrainInfo, int width, int height) + public Map Create(ModData modData, ITerrainInfo terrainInfo, int width, int height) { return new DefaultMap(modData, terrainInfo, width, height); } @@ -166,9 +166,10 @@ public void Serialize(IMap map, List nodes) } } - public class DefaultMap : Map, IMapCell, IMapResource + public class DefaultMap : Map, IMap, IMapResource, IMapElevation, IMapTiles { - public const int SupportedMapFormat = 12; + public const int SupportedMapFormat = 11; + public const int CurrentMapFormat = 12; protected CellLayer cachedTerrainIndexes; protected bool initializedCellProjection; @@ -191,6 +192,9 @@ public class DefaultMap : Map, IMapCell, IMapResource public CellLayer Tiles { get; protected set; } public string Tileset; + string IMap.Tileset => Tileset; + public Ruleset Rules { get; protected set; } + Ruleset IMap.Rules => Rules; public CellLayer Resources { get; protected set; } public CellLayer Height { get; protected set; } public CellLayer Ramp { get; protected set; } @@ -199,9 +203,15 @@ public class DefaultMap : Map, IMapCell, IMapResource public PPos[] ProjectedCells { get; private set; } public CellRegion AllCells { get; private set; } public List AllEdgeCells { get; private set; } - Dictionary IMapCell.ReplacedInvalidTerrainTiles => ReplacedInvalidTerrainTiles; - string IMapCell.Tileset => Tileset; - MapGrid IMapCell.Grid => Grid; + + public event Action CellProjectionChanged; + Dictionary IMap.ReplacedInvalidTerrainTiles => ReplacedInvalidTerrainTiles; + public int2 MapSize { get; protected set; } + MapGrid IMap.Grid => Grid; + int2 IMap.MapSize => MapSize; + protected CVec[][] GridTilesByDistance => Grid.TilesByDistance; + public Rectangle Bounds; + Rectangle IMap.Bounds => Bounds; // Generated data @@ -232,9 +242,16 @@ public class DefaultMap : Map, IMapCell, IMapResource // Format versions public int MapFormat { get; private set; } + int IMap.MapFormat => MapFormat; + public readonly byte TileFormat = 2; public static string ComputeUID(IReadOnlyPackage package) + { + return ComputeUID(package, GetMapFormat(package)); + } + + public static string ComputeUID(IReadOnlyPackage package, int format) { // UID is calculated by taking an SHA1 of the yaml and binary data var requiredFiles = new[] { "map.yaml", "map.bin" }; @@ -247,12 +264,12 @@ public static string ComputeUID(IReadOnlyPackage package) try { foreach (var filename in contents) - if (filename.EndsWith(".yaml") || filename.EndsWith(".bin") || filename.EndsWith(".lua")) + if (filename.EndsWith(".yaml") || filename.EndsWith(".bin") || filename.EndsWith(".lua") || (format >= 12 && filename == "map.png")) streams.Add(package.GetStream(filename)); // Take the SHA1 if (streams.Count == 0) - return CryptoUtil.SHA1Hash(new byte[0]); + return CryptoUtil.SHA1Hash(Array.Empty()); var merged = streams[0]; for (var i = 1; i < streams.Count; i++) @@ -274,16 +291,15 @@ public static string ComputeUID(IReadOnlyPackage package) public DefaultMap(ModData modData, ITerrainInfo terrainInfo, int width, int height) : base(modData) { - var tileRef = terrainInfo.DefaultTerrainTile; + var size = new Size(width, height); Title = "Name your map here"; Author = "Your name here"; + MapSize = new int2(size); Tileset = terrainInfo.Id; - NewSize(new Size(width, height), terrainInfo); - - Tiles.Clear(tileRef); + NewSize(size, terrainInfo); PostInit(); } @@ -300,7 +316,7 @@ public DefaultMap(ModData modData, IReadOnlyPackage package) foreach (var field in YamlFields) field.Deserialize(this, yaml.Nodes); - if (MapFormat != SupportedMapFormat) + if (MapFormat < SupportedMapFormat) throw new InvalidDataException("Map format {0} is not supported.\n File: {1}".F(MapFormat, package.Name)); PlayerDefinitions = MiniYaml.NodesOrEmpty(yaml, "Players"); @@ -315,7 +331,6 @@ public DefaultMap(ModData modData, IReadOnlyPackage package) catch (Exception e) { Log.Write("debug", "Failed to load rules for {0} with error {1}", Title, e); - rules = Ruleset.LoadDefaultsForTileSet(modData, Tileset); } var size = new Size(MapSize.X, MapSize.Y); @@ -372,7 +387,7 @@ public DefaultMap(ModData modData, IReadOnlyPackage package) PostInit(); - Uid = ComputeUID(Package); + Uid = ComputeUID(Package, MapFormat); } protected void PostInit() @@ -568,7 +583,7 @@ public byte[] SavePreview() public override void Save(IReadWritePackage toPackage) { - MapFormat = SupportedMapFormat; + MapFormat = CurrentMapFormat; var root = new List(); foreach (var field in YamlFields) @@ -584,16 +599,28 @@ public override void Save(IReadWritePackage toPackage) toPackage.Update(file, Package.GetStream(file).ReadAllBytes()); if (!LockPreview) - toPackage.Update("map.png", SavePreview()); + { + var previewData = SavePreview(); + if (Package != toPackage || !Enumerable.SequenceEqual(previewData, Package.GetStream("map.png").ReadAllBytes())) + toPackage.Update("map.png", previewData); + } // Update the package with the new map data var s = root.WriteToString(); toPackage.Update("map.yaml", Encoding.UTF8.GetBytes(s)); toPackage.Update("map.bin", SaveBinaryData()); + var textData = Encoding.UTF8.GetBytes(root.WriteToString()); + if (Package != toPackage || !Enumerable.SequenceEqual(textData, Package.GetStream("map.yaml").ReadAllBytes())) + toPackage.Update("map.yaml", textData); + + var binaryData = SaveBinaryData(); + if (Package != toPackage || !Enumerable.SequenceEqual(binaryData, Package.GetStream("map.bin").ReadAllBytes())) + toPackage.Update("map.bin", binaryData); + Package = toPackage; // Update UID to match the newly saved data - Uid = ComputeUID(toPackage); + Uid = ComputeUID(toPackage, MapFormat); } public static void UpdatePreview(ModData modData, MapPreview mp, IReadOnlyPackage p, IReadOnlyPackage parent, MapClassification classification, string[] mapCompatibility, MapGridType gridType) @@ -604,7 +631,6 @@ public static void UpdatePreview(ModData modData, MapPreview mp, IReadOnlyPackag if (yamlStream == null) throw new FileNotFoundException("Required file map.yaml not present in this map"); - // yaml = new MiniYaml(null, MiniYaml.FromStream(yamlStream, "map.yaml")).ToDictionary(); yaml = new MiniYaml(null, MiniYaml.FromStream(yamlStream, "map.yaml", stringPool: modData.MapCache.StringPool)).ToDictionary(); } @@ -615,7 +641,7 @@ public static void UpdatePreview(ModData modData, MapPreview mp, IReadOnlyPackag if (yaml.TryGetValue("MapFormat", out var temp)) { var format = FieldLoader.GetValue("MapFormat", temp.Value); - if (format != SupportedMapFormat) + if (format < SupportedMapFormat) throw new InvalidDataException("Map format {0} is not supported.".F(format)); } @@ -637,7 +663,7 @@ public static void UpdatePreview(ModData modData, MapPreview mp, IReadOnlyPackag if (yaml.TryGetValue("Visibility", out temp)) newData.Visibility = FieldLoader.GetValue("Visibility", temp.Value); - string requiresMod = string.Empty; + var requiresMod = string.Empty; if (yaml.TryGetValue("RequiresMod", out temp)) requiresMod = temp.Value; @@ -686,6 +712,8 @@ public static void UpdatePreview(ModData modData, MapPreview mp, IReadOnlyPackag if (p.Contains("map.png")) using (var dataStream = p.GetStream("map.png")) newData.Preview = new Png(dataStream); + + newData.ModifiedDate = File.GetLastWriteTime(p.Name); } public bool Contains(CPos cell) @@ -906,6 +934,7 @@ void UpdateProjection(CPos cell) var inverse = inverseCellProjection[uv]; inverse.Clear(); inverse.Add(uv); + CellProjectionChanged?.Invoke(cell); return; } @@ -940,6 +969,8 @@ void UpdateProjection(CPos cell) projectedHeight[temp] = height; } } + + CellProjectionChanged?.Invoke(cell); } byte ProjectedCellHeightInner(PPos puv) @@ -1205,10 +1236,10 @@ public void NewSize(Size size, ITerrainInfo terrainInfo) Tiles.Clear(terrainInfo.DefaultTerrainTile); if (Grid.MaximumTerrainHeight > 0) - Height.CellEntryChanged += UpdateProjection; { - Tiles.CellEntryChanged += UpdateProjection; Tiles.CellEntryChanged += UpdateRamp; + Tiles.CellEntryChanged += UpdateProjection; + Height.CellEntryChanged += UpdateProjection; } var tl = new MPos(0, 0); diff --git a/OpenRA.Mods.Common/Orders/PlaceBuildingOrderGenerator.cs b/OpenRA.Mods.Common/Orders/PlaceBuildingOrderGenerator.cs index 2e60f58c602a..6c676cd23619 100644 --- a/OpenRA.Mods.Common/Orders/PlaceBuildingOrderGenerator.cs +++ b/OpenRA.Mods.Common/Orders/PlaceBuildingOrderGenerator.cs @@ -330,7 +330,7 @@ IEnumerable ClearBlockersOrders(World world, CPos topLeft) { var allTiles = variants[variant].BuildingInfo.Tiles(topLeft).ToArray(); var adjacentTiles = Util.ExpandFootprint(allTiles, true).Except(allTiles) - .Where(((IMapCell)world.Map).Contains).ToList(); + .Where(world.Map.Contains).ToList(); var blockers = allTiles.SelectMany(world.ActorMap.GetActorsAt) .Where(a => a.Owner == Queue.Actor.Owner && a.IsIdle) diff --git a/OpenRA.Mods.Common/Orders/UnitOrderGenerator.cs b/OpenRA.Mods.Common/Orders/UnitOrderGenerator.cs index 3bbbacad33ec..f946605cd80f 100644 --- a/OpenRA.Mods.Common/Orders/UnitOrderGenerator.cs +++ b/OpenRA.Mods.Common/Orders/UnitOrderGenerator.cs @@ -106,7 +106,7 @@ public virtual bool InputOverridesSelection(World world, int2 xy, MouseInput mi) return true; var target = Target.FromActor(actor); - var cell = ((IMapCell)world.Map).CellContaining(target.CenterPosition); + var cell = world.Map.CellContaining(target.CenterPosition); var actorsAt = world.ActorMap.GetActorsAt(cell).ToList(); var modifiers = TargetModifiers.None; diff --git a/OpenRA.Mods.Common/Pathfinder/CellInfoLayerPool.cs b/OpenRA.Mods.Common/Pathfinder/CellInfoLayerPool.cs index 5bd06035cd89..564f198f5305 100644 --- a/OpenRA.Mods.Common/Pathfinder/CellInfoLayerPool.cs +++ b/OpenRA.Mods.Common/Pathfinder/CellInfoLayerPool.cs @@ -41,7 +41,7 @@ CellLayer GetLayer() // we don't need to initialize the values in the layer, // we can just clear them to the defaults. if (layer == null) - layer = new CellLayer((IMapCell)map); + layer = new CellLayer(map); else layer.Clear(); diff --git a/OpenRA.Mods.Common/Pathfinder/DensePathGraph.cs b/OpenRA.Mods.Common/Pathfinder/DensePathGraph.cs index b0b01ac005df..63234c4db248 100644 --- a/OpenRA.Mods.Common/Pathfinder/DensePathGraph.cs +++ b/OpenRA.Mods.Common/Pathfinder/DensePathGraph.cs @@ -50,7 +50,7 @@ abstract class DensePathGraph : IPathGraph this.ignoreActor = ignoreActor; this.laneBias = laneBias; this.inReverse = inReverse; - checkTerrainHeight = ((IMapCell)world.Map).Grid.MaximumTerrainHeight > 0; + checkTerrainHeight = world.Map.Grid.MaximumTerrainHeight > 0; } public abstract CellInfo this[CPos node] { get; set; } @@ -114,7 +114,7 @@ public List GetConnections(CPos position) var dy = position.Y - previousNode.Y; var index = dy * 3 + dx + 4; - var heightLayer = ((IMapCell)world.Map).Height; + var heightLayer = ((IMapElevation)world.Map).Height; var directions = (checkTerrainHeight && layer == 0 && previousNode.Layer == 0 && heightLayer[position] != heightLayer[previousNode] ? DirectedNeighborsConservative diff --git a/OpenRA.Mods.Common/Pathfinder/HierarchicalPathFinder.cs b/OpenRA.Mods.Common/Pathfinder/HierarchicalPathFinder.cs index 5cb5c67e92f7..fe12ecbc02e8 100644 --- a/OpenRA.Mods.Common/Pathfinder/HierarchicalPathFinder.cs +++ b/OpenRA.Mods.Common/Pathfinder/HierarchicalPathFinder.cs @@ -307,11 +307,11 @@ public HierarchicalPathFinder(World world, Locomotor locomotor, IActorMap actorM /// void BuildGrids() { - Grid GetCPosBounds(IMapCell map) + Grid GetCPosBounds(IMap map) { if (map.Grid.Type == MapGridType.RectangularIsometric) { - var bottomRight = ((IMapCell)map).AllCells.BottomRight; + var bottomRight = map.AllCells.BottomRight; var bottomRightU = bottomRight.ToMPos(map).U; return new Grid( new CPos(0, -bottomRightU), @@ -322,7 +322,7 @@ Grid GetCPosBounds(IMapCell map) return new Grid(CPos.Zero, (CPos)map.MapSize, false); } - mapBounds = GetCPosBounds((IMapCell)world.Map); + mapBounds = GetCPosBounds(world.Map); gridXs = Exts.IntegerDivisionRoundingAwayFromZero(mapBounds.Width, GridSize); gridYs = Exts.IntegerDivisionRoundingAwayFromZero(mapBounds.Height, GridSize); @@ -938,8 +938,8 @@ public bool PathExists(CPos source, CPos target) if (costEstimator == null) return false; - var mapCell = (IMapCell)world.Map; - if (!mapCell.Contains(source) || !mapCell.Contains(target)) + var map = world.Map; + if (!map.Contains(source) || !map.Contains(target)) return false; RebuildDomains(); @@ -1088,7 +1088,7 @@ List AbstractEdge(CPos abstractCell) /// /// Maps a local cell to a abstract node in the graph. Returns null when the local cell is unreachable. - /// The cell must have been checked to be on the map with . + /// The cell must have been checked to be on the map with . /// CPos? AbstractCellForLocalCell(CPos localCell) { diff --git a/OpenRA.Mods.Common/Projectiles/Bullet.cs b/OpenRA.Mods.Common/Projectiles/Bullet.cs index 62b6276aa88d..91025c0af9d8 100644 --- a/OpenRA.Mods.Common/Projectiles/Bullet.cs +++ b/OpenRA.Mods.Common/Projectiles/Bullet.cs @@ -262,22 +262,22 @@ bool ShouldExplode(World world) var flightLengthReached = ticks++ >= length; var shouldBounce = remainingBounces > 0; - var mapCell = (IMapCell)world.Map; + var map = world.Map; if (flightLengthReached && shouldBounce) { - var cell = mapCell.CellContaining(pos); - if (!mapCell.Contains(cell)) + var cell = map.CellContaining(pos); + if (!map.Contains(cell)) return true; - if (info.InvalidBounceTerrain.Contains(mapCell.GetTerrainInfo(cell).Type)) + if (info.InvalidBounceTerrain.Contains(map.GetTerrainInfo(cell).Type)) return true; if (AnyValidTargetsInRadius(world, pos, info.Width, args.SourceActor, true)) return true; target += (pos - source) * info.BounceRangeModifier / 100; - var dat = mapCell.DistanceAboveTerrain(target); + var dat = map.DistanceAboveTerrain(target); target += new WVec(0, 0, -dat.Length); length = Math.Max((target - pos).Length / speed.Length, 1); @@ -292,7 +292,7 @@ bool ShouldExplode(World world) return true; // Driving into cell with higher height level - if (mapCell.DistanceAboveTerrain(pos).Length < 0) + if (map.DistanceAboveTerrain(pos).Length < 0) return true; // After first bounce, check for targets each tick @@ -321,7 +321,7 @@ public IEnumerable Render(WorldRenderer wr) if (info.Shadow) { - var dat = ((IMapCell)world.Map).DistanceAboveTerrain(pos); + var dat = world.Map.DistanceAboveTerrain(pos); var shadowPos = pos - new WVec(0, 0, dat.Length); foreach (var r in anim.Render(shadowPos, palette)) yield return ((IModifyableRenderable)r) diff --git a/OpenRA.Mods.Common/Projectiles/GravityBomb.cs b/OpenRA.Mods.Common/Projectiles/GravityBomb.cs index 1c64fac071d7..af7aac7e6cc1 100644 --- a/OpenRA.Mods.Common/Projectiles/GravityBomb.cs +++ b/OpenRA.Mods.Common/Projectiles/GravityBomb.cs @@ -129,7 +129,7 @@ public IEnumerable Render(WorldRenderer wr) if (info.Shadow) { - var dat = ((IMapCell)world.Map).DistanceAboveTerrain(pos); + var dat = world.Map.DistanceAboveTerrain(pos); var shadowPos = pos - new WVec(0, 0, dat.Length); foreach (var r in anim.Render(shadowPos, palette)) yield return ((IModifyableRenderable)r) diff --git a/OpenRA.Mods.Common/Projectiles/Missile.cs b/OpenRA.Mods.Common/Projectiles/Missile.cs index b0f7de8f9132..9f3b65f6cccf 100644 --- a/OpenRA.Mods.Common/Projectiles/Missile.cs +++ b/OpenRA.Mods.Common/Projectiles/Missile.cs @@ -508,13 +508,13 @@ void InclineLookahead(World world, int distCheck, out int predClfHgt, out int pr // TODO: Make sure cell on map!!! for (var tick = 0; tick <= tickLimit; tick++) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; posProbe += step; - if (!mapCell.Contains(mapCell.CellContaining(posProbe))) + if (!map.Contains(map.CellContaining(posProbe))) break; - var ht = mapCell.Height[mapCell.CellContaining(posProbe)] * 512; + var ht = ((IMapElevation)map).Height[map.CellContaining(posProbe)] * 512; curDist += stepSize; if (ht > predClfHgt) @@ -898,14 +898,14 @@ public void Tick(World world) contrail.Update(pos); distanceCovered += new WDist(speed); - var mapCell = (IMapCell)world.Map; - var cell = mapCell.CellContaining(pos); - var height = mapCell.DistanceAboveTerrain(pos); + var map = world.Map; + var cell = map.CellContaining(pos); + var height = map.DistanceAboveTerrain(pos); shouldExplode |= height.Length < 0 // Hit the ground || relTarDist < info.CloseEnough.Length // Within range || (info.ExplodeWhenEmpty && rangeLimit >= WDist.Zero && distanceCovered > rangeLimit) // Ran out of fuel - || !mapCell.Contains(cell) // This also avoids an IndexOutOfRangeException in GetTerrainInfo below. - || (!string.IsNullOrEmpty(info.BoundToTerrainType) && mapCell.GetTerrainInfo(cell).Type != info.BoundToTerrainType) // Hit incompatible terrain + || !map.Contains(cell) // This also avoids an IndexOutOfRangeException in GetTerrainInfo below. + || (!string.IsNullOrEmpty(info.BoundToTerrainType) && map.GetTerrainInfo(cell).Type != info.BoundToTerrainType) // Hit incompatible terrain || (height.Length < info.AirburstAltitude.Length && relTarHorDist < info.CloseEnough.Length); // Airburst if (shouldExplode) @@ -951,7 +951,7 @@ public IEnumerable Render(WorldRenderer wr) if (info.Shadow) { - var dat = ((IMapCell)world.Map).DistanceAboveTerrain(pos); + var dat = world.Map.DistanceAboveTerrain(pos); var shadowPos = pos - new WVec(0, 0, dat.Length); foreach (var r in anim.Render(shadowPos, palette)) yield return ((IModifyableRenderable)r) diff --git a/OpenRA.Mods.Common/Projectiles/NukeLaunch.cs b/OpenRA.Mods.Common/Projectiles/NukeLaunch.cs index 09a582b16d2c..ea5e0a981739 100644 --- a/OpenRA.Mods.Common/Projectiles/NukeLaunch.cs +++ b/OpenRA.Mods.Common/Projectiles/NukeLaunch.cs @@ -128,7 +128,7 @@ public void Tick(World world) trailTicks = trailInterval; } - var dat = ((IMapCell)world.Map).DistanceAboveTerrain(pos); + var dat = world.Map.DistanceAboveTerrain(pos); if (ticks == impactDelay || (isDescending && dat <= detonationAltitude)) Explode(world, ticks == impactDelay || removeOnDetonation); diff --git a/OpenRA.Mods.Common/Scripting/Global/MapGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/MapGlobal.cs index 8a4435002ed4..0633db205fe7 100644 --- a/OpenRA.Mods.Common/Scripting/Global/MapGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/MapGlobal.cs @@ -52,48 +52,48 @@ public Actor[] ActorsInBox(WPos topLeft, WPos bottomRight, LuaFunction filter = // HACK: This api method abuses the coordinate system, and should be removed // in favour of proper actor queries. See #8549. [Desc("Returns the location of the top-left corner of the map (assuming zero terrain height).")] - public WPos TopLeft => ((IMapCell)Context.World.Map).ProjectedTopLeft; + public WPos TopLeft => Context.World.Map.ProjectedTopLeft; // HACK: This api method abuses the coordinate system, and should be removed // in favour of proper actor queries. See #8549. [Desc("Returns the location of the bottom-right corner of the map (assuming zero terrain height).")] - public WPos BottomRight => ((IMapCell)Context.World.Map).ProjectedBottomRight; + public WPos BottomRight => Context.World.Map.ProjectedBottomRight; [Desc("Returns a random cell inside the visible region of the map.")] public CPos RandomCell() { - return ((IMapCell)Context.World.Map).ChooseRandomCell(Context.World.SharedRandom); + return Context.World.Map.ChooseRandomCell(Context.World.SharedRandom); } [Desc("Returns a random cell on the visible border of the map.")] public CPos RandomEdgeCell() { - return ((IMapCell)Context.World.Map).ChooseRandomEdgeCell(Context.World.SharedRandom); + return Context.World.Map.ChooseRandomEdgeCell(Context.World.SharedRandom); } [Desc("Returns the closest cell on the visible border of the map from the given cell.")] public CPos ClosestEdgeCell(CPos givenCell) { - return ((IMapCell)Context.World.Map).ChooseClosestEdgeCell(givenCell); + return Context.World.Map.ChooseClosestEdgeCell(givenCell); } [Desc("Returns the first cell on the visible border of the map from the given cell,", "matching the filter function called as function(CPos cell).")] public CPos ClosestMatchingEdgeCell(CPos givenCell, LuaFunction filter) { - return FilteredObjects(((IMapCell)Context.World.Map).AllEdgeCells.OrderBy(c => (givenCell - c).Length), filter).FirstOrDefault(); + return FilteredObjects(Context.World.Map.AllEdgeCells.OrderBy(c => (givenCell - c).Length), filter).FirstOrDefault(); } [Desc("Returns the center of a cell in world coordinates.")] public WPos CenterOfCell(CPos cell) { - return ((IMapCell)Context.World.Map).CenterOfCell(cell); + return Context.World.Map.CenterOfCell(cell); } [Desc("Returns the type of the terrain at the target cell.")] public string TerrainType(CPos cell) { - return ((IMapCell)Context.World.Map).GetTerrainInfo(cell).Type; + return Context.World.Map.GetTerrainInfo(cell).Type; } [Desc("Returns true if there is only one human player.")] diff --git a/OpenRA.Mods.Common/Scripting/Global/MediaGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/MediaGlobal.cs index aa53687839bd..c324068075c8 100644 --- a/OpenRA.Mods.Common/Scripting/Global/MediaGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/MediaGlobal.cs @@ -166,7 +166,7 @@ public bool PlayMovieInRadar(string movie, LuaFunction playComplete = null) Stream s; try { - s = world.Map.Open(movie); + s = ((Map)world.Map).Open(movie); } catch (FileNotFoundException e) { @@ -230,9 +230,9 @@ public void Debug(string text) [Desc("Display a text message at the specified location.")] public void FloatingText(string text, WPos position, int duration = 30, Color? color = null) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - if (string.IsNullOrEmpty(text) || !mapCell.Contains(mapCell.CellContaining(position))) + if (string.IsNullOrEmpty(text) || !map.Contains(map.CellContaining(position))) return; var c = color.HasValue ? color.Value : Color.White; diff --git a/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs index 7d9eaaa00b45..c5a4451128d1 100644 --- a/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs @@ -46,12 +46,12 @@ Actor CreateActor(Player owner, string actorType, bool addToWorld, CPos? entryLo var pi = ai.TraitInfoOrDefault(); if (pi != null) - initDict.Add(new CenterPositionInit(((IMapCell)owner.World.Map).CenterOfCell(entryLocation.Value) + new WVec(0, 0, pi.CruiseAltitude.Length))); + initDict.Add(new CenterPositionInit(owner.World.Map.CenterOfCell(entryLocation.Value) + new WVec(0, 0, pi.CruiseAltitude.Length))); } if (entryLocation.HasValue && nextLocation.HasValue) { - var facing = ((IMapCell)Context.World.Map).FacingBetween(CPos.Zero, CPos.Zero + (nextLocation.Value - entryLocation.Value), WAngle.Zero); + var facing = Context.World.Map.FacingBetween(CPos.Zero, CPos.Zero + (nextLocation.Value - entryLocation.Value), WAngle.Zero); initDict.Add(new FacingInit(facing)); } diff --git a/OpenRA.Mods.Common/Scripting/Global/UserInterfaceGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/UserInterfaceGlobal.cs index f07d7d3e6bc8..02bf1a63f889 100644 --- a/OpenRA.Mods.Common/Scripting/Global/UserInterfaceGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/UserInterfaceGlobal.cs @@ -51,10 +51,10 @@ public string Translate(string text, LuaTable table = null) } } - return Context.World.Map.Translate(text, argumentDictionary); + return ((Map)Context.World.Map).Translate(text, argumentDictionary); } - return Context.World.Map.Translate(text); + return ((Map)Context.World.Map).Translate(text); } } } diff --git a/OpenRA.Mods.Common/Scripting/Properties/AircraftProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/AircraftProperties.cs index b8771a93fb03..b8c677221a96 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/AircraftProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/AircraftProperties.cs @@ -52,7 +52,7 @@ public void Land(Actor landOn) [Desc("Starts the resupplying activity when being on a host building.")] public void Resupply() { - var atLandAltitude = ((IMapCell)Self.World.Map).DistanceAboveTerrain(Self.CenterPosition) == aircraft.Info.LandAltitude; + var atLandAltitude = Self.World.Map.DistanceAboveTerrain(Self.CenterPosition) == aircraft.Info.LandAltitude; var host = aircraft.GetActorBelow(); if (atLandAltitude && host != null) Self.QueueActivity(new Resupply(Self, host, WDist.Zero)); diff --git a/OpenRA.Mods.Common/Scripting/Properties/NukeProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/NukeProperties.cs index 47d2e419e188..12cc8a624b02 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/NukeProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/NukeProperties.cs @@ -30,7 +30,7 @@ public NukeProperties(ScriptContext context, Actor self) [Desc("Activate the actor's NukePower.")] public void ActivateNukePower(CPos target) { - np.Activate(Self, ((IMapCell)Self.World.Map).CenterOfCell(target)); + np.Activate(Self, Self.World.Map.CenterOfCell(target)); } } } diff --git a/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs b/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs index 46b30dbf4d50..199980052831 100644 --- a/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs +++ b/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs @@ -169,21 +169,21 @@ public bool TryGetTileInfo(TerrainTile r, out TerrainTileInfo info) string[] ITemplatedTerrainInfo.EditorTemplateOrder => EditorTemplateOrder; IReadOnlyDictionary ITemplatedTerrainInfo.Templates => Templates; - void ITerrainInfoNotifyMapCreated.MapCreated(IMap map) + void ITerrainInfoNotifyMapCreated.MapCreated(IMap imap) { - var mapCell = (IMapCell)map; + var mapTiles = ((IMapTiles)imap).Tiles; // Randomize PickAny tile variants var r = new MersenneTwister(); - for (var j = map.Bounds.Top; j < map.Bounds.Bottom; j++) + for (var j = imap.Bounds.Top; j < imap.Bounds.Bottom; j++) { - for (var i = map.Bounds.Left; i < map.Bounds.Right; i++) + for (var i = imap.Bounds.Left; i < imap.Bounds.Right; i++) { - var type = mapCell.Tiles[new MPos(i, j)].Type; + var type = mapTiles[new MPos(i, j)].Type; if (!Templates.TryGetValue(type, out var template) || !template.PickAny) continue; - mapCell.Tiles[new MPos(i, j)] = new TerrainTile(type, (byte)r.Next(0, template.TilesCount)); + mapTiles[new MPos(i, j)] = new TerrainTile(type, (byte)r.Next(0, template.TilesCount)); } } } diff --git a/OpenRA.Mods.Common/Traits/AffectsShroud.cs b/OpenRA.Mods.Common/Traits/AffectsShroud.cs index 531d0450aac5..aba804c781c6 100644 --- a/OpenRA.Mods.Common/Traits/AffectsShroud.cs +++ b/OpenRA.Mods.Common/Traits/AffectsShroud.cs @@ -63,7 +63,7 @@ public AffectsShroud(AffectsShroudInfo info) PPos[] ProjectedCells(Actor self) { - var map = (IMapCell)self.World.Map; + var map = self.World.Map; var minRange = Info.MinRange; var maxRange = Range; if (maxRange <= minRange) @@ -81,7 +81,7 @@ PPos[] ProjectedCells(Actor self) var pos = self.CenterPosition; if (Info.Type == VisibilityType.GroundPosition) - pos -= new WVec(WDist.Zero, WDist.Zero, ((IMapCell)self.World.Map).DistanceAboveTerrain(pos)); + pos -= new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(pos)); return Shroud.ProjectedCellsInRange(map, pos, minRange, maxRange, Info.MaxHeightDelta) .ToArray(); @@ -94,7 +94,7 @@ void INotifyCenterPositionChanged.CenterPositionChanged(Actor self, byte oldLaye var centerPosition = self.CenterPosition; var projectedPos = centerPosition - new WVec(0, centerPosition.Z, centerPosition.Z); - var projectedLocation = ((IMapCell)self.World.Map).CellContaining(projectedPos); + var projectedLocation = self.World.Map.CellContaining(projectedPos); var pos = self.CenterPosition; var dirty = Info.MoveRecalculationThreshold.Length > 0 && (pos - cachedPos).LengthSquared > Info.MoveRecalculationThreshold.LengthSquared; @@ -138,7 +138,7 @@ void INotifyAddedToWorld.AddedToWorld(Actor self) { var centerPosition = self.CenterPosition; var projectedPos = centerPosition - new WVec(0, centerPosition.Z, centerPosition.Z); - cachedLocation = ((IMapCell)self.World.Map).CellContaining(projectedPos); + cachedLocation = self.World.Map.CellContaining(projectedPos); cachedPos = centerPosition; CachedTraitDisabled = IsTraitDisabled; var cells = ProjectedCells(self); @@ -162,7 +162,7 @@ void INotifyMoving.MovementTypeChanged(Actor self, MovementType type) { var centerPosition = self.CenterPosition; var projectedPos = centerPosition - new WVec(0, centerPosition.Z, centerPosition.Z); - var projectedLocation = ((IMapCell)self.World.Map).CellContaining(projectedPos); + var projectedLocation = self.World.Map.CellContaining(projectedPos); var pos = self.CenterPosition; cachedLocation = projectedLocation; diff --git a/OpenRA.Mods.Common/Traits/Air/Aircraft.cs b/OpenRA.Mods.Common/Traits/Air/Aircraft.cs index 3a08b09ae48b..3330d1dd2aef 100644 --- a/OpenRA.Mods.Common/Traits/Air/Aircraft.cs +++ b/OpenRA.Mods.Common/Traits/Air/Aircraft.cs @@ -194,12 +194,12 @@ IEnumerable IActorPreviewInitInfo.ActorPreviewInits(ActorInfo ai, Act // Used to determine if an aircraft can spawn landed public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; - var type = mapCell.GetTerrainInfo(cell).Type; + var type = map.GetTerrainInfo(cell).Type; if (!LandableTerrainTypes.Contains(type)) return false; @@ -263,7 +263,7 @@ public WAngle Roll [Sync] public WPos CenterPosition { get; private set; } - public CPos TopLeft => ((IMapCell)self.World.Map).CellContaining(CenterPosition); + public CPos TopLeft => self.World.Map.CellContaining(CenterPosition); public WAngle TurnSpeed => IsTraitDisabled || IsTraitPaused ? WAngle.Zero : Info.TurnSpeed; public WAngle? IdleTurnSpeed => IsTraitDisabled || IsTraitPaused ? null : Info.IdleTurnSpeed; @@ -292,10 +292,10 @@ public WAngle GetTurnSpeed(bool isIdleTurn) public static WPos GroundPosition(Actor self) { - return self.CenterPosition - new WVec(WDist.Zero, WDist.Zero, ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition)); + return self.CenterPosition - new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(self.CenterPosition)); } - public bool AtLandAltitude => ((IMapCell)self.World.Map).DistanceAboveTerrain(GetPosition()) == LandAltitude; + public bool AtLandAltitude => self.World.Map.DistanceAboveTerrain(GetPosition()) == LandAltitude; bool airborne; bool cruising; @@ -380,7 +380,7 @@ protected virtual void AddedToWorld(Actor self) { self.World.AddToMaps(self, this); - var altitude = ((IMapCell)self.World.Map).DistanceAboveTerrain(CenterPosition); + var altitude = self.World.Map.DistanceAboveTerrain(CenterPosition); if (altitude.Length >= Info.MinAirborneAltitude) OnAirborneAltitudeReached(); if (altitude == Info.CruiseAltitude) @@ -472,7 +472,7 @@ public void Repulse() public virtual WVec GetRepulsionForce() { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (!Info.Repulsable) return WVec.Zero; @@ -503,11 +503,11 @@ public virtual WVec GetRepulsionForce() } // Actors outside the map bounds receive an extra nudge towards the center of the map - if (!mapCell.Contains(self.Location)) + if (!map.Contains(self.Location)) { // The map bounds are in projected coordinates, which is technically wrong for this, // but we avoid the issues in practice by guessing the middle of the map instead of the edge - var center = WPos.Lerp(mapCell.ProjectedTopLeft, mapCell.ProjectedBottomRight, 1, 2); + var center = WPos.Lerp(map.ProjectedTopLeft, map.ProjectedBottomRight, 1, 2); repulsionForce += new WVec(0, 1024, 0).Rotate(WRot.FromYaw((self.CenterPosition - center).Yaw)); } @@ -550,7 +550,7 @@ public Actor GetActorBelow() { // Map.DistanceAboveTerrain(WPos pos) is called directly because Aircraft is an IPositionable trait // and all calls occur in Tick methods. - if (((IMapCell)self.World.Map).DistanceAboveTerrain(CenterPosition) != LandAltitude) + if (self.World.Map.DistanceAboveTerrain(CenterPosition) != LandAltitude) return null; // Not on the resupplier. return self.World.ActorMap.GetActorsAt(self.Location) @@ -626,14 +626,7 @@ bool AircraftCanResupplyAt(Actor a, bool allowedToForceEnter = false) public (CPos Cell, SubCell SubCell)[] OccupiedCells() { -<<<<<<< HEAD return landingCells; -======= - if (((IMapCell)self.World.Map).DistanceAboveTerrain(CenterPosition).Length >= Info.MinAirborneAltitude) - return landingCells.Select(c => (c, SubCell.FullCell)).ToArray(); - - return new[] { (TopLeft, SubCell.FullCell) }; ->>>>>>> 2bbe26171b (Repointing classes to new IMapCell interface.) } public WVec FlyStep(WAngle facing) @@ -649,20 +642,20 @@ public WVec FlyStep(int speed, WAngle facing) public CPos? FindLandingLocation(CPos targetCell, WDist maxSearchDistance) { - var mapCell = ((IMapCell)self.World.Map); + var map = self.World.Map; // The easy case if (CanLand(targetCell, blockedByMobile: false)) return targetCell; var cellRange = (maxSearchDistance.Length + 1023) / 1024; - var centerPosition = mapCell.CenterOfCell(targetCell); - foreach (var c in mapCell.FindTilesInCircle(targetCell, cellRange)) + var centerPosition = map.CenterOfCell(targetCell); + foreach (var c in map.FindTilesInCircle(targetCell, cellRange)) { if (!CanLand(c, blockedByMobile: false)) continue; - var delta = mapCell.CenterOfCell(c) - centerPosition; + var delta = map.CenterOfCell(c) - centerPosition; if (delta.LengthSquared < maxSearchDistance.LengthSquared) return c; } @@ -681,9 +674,9 @@ public bool CanLand(IEnumerable cells, Actor dockingActor = null, bool blo public bool CanLand(CPos cell, Actor dockingActor = null, bool blockedByMobile = true) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; foreach (var otherActor in self.World.ActorMap.GetActorsAt(cell)) @@ -695,7 +688,7 @@ public bool CanLand(CPos cell, Actor dockingActor = null, bool blockedByMobile = return true; var landableTerrain = overrideAircraftLanding != null ? overrideAircraftLanding.LandableTerrainTypes : Info.LandableTerrainTypes; - return landableTerrain.Contains(mapCell.GetTerrainInfo(cell).Type); + return landableTerrain.Contains(map.GetTerrainInfo(cell).Type); } bool IsBlockedBy(Actor self, Actor otherActor, Actor ignoreActor, bool blockedByMobile = true) @@ -755,7 +748,7 @@ void INotifyBecomingIdle.OnBecomingIdle(Actor self) protected virtual void OnBecomingIdle(Actor self) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (Info.IdleBehavior == IdleBehaviorType.LeaveMap) { @@ -764,7 +757,7 @@ protected virtual void OnBecomingIdle(Actor self) } else if (Info.IdleBehavior == IdleBehaviorType.LeaveMapAtClosestEdge) { - var edgeCell = mapCell.ChooseClosestEdgeCell(self.Location); + var edgeCell = map.ChooseClosestEdgeCell(self.Location); self.QueueActivity(new FlyOffMap(self, Target.FromCell(self.World, edgeCell))); self.QueueActivity(new RemoveSelf()); } @@ -772,7 +765,7 @@ protected virtual void OnBecomingIdle(Actor self) self.QueueActivity(new ReturnToBase(self, null, !Info.TakeOffOnResupply)); else { - var dat = mapCell.DistanceAboveTerrain(CenterPosition); + var dat = map.DistanceAboveTerrain(CenterPosition); if (dat == LandAltitude) { if (!CanLand(self.Location) && ReservedActor == null) @@ -808,23 +801,18 @@ public SubCell GetAvailableSubCell(CPos a, SubCell preferredSubCell = SubCell.An // Changes position, but not altitude public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any) { - SetPosition(self, ((IMapCell)self.World.Map).CenterOfCell(cell) + new WVec(0, 0, CenterPosition.Z)); + SetPosition(self, self.World.Map.CenterOfCell(cell) + new WVec(0, 0, CenterPosition.Z)); } public void SetPosition(Actor self, WPos pos) { CenterPosition = pos; + var map = self.World.Map; if (!self.IsInWorld) return; -<<<<<<< HEAD - var altitude = self.World.Map.DistanceAboveTerrain(CenterPosition); -======= - self.World.UpdateMaps(self, this); - - var altitude = ((IMapCell)self.World.Map).DistanceAboveTerrain(CenterPosition); ->>>>>>> 2bbe26171b (Repointing classes to new IMapCell interface.) + var altitude = map.DistanceAboveTerrain(CenterPosition); // LandingCells define OccupiedCells, so we need to keep current position with LandindCells in sync. // Though we don't want to update LandingCells when the unit is airborn, as when non-VTOL units reserve @@ -914,11 +902,7 @@ public void RemoveInfluence() public bool HasInfluence() { -<<<<<<< HEAD return landingCells.Length > 0; -======= - return landingCells.Any() || ((IMapCell)self.World.Map).DistanceAboveTerrain(CenterPosition).Length < Info.MinAirborneAltitude; ->>>>>>> 2bbe26171b (Repointing classes to new IMapCell interface.) } #endregion @@ -998,7 +982,7 @@ public bool CanEnterTargetNow(Actor self, in Target target) { // Lambdas can't use 'in' variables, so capture a copy for later var targetActor = target; - if (target.Positions.Any(p => self.World.ActorMap.GetActorsAt(((IMapCell)self.World.Map).CellContaining(p)).Any(a => a != self && a != targetActor.Actor))) + if (target.Positions.Any(p => self.World.ActorMap.GetActorsAt(self.World.Map.CellContaining(p)).Any(a => a != self && a != targetActor.Actor))) return false; MakeReservation(target.Actor); @@ -1063,7 +1047,7 @@ public string VoicePhraseForOrder(Actor self, Order order) case "Move": if (!Info.MoveIntoShroud && order.Target.Type != TargetType.Invalid) { - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (!self.Owner.Shroud.IsExplored(cell)) return null; } @@ -1082,7 +1066,7 @@ public string VoicePhraseForOrder(Actor self, Order order) public void ResolveOrder(Actor self, Order order) { - var mapCell = ((IMapCell)self.World.Map); + var map = self.World.Map; if (IsTraitDisabled) return; @@ -1090,7 +1074,7 @@ public void ResolveOrder(Actor self, Order order) var orderString = order.OrderString; if (orderString == "Move") { - var cell = mapCell.Clamp(mapCell.CellContaining(order.Target.CenterPosition)); + var cell = map.Clamp(map.CellContaining(order.Target.CenterPosition)); if (!Info.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; @@ -1105,7 +1089,7 @@ public void ResolveOrder(Actor self, Order order) } else if (orderString == "Land") { - var cell = mapCell.Clamp(mapCell.CellContaining(order.Target.CenterPosition)); + var cell = map.Clamp(map.CellContaining(order.Target.CenterPosition)); if (!Info.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; @@ -1180,7 +1164,7 @@ void Nudge(Actor self) return; // Disable nudging if the aircraft is outside the map - if (!((IMapCell)self.World.Map).Contains(self.Location)) + if (!self.World.Map.Contains(self.Location)) return; var offset = new WVec(0, -self.World.SharedRandom.Next(512, 2048), 0) @@ -1287,7 +1271,7 @@ public override bool Tick(Actor self) return true; } - if (((IMapCell)self.World.Map).DistanceAboveTerrain(aircraft.CenterPosition).Length <= aircraft.LandAltitude.Length) + if (self.World.Map.DistanceAboveTerrain(aircraft.CenterPosition).Length <= aircraft.LandAltitude.Length) QueueChild(new TakeOff(self)); aircraft.UnReserve(); @@ -1323,7 +1307,7 @@ public virtual bool CanTarget(Actor self, in Target target, ref TargetModifiers if (target.Type != TargetType.Terrain || (aircraft.requireForceMove && !modifiers.HasModifier(TargetModifiers.ForceMove))) return false; - var location = ((IMapCell)self.World.Map).CellContaining(target.CenterPosition); + var location = self.World.Map.CellContaining(target.CenterPosition); // Aircraft can be force-landed by issuing a force-move order on a clear terrain cell // Cells that contain a blocking building are treated as regular force move orders, overriding @@ -1340,7 +1324,7 @@ public virtual bool CanTarget(Actor self, in Target target, ref TargetModifiers IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); var explored = self.Owner.Shroud.IsExplored(location); - cursor = !aircraft.IsTraitPaused && (explored || aircraft.Info.MoveIntoShroud) && ((IMapCell)self.World.Map).Contains(location) ? + cursor = !aircraft.IsTraitPaused && (explored || aircraft.Info.MoveIntoShroud) && self.World.Map.Contains(location) ? aircraft.Info.Cursor : aircraft.Info.BlockedCursor; return true; diff --git a/OpenRA.Mods.Common/Traits/Air/AttackAircraft.cs b/OpenRA.Mods.Common/Traits/Air/AttackAircraft.cs index b22baec39757..fcc2af34f17e 100644 --- a/OpenRA.Mods.Common/Traits/Air/AttackAircraft.cs +++ b/OpenRA.Mods.Common/Traits/Air/AttackAircraft.cs @@ -52,11 +52,11 @@ public override Activity GetAttackActivity(Actor self, AttackSource source, in T protected override bool CanAttack(Actor self, in Target target) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; // Don't fire while landed or when outside the map. - if (mapCell.DistanceAboveTerrain(self.CenterPosition).Length < aircraftInfo.MinAirborneAltitude - || !mapCell.Contains(self.Location)) + if (map.DistanceAboveTerrain(self.CenterPosition).Length < aircraftInfo.MinAirborneAltitude + || !map.Contains(self.Location)) return false; if (!base.CanAttack(self, target)) diff --git a/OpenRA.Mods.Common/Traits/Air/AttackBomber.cs b/OpenRA.Mods.Common/Traits/Air/AttackBomber.cs index 8994da425ffa..54c0521cfc2c 100644 --- a/OpenRA.Mods.Common/Traits/Air/AttackBomber.cs +++ b/OpenRA.Mods.Common/Traits/Air/AttackBomber.cs @@ -52,7 +52,7 @@ void ITick.Tick(Actor self) if (self.IsInWorld) { - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(target.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(target.CenterPosition); target = Target.FromPos(target.CenterPosition - new WVec(WDist.Zero, WDist.Zero, dat)); var wasFacingTarget = facingTarget; diff --git a/OpenRA.Mods.Common/Traits/AppearsOnMapPreview.cs b/OpenRA.Mods.Common/Traits/AppearsOnMapPreview.cs index bdce19d9c745..dad77988d23f 100644 --- a/OpenRA.Mods.Common/Traits/AppearsOnMapPreview.cs +++ b/OpenRA.Mods.Common/Traits/AppearsOnMapPreview.cs @@ -40,7 +40,7 @@ void IMapPreviewSignatureInfo.PopulateMapPreviewSignatureCells(IMap map, ActorIn } else { - var owner = map.PlayerDefinitions.Single(p => s.Get().InternalName == p.Value.Nodes.Last(k => k.Key == "Name").Value.Value); + var owner = ((Map)map).PlayerDefinitions.Single(p => s.Get().InternalName == p.Value.Nodes.Last(k => k.Key == "Name").Value.Value); var colorValue = owner.Value.Nodes.Where(n => n.Key == "Color"); var ownerColor = colorValue.Any() ? colorValue.First().Value.Value : "FFFFFF"; Color.TryParse(ownerColor, out color); @@ -49,7 +49,7 @@ void IMapPreviewSignatureInfo.PopulateMapPreviewSignatureCells(IMap map, ActorIn var ios = ai.TraitInfo(); var cells = ios.OccupiedCells(ai, s.Get().Value); foreach (var cell in cells) - destinationBuffer.Add((cell.Key.ToMPos((IMapCell)map), color)); + destinationBuffer.Add((cell.Key.ToMPos(map), color)); } } diff --git a/OpenRA.Mods.Common/Traits/Attack/AttackBase.cs b/OpenRA.Mods.Common/Traits/Attack/AttackBase.cs index edc9e8302658..85178b5bf072 100644 --- a/OpenRA.Mods.Common/Traits/Attack/AttackBase.cs +++ b/OpenRA.Mods.Common/Traits/Attack/AttackBase.cs @@ -473,7 +473,7 @@ bool CanTargetActor(Actor self, in Target target, ref TargetModifiers modifiers, bool CanTargetLocation(Actor self, CPos location, TargetModifiers modifiers, ref string cursor) { - if (!((IMapCell)self.World.Map).Contains(location)) + if (!self.World.Map.Contains(location)) return false; IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); @@ -510,7 +510,7 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier case TargetType.FrozenActor: return CanTargetActor(self, target, ref modifiers, ref cursor); case TargetType.Terrain: - return CanTargetLocation(self, ((IMapCell)self.World.Map).CellContaining(target.CenterPosition), modifiers, ref cursor); + return CanTargetLocation(self, self.World.Map.CellContaining(target.CenterPosition), modifiers, ref cursor); default: return false; } diff --git a/OpenRA.Mods.Common/Traits/AttackMove.cs b/OpenRA.Mods.Common/Traits/AttackMove.cs index 050e0bd8ca4b..4e86c09e9dd3 100644 --- a/OpenRA.Mods.Common/Traits/AttackMove.cs +++ b/OpenRA.Mods.Common/Traits/AttackMove.cs @@ -68,7 +68,7 @@ string IOrderVoice.VoicePhraseForOrder(Actor self, Order order) { if (!Info.MoveIntoShroud && order.Target.Type != TargetType.Invalid) { - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (!self.Owner.Shroud.IsExplored(cell)) return null; } @@ -83,9 +83,9 @@ public void ResolveOrder(Actor self, Order order) { if (order.OrderString == "AttackMove" || order.OrderString == "AssaultMove") { - var mapCell = ((IMapCell)self.World.Map); + var map = self.World.Map; - var cell = mapCell.Clamp(mapCell.CellContaining(order.Target.CenterPosition)); + var cell = map.Clamp(map.CellContaining(order.Target.CenterPosition)); if (!Info.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; @@ -134,7 +134,7 @@ protected virtual IEnumerable OrderInner(World world, CPos cell, MouseInp var orderName = mi.Modifiers.HasModifier(Modifiers.Ctrl) ? "AssaultMove" : "AttackMove"; // Cells outside the playable area should be clamped to the edge for consistency with move orders - cell = ((IMapCell)world.Map).Clamp(cell); + cell = world.Map.Clamp(cell); yield return new Order(orderName, null, Target.FromCell(world, cell), queued, null, subjects.Select(s => s.Actor).ToArray()); } } @@ -158,7 +158,7 @@ public override string GetCursor(World world, CPos cell, int2 worldPixel, MouseI if (subject.Actor != null) { var info = subject.Trait.Info; - if (((IMapCell)world.Map).Contains(cell)) + if (world.Map.Contains(cell)) { var explored = subject.Actor.Owner.Shroud.IsExplored(cell); var cannotMove = subjects.FirstOrDefault(a => !a.Trait.Info.MoveIntoShroud).Trait; diff --git a/OpenRA.Mods.Common/Traits/AutoCarryable.cs b/OpenRA.Mods.Common/Traits/AutoCarryable.cs index 2b7ccca47cdc..c85c2cf29bce 100644 --- a/OpenRA.Mods.Common/Traits/AutoCarryable.cs +++ b/OpenRA.Mods.Common/Traits/AutoCarryable.cs @@ -50,7 +50,7 @@ void MovementCancelled() void RequestTransport(Actor self, CPos destination) { - var delta = ((IMapCell)self.World.Map).CenterOfCell(destination) - self.CenterPosition; + var delta = self.World.Map.CenterOfCell(destination) - self.CenterPosition; if (delta.HorizontalLengthSquared < info.MinDistance.LengthSquared) { Destination = null; @@ -89,7 +89,7 @@ public override bool Reserve(Actor self, Actor carrier) if (Reserved || !WantsTransport) return false; - var delta = ((IMapCell)self.World.Map).CenterOfCell(Destination.Value) - self.CenterPosition; + var delta = self.World.Map.CenterOfCell(Destination.Value) - self.CenterPosition; if (delta.HorizontalLengthSquared < info.MinDistance.LengthSquared) { // Cancel pickup @@ -107,7 +107,7 @@ public override LockResponse LockForPickup(Actor self, Actor carrier) return LockResponse.Failed; // Last chance to change our mind... - var delta = ((IMapCell)self.World.Map).CenterOfCell(Destination.Value) - self.CenterPosition; + var delta = self.World.Map.CenterOfCell(Destination.Value) - self.CenterPosition; if (delta.HorizontalLengthSquared < info.MinDistance.LengthSquared) { // Cancel pickup diff --git a/OpenRA.Mods.Common/Traits/BlocksProjectiles.cs b/OpenRA.Mods.Common/Traits/BlocksProjectiles.cs index 003560c8300d..55e6f6204286 100644 --- a/OpenRA.Mods.Common/Traits/BlocksProjectiles.cs +++ b/OpenRA.Mods.Common/Traits/BlocksProjectiles.cs @@ -36,11 +36,11 @@ public BlocksProjectiles(BlocksProjectilesInfo info) public static bool AnyBlockingActorAt(World world, WPos pos) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - var dat = mapCell.DistanceAboveTerrain(pos); + var dat = map.DistanceAboveTerrain(pos); - return world.ActorMap.GetActorsAt(mapCell.CellContaining(pos)) + return world.ActorMap.GetActorsAt(map.CellContaining(pos)) .Any(a => a.TraitsImplementing() .Where(t => t.BlockingHeight > dat) .Any(Exts.IsTraitEnabled)); @@ -61,7 +61,7 @@ public static bool AnyBlockingActorsBetween(World world, Player owner, WPos star continue; var hitPos = start.MinimumPointLineProjection(end, a.CenterPosition); - var dat = ((IMapCell)world.Map).DistanceAboveTerrain(hitPos); + var dat = world.Map.DistanceAboveTerrain(hitPos); if ((hitPos - start).Length < length && blockers.Any(t => t.BlockingHeight > dat)) { hit = hitPos; diff --git a/OpenRA.Mods.Common/Traits/BotModules/BaseBuilderBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/BaseBuilderBotModule.cs index c257cb995718..ed3fa7daae71 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/BaseBuilderBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/BaseBuilderBotModule.cs @@ -239,7 +239,7 @@ void SetRallyPointsForNewProductionBuildings(IBot bot) // Won't work for shipyards... CPos ChooseRallyLocationNear(Actor producer) { - var possibleRallyPoints = ((IMapCell)world.Map).FindTilesInCircle(producer.Location, Info.RallyPointScanRadius) + var possibleRallyPoints = world.Map.FindTilesInCircle(producer.Location, Info.RallyPointScanRadius) .Where(c => IsRallyPointValid(c, producer.Info.TraitInfoOrDefault())); if (!possibleRallyPoints.Any()) diff --git a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs index 9743fa64ad97..bf860bbf159d 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs @@ -385,7 +385,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue) { var actorInfo = world.Map.Rules.Actors[actorType]; var bi = actorInfo.TraitInfoOrDefault(); - var mapCell = (IMapCell)world.Map; + var map = world.Map; if (bi == null) return (null, 0); @@ -398,7 +398,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue) var variantActorInfo = actorInfo; var vbi = bi; - var cells = mapCell.FindTilesInAnnulus(center, minRange, maxRange); + var cells = map.FindTilesInAnnulus(center, minRange, maxRange); // Sort by distance to target if we have one if (center != target) @@ -411,7 +411,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue) { if (buildingVariantInfo.Facings != null) { - var vector = mapCell.CenterOfCell(target) - mapCell.CenterOfCell(center); + var vector = map.CenterOfCell(target) - map.CenterOfCell(center); // The rotation Y point to upside vertically, so -Y = Y(rotation) var desireFacing = new WAngle(WAngle.ArcSin((int)((long)Math.Abs(vector.X) * 1024 / vector.Length)).Angle); @@ -472,7 +472,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue) // Build near the closest enemy structure var closestEnemy = world.ActorsHavingTrait().Where(a => !a.Disposed && player.RelationshipWith(a.Owner) == PlayerRelationship.Enemy) - .ClosestTo(mapCell.CenterOfCell(baseBuilder.DefenseCenter)); + .ClosestTo(map.CenterOfCell(baseBuilder.DefenseCenter)); var targetCell = closestEnemy != null ? closestEnemy.Location : baseCenter; @@ -483,7 +483,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue) // Try and place the refinery near a resource field if (resourceLayer != null) { - var nearbyResources = mapCell.FindTilesInAnnulus(baseCenter, baseBuilder.Info.MinBaseRadius, baseBuilder.Info.MaxBaseRadius) + var nearbyResources = map.FindTilesInAnnulus(baseCenter, baseBuilder.Info.MinBaseRadius, baseBuilder.Info.MaxBaseRadius) .Where(a => resourceLayer.GetResource(a).Type != null) .Shuffle(world.LocalRandom).Take(baseBuilder.Info.MaxResourceCellsToCheck); @@ -500,7 +500,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue) case BuildingType.Building: return findPos(baseCenter, baseCenter, baseBuilder.Info.MinBaseRadius, - distanceToBaseIsImportant ? baseBuilder.Info.MaxBaseRadius : ((IMapCell)world.Map).Grid.MaximumTileSearchRange); + distanceToBaseIsImportant ? baseBuilder.Info.MaxBaseRadius : world.Map.Grid.MaximumTileSearchRange); } // Can't find a build location diff --git a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/SupportPowerDecision.cs b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/SupportPowerDecision.cs index 42abd6a63003..c17e1b4aac5d 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/SupportPowerDecision.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/SupportPowerDecision.cs @@ -60,10 +60,10 @@ public int GetAttractiveness(WPos pos, Player firedBy) { var answer = 0; var world = firedBy.World; - var mapCell = (IMapCell)world.Map; - var targetTile = mapCell.CellContaining(pos); + var map = world.Map; + var targetTile = map.CellContaining(pos); - if (!mapCell.Contains(targetTile)) + if (!map.Contains(targetTile)) return 0; foreach (var consideration in Considerations) @@ -75,9 +75,9 @@ public int GetAttractiveness(WPos pos, Player firedBy) answer += consideration.GetAttractiveness(scrutinized, firedBy.RelationshipWith(scrutinized.Owner), firedBy); var delta = new WVec(radiusToUse, radiusToUse, WDist.Zero); - var tl = mapCell.CellContaining(pos - delta); - var br = mapCell.CellContaining(pos + delta); - var checkFrozen = firedBy.FrozenActorLayer.FrozenActorsInRegion(new CellRegion(mapCell.Grid.Type, tl, br)); + var tl = map.CellContaining(pos - delta); + var br = map.CellContaining(pos + delta); + var checkFrozen = firedBy.FrozenActorLayer.FrozenActorsInRegion(new CellRegion(map.Grid.Type, tl, br)); // IsValid check filters out Frozen Actors that have not initialized their Owner foreach (var scrutinized in checkFrozen) diff --git a/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs index bd6c3ba43fa6..d1083db7a5c3 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs @@ -142,12 +142,12 @@ Target FindNextResource(Actor actor, HarvesterTraitWrapper harv) harv.Harvester.CanHarvestCell(cell) && claimLayer.CanClaimCell(actor, cell); - var mapCell = (IMapCell)world.Map; + var map = world.Map; var path = harv.Mobile.PathFinder.FindPathToTargetCellByPredicate( actor, new[] { actor.Location }, isValidResource, BlockedByActor.Stationary, - loc => world.FindActorsInCircle(mapCell.CenterOfCell(loc), Info.HarvesterEnemyAvoidanceRadius) + loc => world.FindActorsInCircle(map.CenterOfCell(loc), Info.HarvesterEnemyAvoidanceRadius) .Where(u => !u.IsDead && actor.Owner.RelationshipWith(u.Owner) == PlayerRelationship.Enemy) - .Sum(u => Math.Max(WDist.Zero.Length, Info.HarvesterEnemyAvoidanceRadius.Length - (mapCell.CenterOfCell(loc) - u.CenterPosition).Length))); + .Sum(u => Math.Max(WDist.Zero.Length, Info.HarvesterEnemyAvoidanceRadius.Length - (map.CenterOfCell(loc) - u.CenterPosition).Length))); if (path.Count == 0) return Target.Invalid; diff --git a/OpenRA.Mods.Common/Traits/BotModules/McvManagerBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/McvManagerBotModule.cs index 888a96ee49d8..00535fc95fd7 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/McvManagerBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/McvManagerBotModule.cs @@ -180,7 +180,7 @@ void DeployMcv(IBot bot, Actor mcv, bool move) // Find the buildable cell that is closest to pos and centered around center Func findPos = (center, target, minRange, maxRange) => { - var cells = ((IMapCell)world.Map).FindTilesInAnnulus(center, minRange, maxRange); + var cells = world.Map.FindTilesInAnnulus(center, minRange, maxRange); // Sort by distance to target if we have one if (center != target) @@ -198,7 +198,7 @@ void DeployMcv(IBot bot, Actor mcv, bool move) var baseCenter = GetRandomBaseCenter(); return findPos(baseCenter, baseCenter, Info.MinBaseRadius, - distanceToBaseIsImportant ? Info.MaxBaseRadius : ((IMapCell)world.Map).Grid.MaximumTileSearchRange); + distanceToBaseIsImportant ? Info.MaxBaseRadius : world.Map.Grid.MaximumTileSearchRange); } List IGameSaveTraitData.IssueTraitData(Actor self) diff --git a/OpenRA.Mods.Common/Traits/BotModules/SquadManagerBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/SquadManagerBotModule.cs index dcce78aac10c..c864945b7a8c 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/SquadManagerBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/SquadManagerBotModule.cs @@ -358,7 +358,7 @@ void ProtectOwn(IBot bot, Actor attacker) if (!protectSq.IsValid) { - var ownUnits = World.FindActorsInCircle(((IMapCell)World.Map).CenterOfCell(GetRandomBaseCenter()), WDist.FromCells(Info.ProtectUnitScanRadius)) + var ownUnits = World.FindActorsInCircle(World.Map.CenterOfCell(GetRandomBaseCenter()), WDist.FromCells(Info.ProtectUnitScanRadius)) .Where(unit => unit.Owner == Player && !Info.ProtectionTypes.Contains(unit.Info.Name) && unit.Info.HasTraitInfo()); foreach (var a in ownUnits) diff --git a/OpenRA.Mods.Common/Traits/BotModules/Squads/States/AirStates.cs b/OpenRA.Mods.Common/Traits/BotModules/Squads/States/AirStates.cs index de85082fb6f2..f89e9bb191ac 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/Squads/States/AirStates.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/Squads/States/AirStates.cs @@ -60,19 +60,19 @@ protected static Actor FindDefenselessTarget(Squad owner) protected static CPos? FindSafePlace(Squad owner, out Actor detectedEnemyTarget, bool needTarget) { - var mapCell = (IMapCell)owner.World.Map; + var map = owner.World.Map; var dangerRadius = owner.SquadManager.Info.DangerScanRadius; detectedEnemyTarget = null; - var columnCount = (mapCell.MapSize.X + dangerRadius - 1) / dangerRadius; - var rowCount = (mapCell.MapSize.Y + dangerRadius - 1) / dangerRadius; + var columnCount = (map.MapSize.X + dangerRadius - 1) / dangerRadius; + var rowCount = (map.MapSize.Y + dangerRadius - 1) / dangerRadius; var checkIndices = Exts.MakeArray(columnCount * rowCount, i => i).Shuffle(owner.World.LocalRandom); foreach (var i in checkIndices) { - var pos = new MPos((i % columnCount) * dangerRadius + dangerRadius / 2, (i / columnCount) * dangerRadius + dangerRadius / 2).ToCPos(mapCell); + var pos = new MPos((i % columnCount) * dangerRadius + dangerRadius / 2, (i / columnCount) * dangerRadius + dangerRadius / 2).ToCPos(map); - if (NearToPosSafely(owner, mapCell.CenterOfCell(pos), out detectedEnemyTarget)) + if (NearToPosSafely(owner, map.CenterOfCell(pos), out detectedEnemyTarget)) { if (needTarget && detectedEnemyTarget == null) continue; diff --git a/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs index fb5991cc054f..1894ad2c887c 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs @@ -135,7 +135,6 @@ void IBotTick.BotTick(IBot bot) } var map = world.Map; - var mapCell = (IMapCell)world.Map; var checkRadius = powerDecision.CoarseScanRadius; var suitableLocations = new List<(MPos UV, int Attractiveness)>(); var totalAttractiveness = 0; @@ -146,11 +145,11 @@ void IBotTick.BotTick(IBot bot) { var tl = new MPos(i, j); var br = new MPos(i + checkRadius, j + checkRadius); - var region = new CellRegion(((IMapCell)map).Grid.Type, tl, br); + var region = new CellRegion(map.Grid.Type, tl, br); // HACK: The AI code should not be messing with raw coordinate transformations - var wtl = mapCell.CenterOfCell(tl.ToCPos(mapCell)); - var wbr = mapCell.CenterOfCell(br.ToCPos(mapCell)); + var wtl = map.CenterOfCell(tl.ToCPos(map)); + var wbr = map.CenterOfCell(br.ToCPos(map)); var targets = world.ActorMap.ActorsInBox(wtl, wbr); var frozenTargets = player.FrozenActorLayer != null ? player.FrozenActorLayer.FrozenActorsInRegion(region) : Enumerable.Empty(); @@ -170,7 +169,7 @@ void IBotTick.BotTick(IBot bot) var averageAttractiveness = totalAttractiveness / suitableLocations.Count; return suitableLocations.Shuffle(world.LocalRandom) .First(x => x.Attractiveness >= averageAttractiveness) - .UV.ToCPos(mapCell); + .UV.ToCPos(map); } /// Detail scans an area, evaluating positions. @@ -194,7 +193,7 @@ void IBotTick.BotTick(IBot bot) for (var j = 0 - extendedRange; j <= (checkRadius + extendedRange); j += fineCheck) { var y = checkPos.Y + j; - var pos = ((IMapCell)world.Map).CenterOfCell(new CPos(x, y)); + var pos = world.Map.CenterOfCell(new CPos(x, y)); var consideredAttractiveness = 0; consideredAttractiveness += powerDecision.GetAttractiveness(pos, player); diff --git a/OpenRA.Mods.Common/Traits/Buildings/ActorPreviewPlaceBuildingPreview.cs b/OpenRA.Mods.Common/Traits/Buildings/ActorPreviewPlaceBuildingPreview.cs index 9df0c6d69e85..a36e4ffa0666 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/ActorPreviewPlaceBuildingPreview.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/ActorPreviewPlaceBuildingPreview.cs @@ -72,7 +72,7 @@ protected override void TickInner() protected override IEnumerable RenderInner(WorldRenderer wr, CPos topLeft, Dictionary footprint) { - var centerPosition = ((IMapCell)wr.World.Map).CenterOfCell(topLeft) + CenterOffset; + var centerPosition = wr.World.Map.CenterOfCell(topLeft) + CenterOffset; var previewRenderables = preview .SelectMany(p => p.Render(wr, centerPosition)); diff --git a/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs b/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs index e650a4cab92d..b9e3731e3fdf 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs @@ -155,7 +155,7 @@ public void Create(ushort template, Dictionary footprint) foreach (var c in footprint.Keys) { var tileInfo = GetTerrainInfo(c); - ((IMapCell)self.World.Map).CustomTerrain[c] = tileInfo.TerrainType; + self.World.Map.CustomTerrain[c] = tileInfo.TerrainType; radarSignature[i++] = (c, tileInfo.GetColor(self.World.LocalRandom)); } } @@ -217,7 +217,7 @@ IRenderable[] TemplateRenderables(WorldRenderer wr, PaletteReference palette, us return footprint.Select(c => (IRenderable)(new SpriteRenderable( terrainRenderer.TileSprite(new TerrainTile(template, c.Value)), - ((IMapCell)wr.World.Map).CenterOfCell(c.Key), WVec.Zero, -offset, palette, 1f, 1f, + wr.World.Map.CenterOfCell(c.Key), WVec.Zero, -offset, palette, 1f, 1f, float3.Ones, TintModifiers.None, true))).ToArray(); } @@ -242,7 +242,7 @@ public IEnumerable ScreenBounds(Actor self, WorldRenderer wr) { foreach (var kv in footprint) { - var xy = wr.ScreenPxPosition(((IMapCell)wr.World.Map).CenterOfCell(kv.Key)); + var xy = wr.ScreenPxPosition(wr.World.Map.CenterOfCell(kv.Key)); var size = terrainRenderer.TileSprite(new TerrainTile(template, kv.Value)).Bounds.Size; // Add an extra pixel padding to avoid issues with odd-sized sprites @@ -319,7 +319,7 @@ void UpdateState() foreach (var c in footprint.Keys) { var tileInfo = GetTerrainInfo(c); - ((IMapCell)self.World.Map).CustomTerrain[c] = tileInfo.TerrainType; + self.World.Map.CustomTerrain[c] = tileInfo.TerrainType; radarSignature[i++] = (c, tileInfo.GetColor(self.World.LocalRandom)); } diff --git a/OpenRA.Mods.Common/Traits/Buildings/Building.cs b/OpenRA.Mods.Common/Traits/Buildings/Building.cs index 1744d3aadabc..b508bd4229fe 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/Building.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/Building.cs @@ -152,14 +152,14 @@ public IEnumerable TransitOnlyTiles(CPos location) public WVec CenterOffset(World w) { - var mapCell = (IMapCell)w.Map; - var off = (mapCell.CenterOfCell(new CPos(Dimensions.X, Dimensions.Y)) - mapCell.CenterOfCell(new CPos(1, 1))) / 2; + var map = w.Map; + var off = (map.CenterOfCell(new CPos(Dimensions.X, Dimensions.Y)) - map.CenterOfCell(new CPos(1, 1))) / 2; return (off - new WVec(0, 0, off.Z)) + LocalCenterOffset; } public BaseProvider FindBaseProvider(World world, Player p, CPos topLeft) { - var center = ((IMapCell)world.Map).CenterOfCell(topLeft) + CenterOffset(world); + var center = world.Map.CenterOfCell(topLeft) + CenterOffset(world); var mapBuildRadius = world.WorldActor.TraitOrDefault(); var allyBuildEnabled = mapBuildRadius != null && mapBuildRadius.AllyBuildRadiusEnabled; @@ -215,9 +215,9 @@ public virtual bool IsCloseEnoughToBase(World world, Player p, ActorInfo ai, CPo var adjacent = requiresBuildableArea.Adjacent; var buildingMaxBounds = Dimensions; - var mapCell = (IMapCell)world.Map; - var scanStart = mapCell.Clamp(topLeft - new CVec(adjacent, adjacent)); - var scanEnd = mapCell.Clamp(topLeft + buildingMaxBounds + new CVec(adjacent, adjacent)); + var map = world.Map; + var scanStart = map.Clamp(topLeft - new CVec(adjacent, adjacent)); + var scanEnd = map.Clamp(topLeft + buildingMaxBounds + new CVec(adjacent, adjacent)); var nearnessCandidates = new List(); var bi = world.WorldActor.Trait(); @@ -298,7 +298,7 @@ public Building(ActorInitializer init, BuildingInfo info) transitOnlyCells = Info.TransitOnlyTiles(TopLeft).ToArray(); - CenterPosition = ((IMapCell)init.World.Map).CenterOfCell(topLeft) + Info.CenterOffset(init.World); + CenterPosition = init.World.Map.CenterOfCell(topLeft) + Info.CenterOffset(init.World); } public (CPos, SubCell)[] OccupiedCells() { return occupiedCells; } diff --git a/OpenRA.Mods.Common/Traits/Buildings/BuildingInfluence.cs b/OpenRA.Mods.Common/Traits/Buildings/BuildingInfluence.cs index 389669eadcf7..a20a77a8a7da 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/BuildingInfluence.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/BuildingInfluence.cs @@ -36,14 +36,14 @@ public BuildingInfluence(World world) { map = world.Map; - influence = new CellLayer((IMapCell)map); + influence = new CellLayer(map); } internal void AddInfluence(Actor a, IEnumerable cells) { foreach (var c in cells) { - var uv = c.ToMPos((IMapCell)map); + var uv = c.ToMPos(map); if (influence.Contains(uv)) influence[uv] = new InfluenceNode { Next = influence[uv], Actor = a }; } @@ -53,7 +53,7 @@ internal void RemoveInfluence(Actor a, IEnumerable cells) { foreach (var c in cells) { - var uv = c.ToMPos((IMapCell)map); + var uv = c.ToMPos(map); if (!influence.Contains(uv)) continue; @@ -72,7 +72,7 @@ static InfluenceNode RemoveInfluenceInner(InfluenceNode influenceNode, Actor toR public IEnumerable GetBuildingsAt(CPos cell) { - var uv = cell.ToMPos((IMapCell)map); + var uv = cell.ToMPos(map); if (!influence.Contains(uv)) yield break; diff --git a/OpenRA.Mods.Common/Traits/Buildings/BuildingUtils.cs b/OpenRA.Mods.Common/Traits/Buildings/BuildingUtils.cs index f0a6eb533823..6ac72e1e3b2e 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/BuildingUtils.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/BuildingUtils.cs @@ -18,9 +18,9 @@ public static class BuildingUtils { public static bool IsCellBuildable(this World world, CPos cell, ActorInfo ai, BuildingInfo bi, Actor toIgnore = null) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; if (!bi.AllowInvalidPlacement) @@ -79,7 +79,7 @@ public static bool IsCellBuildable(this World world, CPos cell, ActorInfo ai, Bu } // Buildings can never be placed on ramps - return mapCell.Ramp[cell] == 0 && bi.TerrainTypes.Contains(mapCell.GetTerrainInfo(cell).Type); + return ((IMapElevation)map).Ramp[cell] == 0 && bi.TerrainTypes.Contains(map.GetTerrainInfo(cell).Type); } public static bool CanPlaceBuilding(this World world, CPos cell, ActorInfo ai, BuildingInfo bi, Actor toIgnore) @@ -88,7 +88,7 @@ public static bool CanPlaceBuilding(this World world, CPos cell, ActorInfo ai, B return true; var resourceLayer = world.WorldActor.TraitOrDefault(); - return bi.Tiles(cell).All(t => ((IMapCell)world.Map).Contains(t) && + return bi.Tiles(cell).All(t => world.Map.Contains(t) && (bi.AllowPlacementOnResources || resourceLayer == null || resourceLayer.GetResource(t).Type == null) && world.IsCellBuildable(t, ai, bi, toIgnore)); } diff --git a/OpenRA.Mods.Common/Traits/Buildings/Exit.cs b/OpenRA.Mods.Common/Traits/Buildings/Exit.cs index fa41be5be1cf..a821a5e0e137 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/Exit.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/Exit.cs @@ -54,7 +54,7 @@ public static Exit NearestExitOrDefault(this Actor actor, WPos pos, string produ // called on the same exits in the same order! var all = Exits(actor, productionType) .OrderByDescending(e => e.Info.Priority) - .ThenBy(e => (((IMapCell)actor.World.Map).CenterOfCell(actor.Location + e.Info.ExitCell) - pos).LengthSquared) + .ThenBy(e => (actor.World.Map.CenterOfCell(actor.Location + e.Info.ExitCell) - pos).LengthSquared) .ToList(); return p != null ? all.FirstOrDefault(p) : all.FirstOrDefault(); diff --git a/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs b/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs index a1bf43dd6465..fe2cf5e913d5 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs @@ -64,7 +64,7 @@ public FootprintPlaceBuildingPreviewPreview(WorldRenderer wr, ActorInfo ai, Foot CenterOffset = ActorInfo.TraitInfo().CenterOffset(world); topLeftScreenOffset = -wr.ScreenPxOffset(CenterOffset); - var tileset = ((IMapCell)world.Map).Tileset.ToLowerInvariant(); + var tileset = world.Map.Tileset.ToLowerInvariant(); if (world.Map.Rules.Sequences.HasSequence("overlay", $"build-valid-{tileset}")) { var validSequence = world.Map.Rules.Sequences.GetSequence("overlay", $"build-valid-{tileset}"); @@ -89,8 +89,8 @@ public FootprintPlaceBuildingPreviewPreview(WorldRenderer wr, ActorInfo ai, Foot PlaceBuildingCellType filter = PlaceBuildingCellType.Invalid | PlaceBuildingCellType.Valid | PlaceBuildingCellType.LineBuild) { var palette = wr.Palette(info.Palette); - var mapCell = (IMapCell)wr.World.Map; - var topLeftPos = mapCell.CenterOfCell(topLeft); + var map = wr.World.Map; + var topLeftPos = map.CenterOfCell(topLeft); foreach (var c in footprint) { if ((c.Value & filter) == 0) @@ -98,7 +98,7 @@ public FootprintPlaceBuildingPreviewPreview(WorldRenderer wr, ActorInfo ai, Foot var tile = (c.Value & PlaceBuildingCellType.Invalid) != 0 ? blockedTile : validTile; var sequenceAlpha = (c.Value & PlaceBuildingCellType.Invalid) != 0 ? blockedAlpha : validAlpha; - var pos = mapCell.CenterOfCell(c.Key); + var pos = map.CenterOfCell(c.Key); var offset = new WVec(0, 0, topLeftPos.Z - pos.Z); var traitAlpha = (c.Value & PlaceBuildingCellType.LineBuild) != 0 ? info.LineBuildFootprintAlpha : info.FootprintAlpha; yield return new SpriteRenderable(tile, pos, offset, -511, palette, 1f, sequenceAlpha * traitAlpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); @@ -107,7 +107,7 @@ public FootprintPlaceBuildingPreviewPreview(WorldRenderer wr, ActorInfo ai, Foot protected virtual IEnumerable RenderAnnotations(WorldRenderer wr, CPos topLeft) { - var centerPosition = ((IMapCell)wr.World.Map).CenterOfCell(topLeft) + CenterOffset; + var centerPosition = wr.World.Map.CenterOfCell(topLeft) + CenterOffset; foreach (var d in decorations) foreach (var r in d.RenderAnnotations(wr, wr.World, ActorInfo, centerPosition)) yield return r; diff --git a/OpenRA.Mods.Common/Traits/Buildings/FreeActorWithDelivery.cs b/OpenRA.Mods.Common/Traits/Buildings/FreeActorWithDelivery.cs index 274ee4cb33f9..7a958d17c741 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/FreeActorWithDelivery.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/FreeActorWithDelivery.cs @@ -68,7 +68,7 @@ public void DoDelivery(CPos location, string actorName, string carrierActorName) var carryall = carrier.Trait(); carryall.AttachCarryable(carrier, cargo); carrier.QueueActivity(new DeliverUnit(carrier, Target.FromCell(self.World, location), info.DeliveryRange, carryall.Info.TargetLineColor)); - carrier.QueueActivity(new Fly(carrier, Target.FromCell(self.World, ((IMapCell)self.World.Map).ChooseRandomEdgeCell(self.World.SharedRandom)))); + carrier.QueueActivity(new Fly(carrier, Target.FromCell(self.World, self.World.Map.ChooseRandomEdgeCell(self.World.SharedRandom)))); carrier.QueueActivity(new RemoveSelf()); self.World.AddFrameEndTask(w => self.World.Add(carrier)); @@ -76,16 +76,16 @@ public void DoDelivery(CPos location, string actorName, string carrierActorName) void CreateActors(string actorName, string deliveringActorName, out Actor cargo, out Actor carrier) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; // Get a carryall spawn location var location = info.SpawnLocation; if (location == CPos.Zero) - location = mapCell.ChooseClosestEdgeCell(self.Location); + location = map.ChooseClosestEdgeCell(self.Location); - var spawn = mapCell.CenterOfCell(location); + var spawn = map.CenterOfCell(location); - var initialFacing = mapCell.FacingBetween(location, self.Location, WAngle.Zero); + var initialFacing = map.FacingBetween(location, self.Location, WAngle.Zero); // If aircraft, spawn at cruise altitude var aircraftInfo = self.World.Map.Rules.Actors[deliveringActorName.ToLowerInvariant()].TraitInfoOrDefault(); diff --git a/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs b/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs index 432f10f94ca0..5ea67a06a951 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs @@ -69,7 +69,7 @@ public GroundLevelBridge(Actor self, GroundLevelBridgeInfo info) void UpdateTerrain(Actor self, byte terrainIndex) { foreach (var cell in cells) - ((IMapCell)self.World.Map).CustomTerrain[cell] = terrainIndex; + self.World.Map.CustomTerrain[cell] = terrainIndex; } void INotifyAddedToWorld.AddedToWorld(Actor self) diff --git a/OpenRA.Mods.Common/Traits/Buildings/ProductionAirdrop.cs b/OpenRA.Mods.Common/Traits/Buildings/ProductionAirdrop.cs index 8367640007cc..4c4337213614 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/ProductionAirdrop.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/ProductionAirdrop.cs @@ -63,7 +63,7 @@ public override bool Produce(Actor self, ActorInfo producee, string productionTy if (info.BaselineSpawn) { var bounds = map.Bounds; - var center = new MPos(bounds.Left + bounds.Width / 2, bounds.Top + bounds.Height / 2).ToCPos((IMapCell)map); + var center = new MPos(bounds.Left + bounds.Width / 2, bounds.Top + bounds.Height / 2).ToCPos(map); var spawnVec = owner.HomeLocation - center; startPos = owner.HomeLocation + spawnVec * (Exts.ISqrt((bounds.Height * bounds.Height + bounds.Width * bounds.Width) / (4 * spawnVec.LengthSquared))); endPos = startPos; @@ -74,10 +74,9 @@ public override bool Produce(Actor self, ActorInfo producee, string productionTy { // Start a fixed distance away: the width of the map. // This makes the production timing independent of spawnpoint - var mapCell = (IMapCell)map; - var loc = self.Location.ToMPos(mapCell); - startPos = new MPos(loc.U + map.Bounds.Width, loc.V).ToCPos(mapCell); - endPos = new MPos(map.Bounds.Left, loc.V).ToCPos(mapCell); + var loc = self.Location.ToMPos(map); + startPos = new MPos(loc.U + map.Bounds.Width, loc.V).ToCPos(map); + endPos = new MPos(map.Bounds.Left, loc.V).ToCPos(map); spawnFacing = info.Facing; } @@ -97,7 +96,7 @@ public override bool Produce(Actor self, ActorInfo producee, string productionTy var actor = w.CreateActor(info.ActorType, new TypeDictionary { - new CenterPositionInit(((IMapCell)w.Map).CenterOfCell(startPos) + new WVec(WDist.Zero, WDist.Zero, aircraftInfo.CruiseAltitude)), + new CenterPositionInit(w.Map.CenterOfCell(startPos) + new WVec(WDist.Zero, WDist.Zero, aircraftInfo.CruiseAltitude)), new OwnerInit(owner), new FacingInit(spawnFacing) }); diff --git a/OpenRA.Mods.Common/Traits/Buildings/RallyPoint.cs b/OpenRA.Mods.Common/Traits/Buildings/RallyPoint.cs index b293e54ea9f4..d2e6a0ffda16 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/RallyPoint.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/RallyPoint.cs @@ -130,7 +130,7 @@ public void ResolveOrder(Actor self, Order order) if (!order.Queued) Path.Clear(); - Path.Add(((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition)); + Path.Add(self.World.Map.CellContaining(order.Target.CenterPosition)); } public static bool IsForceSet(Order order) @@ -160,9 +160,9 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); - var mapCell = (IMapCell)self.World.Map; - var location = mapCell.CellContaining(target.CenterPosition); - if (mapCell.Contains(location)) + var map = self.World.Map; + var location = map.CellContaining(target.CenterPosition); + if (map.Contains(location)) { cursor = info.Cursor; diff --git a/OpenRA.Mods.Common/Traits/Buildings/SequencePlaceBuildingPreview.cs b/OpenRA.Mods.Common/Traits/Buildings/SequencePlaceBuildingPreview.cs index aa7e2fb77228..d619bfd128c6 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/SequencePlaceBuildingPreview.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/SequencePlaceBuildingPreview.cs @@ -77,7 +77,7 @@ protected override IEnumerable RenderInner(WorldRenderer wr, CPos t foreach (var r in RenderFootprint(wr, topLeft, footprint, info.FootprintUnderPreview)) yield return r; - var centerPosition = ((IMapCell)wr.World.Map).CenterOfCell(topLeft) + CenterOffset; + var centerPosition = wr.World.Map.CenterOfCell(topLeft) + CenterOffset; foreach (var r in preview.Render(centerPosition, WVec.Zero, 0, palette)) { if (info.SequenceAlpha < 1f && r is IModifyableRenderable mr) diff --git a/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoAircraft.cs b/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoAircraft.cs index 3bda69267d9b..ae3e6ea262da 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoAircraft.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoAircraft.cs @@ -121,8 +121,8 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) if (order.OrderString == "Move") { - var mapCell = (IMapCell)self.World.Map; - var cell = mapCell.Clamp(mapCell.CellContaining(order.Target.CenterPosition)); + var map = self.World.Map; + var cell = map.Clamp(map.CellContaining(order.Target.CenterPosition)); if (!Info.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; } @@ -167,7 +167,7 @@ string IOrderVoice.VoicePhraseForOrder(Actor self, Order order) case "Move": if (!Info.MoveIntoShroud && order.Target.Type != TargetType.Invalid) { - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (!self.Owner.Shroud.IsExplored(cell)) return null; } @@ -206,10 +206,10 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier if (target.Type != TargetType.Terrain || (aircraft.Info.RequiresForceMove && !modifiers.HasModifier(TargetModifiers.ForceMove))) return false; - var mapCell = (IMapCell)self.World.Map; - var location = mapCell.CellContaining(target.CenterPosition); + var map = self.World.Map; + var location = map.CellContaining(target.CenterPosition); var explored = self.Owner.Shroud.IsExplored(location); - cursor = mapCell.Contains(location) ? aircraft.Info.Cursor : aircraft.Info.BlockedCursor; + cursor = map.Contains(location) ? aircraft.Info.Cursor : aircraft.Info.BlockedCursor; IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); diff --git a/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs b/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs index 547eee714a79..13489b372405 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs @@ -110,7 +110,7 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) if (order.OrderString == "Move") { - var cell = ((IMapCell)self.World.Map).Clamp(((IMapCell)this.self.World.Map).CellContaining(order.Target.CenterPosition)); + var cell = self.World.Map.Clamp(self.World.Map.CellContaining(order.Target.CenterPosition)); if (!Info.LocomotorInfo.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; @@ -153,7 +153,7 @@ string IOrderVoice.VoicePhraseForOrder(Actor self, Order order) case "Move": if (!Info.LocomotorInfo.MoveIntoShroud && order.Target.Type != TargetType.Invalid) { - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (!self.Owner.Shroud.IsExplored(cell)) return null; } @@ -194,17 +194,17 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier if (rejectMove || target.Type != TargetType.Terrain || (mobile.Info.RequiresForceMove && !modifiers.HasModifier(TargetModifiers.ForceMove))) return false; - var mapCell = (IMapCell)self.World.Map; - var location = mapCell.CellContaining(target.CenterPosition); + var map = self.World.Map; + var location = map.CellContaining(target.CenterPosition); IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); var explored = self.Owner.Shroud.IsExplored(location); - if (!mapCell.Contains(location) || + if (!map.Contains(location) || !(self.CurrentActivity is Transform || mobile.transforms.Any(t => !t.IsTraitDisabled && !t.IsTraitPaused)) || (!explored && !mobile.locomotor.Info.MoveIntoShroud) || (explored && !CanEnterCell(self, location))) cursor = mobile.Info.BlockedCursor; - else if (!explored || !mobile.Info.TerrainCursors.TryGetValue(mapCell.GetTerrainInfo(location).Type, out cursor)) + else if (!explored || !mobile.Info.TerrainCursors.TryGetValue(map.GetTerrainInfo(location).Type, out cursor)) cursor = mobile.Info.Cursor; return true; diff --git a/OpenRA.Mods.Common/Traits/Cargo.cs b/OpenRA.Mods.Common/Traits/Cargo.cs index c74b43d4e09e..81079727d563 100644 --- a/OpenRA.Mods.Common/Traits/Cargo.cs +++ b/OpenRA.Mods.Common/Traits/Cargo.cs @@ -237,7 +237,7 @@ public bool CanUnload(BlockedByActor check = BlockedByActor.None) { if (checkTerrainType) { - var terrainType = ((IMapCell)self.World.Map).GetTerrainInfo(self.Location).Type; + var terrainType = self.World.Map.GetTerrainInfo(self.Location).Type; if (!Info.UnloadTerrainTypes.Contains(terrainType)) return false; @@ -410,7 +410,7 @@ void INotifyKilled.Killed(Actor self, AttackInfo e) { var passenger = Unload(self); var cp = self.CenterPosition; - var inAir = ((IMapCell)self.World.Map).DistanceAboveTerrain(cp).Length != 0; + var inAir = self.World.Map.DistanceAboveTerrain(cp).Length != 0; var positionable = passenger.Trait(); positionable.SetPosition(passenger, self.Location); diff --git a/OpenRA.Mods.Common/Traits/Carryall.cs b/OpenRA.Mods.Common/Traits/Carryall.cs index f2daa4b04173..f9195ab0d2e7 100644 --- a/OpenRA.Mods.Common/Traits/Carryall.cs +++ b/OpenRA.Mods.Common/Traits/Carryall.cs @@ -307,7 +307,7 @@ IEnumerable IRender.ScreenBounds(Actor self, WorldRenderer wr) // Check if we can drop the unit at our current location. public bool CanUnload() { - var targetCell = ((IMapCell)self.World.Map).CellContaining(aircraft.GetPosition()); + var targetCell = self.World.Map.CellContaining(aircraft.GetPosition()); return Carryable != null && aircraft.CanLand(targetCell, blockedByMobile: false); } @@ -341,8 +341,8 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) { if (order.OrderString == "DeliverUnit") { - var mapCell = (IMapCell)self.World.Map; - var cell = mapCell.Clamp(mapCell.CellContaining(order.Target.CenterPosition)); + var map = self.World.Map; + var cell = map.Clamp(map.CellContaining(order.Target.CenterPosition)); if (!aircraftInfo.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; @@ -441,10 +441,10 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier return true; } - var mapCell = (IMapCell)self.World.Map; - var location = mapCell.CellContaining(target.CenterPosition); + var map = self.World.Map; + var location = map.CellContaining(target.CenterPosition); var explored = self.Owner.Shroud.IsExplored(location); - cursor = mapCell.Contains(location) ? info.DropOffCursor : info.DropOffBlockedCursor; + cursor = map.Contains(location) ? info.DropOffCursor : info.DropOffBlockedCursor; IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); diff --git a/OpenRA.Mods.Common/Traits/ChangesTerrain.cs b/OpenRA.Mods.Common/Traits/ChangesTerrain.cs index a0f19c81913c..4f36d547b424 100644 --- a/OpenRA.Mods.Common/Traits/ChangesTerrain.cs +++ b/OpenRA.Mods.Common/Traits/ChangesTerrain.cs @@ -36,17 +36,16 @@ void INotifyAddedToWorld.AddedToWorld(Actor self) { var cell = self.Location; var map = self.World.Map; - var mapCell = (IMapCell)self.World.Map; var terrain = map.Rules.TerrainInfo.GetTerrainIndex(info.TerrainType); - previousTerrain = mapCell.CustomTerrain[cell]; - mapCell.CustomTerrain[cell] = terrain; + previousTerrain = map.CustomTerrain[cell]; + map.CustomTerrain[cell] = terrain; } void INotifyRemovedFromWorld.RemovedFromWorld(Actor self) { var cell = self.Location; - var mapCell = (IMapCell)self.World.Map; - mapCell.CustomTerrain[cell] = previousTerrain; + var map = self.World.Map; + map.CustomTerrain[cell] = previousTerrain; } } } diff --git a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnDeploy.cs b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnDeploy.cs index a11d4c318557..08b5b43bdf1b 100644 --- a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnDeploy.cs +++ b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnDeploy.cs @@ -220,13 +220,13 @@ public bool IsValidTerrain(CPos location) bool IsValidTerrainType(CPos location) { - if (!((IMapCell)self.World.Map).Contains(location)) + if (!self.World.Map.Contains(location)) return false; if (!checkTerrainType) return true; - var terrainType = ((IMapCell)self.World.Map).GetTerrainInfo(location).Type; + var terrainType = self.World.Map.GetTerrainInfo(location).Type; return Info.AllowedTerrainTypes.Contains(terrainType); } @@ -236,8 +236,8 @@ bool IsValidRampType(CPos location) if (Info.CanDeployOnRamps) return true; - var mapCell = (IMapCell)self.World.Map; - return !mapCell.Ramp.Contains(location) || mapCell.Ramp[location] == 0; + var mapRamp = ((IMapElevation)self.World.Map).Ramp; + return !mapRamp.Contains(location) || mapRamp[location] == 0; } void INotifyDeployComplete.FinishedDeploy(Actor self) diff --git a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnSubterraneanLayer.cs b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnSubterraneanLayer.cs index 61b87516e400..9c6287be15b9 100644 --- a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnSubterraneanLayer.cs +++ b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnSubterraneanLayer.cs @@ -60,7 +60,7 @@ protected override void Created(Actor self) void PlayTransitionAudioVisuals(Actor self, CPos fromCell) { if (!string.IsNullOrEmpty(Info.SubterraneanTransitionSequence)) - self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(((IMapCell)self.World.Map).CenterOfCell(fromCell), self.World, + self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(self.World.Map.CenterOfCell(fromCell), self.World, Info.SubterraneanTransitionImage, Info.SubterraneanTransitionSequence, Info.SubterraneanTransitionPalette))); @@ -70,7 +70,7 @@ void PlayTransitionAudioVisuals(Actor self, CPos fromCell) void INotifyCenterPositionChanged.CenterPositionChanged(Actor self, byte oldLayer, byte newLayer) { - var depth = ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition); + var depth = self.World.Map.DistanceAboveTerrain(self.CenterPosition); // Grant condition when new layer is Subterranean and depth is lower than transition depth, // revoke condition when new layer is not Subterranean and depth is at or higher than transition depth. diff --git a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTerrain.cs b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTerrain.cs index 2fdda6ae5acb..b2d436b37374 100644 --- a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTerrain.cs +++ b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTerrain.cs @@ -45,14 +45,14 @@ public GrantConditionOnTerrain(ActorInitializer init, GrantConditionOnTerrainInf void ITick.Tick(Actor self) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; var cell = self.Location; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return; // The terrain type may change between ticks without the actor moving - var currentTerrain = cell.Layer == 0 ? mapCell.GetTerrainInfo(cell).Type : + var currentTerrain = cell.Layer == 0 ? map.GetTerrainInfo(cell).Type : terrainTypes[self.World.GetCustomMovementLayers()[cell.Layer].GetTerrainIndex(cell)].Type; var wantsGranted = info.TerrainTypes.Contains(currentTerrain); diff --git a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTileSet.cs b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTileSet.cs index 2ac34151cbe2..144a231fafa8 100644 --- a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTileSet.cs +++ b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnTileSet.cs @@ -40,7 +40,7 @@ public GrantConditionOnTileSet(GrantConditionOnTileSetInfo info) void INotifyCreated.Created(Actor self) { - if (info.TileSets.Contains(((IMapCell)self.World.Map).Tileset)) + if (info.TileSets.Contains(self.World.Map.Tileset)) self.GrantCondition(info.Condition); } } diff --git a/OpenRA.Mods.Common/Traits/Crates/Crate.cs b/OpenRA.Mods.Common/Traits/Crates/Crate.cs index 01ed4bc56aaa..36fa209ba3d1 100644 --- a/OpenRA.Mods.Common/Traits/Crates/Crate.cs +++ b/OpenRA.Mods.Common/Traits/Crates/Crate.cs @@ -47,12 +47,12 @@ public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = S public bool CanExistInCell(World world, CPos cell) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; - var type = mapCell.GetTerrainInfo(cell).Type; + var type = map.GetTerrainInfo(cell).Type; if (!TerrainTypes.Contains(type)) return false; @@ -184,7 +184,8 @@ void ITick.Tick(Actor self) // Sets the location (Location) and position (CenterPosition) public void SetPosition(Actor self, WPos pos) { - var cell = self.World.Map.CellContaining(pos); + var map = self.World.Map; + var cell = map.CellContaining(pos); SetLocation(self, cell); SetCenterPosition(self, self.World.Map.CenterOfCell(cell) + new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(pos))); } @@ -246,7 +247,7 @@ void INotifyAddedToWorld.AddedToWorld(Actor self) self.World.WorldActor.TraitOrDefault()?.IncrementCrates(); - if (((IMapCell)self.World.Map).DistanceAboveTerrain(CenterPosition) > WDist.Zero && self.TraitOrDefault() != null) + if (self.World.Map.DistanceAboveTerrain(CenterPosition) > WDist.Zero && self.TraitOrDefault() != null) self.QueueActivity(new Parachute(self)); } diff --git a/OpenRA.Mods.Common/Traits/Crates/DuplicateUnitCrateAction.cs b/OpenRA.Mods.Common/Traits/Crates/DuplicateUnitCrateAction.cs index 9fdca38e48e3..c3ce74e84c87 100644 --- a/OpenRA.Mods.Common/Traits/Crates/DuplicateUnitCrateAction.cs +++ b/OpenRA.Mods.Common/Traits/Crates/DuplicateUnitCrateAction.cs @@ -69,7 +69,7 @@ public bool CanGiveTo(Actor collector) if (positionable == null) return false; - return ((IMapCell)collector.World.Map).FindTilesInCircle(collector.Location, info.MaxRadius) + return collector.World.Map.FindTilesInCircle(collector.Location, info.MaxRadius) .Any(c => positionable.CanEnterCell(c)); } @@ -84,7 +84,7 @@ public override int GetSelectionShares(Actor collector) public override void Activate(Actor collector) { var positionable = collector.Trait(); - var candidateCells = ((IMapCell)collector.World.Map).FindTilesInCircle(collector.Location, info.MaxRadius) + var candidateCells = collector.World.Map.FindTilesInCircle(collector.Location, info.MaxRadius) .Where(c => positionable.CanEnterCell(c)).Shuffle(collector.World.SharedRandom) .ToArray(); diff --git a/OpenRA.Mods.Common/Traits/DamagedByTerrain.cs b/OpenRA.Mods.Common/Traits/DamagedByTerrain.cs index 298e94b81dfd..af0cbd41df5d 100644 --- a/OpenRA.Mods.Common/Traits/DamagedByTerrain.cs +++ b/OpenRA.Mods.Common/Traits/DamagedByTerrain.cs @@ -52,7 +52,7 @@ void ITick.Tick(Actor self) if (!self.IsInWorld) return; - var t = ((IMapCell)self.World.Map).GetTerrainInfo(self.Location); + var t = self.World.Map.GetTerrainInfo(self.Location); if (!Info.Terrain.Contains(t.Type)) return; diff --git a/OpenRA.Mods.Common/Traits/EjectOnDeath.cs b/OpenRA.Mods.Common/Traits/EjectOnDeath.cs index 1bfaef83ecd3..dffc13a1cea7 100644 --- a/OpenRA.Mods.Common/Traits/EjectOnDeath.cs +++ b/OpenRA.Mods.Common/Traits/EjectOnDeath.cs @@ -46,7 +46,7 @@ public EjectOnDeath(EjectOnDeathInfo info) void INotifyKilled.Killed(Actor self, AttackInfo e) { - if (IsTraitDisabled || self.Owner.WinState == WinState.Lost || !((IMapCell)self.World.Map).Contains(self.Location)) + if (IsTraitDisabled || self.Owner.WinState == WinState.Lost || !self.World.Map.Contains(self.Location)) return; if (self.World.SharedRandom.Next(100) >= Info.SuccessRate) @@ -81,7 +81,7 @@ void INotifyKilled.Killed(Actor self, AttackInfo e) if (subCell != SubCell.Invalid) { td.Add(new SubCellInit(subCell)); - spawnPos = ((IMapCell)self.World.Map).CenterOfSubCell(self.Location, subCell) + new WVec(0, 0, spawnPos.Z); + spawnPos = self.World.Map.CenterOfSubCell(self.Location, subCell) + new WVec(0, 0, spawnPos.Z); } } diff --git a/OpenRA.Mods.Common/Traits/ExitsDebugOverlay.cs b/OpenRA.Mods.Common/Traits/ExitsDebugOverlay.cs index 66ed27306c5a..6ac2131e1b12 100644 --- a/OpenRA.Mods.Common/Traits/ExitsDebugOverlay.cs +++ b/OpenRA.Mods.Common/Traits/ExitsDebugOverlay.cs @@ -63,7 +63,7 @@ IEnumerable IRenderAnnotationsWhenSelected.RenderAnnotations(Actor { var color = self.Owner.Color; var vec = exitCell - self.Location; - var center = ((IMapCell)wr.World.Map).CenterOfCell(exitCell); + var center = wr.World.Map.CenterOfCell(exitCell); yield return new TextAnnotationRenderable(manager.Font, center, 0, color, vec.ToString()); } } @@ -80,7 +80,7 @@ IEnumerable IRenderAnnotationsWhenSelected.RenderAnnotations(Actor continue; var vec = perimCell - self.Location; - var center = ((IMapCell)wr.World.Map).CenterOfCell(perimCell); + var center = wr.World.Map.CenterOfCell(perimCell); yield return new TextAnnotationRenderable(manager.Font, center, 0, color, vec.ToString()); } } @@ -95,7 +95,7 @@ IEnumerable IRenderAnnotationsWhenSelected.RenderAnnotations(Actor if (spawnPos == self.CenterPosition) continue; - var exitCellCenter = ((IMapCell)self.World.Map).CenterOfCell(exitCells[i]); + var exitCellCenter = self.World.Map.CenterOfCell(exitCells[i]); yield return new LineAnnotationRenderable(spawnPos, exitCellCenter, 1, self.Owner.Color); } } diff --git a/OpenRA.Mods.Common/Traits/Explodes.cs b/OpenRA.Mods.Common/Traits/Explodes.cs index b23bd29ca0db..87a32384b7bd 100644 --- a/OpenRA.Mods.Common/Traits/Explodes.cs +++ b/OpenRA.Mods.Common/Traits/Explodes.cs @@ -124,7 +124,7 @@ void INotifyKilled.Killed(Actor self, AttackInfo e) { var cells = buildingInfo.OccupiedTiles(self.Location); foreach (var c in cells) - weapon.Impact(Target.FromPos(((IMapCell)self.World.Map).CenterOfCell(c) + Info.Offset), source); + weapon.Impact(Target.FromPos(self.World.Map.CenterOfCell(c) + Info.Offset), source); return; } diff --git a/OpenRA.Mods.Common/Traits/Harvester.cs b/OpenRA.Mods.Common/Traits/Harvester.cs index 4434891a865c..d4b3f9cf1f7f 100644 --- a/OpenRA.Mods.Common/Traits/Harvester.cs +++ b/OpenRA.Mods.Common/Traits/Harvester.cs @@ -336,7 +336,7 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) if (order.Target.Type != TargetType.Invalid) { // Find the nearest claimable cell to the order location (useful for group-select harvest): - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); loc = mobile.NearestCell(cell, p => mobile.CanEnterCell(p) && claimLayer.TryClaimCell(self, p), 1, 6); } else @@ -396,7 +396,7 @@ public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifier if (modifiers.HasModifier(TargetModifiers.ForceMove)) return false; - var location = ((IMapCell)self.World.Map).CellContaining(target.CenterPosition); + var location = self.World.Map.CellContaining(target.CenterPosition); // Don't leak info about resources under the shroud if (!self.Owner.Shroud.IsExplored(location)) diff --git a/OpenRA.Mods.Common/Traits/HitShape.cs b/OpenRA.Mods.Common/Traits/HitShape.cs index 308f216b8cd5..8b92953af25b 100644 --- a/OpenRA.Mods.Common/Traits/HitShape.cs +++ b/OpenRA.Mods.Common/Traits/HitShape.cs @@ -124,7 +124,7 @@ IEnumerable TargetablePositions(Actor self) { if (Info.UseTargetableCellsOffsets && targetableCells != null) foreach (var c in targetableCells.TargetableCells()) - yield return ((IMapCell)self.World.Map).CenterOfCell(c.Cell); + yield return self.World.Map.CenterOfCell(c.Cell); foreach (var o in Info.TargetableOffsets) { diff --git a/OpenRA.Mods.Common/Traits/Husk.cs b/OpenRA.Mods.Common/Traits/Husk.cs index 9f8cca94807c..6794b9f462ab 100644 --- a/OpenRA.Mods.Common/Traits/Husk.cs +++ b/OpenRA.Mods.Common/Traits/Husk.cs @@ -85,13 +85,13 @@ public Husk(ActorInitializer init, HuskInfo info) this.info = info; self = init.Self; - var mapCell = (IMapCell)init.World.Map; + var map = init.World.Map; TopLeft = init.GetValue(); - CenterPosition = init.GetValue(mapCell.CenterOfCell(TopLeft)); + CenterPosition = init.GetValue(map.CenterOfCell(TopLeft)); Facing = init.GetValue(info.GetInitialFacing()); dragSpeed = init.GetValue(0); - finalPosition = mapCell.CenterOfCell(TopLeft); + finalPosition = map.CenterOfCell(TopLeft); effectiveOwner = init.GetValue(info, self.Owner); } @@ -107,12 +107,12 @@ void INotifyCreated.Created(Actor self) public bool CanExistInCell(CPos cell) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; - if (!info.AllowedTerrain.Contains(mapCell.GetTerrainInfo(cell).Type)) + if (!info.AllowedTerrain.Contains(map.GetTerrainInfo(cell).Type)) return false; return true; @@ -138,7 +138,7 @@ public bool CanEnterCell(CPos a, Actor ignoreActor = null, BlockedByActor check return GetAvailableSubCell(a, SubCell.Any, ignoreActor, check) != SubCell.Invalid; } - public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any) { SetPosition(self, ((IMapCell)self.World.Map).CenterOfCell(cell)); } + public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any) { SetPosition(self, self.World.Map.CenterOfCell(cell)); } public void SetCenterPosition(Actor self, WPos pos) { @@ -155,7 +155,7 @@ public void SetPosition(Actor self, WPos pos) { self.World.ActorMap.RemoveInfluence(self, this); CenterPosition = pos; - TopLeft = ((IMapCell)self.World.Map).CellContaining(pos); + TopLeft = self.World.Map.CellContaining(pos); self.World.ActorMap.AddInfluence(self, this); self.World.UpdateMaps(self, this); diff --git a/OpenRA.Mods.Common/Traits/Immobile.cs b/OpenRA.Mods.Common/Traits/Immobile.cs index b2c25fef1de8..f99350ea62fd 100644 --- a/OpenRA.Mods.Common/Traits/Immobile.cs +++ b/OpenRA.Mods.Common/Traits/Immobile.cs @@ -42,7 +42,7 @@ class Immobile : IOccupySpace, ISync, INotifyAddedToWorld, INotifyRemovedFromWor public Immobile(ActorInitializer init, ImmobileInfo info) { location = init.GetValue(); - position = ((IMapCell)init.World.Map).CenterOfCell(location); + position = init.World.Map.CenterOfCell(location); if (info.OccupiesSpace) occupied = new[] { (TopLeft, SubCell.FullCell) }; diff --git a/OpenRA.Mods.Common/Traits/Infantry/ScaredyCat.cs b/OpenRA.Mods.Common/Traits/Infantry/ScaredyCat.cs index 29958fcbf184..0e066deb6ae2 100644 --- a/OpenRA.Mods.Common/Traits/Infantry/ScaredyCat.cs +++ b/OpenRA.Mods.Common/Traits/Infantry/ScaredyCat.cs @@ -60,7 +60,7 @@ public ScaredyCat(Actor self, ScaredyCatInfo info) mobile = self.Trait(); if (info.AvoidTerrainTypes.Count > 0) - avoidTerrainFilter = c => info.AvoidTerrainTypes.Contains(((IMapCell)self.World.Map).GetTerrainInfo(c).Type); + avoidTerrainFilter = c => info.AvoidTerrainTypes.Contains(self.World.Map.GetTerrainInfo(c).Type); } public void Panic() diff --git a/OpenRA.Mods.Common/Traits/Infantry/TerrainModifiesDamage.cs b/OpenRA.Mods.Common/Traits/Infantry/TerrainModifiesDamage.cs index bf9f3c1433aa..31816fe18daa 100644 --- a/OpenRA.Mods.Common/Traits/Infantry/TerrainModifiesDamage.cs +++ b/OpenRA.Mods.Common/Traits/Infantry/TerrainModifiesDamage.cs @@ -46,10 +46,10 @@ int IDamageModifier.GetDamageModifier(Actor attacker, Damage damage) return FullDamage; var world = self.World; - var mapCell = (IMapCell)world.Map; + var map = world.Map; - var pos = mapCell.CellContaining(self.CenterPosition); - var terrainType = mapCell.GetTerrainInfo(pos).Type; + var pos = map.CellContaining(self.CenterPosition); + var terrainType = map.GetTerrainInfo(pos).Type; if (!Info.TerrainModifier.ContainsKey(terrainType)) return FullDamage; diff --git a/OpenRA.Mods.Common/Traits/IsometricSelectable.cs b/OpenRA.Mods.Common/Traits/IsometricSelectable.cs index db39ee00bfbd..7c2ffda9413d 100644 --- a/OpenRA.Mods.Common/Traits/IsometricSelectable.cs +++ b/OpenRA.Mods.Common/Traits/IsometricSelectable.cs @@ -109,11 +109,11 @@ Polygon Bounds(Actor self, WorldRenderer wr, int[] bounds, int height) yMax = Math.Max(yMax, c.Y); } - var mapCell = (IMapCell)self.World.Map; - left = wr.ScreenPxPosition(mapCell.CenterOfCell(new CPos(xMin, yMax)) - new WVec(768, 0, 0)); - right = wr.ScreenPxPosition(mapCell.CenterOfCell(new CPos(xMax, yMin)) + new WVec(768, 0, 0)); - top = wr.ScreenPxPosition(mapCell.CenterOfCell(new CPos(xMin, yMin)) - new WVec(0, 768, 0)); - bottom = wr.ScreenPxPosition(mapCell.CenterOfCell(new CPos(xMax, yMax)) + new WVec(0, 768, 0)); + var map = self.World.Map; + left = wr.ScreenPxPosition(map.CenterOfCell(new CPos(xMin, yMax)) - new WVec(768, 0, 0)); + right = wr.ScreenPxPosition(map.CenterOfCell(new CPos(xMax, yMin)) + new WVec(768, 0, 0)); + top = wr.ScreenPxPosition(map.CenterOfCell(new CPos(xMin, yMin)) - new WVec(0, 768, 0)); + bottom = wr.ScreenPxPosition(map.CenterOfCell(new CPos(xMax, yMax)) + new WVec(0, 768, 0)); } if (height == 0) diff --git a/OpenRA.Mods.Common/Traits/KillsSelf.cs b/OpenRA.Mods.Common/Traits/KillsSelf.cs index f59e000ff6d4..58f24b142798 100644 --- a/OpenRA.Mods.Common/Traits/KillsSelf.cs +++ b/OpenRA.Mods.Common/Traits/KillsSelf.cs @@ -61,7 +61,7 @@ void ITick.Tick(Actor self) if (!self.IsInWorld || self.IsDead || IsTraitDisabled) return; - if (!((IMapCell)self.World.Map).Contains(self.Location)) + if (!self.World.Map.Contains(self.Location)) return; if (lifetime-- <= 0) diff --git a/OpenRA.Mods.Common/Traits/Mobile.cs b/OpenRA.Mods.Common/Traits/Mobile.cs index 6a67cd350aca..d6027732515c 100644 --- a/OpenRA.Mods.Common/Traits/Mobile.cs +++ b/OpenRA.Mods.Common/Traits/Mobile.cs @@ -262,7 +262,7 @@ public Mobile(ActorInitializer init, MobileInfo info) speedModifiers = Exts.Lazy(() => self.TraitsImplementing().ToArray().Select(x => x.GetSpeedModifier())); - ToSubCell = FromSubCell = info.LocomotorInfo.SharesCell ? ((IMapCell)init.World.Map).Grid.DefaultSubCell : SubCell.FullCell; + ToSubCell = FromSubCell = info.LocomotorInfo.SharesCell ? init.World.Map.Grid.DefaultSubCell : SubCell.FullCell; var subCellInit = init.GetOrDefault(); if (subCellInit != null) @@ -275,7 +275,7 @@ public Mobile(ActorInitializer init, MobileInfo info) if (locationInit != null) { fromCell = toCell = locationInit.Value; - SetCenterPosition(self, ((IMapCell)init.World.Map).CenterOfSubCell(FromCell, FromSubCell)); + SetCenterPosition(self, init.World.Map.CenterOfSubCell(FromCell, FromSubCell)); } Facing = oldFacing = init.GetValue(info.InitialFacing); @@ -451,7 +451,7 @@ public SubCell GetValidSubCell(SubCell preferred = SubCell.Any) if (Info.LocomotorInfo.SharesCell) { if (preferred <= SubCell.FullCell) - return ((IMapCell)self.World.Map).Grid.DefaultSubCell; + return self.World.Map.Grid.DefaultSubCell; } else { @@ -468,7 +468,7 @@ public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any) subCell = GetValidSubCell(subCell); SetLocation(cell, subCell, cell, subCell); - var position = cell.Layer == 0 ? ((IMapCell)self.World.Map).CenterOfCell(cell) : + var position = cell.Layer == 0 ? self.World.Map.CenterOfCell(cell) : self.World.GetCustomMovementLayers()[cell.Layer].CenterOfCell(cell); var subcellOffset = self.World.Map.Grid.OffsetOfSubCell(subCell); @@ -479,7 +479,8 @@ public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any) // Sets the location (fromCell, toCell, FromSubCell, ToSubCell) and CenterPosition public void SetPosition(Actor self, WPos pos) { - var cell = self.World.Map.CellContaining(pos); + var map = self.World.Map; + var cell = map.CellContaining(pos); SetLocation(cell, FromSubCell, cell, FromSubCell); SetCenterPosition(self, self.World.Map.CenterOfSubCell(cell, FromSubCell) + new WVec(0, 0, self.World.Map.DistanceAboveTerrain(pos).Length)); FinishedMoving(self); @@ -491,8 +492,8 @@ public void SetCenterPosition(Actor self, WPos pos) CenterPosition = pos; self.World.UpdateMaps(self, this); - var mapCell = (IMapCell)self.World.Map; - SetTerrainRampOrientation(mapCell.TerrainOrientation(mapCell.CellContaining(pos))); + var map = self.World.Map; + SetTerrainRampOrientation(map.TerrainOrientation(map.CellContaining(pos))); // The first time SetCenterPosition is called is in the constructor before creation, so we need a null check here as well if (notifyCenterPositionChanged == null) @@ -659,7 +660,7 @@ public ReturnToCellActivity(Actor self, int delay = 0, bool recalculateSubCell = protected override void OnFirstRun(Actor self) { pos = self.CenterPosition; - if (((IMapCell)self.World.Map).DistanceAboveTerrain(pos) > WDist.Zero && self.TraitOrDefault() != null) + if (self.World.Map.DistanceAboveTerrain(pos) > WDist.Zero && self.TraitOrDefault() != null) QueueChild(new Parachute(self)); } @@ -668,14 +669,14 @@ public override bool Tick(Actor self) pos = self.CenterPosition; cell = mobile.ToCell; subCell = mobile.ToSubCell; - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (recalculateSubCell) subCell = mobile.Info.LocomotorInfo.SharesCell ? self.World.ActorMap.FreeSubCell(cell, subCell, a => a != self) : SubCell.FullCell; // TODO: solve/reduce cell is full problem if (subCell == SubCell.Invalid) - subCell = mapCell.Grid.DefaultSubCell; + subCell = map.Grid.DefaultSubCell; // Reserve the exit cell mobile.SetPosition(self, cell, subCell); @@ -684,7 +685,7 @@ public override bool Tick(Actor self) if (delay > 0) QueueChild(new Wait(delay)); - QueueChild(mobile.LocalMove(self, pos, mapCell.CenterOfSubCell(cell, subCell))); + QueueChild(mobile.LocalMove(self, pos, map.CenterOfSubCell(cell, subCell))); return true; } } @@ -730,7 +731,7 @@ public bool CanEnterTargetNow(Actor self, in Target target) if (target.Type == TargetType.FrozenActor && !target.FrozenActor.IsValid) return false; - return self.Location == ((IMapCell)self.World.Map).CellContaining(target.CenterPosition) || Util.AdjacentCells(self.World, target).Any(c => c == self.Location); + return self.Location == self.World.Map.CellContaining(target.CenterPosition) || Util.AdjacentCells(self.World, target).Any(c => c == self.Location); } #endregion @@ -761,7 +762,7 @@ public CPos NearestMoveableCell(CPos target, int minRange, int maxRange) if (CanEnterCell(target, check: BlockedByActor.Immovable) && CanStayInCell(target)) return target; - foreach (var tile in ((IMapCell)self.World.Map).FindTilesInAnnulus(target, minRange, maxRange)) + foreach (var tile in self.World.Map.FindTilesInAnnulus(target, minRange, maxRange)) if (CanEnterCell(tile, check: BlockedByActor.Immovable) && CanStayInCell(tile)) return tile; @@ -774,7 +775,7 @@ public CPos NearestCell(CPos target, Func check, int minRange, int m if (check(target)) return target; - foreach (var tile in ((IMapCell)self.World.Map).FindTilesInAnnulus(target, minRange, maxRange)) + foreach (var tile in self.World.Map.FindTilesInAnnulus(target, minRange, maxRange)) if (check(tile)) return tile; @@ -921,7 +922,7 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) if (order.OrderString == "Move") { - var cell = ((IMapCell)self.World.Map).Clamp(((IMapCell)this.self.World.Map).CellContaining(order.Target.CenterPosition)); + var cell = self.World.Map.Clamp(self.World.Map.CellContaining(order.Target.CenterPosition)); if (!Info.LocomotorInfo.MoveIntoShroud && !self.Owner.Shroud.IsExplored(cell)) return; @@ -946,7 +947,7 @@ string IOrderVoice.VoicePhraseForOrder(Actor self, Order order) case "Move": if (!Info.LocomotorInfo.MoveIntoShroud && order.Target.Type != TargetType.Invalid) { - var cell = ((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition); + var cell = self.World.Map.CellContaining(order.Target.CenterPosition); if (!self.Owner.Shroud.IsExplored(cell)) return null; } @@ -992,22 +993,22 @@ public MoveOrderTargeter(Actor self, Mobile unit) public bool CanTarget(Actor self, in Target target, ref TargetModifiers modifiers, ref string cursor) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (rejectMove || target.Type != TargetType.Terrain || (mobile.requireForceMove && !modifiers.HasModifier(TargetModifiers.ForceMove))) return false; - var location = mapCell.CellContaining(target.CenterPosition); + var location = map.CellContaining(target.CenterPosition); IsQueued = modifiers.HasModifier(TargetModifiers.ForceQueue); var explored = self.Owner.Shroud.IsExplored(location); if (mobile.IsTraitPaused - || !mapCell.Contains(location) + || !map.Contains(location) || (!explored && !locomotorInfo.MoveIntoShroud) || (explored && mobile.Locomotor.MovementCostForCell(location) == PathGraph.MovementCostForUnreachableCell)) cursor = mobile.Info.BlockedCursor; - else if (!explored || !mobile.Info.TerrainCursors.TryGetValue(mapCell.GetTerrainInfo(location).Type, out cursor)) + else if (!explored || !mobile.Info.TerrainCursors.TryGetValue(map.GetTerrainInfo(location).Type, out cursor)) cursor = mobile.Info.Cursor; return true; diff --git a/OpenRA.Mods.Common/Traits/Modifiers/FrozenUnderFog.cs b/OpenRA.Mods.Common/Traits/Modifiers/FrozenUnderFog.cs index c2fcf133ebf9..ac3eb47b587e 100644 --- a/OpenRA.Mods.Common/Traits/Modifiers/FrozenUnderFog.cs +++ b/OpenRA.Mods.Common/Traits/Modifiers/FrozenUnderFog.cs @@ -53,7 +53,7 @@ public FrozenUnderFog(ActorInitializer init, FrozenUnderFogInfo info) { this.info = info; - var mapCell = (IMapCell)init.World.Map; + var map = init.World.Map; // Explore map-placed actors if the "Explore Map" option is enabled var shroudInfo = init.World.Map.Rules.Actors[SystemActors.Player].TraitInfo(); @@ -61,7 +61,7 @@ public FrozenUnderFog(ActorInitializer init, FrozenUnderFogInfo info) startsRevealed = exploredMap && init.Contains() && !init.Contains(); var buildingInfo = init.Self.Info.TraitInfoOrDefault(); var footprintCells = buildingInfo?.FrozenUnderFogTiles(init.Self.Location).ToList() ?? new List() { init.Self.Location }; - footprint = footprintCells.SelectMany(c => mapCell.ProjectedCellsCovering(c.ToMPos(mapCell))).ToArray(); + footprint = footprintCells.SelectMany(c => map.ProjectedCellsCovering(c.ToMPos(map))).ToArray(); } void INotifyCreated.Created(Actor self) diff --git a/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderFog.cs b/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderFog.cs index 51788c8288bd..b14b729b0dea 100644 --- a/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderFog.cs +++ b/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderFog.cs @@ -33,7 +33,7 @@ protected override bool IsVisibleInner(Actor self, Player byPlayer) var pos = self.CenterPosition; if (Info.Type == VisibilityType.GroundPosition) - pos -= new WVec(WDist.Zero, WDist.Zero, ((IMapCell)self.World.Map).DistanceAboveTerrain(pos)); + pos -= new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(pos)); return byPlayer.Shroud.IsVisible(pos); } diff --git a/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderShroud.cs b/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderShroud.cs index 9e3393485819..79f94d429d6f 100644 --- a/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderShroud.cs +++ b/OpenRA.Mods.Common/Traits/Modifiers/HiddenUnderShroud.cs @@ -45,7 +45,7 @@ protected virtual bool IsVisibleInner(Actor self, Player byPlayer) var pos = self.CenterPosition; if (Info.Type == VisibilityType.GroundPosition) - pos -= new WVec(WDist.Zero, WDist.Zero, ((IMapCell)self.World.Map).DistanceAboveTerrain(pos)); + pos -= new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(pos)); return byPlayer.Shroud.IsExplored(pos); } diff --git a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromFile.cs b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromFile.cs index 519a8fa3cb81..6958a3af584c 100644 --- a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromFile.cs +++ b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromFile.cs @@ -69,7 +69,7 @@ public PaletteFromFile(World world, PaletteFromFileInfo info) public void LoadPalettes(WorldRenderer wr) { // TO DO: Make this use IMap instead of Map - if (info.Tileset == null || string.Equals(info.Tileset, ((IMapCell)world.Map).Tileset, StringComparison.InvariantCultureIgnoreCase)) + if (info.Tileset == null || string.Equals(info.Tileset, world.Map.Tileset, StringComparison.InvariantCultureIgnoreCase)) wr.AddPalette(info.Name, ((IProvidesCursorPaletteInfo)info).ReadPalette((Map)world.Map), info.AllowModifiers); } diff --git a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromGrayscale.cs b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromGrayscale.cs index ca7b0e3f070c..d33402aeafc3 100644 --- a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromGrayscale.cs +++ b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromGrayscale.cs @@ -52,7 +52,7 @@ public PaletteFromGrayscale(World world, PaletteFromGrayscaleInfo info) public void LoadPalettes(WorldRenderer wr) { // Enable palette only for a specific tileset - if (info.Tileset != null && !string.Equals(info.Tileset, ((IMapCell)world.Map).Tileset, StringComparison.InvariantCultureIgnoreCase)) + if (info.Tileset != null && !string.Equals(info.Tileset, world.Map.Tileset, StringComparison.InvariantCultureIgnoreCase)) return; wr.AddPalette(info.Name, new ImmutablePalette(Enumerable.Range(0, Palette.Size).Select(i => (i == info.TransparentIndex) ? 0 : (uint)Color.FromArgb(255, i, i, i).ToArgb())), info.AllowModifiers); diff --git a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromPng.cs b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromPng.cs index d4d2e9401422..390646002bc8 100644 --- a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromPng.cs +++ b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromPng.cs @@ -76,7 +76,7 @@ public PaletteFromPng(World world, PaletteFromPngInfo info) public void LoadPalettes(WorldRenderer wr) { - if (info.Tileset != null && !string.Equals(info.Tileset, ((IMapCell)world.Map).Tileset, StringComparison.InvariantCultureIgnoreCase)) + if (info.Tileset != null && !string.Equals(info.Tileset, world.Map.Tileset, StringComparison.InvariantCultureIgnoreCase)) return; // TO DO: Make this use IMap instead of Map diff --git a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromRGBA.cs b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromRGBA.cs index db320dc9db13..9951a948c3c9 100644 --- a/OpenRA.Mods.Common/Traits/Palettes/PaletteFromRGBA.cs +++ b/OpenRA.Mods.Common/Traits/Palettes/PaletteFromRGBA.cs @@ -64,7 +64,7 @@ public PaletteFromRGBA(World world, PaletteFromRGBAInfo info) public void LoadPalettes(WorldRenderer wr) { // Enable palette only for a specific tileset - if (info.Tileset != null && !string.Equals(info.Tileset, ((IMapCell)world.Map).Tileset, StringComparison.InvariantCultureIgnoreCase)) + if (info.Tileset != null && !string.Equals(info.Tileset, world.Map.Tileset, StringComparison.InvariantCultureIgnoreCase)) return; var a = info.A / 255f; diff --git a/OpenRA.Mods.Common/Traits/ParaDrop.cs b/OpenRA.Mods.Common/Traits/ParaDrop.cs index 01fc06c0de6b..6155c8efdda6 100644 --- a/OpenRA.Mods.Common/Traits/ParaDrop.cs +++ b/OpenRA.Mods.Common/Traits/ParaDrop.cs @@ -81,7 +81,7 @@ void ITick.Tick(Actor self) OnExitedDropRange(self); // Are we able to drop the next trooper? - if (!inDropRange || cargo.IsEmpty() || !((IMapCell)self.World.Map).Contains(self.Location)) + if (!inDropRange || cargo.IsEmpty() || !self.World.Map.Contains(self.Location)) return; var dropActor = cargo.Peek(); diff --git a/OpenRA.Mods.Common/Traits/Parachutable.cs b/OpenRA.Mods.Common/Traits/Parachutable.cs index 85f13954a816..d73b794aca97 100644 --- a/OpenRA.Mods.Common/Traits/Parachutable.cs +++ b/OpenRA.Mods.Common/Traits/Parachutable.cs @@ -87,7 +87,7 @@ void INotifyParachute.OnParachute(Actor self) void INotifyParachute.OnLanded(Actor self) { IsInAir = false; - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (parachutingToken != Actor.InvalidConditionToken) parachutingToken = self.RevokeCondition(parachutingToken); @@ -100,10 +100,10 @@ void INotifyParachute.OnLanded(Actor self) return; if (IgnoreActor != null && !self.World.ActorMap.GetActorsAt(cell) - .Any(a => a != IgnoreActor && a != self && mapCell.DistanceAboveTerrain(a.CenterPosition) == WDist.Zero)) + .Any(a => a != IgnoreActor && a != self && map.DistanceAboveTerrain(a.CenterPosition) == WDist.Zero)) return; - var onWater = info.WaterTerrainTypes.Contains(mapCell.GetTerrainInfo(cell).Type); + var onWater = info.WaterTerrainTypes.Contains(map.GetTerrainInfo(cell).Type); var sound = onWater ? info.WaterImpactSound : info.GroundImpactSound; Game.Sound.Play(SoundType.World, sound, self.CenterPosition); diff --git a/OpenRA.Mods.Common/Traits/Player/PlaceBuilding.cs b/OpenRA.Mods.Common/Traits/Player/PlaceBuilding.cs index 63a7969cfa2b..ac42ffb814da 100644 --- a/OpenRA.Mods.Common/Traits/Player/PlaceBuilding.cs +++ b/OpenRA.Mods.Common/Traits/Player/PlaceBuilding.cs @@ -68,7 +68,7 @@ void IResolveOrder.ResolveOrder(Actor self, Order order) { var prevItems = GetNumBuildables(self.Owner); var targetActor = w.GetActorById(order.ExtraData); - var targetLocation = ((IMapCell)w.Map).CellContaining(order.Target.CenterPosition); + var targetLocation = w.Map.CellContaining(order.Target.CenterPosition); if (targetActor == null || targetActor.IsDead) return; diff --git a/OpenRA.Mods.Common/Traits/Player/PlayerRadarTerrain.cs b/OpenRA.Mods.Common/Traits/Player/PlayerRadarTerrain.cs index 3961789024ad..97b836246ce2 100644 --- a/OpenRA.Mods.Common/Traits/Player/PlayerRadarTerrain.cs +++ b/OpenRA.Mods.Common/Traits/Player/PlayerRadarTerrain.cs @@ -45,7 +45,7 @@ public PlayerRadarTerrain(Actor self) void UpdateShroudCell(PPos puv) { - var uvs = ((IMapCell)world.Map).Unproject(puv); + var uvs = world.Map.Unproject(puv); foreach (var uv in uvs) UpdateTerrainCell(uv); } @@ -66,20 +66,19 @@ void UpdateTerrainCellColor(MPos uv) public void WorldLoaded(World w, WorldRenderer wr) { radarTerrainLayers = w.WorldActor.TraitsImplementing().ToArray(); - terrainColor = new CellLayer<(int, int)>((IMapCell)w.Map); + terrainColor = new CellLayer<(int, int)>(w.Map); w.AddFrameEndTask(_ => { - var mapCell = (IMapCell)world.Map; + var map = world.Map; // Set initial terrain data - foreach (var uv in mapCell.AllCells.MapCoords) + foreach (var uv in map.AllCells.MapCoords) UpdateTerrainCellColor(uv); - var worldMapCell = (IMapCell)world.Map; - mapCell.Tiles.CellEntryChanged += cell => UpdateTerrainCell(cell.ToMPos(worldMapCell)); + ((IMapTiles)map).Tiles.CellEntryChanged += cell => UpdateTerrainCell(cell.ToMPos(map)); foreach (var rtl in radarTerrainLayers) - rtl.CellEntryChanged += cell => UpdateTerrainCell(cell.ToMPos(worldMapCell)); + rtl.CellEntryChanged += cell => UpdateTerrainCell(cell.ToMPos(map)); IsInitialized = true; }); @@ -93,7 +92,7 @@ public static (int Left, int Right) GetColor(IMap map, IRadarTerrainLayer[] rada if (rtl.TryGetTerrainColorPair(uv, out var c)) return (c.Left.ToArgb(), c.Right.ToArgb()); - var tc = ((IMapCell)map).GetTerrainColorPair(uv); + var tc = map.GetTerrainColorPair(uv); return (tc.Left.ToArgb(), tc.Right.ToArgb()); } } diff --git a/OpenRA.Mods.Common/Traits/Production.cs b/OpenRA.Mods.Common/Traits/Production.cs index e2b929c76f0a..0f3ada004c2f 100644 --- a/OpenRA.Mods.Common/Traits/Production.cs +++ b/OpenRA.Mods.Common/Traits/Production.cs @@ -59,7 +59,7 @@ public virtual void DoProduction(Actor self, ActorInfo producee, ExitInfo exitin { exit = self.Location + exitinfo.ExitCell; var spawn = self.CenterPosition + exitinfo.SpawnOffset; - var to = ((IMapCell)self.World.Map).CenterOfCell(exit); + var to = self.World.Map.CenterOfCell(exit); WAngle initialFacing; if (!exitinfo.Facing.HasValue) @@ -109,7 +109,7 @@ protected virtual Exit SelectExit(Actor self, ActorInfo producee, string product if (rp == null || rp.Path.Count == 0) return self.RandomExitOrDefault(self.World, productionType, p); - return self.NearestExitOrDefault(((IMapCell)self.World.Map).CenterOfCell(rp.Path[0]), productionType, p); + return self.NearestExitOrDefault(self.World.Map.CenterOfCell(rp.Path[0]), productionType, p); } protected Exit SelectExit(Actor self, ActorInfo producee, string productionType) diff --git a/OpenRA.Mods.Common/Traits/ProductionFromMapEdge.cs b/OpenRA.Mods.Common/Traits/ProductionFromMapEdge.cs index 68c1680cff1e..d2efc19e7efa 100644 --- a/OpenRA.Mods.Common/Traits/ProductionFromMapEdge.cs +++ b/OpenRA.Mods.Common/Traits/ProductionFromMapEdge.cs @@ -55,17 +55,17 @@ public override bool Produce(Actor self, ActorInfo producee, string productionTy var destinations = rp != null && rp.Path.Count > 0 ? rp.Path : new List { self.Location }; - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; var location = spawnLocation; if (!location.HasValue) { if (aircraftInfo != null) - location = mapCell.ChooseClosestEdgeCell(self.Location); + location = map.ChooseClosestEdgeCell(self.Location); if (mobileInfo != null) { var locomotor = self.World.WorldActor.TraitsImplementing().First(l => l.Info.Name == mobileInfo.Locomotor); - location = mapCell.ChooseClosestMatchingEdgeCell(self.Location, + location = map.ChooseClosestMatchingEdgeCell(self.Location, c => mobileInfo.CanEnterCell(self.World, null, c) && pathFinder.PathExistsForLocomotor(locomotor, c, destinations[0])); } } @@ -74,13 +74,13 @@ public override bool Produce(Actor self, ActorInfo producee, string productionTy if (!location.HasValue) return false; - var pos = mapCell.CenterOfCell(location.Value); + var pos = map.CenterOfCell(location.Value); // If aircraft, spawn at cruise altitude if (aircraftInfo != null) pos += new WVec(0, 0, aircraftInfo.CruiseAltitude.Length); - var initialFacing = mapCell.FacingBetween(location.Value, destinations[0], WAngle.Zero); + var initialFacing = map.FacingBetween(location.Value, destinations[0], WAngle.Zero); self.World.AddFrameEndTask(w => { diff --git a/OpenRA.Mods.Common/Traits/ProductionParadrop.cs b/OpenRA.Mods.Common/Traits/ProductionParadrop.cs index e38b9c97b7ec..0ff18b858b0b 100644 --- a/OpenRA.Mods.Common/Traits/ProductionParadrop.cs +++ b/OpenRA.Mods.Common/Traits/ProductionParadrop.cs @@ -80,7 +80,7 @@ public override bool Produce(Actor self, ActorInfo producee, string productionTy var altitude = self.World.Map.Rules.Actors[actorType].TraitInfo().CruiseAltitude; var actor = w.CreateActor(actorType, new TypeDictionary { - new CenterPositionInit(((IMapCell)w.Map).CenterOfCell(startPos) + new WVec(WDist.Zero, WDist.Zero, altitude)), + new CenterPositionInit(w.Map.CenterOfCell(startPos) + new WVec(WDist.Zero, WDist.Zero, altitude)), new OwnerInit(owner), new FacingInit(new WAngle(256)), }); @@ -131,9 +131,9 @@ public override void DoProduction(Actor self, ActorInfo producee, ExitInfo exiti if (exitinfo != null) exit += exitinfo.ExitCell; - var mapCell = (IMapCell)self.World.Map; - var spawn = mapCell.CenterOfCell(exit) + new WVec(WDist.Zero, WDist.Zero, altitude); - var to = mapCell.CenterOfCell(exit); + var map = self.World.Map; + var spawn = map.CenterOfCell(exit) + new WVec(WDist.Zero, WDist.Zero, altitude); + var to = map.CenterOfCell(exit); var initialFacing = (exitinfo != null && exitinfo.Facing.HasValue) ? exitinfo.Facing.Value : (to - spawn).Yaw; diff --git a/OpenRA.Mods.Common/Traits/Render/CustomTerrainDebugOverlay.cs b/OpenRA.Mods.Common/Traits/Render/CustomTerrainDebugOverlay.cs index 6bf153e46969..a662b1446695 100644 --- a/OpenRA.Mods.Common/Traits/Render/CustomTerrainDebugOverlay.cs +++ b/OpenRA.Mods.Common/Traits/Render/CustomTerrainDebugOverlay.cs @@ -70,14 +70,14 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR if (self.World.ShroudObscures(uv)) continue; - var mapCell = (IMapCell)wr.World.Map; - var cell = uv.ToCPos(mapCell); - var center = mapCell.CenterOfCell(cell); - var terrainType = ((IMapCell)self.World.Map).CustomTerrain[cell]; + var map = wr.World.Map; + var cell = uv.ToCPos(map); + var center = map.CenterOfCell(cell); + var terrainType = self.World.Map.CustomTerrain[cell]; if (terrainType == byte.MaxValue) continue; - var info = mapCell.GetTerrainInfo(cell); + var info = map.GetTerrainInfo(cell); yield return new TextAnnotationRenderable(font, center, 0, info.Color, info.Type); } } diff --git a/OpenRA.Mods.Common/Traits/Render/Hovers.cs b/OpenRA.Mods.Common/Traits/Render/Hovers.cs index d3016ea434b9..3bffd3691334 100644 --- a/OpenRA.Mods.Common/Traits/Render/Hovers.cs +++ b/OpenRA.Mods.Common/Traits/Render/Hovers.cs @@ -99,7 +99,7 @@ IEnumerable IRenderModifier.ModifyRender(Actor self, WorldRenderer { if (!IsTraitDisabled) { - var visualOffset = ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition) >= info.MinHoveringAltitude + var visualOffset = self.World.Map.DistanceAboveTerrain(self.CenterPosition) >= info.MinHoveringAltitude ? new WAngle(ticks % (info.Ticks * 4) * stepPercentage).Sin() : 0; var currentHeight = info.BobDistance.Length * visualOffset / 1024 + info.InitialHeight.Length; diff --git a/OpenRA.Mods.Common/Traits/Render/LeavesTrails.cs b/OpenRA.Mods.Common/Traits/Render/LeavesTrails.cs index ace2358a74df..2f754129985d 100644 --- a/OpenRA.Mods.Common/Traits/Render/LeavesTrails.cs +++ b/OpenRA.Mods.Common/Traits/Render/LeavesTrails.cs @@ -115,12 +115,12 @@ void ITick.Tick(Actor self) if (++ticks >= cachedInterval) { - var mapCell = (IMapCell)self.World.Map; - var spawnCell = Info.SpawnAtLastPosition ? mapCell.CellContaining(cachedPosition) : mapCell.CellContaining(self.CenterPosition); - if (!mapCell.Contains(spawnCell)) + var map = self.World.Map; + var spawnCell = Info.SpawnAtLastPosition ? map.CellContaining(cachedPosition) : map.CellContaining(self.CenterPosition); + if (!map.Contains(spawnCell)) return; - var type = mapCell.GetTerrainInfo(spawnCell).Type; + var type = map.GetTerrainInfo(spawnCell).Type; if (++offset >= Info.Offsets.Length) offset = 0; @@ -135,7 +135,7 @@ void ITick.Tick(Actor self) var offsetRotation = Info.Offsets[offset].Rotate(body.QuantizeOrientation(self.Orientation)); var spawnPosition = Info.SpawnAtLastPosition ? cachedPosition : self.CenterPosition; var pos = Info.Type == TrailType.CenterPosition ? spawnPosition + body.LocalToWorld(offsetRotation) : - mapCell.CenterOfCell(spawnCell); + map.CenterOfCell(spawnCell); self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, spawnFacing, self.World, Info.Image, Info.Sequences.Random(Game.CosmeticRandom), Info.Palette, Info.VisibleThroughFog))); diff --git a/OpenRA.Mods.Common/Traits/Render/WithAircraftLandingEffect.cs b/OpenRA.Mods.Common/Traits/Render/WithAircraftLandingEffect.cs index a5367404d58b..40134be23a88 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithAircraftLandingEffect.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithAircraftLandingEffect.cs @@ -49,7 +49,7 @@ public WithAircraftLandingEffect(WithAircraftLandingEffectInfo info) void AddEffect(Actor self) { - var position = self.CenterPosition - new WVec(WDist.Zero, WDist.Zero, ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition)); + var position = self.CenterPosition - new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(self.CenterPosition)); self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(position, self.World, Info.Image, Info.Sequences.Random(Game.CosmeticRandom), Info.Palette, Info.VisibleThroughFog))); } @@ -59,8 +59,7 @@ bool ShouldAddEffect(IMap map, CPos cell) if (Info.TerrainTypes.Count == 0) return true; - var mapCell = (IMapCell)map; - return mapCell.Contains(cell) && Info.TerrainTypes.Contains(mapCell.GetTerrainInfo(cell).Type); + return map.Contains(cell) && Info.TerrainTypes.Contains(map.GetTerrainInfo(cell).Type); } void INotifyLanding.Landing(Actor self) @@ -73,7 +72,7 @@ void ITick.Tick(Actor self) if (!shouldAddEffect) return; - if (((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition) > Info.DistanceAboveTerrain) + if (self.World.Map.DistanceAboveTerrain(self.CenterPosition) > Info.DistanceAboveTerrain) return; AddEffect(self); diff --git a/OpenRA.Mods.Common/Traits/Render/WithCrateBody.cs b/OpenRA.Mods.Common/Traits/Render/WithCrateBody.cs index d78753d84540..c67d0defb2fb 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithCrateBody.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithCrateBody.cs @@ -87,7 +87,7 @@ void INotifyParachute.OnLanded(Actor self) void PlaySequence() { - var onWater = info.WaterTerrainTypes.Contains(((IMapCell)self.World.Map).GetTerrainInfo(self.Location).Type); + var onWater = info.WaterTerrainTypes.Contains(self.World.Map.GetTerrainInfo(self.Location).Type); var sequence = onWater ? info.WaterSequence : info.LandSequence; if (!string.IsNullOrEmpty(sequence)) anim.PlayRepeating(sequence); diff --git a/OpenRA.Mods.Common/Traits/Render/WithGateSpriteBody.cs b/OpenRA.Mods.Common/Traits/Render/WithGateSpriteBody.cs index 772bf2b8b1fd..a07de89d4d4c 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithGateSpriteBody.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithGateSpriteBody.cs @@ -105,7 +105,7 @@ void UpdateNeighbours(Actor self) { var footprint = gate.Footprint.ToArray(); var adjacent = Util.ExpandFootprint(footprint, true).Except(footprint) - .Where(((IMapCell)self.World.Map).Contains).ToList(); + .Where(self.World.Map.Contains).ToList(); var adjacentActorTraits = adjacent.SelectMany(self.World.ActorMap.GetActorsAt) .SelectMany(a => a.TraitsImplementing()); diff --git a/OpenRA.Mods.Common/Traits/Render/WithParachute.cs b/OpenRA.Mods.Common/Traits/Render/WithParachute.cs index 2a42ee25c58d..8ebe88b23c2b 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithParachute.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithParachute.cs @@ -177,7 +177,7 @@ IEnumerable IRender.Render(Actor self, WorldRenderer wr) if (self.World.FogObscures(self)) return Enumerable.Empty(); - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(self.CenterPosition); var pos = self.CenterPosition - new WVec(0, 0, dat.Length); var palette = wr.Palette(info.Palette); var alpha = shadow.CurrentSequence.GetAlpha(shadow.CurrentFrame); @@ -196,7 +196,7 @@ IEnumerable IRender.ScreenBounds(Actor self, WorldRenderer wr) if (self.World.FogObscures(self)) return Enumerable.Empty(); - var dat = ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition); + var dat = self.World.Map.DistanceAboveTerrain(self.CenterPosition); var pos = self.CenterPosition - new WVec(0, 0, dat.Length); return new Rectangle[] { shadow.ScreenBounds(wr, pos, info.ShadowOffset) }; } diff --git a/OpenRA.Mods.Common/Traits/Render/WithShadow.cs b/OpenRA.Mods.Common/Traits/Render/WithShadow.cs index 93ddba798688..994d76577b8d 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithShadow.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithShadow.cs @@ -51,7 +51,7 @@ IEnumerable IRenderModifier.ModifyRender(Actor self, WorldRenderer if (IsTraitDisabled) return r; - var height = ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition).Length; + var height = self.World.Map.DistanceAboveTerrain(self.CenterPosition).Length; var shadowSprites = r.Where(s => !s.IsDecoration && s is IModifyableRenderable) .Select(ma => ((IModifyableRenderable)ma).WithTint(shadowColor, ((IModifyableRenderable)ma).TintModifiers | TintModifiers.ReplaceColor) .WithAlpha(shadowAlpha) @@ -70,7 +70,7 @@ IEnumerable IRenderModifier.ModifyScreenBounds(Actor self, WorldRende if (IsTraitDisabled) yield break; - var height = ((IMapCell)self.World.Map).DistanceAboveTerrain(self.CenterPosition).Length; + var height = self.World.Map.DistanceAboveTerrain(self.CenterPosition).Length; var offset = wr.ScreenPxOffset(info.Offset - new WVec(0, 0, height)); foreach (var r in bounds) yield return new Rectangle(r.X + offset.X, r.Y + offset.Y, r.Width, r.Height); diff --git a/OpenRA.Mods.Common/Traits/Render/WithSpriteBody.cs b/OpenRA.Mods.Common/Traits/Render/WithSpriteBody.cs index 41f626b0e7f4..f2ca8c15de89 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithSpriteBody.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithSpriteBody.cs @@ -80,7 +80,7 @@ protected WithSpriteBody(ActorInitializer init, WithSpriteBodyInfo info, Func subtractDAT = null; if (info.ForceToGround) - subtractDAT = () => new WVec(0, 0, -((IMapCell)init.Self.World.Map).DistanceAboveTerrain(init.Self.CenterPosition).Length); + subtractDAT = () => new WVec(0, 0, -init.Self.World.Map.DistanceAboveTerrain(init.Self.CenterPosition).Length); DefaultAnimation = new Animation(init.World, rs.GetImage(init.Self), baseFacing, paused); rs.Add(new AnimationWithOffset(DefaultAnimation, subtractDAT, () => IsTraitDisabled), info.Palette, info.IsPlayerPalette); diff --git a/OpenRA.Mods.Common/Traits/RevealsMap.cs b/OpenRA.Mods.Common/Traits/RevealsMap.cs index b1abf8078fb5..4fb5fcbca316 100644 --- a/OpenRA.Mods.Common/Traits/RevealsMap.cs +++ b/OpenRA.Mods.Common/Traits/RevealsMap.cs @@ -48,7 +48,7 @@ protected void AddCellsToPlayerShroud(Actor self, Player p, PPos[] uv) protected PPos[] ProjectedCells(Actor self) { - return ((IMapCell)self.World.Map).ProjectedCells; + return self.World.Map.ProjectedCells; } void INotifyOwnerChanged.OnOwnerChanged(Actor self, Player oldOwner, Player newOwner) diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/AirstrikePower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/AirstrikePower.cs index 0da1ad943bf8..707ff7fdb0f1 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/AirstrikePower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/AirstrikePower.cs @@ -79,7 +79,7 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag public Actor[] SendAirstrike(Actor self, WPos target, WAngle? facing = null) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; var aircraft = new List(); if (!facing.HasValue) @@ -89,8 +89,8 @@ public Actor[] SendAirstrike(Actor self, WPos target, WAngle? facing = null) var attackRotation = WRot.FromYaw(facing.Value); var delta = new WVec(0, -1024, 0).Rotate(attackRotation); target = target + new WVec(0, 0, altitude); - var startEdge = target - (mapCell.DistanceToEdge(target, -delta) + info.Cordon).Length * delta / 1024; - var finishEdge = target + (mapCell.DistanceToEdge(target, delta) + info.Cordon).Length * delta / 1024; + var startEdge = target - (map.DistanceToEdge(target, -delta) + info.Cordon).Length * delta / 1024; + var finishEdge = target + (map.DistanceToEdge(target, delta) + info.Cordon).Length * delta / 1024; Actor camera = null; Beacon beacon = null; @@ -105,7 +105,7 @@ public Actor[] SendAirstrike(Actor self, WPos target, WAngle? facing = null) { camera = w.CreateActor(info.CameraActor, new TypeDictionary { - new LocationInit(((IMapCell)self.World.Map).CellContaining(target)), + new LocationInit(self.World.Map.CellContaining(target)), new OwnerInit(self.Owner), }); }); diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/GrantExternalConditionPower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/GrantExternalConditionPower.cs index fcdc41ed538f..a7eb3505be0b 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/GrantExternalConditionPower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/GrantExternalConditionPower.cs @@ -87,7 +87,7 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag Game.Sound.Play(SoundType.World, info.OnFireSound, order.Target.CenterPosition); - foreach (var a in UnitsInRange(((IMapCell)self.World.Map).CellContaining(order.Target.CenterPosition))) + foreach (var a in UnitsInRange(self.World.Map.CellContaining(order.Target.CenterPosition))) a.TraitsImplementing() .FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(self)) ?.GrantCondition(a, self, info.Duration); @@ -171,7 +171,7 @@ protected override IEnumerable Render(WorldRenderer wr, World world var pal = wr.Palette(TileSet.TerrainPaletteInternalName); foreach (var t in power.CellsMatching(xy, footprint, dimensions)) - yield return new SpriteRenderable(tile, ((IMapCell)wr.World.Map).CenterOfCell(t), WVec.Zero, -511, pal, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); + yield return new SpriteRenderable(tile, wr.World.Map.CenterOfCell(t), WVec.Zero, -511, pal, 1f, alpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); } protected override string GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi) diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs index 1d0a6f14c93b..1be3fab5d69e 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs @@ -232,7 +232,7 @@ protected override IEnumerable RenderAnnotations(WorldRenderer wr, if (info.CircleRanges == null) yield break; - var centerPosition = ((IMapCell)wr.World.Map).CenterOfCell(wr.Viewport.ViewToWorld(Viewport.LastMousePos)); + var centerPosition = wr.World.Map.CenterOfCell(wr.Viewport.ViewToWorld(Viewport.LastMousePos)); foreach (var range in info.CircleRanges) yield return new RangeCircleAnnotationRenderable( centerPosition, diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs index e1e12e00911a..15a326052497 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs @@ -113,9 +113,9 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag var delta = new WVec(0, -1024, 0).Rotate(dropRotation); target += new WVec(0, 0, altitude); - var mapCell = (IMapCell)self.World.Map; - var startEdge = target - (mapCell.DistanceToEdge(target, -delta) + info.Cordon).Length * delta / 1024; - var finishEdge = target + (mapCell.DistanceToEdge(target, delta) + info.Cordon).Length * delta / 1024; + var map = self.World.Map; + var startEdge = target - (map.DistanceToEdge(target, -delta) + info.Cordon).Length * delta / 1024; + var finishEdge = target + (map.DistanceToEdge(target, delta) + info.Cordon).Length * delta / 1024; Actor camera = null; Beacon beacon = null; @@ -130,7 +130,7 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag { camera = w.CreateActor(info.CameraActor, new TypeDictionary { - new LocationInit(mapCell.CellContaining(target)), + new LocationInit(map.CellContaining(target)), new OwnerInit(self.Owner), }); }); @@ -222,7 +222,7 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag w.Add(a); var drop = a.Trait(); - drop.SetLZ(((IMapCell)w.Map).CellContaining(target + targetOffset), !info.AllowImpassableCells); + drop.SetLZ(w.Map.CellContaining(target + targetOffset), !info.AllowImpassableCells); drop.OnEnteredDropRange += onEnterRange; drop.OnExitedDropRange += onExitRange; drop.OnRemovedFromWorld += onRemovedFromWorld; diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/SelectDirectionalTarget.cs b/OpenRA.Mods.Common/Traits/SupportPowers/SelectDirectionalTarget.cs index e3514e6293c1..f3c7ad89f4d4 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/SelectDirectionalTarget.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/SelectDirectionalTarget.cs @@ -64,7 +64,7 @@ IEnumerable IOrderGenerator.Order(World world, CPos cell, int2 worldPixel if (mi.Button == MouseButton.Left && mi.Event == MouseInputEvent.Down) { - if (!activated && ((IMapCell)world.Map).Contains(cell)) + if (!activated && world.Map.Contains(cell)) { targetCell = cell; targetLocation = mi.Location; @@ -122,7 +122,7 @@ void IOrderGenerator.Tick(World world) string IOrderGenerator.GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi) { - return ((IMapCell)world.Map).Contains(cell) ? cursor : "generic-blocked"; + return world.Map.Contains(cell) ? cursor : "generic-blocked"; } bool IOrderGenerator.HandleKeyPress(KeyInput e) { return false; } diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/SpawnActorPower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/SpawnActorPower.cs index d20723e2f890..11f22d59cad2 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/SpawnActorPower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/SpawnActorPower.cs @@ -61,7 +61,7 @@ public override void Activate(Actor self, Order order, SupportPowerManager manag { var info = Info as SpawnActorPowerInfo; var position = order.Target.CenterPosition; - var cell = ((IMapCell)self.World.Map).CellContaining(position); + var cell = self.World.Map.CellContaining(position); if (!Validate(self.World, info, cell)) return; @@ -103,15 +103,15 @@ public override void SelectTarget(Actor self, string order, SupportPowerManager public bool Validate(World world, SpawnActorPowerInfo info, CPos cell) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return false; if (!info.AllowUnderShroud && world.ShroudObscures(cell)) return false; - if (info.Terrain != null && !info.Terrain.Contains(mapCell.GetTerrainInfo(cell).Type)) + if (info.Terrain != null && !info.Terrain.Contains(map.GetTerrainInfo(cell).Type)) return false; return true; diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs b/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs index 6a46139b2033..5a317ceaae40 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs @@ -300,7 +300,7 @@ public SelectGenericPowerTarget(string order, SupportPowerManager manager, strin protected override IEnumerable OrderInner(World world, CPos cell, int2 worldPixel, MouseInput mi) { world.CancelInputMode(); - if (mi.Button == expectedButton && ((IMapCell)world.Map).Contains(cell)) + if (mi.Button == expectedButton && world.Map.Contains(cell)) yield return new Order(order, manager.Self, Target.FromCell(world, cell), false) { SuppressVisualFeedback = true }; } @@ -316,7 +316,7 @@ protected override void Tick(World world) protected override IEnumerable RenderAnnotations(WorldRenderer wr, World world) { yield break; } protected override string GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi) { - return ((IMapCell)world.Map).Contains(cell) ? cursor : "generic-blocked"; + return world.Map.Contains(cell) ? cursor : "generic-blocked"; } } } diff --git a/OpenRA.Mods.Common/Traits/Wanders.cs b/OpenRA.Mods.Common/Traits/Wanders.cs index 3c1161f4dad7..1a462272d96f 100644 --- a/OpenRA.Mods.Common/Traits/Wanders.cs +++ b/OpenRA.Mods.Common/Traits/Wanders.cs @@ -90,11 +90,11 @@ void INotifyIdle.TickIdle(Actor self) CPos? PickTargetLocation() { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; var target = self.CenterPosition + new WVec(0, -1024 * effectiveMoveRadius, 0).Rotate(WRot.FromFacing(self.World.SharedRandom.Next(255))); - var targetCell = mapCell.CellContaining(target); + var targetCell = map.CellContaining(target); - if (!mapCell.Contains(targetCell)) + if (!map.Contains(targetCell)) { // If MoveRadius is too big there might not be a valid cell to order the attack to (if actor is on a small island and can't leave) if (++ticksIdle % info.ReduceMoveRadiusDelay == 0) @@ -106,7 +106,7 @@ void INotifyIdle.TickIdle(Actor self) if (info.AvoidTerrainTypes.Count > 0) { - var terrainType = mapCell.GetTerrainInfo(targetCell).Type; + var terrainType = map.GetTerrainInfo(targetCell).Type; if (Info.AvoidTerrainTypes.Contains(terrainType)) return null; } diff --git a/OpenRA.Mods.Common/Traits/World/ActorMap.cs b/OpenRA.Mods.Common/Traits/World/ActorMap.cs index 04358339fd08..1318db210cdd 100644 --- a/OpenRA.Mods.Common/Traits/World/ActorMap.cs +++ b/OpenRA.Mods.Common/Traits/World/ActorMap.cs @@ -141,7 +141,7 @@ public void Tick(ActorMap am) currentActors.UnionWith( am.ActorsInBox(position - delta, position + delta) .Where(a => (a.CenterPosition - position).HorizontalLengthSquared < range.LengthSquared - && (vRange.Length == 0 || (((IMapCell)a.World.Map).DistanceAboveTerrain(a.CenterPosition).LengthSquared <= vRange.LengthSquared)))); + && (vRange.Length == 0 || (a.World.Map.DistanceAboveTerrain(a.CenterPosition).LengthSquared <= vRange.LengthSquared)))); if (onActorEntered != null) foreach (var a in currentActors) @@ -192,7 +192,7 @@ public ActorMap(World world, ActorMapInfo info) { this.info = info; map = world.Map; - influence = new[] { new CellLayer((IMapCell)world.Map) }; + influence = new[] { new CellLayer(world.Map) }; cols = CellCoordToBinIndex(world.Map.MapSize.X) + 1; rows = CellCoordToBinIndex(world.Map.MapSize.Y) + 1; @@ -222,7 +222,7 @@ void INotifyCreated.Created(Actor self) foreach (var cml in customMovementLayers) { CustomMovementLayers[cml.Index] = cml; - influence[cml.Index] = new CellLayer((IMapCell)self.World.Map); + influence[cml.Index] = new CellLayer(self.World.Map); } } @@ -266,7 +266,7 @@ public bool MoveNext() public IEnumerable GetActorsAt(CPos a) { // PERF: Custom enumerator for efficiency - using `yield` is slower. - var uv = a.ToMPos((IMapCell)map); + var uv = a.ToMPos(map); var layer = influence[a.Layer]; if (!layer.Contains(uv)) return Enumerable.Empty(); @@ -276,7 +276,7 @@ public IEnumerable GetActorsAt(CPos a) public IEnumerable GetActorsAt(CPos a, SubCell sub) { - var uv = a.ToMPos((IMapCell)map); + var uv = a.ToMPos(map); var layer = influence[a.Layer]; if (!layer.Contains(uv)) yield break; @@ -294,8 +294,7 @@ public bool HasFreeSubCell(CPos cell, bool checkTransient = true) public SubCell FreeSubCell(CPos cell, SubCell preferredSubCell = SubCell.Any, bool checkTransient = true) { - var mapCell = (IMapCell)map; - var uv = cell.ToMPos(mapCell); + var uv = cell.ToMPos(map); var layer = influence[cell.Layer]; if (!layer.Contains(uv)) return preferredSubCell != SubCell.Any ? preferredSubCell : SubCell.First; @@ -304,9 +303,9 @@ public SubCell FreeSubCell(CPos cell, SubCell preferredSubCell = SubCell.Any, bo return preferredSubCell; if (!AnyActorsAt(uv, layer)) - return mapCell.Grid.DefaultSubCell; + return map.Grid.DefaultSubCell; - for (var i = (int)SubCell.First; i < mapCell.Grid.SubCellOffsets.Length; i++) + for (var i = (int)SubCell.First; i < map.Grid.SubCellOffsets.Length; i++) if (i != (int)preferredSubCell && !AnyActorsAt(uv, cell, layer, (SubCell)i, checkTransient)) return (SubCell)i; @@ -315,8 +314,7 @@ public SubCell FreeSubCell(CPos cell, SubCell preferredSubCell = SubCell.Any, bo public SubCell FreeSubCell(CPos cell, SubCell preferredSubCell, Func checkIfBlocker) { - var mapCell = (IMapCell)map; - var uv = cell.ToMPos(mapCell); + var uv = cell.ToMPos(map); var layer = influence[cell.Layer]; if (!layer.Contains(uv)) return preferredSubCell != SubCell.Any ? preferredSubCell : SubCell.First; @@ -325,9 +323,9 @@ public SubCell FreeSubCell(CPos cell, SubCell preferredSubCell, Func layer) // NOTE: always includes transients with influence public bool AnyActorsAt(CPos a) { - var uv = a.ToMPos((IMapCell)map); + var uv = a.ToMPos(map); var layer = influence[a.Layer]; if (!layer.Contains(uv)) return false; @@ -374,7 +372,7 @@ bool AnyActorsAt(MPos uv, CPos a, CellLayer layer, SubCell sub, b // NOTE: can not check aircraft public bool AnyActorsAt(CPos a, SubCell sub, bool checkTransient = true) { - var uv = a.ToMPos((IMapCell)map); + var uv = a.ToMPos(map); var layer = influence[a.Layer]; if (!layer.Contains(uv)) return false; @@ -396,7 +394,7 @@ bool AnyActorsAt(MPos uv, CellLayer layer, SubCell sub, Func withCondition) { - var uv = a.ToMPos((IMapCell)map); + var uv = a.ToMPos(map); var layer = influence[a.Layer]; if (!layer.Contains(uv)) return false; @@ -420,7 +418,7 @@ public void AddInfluence(Actor self, IOccupySpace ios) { foreach (var c in ios.OccupiedCells()) { - var uv = c.Cell.ToMPos((IMapCell)map); + var uv = c.Cell.ToMPos(map); var layer = influence[c.Cell.Layer]; if (!layer.Contains(uv)) continue; @@ -439,7 +437,7 @@ public void RemoveInfluence(Actor self, IOccupySpace ios) { foreach (var c in ios.OccupiedCells()) { - var uv = c.Cell.ToMPos((IMapCell)map); + var uv = c.Cell.ToMPos(map); var layer = influence[c.Cell.Layer]; if (!layer.Contains(uv)) continue; diff --git a/OpenRA.Mods.Common/Traits/World/BridgeLayer.cs b/OpenRA.Mods.Common/Traits/World/BridgeLayer.cs index 70d5620baf23..9027cacd9d48 100644 --- a/OpenRA.Mods.Common/Traits/World/BridgeLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/BridgeLayer.cs @@ -38,7 +38,7 @@ class BridgeLayer public BridgeLayer(World world) { - bridges = new CellLayer((IMapCell)world.Map); + bridges = new CellLayer(world.Map); } public Actor this[CPos cell] => bridges[cell]; diff --git a/OpenRA.Mods.Common/Traits/World/BuildableTerrainOverlay.cs b/OpenRA.Mods.Common/Traits/World/BuildableTerrainOverlay.cs index 450ed24aba10..c6c12ae5aca4 100644 --- a/OpenRA.Mods.Common/Traits/World/BuildableTerrainOverlay.cs +++ b/OpenRA.Mods.Common/Traits/World/BuildableTerrainOverlay.cs @@ -65,17 +65,19 @@ public BuildableTerrainOverlay(Actor self, BuildableTerrainOverlayInfo info) void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) { - var mapCell = (IMapCell)world.Map; - var mCell = (IMapCell)w.Map; + var map = world.Map; + var mapTiles = ((IMapTiles)world.Map).Tiles; + var mapRamp = ((IMapElevation)world.Map).Ramp; + var m = w.Map; render = new TerrainSpriteLayer(w, wr, disabledSprite, BlendMode.Alpha, wr.World.Type != WorldType.Editor); - mapCell.Tiles.CellEntryChanged += UpdateTerrainCell; - mapCell.CustomTerrain.CellEntryChanged += UpdateTerrainCell; + mapTiles.CellEntryChanged += UpdateTerrainCell; + map.CustomTerrain.CellEntryChanged += UpdateTerrainCell; - var cells = mCell.AllCells.Where(c => mCell.Contains(c) && - (!info.AllowedTerrainTypes.Contains(mCell.GetTerrainInfo(c).Type) || - mapCell.Ramp[c] != 0)).ToHashSet(); + var cells = m.AllCells.Where(c => m.Contains(c) && + (!info.AllowedTerrainTypes.Contains(m.GetTerrainInfo(c).Type) || + mapRamp[c] != 0)).ToHashSet(); palette = wr.Palette(info.Palette); @@ -85,12 +87,12 @@ void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) void UpdateTerrainCell(CPos cell) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; - if (!mapCell.Contains(cell)) + if (!map.Contains(cell)) return; - var buildableSprite = !info.AllowedTerrainTypes.Contains(mapCell.GetTerrainInfo(cell).Type) || mapCell.Ramp[cell] != 0 ? disabledSprite : null; + var buildableSprite = !info.AllowedTerrainTypes.Contains(map.GetTerrainInfo(cell).Type) || ((IMapElevation)map).Ramp[cell] != 0 ? disabledSprite : null; render.Update(cell, buildableSprite, palette, 1f, info.Alpha); } diff --git a/OpenRA.Mods.Common/Traits/World/CellTriggerOverlay.cs b/OpenRA.Mods.Common/Traits/World/CellTriggerOverlay.cs index 7955bfabce71..396d3bd439dc 100644 --- a/OpenRA.Mods.Common/Traits/World/CellTriggerOverlay.cs +++ b/OpenRA.Mods.Common/Traits/World/CellTriggerOverlay.cs @@ -72,18 +72,18 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR var triggerPositions = wr.World.ActorMap.TriggerPositions().ToHashSet(); - var mapCell = (IMapCell)wr.World.Map; + var map = wr.World.Map; foreach (var uv in wr.Viewport.VisibleCellsInsideBounds.CandidateMapCoords) { if (self.World.ShroudObscures(uv)) continue; - var cell = uv.ToCPos(mapCell); + var cell = uv.ToCPos(map); if (!triggerPositions.Contains(cell)) continue; - var center = mapCell.CenterOfCell(cell); + var center = map.CenterOfCell(cell); yield return new TextAnnotationRenderable(font, center, 1024, color, "T"); } } diff --git a/OpenRA.Mods.Common/Traits/World/CliffBackImpassabilityLayer.cs b/OpenRA.Mods.Common/Traits/World/CliffBackImpassabilityLayer.cs index 750e836614ac..ada375f7c3fa 100644 --- a/OpenRA.Mods.Common/Traits/World/CliffBackImpassabilityLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/CliffBackImpassabilityLayer.cs @@ -37,23 +37,23 @@ public CliffBackImpassabilityLayer(CliffBackImpassabilityLayerInfo info) public void WorldLoaded(World w, WorldRenderer wr) { var tileType = w.Map.Rules.TerrainInfo.GetTerrainIndex(info.TerrainType); - var mapCell = (IMapCell)w.Map; + var map = w.Map; // Units are allowed behind cliffs *only* if they are part of a tunnel portal var tunnelPortals = w.WorldActor.Info.TraitInfos() .SelectMany(mti => mti.PortalCells()) .ToHashSet(); - foreach (var uv in mapCell.AllCells.MapCoords) + foreach (var uv in map.AllCells.MapCoords) { - if (tunnelPortals.Contains(uv.ToCPos(mapCell))) + if (tunnelPortals.Contains(uv.ToCPos(map))) continue; // All the map cells that visually overlap the current cell - var testCells = mapCell.ProjectedCellsCovering(uv) - .SelectMany(puv => mapCell.Unproject(puv)); + var testCells = map.ProjectedCellsCovering(uv) + .SelectMany(puv => map.Unproject(puv)); if (testCells.Any(x => x.V >= uv.V + 4)) - mapCell.CustomTerrain[uv] = tileType; + map.CustomTerrain[uv] = tileType; } } } diff --git a/OpenRA.Mods.Common/Traits/World/CrateSpawner.cs b/OpenRA.Mods.Common/Traits/World/CrateSpawner.cs index a776d6355ca0..d44b532cca1e 100644 --- a/OpenRA.Mods.Common/Traits/World/CrateSpawner.cs +++ b/OpenRA.Mods.Common/Traits/World/CrateSpawner.cs @@ -130,7 +130,7 @@ void SpawnCrate(Actor self) { var inWater = self.World.SharedRandom.Next(100) < info.WaterChance; var pp = ChooseDropCell(self, inWater, 100); - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (pp == null) return; @@ -147,9 +147,9 @@ void SpawnCrate(Actor self) var delta = new WVec(0, -1024, 0).Rotate(WRot.FromYaw(dropFacing)); var altitude = self.World.Map.Rules.Actors[info.DeliveryAircraft].TraitInfo().CruiseAltitude.Length; - var target = mapCell.CenterOfCell(p) + new WVec(0, 0, altitude); - var startEdge = target - (mapCell.DistanceToEdge(target, -delta) + info.Cordon).Length * delta / 1024; - var finishEdge = target + (mapCell.DistanceToEdge(target, delta) + info.Cordon).Length * delta / 1024; + var target = map.CenterOfCell(p) + new WVec(0, 0, altitude); + var startEdge = target - (map.DistanceToEdge(target, -delta) + info.Cordon).Length * delta / 1024; + var finishEdge = target + (map.DistanceToEdge(target, delta) + info.Cordon).Length * delta / 1024; var plane = w.CreateActor(info.DeliveryAircraft, new TypeDictionary { @@ -174,11 +174,11 @@ void SpawnCrate(Actor self) { for (var n = 0; n < maxTries; n++) { - var mapCell = (IMapCell)self.World.Map; - var p = mapCell.ChooseRandomCell(self.World.SharedRandom); + var map = self.World.Map; + var p = map.ChooseRandomCell(self.World.SharedRandom); // Is this valid terrain? - var terrainType = mapCell.GetTerrainInfo(p).Type; + var terrainType = map.GetTerrainInfo(p).Type; if (!(inWater ? info.ValidWater : info.ValidGround).Contains(terrainType)) continue; diff --git a/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs b/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs index 4c0fc0940ae3..d9fc08e2253e 100644 --- a/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs +++ b/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs @@ -85,7 +85,7 @@ public class CreateMapPlayers : ICreatePlayers { void ICreatePlayers.CreatePlayers(World w, MersenneTwister playerRandom) { - var players = new MapPlayers(w.Map.PlayerDefinitions).Players; + var players = new MapPlayers(((Map)w.Map).PlayerDefinitions).Players; var worldPlayers = new List(); var worldOwnerFound = false; @@ -103,7 +103,7 @@ void ICreatePlayers.CreatePlayers(World w, MersenneTwister playerRandom) } if (!worldOwnerFound) - throw new InvalidOperationException($"Map {w.Map.Title} does not define a player actor owning the world."); + throw new InvalidOperationException($"Map {((Map)w.Map).Title} does not define a player actor owning the world."); Player localPlayer = null; diff --git a/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs b/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs index 205d96af5746..29d07e052b6c 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs @@ -58,7 +58,7 @@ void ICreatePlayers.CreatePlayers(World w, MersenneTwister playerRandom) if (w.Type != WorldType.Editor) return; - Players = new MapPlayers(w.Map.PlayerDefinitions); + Players = new MapPlayers(((Map)w.Map).PlayerDefinitions); worldOwner = Players.Players.Select(kvp => kvp.Value).First(p => !p.Playable && p.OwnsWorld); w.SetWorldOwner(new Player(w, null, worldOwner, playerRandom)); @@ -74,12 +74,12 @@ public void WorldLoaded(World world, WorldRenderer wr) foreach (var pr in Players.Players.Values) wr.UpdatePalettesForPlayer(pr.Name, pr.Color, false); - var ts = ((IMapCell)world.Map).Grid.TileSize; + var ts = world.Map.Grid.TileSize; var width = world.Map.MapSize.X * ts.Width; var height = world.Map.MapSize.Y * ts.Height; screenMap = new SpatiallyPartitioned(width, height, info.BinSize); - foreach (var kv in world.Map.ActorDefinitions) + foreach (var kv in ((Map)world.Map).ActorDefinitions) Add(kv.Key, new ActorReference(kv.Value.Value, kv.Value.ToDictionary()), true); // Update neighbours in one pass @@ -150,7 +150,7 @@ public void Add(EditorActorPreview preview, bool initialSetup = false) // Fallback to the actor's CenterPosition for the ActorMap if it has no Footprint var footprint = preview.Footprint.Select(kv => kv.Key).ToArray(); if (footprint.Length == 0) - footprint = new[] { ((IMapCell)worldRenderer.World.Map).CellContaining(preview.CenterPosition) }; + footprint = new[] { worldRenderer.World.Map.CellContaining(preview.CenterPosition) }; foreach (var cell in footprint) AddPreviewLocation(preview, cell); @@ -174,7 +174,7 @@ public void Remove(EditorActorPreview preview) // Fallback to the actor's CenterPosition for the ActorMap if it has no Footprint var footprint = preview.Footprint.Select(kv => kv.Key).ToArray(); if (footprint.Length == 0) - footprint = new[] { ((IMapCell)worldRenderer.World.Map).CellContaining(preview.CenterPosition) }; + footprint = new[] { worldRenderer.World.Map.CellContaining(preview.CenterPosition) }; foreach (var cell in footprint) { @@ -278,12 +278,11 @@ public IEnumerable PreviewsAt(CPos cell) public SubCell FreeSubCellAt(CPos cell) { var map = worldRenderer.World.Map; - var mapCell = (IMapCell)map; var previews = PreviewsAt(cell).ToList(); if (previews.Count == 0) - return mapCell.Grid.DefaultSubCell; + return map.Grid.DefaultSubCell; - for (var i = (byte)SubCell.First; i < mapCell.Grid.SubCellOffsets.Length; i++) + for (var i = (byte)SubCell.First; i < map.Grid.SubCellOffsets.Length; i++) { var blocked = previews.Any(p => { diff --git a/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs b/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs index d7f81a5d263f..d0ecbad012f6 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs @@ -243,7 +243,7 @@ WPos PreviewPosition(World world, ActorReference actor) if (buildingInfo != null) offset = buildingInfo.CenterOffset(world); - return ((IMapCell)world.Map).CenterOfSubCell(cell, subCell) + offset; + return world.Map.CenterOfSubCell(cell, subCell) + offset; } else throw new InvalidDataException($"Actor {ID} must define Location or CenterPosition"); diff --git a/OpenRA.Mods.Common/Traits/World/EditorCursorLayer.cs b/OpenRA.Mods.Common/Traits/World/EditorCursorLayer.cs index 2689eb6cd069..1253e50b8f1a 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorCursorLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorCursorLayer.cs @@ -79,7 +79,7 @@ void ITickRender.TickRender(WorldRenderer wr, Actor self) terrainOrResourceDirty = false; terrainOrResourcePreview.Clear(); - var pos = ((IMapCell)world.Map).CenterOfCell(cell); + var pos = world.Map.CenterOfCell(cell); if (Type == EditorCursorType.TerrainTemplate) terrainOrResourcePreview.AddRange(terrainRenderer.RenderPreview(wr, TerrainTemplate, pos)); else @@ -107,7 +107,7 @@ void ITickRender.TickRender(WorldRenderer wr, Actor self) if (Actor.RemoveInits() > 0) updated = true; - var subcell = ((IMapCell)world.Map).Contains(cell) ? editorLayer.FreeSubCellAt(cell) : SubCell.Invalid; + var subcell = ((IMapTiles)world.Map).Tiles.Contains(cell) ? editorLayer.FreeSubCellAt(cell) : SubCell.Invalid; if (subcell != SubCell.Invalid) { Actor.AddInit(new SubCellInit(subcell)); diff --git a/OpenRA.Mods.Common/Traits/World/EditorResourceLayer.cs b/OpenRA.Mods.Common/Traits/World/EditorResourceLayer.cs index 0fe0ee97cc83..94bf0b8ee278 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorResourceLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorResourceLayer.cs @@ -90,7 +90,7 @@ int IResourceLayer.GetMaxDensity(string resourceType) int IResourceLayer.AddResource(string resourceType, CPos cell, int amount) { return AddResource(resourceType, cell, amount); } int IResourceLayer.RemoveResource(string resourceType, CPos cell, int amount) { return RemoveResource(resourceType, cell, amount); } void IResourceLayer.ClearResources(CPos cell) { ClearResources(cell); } - bool IResourceLayer.IsVisible(CPos cell) { return ((IMapCell)Map).Contains(cell); } + bool IResourceLayer.IsVisible(CPos cell) { return Map.Contains(cell); } bool IResourceLayer.IsEmpty => false; IResourceLayerInfo IResourceLayer.Info => info; @@ -101,7 +101,7 @@ public EditorResourceLayer(Actor self, EditorResourceLayerInfo info) this.info = info; Map = self.World.Map; - Tiles = new CellLayer((IMapCell)Map); + Tiles = new CellLayer(Map); ResourceTypesByIndex = info.ResourceTypes.ToDictionary( kv => kv.Value.ResourceIndex, kv => kv.Key); @@ -117,16 +117,15 @@ public void WorldLoaded(World w, WorldRenderer wr) var playerResourcesInfo = w.Map.Rules.Actors[SystemActors.Player].TraitInfoOrDefault(); resourceValues = playerResourcesInfo?.ResourceValues ?? new Dictionary(); - foreach (var cell in ((IMapCell)Map).AllCells) + foreach (var cell in Map.AllCells) UpdateCell(cell); } public void UpdateCell(CPos cell) { - var mapCell = (IMapCell)Map; var mapResource = (IMapResource)Map; - var uv = cell.ToMPos(mapCell); + var uv = cell.ToMPos(mapResource); if (!mapResource.Resources.Contains(uv)) return; @@ -147,7 +146,7 @@ public void UpdateCell(CPos cell) UpdateNetWorth(t.Type, t.Density, newTile.Type, newTile.Density); Tiles[uv] = newTile; - mapCell.CustomTerrain[uv] = newTerrain; + mapResource.CustomTerrain[uv] = newTerrain; CellChanged?.Invoke(cell, newTile.Type); if (!info.RecalculateResourceDensity) @@ -211,9 +210,10 @@ protected virtual int CalculateCellDensity(ResourceLayerContents contents, CPos protected virtual bool AllowResourceAt(string resourceType, CPos cell) { - var mapCell = (IMapCell)Map; + var mapRamp = ((IMapElevation)Map).Ramp; + var mapTiles = ((IMapTiles)Map).Tiles; - if (!mapCell.Ramp.Contains(cell) || mapCell.Ramp[cell] != 0) + if (!mapRamp.Contains(cell) || mapRamp[cell] != 0) return false; if (!info.ResourceTypes.TryGetValue(resourceType, out var resourceInfo)) @@ -221,7 +221,7 @@ protected virtual bool AllowResourceAt(string resourceType, CPos cell) // Ignore custom terrain types when spawning resources in the editor var terrainInfo = Map.Rules.TerrainInfo; - var terrainType = terrainInfo.TerrainTypes[terrainInfo.GetTerrainInfo(mapCell.Tiles[cell]).TerrainType].Type; + var terrainType = terrainInfo.TerrainTypes[terrainInfo.GetTerrainInfo(mapTiles[cell]).TerrainType].Type; // TODO: Check against actors in the EditorActorLayer return resourceInfo.AllowedTerrainTypes.Contains(terrainType); diff --git a/OpenRA.Mods.Common/Traits/World/EditorSelectionLayer.cs b/OpenRA.Mods.Common/Traits/World/EditorSelectionLayer.cs index 3c50977c436e..d0529741bf2a 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorSelectionLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorSelectionLayer.cs @@ -78,12 +78,12 @@ void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) public void SetCopyRegion(CPos start, CPos end) { - CopyRegion = CellRegion.BoundingRegion(((IMapCell)map).Grid.Type, new[] { start, end }); + CopyRegion = CellRegion.BoundingRegion(map.Grid.Type, new[] { start, end }); } public void SetPasteRegion(CPos start, CPos end) { - PasteRegion = CellRegion.BoundingRegion(((IMapCell)map).Grid.Type, new[] { start, end }); + PasteRegion = CellRegion.BoundingRegion(map.Grid.Type, new[] { start, end }); } public void Clear() @@ -96,16 +96,16 @@ IEnumerable IRenderAboveShroud.RenderAboveShroud(Actor self, WorldR if (wr.World.Type != WorldType.Editor) yield break; - var mapCell = (IMapCell)wr.World.Map; + var map = wr.World.Map; if (CopyRegion != null) foreach (var c in CopyRegion) - yield return new SpriteRenderable(copyTile, mapCell.CenterOfCell(c), + yield return new SpriteRenderable(copyTile, map.CenterOfCell(c), WVec.Zero, -511, palette, 1f, copyAlpha * info.FootprintAlpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); if (PasteRegion != null) foreach (var c in PasteRegion) - yield return new SpriteRenderable(pasteTile, mapCell.CenterOfCell(c), + yield return new SpriteRenderable(pasteTile, map.CenterOfCell(c), WVec.Zero, -511, palette, 1f, pasteAlpha * info.FootprintAlpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); } diff --git a/OpenRA.Mods.Common/Traits/World/ElevatedBridgeLayer.cs b/OpenRA.Mods.Common/Traits/World/ElevatedBridgeLayer.cs index 9c948b96a580..784af7423050 100644 --- a/OpenRA.Mods.Common/Traits/World/ElevatedBridgeLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/ElevatedBridgeLayer.cs @@ -37,17 +37,16 @@ public class ElevatedBridgeLayer : ICustomMovementLayer, IWorldLoaded public ElevatedBridgeLayer(Actor self, ElevatedBridgeLayerInfo info) { map = self.World.Map; - var mapCell = (IMapCell)self.World.Map; - cellCenters = new CellLayer(mapCell); - terrainIndices = new CellLayer(mapCell); + cellCenters = new CellLayer(map); + terrainIndices = new CellLayer(map); terrainIndices.Clear(map.Rules.TerrainInfo.GetTerrainIndex(info.ImpassableTerrainType)); } public void WorldLoaded(World world, WorldRenderer wr) { - var mapCell = (IMapCell)map; + var mapCell = map; - var cellHeight = ((IMapCell)world.Map).CellHeightStep.Length; + var cellHeight = world.Map.CellHeightStep.Length; foreach (var tti in world.WorldActor.Info.TraitInfos()) { enabled = true; diff --git a/OpenRA.Mods.Common/Traits/World/HierarchicalPathFinderOverlay.cs b/OpenRA.Mods.Common/Traits/World/HierarchicalPathFinderOverlay.cs index 45f8169f1de7..00ea205530c6 100644 --- a/OpenRA.Mods.Common/Traits/World/HierarchicalPathFinderOverlay.cs +++ b/OpenRA.Mods.Common/Traits/World/HierarchicalPathFinderOverlay.cs @@ -84,7 +84,7 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR if (!Enabled) yield break; - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; var pathFinder = self.Trait(); var visibleRegion = wr.Viewport.AllVisibleCells; var locomotors = Locomotor == null @@ -105,17 +105,17 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR foreach (var connectionsFromOneNode in abstractGraph) { var nodeCell = connectionsFromOneNode.Key; - var srcUv = (PPos)nodeCell.ToMPos(mapCell); + var srcUv = (PPos)nodeCell.ToMPos(map); foreach (var cost in connectionsFromOneNode.Value) { - var destUv = (PPos)cost.Destination.ToMPos(mapCell); + var destUv = (PPos)cost.Destination.ToMPos(map); if (!visibleRegion.Contains(destUv) && !visibleRegion.Contains(srcUv)) continue; var connection = new WPos[] { - mapCell.CenterOfSubCell(cost.Destination, SubCell.FullCell), - mapCell.CenterOfSubCell(nodeCell, SubCell.FullCell), + map.CenterOfSubCell(cost.Destination, SubCell.FullCell), + map.CenterOfSubCell(nodeCell, SubCell.FullCell), }; // Connections on the ground layer given in ground color. @@ -133,7 +133,7 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR var centerCell = new CPos( (cost.Destination.X + nodeCell.X) / 2, (cost.Destination.Y + nodeCell.Y) / 2); - var centerPos = mapCell.CenterOfSubCell(centerCell, SubCell.FullCell); + var centerPos = map.CenterOfSubCell(centerCell, SubCell.FullCell); yield return new TextAnnotationRenderable(font, centerPos, 0, lineColor, cost.Cost.ToString()); } } @@ -141,12 +141,12 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR foreach (var domainForCell in abstractDomains) { var nodeCell = domainForCell.Key; - var srcUv = (PPos)nodeCell.ToMPos(mapCell); + var srcUv = (PPos)nodeCell.ToMPos(map); if (!visibleRegion.Contains(srcUv)) continue; // Show the abstract cell and its domain index. - var nodePos = ((IMapCell)self.World.Map).CenterOfSubCell(nodeCell, SubCell.FullCell); + var nodePos = self.World.Map.CenterOfSubCell(nodeCell, SubCell.FullCell); yield return new TextAnnotationRenderable( font, nodePos, 0, info.AbstractNodeColor, $"{domainForCell.Value}: {nodeCell}"); } diff --git a/OpenRA.Mods.Common/Traits/World/JumpjetActorLayer.cs b/OpenRA.Mods.Common/Traits/World/JumpjetActorLayer.cs index 581970d7b6af..e0fab2829893 100644 --- a/OpenRA.Mods.Common/Traits/World/JumpjetActorLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/JumpjetActorLayer.cs @@ -38,11 +38,11 @@ public class JumpjetActorLayer : ICustomMovementLayer public JumpjetActorLayer(Actor self, JumpjetActorLayerInfo info) { - var mapCell = (IMapCell)self.World.Map; + map = self.World.Map; terrainIndex = self.World.Map.Rules.TerrainInfo.GetTerrainIndex(info.TerrainType); - height = new CellLayer((IMapCell)map); - var cellHeight = ((IMapCell)self.World.Map).CellHeightStep.Length; - foreach (var c in mapCell.AllCells) + height = new CellLayer(map); + var cellHeight = map.CellHeightStep.Length; + foreach (var c in map.AllCells) { var neighbourCount = 0; var neighbourHeight = 0; @@ -51,11 +51,11 @@ public JumpjetActorLayer(Actor self, JumpjetActorLayerInfo info) for (var dx = -info.SmoothingRadius; dx <= info.SmoothingRadius; dx++) { var neighbour = c + new CVec(dx, dy); - if (!mapCell.AllCells.Contains(neighbour)) + if (!map.AllCells.Contains(neighbour)) continue; neighbourCount++; - neighbourHeight += mapCell.Height[neighbour]; + neighbourHeight += ((IMapElevation)map).Height[neighbour]; } } @@ -70,14 +70,13 @@ public JumpjetActorLayer(Actor self, JumpjetActorLayerInfo info) WPos ICustomMovementLayer.CenterOfCell(CPos cell) { - var pos = ((IMapCell)map).CenterOfCell(cell); + var pos = map.CenterOfCell(cell); return pos + new WVec(0, 0, height[cell] - pos.Z); } bool ValidTransitionCell(CPos cell, LocomotorInfo li) { - var mapCell = (IMapCell)map; - var terrainType = mapCell.GetTerrainInfo(cell).Type; + var terrainType = map.GetTerrainInfo(cell).Type; var jli = (JumpjetLocomotorInfo)li; if (!jli.JumpjetTransitionTerrainTypes.Contains(terrainType) && jli.JumpjetTransitionTerrainTypes.Count > 0) return false; @@ -85,7 +84,7 @@ bool ValidTransitionCell(CPos cell, LocomotorInfo li) if (jli.JumpjetTransitionOnRamps) return true; - return mapCell.Ramp[cell] == 0; + return ((IMapElevation)map).Ramp[cell] == 0; } short ICustomMovementLayer.EntryMovementCost(LocomotorInfo li, CPos cell) diff --git a/OpenRA.Mods.Common/Traits/World/LegacyBridgeLayer.cs b/OpenRA.Mods.Common/Traits/World/LegacyBridgeLayer.cs index e2f27f68491c..2a15c84605f5 100644 --- a/OpenRA.Mods.Common/Traits/World/LegacyBridgeLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/LegacyBridgeLayer.cs @@ -46,9 +46,9 @@ public LegacyBridgeLayer(Actor self, LegacyBridgeLayerInfo info) public void WorldLoaded(World w, WorldRenderer wr) { - var mapCell = (IMapCell)w.Map; + var map = w.Map; - bridges = new CellLayer(mapCell); + bridges = new CellLayer(map); // Build a list of templates that should be overlayed with bridges foreach (var bridge in info.Bridges) @@ -59,7 +59,7 @@ public void WorldLoaded(World w, WorldRenderer wr) } // Take all templates to overlay from the map - foreach (var cell in mapCell.AllCells.Where(cell => bridgeTypes.ContainsKey(mapCell.Tiles[cell].Type))) + foreach (var cell in map.AllCells.Where(cell => bridgeTypes.ContainsKey(((IMapTiles)map).Tiles[cell].Type))) ConvertBridgeToActor(w, cell); // Link adjacent (long)-bridges so that artwork is updated correctly @@ -69,14 +69,15 @@ public void WorldLoaded(World w, WorldRenderer wr) void ConvertBridgeToActor(World w, CPos cell) { - var mapCell = (IMapCell)w.Map; + var map = w.Map; + var mapTiles = ((IMapTiles)map).Tiles; // This cell already has a bridge overlaying it from a previous iteration if (bridges[cell] != null) return; // Correlate the tile "image" aka subtile with its position to find the template origin - var ti = mapCell.Tiles[cell]; + var ti = mapTiles[cell]; var tile = ti.Type; var index = ti.Index; var template = terrainInfo.Templates[tile]; @@ -92,7 +93,6 @@ void ConvertBridgeToActor(World w, CPos cell) }).Trait(); var subTiles = new Dictionary(); - var mapTiles = mapCell.Tiles; // For each subtile in the template for (byte ind = 0; ind < template.Size.X * template.Size.Y; ind++) diff --git a/OpenRA.Mods.Common/Traits/World/Locomotor.cs b/OpenRA.Mods.Common/Traits/World/Locomotor.cs index 5e66f05f12e8..5105286968ba 100644 --- a/OpenRA.Mods.Common/Traits/World/Locomotor.cs +++ b/OpenRA.Mods.Common/Traits/World/Locomotor.cs @@ -182,14 +182,14 @@ public short MovementCostForCell(CPos cell) short MovementCostForCell(CPos cell, CPos? fromCell) { - var mapCell = (IMapCell)world.Map; - if (!mapCell.Contains(cell)) + var map = world.Map; + if (!map.Contains(cell)) return PathGraph.MovementCostForUnreachableCell; // Prevent units from jumping over height discontinuities. - if (fromCell != null && cell.Layer == 0 && fromCell.Value.Layer == 0 && mapCell.Grid.MaximumTerrainHeight > 0) + if (fromCell != null && cell.Layer == 0 && fromCell.Value.Layer == 0 && map.Grid.MaximumTerrainHeight > 0) { - var heightLayer = mapCell.Height; + var heightLayer = ((IMapElevation)map).Height; if (Math.Abs(heightLayer[cell] - heightLayer[fromCell.Value]) > 1) return PathGraph.MovementCostForUnreachableCell; } @@ -199,7 +199,7 @@ short MovementCostForCell(CPos cell, CPos? fromCell) public int MovementSpeedForCell(CPos cell) { - var index = cell.Layer == 0 ? ((IMapCell)world.Map).GetTerrainIndex(cell) : + var index = cell.Layer == 0 ? world.Map.GetTerrainIndex(cell) : world.GetCustomMovementLayers()[cell.Layer].GetTerrainIndex(cell); return terrainInfos[index].Speed; @@ -291,7 +291,7 @@ bool CanMoveFreelyInto(Actor actor, CPos cell, SubCell subCell, BlockedByActor c public bool CanStayInCell(CPos cell) { - if (!((IMapCell)world.Map).Contains(cell)) + if (!world.Map.Contains(cell)) return false; return !GetCache(cell).CellFlag.HasCellFlag(CellFlag.HasTransitOnlyActor); @@ -370,16 +370,16 @@ bool IsBlockedBy(Actor actor, Actor otherActor, Actor ignoreActor, CPos cell, Bl public void WorldLoaded(World w, WorldRenderer wr) { - var mapCell = (IMapCell)w.Map; + var map = w.Map; actorMap = w.ActorMap; - mapCell.CustomTerrain.CellEntryChanged += UpdateCellCost; - mapCell.Tiles.CellEntryChanged += UpdateCellCost; + map.CustomTerrain.CellEntryChanged += UpdateCellCost; + ((IMapTiles)map).Tiles.CellEntryChanged += UpdateCellCost; actorMap.CellUpdated += CellUpdated; - cellsCost = new[] { new CellLayer(mapCell) }; - blockingCache = new[] { new CellLayer(mapCell) }; + cellsCost = new[] { new CellLayer(map) }; + blockingCache = new[] { new CellLayer(map) }; - foreach (var cell in mapCell.AllCells) + foreach (var cell in map.AllCells) { UpdateCellCost(cell); UpdateCellBlocking(cell); @@ -394,11 +394,11 @@ public void WorldLoaded(World w, WorldRenderer wr) if (cml == null) continue; - var cellLayer = new CellLayer(mapCell); + var cellLayer = new CellLayer(map); cellsCost[cml.Index] = cellLayer; - blockingCache[cml.Index] = new CellLayer(mapCell); + blockingCache[cml.Index] = new CellLayer(map); - foreach (var cell in mapCell.AllCells) + foreach (var cell in map.AllCells) { var index = cml.GetTerrainIndex(cell); @@ -430,7 +430,7 @@ void CellUpdated(CPos cell) void UpdateCellCost(CPos cell) { var index = cell.Layer == 0 - ? ((IMapCell)world.Map).GetTerrainIndex(cell) + ? world.Map.GetTerrainIndex(cell) : world.GetCustomMovementLayers()[cell.Layer].GetTerrainIndex(cell); var cost = PathGraph.MovementCostForUnreachableCell; @@ -443,7 +443,7 @@ void UpdateCellCost(CPos cell) cache[cell] = cost; else { - var uv = cell.ToMPos((IMapCell)world.Map); + var uv = cell.ToMPos(world.Map); var oldCost = cache[uv]; cache[uv] = cost; CellCostChanged(cell, oldCost, cost); diff --git a/OpenRA.Mods.Common/Traits/World/MapStartingLocations.cs b/OpenRA.Mods.Common/Traits/World/MapStartingLocations.cs index 5c7cb942cce6..89edfad663ee 100644 --- a/OpenRA.Mods.Common/Traits/World/MapStartingLocations.cs +++ b/OpenRA.Mods.Common/Traits/World/MapStartingLocations.cs @@ -127,7 +127,7 @@ void INotifyCreated.Created(Actor self) .OptionOrDefault("separateteamspawns", info.SeparateTeamSpawnsCheckboxEnabled); var spawns = new List(); - foreach (var n in self.World.Map.ActorDefinitions) + foreach (var n in ((Map)self.World.Map).ActorDefinitions) if (n.Value.Value == "mpspawn") spawns.Add(new ActorReference(n.Key, n.Value.ToDictionary()).GetValue()); @@ -175,15 +175,15 @@ void IWorldLoaded.WorldLoaded(World world, WorldRenderer wr) { foreach (var p in world.Players) { - var mapCell = (IMapCell)world.Map; + var map = world.Map; if (!p.Playable) continue; if (p == world.LocalPlayer) - wr.Viewport.Center(mapCell.CenterOfCell(p.HomeLocation)); + wr.Viewport.Center(map.CenterOfCell(p.HomeLocation)); - var cells = Shroud.ProjectedCellsInRange(mapCell, p.HomeLocation, info.InitialExploreRange) + var cells = Shroud.ProjectedCellsInRange(map, p.HomeLocation, info.InitialExploreRange) .ToList(); foreach (var q in world.Players) diff --git a/OpenRA.Mods.Common/Traits/World/PathFinderOverlay.cs b/OpenRA.Mods.Common/Traits/World/PathFinderOverlay.cs index be4174b658d6..b32c60368de5 100644 --- a/OpenRA.Mods.Common/Traits/World/PathFinderOverlay.cs +++ b/OpenRA.Mods.Common/Traits/World/PathFinderOverlay.cs @@ -157,8 +157,8 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR foreach (var sourceCell in sourceCells) yield return new TargetLineRenderable(new[] { - ((IMapCell)self.World.Map).CenterOfSubCell(sourceCell, SubCell.FullCell), - ((IMapCell)self.World.Map).CenterOfSubCell(targetCell ?? sourceCell, SubCell.FullCell), + self.World.Map.CenterOfSubCell(sourceCell, SubCell.FullCell), + self.World.Map.CenterOfSubCell(targetCell ?? sourceCell, SubCell.FullCell), }, info.TargetLineColor, 8, 8); foreach (var line in RenderEdges(self, abstractEdges1, 8, 6, info.AbstractColor1)) @@ -201,8 +201,8 @@ static IEnumerable RenderEdges(Actor self, Record edges, int nodeSi foreach (var (source, destination, _, _) in edges) yield return new TargetLineRenderable(new[] { - ((IMapCell)self.World.Map).CenterOfSubCell(source, SubCell.FullCell) + CustomLayerOffset(source), - ((IMapCell)self.World.Map).CenterOfSubCell(destination, SubCell.FullCell) + CustomLayerOffset(destination), + self.World.Map.CenterOfSubCell(source, SubCell.FullCell) + CustomLayerOffset(source), + self.World.Map.CenterOfSubCell(destination, SubCell.FullCell) + CustomLayerOffset(destination), }, destination.Layer == 0 ? color : customColor, edgeSize, nodeSize); } @@ -214,7 +214,7 @@ static IEnumerable RenderCosts(Actor self, Record edges, WVec textO var customColor = CustomLayerColor(color); foreach (var (_, destination, costSoFar, estimatedRemainingCost) in edges) { - var centerPos = ((IMapCell)self.World.Map).CenterOfSubCell(destination, SubCell.FullCell) + + var centerPos = self.World.Map.CenterOfSubCell(destination, SubCell.FullCell) + CustomLayerOffset(destination) + textOffset; yield return new TextAnnotationRenderable(font, centerPos, 0, destination.Layer == 0 ? color : customColor, diff --git a/OpenRA.Mods.Common/Traits/World/ResourceLayer.cs b/OpenRA.Mods.Common/Traits/World/ResourceLayer.cs index 1d68ed88b267..2aad592c771d 100644 --- a/OpenRA.Mods.Common/Traits/World/ResourceLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/ResourceLayer.cs @@ -121,7 +121,7 @@ public ResourceLayer(Actor self, ResourceLayerInfo info) world = self.World; Map = world.Map; BuildingInfluence = self.Trait(); - Content = new CellLayer((IMapCell)Map); + Content = new CellLayer(Map); ResourceTypesByIndex = info.ResourceTypes.ToDictionary( kv => kv.Value.ResourceIndex, kv => kv.Key); @@ -129,9 +129,9 @@ public ResourceLayer(Actor self, ResourceLayerInfo info) protected virtual void WorldLoaded(World w, WorldRenderer wr) { - var mapCell = (IMapCell)w.Map; + var map = w.Map; - foreach (var cell in mapCell.AllCells) + foreach (var cell in map.AllCells) { var resource = ((IMapResource)world.Map).Resources[cell]; if (!ResourceTypesByIndex.TryGetValue(resource.Type, out var resourceType)) @@ -147,7 +147,7 @@ protected virtual void WorldLoaded(World w, WorldRenderer wr) return; // Set initial density based on the number of neighboring resources - foreach (var cell in mapCell.AllCells) + foreach (var cell in map.AllCells) { var resource = Content[cell]; if (resource.Type == null || !info.ResourceTypes.TryGetValue(resource.Type, out var resourceInfo)) @@ -172,15 +172,13 @@ protected virtual void WorldLoaded(World w, WorldRenderer wr) protected virtual bool AllowResourceAt(string resourceType, CPos cell) { - var mapCell = (IMapCell)Map; - - if (!mapCell.Contains(cell) || mapCell.Ramp[cell] != 0) + if (!Map.Contains(cell) || ((IMapElevation)Map).Ramp[cell] != 0) return false; if (resourceType == null || !info.ResourceTypes.TryGetValue(resourceType, out var resourceInfo)) return false; - if (!resourceInfo.AllowedTerrainTypes.Contains(mapCell.GetTerrainInfo(cell).Type)) + if (!resourceInfo.AllowedTerrainTypes.Contains(Map.GetTerrainInfo(cell).Type)) return false; return !BuildingInfluence.AnyBuildingAt(cell); @@ -190,11 +188,11 @@ ResourceLayerContents CreateResourceCell(string resourceType, CPos cell, int den { if (!info.ResourceTypes.TryGetValue(resourceType, out var resourceInfo)) { - ((IMapCell)world.Map).CustomTerrain[cell] = byte.MaxValue; + world.Map.CustomTerrain[cell] = byte.MaxValue; return ResourceLayerContents.Empty; } - ((IMapCell)world.Map).CustomTerrain[cell] = world.Map.Rules.TerrainInfo.GetTerrainIndex(resourceInfo.TerrainType); + world.Map.CustomTerrain[cell] = world.Map.Rules.TerrainInfo.GetTerrainIndex(resourceInfo.TerrainType); ++resCells; return new ResourceLayerContents(resourceType, density.Clamp(1, resourceInfo.MaxDensity)); @@ -202,7 +200,7 @@ ResourceLayerContents CreateResourceCell(string resourceType, CPos cell, int den bool CanAddResource(string resourceType, CPos cell, int amount = 1) { - if (!((IMapCell)world.Map).Contains(cell)) + if (!world.Map.Contains(cell)) return false; if (resourceType == null || !info.ResourceTypes.TryGetValue(resourceType, out var resourceInfo)) @@ -257,7 +255,7 @@ int RemoveResource(string resourceType, CPos cell, int amount = 1) if (density == 0) { Content[cell] = ResourceLayerContents.Empty; - ((IMapCell)Map).CustomTerrain[cell] = byte.MaxValue; + Map.CustomTerrain[cell] = byte.MaxValue; --resCells; CellChanged?.Invoke(cell, null); @@ -282,7 +280,7 @@ void ClearResources(CPos cell) return; Content[cell] = ResourceLayerContents.Empty; - ((IMapCell)Map).CustomTerrain[cell] = byte.MaxValue; + Map.CustomTerrain[cell] = byte.MaxValue; --resCells; CellChanged?.Invoke(cell, null); diff --git a/OpenRA.Mods.Common/Traits/World/ResourceRenderer.cs b/OpenRA.Mods.Common/Traits/World/ResourceRenderer.cs index 29e148058a2a..db23c6c98be3 100644 --- a/OpenRA.Mods.Common/Traits/World/ResourceRenderer.cs +++ b/OpenRA.Mods.Common/Traits/World/ResourceRenderer.cs @@ -113,7 +113,7 @@ public ResourceRenderer(Actor self, ResourceRendererInfo info) World = self.World; ResourceLayer = self.Trait(); ResourceLayer.CellChanged += AddDirtyCell; - RenderContents = new CellLayer((IMapCell)self.World.Map); + RenderContents = new CellLayer(self.World.Map); } void AddDirtyCell(CPos cell, string resourceType) @@ -159,7 +159,7 @@ protected virtual void WorldLoaded(World w, WorldRenderer wr) // Initialize the RenderContent with the initial map state so it is visible // through the fog with the Explored Map option enabled - foreach (var cell in ((IMapCell)w.Map).AllCells) + foreach (var cell in w.Map.AllCells) { var resource = ResourceLayer.GetResource(cell); var rendererCellContents = CreateRenderCellContents(wr, resource, cell); diff --git a/OpenRA.Mods.Common/Traits/World/ShroudRenderer.cs b/OpenRA.Mods.Common/Traits/World/ShroudRenderer.cs index ec670a53679a..130a716bdaf0 100644 --- a/OpenRA.Mods.Common/Traits/World/ShroudRenderer.cs +++ b/OpenRA.Mods.Common/Traits/World/ShroudRenderer.cs @@ -144,11 +144,10 @@ public ShroudRenderer(World world, ShroudRendererInfo info) this.info = info; this.world = world; map = world.Map; - var mapCell = (IMapCell)map; - tileInfos = new CellLayer(mapCell); + tileInfos = new CellLayer(map); - cellsDirty = new CellLayer(mapCell); + cellsDirty = new CellLayer(map); anyCellDirty = true; // Load sprite variants @@ -203,14 +202,13 @@ public ShroudRenderer(World world, ShroudRendererInfo info) void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) { - var worldMapCell = (IMapCell)w.Map; - var mapCell = (IMapCell)map; + var worldMap = w.Map; // Initialize tile cache // This includes the region outside the visible area to cover any sprites peeking outside the map - foreach (var uv in worldMapCell.AllCells.MapCoords) + foreach (var uv in worldMap.AllCells.MapCoords) { - var pos = worldMapCell.CenterOfCell(uv.ToCPos(mapCell)); + var pos = worldMap.CenterOfCell(uv.ToCPos(map)); var screen = wr.Screen3DPosition(pos - new WVec(0, 0, pos.Z)); var variant = (byte)Game.CosmeticRandom.Next(info.ShroudVariants.Length); tileInfos[uv] = new TileInfo(screen, variant); @@ -218,9 +216,9 @@ void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) // All tiles are visible in the editor if (w.Type == WorldType.Editor) - cellVisibility = puv => (mapCell.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Explored); + cellVisibility = puv => (map.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Explored); else - cellVisibility = puv => (mapCell.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Hidden); + cellVisibility = puv => (map.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Hidden); var shroudBlend = shroudSprites[0].Sprite.BlendMode; if (shroudSprites.Any(s => s.Sprite.BlendMode != shroudBlend)) @@ -241,17 +239,16 @@ void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) Shroud.CellVisibility[] GetNeighborsVisbility(PPos puv) { - var mapCell = (IMapCell)map; - var cell = ((MPos)puv).ToCPos(mapCell); - neighbors[(int)Neighbor.Top] = cellVisibility((PPos)(cell + new CVec(0, -1)).ToMPos(mapCell)); - neighbors[(int)Neighbor.Right] = cellVisibility((PPos)(cell + new CVec(1, 0)).ToMPos(mapCell)); - neighbors[(int)Neighbor.Bottom] = cellVisibility((PPos)(cell + new CVec(0, 1)).ToMPos(mapCell)); - neighbors[(int)Neighbor.Left] = cellVisibility((PPos)(cell + new CVec(-1, 0)).ToMPos(mapCell)); - - neighbors[(int)Neighbor.TopLeft] = cellVisibility((PPos)(cell + new CVec(-1, -1)).ToMPos(mapCell)); - neighbors[(int)Neighbor.TopRight] = cellVisibility((PPos)(cell + new CVec(1, -1)).ToMPos(mapCell)); - neighbors[(int)Neighbor.BottomRight] = cellVisibility((PPos)(cell + new CVec(1, 1)).ToMPos(mapCell)); - neighbors[(int)Neighbor.BottomLeft] = cellVisibility((PPos)(cell + new CVec(-1, 1)).ToMPos(mapCell)); + var cell = ((MPos)puv).ToCPos(map); + neighbors[(int)Neighbor.Top] = cellVisibility((PPos)(cell + new CVec(0, -1)).ToMPos(map)); + neighbors[(int)Neighbor.Right] = cellVisibility((PPos)(cell + new CVec(1, 0)).ToMPos(map)); + neighbors[(int)Neighbor.Bottom] = cellVisibility((PPos)(cell + new CVec(0, 1)).ToMPos(map)); + neighbors[(int)Neighbor.Left] = cellVisibility((PPos)(cell + new CVec(-1, 0)).ToMPos(map)); + + neighbors[(int)Neighbor.TopLeft] = cellVisibility((PPos)(cell + new CVec(-1, -1)).ToMPos(map)); + neighbors[(int)Neighbor.TopRight] = cellVisibility((PPos)(cell + new CVec(1, -1)).ToMPos(map)); + neighbors[(int)Neighbor.BottomRight] = cellVisibility((PPos)(cell + new CVec(1, 1)).ToMPos(map)); + neighbors[(int)Neighbor.BottomLeft] = cellVisibility((PPos)(cell + new CVec(-1, 1)).ToMPos(map)); return neighbors; } @@ -314,7 +311,7 @@ void WorldOnRenderPlayerChanged(Player player) else { // Visible under shroud: Explored. Visible under fog: Visible. - cellVisibility = puv => (((IMapCell)map).Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Hidden); + cellVisibility = puv => (map.Contains(puv) ? Shroud.CellVisibility.Visible | Shroud.CellVisibility.Explored : Shroud.CellVisibility.Hidden); } shroud = newShroud; @@ -326,7 +323,7 @@ void WorldOnRenderPlayerChanged(Player player) anyCellDirty = true; var tl = new PPos(0, 0); var br = new PPos(map.MapSize.X - 1, map.MapSize.Y - 1); - UpdateShroud(new ProjectedCellRegion((IMapCell)map, tl, br)); + UpdateShroud(new ProjectedCellRegion(map, tl, br)); } void UpdateShroud(IEnumerable region) @@ -363,7 +360,7 @@ void UpdateShroud(IEnumerable region) void IRenderShroud.RenderShroud(WorldRenderer wr) { - UpdateShroud(((IMapCell)map).ProjectedCells); + UpdateShroud(map.ProjectedCells); fogLayer.Draw(wr.Viewport); shroudLayer.Draw(wr.Viewport); } @@ -371,12 +368,11 @@ void IRenderShroud.RenderShroud(WorldRenderer wr) void UpdateShroudCell(PPos puv) { var uv = (MPos)puv; - var mapCell = (IMapCell)map; cellsDirty[uv] = true; anyCellDirty = true; - var cell = uv.ToCPos(mapCell); + var cell = uv.ToCPos(map); foreach (var direction in CVec.Directions) - if (mapCell.Contains((PPos)(cell + direction).ToMPos((IMapCell)map))) + if (map.Contains((PPos)(cell + direction).ToMPos(map))) cellsDirty[cell + direction] = true; } diff --git a/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs b/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs index ce0b2ce57930..28aae6d86c53 100644 --- a/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs @@ -148,12 +148,12 @@ public void WorldLoaded(World w, WorldRenderer wr) public void AddSmudge(CPos loc) { - if (!((IMapCell)world.Map).Contains(loc)) + if (!world.Map.Contains(loc)) return; if (hasSmoke && Game.CosmeticRandom.Next(0, 100) <= Info.SmokeChance) world.AddFrameEndTask(w => w.Add(new SpriteEffect( - ((IMapCell)w.Map).CenterOfCell(loc), w, Info.SmokeImage, Info.SmokeSequences.Random(w.SharedRandom), Info.SmokePalette))); + w.Map.CenterOfCell(loc), w, Info.SmokeImage, Info.SmokeSequences.Random(w.SharedRandom), Info.SmokePalette))); // A null Sequence indicates a deleted smudge. if ((!dirty.ContainsKey(loc) || dirty[loc].Sequence == null) && !tiles.ContainsKey(loc)) @@ -177,7 +177,7 @@ public void AddSmudge(CPos loc) public void RemoveSmudge(CPos loc) { - if (!((IMapCell)world.Map).Contains(loc)) + if (!world.Map.Contains(loc)) return; var tile = dirty.ContainsKey(loc) ? dirty[loc] : default; diff --git a/OpenRA.Mods.Common/Traits/World/SpawnMapActors.cs b/OpenRA.Mods.Common/Traits/World/SpawnMapActors.cs index 1ecb4dae0234..662e99e498f9 100644 --- a/OpenRA.Mods.Common/Traits/World/SpawnMapActors.cs +++ b/OpenRA.Mods.Common/Traits/World/SpawnMapActors.cs @@ -31,7 +31,7 @@ public void WorldLoaded(World world, WorldRenderer wr) .Concat(world.WorldActor.Owner.PlayerActor.TraitsImplementing()) .ToArray(); - foreach (var kv in world.Map.ActorDefinitions) + foreach (var kv in ((Map)world.Map).ActorDefinitions) { var actorReference = new ActorReference(kv.Value.Value, kv.Value.ToDictionary()); diff --git a/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs b/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs index 8d7eba10d9cc..cbcddaf271e2 100644 --- a/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs +++ b/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs @@ -100,7 +100,7 @@ void SpawnUnitsForPlayer(World w, Player p) if (unitGroup.SupportActors.Length == 0) return; - var supportSpawnCells = ((IMapCell)w.Map).FindTilesInAnnulus(p.HomeLocation, unitGroup.InnerSupportRadius + 1, unitGroup.OuterSupportRadius); + var supportSpawnCells = w.Map.FindTilesInAnnulus(p.HomeLocation, unitGroup.InnerSupportRadius + 1, unitGroup.OuterSupportRadius); foreach (var s in unitGroup.SupportActors) { diff --git a/OpenRA.Mods.Common/Traits/World/SubterraneanActorLayer.cs b/OpenRA.Mods.Common/Traits/World/SubterraneanActorLayer.cs index 2f90c8516cef..62cbac5f9ba2 100644 --- a/OpenRA.Mods.Common/Traits/World/SubterraneanActorLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/SubterraneanActorLayer.cs @@ -39,10 +39,9 @@ public class SubterraneanActorLayer : ICustomMovementLayer public SubterraneanActorLayer(Actor self, SubterraneanActorLayerInfo info) { map = self.World.Map; - var mapCell = (IMapCell)self.World.Map; terrainIndex = self.World.Map.Rules.TerrainInfo.GetTerrainIndex(info.TerrainType); - height = new CellLayer(mapCell); - foreach (var c in mapCell.AllCells) + height = new CellLayer(map); + foreach (var c in map.AllCells) { var neighbourCount = 0; var neighbourHeight = 0; @@ -51,11 +50,11 @@ public SubterraneanActorLayer(Actor self, SubterraneanActorLayerInfo info) for (var dx = -info.SmoothingRadius; dx <= info.SmoothingRadius; dx++) { var neighbour = c + new CVec(dx, dy); - if (!mapCell.AllCells.Contains(neighbour)) + if (!map.AllCells.Contains(neighbour)) continue; neighbourCount++; - neighbourHeight += mapCell.Height[neighbour]; + neighbourHeight += ((IMapElevation)map).Height[neighbour]; } } @@ -70,21 +69,20 @@ public SubterraneanActorLayer(Actor self, SubterraneanActorLayerInfo info) WPos ICustomMovementLayer.CenterOfCell(CPos cell) { - var pos = ((IMapCell)map).CenterOfCell(cell); + var pos = map.CenterOfCell(cell); return pos + new WVec(0, 0, height[cell] - pos.Z); } bool ValidTransitionCell(CPos cell, SubterraneanLocomotorInfo sli) { - var mapCell = (IMapCell)map; - var terrainType = mapCell.GetTerrainInfo(cell).Type; + var terrainType = map.GetTerrainInfo(cell).Type; if (!sli.SubterraneanTransitionTerrainTypes.Contains(terrainType) && sli.SubterraneanTransitionTerrainTypes.Count > 0) return false; if (sli.SubterraneanTransitionOnRamps) return true; - return mapCell.Ramp[cell] == 0; + return ((IMapElevation)map).Ramp[cell] == 0; } short ICustomMovementLayer.EntryMovementCost(LocomotorInfo li, CPos cell) diff --git a/OpenRA.Mods.Common/Traits/World/TerrainGeometryOverlay.cs b/OpenRA.Mods.Common/Traits/World/TerrainGeometryOverlay.cs index a842be56cb48..c712e64d6701 100644 --- a/OpenRA.Mods.Common/Traits/World/TerrainGeometryOverlay.cs +++ b/OpenRA.Mods.Common/Traits/World/TerrainGeometryOverlay.cs @@ -54,18 +54,20 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR if (!Enabled) yield break; - var mapCell = (IMapCell)wr.World.Map; + var map = wr.World.Map; + var mapHeight = ((IMapElevation)map).Height; + var mapRamp = ((IMapElevation)map).Ramp; var colors = wr.World.Map.Rules.TerrainInfo.HeightDebugColors; - var mouseCell = wr.Viewport.ViewToWorld(Viewport.LastMousePos).ToMPos(mapCell); + var mouseCell = wr.Viewport.ViewToWorld(Viewport.LastMousePos).ToMPos(map); foreach (var uv in wr.Viewport.AllVisibleCells.CandidateMapCoords) { - if (!mapCell.Height.Contains(uv) || self.World.ShroudObscures(uv)) + if (!mapHeight.Contains(uv) || self.World.ShroudObscures(uv)) continue; - var height = (int)mapCell.Height[uv]; - var r = mapCell.Grid.Ramps[mapCell.Ramp[uv]]; - var pos = mapCell.CenterOfCell(uv.ToCPos(mapCell)) - new WVec(0, 0, r.CenterHeightOffset); + var height = (int)mapHeight[uv]; + var r = map.Grid.Ramps[mapRamp[uv]]; + var pos = map.CenterOfCell(uv.ToCPos(map)) - new WVec(0, 0, r.CenterHeightOffset); var width = uv == mouseCell ? 3 : 1; // Colors change between points, so render separately @@ -84,10 +86,10 @@ IEnumerable IRenderAnnotations.RenderAnnotations(Actor self, WorldR } // Projected cell coordinates for the current cell - var projectedCorners = mapCell.Grid.Ramps[0].Corners; - foreach (var puv in mapCell.ProjectedCellsCovering(mouseCell)) + var projectedCorners = map.Grid.Ramps[0].Corners; + foreach (var puv in map.ProjectedCellsCovering(mouseCell)) { - var pos = mapCell.CenterOfCell(((MPos)puv).ToCPos(mapCell)); + var pos = map.CenterOfCell(((MPos)puv).ToCPos(map)); for (var i = 0; i < 4; i++) { var j = (i + 1) % 4; diff --git a/OpenRA.Mods.Common/Traits/World/TerrainLighting.cs b/OpenRA.Mods.Common/Traits/World/TerrainLighting.cs index 1c7c3b5ff57c..9a42108fb252 100644 --- a/OpenRA.Mods.Common/Traits/World/TerrainLighting.cs +++ b/OpenRA.Mods.Common/Traits/World/TerrainLighting.cs @@ -68,7 +68,7 @@ public TerrainLighting(World world, TerrainLightingInfo info) map = world.Map; globalTint = new float3(info.RedTint, info.GreenTint, info.BlueTint); - var cellSize = ((IMapCell)map).Grid.Type == MapGridType.RectangularIsometric ? 1448 : 1024; + var cellSize = map.Grid.Type == MapGridType.RectangularIsometric ? 1448 : 1024; partitionedLightSources = new SpatiallyPartitioned( (map.MapSize.X + 1) * cellSize, (map.MapSize.Y + 1) * cellSize, @@ -84,16 +84,15 @@ Rectangle Bounds(LightSource source) public int AddLightSource(WPos pos, WDist range, float intensity, in float3 tint) { - var mapCell = (IMapCell)map; var token = nextLightSourceToken++; - var source = new LightSource(pos, mapCell.CellContaining(pos), range, intensity, tint); + var source = new LightSource(pos, map.CellContaining(pos), range, intensity, tint); var bounds = Bounds(source); lightSources.Add(token, source); partitionedLightSources.Add(source, bounds); if (CellChanged != null) - foreach (var c in (mapCell).FindTilesInCircle(source.Cell, (source.Range.Length + 1023) / 1024)) - CellChanged(c.ToMPos(mapCell)); + foreach (var c in (map).FindTilesInCircle(source.Cell, (source.Range.Length + 1023) / 1024)) + CellChanged(c.ToMPos(map)); return token; } @@ -103,26 +102,25 @@ public void RemoveLightSource(int token) if (!lightSources.TryGetValue(token, out var source)) return; - var mapCell = (IMapCell)map; lightSources.Remove(token); partitionedLightSources.Remove(source); if (CellChanged != null) - foreach (var c in mapCell.FindTilesInCircle(source.Cell, (source.Range.Length + 1023) / 1024)) - CellChanged(c.ToMPos(mapCell)); + foreach (var c in map.FindTilesInCircle(source.Cell, (source.Range.Length + 1023) / 1024)) + CellChanged(c.ToMPos(map)); } float3 ITerrainLighting.TintAt(WPos pos) { - var mapCell = (IMapCell)map; + var mapHeight = ((IMapElevation)map).Height; using (new PerfSample("terrain_lighting")) { - var uv = mapCell.CellContaining(pos).ToMPos(mapCell); + var uv = map.CellContaining(pos).ToMPos(map); var tint = globalTint; - if (!mapCell.Height.Contains(uv)) + if (!mapHeight.Contains(uv)) return tint; - var intensity = info.Intensity + info.HeightStep * mapCell.Height[uv]; + var intensity = info.Intensity + info.HeightStep * mapHeight[uv]; if (lightSources.Count > 0) { foreach (var source in partitionedLightSources.At(new int2(pos.X, pos.Y))) diff --git a/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs b/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs index d2f01b8c470c..ea2dd17f95a3 100644 --- a/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs +++ b/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs @@ -82,17 +82,16 @@ void IWorldLoaded.WorldLoaded(World world, WorldRenderer wr) { worldRenderer = wr; spriteLayer = new TerrainSpriteLayer(world, wr, tileCache.MissingTile, BlendMode.Alpha, world.Type != WorldType.Editor); - var mapCell = (IMapCell)map; - foreach (var cell in mapCell.AllCells) + foreach (var cell in map.AllCells) UpdateCell(cell); - mapCell.Tiles.CellEntryChanged += UpdateCell; - mapCell.Height.CellEntryChanged += UpdateCell; + ((IMapTiles)map).Tiles.CellEntryChanged += UpdateCell; + ((IMapElevation)map).Height.CellEntryChanged += UpdateCell; } public void UpdateCell(CPos cell) { - var tile = ((IMapCell)map).Tiles[cell]; + var tile = ((IMapTiles)map).Tiles[cell]; var palette = terrainInfo.Palette; if (terrainInfo.Templates.TryGetValue(tile.Type, out var template)) palette = ((DefaultTerrainTemplateInfo)template).Palette ?? palette; @@ -115,9 +114,8 @@ void INotifyActorDisposing.Disposing(Actor self) if (disposed) return; - var mapCell = (IMapCell)map; - mapCell.Tiles.CellEntryChanged -= UpdateCell; - mapCell.Height.CellEntryChanged -= UpdateCell; + ((IMapTiles)map).Tiles.CellEntryChanged -= UpdateCell; + ((IMapElevation)map).Height.CellEntryChanged -= UpdateCell; spriteLayer.Dispose(); @@ -134,9 +132,8 @@ Sprite ITiledTerrainRenderer.TileSprite(TerrainTile r, int? variant) Rectangle ITiledTerrainRenderer.TemplateBounds(TerrainTemplateInfo template) { - var mapCell = (IMapCell)map; Rectangle? templateRect = null; - var tileSize = mapCell.Grid.TileSize; + var tileSize = map.Grid.TileSize; var i = 0; for (var y = 0; y < template.Size.Y; y++) @@ -148,8 +145,8 @@ Rectangle ITiledTerrainRenderer.TemplateBounds(TerrainTemplateInfo template) continue; var sprite = tileCache.TileSprite(tile); - var u = mapCell.Grid.Type == MapGridType.Rectangular ? x : (x - y) / 2f; - var v = mapCell.Grid.Type == MapGridType.Rectangular ? y : (x + y) / 2f; + var u = map.Grid.Type == MapGridType.Rectangular ? x : (x - y) / 2f; + var v = map.Grid.Type == MapGridType.Rectangular ? y : (x + y) / 2f; var tl = new float2(u * tileSize.Width, (v - 0.5f * tileInfo.Height) * tileSize.Height) - 0.5f * sprite.Size; var rect = new Rectangle((int)(tl.X + sprite.Offset.X), (int)(tl.Y + sprite.Offset.Y), (int)sprite.Size.X, (int)sprite.Size.Y); @@ -165,9 +162,8 @@ IEnumerable ITiledTerrainRenderer.RenderUIPreview(WorldRenderer wr, if (!(t is DefaultTerrainTemplateInfo template)) yield break; - var mapCell = (IMapCell)map; - var ts = mapCell.Grid.TileSize; - var gridType = mapCell.Grid.Type; + var ts = map.Grid.TileSize; + var gridType = map.Grid.Type; var i = 0; for (var y = 0; y < template.Size.Y; y++) @@ -204,7 +200,7 @@ IEnumerable ITiledTerrainRenderer.RenderPreview(WorldRenderer wr, T continue; var sprite = tileCache.TileSprite(tile, 0); - var offset = ((IMapCell)map).Offset(new CVec(x, y), tileInfo.Height); + var offset = map.Offset(new CVec(x, y), tileInfo.Height); var palette = wr.Palette(template.Palette ?? terrainInfo.Palette); yield return new SpriteRenderable(sprite, origin, offset, 0, palette, 1f, 1f, float3.Ones, TintModifiers.None, false); diff --git a/OpenRA.Mods.Common/Traits/World/TerrainTunnelLayer.cs b/OpenRA.Mods.Common/Traits/World/TerrainTunnelLayer.cs index e47876183457..b497f126759f 100644 --- a/OpenRA.Mods.Common/Traits/World/TerrainTunnelLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/TerrainTunnelLayer.cs @@ -36,15 +36,14 @@ public class TerrainTunnelLayer : ICustomMovementLayer, IWorldLoaded public TerrainTunnelLayer(Actor self, TerrainTunnelLayerInfo info) { map = self.World.Map; - var mapCell = (IMapCell)map; - cellCenters = new CellLayer(mapCell); - terrainIndices = new CellLayer(mapCell); + cellCenters = new CellLayer(map); + terrainIndices = new CellLayer(map); terrainIndices.Clear(map.Rules.TerrainInfo.GetTerrainIndex(info.ImpassableTerrainType)); } public void WorldLoaded(World world, WorldRenderer wr) { - var cellHeight = ((IMapCell)world.Map).CellHeightStep.Length; + var cellHeight = world.Map.CellHeightStep.Length; foreach (var tti in world.WorldActor.Info.TraitInfos()) { enabled = true; @@ -52,10 +51,10 @@ public void WorldLoaded(World world, WorldRenderer wr) var terrain = map.Rules.TerrainInfo.GetTerrainIndex(tti.TerrainType); foreach (var c in tti.TunnelCells()) { - var uv = c.ToMPos((IMapCell)map); + var uv = c.ToMPos(map); terrainIndices[uv] = terrain; - var pos = ((IMapCell)map).CenterOfCell(c); + var pos = map.CenterOfCell(c); cellCenters[uv] = pos - new WVec(0, 0, pos.Z - cellHeight * tti.Height); } diff --git a/OpenRA.Mods.Common/Util.cs b/OpenRA.Mods.Common/Util.cs index b8a2cd2a9d57..1ddab1827a02 100644 --- a/OpenRA.Mods.Common/Util.cs +++ b/OpenRA.Mods.Common/Util.cs @@ -117,12 +117,12 @@ public static bool FacingWithinTolerance(WAngle facing, WAngle desiredFacing, WA public static WPos BetweenCells(World w, CPos from, CPos to) { - var mapCell = (IMapCell)w.Map; + var map = w.Map; - var fromPos = from.Layer == 0 ? mapCell.CenterOfCell(from) : + var fromPos = from.Layer == 0 ? map.CenterOfCell(from) : w.GetCustomMovementLayers()[from.Layer].CenterOfCell(from); - var toPos = to.Layer == 0 ? mapCell.CenterOfCell(to) : + var toPos = to.Layer == 0 ? map.CenterOfCell(to) : w.GetCustomMovementLayers()[to.Layer].CenterOfCell(to); return WPos.Lerp(fromPos, toPos, 1, 2); @@ -189,7 +189,7 @@ public static IEnumerable ExpandFootprint(IEnumerable cells, bool al public static IEnumerable AdjacentCells(World w, in Target target) { - var cells = target.Positions.Select(p => ((IMapCell)w.Map).CellContaining(p)).Distinct(); + var cells = target.Positions.Select(p => w.Map.CellContaining(p)).Distinct(); return ExpandFootprint(cells, true); } diff --git a/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs b/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs index 36a1f4554ea0..1e6c4f064819 100644 --- a/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs +++ b/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs @@ -90,7 +90,7 @@ void IUtilityCommand.Run(Utility utility, string[] args) continue; var testMap = modData.MapLoader.Load(modData, package); - TestMap(testMap, modData); + TestMap((IMap)testMap, modData); } if (errors > 0) @@ -106,8 +106,10 @@ void IUtilityCommand.Run(Utility utility, string[] args) } } - void TestMap(IMap map, ModData modData) + void TestMap(IMap imap, ModData modData) { + var map = (Map)imap; + Console.WriteLine($"Testing map: {map.Title}"); // Lint tests can't be trusted if the map rules are bogus @@ -120,7 +122,7 @@ void TestMap(IMap map, ModData modData) // Run all rule checks on the map if it defines custom rules. if (map.RuleDefinitions != null || map.VoiceDefinitions != null || map.WeaponDefinitions != null) - CheckRules(modData, map.Rules); + CheckRules(modData, imap.Rules); // Run all map-level checks here. foreach (var customMapPassType in modData.ObjectCreator.GetTypesImplementing()) @@ -128,7 +130,7 @@ void TestMap(IMap map, ModData modData) try { var customMapPass = (ILintMapPass)modData.ObjectCreator.CreateBasic(customMapPassType); - customMapPass.Run(EmitError, EmitWarning, modData, map); + customMapPass.Run(EmitError, EmitWarning, modData, imap); } catch (Exception e) { diff --git a/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs b/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs index 144a9cf456c7..cbadc4d6ce1f 100644 --- a/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs @@ -37,7 +37,7 @@ void IUtilityCommand.Run(Utility utility, string[] args) SequenceProvider sequences; var mapPackage = new Folder(Platform.EngineDir).OpenPackage(args[2], modData.ModFiles); if (mapPackage != null) - sequences = modData.MapLoader.Load(modData, mapPackage).Rules.Sequences; + sequences = ((IMap)modData.MapLoader.Load(modData, mapPackage)).Rules.Sequences; else if (!modData.DefaultSequences.TryGetValue(args[2], out sequences)) throw new InvalidOperationException($"{args[2]} is not a valid tileset or map path"); diff --git a/OpenRA.Mods.Common/UtilityCommands/ExtractMapRules.cs b/OpenRA.Mods.Common/UtilityCommands/ExtractMapRules.cs index ce24cf497f75..01c292d56d52 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ExtractMapRules.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ExtractMapRules.cs @@ -32,9 +32,9 @@ void MergeAndPrint(IMap map, string key, MiniYaml value) var files = FieldLoader.GetValue("value", value.Value); foreach (var f in files) { - include |= map.Package.Contains(f); + include |= ((Map)map).Package.Contains(f); if (include) - nodes.AddRange(MiniYaml.FromStream(map.Open(f), f, false)); + nodes.AddRange(MiniYaml.FromStream(((Map)map).Open(f), f, false)); else includes.Add(f); } @@ -53,13 +53,14 @@ void IUtilityCommand.Run(Utility utility, string[] args) var modData = Game.ModData = utility.ModData; var map = modData.MapLoader.Load(modData, new Folder(".").OpenPackage(args[1], modData.ModFiles)); - MergeAndPrint(map, "Rules", map.RuleDefinitions); - MergeAndPrint(map, "Sequences", map.SequenceDefinitions); - MergeAndPrint(map, "ModelSequences", map.ModelSequenceDefinitions); - MergeAndPrint(map, "Weapons", map.WeaponDefinitions); - MergeAndPrint(map, "Voices", map.VoiceDefinitions); - MergeAndPrint(map, "Music", map.MusicDefinitions); - MergeAndPrint(map, "Notifications", map.NotificationDefinitions); + var imap = (IMap)map; + MergeAndPrint(imap, "Rules", map.RuleDefinitions); + MergeAndPrint(imap, "Sequences", map.SequenceDefinitions); + MergeAndPrint(imap, "ModelSequences", map.ModelSequenceDefinitions); + MergeAndPrint(imap, "Weapons", map.WeaponDefinitions); + MergeAndPrint(imap, "Voices", map.VoiceDefinitions); + MergeAndPrint(imap, "Music", map.MusicDefinitions); + MergeAndPrint(imap, "Notifications", map.NotificationDefinitions); } } } diff --git a/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs index 459daa897433..8324259fcf1c 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs @@ -77,7 +77,7 @@ protected void Run(Utility utility, string[] args) RequiresMod = ModData.Manifest.Id }; - SetBounds((IMapCell)Map, mapSection); + SetBounds((IMap)Map, mapSection); ReadPacks(file, filename); ReadTrees(file); @@ -93,15 +93,15 @@ protected void Run(Utility utility, string[] args) LoadWaypoints(waypoints); // Create default player definitions only if there are no players to import - MapPlayers = new MapPlayers(Map.Rules, Players.Count == 0 ? spawnCount : 0); + MapPlayers = new MapPlayers(((IMap)Map).Rules, Players.Count == 0 ? spawnCount : 0); foreach (var p in Players) LoadPlayer(file, p); Map.PlayerDefinitions = MapPlayers.ToMiniYaml(); } - if (Map.Rules.TerrainInfo is ITerrainInfoNotifyMapCreated notifyMapCreated) - notifyMapCreated.MapCreated(Map); + if (((IMap)Map).Rules.TerrainInfo is ITerrainInfoNotifyMapCreated notifyMapCreated) + notifyMapCreated.MapCreated((IMap)Map); var dest = Path.GetFileNameWithoutExtension(args[1]) + ".oramap"; @@ -159,7 +159,7 @@ void LoadBriefing(IniFile file) missionData.Value.Nodes.Add(new MiniYamlNode("Briefing", briefing.Replace("\n", " ").ToString())); } - static void SetBounds(IMapCell map, IniSection mapSection) + static void SetBounds(IMap map, IniSection mapSection) { var offsetX = Exts.ParseIntegerInvariant(mapSection.GetValue("X", "0")); var offsetY = Exts.ParseIntegerInvariant(mapSection.GetValue("Y", "0")); @@ -223,9 +223,9 @@ void LoadVideos(IniFile file, string section) public virtual void ReadActors(IniFile file) { - LoadActors(file, "STRUCTURES", Players, Map); - LoadActors(file, "UNITS", Players, Map); - LoadActors(file, "INFANTRY", Players, Map); + LoadActors(file, "STRUCTURES", Players, (IMap)Map); + LoadActors(file, "UNITS", Players, (IMap)Map); + LoadActors(file, "INFANTRY", Players, (IMap)Map); } public abstract void LoadPlayer(IniFile file, string section); @@ -415,12 +415,12 @@ public void LoadActors(IniFile file, string section, List players, IMap if (section == "INFANTRY") actor.Add(new SubCellInit((SubCell)Exts.ParseByte(parts[4]))); - var actorCount = map.ActorDefinitions.Count; + var actorCount = ((Map)map).ActorDefinitions.Count; if (!map.Rules.Actors.ContainsKey(parts[1].ToLowerInvariant())) Console.WriteLine($"Ignoring unknown actor type: `{parts[1].ToLowerInvariant()}`"); else - map.ActorDefinitions.Add(new MiniYamlNode("Actor" + actorCount++, actor.Save())); + ((Map)map).ActorDefinitions.Add(new MiniYamlNode("Actor" + actorCount++, actor.Save())); } catch (Exception) { diff --git a/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs index fc356612160e..cb256e6e1a59 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs @@ -48,9 +48,10 @@ bool IUtilityCommand.ValidateArguments(string[] args) void IUtilityCommand.Run(Utility utility, string[] args) { var modData = Game.ModData = utility.ModData; - map = (Map)modData.MapLoader.Load(modData, new Folder(Platform.EngineDir).OpenPackage(args[1], modData.ModFiles)); - Console.WriteLine("Resizing map {0} from {1} to {2},{3}", map.Title, map.MapSize, width, height); - ((IMapCell)map).Resize(width, height); + map = modData.MapLoader.Load(modData, new Folder(Platform.EngineDir).OpenPackage(args[1], modData.ModFiles)); + var imap = (IMap)map; + Console.WriteLine("Resizing map {0} from {1} to {2},{3}", map.Title, imap.MapSize, width, height); + imap.Resize(width, height); var forRemoval = new List(); @@ -61,7 +62,7 @@ void IUtilityCommand.Run(Utility utility, string[] args) if (locationInit == null) continue; - if (!((IMapCell)map).Contains(locationInit.Value)) + if (!((IMap)map).Contains(locationInit.Value)) { Console.WriteLine($"Removing actor {actor.Type} located at {locationInit.Value} due being outside of the new map boundaries."); forRemoval.Add(kv); diff --git a/OpenRA.Mods.Common/UtilityCommands/Utilities.cs b/OpenRA.Mods.Common/UtilityCommands/Utilities.cs index d9ca209d915f..c56a0ed0e22d 100644 --- a/OpenRA.Mods.Common/UtilityCommands/Utilities.cs +++ b/OpenRA.Mods.Common/UtilityCommands/Utilities.cs @@ -32,8 +32,8 @@ public static class Utilities { try { - // TO DO: Make this use IMap instead of Map - map = (Map)modData.MapLoader.Load(modData, new Folder(Platform.EngineDir).OpenPackage(mapPath, modData.ModFiles)); + // TODO: Make this use IMap instead of Map + map = modData.MapLoader.Load(modData, new Folder(Platform.EngineDir).OpenPackage(mapPath, modData.ModFiles)); } catch (InvalidDataException ex) { diff --git a/OpenRA.Mods.Common/Warheads/CreateEffectWarhead.cs b/OpenRA.Mods.Common/Warheads/CreateEffectWarhead.cs index 2f339e4dd9c7..70c79990598d 100644 --- a/OpenRA.Mods.Common/Warheads/CreateEffectWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/CreateEffectWarhead.cs @@ -119,7 +119,7 @@ public override void DoImpact(in Target target, WarheadArgs args) if (ForceDisplayAtGroundLevel) { - var dat = ((IMapCell)world.Map).DistanceAboveTerrain(pos); + var dat = world.Map.DistanceAboveTerrain(pos); pos -= new WVec(0, 0, dat.Length); } @@ -138,13 +138,13 @@ public override void DoImpact(in Target target, WarheadArgs args) /// Checks if the warhead is valid against the terrain at impact position. bool IsValidAgainstTerrain(World world, WPos pos) { - var mapCell = (IMapCell)world.Map; - var cell = mapCell.CellContaining(pos); - if (!mapCell.Contains(cell)) + var map = world.Map; + var cell = map.CellContaining(pos); + if (!map.Contains(cell)) return false; - var dat = mapCell.DistanceAboveTerrain(pos); - return IsValidTarget(dat > AirThreshold ? TargetTypeAir : mapCell.GetTerrainInfo(cell).TargetTypes); + var dat = map.DistanceAboveTerrain(pos); + return IsValidTarget(dat > AirThreshold ? TargetTypeAir : map.GetTerrainInfo(cell).TargetTypes); } } } diff --git a/OpenRA.Mods.Common/Warheads/CreateResourceWarhead.cs b/OpenRA.Mods.Common/Warheads/CreateResourceWarhead.cs index ff1b69e05f45..2ad67671c939 100644 --- a/OpenRA.Mods.Common/Warheads/CreateResourceWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/CreateResourceWarhead.cs @@ -34,15 +34,15 @@ public override void DoImpact(in Target target, WarheadArgs args) var firedBy = args.SourceActor; var pos = target.CenterPosition; var world = firedBy.World; - var mapCell = (IMapCell)world.Map; - var dat = mapCell.DistanceAboveTerrain(pos); + var map = world.Map; + var dat = map.DistanceAboveTerrain(pos); if (dat > AirThreshold) return; - var targetTile = mapCell.CellContaining(pos); + var targetTile = map.CellContaining(pos); var minRange = (Size.Length > 1 && Size[1] > 0) ? Size[1] : 0; - var allCells = mapCell.FindTilesInAnnulus(targetTile, minRange, Size[0]); + var allCells = map.FindTilesInAnnulus(targetTile, minRange, Size[0]); var resourceLayer = world.WorldActor.Trait(); var maxDensity = resourceLayer.GetMaxDensity(AddsResourceType); diff --git a/OpenRA.Mods.Common/Warheads/DestroyResourceWarhead.cs b/OpenRA.Mods.Common/Warheads/DestroyResourceWarhead.cs index e0d0f974d827..f799ace23bcd 100644 --- a/OpenRA.Mods.Common/Warheads/DestroyResourceWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/DestroyResourceWarhead.cs @@ -30,23 +30,22 @@ public class DestroyResourceWarhead : Warhead public override void DoImpact(in Target target, WarheadArgs args) { - if (target.Type == TargetType.Invalid) return; var firedBy = args.SourceActor; var pos = target.CenterPosition; var world = firedBy.World; - var mapCell = (IMapCell)world.Map; - var dat = mapCell.DistanceAboveTerrain(pos); + var map = world.Map; + var dat = map.DistanceAboveTerrain(pos); if (dat > AirThreshold) return; - var targetTile = mapCell.CellContaining(pos); + var targetTile = map.CellContaining(pos); var resourceLayer = world.WorldActor.Trait(); var minRange = (Size.Length > 1 && Size[1] > 0) ? Size[1] : 0; - var allCells = mapCell.FindTilesInAnnulus(targetTile, minRange, Size[0]); + var allCells = map.FindTilesInAnnulus(targetTile, minRange, Size[0]); var removeAllTypes = ResourceTypes.Count == 0; diff --git a/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs b/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs index 14c4123c2e18..86abcb28f251 100644 --- a/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs @@ -52,7 +52,7 @@ public override void DoImpact(in Target target, WarheadArgs args) var firedBy = args.SourceActor; var map = firedBy.World.Map; - var targetCell = ((IMapCell)map).CellContaining(target.CenterPosition); + var targetCell = map.CellContaining(target.CenterPosition); var targetCells = CellsMatching(targetCell, false); foreach (var c in targetCells) @@ -75,13 +75,11 @@ void FireProjectileAtCell(IMap map, Actor firedBy, Target target, CPos targetCel if (!weapon.IsValidAgainst(tc, firedBy.World, firedBy)) return; - var mapCell = (IMapCell)map; - var projectileArgs = new ProjectileArgs { Weapon = weapon, - Facing = (mapCell.CenterOfCell(targetCell) - target.CenterPosition).Yaw, - CurrentMuzzleFacing = () => (mapCell.CenterOfCell(targetCell) - target.CenterPosition).Yaw, + Facing = (map.CenterOfCell(targetCell) - target.CenterPosition).Yaw, + CurrentMuzzleFacing = () => (map.CenterOfCell(targetCell) - target.CenterPosition).Yaw, DamageModifiers = args.DamageModifiers, InaccuracyModifiers = Array.Empty(), @@ -90,7 +88,7 @@ void FireProjectileAtCell(IMap map, Actor firedBy, Target target, CPos targetCel Source = target.CenterPosition, CurrentSource = () => target.CenterPosition, SourceActor = firedBy, - PassiveTarget = mapCell.CenterOfCell(targetCell), + PassiveTarget = map.CenterOfCell(targetCell), GuidedTarget = tc }; diff --git a/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs b/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs index 9df550e95e17..84821078d2e1 100644 --- a/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs @@ -37,27 +37,27 @@ public override void DoImpact(in Target target, WarheadArgs args) var firedBy = args.SourceActor; var world = firedBy.World; - var mapCell = (IMapCell)world.Map; + var map = world.Map; if (Chance < world.LocalRandom.Next(100)) return; var pos = target.CenterPosition; - var dat = mapCell.DistanceAboveTerrain(pos); + var dat = map.DistanceAboveTerrain(pos); if (dat > AirThreshold) return; - var targetTile = mapCell.CellContaining(pos); + var targetTile = map.CellContaining(pos); var smudgeLayers = world.WorldActor.TraitsImplementing().ToDictionary(x => x.Info.Type); var minRange = (Size.Length > 1 && Size[1] > 0) ? Size[1] : 0; - var allCells = mapCell.FindTilesInAnnulus(targetTile, minRange, Size[0]); + var allCells = map.FindTilesInAnnulus(targetTile, minRange, Size[0]); // Draw the smudges: foreach (var sc in allCells) { - var smudgeType = mapCell.GetTerrainInfo(sc).AcceptsSmudgeType.FirstOrDefault(SmudgeType.Contains); + var smudgeType = map.GetTerrainInfo(sc).AcceptsSmudgeType.FirstOrDefault(SmudgeType.Contains); if (smudgeType == null) continue; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Editor/LayerSelectorLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Editor/LayerSelectorLogic.cs index f59a956a2682..aa7d64cd1144 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Editor/LayerSelectorLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Editor/LayerSelectorLogic.cs @@ -41,11 +41,8 @@ public LayerSelectorLogic(Widget widget, WorldRenderer worldRenderer) void IntializeLayerPreview() { layerTemplateList.RemoveChildren(); -<<<<<<< HEAD -======= var rules = worldRenderer.World.Map.Rules; - var tileSize = ((IMapCell)worldRenderer.World.Map).Grid.TileSize; ->>>>>>> c55e45a04a (Moved Grid, Tileset, and ReplacedInvalidTerrainTiles from IMap to IMapCell) + var tileSize = worldRenderer.World.Map.Grid.TileSize; foreach (var resourceRenderer in worldRenderer.World.WorldActor.TraitsImplementing()) { foreach (var resourceType in resourceRenderer.ResourceTypes) diff --git a/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs index d14dff63d870..c0f36c1b369d 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs @@ -47,8 +47,9 @@ public MapEditorLogic(Widget widget, World world, WorldRenderer worldRenderer) coordinateLabel.GetText = () => { var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos); - var mapCell = (IMapCell)worldRenderer.World.Map; - return mapCell.Height.Contains(cell) ? $"{cell},{mapCell.Height[cell]} ({mapCell.Tiles[cell].Type})" : ""; + var mapHeight = ((IMapElevation)worldRenderer.World.Map).Height; + var mapTiles = ((IMapTiles)worldRenderer.World.Map).Tiles; + return mapHeight.Contains(cell) ? $"{cell},{mapHeight[cell]} ({mapTiles[cell].Type})" : ""; }; } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Editor/NewMapLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Editor/NewMapLogic.cs index 89a4da3e0628..0bf39103af7c 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Editor/NewMapLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Editor/NewMapLogic.cs @@ -55,18 +55,19 @@ public NewMapLogic(Action onExit, Action onSelect, Widget widget, World width = Math.Max(2, width); height = Math.Max(2, height); - var maxTerrainHeight = ((IMapCell)world.Map).Grid.MaximumTerrainHeight; + var maxTerrainHeight = world.Map.Grid.MaximumTerrainHeight; var tileset = modData.DefaultTerrainInfo[tilesetDropDown.Text]; var map = Game.ModData.MapLoader.Create(Game.ModData, tileset, width + 2, height + maxTerrainHeight + 2); + var imap = (IMap)map; var tl = new PPos(1, 1 + maxTerrainHeight); var br = new PPos(width, height + maxTerrainHeight); - ((IMapCell)map).SetBounds(tl, br); + imap.SetBounds(tl, br); - map.PlayerDefinitions = new MapPlayers(map.Rules, 0).ToMiniYaml(); + map.PlayerDefinitions = new MapPlayers(imap.Rules, 0).ToMiniYaml(); - if (map.Rules.TerrainInfo is ITerrainInfoNotifyMapCreated notifyMapCreated) - notifyMapCreated.MapCreated(map); + if (imap.Rules.TerrainInfo is ITerrainInfoNotifyMapCreated notifyMapCreated) + notifyMapCreated.MapCreated(imap); Action afterSave = uid => { diff --git a/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs index 8a0698cb915f..bb5fcd2510c3 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs @@ -101,14 +101,14 @@ public GameSaveBrowserLogic(Widget widget, ModData modData, Action onExit, Actio { panel.Get("SAVE_TITLE").IsVisible = () => true; - defaultSaveFilename = world.Map.Title; + defaultSaveFilename = ((Map)world.Map).Title; var filenameAttempt = 0; while (true) { if (!File.Exists(Path.Combine(baseSavePath, defaultSaveFilename + ".orasav"))) break; - defaultSaveFilename = world.Map.Title + $" ({++filenameAttempt})"; + defaultSaveFilename = ((Map)world.Map).Title + $" ({++filenameAttempt})"; } var saveButton = panel.Get("SAVE_BUTTON"); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs index 78181d38fdb9..67d0ad3b611b 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs @@ -28,9 +28,10 @@ public DebugLogic(Widget widget, World world, WorldRenderer worldRenderer) var cellPosText = new CachedTransform(t => { var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos); - var mapCell = (IMapCell)worldRenderer.World.Map; - var wpos = mapCell.CenterOfCell(cell); - return mapCell.Height.Contains(cell) ? $"({cell},{mapCell.Height[cell]}) ({wpos})" : ""; + var map = worldRenderer.World.Map; + var mapHeight = ((IMapElevation)map).Height; + var wpos = map.CenterOfCell(cell); + return mapHeight.Contains(cell) ? $"({cell},{mapHeight[cell]}) ({wpos})" : ""; }); labelWidget.GetText = () => cellPosText.Update(Viewport.LastMousePos); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoBriefingLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoBriefingLogic.cs index bcd24806494c..67cbb36589b0 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoBriefingLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoBriefingLogic.cs @@ -20,7 +20,7 @@ class GameInfoBriefingLogic : ChromeLogic public GameInfoBriefingLogic(Widget widget, ModData modData, World world) { var previewWidget = widget.Get("MAP_PREVIEW"); - previewWidget.Preview = () => modData.MapCache[world.Map.Uid]; + previewWidget.Preview = () => modData.MapCache[((Map)world.Map).Uid]; var mapDescriptionPanel = widget.Get("MAP_DESCRIPTION_PANEL"); var mapDescription = widget.Get("MAP_DESCRIPTION"); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoLogic.cs index ea2ee12f260b..8f6d6409c10d 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoLogic.cs @@ -127,8 +127,8 @@ public GameInfoLogic(Widget widget, ModData modData, World world, IngameInfoPane var titleText = widget.Get("TITLE"); - var mapTitle = world.Map.Title; - var firstCategory = world.Map.Categories.FirstOrDefault(); + var mapTitle = ((Map)world.Map).Title; + var firstCategory = ((Map)world.Map).Categories.FirstOrDefault(); if (firstCategory != null) mapTitle = firstCategory + ": " + mapTitle; @@ -153,7 +153,7 @@ void SetupLobbyOptionsPanel(ButtonWidget mapTabButton, Widget optionsPanelContai { Game.LoadWidget(world, "LOBBY_OPTIONS_PANEL", optionsPanelContainer, new WidgetArgs() { - { "getMap", (Func)(() => modData.MapCache[world.Map.Uid]) }, + { "getMap", (Func)(() => modData.MapCache[((Map)world.Map).Uid]) }, { "configurationDisabled", (Func)(() => true) } }); } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/Hotkeys/EditorQuickSaveHotkeyLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/Hotkeys/EditorQuickSaveHotkeyLogic.cs index 599d06621e16..bfd0062e006f 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/Hotkeys/EditorQuickSaveHotkeyLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/Hotkeys/EditorQuickSaveHotkeyLogic.cs @@ -45,17 +45,17 @@ protected override bool OnHotkeyActivated(KeyInput keyInput) var actorDefinitions = editorActorLayer.Save(); if (actorDefinitions != null) - map.ActorDefinitions = actorDefinitions; + ((Map)map).ActorDefinitions = actorDefinitions; var playerDefinitions = editorActorLayer.Players.ToMiniYaml(); if (playerDefinitions != null) - map.PlayerDefinitions = playerDefinitions; + ((Map)map).PlayerDefinitions = playerDefinitions; - var package = (IReadWritePackage)map.Package; - SaveMapLogic.SaveMapInner(map, package, world, modData); + var package = (IReadWritePackage)((Map)map).Package; + SaveMapLogic.SaveMapInner((Map)map, package, world, modData); }; - SaveMapLogic.SaveMap(modData, world, map, map.Package?.Name, saveMap); + SaveMapLogic.SaveMap(modData, world, (Map)map, ((Map)map).Package?.Name, saveMap); return true; } } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameMenuLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameMenuLogic.cs index 19f8a8415034..4271b073fb0d 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameMenuLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameMenuLogic.cs @@ -490,7 +490,7 @@ void CreateExitEditorButton() // Show dialog only if updated since last save button.OnClick = () => { - var map = modData.MapCache.GetUpdatedMap(world.Map.Uid); + var map = modData.MapCache.GetUpdatedMap(((Map)world.Map).Uid); var deletedOrUnavailable = map == null || modData.MapCache[map].Status != MapStatus.Available; if (actionManager.HasUnsavedItems() || deletedOrUnavailable) { diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs index 04ad728aa82d..6c041cc9d207 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs @@ -100,7 +100,7 @@ public ObserverShroudSelectorLogic(Widget widget, ModData modData, World world, if (logicArgs.TryGetValue("WorldViewKey", out yaml)) worldViewKey = modData.Hotkeys[yaml.Value]; - limitViews = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector); + limitViews = ((Map)world.Map).Visibility.HasFlag(MapVisibility.MissionSelector); var groups = new Dictionary>(); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverStatsLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverStatsLogic.cs index f0853f1868e4..626f46a7a759 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverStatsLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverStatsLogic.cs @@ -578,7 +578,7 @@ string AverageOrdersPerMinute(double orders) string Vision(int revealedCells) { - return Math.Ceiling(revealedCells / (float)((IMapCell)world.Map).ProjectedCells.Length * 100).ToString("F0") + "%"; + return Math.Ceiling(revealedCells / (float)world.Map.ProjectedCells.Length * 100).ToString("F0") + "%"; } static Color GetPowerColor(PowerState state) diff --git a/OpenRA.Mods.Common/Widgets/RadarWidget.cs b/OpenRA.Mods.Common/Widgets/RadarWidget.cs index d0823e71c4b8..9bc377b1f13b 100644 --- a/OpenRA.Mods.Common/Widgets/RadarWidget.cs +++ b/OpenRA.Mods.Common/Widgets/RadarWidget.cs @@ -74,7 +74,7 @@ public RadarWidget(World world, WorldRenderer worldRenderer) radarPings = world.WorldActor.TraitOrDefault(); radarTerrainLayers = world.WorldActor.TraitsImplementing().ToArray(); - isRectangularIsometric = ((IMapCell)world.Map).Grid.Type == MapGridType.RectangularIsometric; + isRectangularIsometric = world.Map.Grid.Type == MapGridType.RectangularIsometric; cellWidth = isRectangularIsometric ? 2 : 1; previewWidth = world.Map.MapSize.X; previewHeight = world.Map.MapSize.Y; @@ -89,7 +89,7 @@ void CellTerrainColorChanged(MPos uv) void CellTerrainColorChanged(CPos cell) { - UpdateTerrainColor(cell.ToMPos((IMapCell)world.Map)); + UpdateTerrainColor(cell.ToMPos(world.Map)); } public override void Initialize(WidgetArgs args) @@ -109,7 +109,7 @@ public override void Initialize(WidgetArgs args) if (player == null) { // Set initial terrain data - foreach (var uv in ((IMapCell)world.Map).AllCells.MapCoords) + foreach (var uv in world.Map.AllCells.MapCoords) UpdateTerrainColor(uv); } @@ -121,7 +121,7 @@ void WorldOnRenderPlayerChanged(Player player) SetPlayer(player); // Set initial terrain data - foreach (var uv in ((IMapCell)world.Map).AllCells.MapCoords) + foreach (var uv in world.Map.AllCells.MapCoords) UpdateTerrainColor(uv); } @@ -139,7 +139,7 @@ void SetPlayer(Player player, bool forceUpdate = false) if (newShroud != null) { newShroud.OnShroudChanged += UpdateShroudCell; - foreach (var puv in ((IMapCell)world.Map).ProjectedCells) + foreach (var puv in world.Map.ProjectedCells) UpdateShroudCell(puv); } @@ -155,7 +155,7 @@ void SetPlayer(Player player, bool forceUpdate = false) playerRadarTerrain.CellTerrainColorChanged -= CellTerrainColorChanged; else { - ((IMapCell)world.Map).Tiles.CellEntryChanged -= CellTerrainColorChanged; + ((IMapTiles)world.Map).Tiles.CellEntryChanged -= CellTerrainColorChanged; foreach (var rtl in radarTerrainLayers) rtl.CellEntryChanged -= CellTerrainColorChanged; } @@ -164,7 +164,7 @@ void SetPlayer(Player player, bool forceUpdate = false) newPlayerRadarTerrain.CellTerrainColorChanged += CellTerrainColorChanged; else { - ((IMapCell)world.Map).Tiles.CellEntryChanged += CellTerrainColorChanged; + ((IMapTiles)world.Map).Tiles.CellEntryChanged += CellTerrainColorChanged; foreach (var rtl in radarTerrainLayers) rtl.CellEntryChanged += CellTerrainColorChanged; } @@ -176,7 +176,6 @@ void SetPlayer(Player player, bool forceUpdate = false) void MapBoundsChanged() { var map = world.Map; - var mapCell = (IMapCell)map; // The minimap is drawn in cell space, so we need to // unproject the bounds to find the extent of the map. @@ -197,8 +196,8 @@ void MapBoundsChanged() // This happens when the map tile is outside the map projected space, // e.g. if a tile on the bottom edge has a height > 0. // Guard against this by using the map bounds as a fallback. - var allTop = mapCell.Unproject(new PPos(x, projectedTop)); - var allBottom = mapCell.Unproject(new PPos(x, projectedBottom)); + var allTop = map.Unproject(new PPos(x, projectedTop)); + var allBottom = map.Unproject(new PPos(x, projectedBottom)); if (allTop.Count > 0) top = Math.Min(top, allTop.MinBy(uv => uv.V).V); @@ -267,7 +266,7 @@ void UpdateShroudCell(PPos puv) fixed (byte* colorBytes = &radarData[0]) { var colors = (int*)colorBytes; - foreach (var iuv in ((IMapCell)world.Map).Unproject(puv)) + foreach (var iuv in world.Map.Unproject(puv)) { if (isRectangularIsometric) { @@ -292,7 +291,7 @@ public override string GetCursor(int2 pos) return null; var cell = MinimapPixelToCell(pos); - var worldPixel = worldRenderer.ScreenPxPosition(((IMapCell)world.Map).CenterOfCell(cell)); + var worldPixel = worldRenderer.ScreenPxPosition(world.Map.CenterOfCell(cell)); var location = worldRenderer.Viewport.WorldToViewPx(worldPixel); var mi = new MouseInput @@ -318,7 +317,7 @@ public override bool HandleMouseInput(MouseInput mi) return true; var cell = MinimapPixelToCell(mi.Location); - var pos = ((IMapCell)world.Map).CenterOfCell(cell); + var pos = world.Map.CenterOfCell(cell); if ((mi.Event == MouseInputEvent.Down || mi.Event == MouseInputEvent.Move) && mi.Button == Game.Settings.Game.MouseButtonPreference.Cancel) { @@ -365,13 +364,13 @@ public override void Draw() if (shroud != null) WidgetUtils.DrawSprite(shroudSprite, o, s); - var mapCell = (IMapCell)world.Map; + var map = world.Map; // Draw viewport rect if (hasRadar) { - var tl = CellToMinimapPixel(mapCell.CellContaining(worldRenderer.ProjectedPosition(worldRenderer.Viewport.TopLeft))); - var br = CellToMinimapPixel(mapCell.CellContaining(worldRenderer.ProjectedPosition(worldRenderer.Viewport.BottomRight))); + var tl = CellToMinimapPixel(map.CellContaining(worldRenderer.ProjectedPosition(worldRenderer.Viewport.TopLeft))); + var br = CellToMinimapPixel(map.CellContaining(worldRenderer.ProjectedPosition(worldRenderer.Viewport.BottomRight))); Game.Renderer.EnableScissor(mapRect); DrawRadarPings(); @@ -388,7 +387,7 @@ void DrawRadarPings() foreach (var radarPing in radarPings.Pings.Where(e => e.IsVisible())) { var c = radarPing.Color; - var pingCell = ((IMapCell)world.Map).CellContaining(radarPing.Position); + var pingCell = world.Map.CellContaining(radarPing.Position); var points = radarPing.Points(CellToMinimapPixel(pingCell)).ToArray(); Game.Renderer.RgbaColorRenderer.DrawPolygon(points, 2, c); } @@ -425,10 +424,10 @@ public override void Tick() t.Trait.PopulateRadarSignatureCells(t.Actor, cells); foreach (var cell in cells) { - if (!((IMapCell)world.Map).Contains(cell.Cell)) + if (!((IMapTiles)world.Map).Tiles.Contains(cell.Cell)) continue; - var uv = cell.Cell.ToMPos(((IMapCell)world.Map).Grid.Type); + var uv = cell.Cell.ToMPos(world.Map.Grid.Type); var color = cell.Color.ToArgb(); if (isRectangularIsometric) { @@ -474,7 +473,7 @@ public override void Tick() int2 CellToMinimapPixel(CPos p) { - var uv = p.ToMPos((IMapCell)world.Map); + var uv = p.ToMPos(world.Map); var dx = (int)(previewScale * cellWidth * (uv.U - world.Map.Bounds.Left)); var dy = (int)(previewScale * (uv.V - world.Map.Bounds.Top)); @@ -489,7 +488,7 @@ CPos MinimapPixelToCell(int2 p) { var u = (int)((p.X - mapRect.X) / (previewScale * cellWidth)) + world.Map.Bounds.Left; var v = (int)((p.Y - mapRect.Y) / previewScale) + world.Map.Bounds.Top; - return new MPos(u, v).ToCPos((IMapCell)world.Map); + return new MPos(u, v).ToCPos(world.Map); } public override void Removed() diff --git a/OpenRA.Mods.Common/Widgets/ResourcePreviewWidget.cs b/OpenRA.Mods.Common/Widgets/ResourcePreviewWidget.cs index 7dff62bace4a..e02d369e0103 100644 --- a/OpenRA.Mods.Common/Widgets/ResourcePreviewWidget.cs +++ b/OpenRA.Mods.Common/Widgets/ResourcePreviewWidget.cs @@ -52,7 +52,7 @@ public ResourcePreviewWidget(ModData modData, WorldRenderer worldRenderer, World this.worldRenderer = worldRenderer; viewportSizes = modData.Manifest.Get(); resourceRenderers = world.WorldActor.TraitsImplementing().ToArray(); - tileSize = ((IMapCell)world.Map).Grid.TileSize; + tileSize = world.Map.Grid.TileSize; IdealPreviewSize = new Size( (int)(viewportSizes.DefaultScale * tileSize.Width), (int)(viewportSizes.DefaultScale * tileSize.Height)); diff --git a/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs b/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs index 89bb78671216..bea1a22da665 100644 --- a/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs +++ b/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs @@ -224,7 +224,7 @@ public void UpdateMouseover() ActorTooltipExtra = null; var modifiers = Game.GetModifierKeys(); var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos); - if (!((IMapCell)world.Map).Contains(cell)) + if (!world.Map.Contains(cell)) return; if (world.ShroudObscures(cell)) @@ -440,7 +440,7 @@ public override bool HandleKeyPress(KeyInput e) if (JumpToBottomEdgeKey.IsActivatedBy(e)) { - worldRenderer.Viewport.Center(new WPos(worldRenderer.Viewport.CenterPosition.X, ((IMapCell)worldRenderer.World.Map).ProjectedBottomRight.Y, 0)); + worldRenderer.Viewport.Center(new WPos(worldRenderer.Viewport.CenterPosition.X, worldRenderer.World.Map.ProjectedBottomRight.Y, 0)); return true; } @@ -452,7 +452,7 @@ public override bool HandleKeyPress(KeyInput e) if (JumpToRightEdgeKey.IsActivatedBy(e)) { - worldRenderer.Viewport.Center(new WPos(((IMapCell)worldRenderer.World.Map).ProjectedBottomRight.X, worldRenderer.Viewport.CenterPosition.Y, 0)); + worldRenderer.Viewport.Center(new WPos(worldRenderer.World.Map.ProjectedBottomRight.X, worldRenderer.Viewport.CenterPosition.Y, 0)); return true; } diff --git a/OpenRA.Mods.D2k/Traits/Buildings/D2kActorPreviewPlaceBuildingPreview.cs b/OpenRA.Mods.D2k/Traits/Buildings/D2kActorPreviewPlaceBuildingPreview.cs index 33ecb951f6c7..26ff7b8d3c8c 100644 --- a/OpenRA.Mods.D2k/Traits/Buildings/D2kActorPreviewPlaceBuildingPreview.cs +++ b/OpenRA.Mods.D2k/Traits/Buildings/D2kActorPreviewPlaceBuildingPreview.cs @@ -96,9 +96,9 @@ public D2kActorPreviewPlaceBuildingPreviewPreview(WorldRenderer wr, ActorInfo ai protected override IEnumerable RenderFootprint(WorldRenderer wr, CPos topLeft, Dictionary footprint, PlaceBuildingCellType filter = PlaceBuildingCellType.Invalid | PlaceBuildingCellType.Valid | PlaceBuildingCellType.LineBuild) { - var mapCell = (IMapCell)wr.World.Map; + var map = wr.World.Map; var palette = wr.Palette(info.Palette); - var topLeftPos = mapCell.CenterOfCell(topLeft); + var topLeftPos = map.CenterOfCell(topLeft); var candidateSafeTiles = unpathableCells.Update(topLeft); foreach (var c in footprint) @@ -106,11 +106,11 @@ public D2kActorPreviewPlaceBuildingPreviewPreview(WorldRenderer wr, ActorInfo ai if ((c.Value & filter) == 0) continue; - var isUnsafe = checkUnsafeTiles && mapCell.Contains(c.Key) && candidateSafeTiles.Contains(c.Key) && info.UnsafeTerrainTypes.Contains(mapCell.GetTerrainInfo(c.Key).Type); + var isUnsafe = checkUnsafeTiles && map.Contains(c.Key) && candidateSafeTiles.Contains(c.Key) && info.UnsafeTerrainTypes.Contains(map.GetTerrainInfo(c.Key).Type); var tile = (c.Value & PlaceBuildingCellType.Invalid) != 0 ? blockedTile : isUnsafe ? unsafeTile : validTile; var sequenceAlpha = (c.Value & PlaceBuildingCellType.Invalid) != 0 ? blockedAlpha : isUnsafe ? unsafeAlpha : validAlpha; - var pos = mapCell.CenterOfCell(c.Key); + var pos = map.CenterOfCell(c.Key); var offset = new WVec(0, 0, topLeftPos.Z - pos.Z); var traitAlpha = (c.Value & PlaceBuildingCellType.LineBuild) != 0 ? info.LineBuildFootprintAlpha : info.FootprintAlpha; yield return new SpriteRenderable(tile, pos, offset, -511, palette, 1f, sequenceAlpha * traitAlpha, float3.Ones, TintModifiers.IgnoreWorldTint, true); diff --git a/OpenRA.Mods.D2k/Traits/Buildings/D2kBuilding.cs b/OpenRA.Mods.D2k/Traits/Buildings/D2kBuilding.cs index a973f97b8008..f1a9f4ff84c3 100644 --- a/OpenRA.Mods.D2k/Traits/Buildings/D2kBuilding.cs +++ b/OpenRA.Mods.D2k/Traits/Buildings/D2kBuilding.cs @@ -79,7 +79,7 @@ void INotifyCreated.Created(Actor self) protected override void AddedToWorld(Actor self) { base.AddedToWorld(self); - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; if (layer != null && (info.ConcretePrerequisites.Length == 0 || techTree == null || techTree.HasPrerequisites(info.ConcretePrerequisites))) { @@ -93,7 +93,7 @@ protected override void AddedToWorld(Actor self) foreach (var c in info.Tiles(self.Location)) { // Only place on allowed terrain types - if (!mapCell.Contains(c) || mapCell.CustomTerrain[c] != byte.MaxValue || !info.TerrainTypes.Contains(mapCell.GetTerrainInfo(c).Type)) + if (!map.Contains(c) || map.CustomTerrain[c] != byte.MaxValue || !info.TerrainTypes.Contains(map.GetTerrainInfo(c).Type)) continue; // Don't place under other buildings (or their bib) @@ -111,7 +111,7 @@ protected override void AddedToWorld(Actor self) var c = self.Location + new CVec(i % template.Size.X, i / template.Size.X); // Only place on allowed terrain types - if (!mapCell.Contains(c) || mapCell.CustomTerrain[c] != byte.MaxValue || !info.TerrainTypes.Contains(mapCell.GetTerrainInfo(c).Type)) + if (!map.Contains(c) || map.CustomTerrain[c] != byte.MaxValue || !info.TerrainTypes.Contains(map.GetTerrainInfo(c).Type)) continue; // Don't place under other buildings (or their bib) @@ -129,7 +129,7 @@ protected override void AddedToWorld(Actor self) foreach (var kv in self.OccupiesSpace.OccupiedCells()) { totalTiles++; - if (!info.DamageTerrainTypes.Contains(mapCell.GetTerrainInfo(kv.Cell).Type)) + if (!info.DamageTerrainTypes.Contains(map.GetTerrainInfo(kv.Cell).Type)) safeTiles++; } diff --git a/OpenRA.Mods.D2k/Traits/Sandworm.cs b/OpenRA.Mods.D2k/Traits/Sandworm.cs index 25636871c878..552dadd418ad 100644 --- a/OpenRA.Mods.D2k/Traits/Sandworm.cs +++ b/OpenRA.Mods.D2k/Traits/Sandworm.cs @@ -110,10 +110,10 @@ void RescanForTargets(Actor self) if (noiseDirection == WVec.Zero) return; - var mapCell = (IMapCell)self.World.Map; - var moveTo = mapCell.CellContaining(self.CenterPosition + noiseDirection); + var map = self.World.Map; + var moveTo = map.CellContaining(self.CenterPosition + noiseDirection); - while (!mapCell.Contains(moveTo) || !mobile.CanEnterCell(moveTo, null, BlockedByActor.None)) + while (!map.Contains(moveTo) || !mobile.CanEnterCell(moveTo, null, BlockedByActor.None)) { // without this check, this while can be infinity loop if (moveTo == self.Location) @@ -123,7 +123,7 @@ void RescanForTargets(Actor self) } noiseDirection /= 2; - moveTo = mapCell.CellContaining(self.CenterPosition + noiseDirection); + moveTo = map.CellContaining(self.CenterPosition + noiseDirection); } // Don't get stuck when the noise is distributed evenly! This will make the worm wander instead of trying to move to where it already is diff --git a/OpenRA.Mods.D2k/Traits/SpiceBloom.cs b/OpenRA.Mods.D2k/Traits/SpiceBloom.cs index 294024104399..2be6828aa1c8 100644 --- a/OpenRA.Mods.D2k/Traits/SpiceBloom.cs +++ b/OpenRA.Mods.D2k/Traits/SpiceBloom.cs @@ -90,12 +90,12 @@ public SpiceBloom(Actor self, SpiceBloomInfo info) void ITick.Tick(Actor self) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; - if (!mapCell.Contains(self.Location)) + if (!map.Contains(self.Location)) return; - if (info.GrowthTerrainTypes.Count > 0 && !info.GrowthTerrainTypes.Contains(mapCell.GetTerrainInfo(self.Location).Type)) + if (info.GrowthTerrainTypes.Count > 0 && !info.GrowthTerrainTypes.Contains(map.GetTerrainInfo(self.Location).Type)) return; ticks++; @@ -118,12 +118,12 @@ void ITick.Tick(Actor self) void SeedResources(Actor self) { - var mapCell = (IMapCell)self.World.Map; + var map = self.World.Map; var pieces = self.World.SharedRandom.Next(info.Pieces[0], info.Pieces[1]) * ticks / growTicks; if (pieces < info.Pieces[0]) pieces = info.Pieces[0]; - var cells = mapCell.FindTilesInAnnulus(self.Location, 1, info.Range); + var cells = map.FindTilesInAnnulus(self.Location, 1, info.Range); for (var i = 0; i < pieces; i++) { @@ -153,7 +153,7 @@ void SeedResources(Actor self) Source = self.CenterPosition, CurrentSource = () => self.CenterPosition, SourceActor = self, - PassiveTarget = mapCell.CenterOfCell(cell.Value) + PassiveTarget = map.CenterOfCell(cell.Value) }; self.World.AddFrameEndTask(_ => diff --git a/OpenRA.Mods.D2k/Traits/World/BuildableTerrainLayer.cs b/OpenRA.Mods.D2k/Traits/World/BuildableTerrainLayer.cs index df2ff74b1e6f..01416c17f0b3 100644 --- a/OpenRA.Mods.D2k/Traits/World/BuildableTerrainLayer.cs +++ b/OpenRA.Mods.D2k/Traits/World/BuildableTerrainLayer.cs @@ -49,9 +49,9 @@ public BuildableTerrainLayer(Actor self, BuildableTerrainLayerInfo info) { this.info = info; world = self.World; - var mapCell = (IMapCell)world.Map; - strength = new CellLayer(mapCell); - radarColor = new CellLayer<(Color, Color)>(mapCell); + var map = world.Map; + strength = new CellLayer(map); + radarColor = new CellLayer<(Color, Color)>(map); terrainRenderer = self.Trait(); } @@ -66,9 +66,9 @@ public void AddTile(CPos cell, TerrainTile tile) if (!strength.Contains(cell)) return; - var uv = cell.ToMPos((IMapCell)world.Map); + var uv = cell.ToMPos(world.Map); var tileInfo = world.Map.Rules.TerrainInfo.GetTerrainInfo(tile); - ((IMapCell)world.Map).CustomTerrain[uv] = tileInfo.TerrainType; + world.Map.CustomTerrain[uv] = tileInfo.TerrainType; strength[uv] = info.MaxStrength; radarColor[uv] = (tileInfo.GetColor(world.LocalRandom), tileInfo.GetColor(world.LocalRandom)); dirty[cell] = tile; @@ -93,8 +93,8 @@ public void RemoveTile(CPos cell) if (!strength.Contains(cell)) return; - var uv = cell.ToMPos((IMapCell)world.Map); - ((IMapCell)world.Map).CustomTerrain[uv] = byte.MaxValue; + var uv = cell.ToMPos(world.Map); + world.Map.CustomTerrain[uv] = byte.MaxValue; strength[cell] = 0; radarColor[uv] = (Color.Transparent, Color.Transparent); dirty[cell] = null; diff --git a/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs b/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs index 4857cd98f25f..d6f27b62fbb4 100644 --- a/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs +++ b/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs @@ -335,7 +335,7 @@ void Initialize(string mapFile) var tl = new PPos(MapCordonWidth, MapCordonWidth); var br = new PPos(MapCordonWidth + mapSize.Width - 1, MapCordonWidth + mapSize.Height - 1); - ((IMapCell)map).SetBounds(tl, br); + ((IMap)map).SetBounds(tl, br); // Get all templates from the tileset YAML file that have at least one frame and an Image property corresponding to the requested tileset // Each frame is a tile from the Dune 2000 tileset files, with the Frame ID being the index of the tile in the original file @@ -345,7 +345,7 @@ void Initialize(string mapFile) return templateInfo.Frames != null && string.Equals(templateInfo.Images[0], tilesetName, StringComparison.InvariantCultureIgnoreCase); }).Select(ts => ts.Value).ToList(); - var players = new MapPlayers(map.Rules, playerCount); + var players = new MapPlayers(((IMap)map).Rules, playerCount); map.PlayerDefinitions = players.ToMiniYaml(); } @@ -356,18 +356,17 @@ void FillMap() var tileInfo = stream.ReadUInt16(); var tileSpecialInfo = stream.ReadUInt16(); var tile = GetTile(tileInfo); - var mapCell = (IMapCell)map; - var mapResource = (IMapResource)map; + var mapResources = ((IMapResource)map).Resources; var locationOnMap = GetCurrentTilePositionOnMap(); - mapCell.Tiles[locationOnMap] = tile; + ((IMapTiles)map).Tiles[locationOnMap] = tile; // Spice if (tileSpecialInfo == 1) - mapResource.Resources[locationOnMap] = new ResourceTile(1, 1); + mapResources[locationOnMap] = new ResourceTile(1, 1); if (tileSpecialInfo == 2) - mapResource.Resources[locationOnMap] = new ResourceTile(1, 2); + mapResources[locationOnMap] = new ResourceTile(1, 2); // Actors if (ActorDataByActorCode.ContainsKey(tileSpecialInfo)) diff --git a/OpenRA.Mods.D2k/Warheads/DamagesConcreteWarhead.cs b/OpenRA.Mods.D2k/Warheads/DamagesConcreteWarhead.cs index de5a27559da5..efc69f0871c8 100644 --- a/OpenRA.Mods.D2k/Warheads/DamagesConcreteWarhead.cs +++ b/OpenRA.Mods.D2k/Warheads/DamagesConcreteWarhead.cs @@ -31,7 +31,7 @@ public override void DoImpact(in Target target, WarheadArgs args) var firedBy = args.SourceActor; var world = firedBy.World; var layer = world.WorldActor.Trait(); - var cell = ((IMapCell)world.Map).CellContaining(target.CenterPosition); + var cell = world.Map.CellContaining(target.CenterPosition); layer.HitTile(cell, Damage); } } diff --git a/mods/modcontent/mod.yaml b/mods/modcontent/mod.yaml index 0d90cf9a0ba9..dc92f7a423c6 100644 --- a/mods/modcontent/mod.yaml +++ b/mods/modcontent/mod.yaml @@ -73,3 +73,5 @@ TerrainFormat: DefaultTerrain SpriteSequenceFormat: DefaultSpriteSequence ModelSequenceFormat: PlaceholderModelSequence + +DefaultMapLoader: