ScreenLocate.cs 44 KB

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