ar骑行bug fix

This commit is contained in:
lishuo committed 2023-02-07 18:35:16 +08:00
1 parent 2c9440f656
commit 08b92e7e9b
37 files changed
+3233 -3358

No files matched your search

@@ -82,7 +82,7 @@ namespace Assets.Scripts.Scenes.VideoRide
currentHead.transform.position = vector3;
}
//控制海拔图头像
if (manager.CurrentPlayer.userId == item.UserId)
if (manager.CurrentUserId == item.UserId)
{
currentHead.transform.Find("Main").gameObject.SetActive(true);
currentHead.transform.SetAsLastSibling();
@@ -177,13 +177,13 @@ namespace Assets.Scripts.Scenes.VideoRide
//断网移除所有用户
if (list == null || list.Count == 0)
{
rideObjs.Clear();
visibleRiders.Clear();
var onlineUserList = FindObjectsOfType<AbstractVideoPlayer>();
foreach (var item in onlineUserList)
foreach (var item in visibleRiders)
{
Debug.Log($"销毁了{item}");
DestroyImmediate(item.gameObject);
}
rideObjs.Clear();
visibleRiders.Clear();
CurrentPlayer = null;
return;
}
@@ -204,7 +204,7 @@ namespace Assets.Scripts.Scenes.VideoRide
//如果当前为观察者模式且currentPlayerInfo为null随机选择以为用户观察
if (currentPlayerInfo == null)
{
currentPlayerInfo = needUpdateList.Where(c => c.UserId == currentUserId).FirstOrDefault();
currentPlayerInfo = needUpdateList.Where(c => c.UserId == CurrentUserId).FirstOrDefault();
if(currentPlayerInfo == null)
currentPlayerInfo = needUpdateList.FirstOrDefault();
}
@@ -215,10 +215,11 @@ namespace Assets.Scripts.Scenes.VideoRide
var visibleItem = visibleRiders.Where(c => c.UserId == item.UserId).FirstOrDefault();
if (visibleItem != null)
{
Debug.Log($"count {visibleRiders.Count()}");
visibleItem.SetPlayer(onlineRider.NickName, onlineRider.Speed, onlineRider.PreDistance, onlineRider.EndDistance, item.Cadence, item.HeartRate, onlineRider.WeightKg, item.UserId, onlineRider.Power, currentPlayerInfo.EndDistance, onlineRider.FrameRate.Value);
if(visibleItem.userId == currentUserId)
if (visibleItem.userId == CurrentUserId)
{
CurrentPlayer = visibleItem;
}
}
else
{
@@ -246,8 +247,10 @@ namespace Assets.Scripts.Scenes.VideoRide
visibleRiders.Add(online);
trainController.AddRider(onlineRider);
online.SetPlayer(onlineRider.NickName, onlineRider.Speed, onlineRider.PreDistance, onlineRider.EndDistance, item.Cadence, item.HeartRate, onlineRider.WeightKg, item.UserId, onlineRider.Power, currentPlayerInfo.EndDistance, onlineRider.FrameRate.Value);
if (currentPlayerInfo.UserId == item.UserId)
CurrentPlayer = online;
if (online.userId == CurrentUserId)
{
CurrentPlayer = visibleItem;
}
}
else
{
@@ -262,6 +265,7 @@ namespace Assets.Scripts.Scenes.VideoRide
videoPlayer = Instantiate(playerprefabNV, transform);
}
CurrentUserId = App.CurrentUser.Id;
CurrentPlayer = videoPlayer.GetComponent<AbstractVideoPlayer>();
var vp = videoPlayer.GetComponent<VideoPlayer>();
vp.SetEndDistance(item.EndDistance);
@@ -290,8 +294,7 @@ namespace Assets.Scripts.Scenes.VideoRide
uimanager.SetCurrentMode(aRMode);
if (_aRMode != ARMode.INSPECT)
{
//InitCurrentPlayer();
Debug.Log("ContinueAsync");
CurrentUserId = App.CurrentUser.Id;
ContinueAsync();
}
else
@@ -301,11 +304,12 @@ namespace Assets.Scripts.Scenes.VideoRide
}
public GameObject videoPlayer;
public GameObject target;
private int currentUserId { get; set; }
public int CurrentUserId { get; set; }
//切换人物
public void ChangePlayer(int userId)
{
currentUserId = userId;
Debug.Log($"切换到{userId}");
CurrentUserId = userId;
}
//获取角色头顶信息预制件
public GameObject GetHeadInfo()
+67 -33
View File
@@ -219,14 +219,14 @@ namespace Assets.Scripts.Scenes.VideoRide
}
}
bool startBtnLock = false;
public async void StartRide(BaseEventData baseEvent)
public void StartRide(BaseEventData baseEvent)
{
if (startBtnLock)
return;
startBtnLock = true;
var ui = manager.GetCanvasTransform();
InitAR();
canvasGroup.DOFade(0, 1).onComplete += () => {
InitAR();
gameObject.SetActive(false);
manager.StartGame();
manager.SetCyclingModel(Assets.Scenes.Ride.Scripts.Model.CyclingModel.Single);
@@ -236,7 +236,6 @@ namespace Assets.Scripts.Scenes.VideoRide
public async void InitAR()
{
//加载本地文件
var route = manager.mapRoute;
var arDataPath = $"{PFConstants.ARFolder}/{route.Id}/{route.Id}.json";
var videoRoute = $"{PFConstants.ARFolder}/{route.Id}/route-{route.Id}.json";
@@ -254,8 +253,8 @@ namespace Assets.Scripts.Scenes.VideoRide
public void StartRide(int seconds)
{
var ui = manager.GetCanvasTransform();
InitAR();
canvasGroup.DOFade(0, 0).onComplete += () => {
InitAR();
gameObject.SetActive(false);
manager.SetCyclingModel(CyclingModel.GameRoom);
manager.SetCurrentMode(VideoGameManager.ARMode.RIDE);
@@ -266,47 +265,64 @@ namespace Assets.Scripts.Scenes.VideoRide
},false,true);
}
private bool downloading = false;
private CancellationTokenSource cancelToken;
protected async void DownloadAsync(BaseEventData baseEvent)
{
if (downloading)
return;
beforeDownload();
await startDownloading();
}
private void beforeDownload()
{
downloading = true;
download.SetActive(false);
rideNow.enabled = false;
rideNow.interactable = false;
downloadText.text = "0%";
}
private async Task startDownloading()
{
var route = manager.mapRoute;
var path = PFConstants.VideoFolder;
var localPath = PFConstants.ARFolder;
var arDataPath = route.ARConfig;
var videoRoute = route.VideoRoute;
var cancelToken = new CancellationTokenSource();
var res1 = await UnityWebRequest.Get(arDataPath).SendWebRequest().WithCancellation(cancelToken.Token);//下载AR数据
var res2 = await UnityWebRequest.Get(videoRoute).SendWebRequest().WithCancellation(cancelToken.Token);//下载video视频数据
var res3 = await UnityWebRequest.Get(route.Url).SendWebRequest().ToUniTask(progress: this);//下载视频
//持久化到磁盘
var dataPath = $"{localPath}/{route.Id}";
Helper.CreateDirectoryIfNotExsit(dataPath);
Helper.CreateDirectoryIfNotExsit(dataPath);
File.WriteAllBytes($"{dataPath}/{route.Id}.json", res1.downloadHandler.data);
File.WriteAllBytes($"{dataPath}/route-{route.Id}.json", res2.downloadHandler.data);
File.WriteAllBytes($"{path}/{route.FileName}", res3.downloadHandler.data);
rideNow.enabled = true;
rideNow.interactable = true;
downloadText.text = App.GetLocalString("Ride Now");
var filepath = $"{path}/{route.FileName}";
manager.SetMedia(filepath);
Helper.CreateDirectoryIfNotExsit(dataPath);
Helper.CreateDirectoryIfNotExsit(dataPath);
cancelToken = new CancellationTokenSource();
await Loom.DownloadToFileAsync(arDataPath, $"{dataPath}/{route.Id}.json");
await Loom.DownloadToFileAsync(videoRoute, $"{dataPath}/route-{route.Id}.json");
var res = await Loom.DownloadToFileAsync(route.Url, $"{path}/{route.FileName}",this,cancelToken);
if (res.isDone)
{
var filepath = $"{PFConstants.VideoFolder}/{route.FileName}";
manager.SetMedia(filepath);
rideNow.enabled = true;
rideNow.interactable = true;
downloadText.text = App.GetLocalString("Ride Now");
downloading = false;
}
}
public void Report(float value)
{
if (value < 1)
{
rideNow.enabled = false;
rideNow.interactable = false;
slider.value = (float)Math.Round(value * 100, 0);
downloadText.text = slider.value.ToString() + "%";
download.SetActive(false);
}
else
{
slider.value = 100;
}
if (cancelToken.IsCancellationRequested)
return;
slider.value = value < 1 ? (float)Math.Round(value * 100, 0) : 100;
downloadText.text = slider.value.ToString() + "%";
}
//进入观察模式
private void WatchHandler(BaseEventData data)
@@ -325,7 +341,25 @@ namespace Assets.Scripts.Scenes.VideoRide
}
protected void Cancel(BaseEventData baseEvent)
{
SceneManager.LoadScene("MainScene");
if (cancelToken == null)
{
SceneManager.LoadSceneAsync("MainScene");
return;
}
UIManager.SetModalPanel(transform.Find("ModalPanel").GetComponent<PFUIPanel>());
UIManager.ShowConfirm("Tips", "CancelDownloadConfirm",
() =>
{
cancelToken?.Cancel();
SceneManager.LoadSceneAsync("MainScene");
UIManager.CloseConfirm();
},
2,
() =>
{
UIManager.CloseConfirm();
});
}
protected async void DrawMapRouteAsync(int routeId, int type = 0)
{
@@ -264,9 +264,11 @@ namespace Assets.Scripts.Scenes.VideoRide
}
private void QuitClick(BaseEventData e)
{
if (manager.CurrentPlayer != null && manager.CurrentPlayer.UserId == App.CurrentUser.Id && (manager.CurrentPlayer.ticks == 0 || manager.CurrentPlayer.EndDistance - manager.CurrentPlayer.StartDistance < 0.1f))
var idMainRider = manager.CurrentPlayer != null && manager.CurrentPlayer.UserId == App.CurrentUser.Id;
var shortDistance = idMainRider && (manager.CurrentPlayer.ticks == 0 || manager.cyclingController.recorderData.RiderDatas.Count == 0 || manager.CurrentPlayer.EndDistance - manager.CurrentPlayer.StartDistance < 0.1f);
if (shortDistance)
{
UIManager.ShowConfirm("Quit", App.GetLocalString("Current ride distance too short to save."), () => {
UIManager.ShowConfirm(App.GetLocalString("Quit"), App.GetLocalString("Current ride distance too short to save."), () => {
UIManager.CloseConfirm();
SceneManager.LoadSceneAsync("MainScene");
}, 2, () => { UIManager.CloseConfirm(); });
@@ -276,7 +278,7 @@ namespace Assets.Scripts.Scenes.VideoRide
if (manager._aRMode == VideoGameManager.ARMode.RIDE)
{
UIManager.ShowConfirm("Quit", "Do you want to keep the record?",
UIManager.ShowConfirm(App.GetLocalString("Quit"), App.GetLocalString("Do you want to keep the record?"),
() =>
{
SaveAndShowResult();
@@ -291,7 +293,7 @@ namespace Assets.Scripts.Scenes.VideoRide
}
else
{
UIManager.ShowConfirm("Quit", "Do you want to quit?", () =>
UIManager.ShowConfirm(App.GetLocalString("Quit"), App.GetLocalString("Do you want to quit?"), () =>
{
UIManager.CloseConfirm();
SceneManager.LoadSceneAsync("MainScene");
@@ -1,6 +1,7 @@
using Assets.Scenes.Ride.Scripts;
using Assets.Scripts;
using Assets.Scripts.Apis.Models;
using Cysharp.Threading.Tasks;
using PolyAndCode.UI;
using System;
using System.Collections.Generic;
@@ -31,8 +32,9 @@ class GameRoomDownLoad : MonoBehaviour
public GameObject downLoadTask;
private GameRoomListController manager;
private int RoomId { get; set; }
private string FileName { get; set; }
public int RoomId { get; set; }
public string FileName { get; set; }
public string RouteName { get; set; }
private string FileUrl { get; set; }
private void Start()
{
@@ -69,23 +71,27 @@ class GameRoomDownLoad : MonoBehaviour
private void Update()
{
if (!string.IsNullOrEmpty(FileName) && Loom.DownLoadTaskList.ContainsKey(FileName))
{
processing(Loom.DownLoadTaskList[FileName]);
}
//if (!string.IsNullOrEmpty(FileName) && Loom.DownloadStack.ContainsKey(FileName))
//{
// processing(Loom.DownloadStack[FileName]);
//}
}
public void Init(int Id,string fileName,string url, GameRoomListController gameRoomListController)
public void Init(int Id, string fileName, string url, GameRoomListController gameRoomListController, string routeName)
{
RoomId = Id;
FileName = fileName;
RouteName = routeName;
FileUrl = url;
manager = gameRoomListController;
}
public void ComeIntoStep2(string fileName)
public void ComeIntoStep2(string fileName, string routeName)
{
FileName = fileName;
RouteName = routeName;
step2.SetActive(true);
step2.transform.Find("RouteName").GetComponent<Text>().text = routeName;
step3.transform.Find("RouteName").GetComponent<Text>().text = routeName;
step3.SetActive(false);
}
@@ -103,60 +109,34 @@ class GameRoomDownLoad : MonoBehaviour
private void processing(float p)
{
downloadSlider.value = p;
if (Loom.DownLoadTaskList.ContainsKey(FileName))
if (!Loom.DownloadStack.ContainsKey(FileName) )
{
Loom.DownLoadTaskList[FileName] = p;
Loom.DownloadStack.Add(FileName, new Assets.Core.DownloadInfo(FileName, RouteName, p));
}
else
Loom.DownloadStack[FileName].Process = p;
if (p >= 1)
{
Loom.DownLoadTaskList.Add(FileName, p);
Loom.DownloadStack.Remove(FileName);
}
}
private void DownloadClick(BaseEventData baseEventData)
private async void DownloadClick(BaseEventData baseEventData)
{
var fileName = FileName;
var path = PFConstants.VideoFolder;
var filepath = path + "/" + fileName;
var url = FileUrl;
step2.SetActive(true);
step2.transform.Find("RouteName").GetComponent<Text>().text = RouteName;
//新增
var content = downLoadList.transform.Find("Viewport/Content");
var newtask = Instantiate(downLoadTask, content);
var currentTask = newtask.GetComponent<GameRoomDownloadTask>();
currentTask.Init(RoomId, fileName,gameObject);
Loom.Current.StartCoroutine(Utils.DownloadFileWithProcess(fileName, url
, path,(p, req) =>
{
currentTask.UpdateProcess(p);
processing(p);
}
, (p) =>
{
if (string.IsNullOrEmpty(p))
var filepath = PFConstants.VideoFolder + "/" + FileName;
await Loom.DownloadToFileAsync(FileUrl, filepath, Progress.Create<float>(x => {
processing(x);
if (x >= 1)
{
var process = 100f;
if (Loom.DownLoadTaskList.ContainsKey(FileName))
{
Loom.DownLoadTaskList[FileName] = process;
}
else
{
Loom.DownLoadTaskList.Add(FileName, process);
}
currentTask.UpdateProcess(process);
downloadSlider.value = process;
downloadSlider.value = 100;
step3.SetActive(true);
step3.transform.Find("RouteName").GetComponent<Text>().text = RouteName;
}
else
{
Utils.showToast(gameObject, p);
}
}
));
}));
}
}
@@ -18,32 +18,41 @@ class GameRoomDownloadTask : MonoBehaviour
private Text fileNameText;
public int RoomId { get; set; }
public string RouteName { get; set; }
public string FileName { get; set; }
private void Start()
{
UIManager.AddEvent(btn, EventTriggerType.PointerClick, (e) =>
{
modal.SetActive(true);
modal.GetComponent<GameRoomDownLoad>().ComeIntoStep2(FileName);
if (!modal.transform.parent.Find("MapList").gameObject.activeSelf)
{
modal.SetActive(true);
modal.GetComponent<GameRoomDownLoad>().ComeIntoStep2(FileName, RouteName);
}
else
{
modal.SetActive(false);
}
//transform.parent.parent.parent.gameObject.SetActive(false);
});
}
public void Init(int roomId,string fileName,GameObject downloadPanel)
public void Init(int roomId,string fileName,string routeName,GameObject downloadPanel)
{
modal = downloadPanel;
fileNameText = transform.Find("Text").GetComponent<Text>();
RoomId = roomId;
fileNameText.text = fileName;
RouteName = routeName;
fileNameText.text = routeName;
FileName = fileName;
}
private void Update()
{
if (Loom.DownLoadTaskList.ContainsKey(FileName))
if (Loom.DownloadStack.ContainsKey(FileName))
{
UpdateProcess(Loom.DownLoadTaskList[FileName]);
UpdateProcess(Loom.DownloadStack[FileName].Process);
}
}
@@ -55,11 +64,12 @@ class GameRoomDownloadTask : MonoBehaviour
done.SetActive(true);
doneTxt.SetActive(true);
icon.SetActive(false);
Loom.DownloadStack.Remove(FileName);
canvasGroup.DOFade(0, 2).onComplete += () =>
{
slider.gameObject.SetActive(false);
gameObject.Destroy();
Loom.DownLoadTaskList.Remove(FileName);
Loom.DownloadStack.Remove(FileName);
};
}
}
@@ -72,7 +72,7 @@ public class GameRoomMapItem : MonoBehaviour, IPointerExitHandler, IPointerEnter
var path = PFConstants.VideoFolder;
var filepath = path + "/" + fileName;
transform.Find("DownLoadModal").gameObject.SetActive(map.EnableAR && !File.Exists(filepath));
UIManager.AddEvent(downloadBtn, EventTriggerType.PointerClick, (e) =>
UIManager.AddEvent(downloadBtn, EventTriggerType.PointerClick, async (e) =>
{
downloadBtn.SetActive(false);
downloading.SetActive(true);
@@ -80,19 +80,12 @@ public class GameRoomMapItem : MonoBehaviour, IPointerExitHandler, IPointerEnter
slider.gameObject.SetActive(true);
var progress = Progress.Create<float>(x =>
{
Loom.DownLoadTaskList[map.FileName] = x;
Loom.DownloadStack[map.FileName].Process = x;
slider.value = x;
LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)this.slider.transform);
if (x == 1)
{
transform.Find("DownLoadModal").gameObject.SetActive(false);
}
else
{
transform.Find("DownLoadModal").gameObject.SetActive(true);
}
transform.Find("DownLoadModal").gameObject.SetActive(x!=1);
});
Loom.Download(map, progress);
await Loom.DownloadLoadARDataAndVideo(map, progress);
});
transform.Find("Name").GetComponent<Text>().text = myMap.Name;
@@ -80,7 +80,7 @@ public class GameRoomListController : PFUIPanel
private int CloseTime;
private int Members;
private GameRoomModel GameRoom;
private int RoomId;
[SerializeField]
RectTransform _rectTransform;
@@ -181,12 +181,6 @@ public class GameRoomListController : PFUIPanel
Total = roomList.GameRoomTotal;
ListChanged = true;
}
//else
//{
// list = null;
// Total = 0;
// ListChanged = true;
//}
//查询自己当前创建的房间信息并进入
var info = message.Where(c => c.RoomList != null && c.RoomList.Where(o => o.UserId == App.CurrentUser.Id && o.Status == 0).Any()).FirstOrDefault();
if (info != null)
@@ -194,11 +188,15 @@ public class GameRoomListController : PFUIPanel
GameRoom = info.RoomList[0];
App.gameRoomDetail = GameRoom;
CreateRoomSuccessed = true;
//进入房间清空列表
list = null;
Total = 0;
ListChanged = true;
}
}
catch (Exception e)
{
Debug.LogError(e);
}
}
protected override void Start()
@@ -223,7 +221,7 @@ public class GameRoomListController : PFUIPanel
MapUDPService.MessageListener = ListenerHandler;
MapUDPService.SendQueryGameRoomList(App.CurrentUser.Id, pageHelper.PageIndex, pageHelper.PageSize, seachName);
}
private List<string> fileNameList = new List<string>();
private void Update()
{
//房间已经进行骑行时间
@@ -257,7 +255,7 @@ public class GameRoomListController : PFUIPanel
}
}
#endregion
//列表改变事件
if (ListChanged)
{
Refreash();
@@ -270,25 +268,29 @@ public class GameRoomListController : PFUIPanel
CreateClicked = false;
UIManager.ShowGameRoomDetailPanel();
}
//LOOM中取数据渲染下载当前下载进度
var downLoadList = transform.Find("DownLoadList").gameObject;
var downloadPanel = transform.Find("DownloadPanel").gameObject;
if (Loom.DownLoadTaskList.Count>0)
var list = Loom.DownloadStack.Where(c => c.Value.Process < 1);
if (list.Count() > 0)
{
downLoadList.SetActive(true);
var downloadPanel = transform.Find("DownloadPanel").gameObject;
var content = downLoadList.transform.Find("Viewport/Content");
foreach (var item in Loom.DownLoadTaskList)
var currentList = FindObjectsOfType<GameRoomDownloadTask>();
foreach (var item in list)
{
var done = fileNameList.Where(c => c.Equals(item.Key)).Any();
if (!done)
var loaded = currentList.Where(c => c.FileName.Equals(item.Key)).Any();
if (!loaded)
{
fileNameList.Add(item.Key);
var newtask = Instantiate(_downLoadTask, content);
newtask.GetComponent<GameRoomDownloadTask>().Init(0, item.Key, downloadPanel);
newtask.GetComponent<GameRoomDownloadTask>().Init(0, item.Key, item.Value.DisplayName, downloadPanel);
}
downLoadList.SetActive(true);
}
}
else
{
downLoadList.SetActive(false);
}
}
private void InitStep1()
@@ -744,7 +746,7 @@ public class GameRoomListController : PFUIPanel
//查询fileUrl
GameRoom.FileUrl = ConfigHelper.GameRoomApi.GetMapVideoURL(GameRoom.MapRouteId).data;
download.SetActive(true);
download.GetComponent<GameRoomDownLoad>().Init(RoomId, GameRoom.FileName, GameRoom.FileUrl, this);
download.GetComponent<GameRoomDownLoad>().Init(RoomId, GameRoom.FileName, GameRoom.FileUrl, this, GameRoom.MapRouteName);
}
else
{
@@ -785,6 +787,7 @@ public class GameRoomListController : PFUIPanel
}
}
}
private void ShowStatusModal(Transform tr,GameRoomModel data)
{
tr.Find("Modal/Id").GetComponent<Text>().text = data.RoomId.ToString().PadLeft(7, '0');
@@ -814,7 +817,7 @@ public class GameRoomListController : PFUIPanel
UIManager.AddEvent(quit, EventTriggerType.PointerClick, (e) => { tr.gameObject.SetActive(false); });
tr.gameObject.SetActive(true);
}
private int RoomId;
public void GetInRoom()
{
@@ -837,6 +840,7 @@ public class GameRoomListController : PFUIPanel
MapUDPService.SendJoinGameRoom(App.gameRoomDetail.RoomId,App.CurrentUser.Id,UIManager.Now.GetDateTime().ToUniversalTime());
UIManager.ShowGameRoomDetailPanel();
}
public void SelectRoom(GameRoomModel room)
{
GameRoom = room;
@@ -881,6 +885,7 @@ public class GameRoomListController : PFUIPanel
tabContainer.Find("Country").GetComponent<RawImage>().texture = UIManager.Instance.loginRegOptions.GetCountryImage(map.CountryCode);
}
public void Refresh()
{
content.transform.DestroyChildren();
+18
View File
@@ -18,6 +18,7 @@ using UnityEngine.SceneManagement;
using System.Threading;
using Assets.Scripts.Devices.Ant;
using Assets.Scripts.Scenes.VideoRide;
using UnityEngine.Networking;
public class UIManager : MonoBehaviour
{
@@ -1387,4 +1388,21 @@ public class UIManager : MonoBehaviour
CloseConfirm();
}, 2);
}
//下载文件到本地
IEnumerator DownloadToFile(string url,string filePath)
{
var uwr = new UnityWebRequest(url);
uwr.method = UnityWebRequest.kHttpVerbGET;
var dh = new DownloadHandlerFile(filePath);
dh.removeFileOnAbort = true;
uwr.downloadHandler = dh;
yield return uwr.SendWebRequest();
if (uwr.isHttpError)
Debug.Log(uwr.error);
else
{
Debug.Log("Download saved to: " + filePath);
}
}
}
+33 -20
View File
@@ -1,4 +1,5 @@
using Assets.Scenes.Ride.Scripts;
using Assets.Core;
using Assets.Scenes.Ride.Scripts;
using Assets.Scripts.Apis.Models;
using Cysharp.Threading.Tasks;
using System;
@@ -7,6 +8,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
@@ -18,8 +20,6 @@ public class Loom : MonoBehaviour
public static int maxThreads = 8;
static int numThreads;
public static Dictionary<string, float> DownLoadTaskList = new Dictionary<string, float>();
private static Loom _current;
public static Loom Current
{
@@ -132,14 +132,6 @@ public class Loom : MonoBehaviour
}
}
// Use this for initialization
void Start()
{
}
List<Action> _currentActions = new List<Action>();
// Update is called once per frame
@@ -179,23 +171,44 @@ public class Loom : MonoBehaviour
}
}
public static async void Download(MapRoute route,IProgress<float> progress)
public static Dictionary<string, DownloadInfo> DownloadStack = new Dictionary<string, DownloadInfo>();
public static async Task DownloadLoadARDataAndVideo(MapRoute route,IProgress<float> progress)
{
DownLoadTaskList.Add(route.FileName, 0);
DownloadStack.Add(route.FileName, new DownloadInfo(route.FileName,route.Name,0, route.Url));
var path = PFConstants.VideoFolder;
var localPath = PFConstants.ARFolder;
var arDataPath = route.ARConfig;
var videoRoute = route.VideoRoute;
var cancelToken = new CancellationTokenSource();
var res1 = await UnityWebRequest.Get(arDataPath).SendWebRequest().WithCancellation(cancelToken.Token);//下载AR数据
var res2 = await UnityWebRequest.Get(videoRoute).SendWebRequest().WithCancellation(cancelToken.Token);//下载video视频数据
var res3 = await UnityWebRequest.Get(route.Url).SendWebRequest().ToUniTask(progress);//下载视频
var dataPath = $"{localPath}/{route.Id}";
Helper.CreateDirectoryIfNotExsit(dataPath);
Helper.CreateDirectoryIfNotExsit(dataPath);
File.WriteAllBytes($"{dataPath}/{route.Id}.json", res1.downloadHandler.data);
File.WriteAllBytes($"{dataPath}/route-{route.Id}.json", res2.downloadHandler.data);
File.WriteAllBytes($"{path}/{route.FileName}", res3.downloadHandler.data);
await Loom.DownloadToFileAsync(arDataPath, $"{dataPath}/{route.Id}.json");
await Loom.DownloadToFileAsync(videoRoute, $"{dataPath}/route-{route.Id}.json");
await Loom.DownloadToFileAsync(route.Url, $"{path}/{route.FileName}", progress, cancelToken);
}
/// <summary>
/// 下载文件到本地(持续存入磁盘减少内存占用)
/// </summary>
/// <param name="downloadUrl">文件连接</param>
/// <param name="fullPath">本地文件全路径</param>
/// <param name="progress">下载进度</param>
public static async UniTask<UnityWebRequest> DownloadToFileAsync(string downloadUrl, string fullPath, IProgress<float> progress = null, CancellationTokenSource cancellation = default(CancellationTokenSource))
{
var dh = new DownloadHandlerFile(fullPath)
{
removeFileOnAbort = true
};
var request = UnityWebRequest.Get(downloadUrl);
request.method = UnityWebRequest.kHttpVerbGET;
request.downloadHandler = dh;
return await request.SendWebRequest().ToUniTask(progress, PlayerLoopTiming.Update, (cancellation?.Token ?? default(CancellationToken)));
}
}