ScreenLocate.cs 47 KB

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