hch
2025-12-31 4debfee66e8d8aabd179e2f8a61c7ca5ce62af3d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
using UnityEngine;
using System;
using System.Collections.Generic;
using Spine.Unity;
 
public class BattlePreloadManager
{
    private BattleCacheManager cacheManager = new BattleCacheManager();
    private BattleUnloadManager unloadManager = new BattleUnloadManager();
    
    private bool isLoading = false;
    
    public BattleCacheManager CacheManager => cacheManager;
    public BattleUnloadManager UnloadManager => unloadManager;
    
    /// <summary>
    /// 预加载战斗资源
    /// </summary>
    public void PreloadBattleResources(string battleGuid, List<TeamBase> redTeamList, List<TeamBase> blueTeamList, 
        Action<float> progressCallback, Action completeCallback)
    {
        if (isLoading)
        {
            Debug.LogWarning("BattlePreloadManager: Already loading, ignoring request");
            return;
        }
        
        isLoading = true;
        
        var redTeamInfo = AnalyzeTeamList(redTeamList, true);
        var blueTeamInfo = AnalyzeTeamList(blueTeamList, false);
        
        // ===== 合并红蓝队资源,统一注册 =====
        var allSpineResources = new List<BattleResCache.ResourceIdentifier>();
        var allAudioResources = new List<BattleResCache.ResourceIdentifier>();
        
        allSpineResources.AddRange(redTeamInfo.SpineResources);
        allSpineResources.AddRange(blueTeamInfo.SpineResources);
        allAudioResources.AddRange(redTeamInfo.AudioResources);
        allAudioResources.AddRange(blueTeamInfo.AudioResources);
 
        // 检查是否为同一战场的重复注册(比如队伍变更)——如果红队发生变更,需要强制卸载之前的常驻资源
        if (cacheManager.HasBattleRegistered(battleGuid))
        {
            var existingRedOwners = cacheManager.GetRegisteredOwners(battleGuid, true); // 只比较常驻(红队)
            var newRedOwners = new HashSet<string>();
            foreach (var r in redTeamInfo.SpineResources) if (!string.IsNullOrEmpty(r.OwnerId)) newRedOwners.Add(r.OwnerId);
            foreach (var r in redTeamInfo.AudioResources) if (!string.IsNullOrEmpty(r.OwnerId)) newRedOwners.Add(r.OwnerId);
 
            bool different = false;
            if (existingRedOwners.Count != newRedOwners.Count) different = true;
            else
            {
                foreach (var o in existingRedOwners) if (!newRedOwners.Contains(o)) { different = true; break; }
            }
 
            if (different)
            {
                // 计算哪些 Owner 被移除,只卸载这些 Owner 引用对应的资源以提高性能
                var removedOwners = new HashSet<string>(existingRedOwners);
                removedOwners.ExceptWith(newRedOwners);
 
                if (removedOwners.Count > 0)
                {
                    Debug.Log($"BattlePreloadManager: Detected red-team change for {battleGuid}. Removed owners: {removedOwners.Count}. Unloading affected resources only.");
                    cacheManager.UnregisterBattlefieldOwners(battleGuid, removedOwners);
                }
                else
                {
                    Debug.Log($"BattlePreloadManager: Detected red-team change for {battleGuid}, but no owners were removed (only additions). No unload necessary.");
                }
            }
        }
        
        cacheManager.RegisterBattlefieldResources(battleGuid, allSpineResources, allAudioResources);
        
        StartPreload(allSpineResources, allAudioResources, battleGuid, progressCallback, () =>
        {
            isLoading = false;
            completeCallback?.Invoke();
        });
    }
    
    private TeamResTracker.TeamResourceInfo AnalyzeTeamList(List<TeamBase> teamList, bool isPersistent)
    {
        var combinedInfo = new TeamResTracker.TeamResourceInfo();
        
        if (teamList == null || teamList.Count == 0)
        {
            return combinedInfo;
        }
        
        foreach (var team in teamList)
        {
            if (team == null)
                continue;
                
            var teamInfo = TeamResTracker.AnalyzeTeam(team, isPersistent);
            MergeResourceInfo(combinedInfo, teamInfo);
        }
        
        return combinedInfo;
    }
    
    private void MergeResourceInfo(TeamResTracker.TeamResourceInfo target, TeamResTracker.TeamResourceInfo source)
    {
        // 合并Spine资源(去重)
        foreach (var res in source.SpineResources)
        {
            if (!ContainsResource(target.SpineResources, res))
            {
                target.SpineResources.Add(res);
            }
        }
        
        // 合并音频资源(去重)
        foreach (var res in source.AudioResources)
        {
            if (!ContainsResource(target.AudioResources, res))
            {
                target.AudioResources.Add(res);
            }
        }
    }
    
    private bool ContainsResource(List<BattleResCache.ResourceIdentifier> list, BattleResCache.ResourceIdentifier resource)
    {
        foreach (var item in list)
        {
            if (item.GetKey() == resource.GetKey())
            {
                return true;
            }
        }
        return false;
    }
    
    private void StartPreload(List<BattleResCache.ResourceIdentifier> spineResources,
        List<BattleResCache.ResourceIdentifier> audioResources,
        string battleGuid,
        Action<float> progressCallback, Action completeCallback)
    {
        int totalResources = spineResources.Count + audioResources.Count;
        
        if (totalResources == 0)
        {
            Debug.Log("BattlePreloadManager: No resources to preload");
            completeCallback?.Invoke();
            return;
        }
        
        Debug.Log($"BattlePreloadManager: Preloading {totalResources} resources for battlefield {battleGuid}");
        Debug.Log($"  Spine={spineResources.Count}, Audio={audioResources.Count}");
        
        int loadedCount = 0;
        
        Action onSingleComplete = () =>
        {
            loadedCount++;
            float progress = (float)loadedCount / totalResources;
            progressCallback?.Invoke(progress);
            
            if (loadedCount >= totalResources)
            {
                Debug.Log($"BattlePreloadManager: Completed! {cacheManager.GetCacheStats(battleGuid)}");
                completeCallback?.Invoke();
            }
        };
        
        // 异步加载所有Spine资源
        foreach (var identifier in spineResources)
        {
            LoadSpineAsync(identifier, battleGuid, onSingleComplete);
        }
        
        // 异步加载所有Audio资源
        foreach (var identifier in audioResources)
        {
            LoadAudioAsync(identifier, battleGuid, onSingleComplete);
        }
    }
    
    private void LoadSpineAsync(BattleResCache.ResourceIdentifier identifier, string battleGuid, Action onComplete)
    {
        string key = identifier.GetKey();
        
        ResManager.Instance.LoadAssetAsync<SkeletonDataAsset>(
            identifier.Directory,
            identifier.AssetName,
            (success, asset) =>
            {
                if (success && asset != null)
                {
                    var skeletonData = asset as SkeletonDataAsset;
                    if (skeletonData != null)
                    {
                        var cachedRes = new BattleResCache.CachedResource(identifier, skeletonData, false);
                        cacheManager.UpdateResourceReference(key, cachedRes, battleGuid, identifier.OwnerId);
                        Debug.Log($"BattlePreloadManager: Loaded spine: {key}");
                    }
                }
                else
                {
                    Debug.LogError($"BattlePreloadManager: Failed to load spine: {key}");
                }
                onComplete?.Invoke();
            }
        );
    }
    
    private void LoadAudioAsync(BattleResCache.ResourceIdentifier identifier, string battleGuid, Action onComplete)
    {
        string key = identifier.GetKey();
        
        ResManager.Instance.LoadAssetAsync<AudioClip>(
            identifier.Directory,
            identifier.AssetName,
            (success, asset) =>
            {
                if (success && asset != null)
                {
                    var audioClip = asset as AudioClip;
                    if (audioClip != null)
                    {
                        var cachedRes = new BattleResCache.CachedResource(identifier, audioClip, false);
                        cacheManager.UpdateResourceReference(key, cachedRes, battleGuid, identifier.OwnerId);
                        Debug.Log($"BattlePreloadManager: Loaded audio: {key}");
                    }
                }
                else
                {
                    Debug.LogError($"BattlePreloadManager: Failed to load audio: {key}");
                }
                onComplete?.Invoke();
            },
            false  // needExt = false
        );
    }
}