ScreenLocate.cs 53 KB

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