Merge pull request #3282 from pchote/renderer-refactoring

Renderer refactoring - SheetBuilder
This commit is contained in:
Chris Forbes
2013-05-15 03:26:16 -07:00
11 changed files with 238 additions and 169 deletions

View File

@@ -60,7 +60,9 @@ namespace OpenRA.FileFormats
foreach (var field in Fields)
{
FieldInfo f = this.GetType().GetField(field);
if (f.GetValue(this) == null) continue;
if (f.GetValue(this) == null)
continue;
root.Add(new MiniYamlNode(field, FieldSaver.FormatValue(this, f)));
}
@@ -122,7 +124,9 @@ namespace OpenRA.FileFormats
foreach (var field in fields)
{
FieldInfo f = this.GetType().GetField(field);
if (f.GetValue(this) == null) continue;
if (f.GetValue(this) == null)
continue;
gen.Add(new MiniYamlNode(field, FieldSaver.FormatValue(this, f)));
}
@@ -147,7 +151,7 @@ namespace OpenRA.FileFormats
return tile.Data.TileBitmapBytes[r.index];
byte[] missingTile = new byte[TileSize*TileSize];
for( int i = 0 ; i < missingTile.Length ; i++ )
for (var i = 0; i < missingTile.Length; i++)
missingTile[i] = 0x36;
return missingTile;
@@ -159,6 +163,7 @@ namespace OpenRA.FileFormats
string ret;
if (!tt.TryGetValue(r.index, out ret))
return "Clear"; // Default walkable
return ret;
}

View File

@@ -25,9 +25,7 @@ namespace OpenRA.Graphics
public string Name { get { return name; } }
public Animation(string name)
: this( name, () => 0 )
{
}
: this(name, () => 0) {}
public Animation(string name, Func<int> facingFunc)
{

View File

@@ -9,6 +9,7 @@
#endregion
using System.Drawing;
using System.Drawing.Imaging;
using OpenRA.FileFormats;
using OpenRA.FileFormats.Graphics;
@@ -16,21 +17,44 @@ namespace OpenRA.Graphics
{
public class Sheet
{
Bitmap bitmap;
ITexture texture;
bool dirty;
byte[] data;
public byte[] Data { get; private set; }
public readonly Size Size;
public Sheet(Size size)
{
Size = size;
Data = new byte[4*Size.Width*Size.Height];
}
public Sheet(string filename)
{
bitmap = (Bitmap)Image.FromStream(FileSystem.Open(filename));
var bitmap = (Bitmap)Image.FromStream(FileSystem.Open(filename));
Size = bitmap.Size;
Data = new byte[4*Size.Width*Size.Height];
var b = bitmap.LockBits(bitmap.Bounds(),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
unsafe
{
int* c = (int*)b.Scan0;
for (var x = 0; x < Size.Width; x++)
for (var y = 0; y < Size.Height; y++)
{
var i = 4*Size.Width*y + 4*x;
// Convert argb to bgra
var argb = *(c + (y * b.Stride >> 2) + x);
Data[i++] = (byte)(argb >> 0);
Data[i++] = (byte)(argb >> 8);
Data[i++] = (byte)(argb >> 16);
Data[i++] = (byte)(argb >> 24);
}
}
bitmap.UnlockBits(b);
}
public ITexture Texture
@@ -45,23 +69,61 @@ namespace OpenRA.Graphics
if (dirty)
{
if (data != null)
{
texture.SetData(data, Size.Width, Size.Height);
texture.SetData(Data, Size.Width, Size.Height);
dirty = false;
}
else if (bitmap != null)
{
texture.SetData(bitmap);
dirty = false;
}
}
return texture;
}
}
public byte[] Data { get { if (data == null) data = new byte[4 * Size.Width * Size.Height]; return data; } }
public Bitmap AsBitmap()
{
var b = new Bitmap(Size.Width, Size.Height);
var output = b.LockBits(new Rectangle(0, 0, Size.Width, Size.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
unsafe
{
int* c = (int*)output.Scan0;
for (var x = 0; x < Size.Width; x++)
for (var y = 0; y < Size.Height; y++)
{
var i = 4*Size.Width*y + 4*x;
// Convert bgra to argb
var argb = (Data[i+3] << 24) | (Data[i+2] << 16) | (Data[i+1] << 8) | Data[i];
*(c + (y * output.Stride >> 2) + x) = argb;
}
}
b.UnlockBits(output);
return b;
}
public Bitmap AsBitmap(TextureChannel channel, Palette pal)
{
var b = new Bitmap(Size.Width, Size.Height);
var output = b.LockBits(new Rectangle(0, 0, Size.Width, Size.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
unsafe
{
int* c = (int*)output.Scan0;
for (var x = 0; x < Size.Width; x++)
for (var y = 0; y < Size.Height; y++)
{
var index = Data[4*Size.Width*y + 4*x + (int)channel];
*(c + (y * output.Stride >> 2) + x) = pal.GetColor(index).ToArgb();
}
}
b.UnlockBits(output);
return b;
}
public void MakeDirty() { dirty = true; }
}
}

View File

@@ -8,68 +8,69 @@
*/
#endregion
using System;
using System.Drawing;
namespace OpenRA.Graphics
{
public class SheetBuilder
public class SheetOverflowException : Exception
{
internal SheetBuilder(TextureChannel ch)
{
current = null;
rowHeight = 0;
channel = null;
initialChannel = ch;
public SheetOverflowException()
: base("Sprite sequence spans multiple sheets.\n"+
"This should be considered as a bug, but you "+
"can increase the Graphics.SheetSize setting "+
"to temporarily avoid the problem.") {}
}
public Sprite Add(byte[] src, Size size)
public enum SheetType
{
Sprite rect = Allocate(size);
Indexed = 1,
DualIndexed = 2,
BGRA = 4,
}
public class SheetBuilder
{
Sheet current;
TextureChannel channel;
SheetType type;
int rowHeight = 0;
Point p;
internal SheetBuilder(SheetType t)
{
current = new Sheet(new Size(Renderer.SheetSize, Renderer.SheetSize));;
channel = TextureChannel.Red;
type = t;
}
public Sprite Add(byte[] src, Size size, bool allowSheetOverflow)
{
var rect = Allocate(size, allowSheetOverflow);
Util.FastCopyIntoChannel(rect, src);
return rect;
}
public Sprite Add(Size size, byte paletteIndex)
public Sprite Add(Size size, byte paletteIndex, bool allowSheetOverflow)
{
byte[] data = new byte[size.Width * size.Height];
for (int i = 0; i < data.Length; i++)
var data = new byte[size.Width * size.Height];
for (var i = 0; i < data.Length; i++)
data[i] = paletteIndex;
return Add(data, size);
return Add(data, size, allowSheetOverflow);
}
Sheet NewSheet() { return new Sheet(new Size( Renderer.SheetSize, Renderer.SheetSize ) ); }
Sheet current = null;
int rowHeight = 0;
Point p;
TextureChannel? channel = null;
TextureChannel initialChannel;
TextureChannel? NextChannel(TextureChannel? t)
TextureChannel? NextChannel(TextureChannel t)
{
if (t == null)
return initialChannel;
var nextChannel = (int)t + (int)type;
if (nextChannel > (int)TextureChannel.Alpha)
return null;
switch (t.Value)
{
case TextureChannel.Red: return TextureChannel.Green;
case TextureChannel.Green: return TextureChannel.Blue;
case TextureChannel.Blue: return TextureChannel.Alpha;
case TextureChannel.Alpha: return null;
default: return null;
}
return (TextureChannel)nextChannel;
}
public Sprite Allocate(Size imageSize)
public Sprite Allocate(Size imageSize, bool allowSheetOverflow)
{
if (current == null)
{
current = NewSheet();
channel = NextChannel(null);
}
if (imageSize.Width + p.X > current.Size.Width)
{
p = new Point(0, p.Y + rowHeight);
@@ -81,22 +82,29 @@ namespace OpenRA.Graphics
if (p.Y + imageSize.Height > current.Size.Height)
{
if (null == (channel = NextChannel(channel)))
var next = NextChannel(channel);
if (next == null)
{
current = NewSheet();
channel = NextChannel(channel);
if (!allowSheetOverflow)
throw new SheetOverflowException();
current = new Sheet(new Size(Renderer.SheetSize, Renderer.SheetSize));
channel = TextureChannel.Red;
}
else
channel = next.Value;
rowHeight = imageSize.Height;
p = new Point(0,0);
}
Sprite rect = new Sprite(current, new Rectangle(p, imageSize), channel.Value);
var rect = new Sprite(current, new Rectangle(p, imageSize), channel);
current.MakeDirty();
p.X += imageSize.Width;
return rect;
}
public Sheet Current { get { return current; } }
}
}

View File

@@ -17,52 +17,47 @@ namespace OpenRA.Graphics
public readonly Rectangle bounds;
public readonly Sheet sheet;
public readonly TextureChannel channel;
public readonly RectangleF uv;
public readonly float2 size;
readonly float2[] uvhax;
readonly float2[] textureCoords;
public Sprite(Sheet sheet, Rectangle bounds, TextureChannel channel)
{
this.bounds = bounds;
this.sheet = sheet;
this.channel = channel;
uv = new RectangleF(
(float)(bounds.Left) / sheet.Size.Width,
(float)(bounds.Top) / sheet.Size.Height,
(float)(bounds.Width) / sheet.Size.Width,
(float)(bounds.Height) / sheet.Size.Height);
uvhax = new float2[]
{
new float2( uv.Left, uv.Top ),
new float2( uv.Right, uv.Top ),
new float2( uv.Left, uv.Bottom ),
new float2( uv.Right, uv.Bottom ),
};
this.size = new float2(bounds.Size);
var left = (float)(bounds.Left) / sheet.Size.Width;
var top = (float)(bounds.Top) / sheet.Size.Height;
var right = (float)(bounds.Right) / sheet.Size.Width;
var bottom = (float)(bounds.Bottom) / sheet.Size.Height;
textureCoords = new float2[]
{
new float2(left, top),
new float2(right, top),
new float2(left, bottom),
new float2(right, bottom),
};
}
public float2 FastMapTextureCoords(int k)
{
return uvhax[ k ];
return textureCoords[k];
}
public void DrawAt(WorldRenderer wr, float2 location, string palette)
{
Game.Renderer.WorldSpriteRenderer.DrawSprite( this, location, wr, palette, this.size );
Game.Renderer.WorldSpriteRenderer.DrawSprite(this, location, wr, palette, size);
}
public void DrawAt(float2 location, int paletteIndex)
{
Game.Renderer.WorldSpriteRenderer.DrawSprite( this, location, paletteIndex, this.size );
Game.Renderer.WorldSpriteRenderer.DrawSprite(this, location, paletteIndex, size);
}
public void DrawAt(float2 location, int paletteIndex, float scale)
{
Game.Renderer.WorldSpriteRenderer.DrawSprite(this, location, paletteIndex, this.size * scale);
Game.Renderer.WorldSpriteRenderer.DrawSprite(this, location, paletteIndex, size*scale);
}
public void DrawAt(float2 location, int paletteIndex, float2 size)

View File

@@ -31,8 +31,10 @@ namespace OpenRA.Graphics
glyphs = new Cache<Pair<char, Color>, GlyphInfo>(CreateGlyph,
Pair<char,Color>.EqualityComparer);
// setup a 1-channel SheetBuilder for our private use
if (builder == null) builder = new SheetBuilder(TextureChannel.Alpha);
// setup a SheetBuilder for our private use
// TODO: SheetBuilder state is leaked between mod switches
if (builder == null)
builder = new SheetBuilder(SheetType.BGRA);
PrecacheColor(Color.White);
PrecacheColor(Color.Red);
@@ -96,9 +98,8 @@ namespace OpenRA.Graphics
face.LoadGlyph(index, LoadFlags.Default, LoadTarget.Normal);
face.Glyph.RenderGlyph(RenderMode.Normal);
var s = builder.Allocate(
new Size((int)face.Glyph.Metrics.Width >> 6,
(int)face.Glyph.Metrics.Height >> 6));
var size = new Size((int)face.Glyph.Metrics.Width >> 6, (int)face.Glyph.Metrics.Height >> 6);
var s = builder.Allocate(size, true);
var g = new GlyphInfo
{

View File

@@ -35,12 +35,12 @@ namespace OpenRA.Graphics
if (ImageCount == 0)
{
var shp = new ShpTSReader(FileSystem.OpenWithExts(filename, exts));
return shp.Select(a => Game.modData.SheetBuilder.Add(a.Image, shp.Size)).ToArray();
return shp.Select(a => SheetBuilder.Add(a.Image, shp.Size, true)).ToArray();
}
else
{
var shp = new ShpReader(FileSystem.OpenWithExts(filename, exts));
return shp.Frames.Select(a => SheetBuilder.Add(a.Image, shp.Size)).ToArray();
return shp.Frames.Select(a => SheetBuilder.Add(a.Image, shp.Size, true)).ToArray();
}
}

View File

@@ -18,8 +18,8 @@ namespace OpenRA.Graphics
{
class TerrainRenderer
{
SheetBuilder sheetBuilder;
IVertexBuffer<Vertex> vertexBuffer;
Sheet terrainSheet;
World world;
Map map;
@@ -29,28 +29,22 @@ namespace OpenRA.Graphics
this.world = world;
this.map = world.Map;
// TODO: Use a fixed sheet size specified in the tileset yaml
sheetBuilder = new SheetBuilder(SheetType.Indexed);
var tileSize = new Size(Game.CellSize, Game.CellSize);
var tileMapping = new Cache<TileReference<ushort,byte>, Sprite>(
x => Game.modData.SheetBuilder.Add(world.TileSet.GetBytes(x), tileSize));
var vertices = new Vertex[4 * map.Bounds.Height * map.Bounds.Width];
terrainSheet = tileMapping[map.MapTiles.Value[map.Bounds.Left, map.Bounds.Top]].sheet;
int nv = 0;
x => sheetBuilder.Add(world.TileSet.GetBytes(x), tileSize, false));
var terrainPalette = wr.Palette("terrain").Index;
var vertices = new Vertex[4 * map.Bounds.Height * map.Bounds.Width];
int nv = 0;
for( int j = map.Bounds.Top; j < map.Bounds.Bottom; j++ )
for( int i = map.Bounds.Left; i < map.Bounds.Right; i++ )
for (var j = map.Bounds.Top; j < map.Bounds.Bottom; j++)
for (var i = map.Bounds.Left; i < map.Bounds.Right; i++)
{
var tile = tileMapping[map.MapTiles.Value[i, j]];
// TODO: move GetPaletteIndex out of the inner loop.
Util.FastCreateQuad(vertices, Game.CellSize * new float2(i, j), tile, terrainPalette, nv, tile.size);
nv += 4;
if (tileMapping[map.MapTiles.Value[i, j]].sheet != terrainSheet)
throw new InvalidOperationException("Terrain sprites span multiple sheets. Try increasing Game.Settings.Graphics.SheetSize.");
}
vertexBuffer = Game.Renderer.Device.CreateVertexBuffer(vertices.Length);
@@ -59,7 +53,7 @@ namespace OpenRA.Graphics
public void Draw(WorldRenderer wr, Viewport viewport)
{
int verticesPerRow = map.Bounds.Width * 4;
int verticesPerRow = 4*map.Bounds.Width;
int visibleRows = (int)(viewport.Height * 1f / Game.CellSize / viewport.Zoom + 2);
@@ -79,14 +73,19 @@ namespace OpenRA.Graphics
firstRow = r.Bottom - map.Bounds.Top;
}
if (firstRow < 0) firstRow = 0;
if (lastRow > map.Bounds.Height) lastRow = map.Bounds.Height;
// Sanity checking
if (firstRow < 0)
firstRow = 0;
if( lastRow < firstRow ) lastRow = firstRow;
if (lastRow > map.Bounds.Height)
lastRow = map.Bounds.Height;
if (lastRow < firstRow)
lastRow = firstRow;
Game.Renderer.WorldSpriteRenderer.DrawVertexBuffer(
vertexBuffer, verticesPerRow * firstRow, verticesPerRow * (lastRow - firstRow),
PrimitiveType.QuadList, terrainSheet);
PrimitiveType.QuadList, sheetBuilder.Current);
foreach (var r in world.WorldActor.TraitsImplementing<IRenderOverlay>())
r.Render(wr);

View File

@@ -32,12 +32,13 @@ namespace OpenRA.Graphics
static readonly int[] channelMasks = { 2, 1, 0, 3 }; // yes, our channel order is nuts.
public static void FastCopyIntoChannel(Sprite dest, byte[] src)
public static void FastCopyIntoChannel(Sprite dest, byte[] src) { FastCopyIntoChannel(dest, 0, src); }
public static void FastCopyIntoChannel(Sprite dest, int channelOffset, byte[] src)
{
var data = dest.sheet.Data;
var srcStride = dest.bounds.Width;
var destStride = dest.sheet.Size.Width * 4;
var destOffset = destStride * dest.bounds.Top + dest.bounds.Left * 4 + channelMasks[(int)dest.channel];
var destOffset = destStride * dest.bounds.Top + dest.bounds.Left * 4 + channelMasks[(int)dest.channel + channelOffset];
var destSkip = destStride - 4 * srcStride;
var height = dest.bounds.Height;

View File

@@ -53,7 +53,7 @@ namespace OpenRA
ChromeMetrics.Initialize(Manifest.ChromeMetrics);
ChromeProvider.Initialize(Manifest.Chrome);
SheetBuilder = new SheetBuilder(TextureChannel.Red);
SheetBuilder = new SheetBuilder(SheetType.Indexed);
SpriteLoader = new SpriteLoader(new string[] { ".shp" }, SheetBuilder);
CursorProvider.Initialize(Manifest.Cursors);
}

View File

@@ -99,9 +99,9 @@ namespace OpenRA.Mods.RA
if (cachedTileset != self.World.Map.Tileset)
{
cachedTileset = self.World.Map.Tileset;
var tileSize = new Size(Game.CellSize, Game.CellSize);
sprites = new Cache<TileReference<ushort,byte>, Sprite>(
x => Game.modData.SheetBuilder.Add(self.World.TileSet.GetBytes(x),
new Size(Game.CellSize, Game.CellSize)));
x => Game.modData.SheetBuilder.Add(self.World.TileSet.GetBytes(x), tileSize, true));
}
// Cache templates and tiles for the different states