using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; namespace Foo { public static class StateStack { static readonly Pool Pool = new Pool(); static readonly Stack Stack = new Stack(); public static ManagedRenderState PushState(this GraphicsDevice device) { var rs = Pool.Take(); if (Stack.Count == 0) rs.Reset(device); else rs.Reset(Stack.Peek()); Stack.Push(rs); return rs; } public static void PopState(this GraphicsDevice device) { var poppedRs = Stack.Pop(); poppedRs.Refresh(Stack.Peek()); poppedRs.Commit(device); Pool.Return(poppedRs); } public static ManagedRenderState PeekState(this GraphicsDevice device) { return Stack.Peek(); } public static void ResetState(this GraphicsDevice device) { Stack.Peek().Reset(device); } public static void CommitState(this GraphicsDevice device) { Stack.Peek().Commit(device); } } public class Pool where T : class, new() { readonly Stack stack; public Pool() : this(0) { } public Pool(int size) { stack = new Stack(size); for (int i = 0; i < size; i++) stack.Push(new T()); } public T Take() { return stack.Count > 0 ? stack.Pop() : new T(); } public void Return(T item) { stack.Push(item); } } }