296 lines
7.4 KiB
GDScript
296 lines
7.4 KiB
GDScript
extends Node
|
|
## Music autoload - fetches BGM config from the server and plays context-appropriate tracks.
|
|
##
|
|
## Scene routing:
|
|
## - GameScreen -> Game
|
|
## - FreePlay / LobbyRoom -> Lobby
|
|
## - Everything else -> Menu
|
|
##
|
|
## Volume and mute are controlled via Settings.music_volume / Settings.music_muted.
|
|
## This node streams audio via AudioStreamPlayers on the "Music" bus.
|
|
|
|
const CROSSFADE_DURATION := 1.2
|
|
const CONTEXT_AUDIO_MSG := "content.get_audio_config"
|
|
|
|
const CONTEXT_MENU := "Menu"
|
|
const CONTEXT_LOBBY := "Lobby"
|
|
const CONTEXT_GAME := "Game"
|
|
|
|
const LOBBY_SCENES := {
|
|
"res://scenes/free_play/FreePlayScreen.tscn": true,
|
|
"res://scenes/free_play/LobbyRoomScreen.tscn": true,
|
|
}
|
|
|
|
const GAME_SCENES := {
|
|
"res://scenes/game/GameScreen.tscn": true,
|
|
}
|
|
|
|
var _tracks: Dictionary = {}
|
|
var _stream_cache: Dictionary = {}
|
|
var _current_context: String = ""
|
|
var _current_url: String = ""
|
|
var _desired_context: String = ""
|
|
var _last_scene_path: String = ""
|
|
var _config_loaded: bool = false
|
|
var _request_serial: int = 0
|
|
|
|
var _player_a: AudioStreamPlayer
|
|
var _player_b: AudioStreamPlayer
|
|
var _active_player: AudioStreamPlayer
|
|
var _fade_tween: Tween = null
|
|
|
|
|
|
func _ready() -> void:
|
|
_player_a = _make_player()
|
|
_player_b = _make_player()
|
|
_active_player = _player_a
|
|
|
|
Auth.auth_success.connect(_on_auth_success)
|
|
Auth.session_expired.connect(_on_session_expired)
|
|
Settings.settings_changed.connect(_sync_player_volumes)
|
|
|
|
set_process(true)
|
|
|
|
|
|
func _process(_delta: float) -> void:
|
|
var scene := get_tree().current_scene
|
|
if scene == null:
|
|
return
|
|
|
|
var scene_path := scene.scene_file_path
|
|
if scene_path == _last_scene_path:
|
|
return
|
|
|
|
_last_scene_path = scene_path
|
|
var next_context := _context_for_scene(scene_path)
|
|
if next_context.is_empty():
|
|
stop()
|
|
else:
|
|
play_context(next_context)
|
|
|
|
|
|
func _make_player() -> AudioStreamPlayer:
|
|
var player := AudioStreamPlayer.new()
|
|
player.bus = Settings.BUS_MUSIC
|
|
player.volume_db = _target_volume_db()
|
|
add_child(player)
|
|
return player
|
|
|
|
|
|
func fetch_config() -> void:
|
|
Network.request(CONTEXT_AUDIO_MSG, {},
|
|
func(_type: String, resp: Variant) -> void:
|
|
var data := resp as Dictionary
|
|
_tracks.clear()
|
|
for entry: Dictionary in data.get("tracks", []):
|
|
var context := str(entry.get("context", "")).strip_edges()
|
|
var url := str(entry.get("trackCdnUrl", "")).strip_edges()
|
|
if context.is_empty() or url.is_empty():
|
|
continue
|
|
if not _tracks.has(context):
|
|
_tracks[context] = []
|
|
_tracks[context].append({
|
|
"name": str(entry.get("trackName", "")),
|
|
"url": url,
|
|
})
|
|
|
|
_config_loaded = true
|
|
_apply_desired_context(),
|
|
func(code: String, msg: String) -> void:
|
|
_config_loaded = false
|
|
push_warning("Music: fetch_config failed - %s: %s" % [code, msg]))
|
|
|
|
|
|
func play_context(context: String) -> void:
|
|
_desired_context = context
|
|
_apply_desired_context()
|
|
|
|
|
|
func stop() -> void:
|
|
_desired_context = ""
|
|
_current_context = ""
|
|
_current_url = ""
|
|
_request_serial += 1
|
|
_stop_inactive_player()
|
|
_fade_out(_active_player)
|
|
|
|
|
|
func _apply_desired_context() -> void:
|
|
if _desired_context.is_empty():
|
|
return
|
|
if not _config_loaded:
|
|
return
|
|
if _desired_context == _current_context and not _current_url.is_empty() and _active_player.playing:
|
|
_sync_player_volumes()
|
|
return
|
|
|
|
var options: Array = _tracks.get(_desired_context, [])
|
|
if options.is_empty():
|
|
stop()
|
|
return
|
|
|
|
var entry: Dictionary = options[randi() % options.size()]
|
|
var url := str(entry.get("url", ""))
|
|
if url.is_empty():
|
|
stop()
|
|
return
|
|
if url == _current_url and _active_player.playing:
|
|
_current_context = _desired_context
|
|
_sync_player_volumes()
|
|
return
|
|
|
|
_request_serial += 1
|
|
var serial := _request_serial
|
|
_crossfade_to(url, _desired_context, serial)
|
|
|
|
|
|
func _crossfade_to(url: String, context: String, serial: int) -> void:
|
|
var next: AudioStreamPlayer = _player_b if _active_player == _player_a else _player_a
|
|
var stream := await _load_stream(url)
|
|
if serial != _request_serial:
|
|
return
|
|
if stream == null:
|
|
return
|
|
|
|
if _fade_tween != null:
|
|
_fade_tween.kill()
|
|
_fade_tween = null
|
|
|
|
next.stream = stream
|
|
next.volume_db = -80.0
|
|
next.play()
|
|
|
|
_fade_tween = create_tween().set_parallel(true)
|
|
_fade_tween.tween_property(next, "volume_db", _target_volume_db(), CROSSFADE_DURATION)
|
|
_fade_tween.tween_property(_active_player, "volume_db", -80.0, CROSSFADE_DURATION)
|
|
await _fade_tween.finished
|
|
|
|
if serial != _request_serial:
|
|
return
|
|
|
|
_active_player.stop()
|
|
_active_player = next
|
|
_current_context = context
|
|
_current_url = url
|
|
_fade_tween = null
|
|
_stop_inactive_player()
|
|
_sync_player_volumes()
|
|
|
|
|
|
func _fade_out(player: AudioStreamPlayer) -> void:
|
|
if player == null or not player.playing:
|
|
return
|
|
|
|
if _fade_tween != null:
|
|
_fade_tween.kill()
|
|
_fade_tween = null
|
|
|
|
_fade_tween = create_tween()
|
|
_fade_tween.tween_property(player, "volume_db", -80.0, CROSSFADE_DURATION)
|
|
await _fade_tween.finished
|
|
if player == _active_player and _request_serial >= 0:
|
|
player.stop()
|
|
player.stream = null
|
|
_fade_tween = null
|
|
|
|
|
|
func _stop_inactive_player() -> void:
|
|
var inactive: AudioStreamPlayer = _player_b if _active_player == _player_a else _player_a
|
|
inactive.stop()
|
|
inactive.stream = null
|
|
inactive.volume_db = -80.0
|
|
|
|
|
|
func _sync_player_volumes() -> void:
|
|
var target_db := _target_volume_db()
|
|
if _fade_tween != null:
|
|
if _active_player.playing:
|
|
_active_player.volume_db = target_db
|
|
return
|
|
|
|
if _active_player.playing:
|
|
_active_player.volume_db = target_db
|
|
var inactive: AudioStreamPlayer = _player_b if _active_player == _player_a else _player_a
|
|
if not inactive.playing:
|
|
inactive.volume_db = -80.0
|
|
|
|
|
|
func _target_volume_db() -> float:
|
|
if Settings.music_muted or Settings.music_volume <= 0.0:
|
|
return -80.0
|
|
return linear_to_db(Settings.music_volume)
|
|
|
|
|
|
func _context_for_scene(scene_path: String) -> String:
|
|
if scene_path.is_empty():
|
|
return ""
|
|
if GAME_SCENES.has(scene_path):
|
|
return CONTEXT_GAME
|
|
if LOBBY_SCENES.has(scene_path):
|
|
return CONTEXT_LOBBY
|
|
return CONTEXT_MENU
|
|
|
|
|
|
func _on_auth_success(_user_id: String, _display_name: String) -> void:
|
|
fetch_config()
|
|
|
|
|
|
func _on_session_expired() -> void:
|
|
_tracks.clear()
|
|
_stream_cache.clear()
|
|
_config_loaded = false
|
|
_last_scene_path = ""
|
|
stop()
|
|
|
|
|
|
func _load_stream(url: String) -> AudioStream:
|
|
if _stream_cache.has(url):
|
|
return _stream_cache[url] as AudioStream
|
|
|
|
var stream: AudioStream = null
|
|
if url.begins_with("res://") or url.begins_with("user://"):
|
|
stream = load(url) as AudioStream
|
|
else:
|
|
stream = await _load_remote_stream(url)
|
|
|
|
if stream != null:
|
|
_stream_cache[url] = stream
|
|
return stream
|
|
|
|
|
|
func _load_remote_stream(url: String) -> AudioStream:
|
|
var request_url := _normalize_remote_url(url)
|
|
var http := HTTPRequest.new()
|
|
add_child(http)
|
|
var err := http.request(request_url)
|
|
if err != OK:
|
|
http.queue_free()
|
|
push_warning("Music: request failed for %s (err %d)" % [request_url, err])
|
|
return null
|
|
|
|
var result: Array = await http.request_completed
|
|
http.queue_free()
|
|
|
|
var response_code: int = int(result[1])
|
|
var body: PackedByteArray = result[3]
|
|
if response_code != 200 or body.is_empty():
|
|
push_warning("Music: failed to download %s (HTTP %d)" % [url, response_code])
|
|
return null
|
|
|
|
var ext := url.get_extension().to_lower()
|
|
if ext == "ogg":
|
|
return AudioStreamOggVorbis.load_from_buffer(body)
|
|
if ext == "mp3":
|
|
var mp3 := AudioStreamMP3.new()
|
|
mp3.data = body
|
|
return mp3
|
|
if ext == "wav":
|
|
return AudioStreamWAV.load_from_buffer(body)
|
|
|
|
push_warning("Music: unsupported format '%s'" % ext)
|
|
return null
|
|
|
|
|
|
func _normalize_remote_url(url: String) -> String:
|
|
return url.replace(" ", "%20")
|