123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470 |
- using Assets.Scripts.Models;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using UnityEngine.UI;
- public class WorkerController : MonoBehaviour
- {
- public static Dictionary<uint, List<Structure>> Workers = new Dictionary<uint, List<Structure>>();
- public static List<Structure> TestStructures = new List<Structure>();
- public static List<Beacon> Beacons = new List<Beacon>();
- public GameObject WorkersList; // scroll content
- public Dropdown DropdownCompany;
- public Dropdown DropdownLocation;
- public Dropdown DropdownData;
- public GameObject inputField_date;
- //public InputField inputField_location;
- public GameObject TimeStart;
- public GameObject TimeEnd;
- public GameObject StartHour;
- public GameObject StartMin;
- public GameObject StartSec;
- public GameObject EndHour;
- public GameObject EndMin;
- public GameObject EndSec;
- public GameObject StartStopButton;
- public GameObject ErrorDialog;
- public GameObject ButtonPlay;
- public Dropdown DropdownMode;
- public Toggle ToggleLine;
- public Toggle ToggleDisappearance;
- public GameObject DatePicker;
- public Camera camera;
- public Toggle projection;
- enum Mode { RealTime = 0, History = 1, Stop = 2 };
- Mode active_mode = Mode.Stop;
- int mode = 0;
- //public GameObject Time;
- static Client client = new Client();
- DateTimePicker Date;
- public List<GameObject> maps;
- static List<bool> starting = new List<bool>(); // флаги остановок
- public static Dictionary<uint, bool> end_send = new Dictionary<uint, bool>(); // флаги завершения загрузки
- Dictionary<uint, MarkerMoving> moving = new Dictionary<uint, MarkerMoving>(); // флаги начала движения
- //bool real_time = false;
- //bool history_start = false;
- float interpolationPeriod = 0.1f;
- float time_realtime = 0;
- float time_draw = 0;
- public static List<User> users = new List<User>();
- public static bool users_load = false;
- public static bool beacons_load = false;
- uint location_id = 1;
- public static List<Location> locations = new List<Location>();
- //List<bool> StartStop = new List<bool>();
- // Start is called before the first frame update
- void Start()
- {
- DebugHelper.ActivateConsole();
- Date = DatePicker.GetComponent<DateTimePicker>();
- locations.Add(new Location { id = 1, name = "1 Братск" });
- locations.Add(new Location { id = 22, name = "22 Офис Ижевск" });
- locations.Add(new Location { id = 25, name = "1 Братск" });
- foreach(var l in locations)
- DropdownLocation.options.Add(new Dropdown.OptionData(l.name));
- DropdownCompany.options.Add(new Dropdown.OptionData("Тайшет"));
- DropdownCompany.options.Add(new Dropdown.OptionData("Тестовая"));
- DropdownCompany.options.Add(new Dropdown.OptionData("Братское"));
- //}
- }
- public static int active_location = 0;
- public static int active_company = 0;
- // Update is called once per frame
- void Update()
- {
- if (DropdownMode.value != mode)
- {
- StopProgress();
- active_mode = Mode.Stop;
- mode = DropdownMode.value;
- switch (DropdownMode.value)
- {
- case 0:
- DatePicker.SetActive(false);
- TimeStart.SetActive(false);
- TimeEnd.SetActive(false);
- break;
- case 1:
- DatePicker.SetActive(true);
- TimeStart.SetActive(true);
- TimeEnd.SetActive(true);
- break;
- }
- }
- if(active_company != DropdownCompany.value)
- {
- active_company = DropdownCompany.value;
- foreach(var m in markers)
- {
- Destroy(m.marker.gameObject);
- Destroy(m.marker_line.gameObject);
- Destroy(m.toggle.gameObject);
- }
- markers = new List<Marker>();
- client.SendGetUsers((uint) active_company + 1);
- }
- if (active_location != DropdownLocation.value)
- {
- maps.ElementAt(active_location).SetActive(false);
- maps.ElementAt(DropdownLocation.value).SetActive(true);
- active_location = DropdownLocation.value;
- switch (DropdownLocation.value)
- {
- case 0:
- location_id = 1;
- break;
- case 1:
- location_id = 22;
- break;
- case 2:
- location_id = 25;
- break;
- }
- foreach (var b in Beacons)
- {
- Destroy(b.beacon);
- Destroy(b.button);
- }
- Beacons = new List<Beacon>();
- client.BeaconsRequest((uint)locations[DropdownLocation.value].id);
- }
- foreach (var m in markers)
- {
- m.marker.SetActive(m.toggle.isOn);
- if (m.toggle.isOn && Workers.ContainsKey(m.acc_id) && starting.Last() && end_send[m.acc_id])
- {
- //end_send[m.value.acc_id] = false;
- // moving.Add(true);
- //if (markers.Count - 1 == m.i)
- time_draw += Time.deltaTime;
- if (time_draw >= interpolationPeriod)
- {
- time_draw -= interpolationPeriod;
- StartingAccPositiong(m);
- }
- }
- }
- time_realtime += Time.deltaTime;
- if (active_mode == Mode.RealTime /*&& !inputField_location.text.Equals("")*/ && time_realtime >= interpolationPeriod)
- {
- time_realtime -= interpolationPeriod;
- //var dateNow = DateTime.UtcNow.AddHours(3);
- //Time.GetComponent<Text>().text = dateNow.ToString();
- starting.Add(true);
- //var location_id = uint.Parse(inputField_location.text);
- foreach (var m in markers)
- {
- if (m.toggle.isOn)
- {
- client.CoordinatesRequest(0, 0, 1, location_id, m.acc_id);
- //history_start = true;
- end_send[m.acc_id] = false;
- }
- }
- }
- if (ToggleLine.isOn)
- {
- foreach (var m in markers)
- m.marker_line.gameObject.SetActive(true);
- ToggleDisappearance.interactable = true;
- }
- else
- {
- foreach (var m in markers)
- {
- m.marker_line.gameObject.SetActive(false);
- m.marker_line.positionCount = 0;
- }
- ToggleDisappearance.interactable = false;
- }
- if (projection.isOn)
- {
- //camera_2d.SetActive(true);
- //camera_2_5D.SetActive(false);
- camera.orthographic = true;
- }
- else
- {
- //camera_2d.SetActive(false);
- //camera_2_5D.SetActive(true);
- camera.orthographic = false;
- }
- if (users_load)
- {
- users_load = false;
- foreach (var u in users.OrderBy(u => u.id))
- WorkerMarker(u, Color.green);
- }
- if (beacons_load)
- {
- beacons_load = false;
- foreach (var b in Beacons)
- AddBeacon(b);
- }
- }
- public static List<Marker> markers = new List<Marker>();
- /// <summary>
- /// Создание маркера для сотрудника
- /// </summary>
- /// <param name="acc_id"></param>
- void WorkerMarker(User user, Color color)
- {
- var toggle = Instantiate(Resources.Load("GameObjects/Toggle", typeof(Toggle))) as Toggle;
- toggle.name = $"{user.id}";
- toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{user.id} {user.name}";
- toggle.transform.SetParent(WorkersList.transform);
- toggle.isOn = false;
- var marker = Instantiate(Resources.Load("GameObjects/Capsule", typeof(GameObject))) as GameObject;
- marker.name = $"marker_{user.id}";
- marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{user.id}";
- marker.GetComponent<Renderer>().material.color = color; // UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
- var marker_line = Instantiate(Resources.Load("GameObjects/Line", typeof(LineRenderer))) as LineRenderer;
- marker_line.name = $"marker_line_{user.id}";
- marker_line.startColor = color;
- marker_line.endColor = Color.white;
- marker_line.material.color = color;
- markers.Add(new Marker { acc_id = user.id, marker = marker, toggle = toggle, marker_line = marker_line });
- }
- /// <summary>
- /// Смена положения маркера
- /// </summary>
- /// <param name="pause">Задержка</param>
- /// <param name="step">Шаг до нового положения</param>
- /// <param name="start_pos">Начальное положение</param>
- /// <param name="end_pos">Финальное положение</param>
- /// <param name="worker_marker">Маркер сотрудника</param>
- /// <param name="w">Данные из БД</param>
- /// <param name="count">Номер процесса/запуска</param>
- /// <param name="progress">Номер записи из БД</param>
- /// <param name="all">Всего записей из БД</param>
- /// <returns></returns>
- void Position(float step, Vector3 start_pos, Vector3 end_pos, Marker marker, Structure w, int count, string progress)
- {
- if (marker.marker.activeSelf == true && starting[count])
- {
- var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step);
- var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step);
- //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}");
- var new_position = new Vector3(x_position, 0.5f, y_position);
- if (marker.marker.transform.position != new_position)
- {
- marker.marker.transform.position = new Vector3(x_position, 0.5f, y_position);
- marker.marker_line.SetPosition(marker.marker_line.positionCount++, new Vector3(x_position, 0, y_position));
- if(ToggleDisappearance.isOn)marker.marker_line = LineDisappearance(marker.marker_line);
- }
- 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}";
- marker.toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{w.acc_id} {w.ts.ToString("hh:mm:ss")}{progress}";
- }
- }
- //static IEnumerator RequestPostion(long ts, long te, uint loc, uint account_id)
- //{
- // client.CoordinatesRequest(ts, te, 1, loc);
- // yield return new WaitForSeconds(5);
- // foreach (var t in TestStructures)
- // Debug.Log(t);
- //}
- /// <summary>
- /// Запуск отрисовки
- /// </summary>
- public void ButtonStart()
- {
- if (active_mode == Mode.Stop)
- foreach (var m in markers)
- m.marker_line.positionCount = 0;
- var button_text = StartStopButton.transform.GetChild(0);
- switch (DropdownMode.value)
- {
- case 0:
- //real_time = !real_time;
- if (active_mode == Mode.Stop/*real_time*/)
- {
- active_mode = Mode.RealTime;
- button_text.GetComponent<Text>().text = "Остановить";
- }
- else
- {
- active_mode = Mode.Stop;
- button_text.GetComponent<Text>().text = "Отобразить";
- }
- break;
- case 1:
- if (int.Parse(StartHour.GetComponent<InputField>().text) == 99) SceneManager.LoadScene("Editor3D");
- else
- {
- if (active_mode == Mode.Stop/*real_time*/) active_mode = Mode.History;
- else active_mode = Mode.Stop;
- }//history_start = !history_start;
- if (active_mode == Mode.History/*history_start*/)
- {
- starting.Add(true);
- var date = Date.Date;
- var time_start = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
- time_start = time_start.AddHours(int.Parse(StartHour.GetComponent<InputField>().text));
- time_start = time_start.AddMinutes(int.Parse(StartMin.GetComponent<InputField>().text));
- time_start = time_start.AddSeconds(int.Parse(StartSec.GetComponent<InputField>().text));
- Debug.Log(time_start);
- var time_end = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
- time_end = time_end.AddHours(int.Parse(EndHour.GetComponent<InputField>().text));
- time_end = time_end.AddMinutes(int.Parse(EndMin.GetComponent<InputField>().text));
- time_end = time_end.AddSeconds(int.Parse(EndSec.GetComponent<InputField>().text));
- foreach (var m in markers)
- {
- if (m.toggle.isOn)
- {
- client.CoordinatesRequest(time_start.Ticks, time_end.Ticks, 1, location_id, m.acc_id);
- end_send[m.acc_id] = false;
- }
- }
- button_text.GetComponent<Text>().text = "Остановить";
- }
- else
- {
- StopProgress();
- }
- break;
- }
- }
- public void ErrorDialogClose()
- {
- ErrorDialog.SetActive(false);
- }
- void StopProgress()
- {
- if (starting.Any()) starting[starting.Count - 1] = false;
- StartStopButton.transform.GetChild(0).GetComponent<Text>().text = "Отобразить";
- foreach (var m in markers)
- {
- end_send[m.acc_id] = false;
- moving.Remove(m.acc_id);
- }
- }
- /// <summary>
- /// Затухание траектории
- /// </summary>
- /// <param name="lineRenderer">Траектория</param>
- /// <returns></returns>
- LineRenderer LineDisappearance(LineRenderer lineRenderer)
- {
- //LineRenderer lineRenderer = GetComponent<LineRenderer>();
- int newPositionCount = lineRenderer.positionCount - 1;
- Vector3[] newPositions = new Vector3[newPositionCount];
- for (int i = 0; i < newPositionCount; i++)
- {
- newPositions[i] = lineRenderer.GetPosition(i + 1);
- }
-
- lineRenderer.SetPositions(newPositions);
- return lineRenderer;
- }
- /// <summary>
- /// Смена положения по интервалу
- /// Шаги для плавного перемещения
- /// </summary>
- /// <param name="m">Данные о маркере</param>
- void StartingAccPositiong(Marker m)
- {
- int i = 0;
- float step = 0.1f;
- if (moving.ContainsKey(m.acc_id))
- {
- if (moving[m.acc_id].index < Workers[m.acc_id].Count) i = moving[m.acc_id].index;
- {
- if (moving[m.acc_id].step < 1.1f) step = moving[m.acc_id].step;
- }
- }
- else moving[m.acc_id] = new MarkerMoving();
- var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList();
- if (worker.Any())
- {
- var w = worker.ElementAt(i);
- var start_pos = m.marker.transform.position;
- if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f);
- if (active_mode == Mode.History && i == 0) start_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
- var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
- var progress = "";
- if (active_mode == Mode.History) progress = $"\n{i + 1} из {Workers[m.acc_id].Count}";
- Position(step, start_pos, end_pos, m, w, starting.Count - 1, progress);
- // StartingAccPositiong(m.value, time_step);
- }
- if (step >= 1) i++;
- step += interpolationPeriod; // 0.1f;
- moving[m.acc_id].index = i;
- moving[m.acc_id].step = step;
- }
- public void AddBeacon(Beacon b)
- {
- var beacon = Instantiate(Resources.Load("GameObjects/Beacon", typeof(GameObject))) as GameObject;
- beacon.transform.position = new Vector3(b.x/100, 0.5f, b.y/100);
- beacon.name = $"BeaconButton_{b.id}";
- beacon.GetComponent<BeaconController>().move = false;
- beacon.GetComponent<BeaconController>().info = false;
- var canvas = beacon.transform.GetChild(0);
- canvas.transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{b.id}\nuuid={b.uuid}\nmajor={b.major}\nminor={b.minor}";
-
- b.beacon = beacon;
- }
- public void OpenEditor()
- {
- SceneManager.LoadScene("Scenes/Editor2D");
- }
- void OnGUI()
- {
- //if (Input.GetKeyDown(KeyCode.BackQuote))
- DebugHelper.DrawConsole();
- }
- }
|