diff --git a/scripts/autoload/game_state.gd b/scripts/autoload/game_state.gd index a378c09..530e5fd 100644 --- a/scripts/autoload/game_state.gd +++ b/scripts/autoload/game_state.gd @@ -297,10 +297,48 @@ func _handle_dungeon_enter(data: Dictionary): for p in portal_list: var pid = p.get("id", p.get("Id")) portals[pid] = p + + # Prefetch mob textures early on web (mobs list is included in enter payload) + var mobs_list = data.get("mobs", data.get("Mobs", [])) + _prefetch_mob_textures_from_list(mobs_list) set_state(STATE_PLAYING) dungeon_entered.emit() +func _prefetch_mob_textures_from_list(mobs_list: Array) -> void: + if mobs_list.is_empty(): + return + if not UpdateManager or not UpdateManager._is_web: + return + + var paths: Array = [] + for mob in mobs_list: + if not (mob is Dictionary): + continue + var sprite_config = mob.get("spriteConfig", mob.get("SpriteConfig", null)) + if sprite_config == null or not (sprite_config is Dictionary): + continue + + # New format (sheets) + if sprite_config.has("sheets"): + var sheets = sprite_config.get("sheets", {}) + for sheet_key in sheets: + var sheet_info = sheets[sheet_key] + var path = sheet_info.get("path", "") + if path != "" and not paths.has(path): + paths.append(path) + continue + + # Legacy format (sprites) + var sprites = sprite_config.get("sprites", {}) + for anim_name in sprites: + var sprite_path = sprites[anim_name] + if sprite_path != "" and not paths.has(sprite_path): + paths.append(sprite_path) + + if not paths.is_empty(): + UpdateManager.prefetch_files(paths, true, false) + func _parse_tiles(tiles_string: String): dungeon.tiles = [] if tiles_string.is_empty(): diff --git a/scripts/autoload/network.gd b/scripts/autoload/network.gd index ec98f23..da511be 100644 --- a/scripts/autoload/network.gd +++ b/scripts/autoload/network.gd @@ -78,9 +78,9 @@ func connect_to_server() -> Error: socket = WebSocketPeer.new() # Increase buffer sizes for large dungeon data transfers - socket.inbound_buffer_size = 8 * 1024 * 1024 # 8MB for large state updates - socket.outbound_buffer_size = 1024 * 1024 # 1MB for outgoing messages - socket.max_queued_packets = 4096 # Handle burst traffic + socket.inbound_buffer_size = 32 * 1024 * 1024 # 32MB for large state updates (web can stall) + socket.outbound_buffer_size = 4 * 1024 * 1024 # 4MB for outgoing messages + socket.max_queued_packets = 8192 # Handle burst traffic print("[Network] Attempting connection to: ", SERVER_URL) var err = socket.connect_to_url(SERVER_URL) diff --git a/scripts/autoload/update_manager.gd b/scripts/autoload/update_manager.gd index c8b2544..5b79955 100644 --- a/scripts/autoload/update_manager.gd +++ b/scripts/autoload/update_manager.gd @@ -25,6 +25,10 @@ var _is_updating: bool = false var _files_downloaded: int = 0 var _files_total: int = 0 var _active_request: HTTPRequest = null +var _queued_files: Dictionary = {} # filePath -> true +var _pending_requests: Dictionary = {} # filePath -> priority (requested before manifest) +var _build_queue: Array = [] +var _build_queue_active: bool = false # Runtime loaded resources cache var _loaded_scenes: Dictionary = {} # filePath -> PackedScene @@ -101,22 +105,26 @@ func on_manifest_received(data: Dictionary): print("[UpdateManager] Received manifest with %d files" % _manifest.size()) _check_for_updates() + _flush_pending_requests() func _check_for_updates(): _download_queue.clear() + _queued_files.clear() for file_path in _manifest: var remote = _manifest[file_path] var local_hash = _local_hashes.get(file_path, "") if local_hash != remote.fileHash: - _download_queue.append({ + var entry = { "filePath": file_path, "cdnPath": remote.cdnPath, "fileHash": remote.fileHash, "fileSize": remote.fileSize, "isRequired": remote.isRequired - }) + } + _download_queue.append(entry) + _queued_files[file_path] = true if _download_queue.is_empty(): print("[UpdateManager] All files up to date!") @@ -143,6 +151,7 @@ func _check_for_updates(): func _download_next(): if _download_queue.is_empty(): _is_updating = false + _queued_files.clear() if _is_web: _save_local_manifest_web() _save_local_manifest() @@ -151,6 +160,7 @@ func _download_next(): return var item = _download_queue.pop_front() + _queued_files.erase(item.filePath) var url = cdn_base_url + item.cdnPath + "?h=" + item.fileHash update_progress.emit(_files_downloaded, _files_total, item.filePath) @@ -215,6 +225,70 @@ func _on_download_completed(result: int, response_code: int, _headers: PackedStr _download_next() +## Request a single file on-demand (web: useful if texture wasn't ready) +func request_file(file_path: String, priority: bool = false): + if file_path.is_empty(): + return + if _manifest.is_empty(): + print("[UpdateManager] request_file(%s) - manifest not loaded yet" % file_path) + _pending_requests[file_path] = priority + return + if not _is_web and _local_hashes.has(file_path): + return + if _queued_files.has(file_path): + return + if not _manifest.has(file_path): + print("[UpdateManager] request_file(%s) - not in manifest" % file_path) + return + + var remote = _manifest[file_path] + var entry = { + "filePath": file_path, + "cdnPath": remote.cdnPath, + "fileHash": remote.fileHash, + "fileSize": remote.fileSize, + "isRequired": remote.isRequired + } + + if priority: + _download_queue.push_front(entry) + else: + _download_queue.append(entry) + _queued_files[file_path] = true + if not _is_updating: + _files_total = _download_queue.size() + _files_downloaded = 0 + _is_updating = true + _download_next() + +func _flush_pending_requests(): + if _manifest.is_empty() or _pending_requests.is_empty(): + return + var pending = _pending_requests.duplicate() + var pending_paths = pending.keys() + _pending_requests.clear() + for file_path in pending_paths: + var priority = pending.get(file_path, false) + request_file(file_path, priority) + +## Queue heavy build work (e.g., sprite frame construction) to one per frame. +func queue_build(cb: Callable): + if cb == null: + return + _build_queue.append(cb) + if not _build_queue_active: + _build_queue_active = true + call_deferred("_process_build_queue") + +func _process_build_queue(): + if _build_queue.is_empty(): + _build_queue_active = false + return + var cb = _build_queue.pop_front() + cb.call() + # Run the next build on the next frame to avoid stalling the main thread. + call_deferred("_process_build_queue") + ## Get the cache path for a file (preserves directory structure) func _get_cache_path(file_path: String) -> String: return LOCAL_CACHE_DIR + file_path @@ -454,6 +528,7 @@ func load_texture(file_path: String) -> Texture2D: # Texture not in cache - this is normal for optional textures on web # The calling code should handle null gracefully print("[UpdateManager] load_texture(%s) - Not in memory cache (web build)" % file_path) + request_file(file_path) return null var image = Image.new() @@ -470,6 +545,9 @@ func load_texture(file_path: String) -> Texture2D: print("[UpdateManager] load_texture(%s) - Successfully created texture from buffer" % file_path) var texture = ImageTexture.create_from_image(image) _loaded_textures[file_path] = texture + if _is_web: + # Free raw bytes once the texture exists to reduce memory spikes on web. + _texture_bytes.erase(file_path) return texture ## Check if a file is in the cache (memory or disk) @@ -477,6 +555,9 @@ func has_file(file_path: String) -> bool: # Check memory cache first (works for both web and desktop) if _texture_bytes.has(file_path): return true + # Loaded textures count as cached for web (bytes may have been freed) + if _loaded_textures.has(file_path): + return true # For desktop, also check disk cache if not _is_web: @@ -485,6 +566,52 @@ func has_file(file_path: String) -> bool: return false +## Wait until all files are available (web: checks memory/loaded cache) +func wait_for_files(paths: Array) -> void: + var remaining: Dictionary = {} + for p in paths: + var file_path := str(p) + if file_path.is_empty(): + continue + if not has_file(file_path): + remaining[file_path] = true + + if remaining.is_empty(): + return + + while remaining.size() > 0: + var downloaded_path: String = await file_downloaded + if remaining.has(downloaded_path): + remaining.erase(downloaded_path) + # Clear any that may have been loaded via other paths + for key in remaining.keys(): + if has_file(key): + remaining.erase(key) + +## Prefetch a set of files (web: ensures bytes are downloaded before use) +func prefetch_files(paths: Array, priority: bool = true, wait: bool = true) -> void: + if paths.is_empty(): + return + + var missing: Array = [] + for p in paths: + var file_path := str(p) + if file_path.is_empty(): + continue + if has_file(file_path): + continue + missing.append(file_path) + + if missing.is_empty(): + return + + for file_path in missing: + request_file(file_path, priority) + + # If requested, wait only for these files + if wait: + await wait_for_files(missing) + ## Get the local cache path for a file func get_cache_path(file_path: String) -> String: return _get_cache_path(file_path) diff --git a/scripts/dungeon/dungeon_manager.gd b/scripts/dungeon/dungeon_manager.gd index d28f40d..af2ee68 100644 --- a/scripts/dungeon/dungeon_manager.gd +++ b/scripts/dungeon/dungeon_manager.gd @@ -53,6 +53,8 @@ var attack_cooldown: float = 0.5 # Default attack cooldown in seconds var _last_move_sent_time_ms: int = 0 var _last_move_vec: Vector2 = Vector2.ZERO var _last_aim_sent: float = 0.0 +var _prefetched_mob_paths: Dictionary = {} +var _mob_prefetch_in_progress: bool = false func _ready(): # Add to group for HUD to access @@ -474,6 +476,7 @@ func _on_state_updated(): if player_scene and players_container: _update_entities(players_container, GameState.players, player_scene) if mob_scene and mobs_container: + await _prefetch_mob_textures_if_needed() _update_entities(mobs_container, GameState.mobs, mob_scene) if chest_scene and chests_container: _update_entities(chests_container, GameState.chests, chest_scene) @@ -484,6 +487,61 @@ func _on_state_updated(): if loot_chest_scene and loot_chests_container: _update_loot_chests() +func _collect_mob_sprite_paths(mobs: Dictionary) -> Array: + var paths: Array = [] + for id in mobs: + var mob_data = mobs[id] + var sprite_config = mob_data.get("spriteConfig", mob_data.get("SpriteConfig", null)) + if sprite_config == null or not (sprite_config is Dictionary): + continue + + # New format (sheets) + if sprite_config.has("sheets"): + var sheets = sprite_config.get("sheets", {}) + for sheet_key in sheets: + var sheet_info = sheets[sheet_key] + var path = sheet_info.get("path", "") + if path != "" and not paths.has(path): + paths.append(path) + continue + + # Legacy format (sprites) + var sprites = sprite_config.get("sprites", {}) + for anim_name in sprites: + var sprite_path = sprites[anim_name] + if sprite_path != "" and not paths.has(sprite_path): + paths.append(sprite_path) + + return paths + +func _prefetch_mob_textures_if_needed() -> void: + if not UpdateManager or not UpdateManager._is_web: + return + if _mob_prefetch_in_progress: + return + + var paths = _collect_mob_sprite_paths(GameState.mobs) + if paths.is_empty(): + return + + var missing: Array = [] + for path in paths: + if _prefetched_mob_paths.has(path): + continue + if UpdateManager.has_file(path): + _prefetched_mob_paths[path] = true + continue + missing.append(path) + + if missing.is_empty(): + return + + _mob_prefetch_in_progress = true + await UpdateManager.prefetch_files(missing) + for path in missing: + _prefetched_mob_paths[path] = true + _mob_prefetch_in_progress = false + func _update_entities(container: Node2D, data: Dictionary, scene: PackedScene): if scene == null or container == null: return diff --git a/scripts/dungeon/mob_visual.gd b/scripts/dungeon/mob_visual.gd index 5e0c5ef..fbd6ce7 100644 --- a/scripts/dungeon/mob_visual.gd +++ b/scripts/dungeon/mob_visual.gd @@ -104,7 +104,10 @@ func update_data(data: Dictionary): if sprite_config != null and sprite_config is Dictionary and not sprite_config.is_empty(): if sprite_config != _sprite_config: _sprite_config = sprite_config - _build_animated_sprite() + if UpdateManager and UpdateManager.has_method("queue_build"): + UpdateManager.queue_build(Callable(self, "_build_animated_sprite")) + else: + _build_animated_sprite() else: _setup_fallback(data) @@ -350,14 +353,20 @@ func _on_file_downloaded(file_path: String): for sheet_key in sheets: var sheet_info = sheets[sheet_key] if sheet_info.get("path", "") == file_path: - _build_animated_sprite() + if UpdateManager and UpdateManager.has_method("queue_build"): + UpdateManager.queue_build(Callable(self, "_build_animated_sprite")) + else: + _build_animated_sprite() return # Check legacy format sprites var sprites = _sprite_config.get("sprites", {}) for anim_name in sprites: if sprites[anim_name] == file_path: - _build_animated_sprite() + if UpdateManager and UpdateManager.has_method("queue_build"): + UpdateManager.queue_build(Callable(self, "_build_animated_sprite")) + else: + _build_animated_sprite() return func _setup_fallback(data: Dictionary): diff --git a/scripts/ui/loading_screen.gd b/scripts/ui/loading_screen.gd index f542ee5..bcbb84a 100644 --- a/scripts/ui/loading_screen.gd +++ b/scripts/ui/loading_screen.gd @@ -42,6 +42,10 @@ func _on_update_completed(updated_count: int): status_label.text = "All assets up to date" file_label.text = "" + # Avoid forcing AUTH when background downloads complete while hidden. + if not visible: + return + # Wait a moment then proceed to auth screen await get_tree().create_timer(0.5).timeout GameState.set_state(0) @@ -51,6 +55,10 @@ func _on_update_failed(error: String): file_label.text = "Click to continue anyway" progress_bar.value = 0 + # Avoid forcing AUTH when background downloads fail while hidden. + if not visible: + return + # Allow continuing anyway after 2 seconds await get_tree().create_timer(2.0).timeout GameState.set_state(0)