TG9six 03a642d635 first push
first push
2025-09-06 17:17:39 +04:00

113 lines
3.7 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using Unity.VectorGraphics;
namespace Util.QRUtility
{
public class QRGenPlayerDivi : MonoBehaviour
{
public SVGImage source;
public Color color = Color.white;
private bool _generated = false;
public string inputText = "https://lg.cr/qr/gameshare/telegram/";
private string _playerName = "";
public int pixelsPerUnit = 100;
public bool flipYAxis = false;
private async void OnEnable()
{
if (!_generated)
{
await GenerateQr();
}
}
private async Task GenerateQr()
{
if (Player.Instance != null)
{
_playerName = Client.Instance.myUsername;
}
var textureSvgContent = await LoadSvgFromUrlAsync(inputText + _playerName);
var loadSprite = ConvertSvgToSprite(textureSvgContent);
source.sprite = loadSprite;
}
private async Task<string> LoadSvgFromUrlAsync(string url)
{
using UnityWebRequest request = UnityWebRequest.Get(url);
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
if (request.result == UnityWebRequest.Result.ConnectionError ||
request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"Error loading webpage: {request.error}");
return null;
}
string pageContent = request.downloadHandler.text;
string svgContent = ExtractSVGFromHtml(pageContent);
if (!string.IsNullOrEmpty(svgContent))
Debug.Log("Extracted SVG content");
else
Debug.LogError("SVG not found on the webpage.");
return svgContent;
}
private string ExtractSVGFromHtml(string htmlContent)
{
Regex regex = new Regex(@"<svg[^>]*>(.*?)<\/svg>", RegexOptions.Singleline);
Match match = regex.Match(htmlContent);
if (match.Success)
{
return match.Value;
}
return null;
}
private Sprite ConvertSvgToSprite(string svgContent)
{
if (string.IsNullOrEmpty(svgContent))
{
Debug.LogError("SVG content is empty or null.");
return null;
}
var geometries = GetGeometries(svgContent);
Sprite sprite = VectorUtils.BuildSprite(
geometries,
pixelsPerUnit,
VectorUtils.Alignment.Center,
Vector2.zero,
128,
true);
// VectorUtils.RenderGeometryToTexture(texture, geometries, Color.black);
return sprite;
}
private List<VectorUtils.Geometry> GetGeometries(string svg)
{
using var textReader = new StringReader(svg);
var sceneInfo = SVGParser.ImportSVG(textReader);
var geometry = VectorUtils.TessellateScene(sceneInfo.Scene, new VectorUtils.TessellationOptions
{
StepDistance = 10,
SamplingStepSize = 100,
MaxCordDeviation = 0.5f,
MaxTanAngleDeviation = 0.1f
});
foreach (var hGeometry in geometry)
hGeometry.Color = color;
return geometry;
}
}
}