ScreenLocate.cs 48 KB

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