ScreenLocate.cs 63 KB

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