Line data Source code
1 : package overworld
2 :
3 : import (
4 : "errors"
5 : "fmt"
6 : "math/rand/v2"
7 : "slices"
8 :
9 : gc "github.com/kijimaD/ruins/internal/components"
10 : "github.com/kijimaD/ruins/internal/consts"
11 : "github.com/kijimaD/ruins/internal/mapplanner"
12 : "github.com/kijimaD/ruins/internal/maptemplate"
13 : "github.com/kijimaD/ruins/internal/raw"
14 : "github.com/kijimaD/ruins/internal/rawschema"
15 : w "github.com/kijimaD/ruins/internal/world"
16 : "github.com/kijimaD/ruins/internal/world/lifecycle"
17 : "github.com/kijimaD/ruins/internal/world/query"
18 : "github.com/mlange-42/ark/ecs"
19 : )
20 :
21 : var (
22 : // errFacilityOutOfChunk は施設の絵が置く原点からチャンクに収まらないときに返す
23 : errFacilityOutOfChunk = errors.New("facility template does not fit in the chunk")
24 : // errFacilityGroundNotEarth は下地を残すマスの下が土の地面でないときに返す
25 : errFacilityGroundNotEarth = errors.New("facility ground cell is not on an earth tile")
26 : )
27 :
28 : // planFacility は施設 fac の絵を1枚選んで展開する。絵は入口を北に向けて描いてあり、rng で半々に左へ90度回して入口を西の街路へ向ける。左右の反転も半々で選ぶ
29 : func planFacility(loader *maptemplate.TemplateLoader, fac string, seed uint64, rng *rand.Rand) ([][]maptemplate.MapCell, error) {
30 1 : _, cells, err := loader.FacilityChunk(fac, seed)
31 1 : if err != nil {
32 0 : return nil, err
33 0 : }
34 1 : turns := 0
35 1 : if rng.IntN(2) == 0 {
36 1 : turns = 1
37 1 : }
38 1 : return maptemplate.TransformCells(cells, turns, rng.IntN(2) == 0), nil
39 : }
40 :
41 : // spawnFacility は施設の絵のマスを、チャンク内の区画の左上 (ox, oy) から実体として置く。
42 : // 扉は左右か上下の壁から向きを決める。
43 : // 壁判定の関数と占有したマスを返し、後段の街路の敵が建物の上に湧かないようにする
44 : func spawnFacility(world w.World, g chunkGeom, cells [][]maptemplate.MapCell, ox, oy consts.Tile, fac string, danger consts.Danger, seed uint64) (func(lx, ly consts.Tile) bool, map[consts.Coord[consts.Tile]]bool, error) {
45 1 : if int(oy)+len(cells) > int(g.chunkH) || int(ox)+len(cells[0]) > int(g.chunkW) {
46 1 : return nil, nil, fmt.Errorf("facility %q %dx%d at %d,%d, chunk %dx%d: %w", fac, len(cells[0]), len(cells), ox, oy, g.chunkW, g.chunkH, errFacilityOutOfChunk)
47 1 : }
48 :
49 1 : tileRows := map[string]rawschema.Tile{}
50 1 : tileOf := func(id string) (rawschema.Tile, error) {
51 1 : if t, ok := tileRows[id]; ok {
52 1 : return t, nil
53 1 : }
54 1 : t, err := raw.GetTile(world.Resources.RawMaster, id)
55 1 : if err != nil {
56 0 : return rawschema.Tile{}, err
57 0 : }
58 1 : tileRows[id] = t
59 1 : return t, nil
60 : }
61 2 : inBounds := func(x, y int) bool { return y >= 0 && y < len(cells) && x >= 0 && x < len(cells[y]) }
62 1 : wallAt := func(x, y int) bool {
63 1 : if !inBounds(x, y) || cells[y][x].Terrain == maptemplate.GroundTerrain {
64 1 : return false
65 1 : }
66 1 : t, err := tileOf(cells[y][x].Terrain)
67 1 : return err == nil && t.BlockPass
68 : }
69 :
70 1 : propRows := map[string]rawschema.Prop{}
71 1 : propOf := func(id string) (rawschema.Prop, error) {
72 1 : if p, ok := propRows[id]; ok {
73 1 : return p, nil
74 1 : }
75 1 : p, err := raw.GetProp(world.Resources.RawMaster, id)
76 1 : if err != nil {
77 1 : return rawschema.Prop{}, err
78 1 : }
79 1 : propRows[id] = p
80 1 : return p, nil
81 : }
82 1 : propBlocksPass := func(id string) (bool, error) {
83 1 : if id == "" {
84 1 : return false, nil
85 1 : }
86 1 : prop, err := propOf(id)
87 1 : if err != nil {
88 0 : return false, err
89 0 : }
90 1 : return prop.BlockPass, nil
91 : }
92 :
93 : // 扉の隣には扉や窓が並ぶので、通行を塞ぐ置物も壁と同じく向きを決める側に数える
94 1 : blocks := func(x, y int) (bool, error) {
95 1 : if !inBounds(x, y) {
96 1 : return false, nil
97 1 : }
98 1 : if wallAt(x, y) {
99 1 : return true, nil
100 1 : }
101 1 : b, err := propBlocksPass(cells[y][x].Prop)
102 1 : if err != nil {
103 0 : return false, fmt.Errorf("facility %q prop at %d,%d: %w", fac, x, y, err)
104 0 : }
105 1 : return b, nil
106 : }
107 :
108 1 : poses, err := cellPoses(cells, wallAt, propOf)
109 1 : if err != nil {
110 1 : return nil, nil, fmt.Errorf("facility %q: %w", fac, err)
111 1 : }
112 :
113 1 : tiles := g.tiles.get()
114 1 : occupied := make(map[consts.Coord[consts.Tile]]bool)
115 1 : lootRNG := rand.New(rand.NewPCG(seed, 0x4))
116 1 : beingRNG := rand.New(rand.NewPCG(seed, 0x5))
117 1 : for y, row := range cells {
118 1 : for x, cell := range row {
119 1 : pos := consts.Coord[consts.Tile]{X: g.offsetX + ox + consts.Tile(x), Y: g.offsetY + oy + consts.Tile(y)}
120 1 : occupied[pos] = true
121 1 :
122 1 : if cell.Terrain == maptemplate.GroundTerrain {
123 1 : if err := checkFacilityGround(world, tiles, pos, tileOf); err != nil {
124 1 : return nil, nil, fmt.Errorf("facility %q at %d,%d: %w", fac, x, y, err)
125 1 : }
126 : } else {
127 1 : t, err := tileOf(cell.Terrain)
128 1 : if err != nil {
129 0 : return nil, nil, fmt.Errorf("facility %q tile at %d,%d: %w", fac, x, y, err)
130 0 : }
131 1 : if err := spawnFacilityTile(world, tiles, pos, t); err != nil {
132 0 : return nil, nil, err
133 0 : }
134 : }
135 1 : orientation := gc.DoorOrientationHorizontal
136 1 : left, err := blocks(x-1, y)
137 1 : if err != nil {
138 0 : return nil, nil, err
139 0 : }
140 1 : right, err := blocks(x+1, y)
141 1 : if err != nil {
142 0 : return nil, nil, err
143 0 : }
144 1 : if left && right {
145 1 : orientation = gc.DoorOrientationVertical
146 1 : }
147 1 : if err := spawnFacilityCell(world, cell, pos, orientation, poses[consts.Coord[consts.Tile]{X: consts.Tile(x), Y: consts.Tile(y)}], fac, danger, lootRNG, beingRNG); err != nil {
148 0 : return nil, nil, err
149 0 : }
150 : }
151 : }
152 :
153 2 : isWall := func(lx, ly consts.Tile) bool { return wallAt(int(lx-ox), int(ly-oy)) }
154 1 : return isWall, occupied, nil
155 : }
156 :
157 : // checkFacilityGround は下地を残すマス pos の下に、土の地面のタイルが置かれていることを確かめる
158 : func checkFacilityGround(world w.World, tiles map[gc.GridElement]ecs.Entity, pos consts.Coord[consts.Tile], tileOf func(string) (rawschema.Tile, error)) error {
159 1 : e, ok := tiles[gc.GridElement{Coord: pos}]
160 1 : if !ok || !world.ECS.Alive(e) || !world.Components.RawID.Has(e) {
161 1 : return errFacilityGroundNotEarth
162 1 : }
163 1 : t, err := tileOf(world.Components.RawID.Get(e).ID)
164 1 : if err != nil {
165 0 : return err
166 0 : }
167 1 : if t.Earth == nil || !*t.Earth {
168 1 : return errFacilityGroundNotEarth
169 1 : }
170 1 : return nil
171 : }
172 :
173 : // spawnFacilityTile はタイルの行 t を pos へ置く。行の生成の仕様が別のタイルを指せばそれを置き、オートタイルしないタイルは添字を付けない
174 : func spawnFacilityTile(world w.World, tiles map[gc.GridElement]ecs.Entity, pos consts.Coord[consts.Tile], t rawschema.Tile) error {
175 1 : name := t.Id
176 1 : if t.Spawn != nil && t.Spawn.Tile != nil {
177 1 : name = *t.Spawn.Tile
178 1 : }
179 1 : var index *int
180 1 : if t.Spawn != nil && t.Spawn.Autotile {
181 1 : index = new(0)
182 1 : }
183 1 : if _, err := replaceTileIndexed(world, tiles, pos, name, index); err != nil {
184 0 : return fmt.Errorf("failed to place facility tile (x=%d, y=%d): %w", pos.X, pos.Y, err)
185 0 : }
186 1 : return nil
187 : }
188 :
189 : // spawnFacilityCell はマスの扉、家具と収納の中身、床の戦利品、敵を pos へ置く。扉の向きは呼び出し側が壁から決める
190 : func spawnFacilityCell(world w.World, cell maptemplate.MapCell, pos consts.Coord[consts.Tile], orientation gc.DoorOrientation, pose *gc.Pose, fac string, danger consts.Danger, lootRNG, beingRNG *rand.Rand) error {
191 1 : switch {
192 : case cell.Prop == "door":
193 1 : if _, err := lifecycle.SpawnDoor(world, pos, orientation); err != nil {
194 0 : return fmt.Errorf("failed to place facility door at %d,%d: %w", pos.X, pos.Y, err)
195 0 : }
196 : case cell.Prop != "" && !slices.ContainsFunc(query.GetEntitiesAt(world, pos.X, pos.Y), world.Components.Prop.Has):
197 1 : ent, err := lifecycle.SpawnProp(world, cell.Prop, pos.X, pos.Y)
198 1 : if err != nil {
199 0 : return fmt.Errorf("failed to place facility prop (%s at %d,%d): %w", cell.Prop, pos.X, pos.Y, err)
200 0 : }
201 1 : if pose != nil {
202 1 : world.Components.Pose.Add(ent, pose)
203 1 : }
204 1 : if err := populateStorageLoot(world, ent, cell.Prop, cell.LootTable, fac, lootRNG); err != nil {
205 0 : return fmt.Errorf("failed to populate storage loot (%s): %w", cell.Prop, err)
206 0 : }
207 : }
208 1 : for range cell.ItemCount {
209 1 : if err := spawnFieldLoot(world, cell.ItemGroup, pos, lootRNG); err != nil {
210 0 : return fmt.Errorf("failed to place field loot (%s at %d,%d): %w", cell.ItemGroup, pos.X, pos.Y, err)
211 0 : }
212 : }
213 1 : if cell.Being {
214 1 : if err := spawnFacilityBeing(world, fac, danger, pos, beingRNG); err != nil {
215 0 : return fmt.Errorf("failed to place being of facility %q at %d,%d: %w", fac, pos.X, pos.Y, err)
216 0 : }
217 : }
218 1 : return nil
219 : }
220 :
221 : // cellPoses は施設の絵の facing の置物ごとの置き方を返す。絵の外は塞がりに数えない
222 : func cellPoses(cells [][]maptemplate.MapCell, wallAt func(x, y int) bool, propOf func(id string) (rawschema.Prop, error)) (map[consts.Coord[consts.Tile]]*gc.Pose, error) {
223 1 : facers := map[consts.Coord[consts.Tile]]bool{}
224 1 : blockers := map[consts.Coord[consts.Tile]]bool{}
225 1 : for y, row := range cells {
226 1 : for x, cell := range row {
227 1 : if cell.Prop == "" {
228 1 : continue
229 : }
230 1 : prop, err := propOf(cell.Prop)
231 1 : if err != nil {
232 1 : return nil, fmt.Errorf("prop at %d,%d: %w", x, y, err)
233 1 : }
234 1 : c := consts.Coord[consts.Tile]{X: consts.Tile(x), Y: consts.Tile(y)}
235 1 : isFacing := prop.SpriteRender.HasShape(rawschema.Facing)
236 1 : if isFacing {
237 1 : facers[c] = true
238 1 : }
239 1 : blockers[c] = blockers[c] || isFacing || prop.BlockPass
240 : }
241 : }
242 1 : poses := map[consts.Coord[consts.Tile]]*gc.Pose{}
243 2 : wall := func(c consts.Coord[consts.Tile]) bool { return wallAt(int(c.X), int(c.Y)) }
244 1 : for c, f := range mapplanner.RowPoses(facers, blockers, wall) {
245 1 : poses[c] = &f
246 1 : }
247 1 : return poses, nil
248 : }
249 :
250 : // voidEnclosedTall は、直交と斜めの近傍8マスに通れる地形が無い高さのある地形を虚空にする。壁のオートタイルは部屋を囲む細い輪郭を
251 : // 前提にするので、厚い壁の塊の内側を虚空にして描き崩れを防ぐ。マスの外は outsidePassable が通れると返す座標だけを通れるものとして
252 : // 数える。家具の乗った壁は残す
253 : func voidEnclosedTall(cells [][]maptemplate.MapCell, blocks, isTall func(terrain string) bool, outsidePassable func(x, y int) bool) {
254 1 : passable := func(x, y int) bool {
255 1 : if y < 0 || y >= len(cells) || x < 0 || x >= len(cells[y]) {
256 1 : return outsidePassable(x, y)
257 1 : }
258 1 : return !blocks(cells[y][x].Terrain)
259 : }
260 1 : var enclosed [][2]int
261 1 : for y, row := range cells {
262 1 : for x, c := range row {
263 1 : if !isTall(c.Terrain) || c.Prop != "" {
264 1 : continue
265 : }
266 1 : open := false
267 1 : for dy := -1; dy <= 1 && !open; dy++ {
268 1 : for dx := -1; dx <= 1 && !open; dx++ {
269 1 : open = (dx != 0 || dy != 0) && passable(x+dx, y+dy)
270 1 : }
271 : }
272 1 : if !open {
273 1 : enclosed = append(enclosed, [2]int{x, y})
274 1 : }
275 : }
276 : }
277 1 : for _, p := range enclosed {
278 1 : cells[p[1]][p[0]] = maptemplate.MapCell{Terrain: consts.TileNameVoid}
279 1 : }
280 : }
281 :
282 : // tileIsTall は地形 terrain が高さのあるタイルかを raw のタイルの行から返す
283 : func tileIsTall(raws rawschema.Raws) func(terrain string) bool {
284 1 : tall := map[string]bool{}
285 1 : tiles := raw.PtrSlice(raws.Tiles)
286 1 : for i := range tiles {
287 1 : tall[tiles[i].Id] = raw.TileIsTall(tiles[i])
288 1 : }
289 2 : return func(terrain string) bool { return tall[terrain] }
290 : }
291 :
292 : // tileBlocksPass は地形 terrain が通れないかを raw のタイルの行から返す。行の無い地形は通れないとする
293 : func tileBlocksPass(raws rawschema.Raws) func(terrain string) bool {
294 1 : blocks := map[string]bool{}
295 1 : tiles := raw.PtrSlice(raws.Tiles)
296 1 : for i := range tiles {
297 1 : blocks[tiles[i].Id] = tiles[i].BlockPass
298 1 : }
299 1 : return func(terrain string) bool {
300 1 : if terrain == maptemplate.GroundTerrain {
301 1 : return false
302 1 : }
303 1 : b, ok := blocks[terrain]
304 1 : return !ok || b
305 : }
306 : }
|