ScreenLocate.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. #define ENABLE_LOG
  2. using InfraredManager;
  3. using o0;
  4. using o0.Geometry2D.Float;
  5. using o0InfraredLocate.ZIM;
  6. using SixLabors.ImageSharp.PixelFormats;
  7. using SLAMUVC;
  8. using System;
  9. using System.Collections;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using UnityEngine;
  13. using UnityEngine.Experimental.AI;
  14. using UnityEngine.UI;
  15. using ZIM;
  16. using ZIM.Unity;
  17. using static SLAMUVC.UVCManager;
  18. using Color = UnityEngine.Color;
  19. using Time = UnityEngine.Time;
  20. [RequireComponent(typeof(Canvas))]
  21. public partial class ScreenLocate : o0InfraredCameraHandler
  22. {
  23. public InfraredCameraHelper InfraredCameraHelper;
  24. private const string TAG = "ScreenLocate#";
  25. enum Mode
  26. {
  27. InfraredLocate,
  28. ScreenMap,
  29. ScreenLocateManual
  30. }
  31. enum Platform
  32. {
  33. Window,
  34. Android
  35. }
  36. Platform mPlatform = Platform.Android;
  37. public enum ScreenIdentificationTag
  38. {
  39. // 屏幕定位的方式,手动、半自动、自动
  40. Manual,
  41. SemiAuto,
  42. Auto
  43. }
  44. // 2个灯,顺序根据红外灯的大小 由大到小, 坐标通过 InfraredSpot.ScreenUV 和 InfraredSpot.CameraLocation 获得
  45. public InfraredSpot[] InfraredSpots
  46. {
  47. get
  48. {
  49. return infraredSpotBuffer;
  50. }
  51. }
  52. // 1个灯, 坐标通过 InfraredSpot.ScreenUV 和 InfraredSpot.CameraLocation 获得
  53. public InfraredSpot InfraredSpotSingle
  54. {
  55. get
  56. {
  57. return infraredSpotBuffer[0];
  58. }
  59. }
  60. public InfraredSpot[] infraredSpotBuffer => infraredLocate.InfraredSpotBuffer;
  61. // 当前 应用/生效 的屏幕四边形数据(QuadrilateralInCamera类)
  62. public QuadrilateralInCamera CurrentScreenQuad => screenIdentification.Screen.QuadInCamera;
  63. /// <summary>
  64. /// 定位之后,可能有3种结果(手动、半自动、自动),从中选择一种作为最终识别到的屏幕。
  65. /// 如果选择的是null,即没有识别到屏幕,则返回false,否则返回true
  66. /// </summary>
  67. public bool SelectScreenAfterLocate(ScreenIdentificationTag tag) => ScreenIdentification.SelectScreenAfterLocate(tag);
  68. /// 上一次屏幕定位的情况, 还未识别(或识别失败)的时候返回值是null
  69. public QuadrilateralInCamera LastQuadState(ScreenIdentificationTag tag)
  70. {
  71. QuadrilateralInCamera target = tag switch
  72. {
  73. ScreenLocate.ScreenIdentificationTag.Manual => ScreenIdentification.QuadManual,
  74. ScreenLocate.ScreenIdentificationTag.SemiAuto => ScreenIdentification.QuadSemiAuto,
  75. ScreenLocate.ScreenIdentificationTag.Auto => ScreenIdentification.QuadAuto,
  76. _ => null
  77. };
  78. return target;
  79. }
  80. /// <summary>
  81. /// 上一次半自动识别的情况, 还未识别的时候数组是null
  82. /// 通过索引获取布尔值,false代表这条边识别失败(回退应用了手动数据), 0-下、1-右、2-上、3-左
  83. /// </summary>
  84. public bool[] LastQuadSemiAutoState() => screenIdentification.LastQuadSemiAutoState;
  85. /// <summary>
  86. /// 获取算法执行过程中输出的纹理,0原图,1半自动识别到的全部线段,2屏幕黑白色差,3识别结果,4屏幕色差叠加识别结果,5半自动时的备选线段
  87. /// </summary>
  88. public Texture2D[] OutputTextures => outputTexture2D;
  89. public Vector2 CameraLocationOffset
  90. {
  91. get=>infraredLocate.CameraLocationOffset;
  92. set{
  93. infraredLocate.CameraLocationOffset = value;
  94. }
  95. }
  96. public Vector2 UVOffset
  97. {
  98. get=>infraredLocate.UVOffset;
  99. set{
  100. infraredLocate.UVOffset = value;
  101. }
  102. }
  103. //用来记录最后一次更新的数据
  104. Vector2 OldCameraLocationOffset { get; set; } = new Vector2(0, 0);
  105. //用来记录最后一次更新的数据
  106. Vector2 OldUVOffset { get; set; } = new Vector2(0, 0);
  107. //是否单点显示
  108. public bool bSinglePoint => infraredLocate.bSinglePoint;
  109. // public InfraredDemo InfraredDemoMain => FindObjectOfType<InfraredDemo>();
  110. #region UVC 处理的对象
  111. //public UVCManager mUVCManager;
  112. public CameraInfo mUVCCameraInfo;
  113. public bool getUVCCameraInfo => mUVCCameraInfo != null ? true : false;
  114. public Vector2 getUVCCameraInfoSize => getUVCCameraInfo ? mUVCCameraInfo.Size : new Vector2(320, 240);
  115. private Texture mUVCTexture;
  116. public Texture getUVCTexture => mUVCTexture;
  117. public Texture setUVCTexture
  118. {
  119. set
  120. {
  121. mUVCTexture = value;
  122. }
  123. }
  124. private Texture2D mUVCTexture2D;
  125. // [SerializeField] Texture2DArray mUVCOutArray;
  126. #endregion
  127. public Text Info;
  128. public List<RectTransform> CrosshairInCamera;
  129. public List<RectTransform> CrosshairInScreen;
  130. public RectTransform ScreenQuad;
  131. public Toggle SaveToggle;
  132. public Toggle FullScreenToggle;
  133. public Toggle SingleToggle;
  134. public LineGenerator UILineGenerator;
  135. public bool ShowScreenQuad = false;
  136. // 显示在demo上的rawImage
  137. public List<RawImage> outputRawImages;
  138. readonly Texture2D[] outputTexture2D = new Texture2D[8];
  139. public RawImage FullScreenImage;
  140. public PixelCheaker ScreenPixelCheaker;
  141. public List<Texture2D> DebugScreenImages = new List<Texture2D>();
  142. public bool DebugOnZIMDemo = false;
  143. // private SynchronizationContext mainContext;
  144. public float ReDoLocateCalibrationRatio { get; private set; } // 半自动定位时校准的距离比例,以手动的结果来校准,离手动太远的线段会被舍弃
  145. public void SetCameraSize(Vector size) => cameraSize = size;
  146. public override Vector CameraSize => cameraSize;
  147. // 记录算法中的CameraSize,红外识别和屏幕识别都会使用到
  148. Vector cameraSize;
  149. bool bIdentifyRed = true;//默认设备红色
  150. bool bIdentifyGreen = true;
  151. #region 性能检测相关
  152. public Text m_UITime;
  153. const float m_UIUpdateInterval = 0.1f;
  154. float m_UIUpdateTimer = 0.0f;
  155. List<float> m_History = new List<float>(100);
  156. int m_ValidHistoryFrames = 0;
  157. float m_AverageTime = float.NaN;
  158. float m_MedianTime = float.NaN;
  159. float m_MinTime = float.NaN;
  160. float m_MaxTime = float.NaN;
  161. public float updateInterval = 0.5F;
  162. private double lastInterval;
  163. private int frames = 0;
  164. private float fps;
  165. public Text m_FPS;
  166. #endregion
  167. #region PC部分参数
  168. //亮度
  169. public float pcBrightness { get; set; } = 0.0f;
  170. //对比度
  171. public float pcContrast { get; set; } = 0.0f;
  172. #endregion
  173. // 红外灯识别算法
  174. InfraredLocate infraredLocate;
  175. // 屏幕识别算法
  176. o0.Project.ScreenIdentification screenIdentification;
  177. public o0.Project.ScreenIdentification ScreenIdentification => screenIdentification;
  178. RectTransform canvas;
  179. Mode mode;
  180. //List<(Vector2 pos, GameObject go)> pointManual = new List<(Vector2, GameObject)>();
  181. //o0.Project.WebCam o0WebCam = null;
  182. /// <summary>
  183. /// 正在识别的状态,自动识别时候记录
  184. /// </summary>
  185. bool bAutomaticRecognition { get; set; } = false;//进行捕获时
  186. bool bAutomaticRecognitionStart { get; set; } = false;//是否进行捕获
  187. bool bAutomaticRecognitionEnd { get; set; } = false;//是否结束捕获
  188. [NonSerialized] public RectTransform BackQuad = null;
  189. static public ScreenLocate Main { get; private set; }
  190. static public void AutoLightPixels(Color[] pixels, int width, int height)
  191. {
  192. if (Main.DebugOnZIMDemo)
  193. {
  194. var newTex = pixels.zimAutoLightSimple(width, height);
  195. DebugTexture(7, newTex);
  196. try
  197. {
  198. Main.FullScreenImage.texture = newTex;
  199. }
  200. catch { }
  201. }
  202. }
  203. static public void DebugTexture(int index, Texture2D texture)
  204. {
  205. LateDestory(Main.outputTexture2D[index]);
  206. Main.outputTexture2D[index] = texture;
  207. try
  208. {
  209. Main.outputRawImages[index].texture = texture;
  210. }
  211. catch { }
  212. }
  213. static void LateDestory(UnityEngine.Object o) => Main.StartCoroutine(Main.LateDestoryIEnum(o));
  214. static public void SetScreen(UnityEngine.Color? color = null)
  215. {
  216. if (Main.BackQuad == null)
  217. {
  218. var canvas = GameObject.Find("WebCameraView").GetComponent<RectTransform>();
  219. var background = canvas.Find("Background");
  220. Main.BackQuad = background.GetChild(0).GetComponent<RectTransform>();
  221. }
  222. Main.BackQuad.parent.gameObject.SetActive(color != null);
  223. Main.BackQuad.GetComponent<RawImage>().color = color ?? Color.black;
  224. //Debug.Log("Set Screen " + color.GetColorName());
  225. }
  226. static public void SetScreen(Rect rect, UnityEngine.Color? color = null)
  227. {
  228. if (Main.BackQuad == null)
  229. {
  230. var canvas = GameObject.Find("WebCameraView").GetComponent<RectTransform>();
  231. var background = canvas.Find("Background");
  232. Main.BackQuad = background.GetChild(0).GetComponent<RectTransform>();
  233. }
  234. Main.BackQuad.parent.gameObject.SetActive(color != null);
  235. Main.BackQuad.anchorMin = rect.min;
  236. Main.BackQuad.anchorMax = rect.max;
  237. Main.BackQuad.GetComponent<RawImage>().color = color ?? Color.black;
  238. //Debug.Log("Set Screen " + color.GetColorName());
  239. }
  240. static void DebugBackQuad(Rect? rect = null)
  241. {
  242. if (Main.BackQuad)
  243. {
  244. Main.BackQuad.parent.GetComponent<RawImage>().enabled = false;
  245. Main.BackQuad.GetComponent<RawImage>().color = Color.white;
  246. Main.BackQuad.parent.gameObject.SetActive(!Main.BackQuad.parent.gameObject.activeSelf);
  247. if (rect.HasValue)
  248. {
  249. Main.BackQuad.anchorMin = rect.Value.min;
  250. Main.BackQuad.anchorMax = rect.Value.max;
  251. }
  252. }
  253. }
  254. //public void ReSizeTexture(int width, int height)
  255. //{
  256. // Debug.Log("Cur mUVCTexture Size: [" + mUVCTexture.width + "," + mUVCTexture.height + "]");
  257. // if (mUVCTexture.width < width || mUVCTexture.height < height) // 如果当前分辨率太小,则重新new一个texture
  258. // {
  259. // Texture2D tex = new Texture2D(
  260. // width, height,
  261. // TextureFormat.ARGB32,
  262. // false, /* mipmap */
  263. // true /* linear */);
  264. // tex.filterMode = FilterMode.Point;
  265. // tex.Apply();
  266. // mUVCTexture = tex;
  267. // mUVCCameraInfo.previewTexture = tex;
  268. // var nativeTexPtr = mUVCCameraInfo.previewTexture.GetNativeTexturePtr();
  269. // }
  270. //}
  271. void Awake()
  272. {
  273. if (Main != null)
  274. throw new Exception("[ScreenLocaer] 不允许多个实例");
  275. Main = this;
  276. #if !UNITY_EDITOR_WIN
  277. DebugOnZIMDemo = false;
  278. #endif
  279. //if (mUVCDrawer)
  280. // mUVCDrawer.StartPreviewAction += UVCIsReady;
  281. }
  282. void OnDestroy()
  283. {
  284. //if (mUVCDrawer)
  285. // mUVCDrawer.StartPreviewAction -= UVCIsReady;
  286. }
  287. void Start()
  288. {
  289. //mainContext = SynchronizationContext.Current;
  290. canvas = transform.GetComponent<RectTransform>();
  291. mode = Mode.InfraredLocate;
  292. if (DebugScreenImages.Count != 0 && DebugOnZIMDemo)
  293. {
  294. screenIdentification = new o0.Project.ScreenIdentification(this);
  295. screenIdentification.LocateScreen();
  296. }
  297. ReDoLocateCalibrationRatio = 0.125f;
  298. #region 性能检测相关
  299. for (var i = 0; i < m_History.Capacity; ++i)
  300. {
  301. m_History.Add(0.0f);
  302. }
  303. lastInterval = Time.realtimeSinceStartup;
  304. frames = 0;
  305. #endregion
  306. }
  307. // 初始化算法
  308. void AlgorithmInit()
  309. {
  310. if (screenIdentification == null)
  311. {
  312. screenIdentification = new o0.Project.ScreenIdentification(this);
  313. Debug.Log("[ScreenLocate] 初始化屏幕识别");
  314. //screenIdentification.OnLocateScreenEnter += OnLocateScreenEnter;
  315. screenIdentification.OnLocateScreenEnd += OnLocateScreenEnd;
  316. //初始化屏幕数据
  317. InfraredCameraHelper.InitScreenLocateManual();
  318. }
  319. if (infraredLocate == null)
  320. {
  321. infraredLocate = new InfraredLocate(this, screenIdentification.Screen);
  322. cameraSize = new Vector(getUVCCameraInfoSize.x, getUVCCameraInfoSize.y);
  323. InfraredSpot.RefreshMinVerifyLength(new o0.Geometry2D.Float.Vector(getUVCCameraInfoSize.x, getUVCCameraInfoSize.y));
  324. Debug.Log($"[ScreenLocate] 初始化红外灯识别, 当前相机分辨率: {CameraSize.x}×{CameraSize.y},红外算法追踪距离: {InfraredSpot.MinVerifyLength}");
  325. //InfraredDemo 初始化
  326. //float redfilterValue = PlayerPrefs.GetFloat("Init redFilterSliderValue", 0.8f);
  327. //Debug.Log("Init Red filterValue:" + redfilterValue);
  328. //infraredLocate.SetBrightnessThreshold(redfilterValue); // 参数是 红外灯的亮度阈值,阈值越小能够检测到的亮度就越低,默认值是0.93
  329. // UI相关
  330. if (SingleToggle != null) {
  331. infraredLocate.SetSinglePoint(SingleToggle.isOn);
  332. SingleToggle.onValueChanged.AddListener((i) =>
  333. {
  334. infraredLocate.SetSinglePoint(i);
  335. });
  336. }
  337. }
  338. }
  339. IEnumerator LateDestoryIEnum(UnityEngine.Object o)
  340. {
  341. if (o)
  342. {
  343. yield return new WaitForEndOfFrame();
  344. Destroy(o);
  345. }
  346. }
  347. //ZIMWebCamera场景使用
  348. public void WebCamIsReady(Texture texture)
  349. {
  350. mPlatform = Platform.Window;
  351. mUVCTexture = texture;
  352. mUVCCameraInfo = new CameraInfo(mUVCTexture);
  353. brightness = 0;
  354. //UVC准备好
  355. InfraredCameraHelper?.InvokeOnUVCIsReady(mUVCCameraInfo);
  356. }
  357. /// <summary>
  358. /// UVCManager 创建初始化时候,更新此函数
  359. /// </summary>
  360. /// <param name="cameraInfo"></param>
  361. public void UVCIsReady(CameraInfo cameraInfo)
  362. {
  363. mPlatform = Platform.Android;
  364. mUVCTexture = cameraInfo.previewTexture;
  365. mUVCCameraInfo = cameraInfo;
  366. Debug.Log("UVCIsReady:" + mUVCCameraInfo);
  367. //UVC准备好
  368. InfraredCameraHelper?.InvokeOnUVCIsReady(mUVCCameraInfo);
  369. }
  370. /// <summary>
  371. /// 获取新的 previewTexture
  372. /// </summary>
  373. public void UVCUpdate(bool bChange)
  374. {
  375. mUVCTexture = mUVCCameraInfo.previewTexture;
  376. Debug.Log("[ScreenLocate] UVCUpdate:" + mUVCCameraInfo + ",bChange:" + bChange);
  377. InfraredCameraHelper?.InvokeOnUVCIsUpdate();
  378. //这里判断是否进入自动识别?
  379. if (bAutomaticRecognitionStart)
  380. {
  381. bAutomaticRecognitionStart = false;
  382. Debug.Log("[ScreenLocate] UVCUpdate 开始自动识别 Capture:" + Capture + " ,Delay: " + Delay);
  383. screenIdentification.LocateScreen(Capture, Delay);
  384. }
  385. if (bAutomaticRecognitionEnd)
  386. {
  387. bAutomaticRecognitionEnd = false;
  388. Debug.Log("[ScreenLocate] UVCUpdate 结束捕获,当前摄像机分辨率为: " + mUVCCameraInfo.Size);
  389. bAutomaticRecognition = false;
  390. }
  391. }
  392. /// <summary>
  393. /// 选择模式后更新 quadUnityVectorList
  394. /// </summary>
  395. public void UpdateQuadUnityVectorList()
  396. {
  397. quadUnityVectorList = screenIdentification.Screen.QuadInCamera.GetUnityVertexNormalizedList();
  398. SaveScreenLocateVectorList();
  399. }
  400. int brightness = 0;
  401. /// <summary>
  402. /// 设置算法红外灯的亮度值
  403. /// </summary>
  404. /// <param name="value"></param>
  405. public void SetInfraredLocateBrightnessThreshold(float value)
  406. {
  407. if (infraredLocate != null)
  408. infraredLocate.SetBrightnessThreshold(value); // 参数是 红外灯的亮度阈值,阈值越小能够检测到的亮度就越低,默认值是0.93
  409. }
  410. void Update()
  411. {
  412. //++frames;
  413. //float timeNow = Time.realtimeSinceStartup;
  414. //if (timeNow > lastInterval + updateInterval)
  415. //{
  416. // fps = (float)(frames / (timeNow - lastInterval));
  417. // frames = 0;
  418. // lastInterval = timeNow;
  419. //}
  420. //if (m_FPS != null)
  421. // m_FPS.text = "FPS:" + fps.ToString("f2");
  422. if (mUVCCameraInfo == null) return;
  423. AlgorithmInit();
  424. if (mUVCCameraInfo != null && mUVCCameraInfo.IsPreviewing)
  425. {
  426. //根据getUVCCameraInfoSize 分辨率渲染
  427. CreateUVCTexture2DIfNeeded((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  428. if (!screenIdentification.Update(mUVCTexture2D))
  429. {
  430. // 同步分辨率, 分辨率变化后还需同步到InfraredDemo
  431. if (RefreshCameraSize())
  432. {
  433. if (screenIdentification.Screen.QuadInCamera != null)
  434. {
  435. quadUnityVectorList = screenIdentification.Screen.QuadInCamera.GetUnityVertexNormalizedList();
  436. if (!ContainsNaN(quadUnityVectorList))
  437. {
  438. SaveScreenLocateVectorList();
  439. //SyncInfraredDemo();
  440. //SyncInfraredScreenPositioningView();
  441. InfraredCameraHelper?.InvokeOnUVCPosUpdate(quadUnityVectorList);
  442. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变:[" + (int)getUVCCameraInfoSize.x + "," + (int)getUVCCameraInfoSize.y + "]");
  443. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变,刷新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  444. }
  445. else
  446. {
  447. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  448. }
  449. }
  450. if (DebugOnZIMDemo)
  451. Main.ShowScreen(screenIdentification.Screen.QuadInCamera);
  452. }
  453. if (CameraSize.x != mUVCTexture2D.width || CameraSize.y != mUVCTexture2D.height)
  454. {
  455. Debug.Log($"<color=red>[ScreenLocate] 分辨率不匹配,相机分辨率为: {getUVCCameraInfoSize}, mUVCTexture2D纹理尺寸: {mUVCTexture2D.width}×{mUVCTexture2D.height}</color>");
  456. return;
  457. }
  458. // 获取像素,用于后续操作
  459. var pixels = mUVCTexture2D.GetPixels(); // 从左往右、从下往上
  460. AutoLightPixels(pixels, CameraWidth, CameraHeight);
  461. InfraredUpdate(pixels);
  462. if (mode == Mode.ScreenLocateManual)
  463. {
  464. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  465. {
  466. if (infraredSpotBuffer[i].CameraLocation != null)
  467. {
  468. // 检测到光点
  469. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(CameraSize, FullScreenImage.rectTransform.rect);
  470. CrosshairInCamera[i].gameObject.SetActive(true);
  471. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  472. }
  473. else
  474. CrosshairInCamera[i].gameObject.SetActive(false);
  475. }
  476. }
  477. else if (mode == Mode.InfraredLocate)
  478. {
  479. if (mPlatform == Platform.Window) //渲染ui上面的点。进入游戏可以隐藏
  480. {
  481. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  482. {
  483. if (infraredSpotBuffer[i].CameraLocation != null)
  484. {
  485. // 检测到光点
  486. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(CameraSize, outputRawImages[0].rectTransform.rect);
  487. CrosshairInCamera[i].gameObject.SetActive(true);
  488. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  489. }
  490. else
  491. CrosshairInCamera[i].gameObject.SetActive(false);
  492. }
  493. }
  494. //手机端使用 mPlatform == Platform.Android &&
  495. //通用,手机 和 PC
  496. if (infraredSpotBuffer.Length > 0)
  497. {
  498. int redIndex = 0;
  499. int greenIndex = 1;
  500. //仅仅第一个点显示(如果最大点出界了会闪烁)
  501. if (bSinglePoint)
  502. {
  503. redIndex = 0; //单点识别是,可以选择切换颜色
  504. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  505. {
  506. string str = "Single:";
  507. Info.text = str + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  508. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  509. onFilterPos(infraredSpotBuffer[redIndex].ScreenUV.Value);
  510. }
  511. }
  512. else
  513. {
  514. //雙點模式下選擇第一個點
  515. if (bIdentifyRed && !bIdentifyGreen)
  516. {
  517. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  518. {
  519. Info.text = "Red" + redIndex + ":" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  520. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  521. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  522. }
  523. else
  524. {
  525. Info.text = "未检测到红色最大点!";
  526. }
  527. }
  528. else if (!bIdentifyRed && bIdentifyGreen)
  529. {
  530. if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  531. {
  532. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  533. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  534. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  535. }
  536. else
  537. {
  538. Info.text = "未检测到绿色点!";
  539. }
  540. }
  541. else
  542. {
  543. //两个不选择和两个全选都跑识别两个点
  544. //自動切換 检测到光点
  545. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  546. {
  547. Info.text = "Red:" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  548. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  549. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  550. }
  551. else if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  552. {
  553. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  554. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  555. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  556. }
  557. else
  558. {
  559. Info.text = "未检测到点!";
  560. }
  561. }
  562. }
  563. }
  564. }
  565. else if (mode == Mode.ScreenMap && DebugOnZIMDemo)
  566. {
  567. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  568. {
  569. if (infraredSpotBuffer[i].ScreenUV != null)
  570. {
  571. // 检测到光点
  572. var posInCanvas = infraredSpotBuffer[i].ScreenUV.Value.pixelToLocalPosition_AnchorCenter(new Vector2(1, 1), canvas.rect);
  573. CrosshairInScreen[i].gameObject.SetActive(true);
  574. CrosshairInScreen[i].anchoredPosition = posInCanvas;
  575. }
  576. else
  577. CrosshairInScreen[i].gameObject.SetActive(false);
  578. }
  579. if (Input.GetKeyDown(KeyCode.Escape))
  580. ToMode(Mode.InfraredLocate);
  581. }
  582. }
  583. }
  584. //var t1 = Time.realtimeSinceStartup;
  585. //var dt = t1 - t0;
  586. //m_History[m_ValidHistoryFrames % m_History.Count] = dt;
  587. //++m_ValidHistoryFrames;
  588. //m_UIUpdateTimer += Time.deltaTime;
  589. //if (m_UIUpdateTimer >= m_UIUpdateInterval)
  590. //{
  591. // m_UIUpdateTimer = 0.0f;
  592. // if (m_ValidHistoryFrames >= m_History.Count)
  593. // {
  594. // m_ValidHistoryFrames = 0;
  595. // m_AverageTime = 0.0f;
  596. // m_MinTime = float.PositiveInfinity;
  597. // m_MaxTime = float.NegativeInfinity;
  598. // {
  599. // for (var i = 0; i < m_History.Count; i++)
  600. // {
  601. // var time = m_History[i];
  602. // m_AverageTime += time;
  603. // m_MinTime = Mathf.Min(m_MinTime, time);
  604. // m_MaxTime = Mathf.Max(m_MaxTime, time);
  605. // }
  606. // m_AverageTime /= m_History.Count;
  607. // }
  608. // {
  609. // m_History.Sort();
  610. // // Odd-length history?
  611. // if ((m_History.Count & 1) != 0)
  612. // {
  613. // m_MedianTime = m_History[m_History.Count / 2];
  614. // }
  615. // else
  616. // {
  617. // m_MedianTime = (m_History[m_History.Count / 2] + m_History[m_History.Count / 2 - 1]) / 2.0f;
  618. // }
  619. // }
  620. // }
  621. // var statistics = $"{m_History.Count} 帧样本:\naverage: {m_AverageTime * 1000.0f:F2}ms\nmedian: {m_MedianTime * 1000.0f:F2}ms\nmin: {m_MinTime * 1000.0f:F2}ms\nmax: {m_MaxTime * 1000.0f:F2}ms\n";
  622. // //Method: {m_Method} {UnityEngine.SceneManagement.SceneManager.GetActiveScene().name} |
  623. // if (m_UITime != null)
  624. // m_UITime.text = $"Cam: {mUVCCameraInfo.CurrentWidth}x{mUVCCameraInfo.CurrentHeight}{(mUVCTexture2D? ",T2D:" : "")}{(mUVCTexture2D? mUVCTexture2D.width+ "x" : "")}{(mUVCTexture2D ? mUVCTexture2D.height:"")} \nLast Frame: {dt * 1000.0f:F2}ms \n{statistics}";
  625. //}
  626. //UpdateInputs();
  627. if (DebugOnZIMDemo)
  628. {
  629. if (Input.GetKeyDown(KeyCode.Z))
  630. SelectScreenAfterLocate(ScreenIdentificationTag.Manual);
  631. if (Input.GetKeyDown(KeyCode.X))
  632. SelectScreenAfterLocate(ScreenIdentificationTag.SemiAuto);
  633. if (Input.GetKeyDown(KeyCode.C))
  634. SelectScreenAfterLocate(ScreenIdentificationTag.Auto);
  635. }
  636. }
  637. public void InfraredUpdate(Color[] cameraPixels)
  638. {
  639. infraredLocate.InfraredUpdate(cameraPixels);
  640. if (DebugOnZIMDemo)
  641. DebugPixelSpotArea(infraredLocate.DebugAreas);
  642. }
  643. private bool RefreshCameraSize()
  644. {
  645. var sizeNew = new Vector(getUVCCameraInfoSize.x, getUVCCameraInfoSize.y);
  646. var sizeNewFloat = getUVCCameraInfoSize.o0Vector();
  647. if (sizeNew != CameraSize || (screenIdentification?.Screen?.QuadInCamera != null && sizeNewFloat != screenIdentification.Screen.QuadInCamera.CameraSize))
  648. {
  649. Debug.Log($"<color=aqua>[ScreenLocate] 分辨率变化,刷新分辨率(from {CameraSize.x}×{CameraSize.y} to {sizeNew.x}×{sizeNew.y}), 是否有屏幕数据: {screenIdentification.Screen.QuadInCamera != null}, 是否有手动数据: {screenIdentification.QuadManual != null}</color>");
  650. // 同步相机分辨率
  651. cameraSize = sizeNew;
  652. screenIdentification.Screen.RefreshCameraSize(sizeNewFloat);
  653. screenIdentification.QuadAuto?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  654. screenIdentification.QuadManual?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  655. screenIdentification.QuadSemiAuto?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  656. InfraredSpot.RefreshMinVerifyLength(sizeNewFloat);
  657. return true;
  658. }
  659. return false;
  660. }
  661. Vector2 targetPos = Vector2.zero;
  662. Vector2 movePos = Vector2.zero;
  663. int moveSpeed = 20;
  664. public float filterDis = 3.0f;
  665. void onFilterPos(Vector2 _vector2Pos)
  666. {
  667. //主要用于模拟九轴时候的
  668. //添加一个偏移量,使得最后输出的准心是指向正中心
  669. Vector2 np = new Vector2((_vector2Pos.x - UVOffset.x) * Screen.width, (_vector2Pos.y - UVOffset.y) * Screen.height); //_vector2Pos.pixelToLocalPosition_AnchorCenter(Vector2.one, (transform as RectTransform).rect);
  670. if (Vector2.Distance(np, targetPos) >= filterDis)
  671. {
  672. targetPos = np;
  673. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(targetPos.x, targetPos.y, 0));
  674. //Vector2 np = new Vector2(uvCenterOffset.x * Screen.width, uvCenterOffset.y * Screen.height);
  675. //point -= np;
  676. InfraredCameraHelper?.InvokeOnPositionUpdate(targetPos);
  677. }
  678. //movePos = Vector3.Lerp(movePos, targetPos, Time.deltaTime * moveSpeed);
  679. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(movePos.x, movePos.y, 0));
  680. }
  681. Vector2[] _targetPoints2 = new Vector2[] { Vector2.zero, Vector2.zero };
  682. void onFilterPos2(Vector2 _vector2Pos, int index)
  683. {
  684. Vector2 np = new Vector2((_vector2Pos.x - UVOffset.x) * Screen.width, (_vector2Pos.y - UVOffset.y) * Screen.height);
  685. if (Vector2.Distance(np, _targetPoints2[index]) >= filterDis)
  686. {
  687. _targetPoints2[index] = np;
  688. InfraredCameraHelper?.InvokeOnPositionUpdate2(_targetPoints2[index], index);
  689. }
  690. }
  691. public void DebugPixelSpotArea(List<PixelSpotArea> areas)
  692. {
  693. if (areas!=null)
  694. {
  695. Info.transform.GetChild(0).GetComponent<Text>().text = $"areas.Count: {areas.Count}";
  696. PixelSpotArea a0 = null; // 表示最大半径的区域
  697. PixelSpotArea a1 = null; // 表示第二大半径的区域
  698. foreach (var a in areas)
  699. {
  700. if (a0 == null || a.Radius > a0.Radius)
  701. {
  702. a1 = a0; // 更新第二大为之前最大
  703. a0 = a; // 更新最大为当前的
  704. }
  705. else if (a1 == null || a.Radius > a1.Radius)
  706. {
  707. a1 = a; // 更新第二大
  708. }
  709. }
  710. Texture2D texture = new Texture2D(CameraWidth, CameraHeight);
  711. Color[] blackPixels = new Color[texture.width * texture.height];
  712. for (int i = 0; i < blackPixels.Length; i++)
  713. blackPixels[i] = Color.black;
  714. texture.SetPixels(blackPixels);
  715. if (a0 != null)
  716. {
  717. foreach (var p in a0.Pixels0)
  718. texture.SetPixel((int)p.x, (int)p.y, Color.yellow);
  719. foreach (var p in a0.Pixels1)
  720. texture.SetPixel((int)p.x, (int)p.y, Color.white);
  721. }
  722. if (a1 != null)
  723. {
  724. foreach (var p in a1.Pixels0)
  725. texture.SetPixel((int)p.x, (int)p.y, Color.green);
  726. foreach (var p in a1.Pixels1)
  727. texture.SetPixel((int)p.x, (int)p.y, Color.blue);
  728. }
  729. texture.Apply();
  730. DebugTexture(6, texture);
  731. }
  732. }
  733. #region 自动识别
  734. int Capture = 30;
  735. int Delay = 30;
  736. Vector2 EnterResolution;
  737. // int DefaultResolutionIndex;
  738. // readonly public int HighScreenLocateResolutionIndex = 2; // 自动识别时,摄像机分辨率固定为1280 * 720 ( 对应索引是2 )
  739. public void BtnScreenLocate()
  740. {
  741. if (DebugScreenImages.Count != 0)
  742. {
  743. //screenIdentification = new o0.Project.ScreenIdentification();
  744. cameraSize = new Vector(DebugScreenImages[0].width, DebugScreenImages[0].height);
  745. WebCamIsReady(DebugScreenImages[0]);
  746. CreateUVCTexture2DIfNeeded();
  747. }
  748. //Debug.Log("BtnScreenLocate Capture:" + Capture + " ,Delay: " + Delay);
  749. //screenIdentification.LocateScreen(Capture, Delay);
  750. OnLocateScreenEnter();
  751. }
  752. // bool log1 = false, log2 = false;
  753. public void OnLocateScreenEnter()
  754. {
  755. bAutomaticRecognition = true;
  756. bAutomaticRecognitionStart = true;
  757. ResetScreenIdentification();
  758. //DefaultResolutionIndex = InfraredDemoMain?.ResolutionIndex ?? 0; // 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  759. //HighScreenLocateResolutionIndex = InfraredDemoMain.getTextureToResolutionNewIndex(); // index = 0
  760. // Debug.Log("[ScreenLocate] 开始捕获 DefaultResolutionIndex:" + DefaultResolutionIndex + " ,HighScreenLocateResolutionIndex:" + HighScreenLocateResolutionIndex);
  761. // InfraredDemoMain?.SetResolutionNew(HighScreenLocateResolutionIndex);
  762. EnterResolution = mUVCCameraInfo.Size;// 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  763. Vector2 _HighResolution = mUVCCameraInfo.CurrentCalibrationResolution; //最高的分辨率
  764. Resize((int)_HighResolution.x, (int)_HighResolution.y);
  765. //CreateUVCTexture2DIfNeeded();
  766. // log1 = true;
  767. // log2 = true;
  768. screenIdentification.LocateScreen(); // 自动识别开始的入口
  769. if (DebugOnZIMDemo)
  770. {
  771. var webCam = GetComponent<ZIMWebCamera>();
  772. webCam.AdjustResolution(1920, 1080);
  773. mUVCCameraInfo.SetSize(webCam.webCamTexture.width, webCam.webCamTexture.height);
  774. }
  775. }
  776. /// <summary>
  777. /// 屏幕识别结束
  778. /// </summary>
  779. public void OnLocateScreenEnd()
  780. {
  781. bAutomaticRecognitionEnd = true;
  782. // 记录本次屏幕识别的分辨率(目前采用高分辨率做识别,识别结束后调回低分辨率)
  783. //InfraredDemoMain?.SetResolutionNew(DefaultResolutionIndex);
  784. Resize((int)EnterResolution.x, (int)EnterResolution.y);
  785. if (DebugOnZIMDemo)
  786. {
  787. var webCam = GetComponent<ZIMWebCamera>();
  788. GetComponent<ZIMWebCamera>().AdjustResolution((int)EnterResolution.x, (int)EnterResolution.y);
  789. mUVCCameraInfo.SetSize(webCam.webCamTexture.width, webCam.webCamTexture.height);
  790. }
  791. // 前面的数据ContainsNaN(quadUnityVectorList) 如果没处理到,这里再进行判断一次
  792. // 识别结束后,也要判断半自动数据,即P5?
  793. if (screenIdentification.QuadAuto == null && screenIdentification.QuadSemiAuto == null)
  794. {
  795. InfraredCameraHelper?.InvokeOnUVCPosUpdate(new List<Vector2>());
  796. Debug.LogError("[ScreenLocate] OnLocateScreenEnd 屏幕未识别");
  797. }
  798. }
  799. /**
  800. * 修改相机的实际分辨率
  801. */
  802. public void Resize(int width, int height)
  803. {
  804. if (mUVCCameraInfo == null) return;
  805. #if UNITY_ANDROID
  806. //发送修改指令给相机实际分辨率
  807. mUVCCameraInfo.SetCameraSize(width, height);
  808. #endif
  809. #if UNITY_STANDALONE_WIN
  810. // pc todo 看看怎么处理
  811. // ResizePC(width, height);
  812. #endif
  813. //mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  814. Debug.Log($"[ScreenLocate] 开始修改分辨率 mUVCCameraInfo origin:[{mUVCCameraInfo.CurrentWidth},{mUVCCameraInfo.CurrentHeight}]=>target:[{width},{height}]");
  815. // if (screenIdentification.isInitLocateScreen()) screenIdentification.bStartLocateScreen = true;
  816. }
  817. /// <summary>
  818. /// pc修改分辨率
  819. /// </summary>
  820. /// <param name="width"></param>
  821. /// <param name="height"></param>
  822. public void ResizePC(int width, int height)
  823. {
  824. if (mUVCCameraInfo == null) return;
  825. //if (screenIdentification.isInitLocateScreen()) screenIdentification.bStartLocateScreen = true;
  826. // PcWebCamera pcWebCamera = GetComponent<PcWebCamera>();
  827. // if(pcWebCamera.webCamTexture == null || !pcWebCamera.webCamTexture.isPlaying) return;
  828. //StartCoroutine(ResetWebCam(pcWebCamera, width, height));
  829. mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  830. Debug.Log("[ScreenLocate] Resize mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  831. }
  832. private System.Collections.IEnumerator ResetWebCam(PcWebCamera pcWebCamera, int newWidth, int newHeight)
  833. {
  834. WebCamTexture _webCamTexture = pcWebCamera.webCamTexture;
  835. // Stop the current WebCamTexture
  836. _webCamTexture.Stop();
  837. // Trigger OnWebCamStopped event
  838. // OnWebCamStopped?.Invoke();
  839. // Wait for a short time to ensure resources are released
  840. yield return new WaitForSeconds(0.5f);
  841. // Create a new WebCamTexture with the new dimensions
  842. _webCamTexture = new WebCamTexture(newWidth, newHeight);
  843. pcWebCamera.webCamTexture = _webCamTexture;
  844. mUVCTexture = _webCamTexture;
  845. // Restart the camera
  846. yield return StartCoroutine(StartWebCam(pcWebCamera));
  847. }
  848. private System.Collections.IEnumerator StartWebCam(PcWebCamera pcWebCamera)
  849. {
  850. WebCamTexture _webCamTexture = pcWebCamera.webCamTexture;
  851. _webCamTexture.Play();
  852. // Wait until the WebCamTexture is playing
  853. while (!_webCamTexture.isPlaying)
  854. {
  855. yield return null;
  856. }
  857. // Trigger OnWebCamStarted event
  858. //OnWebCamStarted?.Invoke();
  859. mUVCCameraInfo.SetSize(_webCamTexture.width, _webCamTexture.height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  860. Debug.Log("[ScreenLocate] ResizePc mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  861. // if(screenIdentification.isInitLocateScreen())screenIdentification.bStartLocateScreen = true;
  862. }
  863. #endregion
  864. public void BtnScreenMap()
  865. {
  866. ToMode(Mode.ScreenMap);
  867. }
  868. //进入手动定位屏幕
  869. public void BtnScreenLocateManual()
  870. {
  871. ToMode(Mode.ScreenLocateManual);
  872. }
  873. // 重置屏幕识别的数据
  874. public void ResetScreenIdentification()
  875. {
  876. screenIdentification.Screen.Active = false;
  877. }
  878. // threshold 的值是0-1,0代表最近,1代表最远
  879. public void SetReDoLocateCalibrationRatio(float threshold)
  880. {
  881. const float MIN = 0.02f;
  882. const float MAX = 0.32f;
  883. ReDoLocateCalibrationRatio = MIN + (MAX - MIN) * threshold;
  884. }
  885. /// <summary>
  886. /// 固定的顶点顺序: 左下,右下,左上,右上
  887. /// </summary>
  888. public static List<Vector2> quadUnityVectorList = new();
  889. /// <summary>
  890. /// 打印信息
  891. /// </summary>
  892. /// <param name="list">左下,右下,左上,右上</param>
  893. /// <returns></returns>
  894. public string PrintVector2List(List<Vector2> list)
  895. {
  896. if (screenIdentification == null || !screenIdentification.Screen.Active) return "[]";
  897. string result = "";
  898. if (list.Count == 4)
  899. {
  900. result = "左下" + list[0].ToString() + ",右下" + list[1].ToString() + ",左上" + list[2].ToString() + ",右上" + list[3].ToString();
  901. }
  902. else
  903. {
  904. result = "count != 4 error";
  905. }
  906. //foreach (Vector2 vector in list)
  907. //{
  908. // result += vector.ToString() + " ";
  909. //}
  910. //Debug.Log(result);
  911. return result;
  912. }
  913. /// <summary>
  914. /// 判断是否存在NaN
  915. /// </summary>
  916. /// <param name="vectors"></param>
  917. /// <returns></returns>
  918. public bool ContainsNaN(List<Vector2> vectors)
  919. {
  920. foreach (var v in vectors)
  921. {
  922. if (float.IsNaN(v.x) || float.IsNaN(v.y))
  923. {
  924. return true;
  925. }
  926. }
  927. return false;
  928. }
  929. // 标记屏幕的四个角, ScreenQuadObject 下挂了4个子节点用于标记
  930. public void ShowScreen(RectTransform ScreenQuadObject, QuadrilateralInCamera screen)
  931. {
  932. if (screen == null)
  933. {
  934. Info.text = "识别屏幕失败";
  935. return;
  936. }
  937. Info.text = "已识别到屏幕";
  938. //if (ScreenQuadObject && ScreenQuadObject.childCount >= 4)
  939. //{
  940. // ScreenQuadObject.gameObject.SetActive(true);
  941. // for (int i = 0; i < 4; i++)
  942. // {
  943. // if (DebugOnZIMDemo)
  944. // {
  945. // RectTransform t = ScreenQuadObject.GetChild(i) as RectTransform;
  946. // t.anchoredPosition = screen.Quad[i].pixelToLocalPosition_AnchorCenter(screen.CameraSize, ScreenQuadObject.rect);
  947. // }
  948. // }
  949. //}
  950. quadUnityVectorList = screen.GetUnityVertexNormalizedList(); // 记录四个点
  951. if (!ContainsNaN(quadUnityVectorList))
  952. {
  953. SaveScreenLocateVectorList();
  954. //SyncInfraredDemo();
  955. if (DebugOnZIMDemo)
  956. SyncInfraredScreenPositioningView();
  957. InfraredCameraHelper?.InvokeOnUVCPosUpdate(quadUnityVectorList);
  958. Debug.Log("[ScreenLocate] ShowScreen 已识别到屏幕,更新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  959. }
  960. else
  961. {
  962. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  963. }
  964. }
  965. public void ShowScreen(QuadrilateralInCamera screen) => ShowScreen(ScreenQuad, screen);
  966. /// <summary>
  967. /// 校准点位置存储到本地
  968. /// </summary>
  969. static public void SaveScreenLocateVectorList()
  970. {
  971. //string saveStr = string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")); //,{v.z}
  972. // 如果列表为空,保存空字符串或自定义标记
  973. string saveStr = quadUnityVectorList.Count > 0 ? string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")) : "";
  974. Debug.Log("SaveScreenLocateVectorList: " + saveStr);
  975. PlayerPrefs.SetString("ScreenLocateVectorList", saveStr);
  976. }
  977. /// <summary>
  978. /// 获取本地存储校准点位置
  979. /// </summary>
  980. static public bool GetScreenLocateVectorList()
  981. {
  982. string posListStr = PlayerPrefs.GetString("ScreenLocateVectorList", "");
  983. Debug.Log("GetScreenLocateVectorList:" + posListStr);
  984. if (!string.IsNullOrWhiteSpace(posListStr))
  985. {
  986. quadUnityVectorList.Clear();
  987. quadUnityVectorList = posListStr.Split(';')
  988. .Select(s =>
  989. {
  990. string[] parts = s.Split(',');
  991. return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
  992. })
  993. .ToList();
  994. return true;
  995. }
  996. else return false;
  997. }
  998. public void SetSinglePoint(bool value)=> infraredLocate.SetSinglePoint(value);
  999. public bool IsSinglePoint() => infraredLocate.IsSinglePoint();
  1000. public Vector2 AdjustPointsOffset(Vector2 inputPoint, string type = "CameraLocation") => infraredLocate.GetCenterOffset(inputPoint, type);
  1001. /// <summary>
  1002. /// 重置偏移量
  1003. /// </summary>
  1004. public void ResetPointsOffest() => infraredLocate.ResetCenterOffset();
  1005. /// <summary>
  1006. /// 初始化记录值
  1007. /// </summary>
  1008. /// <param name="inputPointOffset"></param>
  1009. /// <param name="type"></param>
  1010. /// <returns></returns>
  1011. public Vector2 SetPointsOffset(Vector2 inputPointOffset, string type = "CameraLocation")
  1012. {
  1013. // 计算从原始中心到输入点的偏移量
  1014. if (type == "CameraLocation")
  1015. {
  1016. OldCameraLocationOffset = CameraLocationOffset = inputPointOffset;
  1017. return CameraLocationOffset;
  1018. }
  1019. else
  1020. {
  1021. //ScreenUV
  1022. OldUVOffset = UVOffset = inputPointOffset;
  1023. return UVOffset;
  1024. }
  1025. }
  1026. /// <summary>
  1027. /// 撤销操作,
  1028. /// </summary>
  1029. public void RevokePointsOffest() {
  1030. CameraLocationOffset = OldCameraLocationOffset;
  1031. UVOffset = OldUVOffset;
  1032. }
  1033. /// <summary>
  1034. /// 这里计算一个偏移后的cameraLocatoin位置
  1035. /// </summary>
  1036. /// <param name="cameraLocatoin"></param>
  1037. /// <returns></returns>
  1038. public Vector2 GetOffsetCameraLocation(Vector2 cameraLocatoin)
  1039. {
  1040. return cameraLocatoin - CameraLocationOffset;
  1041. }
  1042. void ToMode(Mode mode)
  1043. {
  1044. if (this.mode == mode)
  1045. return;
  1046. if (mode == Mode.ScreenMap)
  1047. {
  1048. if (!screenIdentification.Screen.Active)
  1049. {
  1050. Info.text = "先定位屏幕";
  1051. return;
  1052. }
  1053. Info.text = "按ESC退出";
  1054. SetScreen(Color.black);
  1055. //Info.transform.SetAsLastSibling();
  1056. this.mode = Mode.ScreenMap;
  1057. }
  1058. else if (mode == Mode.InfraredLocate)
  1059. {
  1060. Info.text = screenIdentification.Screen.Active ? "已定位屏幕" : "定位屏幕失败";
  1061. //Info.text = "已识别到屏幕";
  1062. SetScreen(null);
  1063. foreach (var i in CrosshairInScreen)
  1064. i.gameObject.SetActive(false);
  1065. FullScreenImage.gameObject.SetActive(false);
  1066. ScreenPixelCheaker?.HideImage();
  1067. //Info.transform.SetSiblingIndex(transform.childCount - 4);
  1068. this.mode = Mode.InfraredLocate;
  1069. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  1070. Console.WriteLine($"{TAG} Mode.InfraredLocate:已识别到屏幕:{screenIdentification.Screen.Active}");
  1071. #endif
  1072. }
  1073. else if (mode == Mode.ScreenLocateManual)
  1074. {
  1075. Info.text = "左键单击屏幕 左下角";
  1076. FullScreenImage.gameObject.SetActive(true);
  1077. ScreenPixelCheaker?.ShowImage();
  1078. //Info.transform.SetSiblingIndex(transform.childCount - 1);
  1079. // var newTex = WebCamera.webCamTexture.AutoLight(10);
  1080. //DebugTexture(1, TextureToTexture2D(rawImage.texture));
  1081. CreateUVCTexture2DIfNeeded();
  1082. DebugTexture(7, mUVCTexture2D.zimAutoLight(brightness));
  1083. //mUVCTexture2DTemp = TextureToTexture2D(mUVCCameraInfo.previewTexture);
  1084. //DebugTexture(6, mUVCTexture2DTemp.zimAutoLight(brightness));
  1085. this.mode = Mode.ScreenLocateManual;
  1086. }
  1087. }
  1088. private Texture2D TextureToTexture2D(Texture texture, int width = 0, int height = 0)
  1089. {
  1090. if (width == 0)
  1091. width = texture.width;
  1092. if (height == 0)
  1093. height = texture.height;
  1094. Texture2D _texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
  1095. RenderTexture currentRT = RenderTexture.active;
  1096. RenderTexture renderTexture = RenderTexture.GetTemporary(
  1097. width,
  1098. height,
  1099. 0,
  1100. RenderTextureFormat.ARGB32,
  1101. RenderTextureReadWrite.Linear);
  1102. Graphics.Blit(texture, renderTexture);
  1103. RenderTexture.active = renderTexture;
  1104. _texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
  1105. _texture2D.Apply();
  1106. RenderTexture.active = currentRT;
  1107. RenderTexture.ReleaseTemporary(renderTexture);
  1108. return _texture2D;
  1109. }
  1110. //public void CreateUVCTexture2DFocusSizeIfNeeded(int width, int height)
  1111. //{
  1112. // if (mUVCTexture2D != null)
  1113. // Destroy(mUVCTexture2D);
  1114. // mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  1115. //}
  1116. /// <summary>
  1117. /// 使用默认的mUVCTexture宽高
  1118. /// </summary>
  1119. private void CreateUVCTexture2DIfNeeded()
  1120. {
  1121. if (mUVCTexture2D != null)
  1122. Destroy(mUVCTexture2D);
  1123. mUVCTexture2D = TextureToTexture2D(mUVCTexture);
  1124. }
  1125. /// <summary>
  1126. /// 根据宽高调整mUVCTexture2D
  1127. /// </summary>
  1128. /// <param name="width"></param>
  1129. /// <param name="height"></param>
  1130. private void CreateUVCTexture2DIfNeeded(int width = 0, int height = 0)
  1131. {
  1132. if (mUVCTexture2D != null)
  1133. Destroy(mUVCTexture2D);
  1134. mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  1135. }
  1136. #region DoubleButton
  1137. private DateTime m_firstTime;
  1138. private DateTime m_secondTime;
  1139. private void Press()
  1140. {
  1141. Debug.Log("进入手动定位");
  1142. BtnScreenLocateManual();
  1143. resetTime();
  1144. }
  1145. public void OnDoubleClick()
  1146. {
  1147. //超时重置
  1148. if (!m_firstTime.Equals(default(DateTime)))
  1149. {
  1150. var intervalTime = DateTime.Now - m_firstTime;
  1151. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  1152. if (milliSeconds >= 400)
  1153. resetTime();
  1154. }
  1155. // 按下按钮时对两次的时间进行记录
  1156. if (m_firstTime.Equals(default(DateTime)))
  1157. m_firstTime = DateTime.Now;
  1158. else
  1159. m_secondTime = DateTime.Now;
  1160. // 在第二次点击触发,时差小于400ms触发
  1161. if (!m_firstTime.Equals(default(DateTime)) && !m_secondTime.Equals(default(DateTime)))
  1162. {
  1163. var intervalTime = m_secondTime - m_firstTime;
  1164. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  1165. if (milliSeconds < 400)
  1166. Press();
  1167. else
  1168. resetTime();
  1169. }
  1170. }
  1171. private void resetTime()
  1172. {
  1173. m_firstTime = default(DateTime);
  1174. m_secondTime = default(DateTime);
  1175. }
  1176. #endregion
  1177. #region 性能检测相关
  1178. void InvalidateTimings()
  1179. {
  1180. m_ValidHistoryFrames = 0;
  1181. m_AverageTime = float.NaN;
  1182. m_MedianTime = float.NaN;
  1183. m_MinTime = float.NaN;
  1184. m_MaxTime = float.NaN;
  1185. }
  1186. void UpdateInputs()
  1187. {
  1188. //重置
  1189. if (Input.GetKeyDown(KeyCode.UpArrow))
  1190. {
  1191. InvalidateTimings();
  1192. }
  1193. }
  1194. #endregion
  1195. }