Merge pull request #7631 from pchote/sequence-rework

Rework sequence parsing.
This commit is contained in:
Pavel Penev
2015-03-14 00:13:03 +02:00
13 changed files with 157 additions and 61 deletions

View File

@@ -16,7 +16,7 @@ namespace OpenRA.Graphics
public class Animation
{
readonly int defaultTick = 40; // 25 fps == 40 ms
public Sequence CurrentSequence { get; private set; }
public ISpriteSequence CurrentSequence { get; private set; }
public bool IsDecoration = false;
public Func<bool> Paused;
@@ -177,7 +177,7 @@ namespace OpenRA.Graphics
}
}
public Sequence GetSequence(string sequenceName)
public ISpriteSequence GetSequence(string sequenceName)
{
return sequenceProvider.GetSequence(name, sequenceName);
}

View File

@@ -1,157 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Linq;
namespace OpenRA.Graphics
{
public class Sequence
{
readonly Sprite[] sprites;
readonly bool reverseFacings, transpose;
public readonly string Name;
public readonly int Start;
public readonly int Length;
public readonly int Stride;
public readonly int Facings;
public readonly int Tick;
public readonly int ZOffset;
public readonly int ShadowStart;
public readonly int ShadowZOffset;
public readonly int[] Frames;
public Sequence(SpriteCache cache, string unit, string name, MiniYaml info)
{
var srcOverride = info.Value;
Name = name;
var d = info.ToDictionary();
var offset = float2.Zero;
var blendMode = BlendMode.Alpha;
try
{
if (d.ContainsKey("Start"))
Start = Exts.ParseIntegerInvariant(d["Start"].Value);
if (d.ContainsKey("Offset"))
offset = FieldLoader.GetValue<float2>("Offset", d["Offset"].Value);
if (d.ContainsKey("BlendMode"))
blendMode = FieldLoader.GetValue<BlendMode>("BlendMode", d["BlendMode"].Value);
// Apply offset to each sprite in the sequence
// Different sequences may apply different offsets to the same frame
sprites = cache[srcOverride ?? unit].Select(
s => new Sprite(s.Sheet, s.Bounds, s.Offset + offset, s.Channel, blendMode)).ToArray();
if (!d.ContainsKey("Length"))
Length = 1;
else if (d["Length"].Value == "*")
Length = sprites.Length - Start;
else
Length = Exts.ParseIntegerInvariant(d["Length"].Value);
if (d.ContainsKey("Stride"))
Stride = Exts.ParseIntegerInvariant(d["Stride"].Value);
else
Stride = Length;
if (d.ContainsKey("Facings"))
{
var f = Exts.ParseIntegerInvariant(d["Facings"].Value);
Facings = Math.Abs(f);
reverseFacings = f < 0;
}
else
Facings = 1;
if (d.ContainsKey("Tick"))
Tick = Exts.ParseIntegerInvariant(d["Tick"].Value);
else
Tick = 40;
if (d.ContainsKey("Transpose"))
transpose = bool.Parse(d["Transpose"].Value);
if (d.ContainsKey("Frames"))
Frames = Array.ConvertAll<string, int>(d["Frames"].Value.Split(','), Exts.ParseIntegerInvariant);
if (d.ContainsKey("ShadowStart"))
ShadowStart = Exts.ParseIntegerInvariant(d["ShadowStart"].Value);
else
ShadowStart = -1;
if (d.ContainsKey("ShadowZOffset"))
{
WRange r;
if (WRange.TryParse(d["ShadowZOffset"].Value, out r))
ShadowZOffset = r.Range;
}
else
ShadowZOffset = -5;
if (d.ContainsKey("ZOffset"))
{
WRange r;
if (WRange.TryParse(d["ZOffset"].Value, out r))
ZOffset = r.Range;
}
if (Length > Stride)
throw new InvalidOperationException(
"{0}: Sequence {1}.{2}: Length must be <= stride"
.F(info.Nodes[0].Location, unit, name));
if (Start < 0 || Start + Facings * Stride > sprites.Length || ShadowStart + Facings * Stride > sprites.Length)
throw new InvalidOperationException(
"{6}: Sequence {0}.{1} uses frames [{2}..{3}] of SHP `{4}`, but only 0..{5} actually exist"
.F(unit, name, Start, Start + Facings * Stride - 1, srcOverride ?? unit, sprites.Length - 1,
info.Nodes[0].Location));
}
catch (FormatException f)
{
throw new FormatException("Failed to parse sequences for {0}.{1} at {2}:\n{3}".F(unit, name, info.Nodes[0].Location, f));
}
}
public Sprite GetSprite(int frame)
{
return GetSprite(Start, frame, 0);
}
public Sprite GetSprite(int frame, int facing)
{
return GetSprite(Start, frame, facing);
}
public Sprite GetShadow(int frame, int facing)
{
return ShadowStart >= 0 ? GetSprite(ShadowStart, frame, facing) : null;
}
Sprite GetSprite(int start, int frame, int facing)
{
var f = Traits.Util.QuantizeFacing(facing, Facings);
if (reverseFacings)
f = (Facings - f) % Facings;
var i = transpose ? (frame % Length) * Facings + f :
(f * Stride) + (frame % Length);
if (Frames != null)
return sprites[Frames[i]];
return sprites[start + i];
}
}
}

View File

@@ -12,11 +12,35 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace OpenRA.Graphics
{
using Sequences = IReadOnlyDictionary<string, Lazy<IReadOnlyDictionary<string, Sequence>>>;
using UnitSequences = Lazy<IReadOnlyDictionary<string, Sequence>>;
using Sequences = IReadOnlyDictionary<string, Lazy<IReadOnlyDictionary<string, ISpriteSequence>>>;
using UnitSequences = Lazy<IReadOnlyDictionary<string, ISpriteSequence>>;
public interface ISpriteSequence
{
string Name { get; }
int Start { get; }
int Length { get; }
int Stride { get; }
int Facings { get; }
int Tick { get; }
int ZOffset { get; }
int ShadowStart { get; }
int ShadowZOffset { get; }
int[] Frames { get; }
Sprite GetSprite(int frame);
Sprite GetSprite(int frame, int facing);
Sprite GetShadow(int frame, int facing);
}
public interface ISpriteSequenceLoader
{
IReadOnlyDictionary<string, ISpriteSequence> ParseSequences(ModData modData, TileSet tileSet, SpriteCache cache, MiniYamlNode node);
}
public class SequenceProvider
{
@@ -29,13 +53,13 @@ namespace OpenRA.Graphics
this.SpriteCache = cache.SpriteCache;
}
public Sequence GetSequence(string unitName, string sequenceName)
public ISpriteSequence GetSequence(string unitName, string sequenceName)
{
UnitSequences unitSeq;
if (!sequences.Value.TryGetValue(unitName, out unitSeq))
throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName));
Sequence seq;
ISpriteSequence seq;
if (!unitSeq.Value.TryGetValue(sequenceName, out seq))
throw new InvalidOperationException("Unit `{0}` does not have a sequence named `{1}`".F(unitName, sequenceName));
@@ -77,6 +101,7 @@ namespace OpenRA.Graphics
public sealed class SequenceCache : IDisposable
{
readonly ModData modData;
readonly TileSet tileSet;
readonly Lazy<SpriteCache> spriteCache;
public SpriteCache SpriteCache { get { return spriteCache.Value; } }
@@ -85,7 +110,9 @@ namespace OpenRA.Graphics
public SequenceCache(ModData modData, TileSet tileSet)
{
this.modData = modData;
this.tileSet = tileSet;
// Every time we load a tile set, we create a sequence cache for it
spriteCache = Exts.Lazy(() => new SpriteCache(modData.SpriteLoaders, tileSet.Extensions, new SheetBuilder(SheetType.Indexed)));
}
@@ -116,7 +143,7 @@ namespace OpenRA.Graphics
items.Add(node.Key, t);
else
{
t = Exts.Lazy(() => CreateUnitSequences(node));
t = Exts.Lazy(() => modData.SpriteSequenceLoader.ParseSequences(modData, tileSet, SpriteCache, node));
sequenceCache.Add(key, t);
items.Add(node.Key, t);
}
@@ -125,28 +152,6 @@ namespace OpenRA.Graphics
return new ReadOnlyDictionary<string, UnitSequences>(items);
}
IReadOnlyDictionary<string, Sequence> CreateUnitSequences(MiniYamlNode node)
{
var unitSequences = new Dictionary<string, Sequence>();
foreach (var kvp in node.Value.ToDictionary())
{
using (new Support.PerfTimer("new Sequence(\"{0}\")".F(node.Key), 20))
{
try
{
unitSequences.Add(kvp.Key, new Sequence(spriteCache.Value, node.Key, kvp.Key, kvp.Value));
}
catch (FileNotFoundException ex)
{
Log.Write("debug", ex.Message);
}
}
}
return new ReadOnlyDictionary<string, Sequence>(unitSequences);
}
public void Dispose()
{
if (spriteCache.IsValueCreated)

View File

@@ -20,6 +20,17 @@ namespace OpenRA
public enum TileShape { Rectangle, Diamond }
public interface IGlobalModData { }
public sealed class SpriteSequenceFormat : IGlobalModData
{
public readonly string Type;
public readonly IReadOnlyDictionary<string, MiniYaml> Metadata;
public SpriteSequenceFormat(MiniYaml yaml)
{
Type = yaml.Value;
Metadata = new ReadOnlyDictionary<string, MiniYaml>(yaml.ToDictionary());
}
}
// Describes what is to be loaded in order to run a mod
public class Manifest
{
@@ -34,6 +45,7 @@ namespace OpenRA
public readonly IReadOnlyDictionary<string, string> MapFolders;
public readonly MiniYaml LoadScreen;
public readonly MiniYaml LobbyDefaults;
public readonly Dictionary<string, Pair<string, int>> Fonts;
public readonly Size TileSize = new Size(24, 24);
public readonly TileShape TileShape = TileShape.Rectangle;
@@ -92,8 +104,12 @@ namespace OpenRA
Missions = YamlList(yaml, "Missions", true);
ServerTraits = YamlList(yaml, "ServerTraits");
LoadScreen = yaml["LoadScreen"];
LobbyDefaults = yaml["LobbyDefaults"];
if (!yaml.TryGetValue("LoadScreen", out LoadScreen))
throw new InvalidDataException("`LoadScreen` section is not defined.");
if (!yaml.TryGetValue("LobbyDefaults", out LobbyDefaults))
throw new InvalidDataException("`LobbyDefaults` section is not defined.");
Fonts = yaml["Fonts"].ToDictionary(my =>
{
@@ -150,8 +166,20 @@ namespace OpenRA
if (t == null || !typeof(IGlobalModData).IsAssignableFrom(t))
throw new InvalidDataException("`{0}` is not a valid mod manifest entry.".F(kv.Key));
var module = oc.CreateObject<IGlobalModData>(kv.Key);
FieldLoader.Load(module, kv.Value);
IGlobalModData module;
var ctor = t.GetConstructor(new Type[] { typeof(MiniYaml) });
if (ctor != null)
{
// Class has opted-in to DIY initialization
module = (IGlobalModData)ctor.Invoke(new object[] { kv.Value });
}
else
{
// Automatically load the child nodes using FieldLoader
module = oc.CreateObject<IGlobalModData>(kv.Key);
FieldLoader.Load(module, kv.Value);
}
modules.Add(module);
}
}

View File

@@ -25,6 +25,7 @@ namespace OpenRA
public readonly WidgetLoader WidgetLoader;
public readonly MapCache MapCache;
public readonly ISpriteLoader[] SpriteLoaders;
public readonly ISpriteSequenceLoader SpriteSequenceLoader;
public readonly RulesetCache RulesetCache;
public ILoadScreen LoadScreen { get; private set; }
public VoxelLoader VoxelLoader { get; private set; }
@@ -52,17 +53,25 @@ namespace OpenRA
RulesetCache.LoadingProgress += HandleLoadingProgress;
MapCache = new MapCache(this);
var loaders = new List<ISpriteLoader>();
var spriteLoaders = new List<ISpriteLoader>();
foreach (var format in Manifest.SpriteFormats)
{
var loader = ObjectCreator.FindType(format + "Loader");
if (loader == null || !loader.GetInterfaces().Contains(typeof(ISpriteLoader)))
throw new InvalidOperationException("Unable to find a sprite loader for type '{0}'.".F(format));
loaders.Add((ISpriteLoader)ObjectCreator.CreateBasic(loader));
spriteLoaders.Add((ISpriteLoader)ObjectCreator.CreateBasic(loader));
}
SpriteLoaders = loaders.ToArray();
SpriteLoaders = spriteLoaders.ToArray();
var sequenceFormat = Manifest.Get<SpriteSequenceFormat>();
var sequenceLoader = ObjectCreator.FindType(sequenceFormat.Type + "Loader");
var ctor = sequenceLoader != null ? sequenceLoader.GetConstructor(new[] { typeof(ModData) }) : null;
if (sequenceLoader == null || !sequenceLoader.GetInterfaces().Contains(typeof(ISpriteSequenceLoader)) || ctor == null)
throw new InvalidOperationException("Unable to find a sequence loader for type '{0}'.".F(sequenceFormat.Type));
SpriteSequenceLoader = (ISpriteSequenceLoader)ctor.Invoke(new[] { this });
// HACK: Mount only local folders so we have a half-working environment for the asset installer
GlobalFileSystem.UnmountAll();

View File

@@ -109,7 +109,6 @@
<Compile Include="Graphics\MappedImage.cs" />
<Compile Include="Graphics\Minimap.cs" />
<Compile Include="Graphics\Renderer.cs" />
<Compile Include="Graphics\Sequence.cs" />
<Compile Include="Graphics\SequenceProvider.cs" />
<Compile Include="Graphics\Sheet.cs" />
<Compile Include="Graphics\SheetBuilder.cs" />