절차적 맵 생성 - 파동 함수 붕괴 알고리즘

절차적 맵 생성을 위한 여러 알고리즘 (Perlin Noise, Simplex Noise, Cellular Automata, BSP 등)이 있지만 그 중 파동 함수 붕괴 알고리즘에 대해 알아보자.
1. 파동 함수 붕괴 알고리즘 (Wave Function Collapse)
여러 상태가 중첩된 상태에서 셀을 랜덤으로 또는 조건에 의해 하나씩 붕괴시키며 상태를 고정하는 방식이다.
아래 예시를 보자.

위와 같이 타일이 다섯 종류 존재한다고 가정하자.
이 타일을 랜덤하게 배치할 수 있겠으나, 타일끼리 맞닿은 선이 이어져야 한다는 규칙을 추가할 수 있다.
2. 규칙 예시
타일끼리 맞닿은 선이 이어져야 한다.




- 그림 1에서는 왼쪽 타일과 오른쪽 타일에 맞닿은 선이 없으므로 배치 가능
- 그림 2에서는 왼쪽 타일과 오른쪽 타일에 맞닿은 선이 연결되어 있으므로 배치 가능
- 그림 3에서는 왼쪽 타일의 선이 오른쪽 타일의 선과 이어지지 않으므로 배치 불가
위와 같이 규칙을 정한다면 한 타일이 정해져 있을 때 그 주변 타일에 올 수 있는 후보가 달라지게 된다.
3. 알고리즘 과정
다음과 같이 3x3 타일이 존재한다고 가정하자.
1. 초기 타일
위 타일은 아직 붕괴되지 않아 모든 타일이 동일하게 5종류의 타일 후보를 가지게 된다.
이 중에서 타일 하나를 골라 랜덤으로 하나의 타일 종류로 고정한다.
이렇게 여러 후보 중 하나로 타일이 고정되는 것을 붕괴라고 한다.
2. 첫번째 붕괴
(1, 2) 타일이 붕괴했으니 해당 타일과 이웃한 4타일의 후보가 변한다.
1) 위쪽 타일 - (0, 2)
자기 자신의 아래로 선이 이어져야 하므로 올 수 있는 후보는 아래 3개이다.
2) 오른쪽 타일 - 범위 밖
범위 밖이므로 제외한다.
3) 아래쪽 타일 - (2, 2)
자기 자신의 위로 선이 이어져야 하므로 올 수 있는 후보는 아래 3개이다.
4) 왼쪽 타일 - (1, 1)
자기 자신의 오른쪽이 선이 이어지면 안 되므로 올 수 있는 후보는 아래 2개이다.
이제 전체 타일에서 후보의 개수가 가장 적은 타일은 2개의 후보를 가진 (1, 1)이다.
후보의 개수가 가장 적으므로 해당 타일을 선택해서 랜덤으로 하나의 후보를 골라 붕괴시켜준다.
3. 두번째 붕괴
(1, 1) 타일이 붕괴하면서 그 이웃한 타일 (0, 1), (1, 0), (2, 1)의 후보 개수가 변한다.
후보 개수가 가장 적은 타일은 후보를 3개 가지는 타일인데 개수가 5개나 되므로 그 중에서 다음에 붕괴할 타일을 랜덤으로 결정한다.
이 과정을 모든 타일이 붕괴할 때까지 반복하면 된다.
4. 결과


결과적으로 위 오른쪽 이미지가 완성된다.
설정한 규칙인 타일끼리 맞닿은 선이 이어져야 한다 를 지키지만 랜덤으로 타일이 배치된다.
예시로 든 규칙은 간단해서 예외가 발생하지 않았지만,
규칙에 따라 운이 안 좋다면 후보가 0개여서 붕괴할 수 없는 셀도 존재할 수 있으니 주의해야 한다.
알고리즘은 아래 과정을 따르면 된다.
- 원하는 규칙을 정한다.
- 셀의 후보 개수가 적은 순으로 나열하고, 후보 개수가 동일하다면 그 중에 하나를 랜덤으로 선택하여 붕괴
- 셀이 붕괴되면 붕괴된 셀의 종류에 따라 4방향 이웃의 후보 개수를 갱신
- 위 과정을 모든 셀이 붕괴될 때까지 반복
실제 알고리즘은 이해하기 어렵지 않다.
이제 유니티에서 코드를 어떻게 작성하는지 살펴보자.
4. 코드
Cell.cs
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Cell : MonoBehaviour
{
[SerializeField] private Image _image;
public bool Collapsed;
public List<Tile> TileOptions;
private void Awake()
{
_image.color = Color.black;
}
public void CollapseCell(Tile tile)
{
_image.sprite = tile.Sprite;
_image.color = Color.white;
}
}
타일이 배치될 Cell 한 칸에 대한 스크립트이다.
Cell이 붕괴될 때 스프라이트를 붕괴된 Tile 스프라이트로 교체한다.
Tile.cs
using System;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour
{
[SerializeField] private Sprite _sprite;
[SerializeField] private int _tileType;
[SerializeField] private List<Rule> _ruleList;
private Dictionary<Direction, List<int>> _rules = new();
public Sprite Sprite => _sprite;
public int TileType => _tileType;
public Dictionary<Direction, List<int>> Rules => _rules;
public void Init()
{
_rules[Direction.Up] = new();
_rules[Direction.Right] = new();
_rules[Direction.Down] = new();
_rules[Direction.Left] = new();
foreach(Rule rule in _ruleList)
{
foreach (int tileType in rule.TileTypes)
{
_rules[rule.Direction].Add(tileType);
}
}
}
}
[Serializable]
public struct Rule
{
public Direction Direction;
public List<int> TileTypes;
}
public enum Direction
{
Up,
Right,
Down,
Left
}
각 타일 종류에 대한 스크립트이다.
해당 타일의 이웃(위쪽, 오른쪽, 아래쪽, 왼쪽)으로 배치할 수 있는 타일 종류를 규칙에 추가해주면 된다.
WaveFunction.cs
코드가 길기 때문에 하나씩 살펴보자.
1. StartWaveFunctionCollapse()
/// <summary>
/// 파동 함수 붕괴 알고리즘을 실행하여 생성 시작
/// </summary>
public void StartWaveFunctionCollapse()
{
_gridComponents.Clear();
InitTiles();
InitGrid();
}
private void InitTiles()
{
foreach (Tile tile in _tiles)
{
tile.Init();
}
}
private void InitGrid()
{
_gridComponents.Clear();
iterations = 0;
for (int y = 0; y < _dimensions; y++)
{
for (int x = 0; x < _dimensions; x++)
{
Cell newCell = Instantiate(_cellPrefab, _cellParent);
newCell.TileOptions.AddRange(_tiles);
newCell.Collapsed = false;
_gridComponents.Add(newCell);
}
}
StartCoroutine(CheckEntropy());
}
Tile마다 규칙 Dictionary를 추가해주고, Cell을 생성해준다.
Cell은 Image가 붙어있으며, Grid Layout Group을 컴포넌트로 가지는 오브젝트의 자식으로 Instantiate해준다.
2. CheckEntropy()
private IEnumerator CheckEntropy()
{
_tempGrid.Clear();
int min = _tiles.Count;
// 후보가 가장 적은 cell 탐색
foreach (Cell cell in _gridComponents)
{
if (cell.Collapsed) continue;
if (cell.TileOptions.Count < min)
{
min = cell.TileOptions.Count;
}
}
foreach (Cell cell in _gridComponents)
{
if (cell.Collapsed) continue;
if (cell.TileOptions.Count == min)
{
_tempGrid.Add(cell);
}
}
// 셀이 순차적으로 붕괴되는 모습을 보여주기 위한 딜레이
yield return new WaitForSeconds(0.05f);
CollapseCell(_tempGrid);
}
GridComponents 안을 순회하며 붕괴하지 않은 Cell 중 가장 적은 후보를 가진 Cell을 전부 _tempGrid 에 저장한다.
위 코드에서는 셀이 하나씩 붕괴되는 과정을 보여주기 위해 코루틴을 사용했으므로, 코루틴을 사용할 필요는 없다.
3. CollapseCell(), SelectTile()
private void CollapseCell(List<Cell> tempGrid)
{
int randIndex = UnityEngine.Random.Range(0, tempGrid.Count);
// tempGrid 안에서 랜덤으로 셀 선택
Cell cellToCollapse = tempGrid[randIndex];
cellToCollapse.Collapsed = true;
int gridIndex = _gridComponents.IndexOf(cellToCollapse);
int cellX = gridIndex % _dimensions;
int cellY = gridIndex / _dimensions;
// 후보 중에서 랜덤으로 타일 선택
Tile selectedTile = SelectTile(cellToCollapse, cellX, cellY);
cellToCollapse.CollapseCell(selectedTile);
cellToCollapse.TileOptions.Clear();
cellToCollapse.TileOptions.Add(selectedTile);
UpdateGeneration(new Vector2Int(cellX, cellY));
}
private Tile SelectTile(Cell targetCell, int cellX, int cellY)
{
List<Tile> tileOptions = targetCell.TileOptions;
// 후보 중에서 랜덤으로 선택
int randIndex = UnityEngine.Random.Range(0, tileOptions.Count);
return tileOptions[randIndex];
}
이전에 구한 후보가 가장 적은 셀 중 하나를 랜덤으로 선택하고, SelectTile()을 통해 셀의 후보 중 하나를 랜덤으로 다시 선택하여 붕괴시켜준다.
4. UpdateGeneration
private void UpdateGeneration(Vector2Int coord)
{
Cell cell = _gridComponents[coord.x + coord.y * _dimensions];
// 이웃 (위쪽, 오른쪽, 아래쪽, 왼쪽)의 후보 변경
for (int i = 0; i < _directions.Length; i++)
{
int newX = coord.x + _directions[i].x;
int newY = coord.y + _directions[i].y;
int index = newX + newY * _dimensions;
if (newX < 0 || newY < 0
|| newX >= _dimensions || newY >= _dimensions) continue;
Cell neighborCell = _gridComponents[index];
// cell.TileOptions[0] : 붕괴된 셀의 타일
// (Direction)((i + 2) % 4) : 반대 방향 (ex. 위쪽 -> 아래쪽, 왼쪽 -> 오른쪽)
CheckValidity(cell.TileOptions[0].Rules[(Direction)i], neighborCell.TileOptions, (Direction)((i + 2) % 4));
}
iterations++;
if (iterations < _dimensions * _dimensions)
{
StartCoroutine(CheckEntropy());
}
}
private void CheckValidity(List<int> currentTileOptions, List<Tile> neighborTileOptions, Direction oppositeDirection)
{
_validOptions.Clear();
// 현재 이웃의 후보 중, 붕괴된 셀의 이웃에 올 수 있는 후보만 추가
foreach (Tile neighborTile in neighborTileOptions)
{
foreach (int currentTileOption in currentTileOptions)
{
if (neighborTile.TileType == currentTileOption)
{
_validOptions.Add(neighborTile);
break;
}
}
}
neighborTileOptions.Clear();
neighborTileOptions.AddRange(_validOptions);
}
셀 하나가 붕괴되었으므로 해당 셀의 이웃 (위쪽, 오른쪽, 아래쪽, 왼쪽)의 이웃 후보를 갱신해준다.
기존 이웃의 후보 중에서 붕괴된 셀의 이웃으로 올 수 있는 후보만 저장하고, 나머지 해당 후보만 제외한다.
갱신이 끝났다면 CheckEntropy() 를 실행하여 다음 셀을 붕괴시켜주고, 이를 모든 셀이 붕괴될 때까지 반복한다.
5. 전체 코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaveFunction : MonoBehaviour
{
[SerializeField] private Transform _cellParent;
[SerializeField] private Cell _cellPrefab;
[SerializeField] private List<Tile> _tiles;
[SerializeField] private int _dimensions;
[SerializeField] private int iterations = 0;
private List<Cell> _gridComponents = new();
private List<Cell> _tempGrid = new();
private HashSet<Tile> _validOptions = new();
private Vector2Int[] _directions = new[]
{
new Vector2Int(0, -1),
new Vector2Int(1, 0),
new Vector2Int(0, 1),
new Vector2Int(-1, 0)
};
private void Start() => StartWaveFunctionCollapse();
/// <summary>
/// 파동 함수 붕괴 알고리즘을 실행하여 맵 생성 시작
/// </summary>
public void StartWaveFunctionCollapse()
{
_gridComponents.Clear();
InitTiles();
InitGrid();
}
private void InitTiles()
{
foreach (Tile tile in _tiles)
{
tile.Init();
}
}
private void InitGrid()
{
_gridComponents.Clear();
iterations = 0;
for (int y = 0; y < _dimensions; y++)
{
for (int x = 0; x < _dimensions; x++)
{
Cell newCell = Instantiate(_cellPrefab, _cellParent);
newCell.TileOptions.AddRange(_tiles);
newCell.Collapsed = false;
_gridComponents.Add(newCell);
}
}
StartCoroutine(CheckEntropy());
}
private IEnumerator CheckEntropy()
{
_tempGrid.Clear();
int min = _tiles.Count;
// 후보가 가장 적은 cell 탐색
foreach (Cell cell in _gridComponents)
{
if (cell.Collapsed) continue;
if (cell.TileOptions.Count < min)
{
min = cell.TileOptions.Count;
}
}
foreach (Cell cell in _gridComponents)
{
if (cell.Collapsed) continue;
if (cell.TileOptions.Count == min)
{
_tempGrid.Add(cell);
}
}
// 타일이 순차적으로 생성되는 모습을 보여주기 위한 딜레이
yield return new WaitForSeconds(0.05f);
CollapseCell(_tempGrid);
}
private void CollapseCell(List<Cell> tempGrid)
{
int randIndex = UnityEngine.Random.Range(0, tempGrid.Count);
// tempGrid 안에서 랜덤으로 셀 선택
Cell cellToCollapse = tempGrid[randIndex];
cellToCollapse.Collapsed = true;
int gridIndex = _gridComponents.IndexOf(cellToCollapse);
int cellX = gridIndex % _dimensions;
int cellY = gridIndex / _dimensions;
// 후보 중에서 랜덤으로 타일 선택
Tile selectedTile = SelectTile(cellToCollapse, cellX, cellY);
cellToCollapse.CollapseCell(selectedTile);
cellToCollapse.TileOptions.Clear();
cellToCollapse.TileOptions.Add(selectedTile);
UpdateGeneration(new Vector2Int(cellX, cellY));
}
private Tile SelectTile(Cell targetCell, int cellX, int cellY)
{
List<Tile> tileOptions = targetCell.TileOptions;
// 후보 중에서 랜덤으로 선택
int randIndex = UnityEngine.Random.Range(0, tileOptions.Count);
return tileOptions[randIndex];
}
private void UpdateGeneration(Vector2Int coord)
{
Cell cell = _gridComponents[coord.x + coord.y * _dimensions];
for (int i = 0; i < _directions.Length; i++)
{
int newX = coord.x + _directions[i].x;
int newY = coord.y + _directions[i].y;
int index = newX + newY * _dimensions;
if (newX < 0 || newY < 0
|| newX >= _dimensions || newY >= _dimensions) continue;
Cell neighborCell = _gridComponents[index];
// cell.TileOptions[0] : 붕괴된 셀의 타일
// (Direction)((i + 2) % 4) : 반대 방향 (ex. 위쪽 -> 아래쪽, 왼쪽 -> 오른쪽)
CheckValidity(cell.TileOptions[0].Rules[(Direction)i], neighborCell.TileOptions, (Direction)((i + 2) % 4));
}
iterations++;
if (iterations < _dimensions * _dimensions)
{
StartCoroutine(CheckEntropy());
}
}
private void CheckValidity(List<int> currentTileOptions, List<Tile> neighborTileOptions, Direction oppositeDirection)
{
_validOptions.Clear();
foreach (Tile neighborTile in neighborTileOptions)
{
foreach (int currentTileOption in currentTileOptions)
{
if (neighborTile.TileType == currentTileOption)
{
_validOptions.Add(neighborTile);
break;
}
}
}
neighborTileOptions.Clear();
neighborTileOptions.AddRange(_validOptions);
}
}
6. 결과





위처럼 실행할 때마다 매번 다른 결과가 나온다.
기존 파동 함수 붕괴 알고리즘은 붕괴된 셀 이웃의 후보 개수가 갱신되면, 해당 이웃 셀의 이웃도 후보를 갱신해야 하지만, 간단한 맵 생성에서는 위 코드로도 문제 없이 생성된다.



