ScreenLocate.cs 62 KB

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