PlayerController.cs 16 KB

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