PlayerController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using Assets.Scripts.Models;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Threading;
  8. using UnityEngine;
  9. using UnityEngine.SceneManagement;
  10. using UnityEngine.UI;
  11. public class PlayerController : MonoBehaviour
  12. {
  13. public static PlayerController instance;
  14. public Dictionary<uint, List<Structure>> Workers = new Dictionary<uint, List<Structure>>();
  15. public List<Structure> TestStructures = new List<Structure>();
  16. public GameObject WorkersList; // scroll content
  17. public GameObject DateTimePanel;
  18. public GameObject StartHour;
  19. public GameObject StartMin;
  20. public GameObject StartSec;
  21. public GameObject EndHour;
  22. public GameObject EndMin;
  23. public GameObject EndSec;
  24. public GameObject StartStopButton;
  25. public LocationZones locationZones;
  26. public Dropdown DropdownMode;
  27. public Toggle ToggleAllUsers; // отображение всех маркеров пользователей
  28. public Toggle ToggleLine;
  29. public Toggle ToggleDisappearance;
  30. public GameObject DatePicker;
  31. Camera camera;
  32. public GameObject UserInfo;
  33. public GameObject Editor;
  34. public uint? user_broadcast = null;
  35. public bool broadcast = false;
  36. public Dictionary<uint, User> users;
  37. public enum Mode { RealTime = 0, History = 1, Stop = 2 };
  38. public static Mode active_mode = Mode.Stop;
  39. int mode = 0;
  40. Client client;
  41. CompanyController company;
  42. EditorController editor;
  43. DateTimePicker Date;
  44. public Dictionary<uint, bool> end_send = new Dictionary<uint, bool>(); // флаги завершения загрузки
  45. Dictionary<uint, MarkerMoving> moving = new Dictionary<uint, MarkerMoving>(); // флаги начала движения
  46. const float INTERPOLATION_PERIOD = 0.1f;
  47. float time_draw = 0;
  48. public bool users_load = false;
  49. public bool beacons_load = false;
  50. //List<bool> StartStop = new List<bool>();
  51. private void Awake()
  52. {
  53. instance = this;
  54. }
  55. // Start is called before the first frame update
  56. void Start()
  57. {
  58. DebugHelper.ActivateConsole();
  59. client = Client.instance;
  60. company = CompanyController.instance;
  61. editor = Editor.GetComponent<EditorController>();
  62. camera = Camera.main;
  63. //users = new Dictionary<uint, User>();
  64. Date = DatePicker.GetComponent<DateTimePicker>();
  65. //Client.LocationsRequest();
  66. var broadcast_stop = UserInfo.transform.GetChild(1).GetChild(1).GetComponent<Button>();
  67. broadcast_stop.onClick.AddListener(() => BroadcastStop());
  68. ToggleAllUsers = GameObject.Find("ToggleAllUsers").GetComponent<Toggle>();
  69. ToggleAllUsers.onValueChanged.AddListener(delegate {
  70. foreach (var u in users.Values)
  71. u.toggle.isOn = ToggleAllUsers.isOn;
  72. });
  73. }
  74. // Update is called once per frame
  75. void Update()
  76. {
  77. if (DropdownMode.value != mode)
  78. СhangeMode();
  79. time_draw += Time.deltaTime;
  80. if (time_draw >= INTERPOLATION_PERIOD)
  81. {
  82. MarkerMove();
  83. time_draw -= INTERPOLATION_PERIOD;
  84. }
  85. if (users != null)
  86. {
  87. if (ToggleLine.isOn)
  88. {
  89. foreach (var u in users)
  90. u.Value.marker_line.gameObject.SetActive(true);
  91. ToggleDisappearance.interactable = true;
  92. }
  93. else
  94. {
  95. foreach (var u in users)
  96. {
  97. u.Value.marker_line.gameObject.SetActive(false);
  98. u.Value.marker_line.positionCount = 0;
  99. }
  100. ToggleDisappearance.interactable = false;
  101. }
  102. if (users_load)
  103. {
  104. users_load = false;
  105. foreach (var u in users.OrderBy(u => u.Value.id))
  106. {
  107. u.Value.SetParam(BroadcastStart);
  108. if (DropdownMode.value == 0) u.Value.toggle_user.SetActive(u.Value.online);
  109. else u.Value.toggle_user.SetActive(true);
  110. }
  111. }
  112. }
  113. }
  114. /// <summary>
  115. /// Смена положения маркера
  116. /// </summary>
  117. /// <param name="step">Шаг до нового положения</param>
  118. /// <param name="start_pos">Начальное положение</param>
  119. /// <param name="end_pos">Финальное положение</param>
  120. /// <param name="user">Маркер сотрудника</param>
  121. /// <param name="w">Данные из БД</param>
  122. /// <param name="progress">Номер записи из БД</param>
  123. /// <returns></returns>
  124. void Position(float step, Vector3 start_pos, Vector3 end_pos, User user, Structure w, string progress)
  125. {
  126. Debug.LogWarning($"move user {user.id} {end_pos} {w.ts} {w.zone_id}");
  127. if (user.marker.activeSelf == true)
  128. {
  129. var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step);
  130. var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step);
  131. //Debug.Log($"marker name={worker_marker.name} time={pause} step={step} sec x={x_position} y={y_position} x0={start_pos.x} y0={start_pos.z} x1={end_pos.x} y1={end_pos.z}");
  132. var new_position = new Vector3(x_position, 0.5f, y_position);
  133. if (user.marker.transform.position != new_position)
  134. {
  135. user.marker.transform.position = new Vector3(x_position, 0.5f, y_position);
  136. user.marker_line.SetPosition(user.marker_line.positionCount++, new Vector3(x_position, 0, y_position));
  137. if (ToggleDisappearance.isOn) user.marker_line = LineDisappearance(user.marker_line);
  138. }
  139. user.marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}";
  140. user.toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{w.acc_id} {w.ts:HH:mm:ss}{progress}";
  141. }
  142. }
  143. /// <summary>
  144. /// Запуск отрисовки
  145. /// </summary>
  146. public void ButtonStart()
  147. {
  148. if (active_mode == Mode.Stop)
  149. foreach (var u in users)
  150. u.Value.marker_line.positionCount = 0;
  151. var button_text = StartStopButton.transform.GetChild(0);
  152. switch (DropdownMode.value)
  153. {
  154. case 0:
  155. //real_time = !real_time;
  156. if (active_mode == Mode.Stop/*real_time*/)
  157. {
  158. active_mode = Mode.RealTime;
  159. button_text.GetComponent<Text>().text = "Остановить";
  160. }
  161. else
  162. {
  163. active_mode = Mode.Stop;
  164. button_text.GetComponent<Text>().text = "Отобразить";
  165. }
  166. break;
  167. case 1:
  168. if (active_mode == Mode.Stop/*real_time*/) active_mode = Mode.History;
  169. else active_mode = Mode.Stop;
  170. if (active_mode == Mode.History/*history_start*/)
  171. {
  172. var date = Date.Date;
  173. var time_start = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
  174. time_start = time_start.AddHours(int.Parse(StartHour.GetComponent<InputField>().text));
  175. time_start = time_start.AddMinutes(int.Parse(StartMin.GetComponent<InputField>().text));
  176. time_start = time_start.AddSeconds(int.Parse(StartSec.GetComponent<InputField>().text));
  177. Debug.Log(time_start);
  178. var time_end = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
  179. time_end = time_end.AddHours(int.Parse(EndHour.GetComponent<InputField>().text));
  180. time_end = time_end.AddMinutes(int.Parse(EndMin.GetComponent<InputField>().text));
  181. time_end = time_end.AddSeconds(int.Parse(EndSec.GetComponent<InputField>().text));
  182. foreach (var u in users)
  183. {
  184. if (u.Value.toggle.isOn)
  185. {
  186. client.CoordinatesRequest(time_start.Ticks, time_end.Ticks, 1, company.locations_index[company.active_location], u.Value.id);
  187. end_send[u.Value.id] = false;
  188. }
  189. }
  190. button_text.GetComponent<Text>().text = "Остановить";
  191. }
  192. else
  193. {
  194. StopProgress();
  195. }
  196. break;
  197. }
  198. }
  199. public void StopProgress()
  200. {
  201. StartStopButton.transform.GetChild(0).GetComponent<Text>().text = "Отобразить";
  202. active_mode = Mode.Stop;
  203. if(users != null)
  204. foreach (var u in users)
  205. {
  206. end_send[u.Value.id] = false;
  207. moving.Remove(u.Value.id);
  208. }
  209. }
  210. /// <summary>
  211. /// Затухание траектории
  212. /// </summary>
  213. /// <param name="lineRenderer">Траектория</param>
  214. /// <returns></returns>
  215. LineRenderer LineDisappearance(LineRenderer lineRenderer)
  216. {
  217. //LineRenderer lineRenderer = GetComponent<LineRenderer>();
  218. int newPositionCount = lineRenderer.positionCount - 1;
  219. Vector3[] newPositions = new Vector3[newPositionCount];
  220. for (int i = 0; i < newPositionCount; i++)
  221. {
  222. newPositions[i] = lineRenderer.GetPosition(i + 1);
  223. }
  224. lineRenderer.SetPositions(newPositions);
  225. return lineRenderer;
  226. }
  227. /// <summary>
  228. /// Смена положения по интервалу
  229. /// Шаги для плавного перемещения
  230. /// </summary>
  231. /// <param name="u">Данные о маркере</param>
  232. void StartingAccPositiong(User u)
  233. {
  234. int i = 0;
  235. float step = 0.1f;
  236. if (moving.ContainsKey(u.id))
  237. {
  238. if (moving[u.id].index < Workers[u.id].Count) i = moving[u.id].index;
  239. if (moving[u.id].step < 1.1f) step = moving[u.id].step;
  240. }
  241. else moving[u.id] = new MarkerMoving();
  242. var worker = Workers[u.id];
  243. Debug.LogWarning($"worker coord count {u.id} {worker.Count}");
  244. if (active_mode == Mode.RealTime) worker = worker.OrderBy(wr => wr.ts).ToList();
  245. if (worker.Any())
  246. {
  247. var w = worker[i];
  248. locationZones.UserPosition(u, w);
  249. var start_pos = u.marker.transform.position;
  250. if (i != 0) start_pos = new Vector3(worker[i - 1].coord_x, 0.5f, worker[i - 1].coord_y);
  251. if (active_mode == Mode.History && i == 0) start_pos = new Vector3(w.coord_x, 0.5f, w.coord_y);
  252. var end_pos = new Vector3(w.coord_x, 0.5f, w.coord_y);
  253. var progress = "";
  254. if (active_mode == Mode.History) progress = $"\n{i + 1} из {Workers[u.id].Count}";
  255. //if (starting)
  256. Position(step, start_pos, end_pos, u, w, progress);
  257. // StartingAccPositiong(m.value, time_step);
  258. }
  259. step += INTERPOLATION_PERIOD; // 0.1f;
  260. moving[u.id].step = step;
  261. if (Math.Round(step, 1) > 1)
  262. {
  263. Debug.Log($"step:{step}");
  264. i++;
  265. moving[u.id].index = i;
  266. }
  267. if (active_mode == Mode.RealTime)
  268. if (Math.Round(step, 1) > 1)
  269. {
  270. Debug.Log($"Mode.RealTime step:{step}");
  271. Workers.Remove(u.id);
  272. Debug.LogWarning($"clear coord user {u.id}");
  273. }
  274. if (active_mode == Mode.History)
  275. if (i == Workers[u.id].Count)
  276. {
  277. //StopProgress();
  278. Workers.Remove(u.id);
  279. }
  280. }
  281. /// <summary>
  282. /// Отображение маяков
  283. /// </summary>
  284. /// <param name="b"></param>
  285. //public static void AddBeacon(Beacon b)
  286. //{
  287. // var beacon = Instantiate(Resources.Load("GameObjects/Beacon", typeof(GameObject))) as GameObject;
  288. // beacon.transform.position = new Vector3(b.x, 0.5f, b.y);
  289. // beacon.name = $"BeaconButton_{b.id}";
  290. // beacon.GetComponent<BeaconController>().info = false;
  291. // beacon.transform.SetParent(GameObject.Find("Beacons").transform);
  292. // beacon.transform.GetChild(0).GetChild(0).GetChild(0).GetComponent<Text>().text = $"{b.id}\nuuid={b.uuid}\nmajor={b.major}\nminor={b.minor}";
  293. // b.beacon = beacon;
  294. //}
  295. /// <summary>
  296. /// Остановка отрисовки при смене режима история/онлайн
  297. /// </summary>
  298. public void СhangeMode()
  299. {
  300. StopProgress();
  301. active_mode = Mode.Stop;
  302. mode = DropdownMode.value;
  303. switch (DropdownMode.value)
  304. {
  305. case 0:
  306. DateTimePanel.SetActive(false);
  307. if(users != null)
  308. foreach(var u in users)
  309. u.Value.toggle_user.SetActive(u.Value.online);
  310. break;
  311. case 1:
  312. DateTimePanel.SetActive(true);
  313. if (users != null)
  314. foreach (var u in users)
  315. u.Value.toggle_user.SetActive(true);
  316. break;
  317. }
  318. }
  319. /// <summary>
  320. /// Смена позиции маркера
  321. /// </summary>
  322. public void MarkerMove()
  323. {
  324. if(users != null)
  325. foreach (var u in users)
  326. {
  327. if (u.Value != null)
  328. {
  329. if (u.Value.marker.activeSelf != u.Value.toggle.isOn) u.Value.marker.SetActive(u.Value.toggle.isOn);
  330. if (active_mode == Mode.RealTime && u.Value.toggle.isOn && !Workers.ContainsKey(u.Value.id))
  331. {
  332. Debug.LogWarning($"send coord user {u.Value.id}");
  333. var index = company.locations_index[company.active_location];
  334. client.CoordinatesRequest(0, 0, 1, company.locations[index].id, u.Value.id);
  335. u.Value.toggle_user.SetActive(u.Value.online);
  336. }
  337. if (u.Value.toggle.isOn && Workers.ContainsKey(u.Value.id) && active_mode != Mode.Stop/*&& starting*/ /*&& end_send[m.value.acc_id]*/)
  338. {
  339. StartingAccPositiong(u.Value);
  340. if (active_mode == Mode.History && !Workers.Any())
  341. {
  342. //var temp = Workers.Values.Max(v => v.Count);
  343. //if (m.i == temp - 1 && moving[moving.Keys.Last()].step >= 1f)
  344. //{
  345. StopProgress();
  346. //}
  347. //if (active_mode == Mode.RealTime && moving[moving.Keys.Last()].index == 1)
  348. //{
  349. // starting = false;
  350. //}
  351. }
  352. }
  353. }
  354. }
  355. }
  356. public void BroadcastStart(uint id)
  357. {
  358. if (user_broadcast.HasValue)
  359. {
  360. client.ImageStreamStopSend(user_broadcast.Value);
  361. var camera_button = users[user_broadcast.Value].toggle_user.transform.GetChild(1).GetComponent<Button>();
  362. camera_button.GetComponent<Image>().color = Color.white;
  363. broadcast = false;
  364. }
  365. if (user_broadcast != id)
  366. {
  367. client.ImageStreamStartSend(id);
  368. user_broadcast = id;
  369. var name = UserInfo.transform.GetChild(1).GetChild(0).GetComponent<Text>();
  370. name.text = $"{id} {users[id].name_user}";
  371. name.GetComponent<RectTransform>().sizeDelta = new Vector2(name.preferredWidth, 30);
  372. var camera_button = users[id].toggle_user.transform.GetChild(1).GetComponent<Button>();
  373. camera_button.GetComponent<Image>().color = Color.green;
  374. UserInfo.SetActive(false);
  375. broadcast = true;
  376. }
  377. else
  378. {
  379. broadcast = false;
  380. user_broadcast = null;
  381. UserInfo.SetActive(false);
  382. }
  383. }
  384. public void BroadcastStop()
  385. {
  386. if (user_broadcast.HasValue)
  387. {
  388. client.ImageStreamStopSend(user_broadcast.Value);
  389. var camera_button = users[user_broadcast.Value].toggle_user.transform.GetChild(1).GetComponent<Button>();
  390. camera_button.GetComponent<Image>().color = Color.white;
  391. }
  392. broadcast = false;
  393. user_broadcast = null;
  394. UserInfo.SetActive(false);
  395. }
  396. }