WorkerController.cs 17 KB

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