ScreenLocate.cs 54 KB

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