LCOV - code coverage report
Current view: top level - states - mapgen_visualizer.go Coverage Total Hit
Test: coverage.lcov Lines: 75.8 % 132 100
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package states
       2              : 
       3              : import (
       4              :         "fmt"
       5              :         "math/rand/v2"
       6              :         "slices"
       7              : 
       8              :         "github.com/hajimehoshi/ebiten/v2"
       9              :         "github.com/hajimehoshi/ebiten/v2/ebitenutil"
      10              :         gc "github.com/kijimaD/ruins/internal/components"
      11              :         "github.com/kijimaD/ruins/internal/consts"
      12              :         es "github.com/kijimaD/ruins/internal/engine/states"
      13              :         "github.com/kijimaD/ruins/internal/mapplanner"
      14              :         "github.com/kijimaD/ruins/internal/mapspawner"
      15              :         gs "github.com/kijimaD/ruins/internal/systems"
      16              :         w "github.com/kijimaD/ruins/internal/world"
      17              : 
      18              :         "github.com/kijimaD/ruins/internal/world/query"
      19              :         "github.com/mlange-42/ark/ecs"
      20              : )
      21              : 
      22              : // MapGenVisualizerState はマップ生成過程を可視化するVRT専用ステート
      23              : type MapGenVisualizerState struct {
      24              :         es.BaseState[w.World]
      25              :         snapshots []mapplanner.Snapshot
      26              :         // PlannerType は使用するプランナータイプ
      27              :         PlannerType mapplanner.PlannerType
      28              :         // Seed は乱数シード
      29              :         Seed uint64
      30              :         // SnapshotIndex は表示するスナップショットのインデックス
      31              :         SnapshotIndex int
      32              : 
      33              :         mapWidth  consts.Tile
      34              :         mapHeight consts.Tile
      35              :         danger    consts.Danger
      36              : }
      37              : 
      38              : var _ es.State[w.World] = &MapGenVisualizerState{}
      39              : 
      40              : // OnPause は一時停止時の処理
      41            0 : func (st *MapGenVisualizerState) OnPause(_ w.World) error { return nil }
      42              : 
      43              : // OnResume は再開時の処理
      44            0 : func (st *MapGenVisualizerState) OnResume(_ w.World) error { return nil }
      45              : 
      46              : // OnStart はスナップショットを生成してエンティティをスポーンする
      47              : func (st *MapGenVisualizerState) OnStart(world w.World) error {
      48            1 :         seed := st.Seed
      49            1 :         if seed == 0 {
      50            0 :                 seed = world.Resources.Config.RNG.Uint64()
      51            0 :         }
      52              : 
      53            1 :         chain, err := mapplanner.BuildChain(world, consts.MapTileWidth, consts.MapTileHeight, seed, st.PlannerType)
      54            1 :         if err != nil {
      55            0 :                 return fmt.Errorf("failed to create PlannerChain: %w", err)
      56            0 :         }
      57            1 :         chain.Recording = true
      58            1 : 
      59            1 :         if err := chain.Plan(); err != nil {
      60            0 :                 return fmt.Errorf("failed to execute plan: %w", err)
      61            0 :         }
      62              : 
      63              :         // チェーン実行後の実際のマップサイズを使用する。テンプレートベースのPlannerは引数のwidth/heightを無視するため
      64            1 :         st.mapWidth = chain.PlanData.Level.TileWidth
      65            1 :         st.mapHeight = chain.PlanData.Level.TileHeight
      66            1 :         st.danger = chain.PlanData.Danger
      67            1 : 
      68            1 :         st.snapshots = chain.Snapshots
      69            1 :         if st.SnapshotIndex < 0 || st.SnapshotIndex >= len(st.snapshots) {
      70            0 :                 return fmt.Errorf("SnapshotIndex %d out of range, snapshot count %d", st.SnapshotIndex, len(st.snapshots))
      71            0 :         }
      72              : 
      73              :         // カメラをマップ全体が見えるように設定する
      74            1 :         st.setupCamera(world)
      75            1 : 
      76            1 :         return st.spawnSnapshot(world)
      77              : }
      78              : 
      79              : // OnStop はエンティティを削除する
      80              : func (st *MapGenVisualizerState) OnStop(world w.World) error {
      81            0 :         st.clearEntities(world)
      82            0 :         return nil
      83            0 : }
      84              : 
      85              : // Update はVRT専用のため何もしない
      86              : func (st *MapGenVisualizerState) Update(_ w.World) (es.Transition[w.World], error) {
      87            1 :         return st.ConsumeTransition(), nil
      88            1 : }
      89              : 
      90              : // Draw はスプライトとHUDを描画する
      91              : func (st *MapGenVisualizerState) Draw(world w.World, screen *ebiten.Image) error {
      92              :         // RenderSpriteSystemで描画する
      93            1 :         if sys, ok := world.Renderers[(&gs.RenderSpriteSystem{}).String()]; ok {
      94            1 :                 if err := sys.Draw(world, screen); err != nil {
      95            0 :                         return err
      96            0 :                 }
      97              :         }
      98              : 
      99              :         // HUD: フェーズ情報を表示する
     100            1 :         if st.SnapshotIndex < len(st.snapshots) {
     101            1 :                 snap := st.snapshots[st.SnapshotIndex]
     102            1 :                 info := fmt.Sprintf("Phase %d/%d: %s", st.SnapshotIndex+1, len(st.snapshots), snap.Label)
     103            1 :                 ebitenutil.DebugPrint(screen, info)
     104            1 :         }
     105              : 
     106            1 :         return nil
     107              : }
     108              : 
     109              : // setupCamera はマップ全体が画面に収まるようにカメラを設定する
     110              : func (st *MapGenVisualizerState) setupCamera(world w.World) {
     111            1 :         tileSize := float64(consts.TileSize)
     112            1 :         mapPixelW := float64(st.mapWidth) * tileSize
     113            1 :         mapPixelH := float64(st.mapHeight) * tileSize
     114            1 : 
     115            1 :         screenW := float64(world.Resources.ScreenDimensions.Width)
     116            1 :         screenH := float64(world.Resources.ScreenDimensions.Height)
     117            1 : 
     118              :         // マップ全体が画面に収まるスケールを計算する
     119            1 :         scaleX := screenW / mapPixelW
     120            1 :         scaleY := screenH / mapPixelH
     121            1 :         scale := scaleX
     122            1 :         if scaleY < scale {
     123            1 :                 scale = scaleY
     124            1 :         }
     125              :         // 少し余白を持たせる
     126            1 :         scale *= 0.9
     127            1 : 
     128            1 :         centerX := mapPixelW / 2
     129            1 :         centerY := mapPixelH / 2
     130            1 : 
     131            1 :         cameraQuery := ecs.NewFilter1[gc.Camera](world.ECS).Query()
     132            1 :         for cameraQuery.Next() {
     133            1 :                 entity := cameraQuery.Entity()
     134            1 :                 camera := world.Components.Camera.Get(entity)
     135            1 :                 camera.Scale = scale
     136            1 :                 camera.ScaleTo = scale
     137            1 :                 camera.Pos.X = consts.WorldPixel(centerX)
     138            1 :                 camera.Pos.Y = consts.WorldPixel(centerY)
     139            1 :                 camera.Target.X = consts.WorldPixel(centerX)
     140            1 :                 camera.Target.Y = consts.WorldPixel(centerY)
     141            1 :         }
     142              : }
     143              : 
     144              : // spawnSnapshot は現在のスナップショットからエンティティを生成する
     145              : func (st *MapGenVisualizerState) spawnSnapshot(world w.World) error {
     146            1 :         snap := st.snapshots[st.SnapshotIndex]
     147            1 : 
     148            1 :         tiles := slices.Clone(snap.Tiles)
     149            1 :         plan := &mapplanner.MetaPlan{
     150            1 :                 Danger:    st.danger,
     151            1 :                 RawMaster: &world.Resources.RawMaster,
     152            1 :                 Level: gc.Level{
     153            1 :                         TileWidth:  st.mapWidth,
     154            1 :                         TileHeight: st.mapHeight,
     155            1 :                 },
     156            1 :                 Tiles:       tiles,
     157            1 :                 Rooms:       snap.Rooms,
     158            1 :                 Corridors:   snap.Corridors,
     159            1 :                 NPCs:        snap.NPCs,
     160            1 :                 Items:       snap.Items,
     161            1 :                 Props:       snap.Props,
     162            1 :                 Doors:       snap.Doors,
     163            1 :                 NextPortals: snap.NextPortals,
     164            1 :                 SpawnPoints: snap.SpawnPoints,
     165            1 :                 // 収納の中身の抽選が乱数を引くので、シードから決まる乱数を渡して描画を毎回同じにする
     166            1 :                 RNG: rand.New(rand.NewPCG(st.Seed, st.Seed)),
     167            1 :         }
     168              :         // 計画の前のフェーズの空のタイルは void で描く
     169            1 :         for i := range tiles {
     170            1 :                 if tiles[i].Id == "" {
     171            1 :                         tiles[i] = plan.GetTile("void")
     172            1 :                 }
     173              :         }
     174              : 
     175            1 :         if _, err := mapspawner.Spawn(world, plan); err != nil {
     176            0 :                 return fmt.Errorf("failed to spawn snapshot %d: %w", st.SnapshotIndex, err)
     177            0 :         }
     178              : 
     179              :         // 全タイルを可視にする
     180            1 :         st.revealAllTiles(world)
     181            1 : 
     182              :         // プレイヤーを画面外に移動して非表示にする
     183            1 :         st.hidePlayer(world)
     184            1 : 
     185            1 :         return nil
     186              : }
     187              : 
     188              : // revealAllTiles は全タイルを可視状態にする
     189              : func (st *MapGenVisualizerState) revealAllTiles(world w.World) {
     190            1 :         vs := query.GetVisionState(world)
     191            1 :         vs.VisibleTiles = make(map[gc.GridElement]bool)
     192            1 :         for y := consts.Tile(0); y < st.mapHeight; y++ {
     193            1 :                 for x := consts.Tile(0); x < st.mapWidth; x++ {
     194            1 :                         vs.VisibleTiles[gc.GridElement{Coord: consts.Coord[consts.Tile]{X: x, Y: y}}] = true
     195            1 :                 }
     196              :         }
     197              : }
     198              : 
     199              : // hidePlayer はプレイヤーを画面外に移動して描画されないようにする
     200              : func (st *MapGenVisualizerState) hidePlayer(world w.World) {
     201            1 :         playerQuery := ecs.NewFilter2[gc.Player, gc.GridElement](world.ECS).Query()
     202            1 :         for playerQuery.Next() {
     203            1 :                 entity := playerQuery.Entity()
     204            1 :                 ge := world.Components.GridElement.Get(entity)
     205            1 :                 ge.X = -100
     206            1 :                 ge.Y = -100
     207            1 :         }
     208              : }
     209              : 
     210              : // clearEntities はスポーンしたエンティティを削除する
     211              : func (st *MapGenVisualizerState) clearEntities(world w.World) {
     212            0 :         spriteRenderQuery := ecs.NewFilter1[gc.SpriteRender](world.ECS).Query()
     213            0 :         for spriteRenderQuery.Next() {
     214            0 :                 entity := spriteRenderQuery.Entity()
     215            0 :                 if !world.Components.Player.Has(entity) &&
     216            0 :                         !world.Components.LocationInBackpack.Has(entity) &&
     217            0 :                         !world.Components.LocationEquipped.Has(entity) {
     218            0 :                         world.ECS.RemoveEntity(entity)
     219            0 :                 }
     220              :         }
     221            0 :         gridElementQuery := ecs.NewFilter1[gc.GridElement](world.ECS).Query()
     222            0 :         for gridElementQuery.Next() {
     223            0 :                 entity := gridElementQuery.Entity()
     224            0 :                 if !world.Components.Player.Has(entity) {
     225            0 :                         world.ECS.RemoveEntity(entity)
     226            0 :                 }
     227              :         }
     228              : 
     229            0 :         query.InvalidateSpatialIndex(world)
     230              : }
        

Generated by: LCOV version 2.0-1