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