Files
SMD/Assets/Scripts/MachineTaskPanel.cs

401 lines
15 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
public sealed class MachineTaskPanel : MonoBehaviour
{
private const int RequiredCount = 3;
private const float PanelWidth = 432f;
private const float Margin = 24f;
private const float SlideDuration = 0.42f;
private const float GlowPadding = 16f;
private const float GlowDuration = 1.4f;
private MachineCoordinatesMovementScript machine;
private UnityEngine.UI.Button playButton;
private RectTransform panel;
private CanvasGroup panelGroup;
private const float InstructionTop = 58f;
private const float ContentWidth = 386f;
private const float VideoHeight = 217f;
private const float VideoDuration = 0.32f;
private static readonly string[] VideoNames = { "PickUpReel", "InsertReel", "AttachTape", "RunMachine" };
private Text instruction;
private Text secondInstruction;
private RectTransform videoViewport;
private RawImage videoImage;
private VideoPlayer videoPlayer;
private RenderTexture videoTexture;
private VideoClip[] taskVideos;
private int currentVideoStep = -1;
private float videoProgress;
private Text status;
private Image completionGlow;
private Sprite roundedSprite;
private Sprite glowSprite;
private Font font;
private int task;
private int displayedCount = -1;
private bool reelPickedUp;
private bool playPressed;
private bool transitioning;
private void Start()
{
machine = FindAnyObjectByType<MachineCoordinatesMovementScript>();
if (machine == null)
{
Debug.LogWarning("Machine tasks require the machine controller.", this);
enabled = false;
return;
}
BindPlayButton();
BuildPanel();
ShowTask();
}
private void Update()
{
UpdateVideo();
if (task == 2 && playButton == null)
BindPlayButton();
if (transitioning || task >= 3)
return;
int count = task == 0 ? machine.InstalledReelCount : machine.AttachedTapeCount;
if (count != displayedCount && task < 2)
ShowTask();
if ((task < 2 && count >= RequiredCount) || (task == 2 && playPressed))
StartCoroutine(CompleteTask());
}
public void ReelPickedUp()
{
if (reelPickedUp)
return;
reelPickedUp = true;
displayedCount = -1;
}
private void BindPlayButton()
{
var monitor = FindAnyObjectByType<ControlButtonsScript>();
if (monitor != null && monitor.buttonsDictionary != null &&
monitor.buttonsDictionary.TryGetValue("Run", out playButton) && playButton != null)
playButton.onClick.AddListener(OnPlayPressed);
}
private void OnPlayPressed()
{
if (machine.IsWorking && machine.InstalledReelCount >= RequiredCount &&
machine.AttachedTapeCount >= RequiredCount)
playPressed = true;
}
private void ShowTask()
{
var count = task == 0 ? machine.InstalledReelCount : machine.AttachedTapeCount;
displayedCount = count;
instruction.text = task switch
{
0 => (reelPickedUp || count > 0 ? "<color=#B2F1CC>" : "") +
"1. Возьмите катушку с SMD-компонентами (зажать ЛКМ)" +
(reelPickedUp || count > 0 ? "</color>" : ""),
1 => $"Возьмитесь за ленту с катушки и зафиксируйте на станке ({count}/{RequiredCount})",
_ => "Нажмите кнопку RUN на мониторе."
};
secondInstruction.enabled = task == 0;
secondInstruction.text = $"2. Перенесите катушку в фидер ({count}/{RequiredCount})";
status.enabled = false;
LayoutVideo();
}
private IEnumerator CompleteTask()
{
transitioning = true;
status.enabled = true;
LayoutVideo();
float elapsed = 0f;
while (elapsed < GlowDuration)
{
float pulse = Mathf.Sin(elapsed / GlowDuration * 2f * Mathf.PI);
SetGlow(pulse * pulse);
yield return null;
elapsed += Time.unscaledDeltaTime;
}
SetGlow(0f);
float hiddenX = -PanelWidth - Margin - GlowPadding;
yield return Slide(Margin, hiddenX, 1f, 0f);
task++;
if (task < 3)
{
ShowTask();
yield return Slide(hiddenX, Margin, 0f, 1f);
}
else
{
panel.gameObject.SetActive(false);
}
transitioning = false;
}
private IEnumerator Slide(float from, float to, float fromAlpha, float toAlpha)
{
float started = Time.unscaledTime;
float progress;
do
{
progress = Mathf.Clamp01((Time.unscaledTime - started) / SlideDuration);
float eased = Mathf.SmoothStep(0f, 1f, progress);
panel.anchoredPosition = new Vector2(Mathf.Lerp(from, to, eased), -Margin);
panelGroup.alpha = Mathf.Lerp(fromAlpha, toAlpha, eased);
yield return null;
} while (progress < 1f);
}
private void BuildPanel()
{
font = Resources.Load<Font>("Exo2-VariableFont_wght");
if (font == null)
font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
roundedSprite = CreateRoundedSprite(0f);
glowSprite = CreateRoundedSprite(GlowPadding);
var root = new GameObject("Machine Tasks", typeof(RectTransform), typeof(Canvas), typeof(CanvasScaler));
root.transform.SetParent(transform, false);
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 50;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920f, 1080f);
scaler.matchWidthOrHeight = 0.5f;
var panelObject = new GameObject("Task Panel", typeof(RectTransform), typeof(CanvasGroup));
panel = panelObject.GetComponent<RectTransform>();
panel.SetParent(root.transform, false);
panel.anchorMin = panel.anchorMax = panel.pivot = new Vector2(0f, 1f);
panel.sizeDelta = new Vector2(PanelWidth, 262f);
panel.anchoredPosition = new Vector2(Margin, -Margin);
panelGroup = panel.GetComponent<CanvasGroup>();
panelGroup.blocksRaycasts = false;
panelGroup.interactable = false;
var glow = AddImage(panel, "Completion Glow", Color.clear, glowSprite);
Stretch(glow, -GlowPadding);
completionGlow = glow.GetComponent<Image>();
var frame = AddImage(panel, "Outer Border", new Color32(38, 40, 118, 236), roundedSprite);
Stretch(frame, 0f);
var accent = AddImage(frame, "Inner Border", new Color32(89, 161, 241, 238), roundedSprite);
Stretch(accent, 4f);
var background = AddImage(accent, "Background", new Color32(17, 58, 105, 235), roundedSprite);
Stretch(background, 2f);
AddText(background, "Heading", "Задача", new Vector2(0f, -14f), new Vector2(318f, 31f),
26, TextAnchor.UpperCenter, new Color32(233, 245, 255, 255)).fontStyle = FontStyle.Bold;
instruction = AddText(background, "Instructions", "", new Vector2(17f, -58f), new Vector2(386f, 145f),
22, TextAnchor.UpperLeft, Color.white);
secondInstruction = AddText(background, "Second Instruction", "", Vector2.zero, new Vector2(ContentWidth, 70f),
22, TextAnchor.UpperLeft, Color.white);
BuildVideo(background);
status = AddText(background, "Task Status", "Выполнено", new Vector2(0f, -212f), new Vector2(318f, 29f),
22, TextAnchor.UpperCenter, new Color32(151, 255, 188, 255));
status.fontStyle = FontStyle.Bold;
}
private void BuildVideo(Transform parent)
{
taskVideos = new VideoClip[VideoNames.Length];
for (int i = 0; i < VideoNames.Length; i++)
{
taskVideos[i] = Resources.Load<VideoClip>("TaskVideos/" + VideoNames[i]);
}
var viewport = new GameObject("Video Hint", typeof(RectTransform), typeof(RectMask2D));
videoViewport = viewport.GetComponent<RectTransform>();
videoViewport.SetParent(parent, false);
videoViewport.anchorMin = videoViewport.anchorMax = videoViewport.pivot = new Vector2(0f, 1f);
var image = new GameObject("Video Image", typeof(RectTransform), typeof(RawImage));
videoImage = image.GetComponent<RawImage>();
videoImage.raycastTarget = false;
var imageRect = videoImage.rectTransform;
imageRect.SetParent(videoViewport, false);
imageRect.anchorMin = imageRect.anchorMax = imageRect.pivot = new Vector2(0f, 1f);
imageRect.sizeDelta = new Vector2(ContentWidth, VideoHeight);
videoTexture = new RenderTexture(768, 432, 0) { name = "Task Video" };
videoImage.texture = videoTexture;
videoPlayer = viewport.AddComponent<VideoPlayer>();
videoPlayer.playOnAwake = false;
videoPlayer.isLooping = true;
videoPlayer.audioOutputMode = VideoAudioOutputMode.None;
videoPlayer.aspectRatio = VideoAspectRatio.FitInside;
videoPlayer.renderMode = VideoRenderMode.RenderTexture;
videoPlayer.targetTexture = videoTexture;
}
private void UpdateVideo()
{
if (videoPlayer == null)
return;
int nextStep = transitioning || task >= 3 ? -1 : task switch
{
0 => reelPickedUp || machine.InstalledReelCount > 0 ? 1 : 0,
1 => 2,
_ => 3
};
if (nextStep >= 0 && taskVideos[nextStep] == null)
nextStep = -1;
if (currentVideoStep != nextStep && videoProgress <= 0f)
{
videoPlayer.Stop();
currentVideoStep = nextStep;
if (nextStep >= 0)
{
videoPlayer.clip = taskVideos[nextStep];
videoPlayer.Play();
}
}
bool show = currentVideoStep >= 0 && currentVideoStep == nextStep && videoPlayer.isPrepared;
float progress = Mathf.MoveTowards(videoProgress, show ? 1f : 0f, Time.unscaledDeltaTime / VideoDuration);
if (progress != videoProgress)
{
videoProgress = progress;
LayoutVideo();
}
}
private void LayoutVideo()
{
float open = Mathf.SmoothStep(0f, 1f, videoProgress);
float extraHeight = (VideoHeight + 12f) * open;
float afterFirst = InstructionTop + instruction.preferredHeight + 10f;
bool betweenPoints = task == 0 && currentVideoStep == 0;
secondInstruction.rectTransform.anchoredPosition = new Vector2(17f,
-afterFirst - (betweenPoints ? extraHeight : 0f));
float videoTop = task == 0 && !betweenPoints ? afterFirst + secondInstruction.preferredHeight + 10f : afterFirst;
videoViewport.anchoredPosition = new Vector2(17f, -videoTop);
videoViewport.sizeDelta = new Vector2(ContentWidth, VideoHeight * open);
videoImage.color = new Color(1f, 1f, 1f, open);
videoImage.enabled = open > 0f;
float contentBottom = videoTop + extraHeight;
float panelHeight = task == 0
? Mathf.Max(262f, videoTop + 54f) + extraHeight
: contentBottom + (status.enabled ? 46f : 12f);
panel.sizeDelta = new Vector2(PanelWidth, panelHeight);
float statusTop = task == 0 ? panelHeight - 50f : contentBottom + 6f;
status.rectTransform.anchoredPosition = new Vector2(0f, -statusTop);
}
private static RectTransform AddImage(Transform parent, string name, Color color, Sprite sprite)
{
var child = new GameObject(name, typeof(RectTransform), typeof(Image));
child.transform.SetParent(parent, false);
var image = child.GetComponent<Image>();
image.sprite = sprite;
image.type = Image.Type.Sliced;
image.color = color;
image.raycastTarget = false;
return image.rectTransform;
}
private static void Stretch(RectTransform rect, float inset)
{
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
rect.offsetMin = Vector2.one * inset;
rect.offsetMax = -Vector2.one * inset;
}
private Text AddText(Transform parent, string name, string content, Vector2 position, Vector2 size,
int fontSize, TextAnchor alignment, Color color)
{
var child = new GameObject(name, typeof(RectTransform), typeof(Text));
child.transform.SetParent(parent, false);
var text = child.GetComponent<Text>();
text.font = font;
text.fontSize = fontSize;
text.alignment = alignment;
text.color = color;
text.text = content;
text.raycastTarget = false;
var rect = text.rectTransform;
bool centered = alignment == TextAnchor.UpperCenter;
rect.anchorMin = rect.anchorMax = rect.pivot = new Vector2(centered ? 0.5f : 0f, 1f);
rect.anchoredPosition = position;
rect.sizeDelta = size;
return text;
}
private void SetGlow(float strength)
{
completionGlow.color = new Color(0.2f, 0.46f, 1f, strength * 0.9f);
}
private static Sprite CreateRoundedSprite(float blur)
{
const int size = 64;
const float radius = 13f;
const float border = 30f;
var texture = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
var pixels = new Color32[size * size];
float inner = size * 0.5f - radius - blur;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
var corner = new Vector2(
Mathf.Max(0f, Mathf.Abs(x + 0.5f - size * 0.5f) - inner),
Mathf.Max(0f, Mathf.Abs(y + 0.5f - size * 0.5f) - inner));
float distance = corner.magnitude - radius;
float alpha = blur > 0f ? 1f - Mathf.SmoothStep(0f, 1f, distance / blur)
: Mathf.Clamp01(0.5f - distance);
pixels[y * size + x] = new Color32(255, 255, 255, (byte)Mathf.RoundToInt(alpha * 255f));
}
}
texture.SetPixels32(pixels);
texture.Apply(false, true);
return Sprite.Create(texture, new Rect(0f, 0f, size, size), new Vector2(0.5f, 0.5f), 100f,
0, SpriteMeshType.FullRect, Vector4.one * border);
}
private static void DestroySprite(Sprite sprite)
{
if (sprite == null)
return;
Destroy(sprite.texture);
Destroy(sprite);
}
private void OnDestroy()
{
if (playButton != null)
playButton.onClick.RemoveListener(OnPlayPressed);
if (videoPlayer != null)
videoPlayer.Stop();
if (videoTexture != null)
{
videoTexture.Release();
Destroy(videoTexture);
}
DestroySprite(roundedSprite);
DestroySprite(glowSprite);
}
}