#nullable enable using System; using UnityEngine; using UnityEngine.UIElements; namespace UVC.UIToolkit { /// /// Bounds(경계 상자) 입력 필드 컴포넌트. /// Unity BoundsField를 래핑하여 커스텀 스타일을 적용합니다. /// 3D 공간에서 객체의 경계를 정의하는 Center(중심점)와 Extents(크기)를 입력받습니다. /// /// /// Bounds란? /// Bounds는 3D 공간에서 축 정렬 경계 상자(AABB)를 나타냅니다. /// - Center: 경계 상자의 중심점 (Vector3) /// - Extents: 중심에서 각 축 방향으로의 거리 (Vector3), Size의 절반 값 /// - Size: 경계 상자의 전체 크기 (Extents * 2) /// /// Validation 함수를 통한 입력 검증 (FocusOut 시 자동 호출) /// 에러 상태 시 붉은 외곽선 + 에러 메시지 표시 /// /// /// /// C# 코드에서 사용: /// /// // 기본 Bounds 필드 생성 /// var boundsField = new UTKBoundsField(); /// boundsField.label = "충돌 영역"; /// /// // 초기값 설정 (중심점: 0,1,0 / 크기: 2,2,2) /// boundsField.Value = new Bounds( /// new Vector3(0, 1, 0), // center /// new Vector3(2, 2, 2) // size (extents의 2배) /// ); /// /// // 값 변경 이벤트 처리 /// boundsField.OnValueChanged += (bounds) => { /// Debug.Log($"중심점: {bounds.center}"); /// Debug.Log($"크기: {bounds.size}"); /// Debug.Log($"최소점: {bounds.min}, 최대점: {bounds.max}"); /// }; /// /// // 라벨 커스터마이징 /// boundsField.CenterLabel = "중심"; /// boundsField.ExtentsLabel = "범위"; /// boundsField.XLabel = "가로"; /// boundsField.YLabel = "높이"; /// boundsField.ZLabel = "깊이"; /// /// // 비활성화 /// boundsField.IsEnabled = false; /// /// // 읽기 전용 (사용자가 수정할 수 없음) /// var readOnlyField = new UTKBoundsField("고정 경계"); /// readOnlyField.Value = new Bounds(Vector3.zero, Vector3.one); /// readOnlyField.IsReadOnly = true; /// /// Validation (입력 검증): /// /// // 검증 함수 설정 (Func<bool>) /// var boundsField = new UTKBoundsField("경계"); /// boundsField.ErrorMessage = "크기는 양수여야 합니다."; /// boundsField.Validation = () => boundsField.Value.size.x > 0 && boundsField.Value.size.y > 0 && boundsField.Value.size.z > 0; /// // → FocusOut 시 자동으로 검증 /// // → 실패 시 붉은 외곽선 + 에러 메시지 표시, 통과 시 자동 해제 /// /// // 강제 검증 호출 (예: 폼 제출 버튼 클릭 시) /// bool isValid = boundsField.Validate(); /// if (!isValid) return; // 검증 실패 /// /// // 에러 수동 해제 /// boundsField.ClearError(); /// /// // 에러 메시지 직접 설정 (Validation 없이, 서버 오류 등) /// boundsField.ErrorMessage = "서버 오류가 발생했습니다."; /// boundsField.ErrorMessage = ""; // 오류 제거 /// /// UXML에서 사용: /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// 실제 활용 예시: /// /// // 게임 오브젝트의 콜라이더 경계 설정 /// var colliderBounds = new UTKBoundsField("콜라이더 경계"); /// colliderBounds.OnValueChanged += (bounds) => { /// var boxCollider = targetObject.GetComponent(); /// if (boxCollider != null) /// { /// boxCollider.center = bounds.center; /// boxCollider.size = bounds.size; /// } /// }; /// /// [UxmlElement] public partial class UTKBoundsField : BoundsField, IDisposable { #region Constants private const string USS_PATH = "UIToolkit/Input/UTKBoundsField"; #endregion #region Fields private bool _disposed; private bool _isEnabled = true; private bool _isReadOnly; private string _centerLabel = "Center"; private string _extentsLabel = "Extents"; private string _xLabel = "X"; private string _yLabel = "Y"; private string _zLabel = "Z"; private string _errorMessage = ""; private Func? _validation; private Label? _errorLabel; #endregion #region Events /// 값 변경 이벤트 public event Action? OnValueChanged; #endregion #region Properties /// 활성화 상태 [UxmlAttribute("is-enabled")] public bool IsEnabled { get => _isEnabled; set { _isEnabled = value; SetEnabled(value); EnableInClassList("utk-boundsfield--disabled", !value); } } /// 현재 값 public Bounds Value { get => value; set => this.value = value; } /// Center 라벨 [UxmlAttribute("center-label")] public string CenterLabel { get => _centerLabel; set { _centerLabel = value; UpdateAxisLabels(); } } /// Extents 라벨 [UxmlAttribute("extents-label")] public string ExtentsLabel { get => _extentsLabel; set { _extentsLabel = value; UpdateAxisLabels(); } } /// X축 라벨 [UxmlAttribute("x-label")] public string XLabel { get => _xLabel; set { _xLabel = value; UpdateAxisLabels(); } } /// Y축 라벨 [UxmlAttribute("y-label")] public string YLabel { get => _yLabel; set { _yLabel = value; UpdateAxisLabels(); } } /// Z축 라벨 [UxmlAttribute("z-label")] public string ZLabel { get => _zLabel; set { _zLabel = value; UpdateAxisLabels(); } } /// 읽기 전용 상태 [UxmlAttribute("is-readonly")] public bool IsReadOnly { get => _isReadOnly; set { _isReadOnly = value; UpdateReadOnlyState(); EnableInClassList("utk-boundsfield--readonly", value); } } /// 에러 메시지. 비어있지 않으면 에러 상태로 표시 [UxmlAttribute("error-message")] public string ErrorMessage { get => _errorMessage; set { _errorMessage = value; var hasError = !string.IsNullOrEmpty(value); EnableInClassList("utk-boundsfield--error", hasError); UpdateErrorLabel(hasError ? value : null); } } /// 검증 함수. FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시 public Func? Validation { get => _validation; set => _validation = value; } #endregion #region Constructor public UTKBoundsField() : base() { UTKThemeManager.Instance.ApplyThemeToElement(this); var uss = Resources.Load(USS_PATH); if (uss != null) { styleSheets.Add(uss); } SetupStyles(); SetupEvents(); SubscribeToThemeChanges(); } public UTKBoundsField(string label) : this() { this.label = label; } #endregion #region Setup private void SetupStyles() { AddToClassList("utk-boundsfield"); // 초기 라벨 설정 schedule.Execute(() => UpdateAxisLabels()); } private void SetupEvents() { RegisterCallback>(OnFieldValueChanged); RegisterCallback(OnFocusOut); } private void SubscribeToThemeChanges() { UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged; RegisterCallback(OnAttachToPanelForTheme); RegisterCallback(OnDetachFromPanelForTheme); } private void OnAttachToPanelForTheme(AttachToPanelEvent evt) { UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged; UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged; UTKThemeManager.Instance.ApplyThemeToElement(this); } private void OnDetachFromPanelForTheme(DetachFromPanelEvent evt) { UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged; } private void OnThemeChanged(UTKTheme theme) { UTKThemeManager.Instance.ApplyThemeToElement(this); } private void UpdateAxisLabels() { // BoundsField의 내부 Vector3Field들을 찾아서 라벨 변경 (Center, Extents 순서) var vector3Fields = this.Query().ToList(); if (vector3Fields.Count >= 2) { vector3Fields[0].label = _centerLabel; vector3Fields[1].label = _extentsLabel; // 각 Vector3Field의 내부 FloatField들을 찾아서 X, Y, Z 라벨 변경 foreach (var vector3Field in vector3Fields) { var floatFields = vector3Field.Query().ToList(); if (floatFields.Count >= 3) { floatFields[0].label = _xLabel; floatFields[1].label = _yLabel; floatFields[2].label = _zLabel; } } } } private void UpdateReadOnlyState() { // 내부 Vector3Field들의 TextInput을 찾아서 읽기 전용 설정 var textInputs = this.Query>().ToList(); foreach (var textInput in textInputs) { textInput.isReadOnly = _isReadOnly; } } #endregion #region Event Handlers private void OnFieldValueChanged(ChangeEvent evt) { OnValueChanged?.Invoke(evt.newValue); } private void OnFocusOut(FocusOutEvent evt) { RunValidation(); } #endregion #region Methods /// /// 강제로 Validation을 실행하여 에러 상태를 업데이트합니다. /// /// Validation이 null이면 true, 아니면 Validation 결과 public bool Validate() { return RunValidation(); } /// 에러 상태를 수동으로 해제합니다. public void ClearError() { ErrorMessage = ""; } private bool RunValidation() { if (_validation == null) return true; var isValid = _validation.Invoke(); if (isValid) { // 검증 통과 시 에러 상태 해제 EnableInClassList("utk-boundsfield--error", false); UpdateErrorLabel(null); } else { // 검증 실패 시 에러 상태 표시 EnableInClassList("utk-boundsfield--error", true); UpdateErrorLabel(_errorMessage); } return isValid; } private void UpdateErrorLabel(string? message) { if (string.IsNullOrEmpty(message)) { // 에러 라벨 숨기기 (존재하면) if (_errorLabel != null) { _errorLabel.style.display = DisplayStyle.None; } return; } // 에러 라벨 생성 (지연 생성 - 필요할 때만) if (_errorLabel == null) { _errorLabel = new Label(); _errorLabel.AddToClassList("utk-boundsfield__error-message"); _errorLabel.style.display = DisplayStyle.None; Add(_errorLabel); } _errorLabel.text = message; _errorLabel.style.display = DisplayStyle.Flex; } #endregion #region IDisposable public void Dispose() { if (_disposed) return; _disposed = true; UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged; UnregisterCallback(OnAttachToPanelForTheme); UnregisterCallback(OnDetachFromPanelForTheme); UnregisterCallback>(OnFieldValueChanged); UnregisterCallback(OnFocusOut); OnValueChanged = null; _validation = null; _errorLabel = null; } #endregion } }