ScreenLocate.cs 45 KB

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