LCOV - code coverage report
Current view: top level - maptemplate - template.go Coverage Total Hit
Test: coverage.lcov Lines: 91.9 % 568 522
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package maptemplate
       2              : 
       3              : import (
       4              :         "errors"
       5              :         "fmt"
       6              :         "io"
       7              :         "io/fs"
       8              :         "maps"
       9              :         "math/rand/v2"
      10              :         "slices"
      11              :         "strconv"
      12              :         "strings"
      13              :         "sync"
      14              :         "unicode"
      15              :         "unicode/utf8"
      16              : 
      17              :         "github.com/kijimaD/ruins/assets"
      18              :         "github.com/kijimaD/ruins/internal/consts"
      19              :         "github.com/pelletier/go-toml/v2"
      20              : )
      21              : 
      22              : // placeholderChar はプレースホルダ領域を示す文字
      23              : const placeholderChar = '@'
      24              : 
      25              : // placeholderStr はプレースホルダの文字列表現
      26              : const placeholderStr = "@"
      27              : 
      28              : // GroundTerrain はその場所の下地をそのまま残す地形。施設の庭や敷地の外に使い、置かれた区分の下地とつなげる。
      29              : // 地上では施設より先に置く地物のタイルも残るので、施設より先の地物は土の地面以外を置かない。施設を置くときに下が土の地面かを確かめる。
      30              : // ダンジョンのテンプレートで使うときは、そのダンジョンの行に下地 ground が要る
      31              : const GroundTerrain = "ground"
      32              : 
      33              : var (
      34              :         // errInvalidChunkName はチャンク名が "{幅}x{高さ}_名前" 形式でないときに返す
      35              :         errInvalidChunkName = errors.New("chunk name must be in '{width}x{height}_name' format")
      36              :         // errInvalidWidth はチャンク名の幅が整数でないときに返す
      37              :         errInvalidWidth = errors.New("failed to parse width")
      38              :         // errInvalidHeight はチャンク名の高さが整数でないときに返す
      39              :         errInvalidHeight = errors.New("failed to parse height")
      40              :         // errNonPositiveWeight は重みが正の整数でないときに返す
      41              :         errNonPositiveWeight = errors.New("weight must be a positive integer")
      42              :         // errNonPositiveSize はサイズが正の整数でないときに返す
      43              :         errNonPositiveSize = errors.New("size must be a positive integer")
      44              :         // errMapEmpty はマップが空のときに返す
      45              :         errMapEmpty = errors.New("map is empty")
      46              :         // errMapRowEmpty はマップの行が空のときに返す
      47              :         errMapRowEmpty = errors.New("map row is empty")
      48              :         // errMapRowLengthMismatch はマップの行ごとの長さが揃っていないときに返す
      49              :         errMapRowLengthMismatch = errors.New("map row length mismatch")
      50              :         // errInvalidEdge は部屋の絵の辺の種類が wall・door・open のどれでもないときに返す
      51              :         errInvalidEdge = errors.New("room edge must be wall, door or open")
      52              :         // errMapNotASCII はマップに ASCII でない文字があるときに返す
      53              :         errMapNotASCII = errors.New("map has a non-ASCII character")
      54              :         // errMapSizeMismatch はマップの実サイズが名前で定義したサイズと一致しないときに返す
      55              :         errMapSizeMismatch = errors.New("map size does not match defined size")
      56              :         // errCoordinateOutOfRange は座標がマップの範囲外のときに返す
      57              :         errCoordinateOutOfRange = errors.New("coordinate out of range")
      58              :         // errChunkNotFound は指定名のチャンクが登録されていないときに返す
      59              :         errChunkNotFound = errors.New("chunk not found")
      60              :         // errPaletteNotFound は指定名のパレットが登録されていないときに返す
      61              :         errPaletteNotFound = errors.New("palette not found")
      62              :         // errNoChunkCandidate は選択できるチャンク候補がないときに返す
      63              :         errNoChunkCandidate = errors.New("chunk candidates are empty or total weight is 0")
      64              :         // errExpansionDepthExceeded はチャンク展開の深さが上限を超えたときに返す
      65              :         errExpansionDepthExceeded = errors.New("chunk expansion depth exceeded limit")
      66              :         // errCircularChunkReference はチャンクの循環参照を検出したときに返す
      67              :         errCircularChunkReference = errors.New("detected circular chunk reference")
      68              :         // errPlacementIDMissing はplacementのIDが未指定のときに返す
      69              :         errPlacementIDMissing = errors.New("ID is not specified")
      70              :         // errPlaceholderRemains は展開後のマップにプレースホルダが残っているときに返す
      71              :         errPlaceholderRemains = errors.New("unexpanded placeholder '@' remains in expanded map")
      72              :         // errIdentifierNotSingleChar は識別子が1文字でないときに返す
      73              :         errIdentifierNotSingleChar = errors.New("identifier must be a single character")
      74              :         // errIdentifierNotFound は識別子がマップ中に見つからないときに返す
      75              :         errIdentifierNotFound = errors.New("identifier not found")
      76              :         // errRegionIncomplete はプレースホルダの矩形領域がマップの範囲外にはみ出すときに返す
      77              :         errRegionIncomplete = errors.New("rectangular region is incomplete")
      78              :         // errInvalidPlaceholderChar はプレースホルダ領域に@と識別子以外の文字があるときに返す
      79              :         errInvalidPlaceholderChar = errors.New("invalid char")
      80              :         // errRegionSizeMismatch はプレースホルダ領域とチャンクのサイズが一致しないときに返す
      81              :         errRegionSizeMismatch = errors.New("placeholder region size does not match chunk size")
      82              : )
      83              : 
      84              : // MapCell はマップの1セルを表す解決済みオブジェクト。
      85              : // 各チャンクがパレットを独立に解決した結果を保持する
      86              : type MapCell struct {
      87              :         Terrain   string // 地形名
      88              :         Prop      string // Prop ID(なければ空文字)
      89              :         NPC       string // NPC ID(なければ空文字)
      90              :         LootTable string // 収納の中身を引く itemTables の id。収納でなければ空
      91              :         ItemGroup string // 床に落ちる戦利品の itemGroup の id。無ければ空
      92              :         ItemCount int    // ItemGroup から引く回数。パレットの確率と回数の範囲から解決済み
      93              :         Being     bool   // 施設の敵の表から1体置く
      94              : }
      95              : 
      96              : // ResolveMapCells はマップ文字列をパレットで解決し、セル配列に変換する。
      97              : // パレットで解決できない文字は文字自体をTerrain名として使用する。prop の候補は rng で選ぶ
      98              : func ResolveMapCells(mapStr string, palette *Palette, rng *rand.Rand) [][]MapCell {
      99            1 :         lines := strings.Split(strings.TrimSpace(mapStr), "\n")
     100            1 :         cells := make([][]MapCell, len(lines))
     101            1 :         for y, line := range lines {
     102            1 :                 runes := []rune(line)
     103            1 :                 cells[y] = make([]MapCell, len(runes))
     104            1 :                 for x, ch := range runes {
     105            1 :                         charStr := string(ch)
     106            1 :                         var cell MapCell
     107            1 :                         if palette != nil {
     108            1 :                                 if terrain, ok := palette.GetTerrain(charStr); ok {
     109            1 :                                         cell.Terrain = terrain
     110            1 :                                 }
     111            1 :                                 if prop, lootTable, ok := palette.GetProp(charStr, rng); ok {
     112            1 :                                         cell.Prop = prop
     113            1 :                                         cell.LootTable = lootTable
     114            1 :                                 }
     115            1 :                                 if npc, ok := palette.GetNPC(charStr); ok {
     116            1 :                                         cell.NPC = npc
     117            1 :                                 }
     118            1 :                                 if item, ok := palette.Items[charStr]; ok {
     119            1 :                                         cell.ItemGroup = item.ItemGroup
     120            1 :                                         cell.ItemCount = item.roll(rng)
     121            1 :                                 }
     122            1 :                                 if being, ok := palette.Beings[charStr]; ok {
     123            1 :                                         chance := chancePercent(being.Chance)
     124            1 :                                         cell.Being = chance == 100 || rng.IntN(100) < chance
     125            1 :                                 }
     126              :                         }
     127              :                         // パレットで解決できなかった場合、文字自体をTerrain名として使用する
     128            1 :                         if cell.Terrain == "" {
     129            1 :                                 cell.Terrain = charStr
     130            1 :                         }
     131            1 :                         cells[y][x] = cell
     132              :                 }
     133              :         }
     134            1 :         return cells
     135              : }
     136              : 
     137              : // FormatResolvedMap はセル配列を可読文字列に変換する。
     138              : // 各セルは "terrain" 形式で、prop/NPCがあれば "terrain:prop" や "terrain:prop:npc" になる
     139              : func FormatResolvedMap(cells [][]MapCell) string {
     140            1 :         var sb strings.Builder
     141            1 :         for y, row := range cells {
     142            1 :                 if y > 0 {
     143            1 :                         sb.WriteByte('\n')
     144            1 :                 }
     145            1 :                 for x, cell := range row {
     146            1 :                         if x > 0 {
     147            1 :                                 sb.WriteByte(' ')
     148            1 :                         }
     149            1 :                         sb.WriteString(cell.Terrain)
     150            1 :                         if cell.Prop != "" || cell.NPC != "" {
     151            1 :                                 sb.WriteByte(':')
     152            1 :                                 sb.WriteString(cell.Prop)
     153            1 :                         }
     154            1 :                         if cell.NPC != "" {
     155            1 :                                 sb.WriteByte(':')
     156            1 :                                 sb.WriteString(cell.NPC)
     157            1 :                         }
     158              :                 }
     159              :         }
     160            1 :         return sb.String()
     161              : }
     162              : 
     163              : // ChunkTemplate はチャンクテンプレート定義
     164              : // すべてのマップ要素(小さな部品から大きなレイアウトまで)を表す
     165              : type ChunkTemplate struct {
     166              :         Name        string           `toml:"name"`     // キー
     167              :         Facility    string           `toml:"facility"` // この絵を使う施設の id。施設の絵でなければ空
     168              :         Edges       *ChunkEdges      `toml:"edges"`    // 部屋の絵の4つの辺の種類。複数のチャンクにまたがる建物の部屋でなければ省く
     169              :         Weight      int              `toml:"weight"`   // 出現確率の重み
     170              :         Size        Size             // マップサイズ(名前から自動パース)
     171              :         Palettes    []string         `toml:"palettes"`      // 使用するパレットID
     172              :         Map         string           `toml:"map,multiline"` // ASCIIマップ
     173              :         Placements  []ChunkPlacement `toml:"placements"`    // ネストされたチャンクの配置
     174              :         SpawnPoints []SpawnPoint     `toml:"spawn_points"`  // スポーン地点の配置
     175              : }
     176              : 
     177              : // EdgeKind は部屋の絵の辺の種類
     178              : type EdgeKind string
     179              : 
     180              : const (
     181              :         // EdgeWall は辺の全体が壁
     182              :         EdgeWall EdgeKind = "wall"
     183              :         // EdgeDoor は辺の真ん中の2マスが扉で、残りが壁
     184              :         EdgeDoor EdgeKind = "door"
     185              :         // EdgeOpen は辺の全体が吹き抜け
     186              :         EdgeOpen EdgeKind = "open"
     187              : )
     188              : 
     189              : // ChunkEdges は部屋の絵の北・東・南・西の辺の種類
     190              : type ChunkEdges struct {
     191              :         North EdgeKind `toml:"north"`
     192              :         East  EdgeKind `toml:"east"`
     193              :         South EdgeKind `toml:"south"`
     194              :         West  EdgeKind `toml:"west"`
     195              : }
     196              : 
     197              : // array は辺を北・東・南・西の順に並べる
     198              : func (e ChunkEdges) array() [4]EdgeKind {
     199            1 :         return [4]EdgeKind{e.North, e.East, e.South, e.West}
     200            1 : }
     201              : 
     202              : // transformEdges は TransformCells と同じく、左右に反転してから左回りに quarterTurns 回だけ回したときの辺を返す。
     203              : // 左回りに回すと、北の辺は西へ、東は北へ、南は東へ、西は南へ移る
     204              : func transformEdges(edges [4]EdgeKind, quarterTurns int, mirror bool) [4]EdgeKind {
     205            1 :         n, e, s, w := edges[0], edges[1], edges[2], edges[3]
     206            1 :         if mirror {
     207            1 :                 e, w = w, e
     208            1 :         }
     209            1 :         for range ((quarterTurns % 4) + 4) % 4 {
     210            1 :                 n, e, s, w = e, s, w, n
     211            1 :         }
     212            1 :         return [4]EdgeKind{n, e, s, w}
     213              : }
     214              : 
     215              : // Size はマップのサイズ(幅×高さ)を表す
     216              : type Size struct {
     217              :         W int // 幅
     218              :         H int // 高さ
     219              : }
     220              : 
     221              : // String はサイズを "{幅}x{高さ}" 形式の文字列として返す
     222              : func (s Size) String() string {
     223            1 :         return fmt.Sprintf("%dx%d", s.W, s.H)
     224            1 : }
     225              : 
     226              : // ChunkPlacement はネストされたチャンクの配置情報
     227              : type ChunkPlacement struct {
     228              :         // チャンク名の配列(重み付き選択)
     229              :         // バリエーションの出し方には2つある
     230              :         // - マイナーな違い(内装配置の違いなど): 同じ名前で作成する
     231              :         //   例: chunks = ["11x6_convenience_store"] → 2つの11x6_convenience_store, 11x6_convenience_store から選択する
     232              :         // - メジャーな違い(異なる用途の建物など): 異なる名前を配列で列挙する
     233              :         //   例: chunks = ["11x6_convenience_store", "11x6_clinic"] → コンビニか整骨院のどちらかが選ばれる
     234              :         Chunks []string `toml:"chunks"`
     235              :         ID     string   `toml:"id"` // プレースホルダ識別子(右下に配置される1文字)
     236              : }
     237              : 
     238              : // SpawnPoint はスポーン地点の配置情報
     239              : // TOMLから読み込んだ後、mapplannerで使用される
     240              : type SpawnPoint struct {
     241              :         X int `toml:"x" json:"x"` // X座標
     242              :         Y int `toml:"y" json:"y"` // Y座標
     243              : }
     244              : 
     245              : // ChunkTemplateFile はTOMLファイルのルート構造
     246              : type ChunkTemplateFile struct {
     247              :         Chunks []ChunkTemplate `toml:"chunk"`
     248              : }
     249              : 
     250              : // TemplateLoader はテンプレート定義の読み込みを担当する
     251              : type TemplateLoader struct {
     252              :         chunkCache   map[string][]*ChunkTemplate // 同じ名前で複数のバリエーションをサポート
     253              :         paletteCache map[string]*Palette
     254              : }
     255              : 
     256              : // NewTemplateLoader はTemplateLoaderを生成する
     257              : func NewTemplateLoader() *TemplateLoader {
     258            1 :         return &TemplateLoader{
     259            1 :                 chunkCache:   make(map[string][]*ChunkTemplate),
     260            1 :                 paletteCache: make(map[string]*Palette),
     261            1 :         }
     262              : }
     263              : 
     264              : // FacilityTemplates は施設の絵、部品、パレットを読み込んだ loader を返す。資材は埋め込みで実行中に変わらないので、読み込みは1度だけ行う
     265              : func FacilityTemplates() (*TemplateLoader, error) {
     266            1 :         return loadFacilityTemplates()
     267            1 : }
     268              : 
     269              : var loadFacilityTemplates = sync.OnceValues(func() (*TemplateLoader, error) {
     270            1 :         l := NewTemplateLoader()
     271            1 :         if err := l.RegisterAllChunks([]string{"levels/chunks", "levels/facilities", "levels/layouts"}); err != nil {
     272            0 :                 return nil, err
     273            0 :         }
     274            1 :         if err := l.RegisterAllPalettes([]string{"levels/palettes"}); err != nil {
     275            0 :                 return nil, err
     276            0 :         }
     277            1 :         return l, nil
     278              : })
     279              : 
     280              : // Load はio.Readerからチャンクテンプレート定義を読み込む
     281              : func (l *TemplateLoader) Load(r io.Reader) ([]ChunkTemplate, error) {
     282            1 :         data, err := io.ReadAll(r)
     283            1 :         if err != nil {
     284            0 :                 return nil, fmt.Errorf("failed to read template: %w", err)
     285            0 :         }
     286              : 
     287            1 :         var file ChunkTemplateFile
     288            1 :         if err := toml.Unmarshal(data, &file); err != nil {
     289            1 :                 return nil, fmt.Errorf("failed to parse template TOML: %w", err)
     290            1 :         }
     291              : 
     292            1 :         for i := range file.Chunks {
     293              :                 // 名前からサイズを自動設定
     294            1 :                 if err := l.parseSizeFromName(&file.Chunks[i]); err != nil {
     295            1 :                         return nil, fmt.Errorf("failed to parse template %d name: %w", i, err)
     296            1 :                 }
     297              : 
     298            1 :                 if err := l.validate(&file.Chunks[i]); err != nil {
     299            1 :                         return nil, fmt.Errorf("failed to validate template %d: %w", i, err)
     300            1 :                 }
     301              :         }
     302              : 
     303            1 :         return file.Chunks, nil
     304              : }
     305              : 
     306              : // LoadFile はTOMLファイルからチャンクテンプレート定義を読み込む
     307              : func (l *TemplateLoader) LoadFile(path string) ([]ChunkTemplate, error) {
     308            1 :         f, err := assets.FS.Open(path)
     309            1 :         if err != nil {
     310            1 :                 return nil, fmt.Errorf("failed to read template file: %w", err)
     311            1 :         }
     312            2 :         defer func() { _ = f.Close() }()
     313              : 
     314            1 :         return l.Load(f)
     315              : }
     316              : 
     317              : // parseSizeFromName は名前から "{幅}x{高さ}_" 形式のサイズをパースする
     318              : // 例: "5x5_meeting_room" -> Size = [5, 5]
     319              : func (l *TemplateLoader) parseSizeFromName(t *ChunkTemplate) error {
     320              :         // 名前から "{幅}x{高さ}_" 形式を探す
     321            1 :         parts := strings.Split(t.Name, "_")
     322            1 :         if len(parts) == 0 {
     323            0 :                 return fmt.Errorf("chunk name is empty")
     324            0 :         }
     325              : 
     326              :         // 最初の部分が "{幅}x{高さ}" 形式かチェック
     327            1 :         sizePart := parts[0]
     328            1 :         dimensions := strings.Split(sizePart, "x")
     329            1 :         if len(dimensions) != 2 {
     330            1 :                 return fmt.Errorf("%w: %s", errInvalidChunkName, t.Name)
     331            1 :         }
     332              : 
     333            1 :         width, err := strconv.Atoi(dimensions[0])
     334            1 :         if err != nil {
     335            1 :                 return fmt.Errorf("%w: %s", errInvalidWidth, dimensions[0])
     336            1 :         }
     337              : 
     338            1 :         height, err := strconv.Atoi(dimensions[1])
     339            1 :         if err != nil {
     340            1 :                 return fmt.Errorf("%w: %s", errInvalidHeight, dimensions[1])
     341            1 :         }
     342              : 
     343            1 :         t.Size = Size{W: width, H: height}
     344            1 :         return nil
     345              : }
     346              : 
     347              : // validate はテンプレート定義の妥当性を検証する
     348              : func (l *TemplateLoader) validate(t *ChunkTemplate) error {
     349            1 :         if t.Name == "" {
     350            0 :                 return fmt.Errorf("chunk name key is empty")
     351            0 :         }
     352              : 
     353            1 :         if t.Weight <= 0 {
     354            1 :                 return fmt.Errorf("%w: %d", errNonPositiveWeight, t.Weight)
     355            1 :         }
     356              : 
     357            1 :         if t.Size.W <= 0 || t.Size.H <= 0 {
     358            1 :                 return fmt.Errorf("%w: %s", errNonPositiveSize, t.Size)
     359            1 :         }
     360              : 
     361            1 :         return l.validateMap(t)
     362              : }
     363              : 
     364              : // validateMap はマップの妥当性を検証する
     365              : func (l *TemplateLoader) validateMap(t *ChunkTemplate) error {
     366            1 :         if t.Edges != nil {
     367            1 :                 for _, e := range t.Edges.array() {
     368            1 :                         if e != EdgeWall && e != EdgeDoor && e != EdgeOpen {
     369            1 :                                 return fmt.Errorf("%w: %q", errInvalidEdge, e)
     370            1 :                         }
     371              :                 }
     372              :         }
     373            1 :         if t.Map == "" {
     374            1 :                 return errMapEmpty
     375            1 :         }
     376              : 
     377            1 :         lines := strings.Split(strings.TrimSpace(t.Map), "\n")
     378            1 :         if len(lines) == 0 {
     379            0 :                 return errMapEmpty
     380            0 :         }
     381              : 
     382            1 :         expectedWidth := utf8.RuneCountInString(lines[0])
     383            1 :         if expectedWidth == 0 {
     384            1 :                 return errMapRowEmpty
     385            1 :         }
     386              : 
     387            1 :         for i, line := range lines {
     388              :                 // プレースホルダや部品の位置はバイトの添字で引くので、1文字を1バイトに限る
     389            2 :                 if j := strings.IndexFunc(line, func(r rune) bool { return r > unicode.MaxASCII }); j >= 0 {
     390            1 :                         return fmt.Errorf("%w: row %d byte %d", errMapNotASCII, i, j)
     391            1 :                 }
     392            1 :                 lineWidth := utf8.RuneCountInString(line)
     393            1 :                 if lineWidth != expectedWidth {
     394            1 :                         return fmt.Errorf("%w: row %d expected %d, got %d", errMapRowLengthMismatch, i, expectedWidth, lineWidth)
     395            1 :                 }
     396              :         }
     397              : 
     398            1 :         actualWidth := expectedWidth
     399            1 :         actualHeight := len(lines)
     400            1 :         if actualWidth != t.Size.W || actualHeight != t.Size.H {
     401            1 :                 return fmt.Errorf("%w: actual size [%d, %d], defined size %s", errMapSizeMismatch, actualWidth, actualHeight, t.Size)
     402            1 :         }
     403              : 
     404            1 :         return nil
     405              : }
     406              : 
     407              : // GetMapLines はマップを行の配列として取得する
     408              : func (t *ChunkTemplate) GetMapLines() []string {
     409            1 :         return strings.Split(strings.TrimSpace(t.Map), "\n")
     410            1 : }
     411              : 
     412              : // GetCharAt は指定座標の文字を取得する
     413              : func (t *ChunkTemplate) GetCharAt(x, y int) (string, error) {
     414            1 :         lines := t.GetMapLines()
     415            1 :         if y < 0 || y >= len(lines) {
     416            1 :                 return "", fmt.Errorf("y %w: %d", errCoordinateOutOfRange, y)
     417            1 :         }
     418            1 :         if x < 0 || x >= len(lines[y]) {
     419            1 :                 return "", fmt.Errorf("x %w: %d", errCoordinateOutOfRange, x)
     420            1 :         }
     421            1 :         return string(lines[y][x]), nil
     422              : }
     423              : 
     424              : // LoadChunk はチャンク定義を読み込んでキャッシュする
     425              : // 同じ名前のチャンクが複数ある場合、すべて登録される(バリエーション)
     426              : func (l *TemplateLoader) LoadChunk(path string) error {
     427            1 :         templates, err := l.LoadFile(path)
     428            1 :         if err != nil {
     429            1 :                 return fmt.Errorf("failed to read chunk: %w", err)
     430            1 :         }
     431              : 
     432            1 :         for i := range templates {
     433            1 :                 name := templates[i].Name
     434            1 :                 l.chunkCache[name] = append(l.chunkCache[name], &templates[i])
     435            1 :         }
     436              : 
     437            1 :         return nil
     438              : }
     439              : 
     440              : // GetChunks はキャッシュから指定名のすべてのチャンクバリエーションを取得する
     441              : func (l *TemplateLoader) GetChunks(chunkName string) ([]*ChunkTemplate, error) {
     442            1 :         chunks, ok := l.chunkCache[chunkName]
     443            1 :         if !ok || len(chunks) == 0 {
     444            1 :                 return nil, fmt.Errorf("%w: '%s'", errChunkNotFound, chunkName)
     445            1 :         }
     446            1 :         return chunks, nil
     447              : }
     448              : 
     449              : // Facilities は絵が登録されている施設の id を昇順で返す
     450              : func (l *TemplateLoader) Facilities() []string {
     451            1 :         set := map[string]bool{}
     452            1 :         for _, chunks := range l.chunkCache {
     453            1 :                 for _, c := range chunks {
     454            1 :                         if c.Facility != "" {
     455            1 :                                 set[c.Facility] = true
     456            1 :                         }
     457              :                 }
     458              :         }
     459            1 :         return slices.Sorted(maps.Keys(set))
     460              : }
     461              : 
     462              : // FacilityChunkNames は施設 facility の絵の名前を昇順で返す
     463              : func (l *TemplateLoader) FacilityChunkNames(facility string) []string {
     464            1 :         var names []string
     465            1 :         for _, name := range slices.Sorted(maps.Keys(l.chunkCache)) {
     466            2 :                 if slices.ContainsFunc(l.chunkCache[name], func(c *ChunkTemplate) bool { return c.Facility == facility }) {
     467            1 :                         names = append(names, name)
     468            1 :                 }
     469              :         }
     470            1 :         return names
     471              : }
     472              : 
     473              : // FacilityChunk は施設 facility の1棟の絵から重み付きで1枚選び、展開したセル配列を返す。部屋の絵は選ばない
     474              : func (l *TemplateLoader) FacilityChunk(facility string, seed uint64) (*ChunkTemplate, [][]MapCell, error) {
     475            1 :         var candidates []*ChunkTemplate
     476            1 :         for _, name := range slices.Sorted(maps.Keys(l.chunkCache)) {
     477            1 :                 for _, c := range l.chunkCache[name] {
     478            1 :                         if c.Facility == facility && c.Edges == nil {
     479            1 :                                 candidates = append(candidates, c)
     480            1 :                         }
     481              :                 }
     482              :         }
     483            1 :         chunk, err := l.selectChunkByWeightFromList(candidates, rand.New(rand.NewPCG(seed, mixSeed(seed, 0))))
     484            1 :         if err != nil {
     485            1 :                 return nil, nil, fmt.Errorf("facility '%s': %w", facility, err)
     486            1 :         }
     487            1 :         cells, err := chunk.ExpandWithPlacements(l, mixSeed(seed, 1))
     488            1 :         if err != nil {
     489            0 :                 return nil, nil, err
     490            0 :         }
     491            1 :         return chunk, cells, nil
     492              : }
     493              : 
     494              : // HasRooms は施設 facility が部屋の絵を持つかを返す
     495              : func (l *TemplateLoader) HasRooms(facility string) bool {
     496            1 :         for _, chunks := range l.chunkCache {
     497            2 :                 if slices.ContainsFunc(chunks, func(c *ChunkTemplate) bool { return c.Facility == facility && c.Edges != nil }) {
     498            1 :                         return true
     499            1 :                 }
     500              :         }
     501            0 :         return false
     502              : }
     503              : 
     504              : // roomChoice は部屋の絵と、辺を合わせる向き
     505              : type roomChoice struct {
     506              :         chunk  *ChunkTemplate
     507              :         turns  int
     508              :         mirror bool
     509              : }
     510              : 
     511              : // FacilityRoom は施設 facility の部屋の絵から、北・東・南・西の辺が edges になる絵と向きを重みで1つ選び、
     512              : // 展開して向きを合わせたセル配列を返す。1枚の絵は回転と反転で、合う向きの数だけ候補になる
     513              : func (l *TemplateLoader) FacilityRoom(facility string, edges [4]EdgeKind, seed uint64) (*ChunkTemplate, [][]MapCell, error) {
     514            1 :         var choices []roomChoice
     515            1 :         for _, name := range slices.Sorted(maps.Keys(l.chunkCache)) {
     516            1 :                 for _, c := range l.chunkCache[name] {
     517            1 :                         if c.Facility != facility || c.Edges == nil {
     518            1 :                                 continue
     519              :                         }
     520            1 :                         for _, mirror := range []bool{false, true} {
     521            1 :                                 for turns := range 4 {
     522            1 :                                         if transformEdges(c.Edges.array(), turns, mirror) == edges {
     523            1 :                                                 choices = append(choices, roomChoice{chunk: c, turns: turns, mirror: mirror})
     524            1 :                                         }
     525              :                                 }
     526              :                         }
     527              :                 }
     528              :         }
     529            2 :         i, ok := consts.Pick(rand.New(rand.NewPCG(seed, mixSeed(seed, 0))), choices, func(c roomChoice) float64 { return float64(c.chunk.Weight) })
     530            1 :         if !ok {
     531            1 :                 return nil, nil, fmt.Errorf("facility '%s' room %v: %w", facility, edges, errNoChunkCandidate)
     532            1 :         }
     533            1 :         c := choices[i]
     534            1 :         cells, err := c.chunk.ExpandWithPlacements(l, mixSeed(seed, 1))
     535            1 :         if err != nil {
     536            0 :                 return nil, nil, err
     537            0 :         }
     538            1 :         return c.chunk, TransformCells(cells, c.turns, c.mirror), nil
     539              : }
     540              : 
     541              : // TransformCells は絵を左右に反転してから、左回りに quarterTurns 回だけ90度回したセル配列を返す
     542              : func TransformCells(cells [][]MapCell, quarterTurns int, mirror bool) [][]MapCell {
     543            1 :         out := cells
     544            1 :         if mirror {
     545            1 :                 out = make([][]MapCell, len(cells))
     546            1 :                 for y, row := range cells {
     547            1 :                         out[y] = slices.Clone(row)
     548            1 :                         slices.Reverse(out[y])
     549            1 :                 }
     550              :         }
     551            1 :         for range ((quarterTurns % 4) + 4) % 4 {
     552            1 :                 h, w := len(out), len(out[0])
     553            1 :                 turned := make([][]MapCell, w)
     554            1 :                 for ny := range w {
     555            1 :                         turned[ny] = make([]MapCell, h)
     556            1 :                         for nx := range h {
     557            1 :                                 turned[ny][nx] = out[nx][w-1-ny]
     558            1 :                         }
     559              :                 }
     560            1 :                 out = turned
     561              :         }
     562            1 :         return out
     563              : }
     564              : 
     565              : // RegisterChunk はチャンクテンプレートをキャッシュに登録する
     566              : func (l *TemplateLoader) RegisterChunk(t *ChunkTemplate) {
     567            1 :         l.chunkCache[t.Name] = append(l.chunkCache[t.Name], t)
     568            1 : }
     569              : 
     570              : // RegisterPalette はパレットをキャッシュに登録する
     571              : func (l *TemplateLoader) RegisterPalette(p *Palette) {
     572            1 :         l.paletteCache[p.ID] = p
     573            1 : }
     574              : 
     575              : // RegisterAllChunks は指定されたディレクトリ配下のすべての.tomlファイルをチャンクとして登録する
     576              : func (l *TemplateLoader) RegisterAllChunks(directories []string) error {
     577            1 :         for _, dir := range directories {
     578            1 :                 entries, err := fs.ReadDir(assets.FS, dir)
     579            1 :                 if err != nil {
     580            1 :                         return fmt.Errorf("failed to read directory %s: %w", dir, err)
     581            1 :                 }
     582              : 
     583            1 :                 for _, entry := range entries {
     584            1 :                         if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".toml") {
     585            0 :                                 continue
     586              :                         }
     587              : 
     588            1 :                         path := dir + "/" + entry.Name()
     589            1 :                         if err := l.LoadChunk(path); err != nil {
     590            0 :                                 return err
     591            0 :                         }
     592              :                 }
     593              :         }
     594              : 
     595            1 :         return nil
     596              : }
     597              : 
     598              : // RegisterAllPalettes は指定されたディレクトリ配下のすべての.tomlファイルをパレットとして登録する
     599              : func (l *TemplateLoader) RegisterAllPalettes(directories []string) error {
     600            1 :         paletteLoader := NewPaletteLoader()
     601            1 : 
     602            1 :         for _, dir := range directories {
     603            1 :                 entries, err := fs.ReadDir(assets.FS, dir)
     604            1 :                 if err != nil {
     605            1 :                         return fmt.Errorf("failed to read directory %s: %w", dir, err)
     606            1 :                 }
     607              : 
     608            1 :                 for _, entry := range entries {
     609            1 :                         if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".toml") {
     610            0 :                                 continue
     611              :                         }
     612              : 
     613            1 :                         path := dir + "/" + entry.Name()
     614            1 :                         palette, err := paletteLoader.LoadFile(path)
     615            1 :                         if err != nil {
     616            0 :                                 return fmt.Errorf("failed to read palette %s: %w", path, err)
     617            0 :                         }
     618              : 
     619            1 :                         l.paletteCache[palette.ID] = palette
     620              :                 }
     621              :         }
     622              : 
     623            1 :         return nil
     624              : }
     625              : 
     626              : // LoadTemplateByName はテンプレート名で展開済みテンプレートとパレットと解決済みセル配列を取得する。
     627              : // 同じ名前のバリエーションが複数ある場合、重み付きランダム選択する。
     628              : // 各チャンクは自身のパレットで独立に解決する
     629              : func (l *TemplateLoader) LoadTemplateByName(name string, seed uint64) (*ChunkTemplate, *Palette, [][]MapCell, error) {
     630            1 :         chunks, err := l.GetChunks(name)
     631            1 :         if err != nil {
     632            1 :                 return nil, nil, nil, err
     633            1 :         }
     634              : 
     635              :         // 重み付きランダム選択
     636            1 :         rng := rand.New(rand.NewPCG(seed, seed))
     637            1 :         template, err := l.selectChunkByWeightFromList(chunks, rng)
     638            1 :         if err != nil {
     639            0 :                 return nil, nil, nil, err
     640            0 :         }
     641              : 
     642            1 :         templateCopy := *template
     643            1 : 
     644            1 :         palettes := make([]*Palette, 0, len(templateCopy.Palettes))
     645            1 :         for _, paletteName := range templateCopy.Palettes {
     646            1 :                 palette, ok := l.paletteCache[paletteName]
     647            1 :                 if !ok {
     648            1 :                         return nil, nil, nil, fmt.Errorf("%w: '%s'; register it in advance with RegisterAllPalettes", errPaletteNotFound, paletteName)
     649            1 :                 }
     650            1 :                 palettes = append(palettes, palette)
     651              :         }
     652              : 
     653            1 :         mergedPalette := MergePalettes(palettes...)
     654            1 : 
     655              :         // セル配列に展開する
     656            1 :         resolvedMap, err := templateCopy.ExpandWithPlacements(l, seed)
     657            1 :         if err != nil {
     658            0 :                 return nil, nil, nil, fmt.Errorf("failed to expand chunk: %w", err)
     659            0 :         }
     660              : 
     661            1 :         return &templateCopy, mergedPalette, resolvedMap, nil
     662              : }
     663              : 
     664              : // selectChunkByWeight は重みづけランダム選択でチャンクを選択する
     665              : // 各チャンク名に複数のバリエーションがある場合、すべてを候補に含める
     666              : func (l *TemplateLoader) selectChunkByWeight(chunkNames []string, rng *rand.Rand) (*ChunkTemplate, error) {
     667            1 :         if len(chunkNames) == 0 {
     668            1 :                 return nil, errNoChunkCandidate
     669            1 :         }
     670              : 
     671            1 :         candidates := make([]*ChunkTemplate, 0)
     672            1 : 
     673              :         // 各チャンク名のすべてのバリエーションを候補に追加
     674            1 :         for _, name := range chunkNames {
     675            1 :                 chunks, err := l.GetChunks(name)
     676            1 :                 if err != nil {
     677            1 :                         return nil, err
     678            1 :                 }
     679            1 :                 candidates = append(candidates, chunks...)
     680              :         }
     681              : 
     682            1 :         return l.selectChunkByWeightFromList(candidates, rng)
     683              : }
     684              : 
     685              : // buildMergedPalette はパレット名のリストからマージ済みパレットを構築する
     686              : func (l *TemplateLoader) buildMergedPalette(paletteNames []string) *Palette {
     687            1 :         if len(paletteNames) == 0 {
     688            1 :                 return nil
     689            1 :         }
     690            1 :         palettes := make([]*Palette, 0, len(paletteNames))
     691            1 :         for _, name := range paletteNames {
     692            1 :                 if p, ok := l.paletteCache[name]; ok {
     693            1 :                         palettes = append(palettes, p)
     694            1 :                 }
     695              :         }
     696            1 :         if len(palettes) == 0 {
     697            1 :                 return nil
     698            1 :         }
     699            1 :         return MergePalettes(palettes...)
     700              : }
     701              : 
     702              : // selectChunkByWeightFromList はChunkTemplateのリストから重み付きランダム選択する
     703              : func (l *TemplateLoader) selectChunkByWeightFromList(candidates []*ChunkTemplate, rng *rand.Rand) (*ChunkTemplate, error) {
     704            2 :         i, ok := consts.Pick(rng, candidates, func(c *ChunkTemplate) float64 { return float64(c.Weight) })
     705            1 :         if !ok {
     706            1 :                 return nil, errNoChunkCandidate
     707            1 :         }
     708            1 :         return candidates[i], nil
     709              : }
     710              : 
     711              : // ExpandWithPlacements はplacements方式でチャンクを展開し、解決済みセル配列を返す。
     712              : // 各子チャンクは自身のパレットで独立に解決してからオーバーレイする。
     713              : func (t *ChunkTemplate) ExpandWithPlacements(loader *TemplateLoader, seed uint64) ([][]MapCell, error) {
     714            1 :         visiting := make(map[string]bool)
     715            1 :         return t.expandWithPlacementsRecursive(loader, seed, 0, visiting)
     716            1 : }
     717              : 
     718              : // expandWithPlacementsRecursive はチャンクを再帰的に展開し、セル配列を返す。
     719              : // 各チャンクは自身のパレットで独立に解決する
     720              : func (t *ChunkTemplate) expandWithPlacementsRecursive(loader *TemplateLoader, seed uint64, depth int, visiting map[string]bool) ([][]MapCell, error) {
     721            1 :         const maxDepth = 10
     722            1 : 
     723            1 :         if depth > maxDepth {
     724            1 :                 return nil, fmt.Errorf("%w: %d", errExpansionDepthExceeded, maxDepth)
     725            1 :         }
     726              : 
     727            1 :         if visiting[t.Name] {
     728            1 :                 return nil, fmt.Errorf("%w: %s", errCircularChunkReference, t.Name)
     729            1 :         }
     730              : 
     731              :         // このチャンクのパレットで文字をセルに解決する
     732            1 :         palette := loader.buildMergedPalette(t.Palettes)
     733            1 :         cells := ResolveMapCells(t.Map, palette, rand.New(rand.NewPCG(seed, mixSeed(seed, 0))))
     734            1 : 
     735            1 :         visiting[t.Name] = true
     736            1 :         defer delete(visiting, t.Name)
     737            1 : 
     738            1 :         if err := t.expandNested(loader, palette, cells, seed, depth, visiting); err != nil {
     739            1 :                 return nil, err
     740            1 :         }
     741            1 :         if len(t.Placements) == 0 {
     742            1 :                 return cells, nil
     743            1 :         }
     744              : 
     745            1 :         lines := t.GetMapLines()
     746            1 :         rng := rand.New(rand.NewPCG(seed, seed))
     747            1 : 
     748              :         // 最初に全ての識別子の位置を検出(元のマップから)
     749            1 :         placementRegions := make([][]placeholderRegion, len(t.Placements))
     750            1 : 
     751            1 :         for idx, placement := range t.Placements {
     752            1 :                 if placement.ID == "" {
     753            1 :                         return nil, fmt.Errorf("placement %d: %w", idx, errPlacementIDMissing)
     754            1 :                 }
     755              : 
     756            1 :                 regions, err := findAllPlaceholderRegionsByID(lines, placement.ID)
     757            1 :                 if err != nil {
     758            0 :                         return nil, fmt.Errorf("placement %d (ID='%s'): %w", idx, placement.ID, err)
     759            0 :                 }
     760              : 
     761            1 :                 placementRegions[idx] = regions
     762              :         }
     763              : 
     764              :         // 各placements定義を処理。同じIDが複数箇所にある場合はそれぞれ独立に展開する
     765            1 :         for idx, placement := range t.Placements {
     766            1 :                 for regionIdx, region := range placementRegions[idx] {
     767              :                         // チャンクを重み付き選択(領域ごとに独立して選択する)
     768            1 :                         selectedChunk, err := loader.selectChunkByWeight(placement.Chunks, rng)
     769            1 :                         if err != nil {
     770            1 :                                 return nil, fmt.Errorf("failed to select chunk (placement %d, region %d): %w", idx, regionIdx, err)
     771            1 :                         }
     772              : 
     773              :                         // 再帰的に展開(子は自身のパレットで解決する)
     774            1 :                         regionSeed := mixSeed(seed, uint64(idx)*1000+uint64(regionIdx)+1)
     775            1 :                         childCells, err := selectedChunk.expandWithPlacementsRecursive(loader, regionSeed, depth+1, visiting)
     776            1 :                         if err != nil {
     777            1 :                                 return nil, err
     778            1 :                         }
     779              : 
     780              :                         // サイズチェック
     781            1 :                         if len(childCells) != selectedChunk.Size.H {
     782            0 :                                 return nil, fmt.Errorf("chunk '%s' height mismatch: expected %d, got %d", selectedChunk.Name, selectedChunk.Size.H, len(childCells))
     783            0 :                         }
     784            1 :                         if len(childCells) > 0 && len(childCells[0]) != selectedChunk.Size.W {
     785            0 :                                 return nil, fmt.Errorf("chunk '%s' width mismatch: expected %d, got %d", selectedChunk.Name, selectedChunk.Size.W, len(childCells[0]))
     786            0 :                         }
     787              : 
     788              :                         // サイズの完全一致を検証
     789            1 :                         if region.width != selectedChunk.Size.W || region.height != selectedChunk.Size.H {
     790            1 :                                 return nil, fmt.Errorf(
     791            1 :                                         "parent chunk '%s': placement %d (ID='%s', child chunk='%s'): %w: region [%d,%d] at position [%d,%d], chunk size %s",
     792            1 :                                         t.Name, idx, placement.ID, selectedChunk.Name, errRegionSizeMismatch, region.width, region.height, region.x, region.y, selectedChunk.Size,
     793            1 :                                 )
     794            1 :                         }
     795              : 
     796              :                         // 子のセルを親のセルにオーバーレイする
     797            1 :                         for cy := range selectedChunk.Size.H {
     798            1 :                                 for cx := range selectedChunk.Size.W {
     799            1 :                                         targetX := region.x + cx
     800            1 :                                         targetY := region.y + cy
     801            1 :                                         if targetY < len(cells) && targetX < len(cells[targetY]) {
     802            1 :                                                 cells[targetY][targetX] = childCells[cy][cx]
     803            1 :                                         }
     804              :                                 }
     805              :                         }
     806              :                 }
     807              :         }
     808              : 
     809              :         // 展開後にTerrainが空のセル(未解決プレースホルダ)がないか検証
     810            1 :         if err := validateNoPlaceholdersRemaining(cells); err != nil {
     811            1 :                 return nil, err
     812            1 :         }
     813              : 
     814            1 :         return cells, nil
     815              : }
     816              : 
     817              : // expandNested はパレットの部品の文字の位置に、候補から選んだ部品を左上を合わせて重ねる
     818              : func (t *ChunkTemplate) expandNested(loader *TemplateLoader, palette *Palette, cells [][]MapCell, seed uint64, depth int, visiting map[string]bool) error {
     819            1 :         if palette == nil || len(palette.Nested) == 0 {
     820            1 :                 return nil
     821            1 :         }
     822            1 :         rng := rand.New(rand.NewPCG(seed, mixSeed(seed, 1)))
     823            1 :         for y, line := range t.GetMapLines() {
     824            1 :                 for x, ch := range []rune(line) {
     825            1 :                         entry, ok := palette.Nested[string(ch)]
     826            1 :                         if !ok {
     827            1 :                                 continue
     828              :                         }
     829            2 :                         i, ok := consts.Pick(rng, entry.Chunks, func(c WeightedChunkRef) float64 { return float64(c.Weight) })
     830            1 :                         if !ok {
     831            0 :                                 return fmt.Errorf("chunk '%s' nested %q: %w", t.Name, ch, errNoChunkCandidate)
     832            0 :                         }
     833            1 :                         if entry.Chunks[i].Name == nullChunk {
     834            1 :                                 continue
     835              :                         }
     836            1 :                         child, err := loader.selectChunkByWeight([]string{entry.Chunks[i].Name}, rng)
     837            1 :                         if err != nil {
     838            0 :                                 return fmt.Errorf("chunk '%s' nested %q: %w", t.Name, ch, err)
     839            0 :                         }
     840            1 :                         if y+child.Size.H > len(cells) || x+child.Size.W > len(cells[y]) {
     841            1 :                                 return fmt.Errorf("chunk '%s' nested %q at [%d,%d] child '%s' %s: %w", t.Name, ch, x, y, child.Name, child.Size, errRegionIncomplete)
     842            1 :                         }
     843            1 :                         childCells, err := child.expandWithPlacementsRecursive(loader, mixSeed(seed, uint64(y*len(line)+x)+2), depth+1, visiting)
     844            1 :                         if err != nil {
     845            0 :                                 return err
     846            0 :                         }
     847            1 :                         for cy, row := range childCells {
     848            1 :                                 copy(cells[y+cy][x:], row)
     849            1 :                         }
     850              :                 }
     851              :         }
     852            1 :         return nil
     853              : }
     854              : 
     855              : // validateNoPlaceholdersRemaining は展開後のセル配列にプレースホルダが残っていないか検証する
     856              : func validateNoPlaceholdersRemaining(cells [][]MapCell) error {
     857            1 :         for y, row := range cells {
     858            1 :                 for x, cell := range row {
     859            1 :                         if cell.Terrain == placeholderStr {
     860            1 :                                 return fmt.Errorf("%w at x=%d, y=%d", errPlaceholderRemains, x, y)
     861            1 :                         }
     862              :                 }
     863              :         }
     864            1 :         return nil
     865              : }
     866              : 
     867              : // placeholderRegion はプレースホルダ領域の位置とサイズ
     868              : type placeholderRegion struct {
     869              :         x, y, width, height int
     870              : }
     871              : 
     872              : // findAllPlaceholderRegionsByID は識別子に一致する全てのプレースホルダ領域を検出する。
     873              : // 同じIDが複数箇所にある場合、それぞれ独立した領域として返す
     874              : func findAllPlaceholderRegionsByID(lines []string, id string) ([]placeholderRegion, error) {
     875            1 :         if len(id) != 1 {
     876            1 :                 return nil, fmt.Errorf("%w: %q", errIdentifierNotSingleChar, id)
     877            1 :         }
     878              : 
     879            1 :         idChar := rune(id[0])
     880            1 : 
     881            1 :         positions := findAllIdentifierPositions(lines, idChar)
     882            1 :         if len(positions) == 0 {
     883            1 :                 return nil, fmt.Errorf("%w: '%s'", errIdentifierNotFound, id)
     884            1 :         }
     885              : 
     886            1 :         var regions []placeholderRegion
     887            1 :         for _, pos := range positions {
     888            1 :                 idX, idY := pos[0], pos[1]
     889            1 : 
     890            1 :                 startX := findLeftEdge(lines, idY, idX, placeholderChar, idChar)
     891            1 :                 tempWidth := calculateRowWidth(lines[idY], startX, placeholderChar, idChar)
     892            1 :                 startY := findTopEdge(lines, idY, startX, tempWidth, placeholderChar, idChar)
     893            1 :                 width := calculateRowWidth(lines[startY], startX, placeholderChar, idChar)
     894            1 :                 height := calculateHeight(lines, startY, startX, placeholderChar, idChar)
     895            1 : 
     896            1 :                 if err := validateRectangle(lines, id, startX, startY, width, height, placeholderChar, idChar); err != nil {
     897            1 :                         return nil, err
     898            1 :                 }
     899              : 
     900            1 :                 regions = append(regions, placeholderRegion{x: startX, y: startY, width: width, height: height})
     901              :         }
     902              : 
     903            1 :         return regions, nil
     904              : }
     905              : 
     906              : // findAllIdentifierPositions は識別子の全出現位置を返す
     907              : func findAllIdentifierPositions(lines []string, idChar rune) [][2]int {
     908            1 :         var positions [][2]int
     909            1 :         for y, line := range lines {
     910            1 :                 for x, ch := range line {
     911            1 :                         if ch == idChar {
     912            1 :                                 positions = append(positions, [2]int{x, y})
     913            1 :                         }
     914              :                 }
     915              :         }
     916            1 :         return positions
     917              : }
     918              : 
     919              : // findLeftEdge は左端を探す
     920              : func findLeftEdge(lines []string, idY, idX int, placeholder, idChar rune) int {
     921            1 :         startX := idX
     922            1 :         for startX > 0 {
     923            1 :                 ch := rune(lines[idY][startX-1])
     924            1 :                 if ch == placeholder || ch == idChar {
     925            1 :                         startX--
     926            1 :                 } else {
     927            1 :                         break
     928              :                 }
     929              :         }
     930            1 :         return startX
     931              : }
     932              : 
     933              : // calculateRowWidth は行の幅を計算
     934              : func calculateRowWidth(line string, startX int, placeholder, idChar rune) int {
     935            1 :         width := 0
     936            1 :         for x := startX; x < len(line); x++ {
     937            1 :                 ch := rune(line[x])
     938            1 :                 if ch == placeholder || ch == idChar {
     939            1 :                         width++
     940            1 :                 } else {
     941            1 :                         break
     942              :                 }
     943              :         }
     944            1 :         return width
     945              : }
     946              : 
     947              : // findTopEdge は上端を探す
     948              : func findTopEdge(lines []string, idY, startX, tempWidth int, placeholder, idChar rune) int {
     949            1 :         startY := idY
     950            1 :         for startY > 0 {
     951            1 :                 if startX+tempWidth > len(lines[startY-1]) {
     952            0 :                         break
     953              :                 }
     954            1 :                 allMatch := true
     955            1 :                 for x := startX; x < startX+tempWidth; x++ {
     956            1 :                         ch := rune(lines[startY-1][x])
     957            1 :                         if ch != placeholder && ch != idChar {
     958            1 :                                 allMatch = false
     959            1 :                                 break
     960              :                         }
     961              :                 }
     962            1 :                 if allMatch {
     963            1 :                         startY--
     964            1 :                 } else {
     965            1 :                         break
     966              :                 }
     967              :         }
     968            1 :         return startY
     969              : }
     970              : 
     971              : // calculateHeight は高さを計算
     972              : func calculateHeight(lines []string, startY, startX int, placeholder, idChar rune) int {
     973            1 :         height := 0
     974            1 :         for y := startY; y < len(lines) && startX < len(lines[y]); y++ {
     975            1 :                 ch := rune(lines[y][startX])
     976            1 :                 if ch == placeholder || ch == idChar {
     977            1 :                         height++
     978            1 :                 } else {
     979            1 :                         break
     980              :                 }
     981              :         }
     982            1 :         return height
     983              : }
     984              : 
     985              : // validateRectangle は矩形領域全体が@または識別子で埋まっているか検証
     986              : func validateRectangle(lines []string, id string, startX, startY, width, height int, placeholder, idChar rune) error {
     987            1 :         for dy := range height {
     988            1 :                 y := startY + dy
     989            1 :                 if y >= len(lines) {
     990            1 :                         return fmt.Errorf("identifier '%s': %w; y=%d out of range", id, errRegionIncomplete, y)
     991            1 :                 }
     992            1 :                 for dx := range width {
     993            1 :                         x := startX + dx
     994            1 :                         if x >= len(lines[y]) {
     995            1 :                                 return fmt.Errorf("identifier '%s': %w; x=%d, y=%d out of range", id, errRegionIncomplete, x, y)
     996            1 :                         }
     997            1 :                         ch := rune(lines[y][x])
     998            1 :                         if ch != placeholder && ch != idChar {
     999            1 :                                 return fmt.Errorf(
    1000            1 :                                         "identifier '%s': %w '%c' in placeholder region [%d,%d]; expected '@' or '%s'",
    1001            1 :                                         id, errInvalidPlaceholderChar, ch, x, y, id,
    1002            1 :                                 )
    1003            1 :                         }
    1004              :                 }
    1005              :         }
    1006            1 :         return nil
    1007              : }
    1008              : 
    1009              : // validatePlaceholders はプレースホルダ(@)とplacementsの整合性を検証する
    1010              : func (t *ChunkTemplate) validatePlaceholders(loader *TemplateLoader) error {
    1011            1 :         lines := t.GetMapLines()
    1012            1 : 
    1013              :         // 各placements定義をチェック
    1014            1 :         for idx, placement := range t.Placements {
    1015              :                 // チャンクの最初のバリエーションからサイズを取得(すべて同じサイズのはず)
    1016            1 :                 chunks, err := loader.GetChunks(placement.Chunks[0])
    1017            1 :                 if err != nil {
    1018            0 :                         return fmt.Errorf("placement %d: %w", idx, err)
    1019            0 :                 }
    1020            1 :                 if len(chunks) == 0 {
    1021            0 :                         return fmt.Errorf("placement %d: %w: '%s'", idx, errChunkNotFound, placement.Chunks[0])
    1022            0 :                 }
    1023              : 
    1024            1 :                 expectedWidth := chunks[0].Size.W
    1025            1 :                 expectedHeight := chunks[0].Size.H
    1026            1 : 
    1027              :                 // 識別子から位置を検出して検証
    1028            1 :                 if placement.ID == "" {
    1029            0 :                         return fmt.Errorf("placement %d (%s): %w", idx, placement.Chunks[0], errPlacementIDMissing)
    1030            0 :                 }
    1031              : 
    1032            1 :                 regions, err := findAllPlaceholderRegionsByID(lines, placement.ID)
    1033            1 :                 if err != nil {
    1034            1 :                         return fmt.Errorf("placement %d (%s): %w", idx, placement.Chunks[0], err)
    1035            1 :                 }
    1036              : 
    1037              :                 // 全領域のサイズの完全一致を検証
    1038            1 :                 for regionIdx, region := range regions {
    1039            1 :                         if region.width != expectedWidth || region.height != expectedHeight {
    1040            1 :                                 return fmt.Errorf(
    1041            1 :                                         "parent chunk '%s': placement %d (ID='%s', region %d, child chunk='%s'): %w: region [%d,%d] at position [%d,%d], chunk size %s",
    1042            1 :                                         t.Name, idx, placement.ID, regionIdx, placement.Chunks[0], errRegionSizeMismatch, region.width, region.height, region.x, region.y, chunks[0].Size,
    1043            1 :                                 )
    1044            1 :                         }
    1045              :                 }
    1046              :         }
    1047              : 
    1048            1 :         return nil
    1049              : }
    1050              : 
    1051              : // mixSeed は親の seed と番号から子の seed を作る。加算だと隣り合う番号の子が似た乱数列を引くので撹拌する
    1052              : func mixSeed(seed, n uint64) uint64 {
    1053            1 :         z := seed + n*0x9e3779b97f4a7c15
    1054            1 :         z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
    1055            1 :         z = (z ^ (z >> 27)) * 0x94d049bb133111eb
    1056            1 :         return z ^ (z >> 31)
    1057            1 : }
        

Generated by: LCOV version 2.0-1