ScreenLocate.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. #define ENABLE_LOG
  2. using Serenegiant.UVC;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using UnityEngine;
  7. using UnityEngine.UI;
  8. using ZIM;
  9. using static Serenegiant.UVC.UVCManager;
  10. using Color = UnityEngine.Color;
  11. [RequireComponent(typeof(Canvas))]
  12. public class ScreenLocate : MonoBehaviour
  13. {
  14. private const string TAG = "ScreenLocate#";
  15. enum Mode
  16. {
  17. InfraredLocate,
  18. ScreenMap,
  19. ScreenLocateManual
  20. }
  21. enum InfraredCount
  22. {
  23. Single,
  24. Double
  25. }
  26. enum Platform
  27. {
  28. Window,
  29. Android
  30. }
  31. Platform mPlatform = Platform.Android;
  32. // 2个灯,顺序根据红外灯的大小 由大到小, 坐标通过 InfraredSpot.ScreenUV 和 InfraredSpot.CameraLocation 获得
  33. public InfraredSpot[] InfraredSpots
  34. {
  35. get
  36. {
  37. infraredCount = InfraredCount.Double;
  38. return infraredSpotBuffer;
  39. }
  40. }
  41. // 1个灯, 坐标通过 InfraredSpot.ScreenUV 和 InfraredSpot.CameraLocation 获得
  42. public InfraredSpot InfraredSpotSingle
  43. {
  44. get
  45. {
  46. infraredCount = InfraredCount.Single;
  47. return infraredSpotBuffer[0];
  48. }
  49. }
  50. InfraredSpot[] infraredSpotBuffer;
  51. InfraredCount infraredCount;
  52. #region UVC 处理的对象
  53. public UVCManager mUVCManager;
  54. public UVCDrawer mUVCDrawer;
  55. public CameraInfo mUVCCameraInfo;
  56. private Texture mUVCTexture;
  57. private Texture2D mUVCTexture2D;
  58. // [SerializeField] Texture2DArray mUVCOutArray;
  59. #endregion
  60. public Text Info;
  61. public List<RectTransform> CrosshairInCamera;
  62. public List<RectTransform> CrosshairInScreen;
  63. public RectTransform ScreenQuad;
  64. public Toggle SaveToggle;
  65. public bool ShowScreenQuad = false;
  66. public RawImage rawImage;
  67. public RawImage rawImage1;
  68. public RawImage rawImage2;
  69. public RawImage rawImage3;
  70. public RawImage rawImage4;
  71. public RawImage rawImage5;
  72. public RawImage FullScreenImage;
  73. public InfraredSpotSettings InfraredSpotSettings;
  74. public Texture2D DebugScreenImage;
  75. public Button startUVCBtn;
  76. public Button manualDebugBtn;
  77. public InfraredManager.UIManagerSingle mUIManagerSingle;
  78. // private SynchronizationContext mainContext;
  79. //是否单点显示
  80. bool bSinglePoint = true;//默认单点识别
  81. public Toggle SinglePointToggle;
  82. bool bIdentifyRed = true;//默认设备红色
  83. public Toggle SinglePointToggleColor;
  84. InfraredLocate infraredLocate;
  85. RectTransform canvas;
  86. Mode mode;
  87. List<Vector2> pointManual = new List<Vector2>();
  88. //o0.Project.WebCam o0WebCam = null;
  89. o0.Project.ScreenIdentification screenIdentification;
  90. static public ScreenLocate Main;
  91. static public List<RawImage> DebugImage = new List<RawImage>();
  92. static public RectTransform BackQuad = null;
  93. static public void DebugTexture(int index, Texture texture)
  94. {
  95. Destroy(DebugImage[index].texture);
  96. DebugImage[index].texture = texture;
  97. }
  98. static public void SetScreen(UnityEngine.Color? color = null)
  99. {
  100. if (BackQuad == null)
  101. {
  102. var canvas = GameObject.Find("WebCameraView").GetComponent<RectTransform>();
  103. var background = canvas.Find("Background");
  104. BackQuad = background.GetChild(0).GetComponent<RectTransform>();
  105. }
  106. BackQuad.parent.gameObject.SetActive(color != null);
  107. BackQuad.GetComponent<RawImage>().color = color ?? Color.black;
  108. }
  109. static public void SetScreen(Rect rect, UnityEngine.Color? color = null)
  110. {
  111. if (BackQuad == null)
  112. {
  113. var canvas = GameObject.Find("WebCameraView").GetComponent<RectTransform>();
  114. var background = canvas.Find("Background");
  115. BackQuad = background.GetChild(0).GetComponent<RectTransform>();
  116. }
  117. BackQuad.parent.gameObject.SetActive(color != null);
  118. BackQuad.anchorMin = rect.min;
  119. BackQuad.anchorMax = rect.max;
  120. BackQuad.GetComponent<RawImage>().color = color ?? Color.black;
  121. }
  122. static void DebugBackQuad(Rect? rect = null)
  123. {
  124. if (BackQuad)
  125. {
  126. BackQuad.parent.GetComponent<RawImage>().enabled = false;
  127. BackQuad.GetComponent<RawImage>().color = Color.white;
  128. BackQuad.parent.gameObject.SetActive(!BackQuad.parent.gameObject.activeSelf);
  129. if (rect.HasValue)
  130. {
  131. BackQuad.anchorMin = rect.Value.min;
  132. BackQuad.anchorMax = rect.Value.max;
  133. }
  134. }
  135. }
  136. void Awake()
  137. {
  138. if (mUVCDrawer)
  139. mUVCDrawer.StartPreviewAction += UVCIsReady;
  140. }
  141. void OnDestroy()
  142. {
  143. if (mUVCDrawer)
  144. mUVCDrawer.StartPreviewAction -= UVCIsReady;
  145. }
  146. void Start()
  147. {
  148. //mainContext = SynchronizationContext.Current;
  149. Main = this;
  150. DebugImage.Add(rawImage);
  151. DebugImage.Add(rawImage1);
  152. DebugImage.Add(rawImage2);
  153. DebugImage.Add(rawImage3);
  154. DebugImage.Add(rawImage4);
  155. DebugImage.Add(rawImage5);
  156. DebugImage.Add(FullScreenImage);
  157. canvas = transform.GetComponent<RectTransform>();
  158. mode = Mode.InfraredLocate;
  159. infraredCount = InfraredCount.Single;
  160. if (SinglePointToggle)
  161. {
  162. //如果是单点显示
  163. bSinglePoint = PlayerPrefs.GetInt("bSinglePoint", 1) == 1;
  164. SinglePointToggle.isOn = bSinglePoint;
  165. }
  166. if (SinglePointToggleColor)
  167. {
  168. bIdentifyRed = PlayerPrefs.GetInt("bIdentifyRed", 1) == 1;
  169. SinglePointToggleColor.isOn = bIdentifyRed;
  170. }
  171. }
  172. //ZIMWebCamera场景使用
  173. public void WebCamIsReady(Texture texture)
  174. {
  175. mPlatform = Platform.Window;
  176. mUVCTexture = texture;
  177. mUVCCameraInfo = new CameraInfo(mUVCTexture);
  178. brightness = 0;
  179. }
  180. //手机端UVCCamra使用
  181. public void UVCIsReady(Texture texture)
  182. {
  183. mPlatform = Platform.Android;
  184. //this.startUVCBtn.interactable = true;
  185. mUVCTexture = texture;
  186. //ARGB32
  187. //mUVCTexture2D = Texture2D.CreateExternalTexture(texture.width, texture.height, TextureFormat.ARGB32, false, true, texture.GetNativeTexturePtr()); //TextureToTexture2D(texture);
  188. //Debug.Log("mUVCTexture2D isReable:" + mUVCTexture2D.isReadable);
  189. //Debug.Log("mUVCTexture2D mipmapCount:" + (mUVCTexture2D.mipmapCount > 1));
  190. List<CameraInfo> cameraInfos = mUVCManager.GetAttachedDevices();
  191. mUVCCameraInfo = cameraInfos[cameraInfos.Count - 1];
  192. manualDebugBtn.interactable = true;
  193. }
  194. public void OnChangeSinglePoint()
  195. {
  196. bSinglePoint = SinglePointToggle.isOn;
  197. PlayerPrefs.SetInt("bSinglePoint", bSinglePoint ? 1 : 0);
  198. }
  199. public void OnChangeSinglePointColor()
  200. {
  201. bIdentifyRed = SinglePointToggleColor.isOn;
  202. PlayerPrefs.SetInt("bIdentifyRed", bIdentifyRed ? 1 : 0);
  203. }
  204. public void startUVC()
  205. {
  206. }
  207. int brightness = 0;
  208. //public Text brightnessText;
  209. //public void SliderBrightness(Slider slider)
  210. //{
  211. // var _value = slider.value;
  212. // brightness = (int)_value;
  213. // brightnessText.text = (2 + brightness) + "";
  214. //}
  215. void Update()
  216. {
  217. if (mUVCCameraInfo == null) return;
  218. if (screenIdentification == null)
  219. screenIdentification = new o0.Project.ScreenIdentification(mUVCTexture);
  220. if (infraredLocate == null)
  221. infraredLocate = new InfraredLocate(mUVCCameraInfo, screenIdentification, InfraredSpotSettings);
  222. if (mode == Mode.ScreenLocateManual)
  223. {
  224. if (Input.GetMouseButtonDown(0))
  225. {
  226. var mouse = Input.mousePosition;
  227. var u = mouse.x / Screen.width;
  228. var v = mouse.y / Screen.height;
  229. u = Math.Clamp(u, 0, 1);
  230. v = Math.Clamp(v, 0, 1);
  231. pointManual.Add(new Vector2(u * mUVCTexture.width, v * mUVCTexture.height));
  232. var obj = Instantiate(Resources.Load("Point")) as GameObject;
  233. obj.transform.SetParent(FullScreenImage.transform);
  234. obj.transform.localPosition = new Vector2(u, v).pixelToLocalPosition_AnchorCenter(new Vector2(1, 1), FullScreenImage.rectTransform.rect);
  235. if (pointManual.Count == 1)
  236. Info.text = "左键单击屏幕 右下角";
  237. else if (pointManual.Count == 2)
  238. Info.text = "左键单击屏幕 右上角";
  239. else if (pointManual.Count == 3)
  240. Info.text = "左键单击屏幕 左上角";
  241. else if (pointManual.Count == 4)
  242. {
  243. screenIdentification.LocateScreenManual(new OrdinalQuadrilateral(pointManual[0].o0Vector(), pointManual[1].o0Vector(), pointManual[3].o0Vector(), pointManual[2].o0Vector()));
  244. pointManual.Clear();
  245. ShowScreen(screenIdentification.Screen.Quad);
  246. foreach (Transform i in FullScreenImage.transform)
  247. Destroy(i.gameObject);
  248. ToMode(Mode.InfraredLocate);
  249. }
  250. }
  251. return;
  252. }
  253. /* New*/
  254. if (mUVCCameraInfo != null && mUVCCameraInfo.IsPreviewing && screenIdentification.Screen.Active) // 成功定位屏幕后才做红外识别
  255. {
  256. CreateUVCTexture2DIfNeeded();
  257. if (!screenIdentification.Update(mUVCTexture2D))
  258. {
  259. if (mode == Mode.InfraredLocate)
  260. {
  261. //0,0, cameraTexture2D.width, cameraTexture2D.height,0
  262. var pixels = mUVCTexture2D.GetPixels(); // 从左往右、从下往上
  263. //InfraredSpots = infraredLocate.Update(pixels);
  264. if (bSinglePoint)
  265. infraredSpotBuffer = infraredLocate.UpdateSingle(pixels);
  266. else
  267. infraredSpotBuffer = infraredLocate.Update(pixels);
  268. if (mPlatform == Platform.Window || mUIManagerSingle.bGetPanelActive) //渲染ui上面的点。进入游戏可以隐藏
  269. {
  270. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  271. {
  272. if (infraredSpotBuffer[i].CameraLocation != null)
  273. {
  274. // 检测到光点
  275. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(mUVCCameraInfo.Size, rawImage.rectTransform.rect);
  276. CrosshairInCamera[i].gameObject.SetActive(true);
  277. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  278. }
  279. else
  280. CrosshairInCamera[i].gameObject.SetActive(false);
  281. }
  282. }
  283. //手机端使用
  284. if (mPlatform == Platform.Android && infraredSpotBuffer.Length > 0)
  285. {
  286. int redIndex = 0;
  287. int greenIndex = 1;
  288. //仅仅第一个点显示(如果最大点出界了会闪烁)
  289. if (bSinglePoint)
  290. {
  291. redIndex = 0; //单点识别是,可以选择切换颜色
  292. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  293. {
  294. string str = "Single:";
  295. Info.text = str + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  296. InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  297. }
  298. }
  299. else
  300. {
  301. // 检测到光点
  302. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  303. {
  304. Info.text = "Red:" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  305. InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  306. }
  307. else if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  308. {
  309. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  310. InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  311. }
  312. }
  313. }
  314. }
  315. }
  316. }
  317. }
  318. public void BtnScreenLocate()
  319. {
  320. screenIdentification.LocateScreen();
  321. }
  322. public void BtnScreenMap()
  323. {
  324. ToMode(Mode.ScreenMap);
  325. }
  326. //进入手动定位屏幕
  327. public void BtnScreenLocateManual()
  328. {
  329. ToMode(Mode.ScreenLocateManual);
  330. }
  331. // 标记屏幕的四个角
  332. public void ShowScreen(OrdinalQuadrilateral quad)
  333. {
  334. if (quad == null)
  335. {
  336. Info.text = "识别屏幕失败";
  337. return;
  338. }
  339. Info.text = "已识别到屏幕";
  340. if (ShowScreenQuad)
  341. {
  342. ScreenQuad.gameObject.SetActive(true);
  343. for (int i = 0; i < 4; i++)
  344. {
  345. RectTransform t = ScreenQuad.GetChild(i) as RectTransform;
  346. //mUVCCameraInfo.Size
  347. t.anchoredPosition = quad[i].UnityVector().pixelToLocalPosition_AnchorCenter(mUVCCameraInfo.Size, ScreenQuad.rect);
  348. }
  349. }
  350. }
  351. void ToMode(Mode mode)
  352. {
  353. if (this.mode == mode)
  354. return;
  355. if (mode == Mode.ScreenMap)
  356. {
  357. if (!screenIdentification.Screen.Active)
  358. {
  359. Info.text = "先定位屏幕";
  360. return;
  361. }
  362. Info.text = "按ESC退出";
  363. SetScreen(Color.black);
  364. Info.transform.SetAsLastSibling();
  365. this.mode = Mode.ScreenMap;
  366. }
  367. else if (mode == Mode.InfraredLocate)
  368. {
  369. Info.text = screenIdentification.Screen.Active ? "已定位屏幕" : "定位屏幕失败";
  370. //Info.text = "已识别到屏幕";
  371. SetScreen(null);
  372. foreach (var i in CrosshairInScreen)
  373. i.gameObject.SetActive(false);
  374. FullScreenImage.gameObject.SetActive(false);
  375. Info.transform.SetSiblingIndex(transform.childCount - 4);
  376. this.mode = Mode.InfraredLocate;
  377. DebugTexture(6, null);
  378. //DebugTexture(1, null); //null
  379. // rawImage1.texture = null;
  380. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  381. Console.WriteLine($"{TAG} Mode.InfraredLocate:已识别到屏幕:{ screenIdentification.Screen.Active}");
  382. #endif
  383. }
  384. else if (mode == Mode.ScreenLocateManual)
  385. {
  386. Info.text = "左键单击屏幕 左下角";
  387. FullScreenImage.gameObject.SetActive(true);
  388. Info.transform.SetSiblingIndex(transform.childCount - 1);
  389. // var newTex = WebCamera.webCamTexture.AutoLight(10);
  390. //DebugTexture(1, TextureToTexture2D(rawImage.texture));
  391. CreateUVCTexture2DIfNeeded();
  392. DebugTexture(6, mUVCTexture2D.zimAutoLight(brightness));
  393. //mUVCTexture2DTemp = TextureToTexture2D(mUVCCameraInfo.previewTexture);
  394. //DebugTexture(6, mUVCTexture2DTemp.zimAutoLight(brightness));
  395. this.mode = Mode.ScreenLocateManual;
  396. }
  397. }
  398. private Texture2D TextureToTexture2D(Texture texture)
  399. {
  400. Texture2D _texture2D = new Texture2D(texture.width, texture.height, TextureFormat.ARGB32, false, true);
  401. RenderTexture currentRT = RenderTexture.active;
  402. RenderTexture renderTexture = RenderTexture.GetTemporary(
  403. texture.width,
  404. texture.height,
  405. 0,
  406. RenderTextureFormat.ARGB32,
  407. RenderTextureReadWrite.Linear);
  408. Graphics.Blit(texture, renderTexture);
  409. RenderTexture.active = renderTexture;
  410. _texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
  411. _texture2D.Apply();
  412. RenderTexture.active = currentRT;
  413. RenderTexture.ReleaseTemporary(renderTexture);
  414. return _texture2D;
  415. }
  416. private void CreateUVCTexture2DIfNeeded()
  417. {
  418. if (mUVCTexture2D != null)
  419. Destroy(mUVCTexture2D);
  420. mUVCTexture2D = TextureToTexture2D(mUVCTexture);
  421. }
  422. #region DoubleButton
  423. private DateTime m_firstTime;
  424. private DateTime m_secondTime;
  425. private void Press()
  426. {
  427. Debug.Log("进入手动定位");
  428. BtnScreenLocateManual();
  429. resetTime();
  430. }
  431. public void OnDoubleClick()
  432. {
  433. //超时重置
  434. if (!m_firstTime.Equals(default(DateTime)))
  435. {
  436. var intervalTime = DateTime.Now - m_firstTime;
  437. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  438. if (milliSeconds >= 400)
  439. resetTime();
  440. }
  441. // 按下按钮时对两次的时间进行记录
  442. if (m_firstTime.Equals(default(DateTime)))
  443. m_firstTime = DateTime.Now;
  444. else
  445. m_secondTime = DateTime.Now;
  446. // 在第二次点击触发,时差小于400ms触发
  447. if (!m_firstTime.Equals(default(DateTime)) && !m_secondTime.Equals(default(DateTime)))
  448. {
  449. var intervalTime = m_secondTime - m_firstTime;
  450. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  451. if (milliSeconds < 400)
  452. Press();
  453. else
  454. resetTime();
  455. }
  456. }
  457. private void resetTime()
  458. {
  459. m_firstTime = default(DateTime);
  460. m_secondTime = default(DateTime);
  461. }
  462. #endregion
  463. }