ScreenLocate.cs 59 KB

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