ScreenLocate.cs 43 KB

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