TableTower/ui/card_refresh_queue.gd

95 lines
2.6 KiB
GDScript3
Raw Normal View History

class_name CardRefreshQueue
extends RefCounted
## Rebuilds cards after a switch between Play and Build without stopping the
## app: cards in view at once, the rest a few per frame, the ones that have
## come into view first. Until its turn, a card out of view keeps its old
## layout. Cards are held by id, so a deleted card just drops out.
## How long one frame may spend on waiting cards (at least one is rebuilt).
const FRAME_USEC := 6000
## While cards wait, threads redraw in the first frames after a switch (the
## cards in view settle) and then only every so many frames.
const SETTLE_FRAMES := 4
const REDRAW_EVERY := 12
var m: Main
## FRAME_USEC; tests raise it so they don't depend on the machine's speed.
var frame_usec := FRAME_USEC
## Waiting card ids (id -> true). TableCard.rebuild takes its card out.
var _waiting: Dictionary = {}
var _frames_since_switch := 0
func _init(p_main: Main) -> void:
m = p_main
## Rebuilds every card: now when it's in view, soon when it isn't.
func rebuild_all() -> void:
var view := m.board.view_rect()
_waiting.clear()
_frames_since_switch = 0
for tid: String in m.cards:
var card: TableCard = m.cards[tid]
if _in_view(card, view):
card.rebuild()
else:
_waiting[tid] = true
## Rebuilds the card now if it was waiting.
func ensure(tid: String) -> void:
if _waiting.has(tid) and m.cards.has(tid):
(m.cards[tid] as TableCard).rebuild()
func forget(tid: String) -> void:
_waiting.erase(tid)
func is_waiting(tid: String) -> bool:
return _waiting.has(tid)
func is_idle() -> bool:
return _waiting.is_empty()
## Rebuilds everything still waiting.
func finish() -> void:
for tid: String in _waiting.keys():
ensure(tid)
_waiting.clear()
## True when a redraw of the threads can wait: only cards out of view are
## changing (nothing is being dragged) and more of them are to come.
func holds_redraw() -> bool:
return not _waiting.is_empty() and _frames_since_switch > SETTLE_FRAMES \
and _frames_since_switch % REDRAW_EVERY != 0 and not Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT)
## Called every frame.
func step() -> void:
if _waiting.is_empty():
return
_frames_since_switch += 1
var view := m.board.view_rect()
var later: Array[String] = []
var started := Time.get_ticks_usec()
for tid: String in _waiting.keys():
if not m.cards.has(tid):
_waiting.erase(tid)
elif _in_view(m.cards[tid], view):
ensure(tid)
else:
later.append(tid)
for tid in later:
if Time.get_ticks_usec() - started >= frame_usec:
return
ensure(tid)
func _in_view(card: TableCard, view: Rect2) -> bool:
return card.visible and view.intersects(Rect2(card.position, card.size).grow(TableCard.INLET_Y))