چیست؟
Double Buffer از یک state دو کپی نگه میدارد. در طول هر قدم، همه از Current میخوانند و همهٔ نوشتنها به Next میرود. وقتی قدم تمام شد، Swap() دو ارجاع را جابهجا میکند و state تازه یکجا دیده میشود.
مشکلی که حل میکند وابستگی به ترتیب است. اگر یک cellular automaton جدولش را درجا بهروز کند، خانهٔ (۵،۳) از روی همسایههایی حساب میشود که قبلاً به نسل بعد رفتهاند، در حالی که خانهٔ (۴،۳) همسایههای قدیمی را دیده بود. نتیجه به سمت پیمایش حلقه بستگی پیدا میکند، نه به قانونها.
هر فریم بدون اینکه فکرش را بکنی از آن استفاده میکنی: Unity در back buffer رندر میکند در حالی که front buffer روی صفحه است، و بعد با یک swap جای این دو را عوض میکند تا تصویر تازه نمایش داده شود. روی GPU هم شبیهسازیهایی مثل سیال، blur یا reaction-diffusion همین کار را با دو RenderTexture انجام میدهند؛ در shader از یکی میخوانند و در دیگری مینویسند (به این میگویند ping-pong).
کِی به کار میآید؟
وقتی عناصر زیادی باید «همزمان» از روی state مشترک بهروز شوند، سراغش برو: Game of Life، پخش شدن گرما یا آب روی tileها، influence map و boidهایی که همه باید به موقعیتهای فریم قبل واکنش نشان دهند.
جایی هم به کار میآید که یک سیستم stateی را مینویسد که سیستم دیگری کمکم آن را میخواند، و خواننده هیچوقت نباید نتیجهٔ نیمهنوشته ببیند: مثلاً مرحلهای که طی چند فریم ساخته میشود، یا یک job که دادهای را مینویسد که main thread مصرفش میکند.
اگر بهروزرسانیها واقعاً مستقلاند (هر عنصر فقط خودش را میخواند)، یا ترتیب بخشی از طراحی است، از آن استفاده نکن. بافر دوم حافظه و یک swap هزینه دارد، و اگر کسی وسط بهروزرسانی چیزی نخواند، فایدهای هم ندارد.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using UnityEngine;
namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Steps the simulation on a fixed tick and draws Current into a texture.
/// The view never sees a half-written generation.
/// </summary>
public class LifeView : MonoBehaviour
{
[SerializeField] private int width = 64;
[SerializeField] private int height = 36;
[SerializeField] private float stepsPerSecond = 8f;
[SerializeField] private Renderer target;
private LifeGrid grid;
private Texture2D texture;
private Color32[] pixels;
private float timer;
private void Awake()
{
grid = new LifeGrid(width, height);
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
grid.Set(x, y, Random.value < 0.25f);
texture = new Texture2D(width, height, TextureFormat.RGBA32, false) { filterMode = FilterMode.Point };
pixels = new Color32[width * height];
target.material.mainTexture = texture;
}
private void Update()
{
timer += Time.deltaTime;
if (timer < 1f / stepsPerSecond) return;
timer = 0f;
grid.Step();
Draw();
}
private void Draw()
{
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels[y * width + x] = grid[x, y] ? new Color32(120, 255, 180, 255) : new Color32(12, 14, 22, 255);
texture.SetPixels32(pixels);
texture.Apply(false);
}
private void OnDestroy() => Destroy(texture);
}
}namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Conway's Game of Life on a wrapping grid. Every cell of the new
/// generation is computed only from the previous generation.
/// </summary>
public sealed class LifeGrid
{
private readonly DoubleBuffer<bool[,]> cells;
public int Width { get; }
public int Height { get; }
public int Generation { get; private set; }
public LifeGrid(int width, int height)
{
Width = width;
Height = height;
cells = new DoubleBuffer<bool[,]>(new bool[width, height], new bool[width, height]);
}
public bool this[int x, int y] => cells.Current[x, y];
public void Set(int x, int y, bool alive) => cells.Current[x, y] = alive;
public void Step()
{
bool[,] read = cells.Current;
bool[,] write = cells.Next;
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int n = CountNeighbours(read, x, y);
// Reads come from 'read' only, so the scan order cannot matter.
write[x, y] = n == 3 || (n == 2 && read[x, y]);
}
cells.Swap();
Generation++;
}
private int CountNeighbours(bool[,] grid, int x, int y)
{
int count = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + Width) % Width;
int ny = (y + dy + Height) % Height;
if (grid[nx, ny]) count++;
}
return count;
}
}
}namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Two copies of the same state. Readers only see Current; the writer
/// fills Next, then Swap() publishes it in one cheap reference flip.
/// </summary>
public sealed class DoubleBuffer<T>
{
private T current;
private T next;
public DoubleBuffer(T first, T second)
{
current = first;
next = second;
}
/// <summary>The finished state of the last step. Read-only by convention.</summary>
public T Current => current;
/// <summary>The state being written for the next step.</summary>
public T Next => next;
/// <summary>No copying: the two buffers just trade roles.</summary>
public void Swap() => (current, next) = (next, current);
}
}قبل و بعد از پترن
یک موقعیت واقعی: یک شبیهسازی جدولی که خانههایش را درجا بهروز میکند. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
LifeGrid.Step روی cells حلقه میزند و هر مقدار تازه را مستقیم در همان آرایه مینویسد. وقتی به یک خانه میرسد، همسایههای چپ و بالایش از قبل مقدار نسل بعد را دارند.
gliderها از هم میپاشند، blinkerها دیگر چشمک نمیزنند و برعکس کردن سمت پیمایش حلقه نتیجهٔ دیگری میدهد. این باگ موذی است، چون جدول هنوز «زنده به نظر میرسد»؛ پس معمولاً تا وقتی یک طراح مرحلهای بر پایهٔ یک الگوی شناختهشده بسازد، زنده میماند.
✓ چه چیزی عوض شد؟
- آرایهٔ تکی
bool[,] cellsبه یکDoubleBuffer<bool[,]>تبدیل شد که دو آرایهٔ هماندازه نگه میدارد. Stepفقط ازcells.Current(با اسمread) میخواند و فقط درcells.Next(با اسمwrite) مینویسد.- یک
cells.Swap()در انتها نسل تازه را منتشر میکند؛ indexer وSetهم ازCurrentمیخوانند. CountNeighboursعوض نشده است: از قبل جدول را بهعنوان پارامتر میگرفت، پس حالا بافر خواندن را دریافت میکند.
namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Without Double Buffer: the grid is updated in place, so cells later in
/// the scan read neighbours that already belong to the next generation.
/// </summary>
public sealed class LifeGrid
{
private readonly bool[,] cells;
public int Width { get; }
public int Height { get; }
public int Generation { get; private set; }
public LifeGrid(int width, int height)
{
Width = width;
Height = height;
cells = new bool[width, height];
}
public bool this[int x, int y] => cells[x, y];
public void Set(int x, int y, bool alive) => cells[x, y] = alive;
public void Step()
{
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int n = CountNeighbours(cells, x, y);
// Bug: the left and upper neighbours were already overwritten.
cells[x, y] = n == 3 || (n == 2 && cells[x, y]);
}
Generation++;
}
private int CountNeighbours(bool[,] grid, int x, int y)
{
int count = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + Width) % Width;
int ny = (y + dy + Height) % Height;
if (grid[nx, ny]) count++;
}
return count;
}
}
}namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// With Double Buffer: every read comes from the finished generation and
/// every write goes to the other buffer, then the two swap roles.
/// </summary>
public sealed class LifeGrid
{
private readonly DoubleBuffer<bool[,]> cells;
public int Width { get; }
public int Height { get; }
public int Generation { get; private set; }
public LifeGrid(int width, int height)
{
Width = width;
Height = height;
cells = new DoubleBuffer<bool[,]>(new bool[width, height], new bool[width, height]);
}
public bool this[int x, int y] => cells.Current[x, y];
public void Set(int x, int y, bool alive) => cells.Current[x, y] = alive;
public void Step()
{
bool[,] read = cells.Current;
bool[,] write = cells.Next;
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int n = CountNeighbours(read, x, y);
write[x, y] = n == 3 || (n == 2 && read[x, y]);
}
cells.Swap();
Generation++;
}
private int CountNeighbours(bool[,] grid, int x, int y)
{
int count = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + Width) % Width;
int ny = (y + dy + Height) % Height;
if (grid[nx, ny]) count++;
}
return count;
}
}
}مزایا و معایب
+ مزایا
- نتیجهها قطعی و مستقل از ترتیب پیمایشاند؛ پس فکر کردن دربارهٔ شبیهسازی و موازی کردنش راحت است.
- خوانندهها همیشه یک state کامل و سازگار میبینند؛ هیچ «پارگی»ای وسط یک قدم پیش نمیآید.
- swap فقط جابهجایی ارجاع است؛ پس منتشر کردن یک state کاملاً تازه O(1) است.
− معایب
- برای state بافرشده دو برابر حافظه لازم است، که در جدولها یا textureهای بزرگ مهم میشود.
- هر عنصر باید در هر قدم نوشته شود، وگرنه
Nextمقدارهای کهنهٔ دو قدم قبل را نگه میدارد. - تغییرها یک قدم دیرتر دیده میشوند؛ یعنی یک فریم تأخیر که بعضی سیستمها (ورودی، برخورد) تحملش را ندارند.
چند نکتهٔ کاربردی
- ۰۱ارجاعها را جابهجا کن، هیچوقت آرایه کپی نکن.
(current, next) = (next, current)تمام چیزی است کهSwap()لازم دارد. - ۰۲مطمئن شو که در هر قدم به همهٔ خانههای
Nextمقدار داده میشود؛ اگر فقط خانههای «تغییرکرده» را مینویسی، اول پاکش کن یا کپی کن. - ۰۳برای جدولهای بزرگ، آن را با
NativeArray<T>و یکIJobParallelForترکیب کن: یک job ازCurrentمیخواند و درNextمینویسد، و swap بعد ازComplete()روی main thread انجام میشود. - ۰۴روی GPU از دو
RenderTextureوGraphics.Blit(a, b, material)استفاده کن و بعد متغیرها را جابهجا کن. هیچوقت در یک pass از یکRenderTextureهم نخوان و هم در آن ننویس. - ۰۵اسم بافرها را بر اساس نقششان بگذار (
read/write)، نه با شماره؛ تا کسی اشتباهی در بافری که دارد خوانده میشود ننویسد.