diff --git a/PersonScript.cs b/PersonScript.cs index a969877..7828805 100644 --- a/PersonScript.cs +++ b/PersonScript.cs @@ -150,7 +150,7 @@ public class TeleportationChecker } float currentDistance = Vector3.Distance(_agent.transform.position, targetPoint); - Debug.Log($"{currentDistance} {maxDistance}"); + //Debug.Log($"{currentDistance} {maxDistance}"); if (currentDistance - textScale * _agent.radius < maxDistance ) { Debug.Log("Move"); diff --git a/PlayerScript.cs b/PlayerScript.cs index fcafa8d..a3c99b0 100644 --- a/PlayerScript.cs +++ b/PlayerScript.cs @@ -1,4 +1,3 @@ -using System.Collections; using System.Collections.Generic; using UnityEngine; @@ -11,12 +10,240 @@ public class PlayerScript : MonoBehaviour public float zoom = 0.25f; // чувствительность при увеличении, колесиком мышки public float zoomMax = 10; // макс. увеличение public float zoomMin = 3; // мин. увеличение - private float X, Y; + public float X, Y; - void Start() + RayClusterFinder rayClusterFinder; + void Start() { + rayClusterFinder = new RayClusterFinder(); + } - } + Vector3 playerOffset = new Vector3(0,1.5f,0); + Vector3 lastPlayerPosition = new Vector3(), lastCameraPosition = new Vector3(); + + public static Quaternion GetRotationBetweenVectors(Vector3 a, Vector3 b) + { + // Нормализуем векторы (на случай, если они не нормализованы) + a = a.normalized; + b = b.normalized; + + // Если векторы коллинеарны: + if (a == b) + return Quaternion.identity; // Нет вращения + + if (a == -b) + { + // Если векторы противоположны, выбираем произвольную ось, перпендикулярную `a` + Vector3 axis1 = (Mathf.Abs(a.x) > 0.9f) ? Vector3.Cross(a, Vector3.up).normalized + : Vector3.Cross(a, Vector3.right).normalized; + return Quaternion.AngleAxis(180f, axis1); + } + + // Ось вращения (нормализованное векторное произведение) + Vector3 axis = Vector3.Cross(a, b).normalized; + + // Угол вращения (через скалярное произведение) + float angle = Mathf.Acos(Vector3.Dot(a, b)) * Mathf.Rad2Deg; + + // Возвращаем кватернион + return Quaternion.AngleAxis(angle, axis); + } + + public static Quaternion GetRotationBetweenVectorsWithZeroZ(Vector3 a, Vector3 b) + { + // Нормализуем векторы + a = a.normalized; + b = b.normalized; + + // Если векторы коллинеарны + if (a == b) + return Quaternion.identity; + + if (a == -b) + { + // Для противоположных векторов выбираем ось, перпендикулярную a и лежащую в плоскости XY + Vector3 axis1 = new Vector3(-a.y, a.x, 0).normalized; + return Quaternion.AngleAxis(180f, axis1); + } + + // Находим ось вращения + Vector3 axis = Vector3.Cross(a, b).normalized; + + // Проецируем ось на плоскость XY, чтобы исключить Z-компоненту + Vector3 flatAxis = new Vector3(axis.x, axis.y, 0).normalized; + + // Если проекция нулевая (векторы отличаются только по Z), + // используем ось X или Y + if (flatAxis == Vector3.zero) + { + flatAxis = Vector3.up; + } + + // Вычисляем угол между векторами + float angle = Mathf.Acos(Vector3.Dot(a, b)) * Mathf.Rad2Deg; + + // Создаем кватернион с нулевым поворотом вокруг Z + Quaternion rotation = Quaternion.AngleAxis(angle, flatAxis); + + // Дополнительно убедимся, что в кватернионе нет поворота вокруг Z + Vector3 euler = rotation.eulerAngles; + return Quaternion.Euler(euler.x, euler.y, 0); + } + + static float GetDeltaAzimut(float a, float b) + { + // Нормализуем углы в диапазон [0, 360) + a = (a % 360 + 360) % 360; + b = (b % 360 + 360) % 360; + + // Вычисляем разницу + float delta = b - a; + + // Корректируем разницу до минимального значения + if (delta > 180) + delta -= 360; + else if (delta < -180) + delta += 360; + + return delta; + //if (a < 0) + //{ + // a = a * -1 + 180; + //} + + //if (b < 0) + //{ + // b = b * -1 + 180; + //} + + //return b - a; + } + + public static Quaternion GetRotationBetweenVectorsWithZeroZ1(Vector3 a, Vector3 b, out float deltaZenith, out float deltaAzimuth) + { + // Нормализация векторов + a = a.normalized; + b = b.normalized; + + // Азимут и зенит для A + float azimuthA = Mathf.Atan2(a.z, a.x) * Mathf.Rad2Deg; + float zenithA = Mathf.Acos(a.y) * Mathf.Rad2Deg; + + // Азимут и зенит для B + float azimuthB = Mathf.Atan2(b.z, b.x) * Mathf.Rad2Deg; + float zenithB = Mathf.Acos(b.y) * Mathf.Rad2Deg; + + // Разница азимутов (с учётом цикличности) + //float deltaAzimuth = Mathf.DeltaAngle(azimuthA, azimuthB); + + // Разница зенитов + deltaZenith = zenithB - zenithA; + + //Quaternion.Euler(0, 90f, 0f) * Vector3(0, 0, 1) == Vector3(1,0,0); + deltaAzimuth = GetDeltaAzimut(azimuthA,azimuthB); + + Quaternion finalRot = Quaternion.Euler(deltaZenith, -deltaAzimuth, 0f); + + // Проверка (опционально) + Vector3 rotatedA = finalRot * a; + if ((rotatedA - b).magnitude > 0.01f) + { + deltaZenith *= -1; + finalRot = Quaternion.Euler(deltaZenith, -deltaAzimuth, 0f); + rotatedA = finalRot * a; + if ((rotatedA - b).magnitude > 0.01f) + { + Debug.LogWarning("Погрешность превышает допустимую!"); + } + } + return finalRot; + } + + + void FixedUpdate() + { + if (SceneParams.Instance.cameraSettings.IsAutoRotateCamera == false || SceneParams.Instance.cameraSettings.IsStartPos) return; + if (lastPlayerPosition == target.transform.position && + lastCameraPosition == transform.position) return; + lastPlayerPosition = target.transform.position; + lastCameraPosition = transform.position; + Vector3 player = target.transform.position; + player += playerOffset; + + Vector3[] checkiablePoints = new Vector3[3] + { + new Vector3(player.x,player.y,player.z+0.1f), + new Vector3(player.x,player.y,player.z+1.0f), + new Vector3(player.x, player.y, player.z+1.8f) + }; + + bool isCast = false; + Vector3 direction; + + foreach (var point in checkiablePoints) + { + direction = transform.position - point; + if (Physics.Raycast(point, direction.normalized, out var hit, Vector3.Distance(point, transform.position))){ + isCast = true; + break; + } + } + + if (isCast) + { + Debug.Log($"{player} - {transform.position}"); + Vector3 newPosition = rayClusterFinder.Calculate(checkiablePoints); + + // 1. Вычисляем новое смещение + float distance = Vector3.Distance(target.position, newPosition); + + // 2. Устанавливаем смещение по оси Z + // Расчёт Z вектора для констатных двух параметров x,y (0,1,z) + offset.z = Mathf.Sqrt(distance * distance - 1); + + offset.z *= -1; + + //transform.LookAt(target); + //return; + // 3. Вычисляем направление от новой позиции камеры к объекту + Vector3 directionToTarget = (newPosition-target.position); + // 4. Вычисляем вращение на основе направления + //Quaternion rotation = GetRotationBetweenVectors(offset, directionToTarget); + Quaternion rotation = GetRotationBetweenVectorsWithZeroZ1(offset, directionToTarget, out var deltaZenith, out var deltaAzimuth); + //Quaternion.Euler(deltaZenith, -deltaAzimuth, 0f); + //Quaternion.Euler(-Y, X, 0f); + // Y = deltaZenit + // X = -deltaAzimut // + //offset *= -1; + //deltaZenith = 180.0f - deltaZenith; + //deltaAzimuth = deltaAzimuth + 180.0f; + //rotation = Quaternion.Inverse(rotation); + //rotation = Quaternion.Euler(deltaZenith, -(deltaAzimuth), 0f); + Y = -deltaZenith; + X = -deltaAzimuth; + // 5. Применяем вращение к локальной ротации объекта + transform.localRotation = rotation; + + // 6. Обновляем позицию камеры с учетом смещения + // Здесь мы используем локальную ротацию для расчета новой позиции + Vector3 calculatedPosition = transform.localRotation * offset + target.position; + + // 7. Устанавливаем позицию камеры + //transform.position = calculatedPosition; + lastCameraPosition = calculatedPosition; + + // 8. Проверяем, совпадает ли рассчитанная позиция с заданной + distance = Vector3.Distance(newPosition, calculatedPosition); + if (distance < 0.01f) + { + Debug.Log("Рассчитано верно"); + } else + { + Debug.Log("Рассчитано не верно"); + } + } + + } public void SetPlayerPosition() { @@ -52,3 +279,154 @@ public class PlayerScript : MonoBehaviour } } } + +public class RayClusterFinder +{ + public float proximityRadius = 5f; // Радиус для поиска ближайших лучей + + public float maxDistance = 10f; // Максимальная длина луча + public float minDistance = 3f; // Максимальная длина луча + public float upperZenithAngle = 5f; // Угол верхнего зенита + public float lowerZenithAngle = -35f; // Угол нижнего зенита + public float azimuthStep = 10f; // Шаг по азимуту + + private List rayOrigins = new List(); // Список для хранения начальных точек лучей + + public RayClusterFinder() + { + } + + Vector3 bestVertex; + + public Vector3 Calculate(Vector3[] origin) + { + //CastRays(); + CastSphericalRays(origin); + FindRayWithMostNeighbors(origin); + return bestVertex; + } + + void CastSphericalRays(Vector3[] originArr) + { + rayOrigins.Clear(); + + foreach (var origin in originArr) + { + // Преобразуем углы в радианы + float upperZenithRad = (upperZenithAngle + 90) * Mathf.Deg2Rad; + float lowerZenithRad = (lowerZenithAngle + 90) * Mathf.Deg2Rad; + float azimuthStepRad = azimuthStep * Mathf.Deg2Rad; + + // Генерация лучей + for (float zenith = lowerZenithRad; zenith <= upperZenithRad; zenith += azimuthStepRad) + { + for (float azimuth = 0; azimuth < 360 * Mathf.Deg2Rad; azimuth += azimuthStepRad) + { + // Вычисляем направление луча + float x = Mathf.Sin(zenith) * Mathf.Cos(azimuth); + float y = Mathf.Cos(zenith); + float z = Mathf.Sin(zenith) * Mathf.Sin(azimuth); + Vector3 direction = new Vector3(x, y, z).normalized; + + // Позиция начала луча (центр капсулы) + + // Отправляем луч + RaycastHit hit; + if (Physics.Raycast(origin, direction, out hit, maxDistance)) + { + // Проверяем, если расстояние до столкновения меньше или равно maxDistance + if (hit.distance <= maxDistance && hit.distance >= minDistance) + { + rayOrigins.Add(hit.point); // Сохраняем валидное столкновение + //Debug.DrawLine(origin, hit.point, Color.red, 1000000); // Отображаем луч до столкновения + //Debug.Log($"Hit: {hit.collider.name} at {hit.point}"); + } + } + else + { + rayOrigins.Add(origin + direction * maxDistance); + //Debug.DrawRay(origin, direction * maxDistance, Color.green, 1000000); // Отображаем луч, если нет столкновения + } + } + } + } + } + void FindRayWithMostNeighbors(Vector3[] originalCenterArr) + { + Vector3 originalCenter = Vector3.zero; + + // 1. Calculate the center of all points + foreach (var origin in originalCenterArr) + { + originalCenter += origin; + } + originalCenter /= rayOrigins.Count; // Divide by the number of points to get the center + + + int maxNeighbors = 0; + List neighborsVertex = new List(); + Vector3 center = Vector3.zero; + + // 1. Calculate the center of all points + foreach (var origin in rayOrigins) + { + center += origin; + } + center /= rayOrigins.Count; // Divide by the number of points to get the center + + // 2. Find rays with the most neighbors + foreach (var origin in rayOrigins) + { + int neighborCount = 0; + + foreach (var otherOrigin in rayOrigins) + { + if (origin != otherOrigin && Vector3.Distance(origin, otherOrigin) <= proximityRadius) + { + neighborCount++; + } + } + + if (neighborCount > maxNeighbors) + { + neighborsVertex.Clear(); + maxNeighbors = neighborCount; + neighborsVertex.Add(origin); + } + else if (neighborCount == maxNeighbors) + { + neighborsVertex.Add(origin); + } + } + + // 3. Find the vector from the original center to the calculated center + Vector3 directionToCenter = (center - originalCenter).normalized; + + // 4. Find the point that has the closest direction to this vector + Vector3 closestVertex = Vector3.zero; + float closestAngle = float.MaxValue; + + foreach (var vertex in neighborsVertex) + { + Debug.DrawLine(originalCenter, vertex, Color.green, 15); + Vector3 directionFromOriginal = (vertex - originalCenter).normalized; // Direction from original center to the vertex + float angle = Vector3.Angle(directionToCenter, directionFromOriginal); // Calculate the angle between the two directions + + if (angle < closestAngle) + { + closestAngle = angle; + closestVertex = vertex; + } + } + + //Debug.Log($"Closest direction to the center: {closestVertex}"); + //Debug.Log($"Center0: {originalCenter}"); + //Debug.Log($"Center1: {center}"); + //Debug.Log($"vector: {center - originalCenter}"); + + bestVertex = closestVertex; + Debug.DrawLine(originalCenter, originalCenter + (center-originalCenter).normalized * 10f, Color.red, 15); + Debug.DrawLine(originalCenter, originalCenter + (closestVertex- originalCenter) * 1.5f, Color.blue, 15); + } +} + diff --git a/SceneParams.cs b/SceneParams.cs index 295d156..2781c92 100644 --- a/SceneParams.cs +++ b/SceneParams.cs @@ -30,7 +30,7 @@ class SceneParams get => isBlockMove; set { - if (Instance.IsDataHistoryLoadged) + if (Instance.IsDataHistoryLoaded) isBlockMove = value; } } @@ -45,6 +45,8 @@ class SceneParams public Transform DefaultTransform = null; public bool IsStartPos { get; set; } = true; + + public bool IsAutoRotateCamera { get; set; } = true; } public class SpawnMovePoint diff --git a/SphericalRaycaster.cs b/SphericalRaycaster.cs new file mode 100644 index 0000000..3ba71f3 --- /dev/null +++ b/SphericalRaycaster.cs @@ -0,0 +1,82 @@ +п»їusing System.Collections.Generic; +using UnityEngine; + +public class SphericalRaycaster : MonoBehaviour +{ + public Transform player; // Ссылка РЅР° объект РёРіСЂРѕРєР° (капсулу) + public float maxDistance = 10f; // Максимальная длина луча + public float minDistance = 3f; // Максимальная длина луча + public float upperZenithAngle = 30f; // РЈРіРѕР» верхнего зенита + public float lowerZenithAngle = -30f; // РЈРіРѕР» нижнего зенита + public float azimuthStep = 15f; // Шаг РїРѕ азимуту + + //private List validHits = new List(); // РЎРїРёСЃРѕРє для хранения валидных столкновений + + void Start() + { + } + + bool fa = true; + private void Update() + { + if (fa) + { + CastSphericalRays(); + fa = false; + } + + Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)); + float distance = 100f; + Debug.DrawRay(ray.origin, ray.direction * distance, Color.red); + //RaycastHit hit; + } + List rayOrigins = new List(); + void CastSphericalRays() + { + rayOrigins.Clear(); + + // Преобразуем углы РІ радианы + float upperZenithRad = (upperZenithAngle+90) * Mathf.Deg2Rad; + float lowerZenithRad = (lowerZenithAngle+90) * Mathf.Deg2Rad; + float azimuthStepRad = azimuthStep * Mathf.Deg2Rad; + + // Генерация лучей + for (float zenith = lowerZenithRad; zenith <= upperZenithRad; zenith += azimuthStepRad) + { + for (float azimuth = 0; azimuth < 360 * Mathf.Deg2Rad; azimuth += azimuthStepRad) + { + // Вычисляем направление луча + float x = Mathf.Sin(zenith) * Mathf.Cos(azimuth); + float y = Mathf.Cos(zenith); + float z = Mathf.Sin(zenith) * Mathf.Sin(azimuth); + Vector3 direction = new Vector3(x, y, z).normalized; + + // Позиция начала луча (центр капсулы) + Vector3 origin = player.position; + + // Отправляем луч + RaycastHit hit; + if (Physics.Raycast(origin, direction, out hit, maxDistance)) + { + // Проверяем, если расстояние РґРѕ столкновения меньше или равно maxDistance + if (hit.distance <= maxDistance && hit.distance >= minDistance) + { + rayOrigins.Add(hit.point); // Сохраняем валидное столкновение + Debug.DrawLine(origin, hit.point, Color.red, 1000000); // Отображаем луч РґРѕ столкновения + Debug.Log($"Hit: {hit.collider.name} at {hit.point}"); + } + } + else + { + rayOrigins.Add(origin + direction * maxDistance); + //Debug.DrawRay(origin, direction * maxDistance, Color.green, 1000000); // Отображаем луч, если нет столкновения + } + } + } + } + + void Calculate() + { + + } +} diff --git a/SphericalRaycaster.cs.meta b/SphericalRaycaster.cs.meta new file mode 100644 index 0000000..a59d298 --- /dev/null +++ b/SphericalRaycaster.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c798093f65a17ae4a92da0a1ed7ffec5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Uiika.cs b/Uiika.cs index ed3d058..88bbd54 100644 --- a/Uiika.cs +++ b/Uiika.cs @@ -9,6 +9,9 @@ using System.Globalization; using System.Linq; using Assets.Scripts; using UI.Dates; +using Trackman; +using System.Reflection; +using UnityEditor; class PlayBackControlUI { @@ -27,6 +30,9 @@ class PlayBackControlUI public VisualElement Speedx16 { get; set; } public VisualElement Speedx32 { get; set; } public VisualElement Speedx64 { get; set; } + public VisualElement RotateCamera { get; set; } + public Button ButtonRotateCamera { get; set; } + } public class TextInputModel @@ -89,8 +95,10 @@ public class TextInputModel } } cursorIndex = newValue; + Debug.Log(newValue); } + IsNeedSkeep = true; EventIndexChange.Invoke(cursorIndex); } } @@ -98,7 +106,7 @@ public class TextInputModel public string Mask { get; set; } = null; public char Pattern = '*'; - + public bool IsNeedSkeep = false; public bool IsDoImmidateUpdate = false; public string Value { get; set; } = ""; @@ -158,6 +166,21 @@ public class ProgressBarModel } } + public void UpdateCurrentTimeSeconds(int secondsFromBegin) + { + currentTime = dateBegin.AddSeconds(secondsFromBegin); + + if (currentTime > dateEnd) + { + currentTime = dateEnd; + FinishWatch.Invoke(); + } + else + { + CurrentTimeChanged.Invoke(); + } + } + public float GetProgress() { return (float)(currentTime - dateBegin).TotalSeconds / (float)(dateEnd - dateBegin).TotalSeconds; @@ -271,6 +294,42 @@ class ProgressBarController speedValueDictionary.Add(ui.PlayBackControl.Speedx32, 32); speedValueDictionary.Add(ui.PlayBackControl.Speedx64, 64); + ui.PlayBackControl.ButtonRotateCamera.clicked += () => { + if (SceneParams.Instance.cameraSettings.IsAutoRotateCamera) + { + SceneParams.Instance.cameraSettings.IsAutoRotateCamera = false; + // Выключаем РїРѕРІРѕСЂРѕС‚ камеры + } + else + { + SceneParams.Instance.cameraSettings.IsAutoRotateCamera = true; + // Включаем РїРѕРІРѕСЂРѕС‚ камеры + } + + DoUpdateRotateCamera(); + }; + + DoUpdateRotateCamera(); + + } + + private void DoUpdateRotateCamera() + { + if (!SceneParams.Instance.cameraSettings.IsAutoRotateCamera) + { + if (ColorUtility.TryParseHtmlString("#FFFFFFFF", out Color color)) + { + ui.PlayBackControl.RotateCamera.style.unityBackgroundImageTintColor = color; + }; + } + else + { + if (ColorUtility.TryParseHtmlString("#00A1E7FF", out Color color)) + { + ui.PlayBackControl.RotateCamera.style.unityBackgroundImageTintColor = color; + }; + } + ui.PlayBackControl.RotateCamera.MarkDirtyRepaint(); } void InitSpeedButton(VisualElement control) @@ -332,11 +391,12 @@ class ProgressBarController if (evt.button == (int)UnityEngine.UIElements.MouseButton.LeftMouse) { isDragging = true; // Устанавливаем флаг перетаскивания - SceneParams.Instance.cameraSettings.IsBlockMove = true; + //SceneParams.Instance.cameraSettings.IsBlockMove = true; evt.StopPropagation(); // Останавливаем дальнейшую обработку события } } + private void OnMouseUp(MouseUpEvent evt) { // Проверяем, отпущена ли левая РєРЅРѕРїРєР° мыши @@ -345,7 +405,7 @@ class ProgressBarController isDragging = false; // Сбрасываем флаг перетаскивания evt.StopPropagation(); // Останавливаем дальнейшую обработку события UpdateWithX(evt.localMousePosition.x); - SceneParams.Instance.cameraSettings.IsBlockMove = false; + //SceneParams.Instance.cameraSettings.IsBlockMove = false; } } @@ -353,7 +413,7 @@ class ProgressBarController { isDragging = false; evt.StopPropagation(); - SceneParams.Instance.cameraSettings.IsBlockMove = false; + //SceneParams.Instance.cameraSettings.IsBlockMove = false; } @@ -718,9 +778,18 @@ public class RequestFormController )); } + internal void Update() { - model.Tag.CursorIndex = ui.TagTextField.cursorIndex; + //if (model.Tag.IsNeedSkeep) + //{ + // //model.Tag.IsNeedSkeep = false; + //} + //else + //{ + model.Tag.CursorIndex = ui.TagTextField.cursorIndex; + //} + model.DateBegin.CursorIndex = ui.DateBeginTextField.cursorIndex; model.DateEnd.CursorIndex = ui.DateEndTextField.cursorIndex; } @@ -814,6 +883,8 @@ public class Uiika : MonoBehaviour public VisualTreeAsset tabletemplate; public VisualTreeAsset markPointOnBar; public GameObject CanvasCalendar; + public Texture2D CursorSelect; + public Label forcodes { get; set; } // <-- UI пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ @@ -836,6 +907,7 @@ public class Uiika : MonoBehaviour void TextFiledCursorIndexChanged(TextField textField, int pos) { + textField.cursorIndex = pos; textField.SelectRange(pos, pos + 1); } @@ -1009,6 +1081,8 @@ public class Uiika : MonoBehaviour Speedx16 = GetVisualElementByName("Speedx16"), Speedx32 = GetVisualElementByName("Speedx32"), Speedx64 = GetVisualElementByName("Speedx64"), + RotateCamera = GetVisualElementByName("rotate-camera"), + ButtonRotateCamera = GetVisualElementByName