ScreenLocate.cs 53 KB

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