LCOV - code coverage report
Current view: top level - overworld - building.go Coverage Total Hit
Test: coverage.lcov Lines: 96.9 % 194 188
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package overworld
       2              : 
       3              : import (
       4              :         "errors"
       5              :         "fmt"
       6              :         "math/rand/v2"
       7              :         "slices"
       8              : 
       9              :         "github.com/kijimaD/ruins/internal/consts"
      10              :         "github.com/kijimaD/ruins/internal/maptemplate"
      11              :         "github.com/kijimaD/ruins/internal/raw"
      12              :         "github.com/kijimaD/ruins/internal/rawschema"
      13              :         "github.com/kijimaD/ruins/internal/world/query"
      14              : )
      15              : 
      16              : // errRoomSizeMismatch は部屋の絵の大きさがチャンクから帯を引いた大きさと一致しないときに返す
      17              : var errRoomSizeMismatch = errors.New("room template size does not match the chunk")
      18              : 
      19              : // buildingLot は区域の中の建物の区画。区域の中の座標 anchor から w×h チャンク広がり、施設を1つ建てる
      20              : type buildingLot struct {
      21              :         facility string
      22              :         anchor   consts.Coord[consts.Chunk]
      23              :         w, h     consts.Chunk
      24              :         interior rawschema.FacilityInterior
      25              :         seed     uint64
      26              : }
      27              : 
      28              : // lotsOf は区域 r を建物の区画で埋める。左上のチャンクから順に、未割り当てのチャンクの地区で施設を引き、
      29              : // 施設の大きさの候補を重みで引く。区画は同じ地区で未割り当てのチャンクだけに収まるまで小さくする。
      30              : // 施設の深さの足切りには、深さの起点の行 spawnRow から測った区域の北の端の危険度を使う。区域の中で足切りを揃えるため、チャンクごとには測らない
      31              : func lotsOf(raws rawschema.Raws, cat zoneCatalog, r districtRegion, spawnRow consts.Chunk) []buildingLot {
      32            1 :         danger := query.DangerLevelForDepth(consts.NorthDepth(spawnRow, r.anchor.Y))
      33            1 :         facilities := map[string]rawschema.Facility{}
      34            1 :         for _, f := range raw.PtrSlice(raws.Facilities) {
      35            1 :                 facilities[f.Id] = f
      36            1 :         }
      37            1 :         taken := map[consts.Coord[consts.Chunk]]bool{}
      38            1 :         free := func(x, y consts.Chunk, z rawschema.Zone) bool {
      39            1 :                 c := consts.Coord[consts.Chunk]{X: x, Y: y}
      40            1 :                 return x < r.w && y < r.h && !taken[c] && r.zoneAt(c) == z
      41            1 :         }
      42            1 :         fits := func(x, y, w, h consts.Chunk, z rawschema.Zone) bool {
      43            1 :                 for dy := range h {
      44            1 :                         for dx := range w {
      45            1 :                                 if !free(x+dx, y+dy, z) {
      46            1 :                                         return false
      47            1 :                                 }
      48              :                         }
      49              :                 }
      50            1 :                 return true
      51              :         }
      52              : 
      53            1 :         var lots []buildingLot
      54            1 :         place := func(f rawschema.Facility, anchor consts.Coord[consts.Chunk], w, h consts.Chunk) {
      55            1 :                 interior := rawschema.FacilityInteriorRooms
      56            1 :                 if f.Interior != nil {
      57            1 :                         interior = *f.Interior
      58            1 :                 }
      59            1 :                 for dy := range h {
      60            1 :                         for dx := range w {
      61            1 :                                 taken[anchor.Add(consts.Coord[consts.Chunk]{X: dx, Y: dy})] = true
      62            1 :                         }
      63              :                 }
      64            1 :                 lots = append(lots, buildingLot{facility: f.Id, anchor: anchor, w: w, h: h, interior: interior, seed: ChunkSeed2D(r.seed, anchor.X, anchor.Y)})
      65              :         }
      66            1 :         if f, ok := facilities[r.landmark()]; ok {
      67            1 :                 if anchor, w, h, ok := landmarkLot(r, f, fits); ok {
      68            1 :                         place(f, anchor, w, h)
      69            1 :                 }
      70              :         }
      71            1 :         for y := range r.h {
      72            1 :                 for x := range r.w {
      73            1 :                         l := consts.Coord[consts.Chunk]{X: x, Y: y}
      74            1 :                         if taken[l] {
      75            1 :                                 continue
      76              :                         }
      77            1 :                         z := r.zoneAt(l)
      78            1 :                         // 施設抽選は建物幾何と別の乱数ストリームにして、片方を変えても他方が動かないようにする。
      79              :                         // ストリーム識別子 0x1 は施設抽選、0x2 は建物幾何と敵配置。renderUrbanChunk と揃える
      80            1 :                         frng := rand.New(rand.NewPCG(ChunkSeed2D(r.seed, x, y), 0x1))
      81            1 :                         f := facilities[rollFacilityInZone(frng, cat, z, r.span(), danger, r.landmark())]
      82            1 :                         fps := facilityFootprints(f)
      83            2 :                         i, _ := consts.Pick(frng, fps, func(fp rawschema.FacilityFootprint) float64 { return float64(fp.Weight) })
      84            1 :                         w, h := consts.Chunk(fps[i].W), consts.Chunk(fps[i].H)
      85            1 :                         for !fits(x, y, w, h, z) {
      86            1 :                                 if w >= h && w > 1 {
      87            1 :                                         w--
      88            1 :                                 } else {
      89            1 :                                         h--
      90            1 :                                 }
      91              :                         }
      92            1 :                         place(f, l, w, h)
      93              :                 }
      94              :         }
      95            1 :         return lots
      96              : }
      97              : 
      98              : // landmarkLot は区域の目玉の施設 f を、施設が建つ地区の真ん中へ置く区画を返す。大きさは候補のうち一番大きい面積から順に、候補が無ければ 1×1 で、
      99              : // 地区に収まるものを選ぶ。区域の作りがその地区を割り振らなければ置かない
     100              : func landmarkLot(r districtRegion, f rawschema.Facility, fits func(x, y, w, h consts.Chunk, z rawschema.Zone) bool) (consts.Coord[consts.Chunk], consts.Chunk, consts.Chunk, bool) {
     101            1 :         for _, fz := range f.Zones {
     102            1 :                 var cells []consts.Coord[consts.Chunk]
     103            1 :                 for y := range r.h {
     104            1 :                         for x := range r.w {
     105            1 :                                 if c := (consts.Coord[consts.Chunk]{X: x, Y: y}); r.zoneAt(c) == fz.Zone {
     106            1 :                                         cells = append(cells, c)
     107            1 :                                 }
     108              :                         }
     109              :                 }
     110            1 :                 if len(cells) == 0 {
     111            1 :                         continue
     112              :                 }
     113            1 :                 minC, maxC := cells[0], cells[0]
     114            1 :                 for _, c := range cells {
     115            1 :                         minC = consts.Coord[consts.Chunk]{X: min(minC.X, c.X), Y: min(minC.Y, c.Y)}
     116            1 :                         maxC = consts.Coord[consts.Chunk]{X: max(maxC.X, c.X), Y: max(maxC.Y, c.Y)}
     117            1 :                 }
     118            1 :                 fps := slices.Clone(facilityFootprints(f))
     119            2 :                 slices.SortStableFunc(fps, func(a, b rawschema.FacilityFootprint) int { return b.W*b.H - a.W*a.H })
     120            1 :                 for _, fp := range fps {
     121            1 :                         w, h := consts.Chunk(fp.W), consts.Chunk(fp.H)
     122            1 :                         x := minC.X + (maxC.X-minC.X+1-w)/2
     123            1 :                         y := minC.Y + (maxC.Y-minC.Y+1-h)/2
     124            1 :                         if x >= 0 && y >= 0 && fits(x, y, w, h, fz.Zone) {
     125            1 :                                 return consts.Coord[consts.Chunk]{X: x, Y: y}, w, h, true
     126            1 :                         }
     127              :                 }
     128              :         }
     129            1 :         return consts.Coord[consts.Chunk]{}, 0, 0, false
     130              : }
     131              : 
     132              : // lotAt は区域の中の座標 l を含む区画を返す。lotsOf が区域を隙間なく埋めるので必ず見つかる
     133              : func lotAt(lots []buildingLot, l consts.Coord[consts.Chunk]) buildingLot {
     134            1 :         for _, b := range lots {
     135            1 :                 if l.X >= b.anchor.X && l.X < b.anchor.X+b.w && l.Y >= b.anchor.Y && l.Y < b.anchor.Y+b.h {
     136            1 :                         return b
     137            1 :                 }
     138              :         }
     139            0 :         panic(fmt.Sprintf("no lot covers %v", l))
     140              : }
     141              : 
     142              : // roomEdges は区画の中の座標 l のチャンクの、北・東・南・西の辺の種類を返す。区画の外へ向く辺は壁で、
     143              : // 北の辺の真ん中の列にだけ入口の扉を開ける。区画の内側の辺は、hall なら吹き抜け、rooms なら迷路の扉か壁
     144              : func (b buildingLot) roomEdges(l consts.Coord[consts.Chunk]) [4]maptemplate.EdgeKind {
     145            1 :         var doors map[[2]consts.Coord[consts.Chunk]]bool
     146            1 :         if b.interior == rawschema.FacilityInteriorRooms {
     147            1 :                 doors = b.mazeDoors()
     148            1 :         }
     149            1 :         edge := func(d consts.Coord[consts.Chunk]) maptemplate.EdgeKind {
     150            1 :                 n := l.Add(d)
     151            1 :                 if n.X < 0 || n.Y < 0 || n.X >= b.w || n.Y >= b.h {
     152            1 :                         return maptemplate.EdgeWall
     153            1 :                 }
     154            1 :                 if b.interior == rawschema.FacilityInteriorHall {
     155            1 :                         return maptemplate.EdgeOpen
     156            1 :                 }
     157            1 :                 if doors[edgeKey(l, n)] {
     158            1 :                         return maptemplate.EdgeDoor
     159            1 :                 }
     160            1 :                 return maptemplate.EdgeWall
     161              :         }
     162            1 :         edges := [4]maptemplate.EdgeKind{
     163            1 :                 edge(consts.Coord[consts.Chunk]{Y: -1}),
     164            1 :                 edge(consts.Coord[consts.Chunk]{X: 1}),
     165            1 :                 edge(consts.Coord[consts.Chunk]{Y: 1}),
     166            1 :                 edge(consts.Coord[consts.Chunk]{X: -1}),
     167            1 :         }
     168            1 :         if l.Y == 0 && l.X == b.w/2 {
     169            1 :                 edges[0] = maptemplate.EdgeDoor
     170            1 :         }
     171            1 :         return edges
     172              : }
     173              : 
     174              : // mazeDoors は区画の中のチャンクを節にした全域木の辺を返す。入口のチャンクから、区画の seed で順を混ぜた
     175              : // 深さ優先でたどる。どの部屋にも入口から扉を通って入れる
     176              : func (b buildingLot) mazeDoors() map[[2]consts.Coord[consts.Chunk]]bool {
     177            1 :         rng := rand.New(rand.NewPCG(b.seed, 0x6))
     178            1 :         doors := map[[2]consts.Coord[consts.Chunk]]bool{}
     179            1 :         seen := map[consts.Coord[consts.Chunk]]bool{}
     180            1 :         var visit func(c consts.Coord[consts.Chunk])
     181            1 :         visit = func(c consts.Coord[consts.Chunk]) {
     182            1 :                 seen[c] = true
     183            1 :                 dirs := []consts.Coord[consts.Chunk]{{Y: -1}, {X: 1}, {Y: 1}, {X: -1}}
     184            2 :                 rng.Shuffle(len(dirs), func(i, j int) { dirs[i], dirs[j] = dirs[j], dirs[i] })
     185            1 :                 for _, d := range dirs {
     186            1 :                         n := c.Add(d)
     187            1 :                         if n.X < 0 || n.Y < 0 || n.X >= b.w || n.Y >= b.h || seen[n] {
     188            1 :                                 continue
     189              :                         }
     190            1 :                         doors[edgeKey(c, n)] = true
     191            1 :                         visit(n)
     192              :                 }
     193              :         }
     194            1 :         visit(consts.Coord[consts.Chunk]{X: b.w / 2})
     195            1 :         return doors
     196              : }
     197              : 
     198              : // edgeKey は隣り合う2チャンクの辺を、向きに依らない鍵にする
     199              : func edgeKey(a, b consts.Coord[consts.Chunk]) [2]consts.Coord[consts.Chunk] {
     200            1 :         if a.Y < b.Y || a.Y == b.Y && a.X < b.X {
     201            1 :                 return [2]consts.Coord[consts.Chunk]{a, b}
     202            1 :         }
     203            1 :         return [2]consts.Coord[consts.Chunk]{b, a}
     204              : }
     205              : 
     206              : // roomChunkCells は区画 b の中の座標 l のチャンクの部屋の絵を引き、北と西の帯と合わせてチャンク全体のマスを組む。
     207              : // 帯は区画の外周なら街路、内側なら隣の部屋との繋ぎにする。isTall は高さのある地形かを返す
     208              : func roomChunkCells(loader *maptemplate.TemplateLoader, b buildingLot, l consts.Coord[consts.Chunk], chunkW, chunkH consts.Tile, streets streetTiles, isTall func(terrain string) bool) ([][]maptemplate.MapCell, error) {
     209            1 :         edges := b.roomEdges(l)
     210            1 :         _, room, err := loader.FacilityRoom(b.facility, edges, ChunkSeed2D(b.seed, l.X, l.Y))
     211            1 :         if err != nil {
     212            0 :                 return nil, err
     213            0 :         }
     214            1 :         s := int(urbanStreetW)
     215            1 :         w, h := int(chunkW), int(chunkH)
     216            1 :         if len(room) != h-s || len(room[0]) != w-s {
     217            0 :                 return nil, fmt.Errorf("facility %q room %dx%d, chunk %dx%d: %w", b.facility, len(room[0]), len(room), w, h, errRoomSizeMismatch)
     218            0 :         }
     219              : 
     220            1 :         cells := make([][]maptemplate.MapCell, h)
     221            1 :         for y := range cells {
     222            1 :                 cells[y] = make([]maptemplate.MapCell, w)
     223            1 :                 for x := range cells[y] {
     224            1 :                         cells[y][x] = maptemplate.MapCell{Terrain: streetTerrain(consts.Tile(x), consts.Tile(y), streets)}
     225            1 :                 }
     226              :         }
     227            1 :         for y, row := range room {
     228            1 :                 copy(cells[y+s][s:], row)
     229            1 :         }
     230            1 :         drawRoomStrips(cells, room, b, l, edges, roomWall(room, isTall))
     231            1 :         return cells, nil
     232              : }
     233              : 
     234              : // roomWall は部屋の絵の壁の地形を返す。部屋は1種類の壁で組むので、高さのある地形を見つけた最初のものを使う。
     235              : // 高さのある地形が無い部屋は wall を返す
     236              : func roomWall(room [][]maptemplate.MapCell, isTall func(terrain string) bool) string {
     237            1 :         for _, row := range room {
     238            1 :                 for _, c := range row {
     239            1 :                         if isTall(c.Terrain) {
     240            1 :                                 return c.Terrain
     241            1 :                         }
     242              :                 }
     243              :         }
     244            1 :         return consts.TileNameWall
     245              : }
     246              : 
     247              : // drawRoomStrips は区画の内側に面するチャンクの北と西の帯を、隣の部屋との繋ぎとして描く。区画の外周の帯は街路のまま残す。
     248              : // 帯の壁は部屋の壁の地形 wallTerrain で描く
     249              : func drawRoomStrips(cells, room [][]maptemplate.MapCell, b buildingLot, l consts.Coord[consts.Chunk], edges [4]maptemplate.EdgeKind, wallTerrain string) {
     250            1 :         s := int(urbanStreetW)
     251            1 :         h, w := len(cells), len(cells[0])
     252            1 :         wall := maptemplate.MapCell{Terrain: wallTerrain}
     253            2 :         floor := func(x, y int) maptemplate.MapCell { return maptemplate.MapCell{Terrain: room[y][x].Terrain} }
     254            1 :         mid := (w - s) / 2
     255            1 : 
     256              :         // 帯の端が区画の外に面していれば壁にして、吹き抜けの帯から建物の外へ抜けないようにする
     257            2 :         northEnd := func(x int) bool { return l.X == 0 && x == s || l.X == b.w-1 && x == w-1 }
     258            2 :         westEnd := func(y int) bool { return l.Y == 0 && y == s || l.Y == b.h-1 && y == h-1 }
     259            1 :         if l.Y > 0 {
     260            1 :                 for y := range s {
     261            1 :                         for x := s; x < w; x++ {
     262            1 :                                 cells[y][x] = wall
     263            1 :                                 if stripOpen(edges[0], x-s, mid, northEnd(x)) {
     264            1 :                                         cells[y][x] = floor(x-s, 0)
     265            1 :                                 }
     266              :                         }
     267              :                 }
     268              :         }
     269            1 :         if l.X > 0 {
     270            1 :                 for y := s; y < h; y++ {
     271            1 :                         for x := range s {
     272            1 :                                 cells[y][x] = wall
     273            1 :                                 if stripOpen(edges[3], y-s, mid, westEnd(y)) {
     274            1 :                                         cells[y][x] = floor(0, y-s)
     275            1 :                                 }
     276              :                         }
     277              :                 }
     278              :         }
     279            1 :         if l.X > 0 && l.Y > 0 {
     280            1 :                 corner := wall
     281            1 :                 if b.interior == rawschema.FacilityInteriorHall {
     282            1 :                         corner = floor(0, 0)
     283            1 :                 }
     284            1 :                 for y := range s {
     285            1 :                         for x := range s {
     286            1 :                                 cells[y][x] = corner
     287            1 :                         }
     288              :                 }
     289              :         }
     290              : }
     291              : 
     292              : // stripOpen は辺の種類 kind の帯で、辺に沿った位置 i のマスが床かを返す。扉は真ん中の2マス、吹き抜けは
     293              : // 区画の外に面する端 end を除く全て
     294              : func stripOpen(kind maptemplate.EdgeKind, i, mid int, end bool) bool {
     295            1 :         switch kind {
     296              :         case maptemplate.EdgeOpen:
     297            1 :                 return !end
     298              :         case maptemplate.EdgeDoor:
     299            1 :                 return i == mid-1 || i == mid
     300              :         case maptemplate.EdgeWall:
     301            1 :                 return false
     302              :         }
     303            0 :         return false
     304              : }
     305              : 
     306              : // facilityFootprints は施設 f の大きさの候補を返す。行が候補を省けば1チャンクの1つだけにする
     307              : func facilityFootprints(f rawschema.Facility) []rawschema.FacilityFootprint {
     308            1 :         if fps := raw.PtrSlice(f.Footprints); len(fps) > 0 {
     309            1 :                 return fps
     310            1 :         }
     311            1 :         return []rawschema.FacilityFootprint{{W: 1, H: 1, Weight: 1}}
     312              : }
        

Generated by: LCOV version 2.0-1