PlayerController.cs 16 KB

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