Separated resource rendering into another trait

This commit is contained in:
teinarss
2019-06-18 22:09:45 +02:00
committed by abcdefg30
parent 0e93d85273
commit f0b69f8b8d
16 changed files with 377 additions and 180 deletions

View File

@@ -56,7 +56,7 @@ namespace OpenRA.Mods.Common.Traits
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));
}

View File

@@ -269,7 +269,7 @@ namespace OpenRA.Mods.Common.Traits
if (cell.Layer != 0)
return false;
var resType = resLayer.GetResource(cell);
var resType = resLayer.GetResourceType(cell);
if (resType == null)
return false;
@@ -395,7 +395,7 @@ namespace OpenRA.Mods.Common.Traits
if (!self.Owner.Shroud.IsExplored(location))
return false;
var res = self.World.WorldActor.Trait<ResourceLayer>().GetRenderedResource(location);
var res = self.World.WorldActor.Trait<ResourceRenderer>().GetRenderedResourceType(location);
var info = self.Info.TraitInfo<HarvesterInfo>();
if (res == null || !info.Resources.Contains(res.Info.Type))

View File

@@ -65,7 +65,7 @@ namespace OpenRA.Mods.Common.Traits
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))

View File

@@ -31,7 +31,7 @@ namespace OpenRA.Mods.Common.Traits
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>();
@@ -48,7 +48,7 @@ namespace OpenRA.Mods.Common.Traits
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);
@@ -98,7 +98,7 @@ namespace OpenRA.Mods.Common.Traits
ResourceType type;
if (Resources.TryGetValue(tile.Type, out type))
{
Tiles[uv] = new CellContents
Tiles[uv] = new EditorCellContents
{
Type = type,
Variant = ChooseRandomVariant(type),
@@ -108,7 +108,7 @@ namespace OpenRA.Mods.Common.Traits
}
else
{
Tiles[uv] = CellContents.Empty;
Tiles[uv] = EditorCellContents.Empty;
Map.CustomTerrain[uv] = byte.MaxValue;
}
@@ -143,7 +143,7 @@ namespace OpenRA.Mods.Common.Traits
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;
@@ -213,4 +213,13 @@ namespace OpenRA.Mods.Common.Traits
disposed = true;
}
}
public struct EditorCellContents
{
public static readonly EditorCellContents Empty = default(EditorCellContents);
public ResourceType Type;
public int Density;
public string Variant;
public Sprite Sprite;
}
}

View File

@@ -24,64 +24,38 @@ namespace OpenRA.Mods.Common.Traits
public virtual object Create(ActorInitializer init) { return new ResourceLayer(init.Self); }
}
public class ResourceLayer : IRenderOverlay, IWorldLoaded, ITickRender, INotifyActorDisposing
public class ResourceLayer : IWorldLoaded
{
static readonly CellContents EmptyCell = default(CellContents);
readonly World world;
readonly BuildingInfluence buildingInfluence;
readonly HashSet<CPos> dirty = new HashSet<CPos>();
readonly Dictionary<PaletteReference, TerrainSpriteLayer> spriteLayers = new Dictionary<PaletteReference, TerrainSpriteLayer>();
protected readonly CellLayer<CellContents> Content;
protected readonly CellLayer<CellContents> RenderContent;
public bool IsResourceLayerEmpty { get { return resCells < 1; } }
bool disposed;
int resCells;
public event Action<CPos, ResourceType> CellChanged;
public ResourceLayer(Actor self)
{
world = self.World;
buildingInfluence = self.Trait<BuildingInfluence>();
Content = new CellLayer<CellContents>(world.Map);
RenderContent = new CellLayer<CellContents>(world.Map);
RenderContent.CellEntryChanged += UpdateSpriteLayers;
}
void UpdateSpriteLayers(CPos cell)
{
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 && resource.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);
}
int GetAdjacentCellsWith(ResourceType t, CPos cell)
{
var sum = 0;
for (var u = -1; u < 2; u++)
var directions = CVec.Directions;
for (var i = 0; i < directions.Length; i++)
{
for (var v = -1; v < 2; v++)
{
var c = cell + new CVec(u, v);
if (Content.Contains(c) && Content[c].Type == t)
++sum;
}
var c = cell + directions[i];
if (Content.Contains(c) && Content[c].Type == t)
++sum;
}
return sum;
@@ -92,27 +66,6 @@ namespace OpenRA.Mods.Common.Traits
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.");
}
foreach (var cell in w.Map.AllCells)
{
ResourceType t;
@@ -127,61 +80,21 @@ namespace OpenRA.Mods.Common.Traits
foreach (var cell in w.Map.AllCells)
{
var type = Content[cell].Type;
var type = GetResourceType(cell);
if (type != null)
{
// Set initial density based on the number of neighboring resources
// Adjacent includes the current cell, so is always >= 1
var adjacent = GetAdjacentCellsWith(type, cell);
var density = int2.Lerp(0, type.Info.MaxDensity, adjacent, 9);
var temp = Content[cell];
var temp = GetResource(cell);
temp.Density = Math.Max(density, 1);
// Initialize the RenderContent with the initial map state
// because the shroud may not be enabled.
RenderContent[cell] = Content[cell] = temp;
UpdateRenderedSprite(cell);
Content[cell] = temp;
}
}
}
protected virtual void UpdateRenderedSprite(CPos cell)
{
var t = RenderContent[cell];
if (t.Density > 0)
{
var sprites = t.Type.Variants[t.Variant];
var frame = int2.Lerp(0, sprites.Length - 1, t.Density, t.Type.Info.MaxDensity);
t.Sprite = sprites[frame];
}
else
t.Sprite = null;
RenderContent[cell] = t;
}
protected virtual string ChooseRandomVariant(ResourceType t)
{
return t.Variants.Keys.Random(Game.CosmeticRandom);
}
void ITickRender.TickRender(WorldRenderer wr, Actor self)
{
var remove = new List<CPos>();
foreach (var c in dirty)
{
if (!self.World.FogObscures(c))
{
RenderContent[c] = Content[c];
UpdateRenderedSprite(c);
remove.Add(c);
}
}
foreach (var r in remove)
dirty.Remove(r);
}
public bool AllowResourceAt(ResourceType rt, CPos cell)
{
if (!world.Map.Contains(cell))
@@ -212,7 +125,7 @@ namespace OpenRA.Mods.Common.Traits
if (!world.Map.Contains(cell))
return false;
var currentResourceType = GetResource(cell);
var currentResourceType = GetResourceType(cell);
return (currentResourceType == newResourceType && !IsFull(cell))
|| (currentResourceType == null && AllowResourceAt(newResourceType, cell));
}
@@ -224,8 +137,7 @@ namespace OpenRA.Mods.Common.Traits
return new CellContents
{
Type = t,
Variant = ChooseRandomVariant(t),
Type = t
};
}
@@ -241,12 +153,14 @@ namespace OpenRA.Mods.Common.Traits
cell.Density = Math.Min(cell.Type.Info.MaxDensity, cell.Density + n);
Content[p] = cell;
dirty.Add(p);
if (CellChanged != null)
CellChanged(p, cell.Type);
}
public bool IsFull(CPos cell)
{
return Content[cell].Density == Content[cell].Type.Info.MaxDensity;
var cellContents = Content[cell];
return cellContents.Density == cellContents.Type.Info.MaxDensity;
}
public ResourceType Harvest(CPos cell)
@@ -264,7 +178,8 @@ namespace OpenRA.Mods.Common.Traits
else
Content[cell] = c;
dirty.Add(cell);
if (CellChanged != null)
CellChanged(cell, c.Type);
return c.Type;
}
@@ -272,7 +187,8 @@ namespace OpenRA.Mods.Common.Traits
public void Destroy(CPos cell)
{
// Don't break other users of CustomTerrain if there are no resources
if (Content[cell].Type == null)
var c = Content[cell];
if (c.Type == null)
return;
--resCells;
@@ -281,11 +197,13 @@ namespace OpenRA.Mods.Common.Traits
Content[cell] = EmptyCell;
world.Map.CustomTerrain[cell] = byte.MaxValue;
dirty.Add(cell);
if (CellChanged != null)
CellChanged(cell, c.Type);
}
public ResourceType GetResource(CPos cell) { return Content[cell].Type; }
public ResourceType GetRenderedResource(CPos cell) { return RenderContent[cell].Type; }
public CellContents GetResource(CPos cell) { return Content[cell]; }
public ResourceType GetResourceType(CPos cell) { return Content[cell].Type; }
public int GetResourceDensity(CPos cell) { return Content[cell].Density; }
public int GetMaxResourceDensity(CPos cell)
{
@@ -295,26 +213,11 @@ namespace OpenRA.Mods.Common.Traits
return Content[cell].Type.Info.MaxDensity;
}
void INotifyActorDisposing.Disposing(Actor self)
{
if (disposed)
return;
foreach (var kv in spriteLayers.Values)
kv.Dispose();
RenderContent.CellEntryChanged -= UpdateSpriteLayers;
disposed = true;
}
public struct CellContents
{
public static readonly CellContents Empty = default(CellContents);
public ResourceType Type;
public int Density;
public string Variant;
public Sprite Sprite;
}
}
}

View File

@@ -0,0 +1,208 @@
#region Copyright & License Information
/*
* Copyright 2007-2020 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 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 Queue<CPos> cleanDirty = new Queue<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);
}
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))
{
var resourceContent = ResourceLayer.GetResource(cell);
var rendererCellContents = new RendererCellContents(ChooseRandomVariant(resourceContent.Type), resourceContent.Type, resourceContent.Density);
RenderContent[cell] = rendererCellContents;
UpdateRenderedSprite(cell, rendererCellContents);
}
}
}
protected void UpdateSpriteLayers(CPos cell, Sprite sprite, PaletteReference palette)
{
foreach (var kv in spriteLayers)
{
// resource.Type is meaningless (and may be null) if resource.Sprite is null
if (sprite != null && palette == kv.Key)
kv.Value.Update(cell, 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)
{
foreach (var cell in dirty)
{
if (self.World.FogObscures(cell))
continue;
var resourceContent = ResourceLayer.GetResource(cell);
if (resourceContent.Density > 0)
{
var cellContents = RenderContent[cell];
var variant = cellContents.Variant;
if (cellContents.Variant == null || cellContents.Type != resourceContent.Type)
variant = ChooseRandomVariant(resourceContent.Type);
var rendererCellContents = new RendererCellContents(variant, resourceContent.Type, resourceContent.Density);
RenderContent[cell] = rendererCellContents;
UpdateRenderedSprite(cell, rendererCellContents);
}
else
{
var rendererCellContents = RendererCellContents.Empty;
RenderContent[cell] = rendererCellContents;
UpdateRenderedSprite(cell, rendererCellContents);
}
cleanDirty.Enqueue(cell);
}
while (cleanDirty.Count > 0)
dirty.Remove(cleanDirty.Dequeue());
}
protected virtual void UpdateRenderedSprite(CPos cell, RendererCellContents content)
{
var density = content.Density;
var type = content.Type;
if (content.Density > 0)
{
// 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;
var sprites = type.Variants[content.Variant];
var maxDensity = type.Info.MaxDensity;
var frame = int2.Lerp(0, sprites.Length - 1, density, maxDensity);
UpdateSpriteLayers(cell, sprites[frame], type.Palette);
}
else
UpdateSpriteLayers(cell, null, null);
}
bool disposed;
void INotifyActorDisposing.Disposing(Actor self)
{
if (disposed)
return;
foreach (var kv in spriteLayers.Values)
kv.Dispose();
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 readonly string Variant;
public readonly ResourceType Type;
public readonly int Density;
public static readonly RendererCellContents Empty = default(RendererCellContents);
public RendererCellContents(string variant, ResourceType type, int density)
{
Variant = variant;
Type = type;
Density = density;
}
}
}
}