Skip to content

Commit

Permalink
Separated resource rendering into another trait
Browse files Browse the repository at this point in the history
  • Loading branch information
teinarss committed Jun 28, 2019
1 parent 9f59b00 commit 9f385ea
Show file tree
Hide file tree
Showing 15 changed files with 303 additions and 171 deletions.
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Orders/PlaceBuildingOrderGenerator.cs
Expand Up @@ -272,7 +272,7 @@ IEnumerable<IRenderable> IOrderGenerator.RenderAboveShroud(WorldRenderer wr, Wor
{
var isCloseEnough = buildingInfo.IsCloseEnoughToBase(world, world.LocalPlayer, actorInfo, topLeft);
foreach (var t in buildingInfo.Tiles(topLeft))
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResource(t) == null)));
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResourceType(t) == null)));
}

return preview != null ? preview.Render(wr, topLeft, footprint) : Enumerable.Empty<IRenderable>();
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/Buildings/BuildingUtils.cs
Expand Up @@ -56,7 +56,7 @@ public static bool CanPlaceBuilding(this World world, CPos cell, ActorInfo ai, B

var res = world.WorldActor.TraitOrDefault<ResourceLayer>();
return bi.Tiles(cell).All(
t => world.Map.Contains(t) && (res == null || res.GetResource(t) == null) &&
t => world.Map.Contains(t) && (res == null || res.GetResourceType(t) == null) &&
world.IsCellBuildable(t, ai, bi, toIgnore));
}

Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Common/Traits/Harvester.cs
Expand Up @@ -287,7 +287,7 @@ public bool CanHarvestCell(Actor self, CPos cell)
if (cell.Layer != 0)
return false;

var resType = resLayer.GetResource(cell);
var resType = resLayer.GetResourceType(cell);
if (resType == null)
return false;

Expand Down Expand Up @@ -419,7 +419,7 @@ public bool CanTarget(Actor self, Target target, List<Actor> othersAtTarget, ref
if (!self.Owner.Shroud.IsExplored(location))
return false;

var res = self.World.WorldActor.Trait<ResourceLayer>().GetRenderedResource(location);
var res = self.World.WorldActor.Trait<ResourceLayer>().GetResourceType(location);
var info = self.Info.TraitInfo<HarvesterInfo>();

if (res == null || !info.Resources.Contains(res.Info.Type))
Expand Down
196 changes: 196 additions & 0 deletions OpenRA.Mods.Common/Traits/Player/ResourceRenderer.cs
@@ -0,0 +1,196 @@
#region Copyright & License Information
/*
* Copyright 2007-2019 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion

using System.Collections.Generic;
using System.IO;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Traits;

namespace OpenRA.Mods.Common.Traits
{
[Desc("Visualizes the state of the `ResourceLayer`.", " Attach this to the world actor.")]
public class ResourceRendererInfo : ITraitInfo, Requires<ResourceLayerInfo>
{
[FieldLoader.Require]
[Desc("Only render these ResourceType Type names.")]
public readonly string[] RenderTypes = null;

public virtual object Create(ActorInitializer init) { return new ResourceRenderer(init.Self, this); }
}

public class ResourceRenderer : IWorldLoaded, IRenderOverlay, ITickRender, INotifyActorDisposing
{
protected readonly ResourceLayer ResourceLayer;

protected readonly CellLayer<RendererCellContents> RenderContent;

protected readonly ResourceRendererInfo Info;

readonly HashSet<CPos> dirty = new HashSet<CPos>();

readonly Dictionary<PaletteReference, TerrainSpriteLayer> spriteLayers = new Dictionary<PaletteReference, TerrainSpriteLayer>();

public ResourceRenderer(Actor self, ResourceRendererInfo info)
{
Info = info;

ResourceLayer = self.Trait<ResourceLayer>();
ResourceLayer.CellChanged += AddDirtyCell;

RenderContent = new CellLayer<RendererCellContents>(self.World.Map);
RenderContent.CellEntryChanged += UpdateSpriteLayers;
}

void AddDirtyCell(CPos cell, ResourceType resType)
{
if (resType == null || Info.RenderTypes.Contains(resType.Info.Type))
dirty.Add(cell);
}

void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr)
{
var resources = w.WorldActor.TraitsImplementing<ResourceType>()
.ToDictionary(r => r.Info.ResourceType, r => r);

// Build the sprite layer dictionary for rendering resources
// All resources that have the same palette must also share a sheet and blend mode
foreach (var r in resources)
{
var layer = spriteLayers.GetOrAdd(r.Value.Palette, pal =>
{
var first = r.Value.Variants.First().Value.First();
return new TerrainSpriteLayer(w, wr, first.Sheet, first.BlendMode, pal, wr.World.Type != WorldType.Editor);
});

// Validate that sprites are compatible with this layer
var sheet = layer.Sheet;
if (r.Value.Variants.Any(kv => kv.Value.Any(s => s.Sheet != sheet)))
throw new InvalidDataException("Resource sprites span multiple sheets. Try loading their sequences earlier.");

var blendMode = layer.BlendMode;
if (r.Value.Variants.Any(kv => kv.Value.Any(s => s.BlendMode != blendMode)))
throw new InvalidDataException("Resource sprites specify different blend modes. "
+ "Try using different palettes for resource types that use different blend modes.");
}

// Initialize the RenderContent with the initial map state
// because the shroud may not be enabled.
foreach (var cell in w.Map.AllCells)
{
var type = ResourceLayer.GetResourceType(cell);
if (type != null && Info.RenderTypes.Contains(type.Info.Type))
UpdateRenderedSprite(cell);
}
}

protected void UpdateSpriteLayers(CPos cell)
{
var type = ResourceLayer.GetResourceType(cell);
if (type != null && !Info.RenderTypes.Contains(type.Info.Type))
return;

var resource = RenderContent[cell];
foreach (var kv in spriteLayers)
{
// resource.Type is meaningless (and may be null) if resource.Sprite is null
if (resource.Sprite != null && type.Palette == kv.Key)
kv.Value.Update(cell, resource.Sprite);
else
kv.Value.Update(cell, null);
}
}

void IRenderOverlay.Render(WorldRenderer wr)
{
foreach (var kv in spriteLayers.Values)
kv.Draw(wr.Viewport);
}

void ITickRender.TickRender(WorldRenderer wr, Actor self)
{
var remove = new List<CPos>();
foreach (var c in dirty)
{
if (self.World.FogObscures(c))
continue;

UpdateRenderedSprite(c);
remove.Add(c);
}

foreach (var r in remove)
dirty.Remove(r);
}

protected virtual void UpdateRenderedSprite(CPos cell)
{
var content = ResourceLayer.GetResourceContent(cell);
var density = content.Density;
var type = content.Type;
var renderContent = RenderContent[cell];
if (type != null)
{
// The call chain for this method (that starts with AddDirtyCell()) guarantees
// that the new content type would still be suitable for this renderer,
// but that is a bit too fragile to rely on in case the code starts changing.
if (!Info.RenderTypes.Contains(type.Info.Type))
return;

// Since renderContent is not nullable it will always have a value, but empty.
// Also it is possible to have a frozen cell with resource X that upon revelaing turns out has changed to resource Y.
if (renderContent.Variant == null || renderContent.Type != type)
renderContent.Variant = ChooseRandomVariant(type);

var sprites = type.Variants[renderContent.Variant];
var maxDensity = ResourceLayer.GetMaxResourceDensity(cell);
var frame = int2.Lerp(0, sprites.Length - 1, density, maxDensity);

renderContent.Sprite = sprites[frame];
renderContent.Type = type;
}
else
renderContent = RendererCellContents.Empty;

RenderContent[cell] = renderContent;
}

bool disposed;
void INotifyActorDisposing.Disposing(Actor self)
{
if (disposed)
return;

foreach (var kv in spriteLayers.Values)
kv.Dispose();

RenderContent.CellEntryChanged -= UpdateSpriteLayers;
ResourceLayer.CellChanged -= AddDirtyCell;

disposed = true;
}

protected virtual string ChooseRandomVariant(ResourceType t)
{
return t.Variants.Keys.Random(Game.CosmeticRandom);
}

public ResourceType GetRenderedResourceType(CPos cell) { return RenderContent[cell].Type; }

public struct RendererCellContents
{
public static readonly RendererCellContents Empty = default(RendererCellContents);
public string Variant;
public Sprite Sprite;
public ResourceType Type;
}
}
}
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/SeedsResource.cs
Expand Up @@ -65,7 +65,7 @@ public void Seed(Actor self)
var cell = Util.RandomWalk(self.Location, self.World.SharedRandom)
.Take(info.MaxRange)
.SkipWhile(p => !self.World.Map.Contains(p) ||
(resLayer.GetResource(p) == resourceType && resLayer.IsFull(p)))
(resLayer.GetResourceType(p) == resourceType && resLayer.IsFull(p)))
.Cast<CPos?>().FirstOrDefault();

if (cell != null && resLayer.CanSpawnResourceAt(resourceType, cell.Value))
Expand Down
19 changes: 14 additions & 5 deletions OpenRA.Mods.Common/Traits/World/EditorResourceLayer.cs
Expand Up @@ -31,7 +31,7 @@ public class EditorResourceLayer : IWorldLoaded, IRenderOverlay, INotifyActorDis
protected readonly Map Map;
protected readonly TileSet Tileset;
protected readonly Dictionary<int, ResourceType> Resources;
protected readonly CellLayer<CellContents> Tiles;
protected readonly CellLayer<EditorCellContents> Tiles;
protected readonly HashSet<CPos> Dirty = new HashSet<CPos>();

readonly Dictionary<PaletteReference, TerrainSpriteLayer> spriteLayers = new Dictionary<PaletteReference, TerrainSpriteLayer>();
Expand All @@ -48,7 +48,7 @@ public EditorResourceLayer(Actor self)
Map = self.World.Map;
Tileset = self.World.Map.Rules.TileSet;

Tiles = new CellLayer<CellContents>(Map);
Tiles = new CellLayer<EditorCellContents>(Map);
Resources = self.TraitsImplementing<ResourceType>()
.ToDictionary(r => r.Info.ResourceType, r => r);

Expand Down Expand Up @@ -98,7 +98,7 @@ public void UpdateCell(CPos cell)
ResourceType type;
if (Resources.TryGetValue(tile.Type, out type))
{
Tiles[uv] = new CellContents
Tiles[uv] = new EditorCellContents
{
Type = type,
Variant = ChooseRandomVariant(type),
Expand All @@ -108,7 +108,7 @@ public void UpdateCell(CPos cell)
}
else
{
Tiles[uv] = CellContents.Empty;
Tiles[uv] = EditorCellContents.Empty;
Map.CustomTerrain[uv] = byte.MaxValue;
}

Expand Down Expand Up @@ -143,7 +143,7 @@ public int ResourceDensityAt(CPos c)
return Math.Max(int2.Lerp(0, type.Info.MaxDensity, adjacent, 9), 1);
}

public virtual CellContents UpdateDirtyTile(CPos c)
public virtual EditorCellContents UpdateDirtyTile(CPos c)
{
var t = Tiles[c];
var type = t.Type;
Expand Down Expand Up @@ -213,4 +213,13 @@ void INotifyActorDisposing.Disposing(Actor self)
disposed = true;
}
}

public struct EditorCellContents
{
public static readonly EditorCellContents Empty = default(EditorCellContents);
public ResourceType Type;
public int Density;
public string Variant;
public Sprite Sprite;
}
}

0 comments on commit 9f385ea

Please sign in to comment.