LCOV - code coverage report
Current view: top level - systems - vision.go Coverage Total Hit
Test: coverage.lcov Lines: 69.2 % 266 184
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package systems
       2              : 
       3              : import (
       4              :         "image/color"
       5              :         "math"
       6              : 
       7              :         gc "github.com/kijimaD/ruins/internal/components"
       8              :         "github.com/kijimaD/ruins/internal/consts"
       9              :         "github.com/kijimaD/ruins/internal/geometry"
      10              :         w "github.com/kijimaD/ruins/internal/world"
      11              : 
      12              :         "github.com/kijimaD/ruins/internal/world/query"
      13              :         "github.com/mlange-42/ark/ecs"
      14              : )
      15              : 
      16              : // VisionSystem はタイルごとの視界を計算するUpdaterシステム。
      17              : // 計算結果の光源情報は VisionState シングルトンに書き込み、描画側はそこから参照する。
      18              : type VisionSystem struct {
      19              :         // プレイヤー位置キャッシュ(タイル移動ごとに更新)
      20              :         lastPlayer    consts.Coord[consts.WorldPixel]
      21              :         isInitialized bool
      22              : }
      23              : 
      24              : // NewVisionSystem はVisionSystemを初期化する
      25              : func NewVisionSystem() *VisionSystem {
      26            1 :         return &VisionSystem{}
      27            1 : }
      28              : 
      29              : // String はシステム名を返す
      30              : // w.Updater interfaceを実装
      31              : func (sys VisionSystem) String() string {
      32            1 :         return "VisionSystem"
      33            1 : }
      34              : 
      35              : // Update は視界計算を行う
      36              : // w.Updater interfaceを実装
      37              : func (sys *VisionSystem) Update(world w.World) error {
      38              :         // プレイヤー位置を取得
      39            0 :         var playerGridElement *gc.GridElement
      40            0 :         playerQuery := ecs.NewFilter2[gc.GridElement, gc.Player](world.ECS).Query()
      41            0 :         for playerQuery.Next() {
      42            0 :                 entity := playerQuery.Entity()
      43            0 :                 playerGridElement = world.Components.GridElement.Get(entity)
      44            0 :         }
      45              : 
      46            0 :         if playerGridElement == nil {
      47            0 :                 return nil
      48            0 :         }
      49              : 
      50              :         // タイル座標をワールドピクセル座標に変換
      51            0 :         playerPos := consts.TileCenterToWorld(playerGridElement.Coord)
      52            0 : 
      53            0 :         if query.GetDungeon(world) == nil {
      54            0 :                 return nil
      55            0 :         }
      56            0 :         field := query.GetCurrentStageField(world)
      57            0 :         if field == nil {
      58            0 :                 return nil
      59            0 :         }
      60            0 :         vs := query.GetVisionState(world)
      61            0 : 
      62              :         // 移動ごとの視界更新判定(移動ごとに更新)
      63            0 :         const updateThreshold = int(consts.TileSize)
      64            0 :         needsUpdate := !sys.isInitialized ||
      65            0 :                 geometry.Abs(int(playerPos.X-sys.lastPlayer.X)) >= updateThreshold ||
      66            0 :                 geometry.Abs(int(playerPos.Y-sys.lastPlayer.Y)) >= updateThreshold
      67            0 : 
      68              :         // 外部から要求された視界更新を消費する
      69            0 :         if vs.ConsumePendingUpdate() {
      70            0 :                 needsUpdate = true
      71            0 :         }
      72              : 
      73            0 :         if !needsUpdate {
      74            0 :                 return nil
      75            0 :         }
      76              : 
      77              :         // 視界遮断タイルのインデックスを構築する
      78            0 :         blockViewIndex := buildBlockViewIndex(world)
      79            0 : 
      80              :         // タイルの可視性マップを更新。屋外の天候で視程を縮める。地下では地上の天候は視界に効かせない。
      81              :         // VisionDelta は負か0のみを想定し、下限で床を打ち0にはしない。正の値を足す天候を作るなら上限も要る
      82            0 :         const minVisionTiles consts.Tile = 8
      83            0 :         weatherVision := 0
      84            0 :         if query.IsOnOverworld(world) {
      85            0 :                 weatherVision = world.Resources.WeatherDefs.Kinds[query.GetWeather(world).Current].Effect.VisionDelta
      86            0 :         }
      87            0 :         effectiveTiles := max(consts.VisionRadiusTiles+consts.Tile(weatherVision), minVisionTiles)
      88            0 :         visionRadius := consts.WorldPixel(effectiveTiles) * consts.TileSize
      89            0 :         visibilityData := calculateTileVisibilityWithDistance(playerPos, visionRadius, blockViewIndex)
      90            0 : 
      91              :         // 光源情報を更新前にクリアする
      92            0 :         vs.LightSourceCache = make(map[gc.GridElement]gc.LightInfo)
      93            0 : 
      94              :         // 視界内タイルの光源情報を計算し、探索済みマークを行う。
      95              :         // マップ外座標はデータに含めない。
      96              :         // 環境光は明るさと色を持つ。ダンジョンは微小で無彩色、地上は時間帯の日照と色で、屋根の下は
      97              :         // 囲われの日照を受ける割合だけ日照を受ける。昼の屋外は全体が明るく松明が要らず、
      98              :         // ダンジョンと深夜と屋内は松明の届く範囲だけが見える
      99            0 :         ambient := dungeonAmbient
     100            0 :         ambientColor := [3]float64{1, 1, 1}
     101            0 :         var daylightPercents map[gc.GridElement]int
     102            0 :         if query.IsOnOverworld(world) {
     103            0 :                 gt := query.GetGameTime(world)
     104            0 :                 ambient = overworldDaylight(world.Resources.CalendarDefs, gt)
     105            0 :                 ambientColor = overworldAmbientColor(world.Resources.CalendarDefs, gt)
     106            0 :                 daylightPercents = buildDaylightPercentIndex(world)
     107            0 :         }
     108            0 :         visibleTiles := make(map[gc.GridElement]bool)
     109            0 :         for _, tileData := range visibilityData {
     110            0 :                 if !tileData.Visible {
     111            0 :                         continue
     112              :                 }
     113            0 :                 gridElement := gc.GridElement{Coord: consts.Coord[consts.Tile]{X: consts.Tile(tileData.Col), Y: consts.Tile(tileData.Row)}}
     114            0 :                 if !isInMapBounds(gridElement, field.Level) {
     115            0 :                         continue
     116              :                 }
     117              : 
     118            0 :                 tileAmbient := ambient
     119            0 :                 if p, ok := daylightPercents[gridElement]; ok {
     120            0 :                         tileAmbient = shelteredAmbient(ambient, p)
     121            0 :                 }
     122            0 :                 info := calculateLightSourceDarkness(world, consts.Coord[int]{X: tileData.Col, Y: tileData.Row}, blockViewIndex, tileAmbient, ambientColor)
     123            0 :                 // 明るさが閾値未満なら見えない。視界を光の届く範囲へ寄せる。
     124              :                 // 見えないタイルは記憶側へ回るので、暗所の敵やアイテムは自然に隠れる
     125            0 :                 if 1.0-info.Darkness < visibilityThreshold {
     126            0 :                         continue
     127              :                 }
     128            0 :                 vs.LightSourceCache[gridElement] = info
     129            0 :                 field.ExploredTiles[gridElement] = true
     130            0 :                 visibleTiles[gridElement] = true
     131              :         }
     132            0 :         vs.VisibleTiles = visibleTiles
     133            0 : 
     134            0 :         sys.lastPlayer = playerPos
     135            0 :         sys.isInitialized = true
     136            0 : 
     137            0 :         return nil
     138              : }
     139              : 
     140              : // TileVisibility はレイキャストによるタイルの可視性判定結果を表す
     141              : type TileVisibility struct {
     142              :         Row     int
     143              :         Col     int
     144              :         Visible bool
     145              : }
     146              : 
     147              : type (
     148              :         // VisibleDarkness は視界内タイルの暗闇の強さを表す
     149              :         VisibleDarkness float64
     150              :         // RememberedDarkness は記憶済みタイルの暗闇の強さを表す
     151              :         RememberedDarkness float64
     152              : )
     153              : 
     154              : // TileRenderInfo はタイルごとの描画情報を表す
     155              : type TileRenderInfo interface {
     156              :         tileRenderInfo()
     157              : }
     158              : 
     159              : // TileRenderVisible は視界内の状態
     160              : type TileRenderVisible struct {
     161              :         Darkness   VisibleDarkness // 暗闘の強さ。0.0で完全に明るく、1.0で完全に暗い
     162              :         LightColor color.RGBA      // 光源がある場合の色
     163              :         Ambient    float64         // タイルが受ける環境光の明るさ。光の情報が無ければ 0 で、昼の底上げを受けない
     164              : }
     165              : 
     166            0 : func (TileRenderVisible) tileRenderInfo() {}
     167              : 
     168              : // TileRenderRemembered は視界外だが記憶済みの状態。床のみうっすら描画する
     169              : type TileRenderRemembered struct {
     170              :         Darkness RememberedDarkness
     171              : }
     172              : 
     173            0 : func (TileRenderRemembered) tileRenderInfo() {}
     174              : 
     175              : // TileRenderUnexplored はまだ一度も見ていない未探索の状態。
     176              : // 未探索は viewport の大半を占め map へ格納するとコストが高いので、map には入れず
     177              : // tileRenderAt が不在時に返す番兵として使う。
     178              : type TileRenderUnexplored struct{}
     179              : 
     180            0 : func (TileRenderUnexplored) tileRenderInfo() {}
     181              : 
     182              : // tileRenderAt はタイルの描画情報を返す。map に無いタイルは未探索とみなし
     183              : // TileRenderUnexplored を返す。不在を未探索へ明示的に写し、呼び出し側で3状態を網羅できるようにする。
     184              : func tileRenderAt(m map[gc.GridElement]TileRenderInfo, grid gc.GridElement) TileRenderInfo {
     185            1 :         if info, ok := m[grid]; ok {
     186            1 :                 return info
     187            1 :         }
     188            1 :         return TileRenderUnexplored{}
     189              : }
     190              : 
     191              : // computeTileRenderMap はタイルごとの描画情報を一括計算する。
     192              : // VisibleTiles・ExploredTiles・光源情報を統合して、
     193              : // 各描画関数が参照するだけで済む描画情報マップを返す
     194              : func computeTileRenderMap(world w.World, lights map[gc.GridElement]gc.LightInfo) map[gc.GridElement]TileRenderInfo {
     195            1 :         result := make(map[gc.GridElement]TileRenderInfo)
     196            1 :         field := query.GetCurrentStageField(world)
     197            1 :         vs := query.GetVisionState(world)
     198            1 : 
     199              :         // 現在見えているタイルを設定する。明るさは光源の加算結果 li.Darkness を使う。
     200              :         // ただし記憶タイルより暗くはしない。今見えているタイルが、ただ記憶しているだけの
     201              :         // タイルより暗く見えると、光の輪の縁だけが黒いリングになって不自然になるのを防ぐ
     202            1 :         for grid := range vs.VisibleTiles {
     203            1 :                 visible := TileRenderVisible{Darkness: DarknessVisible}
     204            1 :                 if li, ok := lights[grid]; ok {
     205            1 :                         visible.Darkness = VisibleDarkness(math.Min(li.Darkness, float64(DarknessRemembered)))
     206            1 :                         visible.Ambient = li.Ambient
     207            1 :                         // 完全な暗黒には色を乗せない。描画側も無視するが、意図を明示する
     208            1 :                         if li.Darkness < 1.0 {
     209            1 :                                 visible.LightColor = li.Color
     210            1 :                         }
     211              :                 }
     212            1 :                 result[grid] = visible
     213              :         }
     214              : 
     215              :         // 視界外だが記憶済みのタイルを設定する
     216            1 :         if field != nil {
     217            1 :                 for grid := range field.ExploredTiles {
     218            1 :                         if _, exists := result[grid]; !exists {
     219            1 :                                 result[grid] = TileRenderRemembered{Darkness: DarknessRemembered}
     220            1 :                         }
     221              :                 }
     222              :         }
     223              : 
     224            1 :         return result
     225              : }
     226              : 
     227              : // isInMapBounds は座標がマップの有効範囲内かを判定する
     228              : func isInMapBounds(grid gc.GridElement, level gc.Level) bool {
     229            1 :         return grid.X >= 0 && grid.X < level.TileWidth && grid.Y >= 0 && grid.Y < level.TileHeight
     230            1 : }
     231              : 
     232              : // calculateTileVisibilityWithDistance はレイキャストでタイルごとの可視性と距離を計算する。
     233              : // 結果はキーで引かず順に走査するだけなので、マップでなくスライスで返す。座標は各要素の
     234              : // Row・Col が持つ。タイルごとの文字列キー生成を避け、視界内タイル数ぶんの alloc を無くす。
     235              : func calculateTileVisibilityWithDistance(playerPos consts.Coord[consts.WorldPixel], radius consts.WorldPixel, blockIndex map[gc.GridElement]bool) []TileVisibility {
     236              :         // プレイヤーの位置からタイル座標を計算
     237            1 :         playerTileX := int(playerPos.X) / int(consts.TileSize)
     238            1 :         playerTileY := int(playerPos.Y) / int(consts.TileSize)
     239            1 : 
     240              :         // 視界範囲を分割して段階的処理(視界範囲最適化)
     241            1 :         maxTileDistance := int(radius)/int(consts.TileSize) + 2
     242            1 : 
     243              :         // 走査する正方形のタイル数を上限に事前確保し、追加時の再確保を避ける
     244            1 :         side := 2*maxTileDistance + 1
     245            1 :         visibility := make([]TileVisibility, 0, side*side)
     246            1 : 
     247              :         // タイルベース視界判定(Dark Days Ahead風)
     248              : 
     249            1 :         for dx := -maxTileDistance; dx <= maxTileDistance; dx++ {
     250            1 :                 for dy := -maxTileDistance; dy <= maxTileDistance; dy++ {
     251            1 :                         tileX := playerTileX + dx
     252            1 :                         tileY := playerTileY + dy
     253            1 : 
     254              :                         // タイルの中心座標を計算
     255            1 :                         tileCenter := consts.TileCenterToWorld(consts.Coord[consts.Tile]{X: consts.Tile(tileX), Y: consts.Tile(tileY)})
     256            1 : 
     257              :                         // プレイヤーからタイル中心への距離をチェック(平方根計算の最適化)
     258            1 :                         dxF := float64(tileCenter.X - playerPos.X)
     259            1 :                         dyF := float64(tileCenter.Y - playerPos.Y)
     260            1 :                         distanceSquared := dxF*dxF + dyF*dyF
     261            1 :                         radiusSquared := float64(radius) * float64(radius)
     262            1 : 
     263              :                         // 視界範囲内のタイルのみ処理
     264            1 :                         if distanceSquared <= radiusSquared {
     265            1 :                                 visible := isTileVisibleByRaycast(playerPos, tileCenter, blockIndex)
     266            1 : 
     267            1 :                                 visibility = append(visibility, TileVisibility{
     268            1 :                                         Row:     tileY,
     269            1 :                                         Col:     tileX,
     270            1 :                                         Visible: visible,
     271            1 :                                 })
     272            1 :                         }
     273              :                         // 視界外のタイルは処理しない(最適化)
     274              :                 }
     275              :         }
     276              : 
     277            1 :         return visibility
     278              : }
     279              : 
     280              : // isTileVisibleByRaycast はタイルベース視界判定
     281              : func isTileVisibleByRaycast(player, target consts.Coord[consts.WorldPixel], blockIndex map[gc.GridElement]bool) bool {
     282              :         // タイル座標に変換
     283            1 :         playerTileX := int(player.X / consts.TileSize)
     284            1 :         playerTileY := int(player.Y / consts.TileSize)
     285            1 :         targetTileX := int(target.X / consts.TileSize)
     286            1 :         targetTileY := int(target.Y / consts.TileSize)
     287            1 : 
     288              :         // 同じタイルまたは隣接タイルは常に見える
     289            1 :         if geometry.Abs(targetTileX-playerTileX) <= 1 && geometry.Abs(targetTileY-playerTileY) <= 1 {
     290            1 :                 return true
     291            1 :         }
     292              : 
     293              :         // ブレゼンハムのライン描画アルゴリズムでタイルベースの視線判定
     294            1 :         return bresenhamLineOfSight(playerTileX, playerTileY, targetTileX, targetTileY, blockIndex)
     295              : }
     296              : 
     297              : // bresenhamLineOfSight はブレゼンハムアルゴリズムを使用したタイルベース視線判定
     298              : func bresenhamLineOfSight(x0, y0, x1, y1 int, blockIndex map[gc.GridElement]bool) bool {
     299            1 :         dx := geometry.Abs(x1 - x0)
     300            1 :         dy := geometry.Abs(y1 - y0)
     301            1 : 
     302            1 :         var sx, sy int
     303            1 :         if x0 < x1 {
     304            1 :                 sx = 1
     305            1 :         } else {
     306            1 :                 sx = -1
     307            1 :         }
     308            1 :         if y0 < y1 {
     309            1 :                 sy = 1
     310            1 :         } else {
     311            1 :                 sy = -1
     312            1 :         }
     313              : 
     314            1 :         err := dx - dy
     315            1 :         x, y := x0, y0
     316            1 : 
     317            1 :         for {
     318              :                 // ターゲットに到達したら見える
     319            1 :                 if x == x1 && y == y1 {
     320            1 :                         return true
     321            1 :                 }
     322              : 
     323              :                 // 現在のタイルが視界を遮るかチェック
     324            1 :                 if blockIndex[gc.GridElement{Coord: consts.Coord[consts.Tile]{X: consts.Tile(x), Y: consts.Tile(y)}}] {
     325            1 :                         return false
     326            1 :                 }
     327              : 
     328            1 :                 e2 := 2 * err
     329            1 :                 if e2 > -dy {
     330            1 :                         err -= dy
     331            1 :                         x += sx
     332            1 :                 }
     333            1 :                 if e2 < dx {
     334            1 :                         err += dx
     335            1 :                         y += sy
     336            1 :                 }
     337              :         }
     338              : }
     339              : 
     340              : // overworldDaylight は地上の日照の明るさを、隣接する時間帯の中心値の間を線形補間して連続に返す。
     341              : // 段差だと夕へ入った瞬間に暗くなり夜のように見えるので、代表値をなだらかにつないで徐々に変える。
     342              : func overworldDaylight(defs gc.CalendarDefs, gt *gc.GameTime) float64 {
     343            1 :         from, to, t := gt.GetDaylightLerp()
     344            1 :         a := defs.TimesOfDay[from].Daylight
     345            1 :         b := defs.TimesOfDay[to].Daylight
     346            1 :         return a + (b-a)*t
     347            1 : }
     348              : 
     349              : // overworldAmbientColor は地上の環境光の色を、隣接する時間帯の中心色の間を線形補間して連続に返す。
     350              : // 段差だと夕焼け色が一瞬で寒色の夜へ切り替わるので、代表色をなだらかにつないで徐々に変える。
     351              : // 明るさは overworldDaylight が持つので、ここは色味だけを表す。
     352              : func overworldAmbientColor(defs gc.CalendarDefs, gt *gc.GameTime) [3]float64 {
     353            1 :         from, to, t := gt.GetDaylightLerp()
     354            1 :         a := defs.TimesOfDay[from].AmbientColor
     355            1 :         b := defs.TimesOfDay[to].AmbientColor
     356            1 :         return [3]float64{a[0] + (b[0]-a[0])*t, a[1] + (b[1]-a[1])*t, a[2] + (b[2]-a[2])*t}
     357            1 : }
     358              : 
     359              : // shelteredAmbient は日照 daylight のうち percent の割合だけを受けた環境光を返す。0 ならダンジョンと同じ暗さになる。
     360              : // 日照がダンジョンより暗くても、屋根の下が屋外より明るくはならない
     361              : func shelteredAmbient(daylight float64, percent int) float64 {
     362            1 :         return math.Min(daylight, dungeonAmbient+(daylight-dungeonAmbient)*float64(percent)/100)
     363            1 : }
     364              : 
     365              : // buildDaylightPercentIndex は日照を減らして受けるタイルの座標と、日照を受ける割合を集める。表に無い座標は日照をそのまま受ける
     366              : func buildDaylightPercentIndex(world w.World) map[gc.GridElement]int {
     367            1 :         index := make(map[gc.GridElement]int)
     368            1 :         shelters := world.Resources.TileEnvDefs.Shelters
     369            1 :         q := query.ActiveFilter3[gc.GridElement, gc.TileEnvironment, gc.Tile](world).Query()
     370            1 :         for q.Next() {
     371            1 :                 def, ok := shelters[world.Components.TileEnvironment.Get(q.Entity()).Shelter]
     372            1 :                 if ok && def.DaylightPercent < 100 {
     373            1 :                         index[*world.Components.GridElement.Get(q.Entity())] = def.DaylightPercent
     374            1 :                 }
     375              :         }
     376            1 :         return index
     377              : }
     378              : 
     379              : // lightAccum は環境光と光源を畳んで明るさと色を溜める。フィルタ列で順に組み立てる。
     380              : type lightAccum struct {
     381              :         brightness       float64 // 加算した明るさ。resolve で 0..1 にクランプする
     382              :         sumR, sumG, sumB float64 // 色の加重和。weight で割って平均色にする
     383              :         weight           float64 // 加重和の総重み
     384              : }
     385              : 
     386              : // ambientLight は環境光を基底に置いた accum を返す。無照明のタイルはこの色と明るさになる。
     387              : func ambientLight(ambient float64, color [3]float64) lightAccum {
     388            1 :         return lightAccum{
     389            1 :                 brightness: ambient,
     390            1 :                 sumR:       color[0] * 255 * ambient,
     391            1 :                 sumG:       color[1] * 255 * ambient,
     392            1 :                 sumB:       color[2] * 255 * ambient,
     393            1 :                 weight:     ambient,
     394            1 :         }
     395              : }
     396              : 
     397              : // addSource は光源1つを寄与 contrib で足す。明るさは加算合成、色は加重和へ積む。
     398              : func (a lightAccum) addSource(c color.RGBA, contrib float64) lightAccum {
     399            1 :         a.brightness += contrib
     400            1 :         a.sumR += float64(c.R) * contrib
     401            1 :         a.sumG += float64(c.G) * contrib
     402            1 :         a.sumB += float64(c.B) * contrib
     403            1 :         a.weight += contrib
     404            1 :         return a
     405            1 : }
     406              : 
     407              : // resolve は溜めた明るさと色を LightInfo にまとめる。
     408              : func (a lightAccum) resolve() gc.LightInfo {
     409            1 :         brightness := math.Max(0, math.Min(1, a.brightness))
     410            1 :         col := color.RGBA{A: 255}
     411            1 :         if a.weight > 0 {
     412            1 :                 col.R = uint8(math.Min(255, a.sumR/a.weight))
     413            1 :                 col.G = uint8(math.Min(255, a.sumG/a.weight))
     414            1 :                 col.B = uint8(math.Min(255, a.sumB/a.weight))
     415            1 :         }
     416            1 :         return gc.LightInfo{Darkness: 1 - brightness, Color: col}
     417              : }
     418              : 
     419              : // calculateLightSourceDarkness はタイルの明るさを光源の加算合成で求め、暗さ=1-明るさで返す。
     420              : // 環境光を基底に、各光源を減衰と suppress で絞って足し込む。壁で視線が遮られた光源は寄与しない。
     421              : func calculateLightSourceDarkness(world w.World, tile consts.Coord[int], blockIndex map[gc.GridElement]bool, ambient float64, ambientColor [3]float64) gc.LightInfo {
     422            1 :         acc := ambientLight(ambient, ambientColor)
     423            1 : 
     424              :         // 環境光で光源の寄与を絞る係数。lightFadeLow 以下で満額、lightFadeHigh 以上で 0。明るさと色の両方にかける
     425            1 :         suppress := 1 - smoothstep(lightFadeLow, lightFadeHigh, ambient)
     426            1 : 
     427              :         // 全ての光源をチェック。退避中ステージの光源は現ステージを照らさない。
     428              :         // 火は燃え尽きると自分の LightSource を外すので照らさなくなる
     429            1 :         lightQuery := query.ActiveFilter2[gc.LightSource, gc.GridElement](world).Query()
     430            1 :         for lightQuery.Next() {
     431            1 :                 lightEntity := lightQuery.Entity()
     432            1 :                 lightSource := world.Components.LightSource.Get(lightEntity)
     433            1 : 
     434            1 :                 if !lightSource.Enabled {
     435            0 :                         continue
     436              :                 }
     437              : 
     438            1 :                 lightGrid := world.Components.GridElement.Get(lightEntity)
     439            1 :                 distance := geometry.Distance(float64(tile.X), float64(tile.Y), float64(lightGrid.X), float64(lightGrid.Y))
     440            1 :                 if distance > float64(lightSource.Radius) {
     441            0 :                         continue
     442              :                 }
     443              :                 // 光源からタイルへの視線が壁で遮られているなら光は届かない。壁の裏へ漏らさない。
     444            1 :                 if !bresenhamLineOfSight(int(lightGrid.X), int(lightGrid.Y), tile.X, tile.Y, blockIndex) {
     445            1 :                         continue
     446              :                 }
     447              : 
     448              :                 // 中心1タイルまでは最大の明るさにする
     449            1 :                 if distance < 1.0 {
     450            1 :                         distance = 1.0
     451            1 :                 }
     452            1 :                 nd := distance / float64(lightSource.Radius)
     453            1 : 
     454              :                 // 平坦な床を照らす見た目にする。半径の内側 lightPlateau までは一様に明るく、
     455              :                 // 外縁だけ滑らかに0へ落とす。中心だけ極端に明るい逆二乗だと、トップダウンでは
     456              :                 // 光った球のように見えてしまうのを避ける
     457            1 :                 atten := 1.0 - smoothstep(lightPlateau, 1.0, nd)
     458            1 : 
     459            1 :                 acc = acc.addSource(lightSource.Color, atten*suppress)
     460              :         }
     461              : 
     462            1 :         info := acc.resolve()
     463            1 :         info.Ambient = ambient
     464            1 :         return info
     465              : }
     466              : 
     467              : // 各タイル状態の暗闇の強さ
     468              : const (
     469              :         DarknessVisible    VisibleDarkness    = 0.15
     470              :         DarknessRemembered RememberedDarkness = 0.75
     471              : )
     472              : 
     473              : // ライティングの調整値
     474              : const (
     475              :         // dungeonAmbient はダンジョンの環境光。松明が無いと見えないくらい暗い
     476              :         dungeonAmbient = 0.06
     477              :         // lightFadeLow は光源のフェードの下端。これ以下の環境光では光源が満額効く
     478              :         lightFadeLow = 0.45
     479              :         // lightFadeHigh は光源のフェードの上端。これ以上の環境光では光源が明るさも色も足さない。
     480              :         // ここで消えた明るさは render3d.go の dayOverbright が日中の底上げで補う
     481              :         lightFadeHigh = 0.8
     482              :         // visibilityThreshold はこの明るさ未満のタイルを見えないとみなす境界。視界を光の届く範囲へ寄せる
     483              :         visibilityThreshold = 0.10
     484              :         // lightPlateau は光源の平坦域。正規化距離がこの値までは一様に明るく、外縁で滑らかに落とす
     485              :         lightPlateau = 0.45
     486              : )
     487              : 
     488              : // smoothstep は edge0..edge1 を 0..1 へ滑らかに写す。両端の傾きが0のS字。
     489              : func smoothstep(edge0, edge1, x float64) float64 {
     490            1 :         t := (x - edge0) / (edge1 - edge0)
     491            1 :         t = math.Max(0, math.Min(1, t))
     492            1 :         return t * t * (3 - 2*t)
     493            1 : }
     494              : 
     495              : // buildBlockViewIndex は全BlockViewエンティティのタイル座標をインデックス化する
     496              : func buildBlockViewIndex(world w.World) map[gc.GridElement]bool {
     497            1 :         index := make(map[gc.GridElement]bool)
     498            1 :         // 退避中ステージの遮蔽物は現ステージの視界を遮らない
     499            1 :         blockViewQuery := query.ActiveFilter2[gc.GridElement, gc.BlockView](world).Query()
     500            1 :         for blockViewQuery.Next() {
     501            1 :                 entity := blockViewQuery.Entity()
     502            1 :                 grid := world.Components.GridElement.Get(entity)
     503            1 :                 index[*grid] = true
     504            1 :         }
     505            1 :         return index
     506              : }
        

Generated by: LCOV version 2.0-1