using UnityEngine;

public class GradientMaskMaterial : MonoBehaviour
{
    public enum GradientPreset
    {
        LeftToRight,
        RightToLeft,
        TopToBottom,
        BottomToTop,
        Custom
    }

    [SerializeField] private GradientPreset preset = GradientPreset.TopToBottom;
    [SerializeField] private Vector2 customDirection = Vector2.up;
    [SerializeField] private float gradientStart = 0f;
    [SerializeField] private float gradientEnd = 1f;
    
    [SerializeField] private Renderer targetRenderer;
    private Material material;

    private void Awake()
    {
        // 如果没有指定目标渲染器，使用当前对象的渲染器
        if (targetRenderer == null)
        {
            targetRenderer = GetComponent<Renderer>();
        }

        if (targetRenderer != null)
        {
            // 创建材质实例以避免影响其他使用相同材质的对象
            material = new Material(targetRenderer.material);
            targetRenderer.material = material;
            UpdateGradient();
        }
    }

    private void Update()
    {
        // 在编辑器中可视化调整时更新梯度
        #if UNITY_EDITOR
        if (material != null)
        {
            UpdateGradient();
        }
        #endif
    }

    public void UpdateGradient()
    {
        if (material == null) return;

        Vector2 direction;
        
        // 根据预设设置梯度方向
        switch (preset)
        {
            case GradientPreset.LeftToRight:
                direction = Vector2.right;
                break;
            case GradientPreset.RightToLeft:
                direction = Vector2.left;
                break;
            case GradientPreset.TopToBottom:
                direction = Vector2.down;
                break;
            case GradientPreset.BottomToTop:
                direction = Vector2.up;
                break;
            case GradientPreset.Custom:
                direction = customDirection.normalized;
                break;
            default:
                direction = Vector2.up;
                break;
        }

        // 更新着色器参数
        material.SetVector("_GradientDirection", new Vector4(direction.x, direction.y, 0, 0));
        material.SetFloat("_GradientStart", gradientStart);
        material.SetFloat("_GradientEnd", gradientEnd);
    }
    
    // 公共方法用于动态更改梯度
    public void SetGradientDirection(Vector2 direction)
    {
        preset = GradientPreset.Custom;
        customDirection = direction;
        UpdateGradient();
    }
    
    public void SetGradientRange(float start, float end)
    {
        gradientStart = Mathf.Clamp01(start);
        gradientEnd = Mathf.Clamp01(end);
        UpdateGradient();
    }
} 