ScreenLocate.cs 39 KB

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