InfraredDemo.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using InfraredManager;
  6. using ZIM;
  7. using System.Linq;
  8. using SLAMUVC;
  9. using System;
  10. using SmartBowSDK;
  11. using ZIM.Unity;
  12. using o0InfraredLocate.ZIM;
  13. public class InfraredDemo : JCUnityLib.ViewBase
  14. {
  15. public static bool DebugInEditor = true;
  16. public static InfraredDemo _ins;
  17. [SerializeField]
  18. RectTransform canvasRectTransform;
  19. public Button mBtnSee;
  20. Reporter reporter;
  21. public Text FPSText;
  22. public static void Create()
  23. {
  24. if (_ins) return;
  25. GameObject o = Instantiate(Resources.Load<GameObject>("InfraredDemo"));
  26. DontDestroyOnLoad(o);
  27. _ins = o.GetComponent<InfraredDemo>();
  28. //添加一个父物体
  29. o.transform.SetParent(ViewMgr.Instance.transform.Find("1").transform);
  30. CanvasScaler canvasScaler = o.GetComponent<CanvasScaler>();
  31. if (canvasScaler != null)
  32. {
  33. Destroy(canvasScaler);
  34. }
  35. RectTransform rectTransform = o.GetComponent<RectTransform>();
  36. rectTransform.anchorMin = Vector2.zero; // 左下角对齐父级
  37. rectTransform.anchorMax = Vector2.one; // 右上角对齐父级
  38. rectTransform.offsetMin = Vector2.zero; // 移除左下角偏移
  39. rectTransform.offsetMax = Vector2.zero; // 移除右上角偏移
  40. rectTransform.localScale = Vector3.one; // 确保缩放为 1
  41. //直接初始化一次
  42. _ins.InitInfraredCamera();
  43. }
  44. void Start()
  45. {
  46. //生成一个控制台
  47. GameObject obj = UserPlayer.InitReturnLogReporter() as GameObject;
  48. if (obj != null) {
  49. reporter = obj.GetComponent<Reporter>();
  50. Application.logMessageReceived += HandleLog;
  51. // 模拟错误日志
  52. // Debug.LogError("Test Error: This is a simulated error message.");
  53. // 模拟异常日志
  54. // Debug.LogException(new System.Exception("Test Exception: This is a simulated exception."));
  55. }
  56. if (Application.platform != RuntimePlatform.WindowsEditor) DebugInEditor = false;
  57. SetVisiable(false);
  58. InitDebugScreenPoint();
  59. // gameObject.AddComponent<FPSTester>();
  60. if (CommonConfig.StandaloneModeOrPlatformB)
  61. {
  62. mBtnSee.gameObject.SetActive(false);
  63. }
  64. else {
  65. mBtnSee.interactable = false;
  66. mBtnSee.transform.Find("Text").GetComponent<Text>().text = TextAutoLanguage2.GetTextByKey("WaitingForInitialization"); // "等待初始化..";
  67. }
  68. //直接初始化一次
  69. //InitInfraredCamera();
  70. Debug.Log("[InfraredDemo] Start Function!");
  71. initToggle();
  72. initExport();
  73. InitFullScreen();
  74. #if UNITY_STANDALONE_WIN
  75. _calibrationFixedText.transform.parent.gameObject.SetActive(false);
  76. #endif
  77. }
  78. void OnDestroy()
  79. {
  80. if(reporter!= null) Application.logMessageReceived -= HandleLog;
  81. }
  82. void Update()
  83. {
  84. UpdateInfraredCamera();
  85. //UpdateDebugScreenPoint();
  86. if(reporter!=null) FPSText.text = "FPS:" + reporter.fps;
  87. }
  88. public void OnClick_See()
  89. {
  90. SetVisiable(!_visiable);
  91. }
  92. //初始化一次 initScreenLocateManual
  93. bool hasCalled = false;
  94. bool _visiable;
  95. void SetVisiable(bool value)
  96. {
  97. _visiable = value;
  98. transform.Find("Background").gameObject.SetActive(value);
  99. transform.Find("InfraredCamera").gameObject.SetActive(value);
  100. //如果是b端,控制这里按钮显示
  101. if (CommonConfig.StandaloneModeOrPlatformB)
  102. {
  103. mBtnSee.gameObject.SetActive(value);
  104. }
  105. updateBtnSee();
  106. Action<Text> onApplyToNext = (t) => {
  107. updateBtnSee();
  108. };
  109. mBtnSee.GetComponentInChildren<TextAutoLanguage2>().onApplyToNext += onApplyToNext;
  110. //if (value) InitInfraredCamera();
  111. //刷新翻译的Dropdown
  112. if (value) {
  113. UpdateLanguage();
  114. updateDropdownResolution2();
  115. }
  116. //if (!hasCalled && value)
  117. //{
  118. // hasCalled = true;
  119. // //如果本地有记录,初始化一次
  120. // StartCoroutine(initScreenLocateManual());
  121. // Debug.Log("[InfraredDemo] SetVisiable Function!");
  122. //}
  123. }
  124. void updateBtnSee() {
  125. mBtnSee.GetComponentInChildren<Text>().text = _visiable ? TextAutoLanguage2.GetTextByKey("HideInterface") : TextAutoLanguage2.GetTextByKey("DebugInfrared");//"隐藏界面" : "调试红外";
  126. }
  127. Text _spText;
  128. Vector2 _screenPoint;
  129. void InitDebugScreenPoint()
  130. {
  131. _spText = transform.Find("SPText").GetComponent<Text>();
  132. //_spText.gameObject.SetActive(DebugInEditor);
  133. _spText.gameObject.SetActive(false);
  134. }
  135. void UpdateDebugScreenPoint()
  136. {
  137. if (!DebugInEditor) return;
  138. if (infraredCameraHelper == null) return;
  139. _screenPoint.x = Mathf.Clamp(
  140. _screenPoint.x + Input.GetAxis("Horizontal") * Screen.width / 400f,
  141. 0, Screen.width);
  142. _screenPoint.y = Mathf.Clamp(
  143. _screenPoint.y + Input.GetAxis("Vertical") * Screen.height / 400f,
  144. 0, Screen.height);
  145. infraredCameraHelper.InvokeOnPositionUpdate(_screenPoint);
  146. _spText.text = _screenPoint.ToString();
  147. }
  148. #region 红外摄像
  149. [SerializeField] RawImage _cameraRender;
  150. [SerializeField] RawImage _cameraRender2;
  151. /// <summary>
  152. /// 测试texture
  153. /// </summary>
  154. public RawImage MyCameraRender2
  155. {
  156. get { return _cameraRender2; }
  157. set { _cameraRender2 = value; }
  158. }
  159. //[SerializeField] MaintainAspectRatio _MaintainAspectRatio;
  160. [SerializeField] List<RectTransform> _crosshairsInCamera;
  161. [SerializeField] Slider _sliderShakeFilter;
  162. [SerializeField] Button _btnReset;
  163. [SerializeField] Button _btnScreenLocateManual;
  164. [SerializeField] Button _btnScreenLocateManualAuto;
  165. [SerializeField] Slider _sliderCapture;
  166. [SerializeField] Slider _sliderDelay;
  167. [SerializeField] Dropdown _dropdownResolution;
  168. [SerializeField] Dropdown _dropdownResolution2;
  169. [SerializeField] Slider _sliderLineWidth;
  170. [SerializeField] Slider _fanWidth;
  171. //红外线阈值
  172. [SerializeField] Slider _infraredFilter;
  173. //调试UVC参数
  174. [SerializeField] GameObject _cameraParameterPanel;
  175. [SerializeField] Button _btnAdjusting;
  176. //野鸭选择
  177. [SerializeField] Dropdown _duckLevelDropdown;
  178. //Dictionary<string, ParamFloatValue> dUVCParameters = new Dictionary<string, ParamFloatValue>();
  179. //public ParamFloatValue brightness = new ParamFloatValue("ic_brightness", 1.0f);
  180. //public ParamFloatValue saturation = new ParamFloatValue("ic_saturation", 1.0f);
  181. //public ParamFloatValue contrast = new ParamFloatValue("ic_contrast", 1.0f);
  182. #if UNITY_ANDROID
  183. //初始化纹理-1280*720,index = 0
  184. // public ParamFloatValue resoution = new ParamFloatValue("ic_resoution2", 0);
  185. //摄像机分辨率 -320*240,index = 10
  186. public ParamFloatValue resoutionNew = new ParamFloatValue("ic_resoutionNew", 10);
  187. //摄像机分辨率 -只处理高低分辨率情况
  188. public ParamFloatValue resoution = new ParamFloatValue("ic_resoution", 0);
  189. //string[] resolutions = { "高分辨率", "低分辨率" };
  190. #endif
  191. //抖动过滤值 - 6.0
  192. public ParamFloatValue shakeFilterValue = new ParamFloatValue("ic_shakeFilterValue2", 6.0f);
  193. //亮度过滤阈值 - 0.8
  194. public ParamFloatValue infraredFileterValue = new ParamFloatValue("ic_infraredFileterValue", 0.8f);
  195. //准心的偏移值
  196. public ParamVector2Value cameraLocationValue = new ParamVector2Value("ic_cameraLocation", Vector2.zero);
  197. public ParamVector2Value screenUVValue = new ParamVector2Value("ic_screenUV", Vector2.zero);
  198. //线段宽度阈值
  199. public ParamFloatValue lineWidth = new ParamFloatValue("ic_lineWidth", 4.0f);
  200. //扇形宽度
  201. public ParamFloatValue fanWidth = new ParamFloatValue("ic_fanWidth", 90.0f);
  202. public ParamFloatValue captureValue = new ParamFloatValue("ic_captureValue", 30.0f);
  203. public ParamFloatValue delayValue = new ParamFloatValue("ic_delayValue", 30.0f);
  204. //红外准心,默认打开吧
  205. public ParamFloatValue crosshairValue = new ParamFloatValue("ic_crosshairValue", 1);
  206. //野鸭测试存储
  207. public ParamFloatValue duckHunterLevel = new ParamFloatValue("test_duckHunterLevelValue", 1);
  208. //存储滑块信息。camera
  209. public Dictionary<string ,ParamFloatValue> ParamFloatValueCameraSlider = new Dictionary<string, ParamFloatValue>();
  210. public static InfraredCameraHelper infraredCameraHelper;
  211. public static bool running { get => infraredCameraHelper != null; }
  212. private bool _inited;
  213. #region 参数控制
  214. public GameObject togglePrefab; // 拖入一个Toggle预设体
  215. public GameObject sliderPrefab; // 拖入一个Slider预设体
  216. public GameObject spawnPoint;
  217. //自动曝光
  218. bool bAutoAE = false;
  219. Toggle CTRLAEToggle;
  220. Slider CTRLAEABSSlider;
  221. string[] sliderNameArray = new string[]{
  222. "自动曝光模式",
  223. "曝光时间(绝对)",
  224. "亮度", //
  225. "对比度",
  226. "色调",
  227. "饱和度",
  228. "锐度",
  229. "伽玛",
  230. //"白平衡温度",
  231. //"白平衡分量",
  232. "背光补偿",
  233. "增益" };
  234. string[] sliderStrArray = new string[]{
  235. "CTRL_AE",
  236. "CTRL_AE_ABS",
  237. "PU_BRIGHTNESS",
  238. "PU_CONTRAST",
  239. "PU_HUE",
  240. "PU_SATURATION",
  241. "PU_SHARPNESS",
  242. "PU_GAMMA",
  243. //"PU_WB_TEMP",
  244. //"PU_WB_COMPO",
  245. "PU_BACKLIGHT",
  246. "PU_GAIN" };
  247. UVCManager.CameraInfo currentCameraInfo;
  248. //初始化相机参数
  249. public void initSlider(UVCManager.CameraInfo cameraInfo)
  250. {
  251. if (currentCameraInfo != null) return;
  252. currentCameraInfo = cameraInfo;
  253. string[] sliderNameArrayKey = new string[] {
  254. "AutoExposureMode", // "自动曝光模式"
  255. "ExposureTimeAbsolute", // "曝光时间(绝对)"
  256. "Brightness", // "亮度"
  257. "Contrast", // "对比度"
  258. "Hue", // "色调"
  259. "Saturation", // "饱和度"
  260. "Sharpness", // "锐度"
  261. "Gamma", // "伽玛"
  262. "BacklightCompensation", // "背光补偿"
  263. "Gain" // "增益"
  264. };
  265. for (int i = 0; i < sliderStrArray.Length; i++)
  266. {
  267. string typeStr = sliderStrArray[i];
  268. // UInt64 _VALUE = cameraInfo.GetTypeByName(typeStr);
  269. //不支持的,跳过
  270. bool bContains = cameraInfo.ContainsKey(typeStr);
  271. if (!bContains) continue;
  272. if (typeStr == "CTRL_AE")
  273. {
  274. //曝光Toggle
  275. GameObject toggleObject = Instantiate(togglePrefab, spawnPoint.transform);
  276. toggleObject.SetActive(true);
  277. toggleObject.name = typeStr;
  278. Text labelObj = toggleObject.transform.Find("Label").GetComponent<Text>();
  279. //labelObj.text = sliderNameArray[i];
  280. labelObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayKey[i]);
  281. Toggle toggle = toggleObject.GetComponent<Toggle>();
  282. CTRLAEToggle = toggle;
  283. UVCCtrlInfo _AEInfo = cameraInfo.GetInfo(typeStr);
  284. Debug.Log("UVCCtrlInfo:" + _AEInfo.ToString());
  285. int _currentValue = cameraInfo.GetValue(typeStr);
  286. bAutoAE = _currentValue == 8 ? true : false; //如果当前值是 8,则当前摄像机是自动曝光模式
  287. toggle.isOn = bAutoAE;
  288. //cameraInfo.SetValue(_VALUE, _currentValue!=8? 8:1);
  289. toggle.onValueChanged.AddListener((bool bValue) =>
  290. {
  291. //Debug.Log("Toggle value changed to: " + bValue + " from " + _VALUE);
  292. if (typeStr == "CTRL_AE")
  293. {
  294. //开关控制是否自动曝光
  295. bAutoAE = bValue;
  296. if (CTRLAEABSSlider) CTRLAEABSSlider.interactable = !bAutoAE;
  297. int _value = bValue ? 8 : 1;
  298. //Debug.Log("_value " + _value);
  299. cameraInfo.SetValue(typeStr, _value);
  300. }
  301. });
  302. }
  303. else
  304. {
  305. //其余使用slider
  306. GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
  307. sliderObject.SetActive(true);
  308. sliderObject.name = typeStr;
  309. Slider slider = sliderObject.GetComponent<Slider>();
  310. Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
  311. Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
  312. //titleTextObj.text = sliderNameArray[i];//类型名字
  313. titleTextObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayKey[i]);
  314. if (slider != null)
  315. {
  316. UVCCtrlInfo _UVCCtrlInfo = cameraInfo.GetInfo(typeStr);
  317. slider.minValue = _UVCCtrlInfo.min;
  318. slider.maxValue = _UVCCtrlInfo.max;
  319. slider.wholeNumbers = true;
  320. int _defValue = _UVCCtrlInfo.def;
  321. //指定默认值
  322. //5、UVC亮度 - 50
  323. //6、UVC对比度 - 50
  324. if (typeStr == "PU_BRIGHTNESS") {
  325. _defValue = 50;
  326. } else if (typeStr == "PU_CONTRAST") {
  327. _defValue = 50;
  328. }
  329. //记录一个typeStr类型的数据存储操作对象
  330. ParamFloatValue paramFloatValue = new ParamFloatValue("ic_uvc_" + typeStr, _defValue);
  331. ParamFloatValueCameraSlider.Add(typeStr, paramFloatValue);
  332. if (typeStr == "PU_BRIGHTNESS" || typeStr == "PU_CONTRAST")
  333. {
  334. //获取设置默认存储的值
  335. int _Value = (int)paramFloatValue.Get();
  336. cameraInfo.SetValue(typeStr, _Value);
  337. Debug.Log("[InfraredDemo] UVC 设置" + typeStr + "默认值:" + _Value);
  338. slider.value = _Value;
  339. textObj.text = _Value + "";
  340. }
  341. else {
  342. //获取设置当前值
  343. int _currentValue = cameraInfo.GetValue(typeStr);
  344. slider.value = _currentValue;
  345. textObj.text = _currentValue + "";
  346. }
  347. //如果是曝光slider
  348. if (typeStr == "CTRL_AE_ABS")
  349. {
  350. CTRLAEABSSlider = slider;
  351. slider.interactable = !bAutoAE;
  352. }
  353. slider.onValueChanged.AddListener((newValue) =>
  354. {
  355. var _value = Mathf.FloorToInt(newValue);
  356. textObj.text = _value + "";
  357. //Debug.Log("Slider value changed to: " + newValue + " from " + _VALUE);
  358. cameraInfo.SetValue(typeStr, _value);
  359. paramFloatValue.Set(_value);
  360. });
  361. }
  362. }
  363. }
  364. }
  365. public void OpenUVCPanel()
  366. {
  367. _cameraParameterPanel.SetActive(true);
  368. }
  369. public void CloseUVCPanel()
  370. {
  371. _cameraParameterPanel.SetActive(false);
  372. }
  373. public void onResetUVCData()
  374. {
  375. #if UNITY_ANDROID
  376. resetUVCData();
  377. #endif
  378. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  379. resetPCData();
  380. #endif
  381. }
  382. void resetUVCData() {
  383. if (currentCameraInfo == null) return;
  384. for (int i = 0; i < sliderStrArray.Length; i++)
  385. {
  386. string typeStr = sliderStrArray[i];
  387. // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  388. bool bContains = currentCameraInfo.ContainsKey(typeStr);
  389. if (!bContains) continue;
  390. if (typeStr == "CTRL_AE")
  391. {
  392. //toggle值不进行重置
  393. Debug.Log("CTRL_AE 不需要重置");
  394. }
  395. else if (typeStr == "CTRL_AE_ABS")
  396. {
  397. if (!bAutoAE)
  398. {
  399. //如果是手动曝光,重置值
  400. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  401. Slider slider = trans.GetComponent<Slider>();
  402. Text textObj = trans.Find("text").GetComponent<Text>();
  403. UVCCtrlInfo _AEInfo = currentCameraInfo.GetInfo(typeStr);
  404. //获取当前值
  405. int _currentValue = currentCameraInfo.GetValue(typeStr);
  406. Debug.Log("CTRL_AE_ABS:" + _currentValue + " = " + _AEInfo.def + " = " + ",bAutoAE:" + bAutoAE);
  407. textObj.text = _AEInfo.def + "";
  408. slider.value = _AEInfo.def;
  409. if (_AEInfo.def != _currentValue) currentCameraInfo.SetValue(typeStr, _AEInfo.def);
  410. }
  411. }
  412. else
  413. {
  414. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  415. Slider slider = trans.GetComponent<Slider>();
  416. Text textObj = trans.Find("text").GetComponent<Text>();
  417. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  418. ParamFloatValue paramFloatValue = ParamFloatValueCameraSlider.GetValueOrDefault(typeStr);
  419. //重置的值
  420. int _defValue = _UVCCtrlInfo.def;
  421. if (typeStr == "PU_BRIGHTNESS")
  422. {
  423. _defValue = (int)paramFloatValue.GetDefault();
  424. }
  425. else if (typeStr == "PU_CONTRAST")
  426. {
  427. _defValue = (int)paramFloatValue.GetDefault();
  428. }
  429. textObj.text = _defValue + "";
  430. slider.value = _defValue;
  431. //获取当前值
  432. int _currentValue = currentCameraInfo.GetValue(typeStr);
  433. //重置存储值
  434. paramFloatValue.Reset();
  435. //存储初始值,设置一次到UVC参数
  436. if (_defValue != _currentValue) currentCameraInfo.SetValue(typeStr, _defValue);
  437. }
  438. }
  439. }
  440. //windows 相机
  441. string[] sliderNameArrayPC = new string[]{
  442. "亮度",
  443. "对比度",};
  444. string[] sliderNameArrayPCKey = new string[]{
  445. "Brightness",
  446. "Contrast",};
  447. string[] sliderStrArrayPC = new string[]{
  448. "PU_BRIGHTNESS",
  449. "PU_CONTRAST"};
  450. //记录一个typeStr类型的数据存储操作对象
  451. ParamFloatValue pcBRIGHTNESS = new ParamFloatValue("ic_pc_PU_BRIGHTNESS", 0);
  452. ParamFloatValue pcCONTRAST = new ParamFloatValue("ic_pc_PU_CONTRAST", 0);
  453. public void initSliderPC()
  454. {
  455. for (int i = 0; i < sliderStrArrayPC.Length; i++)
  456. {
  457. string typeStr = sliderStrArrayPC[i];
  458. GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
  459. sliderObject.SetActive(true);
  460. sliderObject.name = typeStr;
  461. Slider slider = sliderObject.GetComponent<Slider>();
  462. Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
  463. Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
  464. //titleTextObj.text = TextAutoLanguage2.GetTextByKey(sliderNameArrayPCKey[i]);// sliderNameArrayPC[i];//类型名字
  465. titleTextObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayPCKey[i]);
  466. if (slider != null)
  467. {
  468. slider.minValue = -1;
  469. slider.maxValue = 1;
  470. //记录一个typeStr类型的数据存储操作对象
  471. if (typeStr == "PU_BRIGHTNESS")
  472. {
  473. //获取设置默认存储的值
  474. float _Value = pcBRIGHTNESS.Get();
  475. infraredCameraHelper.SetBrightness(_Value);
  476. Debug.Log("[InfraredDemo] PC 设置 PU_BRIGHTNESS:" + typeStr + "默认值:" + _Value);
  477. slider.value = _Value;
  478. textObj.text = _Value + "";
  479. slider.onValueChanged.AddListener((newValue) =>
  480. {
  481. var _value = newValue;
  482. textObj.text = _value + "";
  483. infraredCameraHelper.SetBrightness(_value);
  484. pcBRIGHTNESS.Set(_value);
  485. });
  486. }
  487. else if (typeStr == "PU_CONTRAST")
  488. {
  489. //获取设置默认存储的值
  490. float _Value = pcCONTRAST.Get();
  491. infraredCameraHelper.SetContrast(_Value);
  492. Debug.Log("[InfraredDemo] PC 设置 PU_CONTRAST:" + typeStr + "默认值:" + _Value);
  493. slider.value = _Value;
  494. textObj.text = _Value + "";
  495. slider.onValueChanged.AddListener((newValue) =>
  496. {
  497. var _value = newValue;
  498. textObj.text = _value + "";
  499. infraredCameraHelper.SetContrast(_value);
  500. pcCONTRAST.Set(_value);
  501. });
  502. }
  503. }
  504. }
  505. }
  506. void resetPCData() {
  507. for (int i = 0; i < sliderStrArrayPC.Length; i++)
  508. {
  509. string typeStr = sliderStrArrayPC[i];
  510. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  511. Slider slider = trans.GetComponent<Slider>();
  512. Text textObj = trans.Find("text").GetComponent<Text>();
  513. //重置的值
  514. int _defValue = 0;
  515. if (typeStr == "PU_BRIGHTNESS")
  516. {
  517. _defValue = 0;
  518. infraredCameraHelper.SetBrightness(_defValue);
  519. }
  520. else if (typeStr == "PU_CONTRAST")
  521. {
  522. _defValue = 0;
  523. infraredCameraHelper.SetContrast(_defValue);
  524. }
  525. textObj.text = _defValue + "";
  526. slider.value = _defValue;
  527. }
  528. }
  529. #endregion
  530. void InitInfraredCamera()
  531. {
  532. if (_inited) return;
  533. _inited = true;
  534. //SDK创建
  535. if (infraredCameraHelper == null)
  536. {
  537. infraredCameraHelper = InfraredCameraHelper.GetInstance();
  538. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  539. infraredCameraHelper.CreateToPc();
  540. #endif
  541. #if UNITY_ANDROID
  542. //开始时候设置一个默认分辨率
  543. Debug.Log("开始时候的分辨率下标:" + resoution.Get());
  544. Vector2 resoutionVec2 = SetDefByIndex((int)resoution.Get());
  545. infraredCameraHelper.Create((int)resoutionVec2.x, (int)resoutionVec2.y);
  546. #endif
  547. infraredCameraHelper.OnPositionUpdate += (Vector2 point) =>
  548. {
  549. if (Camera.main == null) return;
  550. Ray ray = Camera.main.ScreenPointToRay(point);
  551. Vector3 rayEndPoint = ray.GetPoint(200);
  552. Quaternion quat = Quaternion.LookRotation(rayEndPoint - Camera.main.transform.position);
  553. // 挑战场景中其相机的父级有旋转,需要换算
  554. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "GameChallenge")
  555. {
  556. quat = Quaternion.AngleAxis(-180, Vector3.up) * quat;
  557. }
  558. if (CameraToLook.ins != null) CameraToLook.ins.localRotation = quat;
  559. if (SB_EventSystem.ins) SB_EventSystem.ins.MoveSimulateMouseByInfrared(point);
  560. //移动目标游戏
  561. if (GeneratingTarget.gm != null) GeneratingTarget.gm.shootingEvent.OnPositionUpdate(point);
  562. };
  563. infraredCameraHelper.OnUVCIsReady += (UVCManager.CameraInfo camera) =>
  564. {
  565. //生成控制摄像机的参数滑条
  566. Debug.Log("初始化摄像机!");
  567. //可以操作按钮
  568. mBtnSee.interactable = true;
  569. //mBtnSee.transform.Find("Text").GetComponent<Text>().text = "调试红外";
  570. updateBtnSee();
  571. //延迟重新设置一次分辨率
  572. StartCoroutine(delayInitOhterInfo(camera));
  573. };
  574. //屏幕变化时候
  575. infraredCameraHelper.OnUVCPosUpdate += (list) =>
  576. {
  577. Debug.Log("OnUVCPosUpdate list.Count" + list.Count);
  578. SetLocatePointsToCameraRender(list, 1, 1);
  579. //InfraredScreenPositioningView 页面
  580. if (list.Count == 4)
  581. {
  582. FindObjectOfType<InfraredScreenPositioningView>()?.SyncScreenPosition();
  583. }
  584. else {
  585. FindObjectOfType<InfraredScreenPositioningView>()?.onReset();
  586. }
  587. };
  588. //算法准备事件
  589. infraredCameraHelper.OnScreenLocateIsReady += () =>
  590. {
  591. Debug.Log("OnScreenLocateIsReady.");
  592. //b端设置偏移值
  593. if (CommonConfig.StandaloneModeOrPlatformB)
  594. {
  595. InitCenterOffset();
  596. }
  597. };
  598. }
  599. }
  600. private void updateDropdownResolution2()
  601. {
  602. string[] resolutions = {
  603. TextAutoLanguage2.GetTextByKey("HighResolution"),
  604. TextAutoLanguage2.GetTextByKey("LowResolution")
  605. };
  606. // 清除默认选项
  607. _dropdownResolution2.ClearOptions();
  608. // 将分辨率字符串数组转换为 Dropdown 选项
  609. _dropdownResolution2.AddOptions(new List<string>(resolutions));
  610. }
  611. /// <summary>
  612. /// 初始化一些游戏配置
  613. /// </summary>
  614. /// <returns></returns>
  615. IEnumerator delayInitOhterInfo(UVCManager.CameraInfo camera) {
  616. //yield return new WaitForSeconds(1f);
  617. yield return new WaitForEndOfFrame();
  618. #if UNITY_ANDROID
  619. initSlider(camera);
  620. camera.GetResolutionsStrs();
  621. // 默认设置
  622. updateDropdownResolution2();
  623. int index = (int)resoution.Get();
  624. _dropdownResolution2.value = index;
  625. _dropdownResolution2.RefreshShownValue();
  626. // 处理 Dropdown 的选择变化
  627. _dropdownResolution2.onValueChanged.AddListener(index => { OnResolutionChanged(index); });
  628. #endif
  629. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  630. initSliderPC();
  631. //隐藏不需要的设置
  632. _btnAdjusting.transform.Find("Text").GetComponent<Text>().text = "调整PC参数";
  633. _dropdownResolution.gameObject.SetActive(false);
  634. _dropdownResolution2.gameObject.SetActive(false);
  635. #endif
  636. //震动阈值
  637. SetShakeFilterValue(shakeFilterValue.Get());
  638. _sliderShakeFilter.onValueChanged.AddListener(SetShakeFilterValue);
  639. //功能按钮
  640. //重置触发测试
  641. _btnReset.onClick.AddListener(OnClick_Reset);
  642. _btnScreenLocateManual.onClick.AddListener(OnClick_ScreenLocateManual);
  643. _btnScreenLocateManualAuto.onClick.AddListener(OnClick_ScreenLocateManualAuto);
  644. SetCaptureValue(captureValue.Get());
  645. _sliderCapture.onValueChanged.AddListener(SetCaptureValue);
  646. SetDelayValue(delayValue.Get());
  647. _sliderDelay.onValueChanged.AddListener(SetDelayValue);
  648. //绘制线段
  649. SetLineWidth(lineWidth.Get());
  650. _sliderLineWidth.onValueChanged.AddListener(SetLineWidth);
  651. SetFanWidth(fanWidth.Get());
  652. _fanWidth.onValueChanged.AddListener(SetFanWidth);
  653. //检测红外亮度阈值
  654. SetInfraredFilterValue(infraredFileterValue.Get());
  655. _infraredFilter.onValueChanged.AddListener(SetInfraredFilterValue);
  656. //野鸭设置初始关卡
  657. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  658. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  659. _duckLevelDropdown.onValueChanged.AddListener(SetDuckLevelTest);
  660. ////b端设置偏移值
  661. //if (CommonConfig.StandaloneModeOrPlatformB) {
  662. // InitCenterOffset();
  663. //}
  664. }
  665. /// <summary>
  666. /// 初始化时候获取设置和存储来控制显示准心
  667. /// </summary>
  668. /// <returns></returns>
  669. public bool bInitCrosshairShow() {
  670. return UserSettings.ins.openCrossHair && getCrosshairValue() == 1 ? true : false;
  671. }
  672. /// <summary>
  673. /// 获取弓箭准心存储值
  674. /// </summary>
  675. /// <returns></returns>
  676. public int getCrosshairValue() {
  677. return (int)crosshairValue.Get();
  678. }
  679. public void setCrosshairValue(bool bshow) {
  680. crosshairValue.Set(bshow ? 1 : 0);
  681. }
  682. public void onStartPreview()
  683. {
  684. infraredCameraHelper.onStartPreview();
  685. }
  686. public void onStopPreview()
  687. {
  688. infraredCameraHelper.onStopPreview();
  689. }
  690. /// <summary>
  691. /// 获取并且初始化一次记录点的数据
  692. /// </summary>
  693. /// <returns></returns>
  694. IEnumerator initScreenLocateManual()
  695. {
  696. yield return new WaitForSeconds(1f);
  697. infraredCameraHelper.InitScreenLocateManual();
  698. }
  699. IEnumerator RestartOrKillApp()
  700. {
  701. yield return new WaitForSeconds(0.3f);
  702. if (Application.isEditor) yield break;
  703. if (Application.platform == RuntimePlatform.Android)
  704. {
  705. using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  706. {
  707. const int kIntent_FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
  708. const int kIntent_FLAG_ACTIVITY_NEW_TASK = 0x10000000;
  709. var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  710. var pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
  711. var intent = pm.Call<AndroidJavaObject>("getLaunchIntentForPackage", Application.identifier);
  712. intent.Call<AndroidJavaObject>("setFlags", kIntent_FLAG_ACTIVITY_NEW_TASK | kIntent_FLAG_ACTIVITY_CLEAR_TASK);
  713. currentActivity.Call("startActivity", intent);
  714. currentActivity.Call("finish");
  715. var process = new AndroidJavaClass("android.os.Process");
  716. int pid = process.CallStatic<int>("myPid");
  717. process.CallStatic("killProcess", pid);
  718. }
  719. }
  720. else {
  721. // 获取当前应用程序的可执行文件路径
  722. string executablePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  723. // 重启应用程序
  724. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
  725. {
  726. FileName = executablePath,
  727. UseShellExecute = false
  728. };
  729. System.Diagnostics.Process.Start(startInfo);
  730. // 退出当前应用程序
  731. Application.Quit();
  732. };
  733. }
  734. void UpdateInfraredCamera()
  735. {
  736. if (!_visiable) return;
  737. if (!_inited) return;
  738. if (infraredCameraHelper == null) return;
  739. //渲染相机画面
  740. //_cameraRender.texture = infraredCameraHelper.GetCameraTexture();
  741. //_cameraRender.material = infraredCameraHelper.GetCameraMaterial();
  742. if (ScreenLocate.Main.getUVCTexture)
  743. {
  744. if (isFullscreen || ScreenLocate.Main.OutputTextures[4] == null)
  745. {
  746. if (_cameraRender.texture == null || ScreenLocate.Main.getUVCTexture.GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  747. _cameraRender.texture = ScreenLocate.Main.getUVCTexture;
  748. //ScreenLocate.Main.OutputTextures[4] == null 并且 摄像机缩小的情况下。显示适配线段
  749. if (!isFullscreen) SetAllToggle(true);
  750. }
  751. else if (ScreenLocate.Main.OutputTextures[4] != null)
  752. {
  753. //缩小的情况下。显示黑白色差的合成图
  754. if (_cameraRender.texture == null || ScreenLocate.Main.OutputTextures[4] != null && ScreenLocate.Main.OutputTextures[4].GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  755. _cameraRender.texture = ScreenLocate.Main.OutputTextures[4];
  756. //底图缩小的情况下。不显示适配线段,并且隐藏points
  757. if (!isFullscreen) {
  758. if (showPoints) {
  759. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  760. for (int i = 0; i < pointsTF2.childCount; i++)
  761. {
  762. Transform pointTF = pointsTF2.GetChild(i);
  763. pointTF.gameObject.SetActive(false);
  764. showPoints = false;
  765. }
  766. }
  767. SetAllToggle(false);
  768. }
  769. }
  770. //_cameraRender.SetNativeSize();
  771. // _MaintainAspectRatio.AdjustSize();
  772. }
  773. //在相机画面显示准心
  774. if (ScreenLocate.Main)
  775. {
  776. var _sl = ScreenLocate.Main;
  777. var buffer = _sl.infraredSpotBuffer;
  778. if (buffer != null)
  779. {
  780. for (int i = 0; i < buffer.Length; i++)
  781. {
  782. if (buffer[i].CameraLocation != null)
  783. {
  784. //添加一个偏移量,使得最后输出的准心是指向正中心
  785. Vector2 newPoint2 = _sl.GetOffsetCameraLocation(buffer[i].CameraLocation.Value);
  786. // 检测到光点
  787. var pos = newPoint2.pixelToLocalPosition_AnchorCenter(_sl.mUVCCameraInfo.Size, _cameraRender.rectTransform.rect);
  788. _crosshairsInCamera[i].gameObject.SetActive(true);
  789. _crosshairsInCamera[i].anchoredPosition = pos;
  790. }
  791. else
  792. _crosshairsInCamera[i].gameObject.SetActive(false);
  793. }
  794. }
  795. //渲染固定摄像机分辨率
  796. SetCalibrationFixedText(_sl.mUVCCameraInfo.CurrentCalibrationResolution);
  797. //渲染摄像机大小
  798. if (_sl.mUVCCameraInfo != null) SetCameraSizeText(_sl.mUVCCameraInfo.Size);
  799. //渲染摄像机识别点位置
  800. SetQuadUnityVectorListText(_sl.PrintVector2List(ScreenLocate.quadUnityVectorList));
  801. }
  802. }
  803. bool showPoints = false;
  804. public void SetLocatePointsToCameraRender(List<Vector2> points, float w, float h)
  805. {
  806. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  807. if (pointsTF2.childCount == points.Count)
  808. {
  809. Vector2 texSize = new Vector2(w, h);
  810. for (int i = 0; i < pointsTF2.childCount; i++)
  811. {
  812. Transform pointTF = pointsTF2.GetChild(i);
  813. Vector2 pos = points[i];
  814. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  815. pointTF.gameObject.SetActive(true);
  816. showPoints = true;
  817. }
  818. }
  819. else {
  820. for (int i = 0; i < pointsTF2.childCount; i++)
  821. {
  822. Transform pointTF = pointsTF2.GetChild(i);
  823. pointTF.gameObject.SetActive(false);
  824. showPoints = false;
  825. }
  826. }
  827. //绘制数据
  828. DrawTestLine();
  829. }
  830. #region 测试数据绘制
  831. [SerializeField] private Toggle curToggle;
  832. [SerializeField] private Toggle autoToggle; // 控制 AutoUILineGenerator 的 Toggle
  833. [SerializeField] private Toggle semiAutoToggle; // 控制 SemiAutoUILineGenerator 的 Toggle
  834. [SerializeField] private Toggle manualToggle; // 控制 ManualUILineGenerator 的 Toggle
  835. [SerializeField] LineGenerator CurUILineGenerator;//当前结果屏幕线条
  836. [SerializeField] LineGenerator AutoUILineGenerator;//第一个结果屏幕线条
  837. [SerializeField] LineGenerator SemiAutoUILineGenerator;//第二个结果屏幕线条
  838. [SerializeField] LineGenerator ManualUILineGenerator;//第三个结果屏幕线条
  839. [SerializeField] private Dropdown dropdown; // 引用场景中的 Dropdown 组件
  840. [SerializeField] RawImage _cameraRenderTest5;
  841. [SerializeField] RawImage _cameraRenderTest6;
  842. void DrawTestLine()
  843. {
  844. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  845. // 判断 texSize 是否为有效值
  846. if (texSize == Vector2.zero)
  847. {
  848. Debug.LogWarning("Texture size is zero, cannot proceed with line drawing.");
  849. return;
  850. }
  851. // 设置三个屏幕四边形和线条生成器
  852. QuadrilateralInCamera[] screenQuads = new QuadrilateralInCamera[] {
  853. ScreenLocate.Main.ScreenIdentification?.QuadAuto,
  854. ScreenLocate.Main.ScreenIdentification?.QuadSemiAuto,
  855. ScreenLocate.Main.ScreenIdentification?.QuadManual
  856. };
  857. LineGenerator[] lineGenerators = new LineGenerator[] {
  858. AutoUILineGenerator,
  859. SemiAutoUILineGenerator,
  860. ManualUILineGenerator
  861. };
  862. for (int i = 0; i < screenQuads.Length; i++)
  863. {
  864. if (screenQuads[i] == null)
  865. {
  866. Debug.LogWarning($"Screen quadrilateral {i} is null, skipping this line.");
  867. continue;
  868. }
  869. if (lineGenerators[i] == null)
  870. {
  871. Debug.LogWarning($"Line generator {i} is null, skipping this line.");
  872. continue;
  873. }
  874. lineGenerators[i].Points = ConvertQuadToPoints(screenQuads[i], texSize);
  875. }
  876. // 清除旧选项并填充新的选项
  877. dropdown.ClearOptions();
  878. List<string> options = new List<string>();
  879. //for (int i = 0; i < screenQuads.Length; i++)
  880. //{
  881. // options.Add($"Quad {i + 1}");
  882. //}
  883. //options.Add("自动识别");
  884. //options.Add("半自动识别");
  885. //options.Add("手动识别");
  886. options.Add(TextAutoLanguage2.GetTextByKey("AutoRecognition")); // "自动识别"
  887. options.Add(TextAutoLanguage2.GetTextByKey("SemiAutoRecognition")); // "半自动识别"
  888. options.Add(TextAutoLanguage2.GetTextByKey("ManualRecognition")); // "手动识别"
  889. dropdown.AddOptions(options);
  890. // 添加监听器来处理选择事件
  891. dropdown.onValueChanged.AddListener((index) => {
  892. OnDropdownValueChanged(index, screenQuads);
  893. });
  894. if (screenQuads[0] != null || screenQuads[1] != null)
  895. {
  896. Texture texImage6 = ScreenLocate.Main.OutputTextures[5];
  897. if (texImage6 != null) _cameraRenderTest6.texture = texImage6;
  898. }
  899. if (ScreenLocate.quadUnityVectorList.Count == 4) {
  900. //绘制白色线段
  901. var lo = new Vector2(-0.5f, -0.5f);
  902. CurUILineGenerator.Points = new Vector2[4] {
  903. 2 * (ScreenLocate.quadUnityVectorList[0] + lo),
  904. 2 * (ScreenLocate.quadUnityVectorList[1] + lo),
  905. 2 * (ScreenLocate.quadUnityVectorList[3] + lo),
  906. 2 * (ScreenLocate.quadUnityVectorList[2] + lo) };
  907. }
  908. }
  909. // 当下拉框选项更改时调用的方法
  910. private void OnDropdownValueChanged(int index, QuadrilateralInCamera[] screenQuads)
  911. {
  912. if (index >= 0 && index < screenQuads.Length)
  913. {
  914. if (screenQuads[index] != null)
  915. {
  916. QuadrilateralInCamera selectedQuad = screenQuads[index];
  917. Debug.Log($"Selected Quad {index + 1}: {selectedQuad}");
  918. CurUILineGenerator.Points = ConvertQuadToPoints(selectedQuad, ScreenLocate.Main.getUVCCameraInfoSize);
  919. }
  920. else
  921. {
  922. Debug.LogWarning($"Selected Quad {index + 1} is null.");
  923. }
  924. }
  925. else
  926. {
  927. Debug.LogWarning("所选索引超出范围!");
  928. }
  929. }
  930. /// <summary>
  931. /// 提取转换四边形的方法
  932. /// </summary>
  933. /// <param name="quad"></param>
  934. /// <param name="texSize"></param>
  935. /// <returns></returns>
  936. public Vector2[] ConvertQuadToPoints(QuadrilateralInCamera quad, Vector2 texSize)
  937. {
  938. if (quad == null || quad.Quad == null || quad.Quad.Count < 4)
  939. {
  940. Debug.LogWarning("Invalid quadrilateral data provided.");
  941. return new Vector2[0]; // 返回空数组以避免异常
  942. }
  943. Vector2 offset = new Vector2(-0.5f, -0.5f); // 假设 'lo' 是某个已定义的偏移量
  944. return new Vector2[4] {
  945. 2 * (new Vector2(quad.Quad[0].x / texSize.x, quad.Quad[0].y / texSize.y) + offset),
  946. 2 * (new Vector2(quad.Quad[1].x / texSize.x, quad.Quad[1].y / texSize.y) + offset),
  947. 2 * (new Vector2(quad.Quad[3].x / texSize.x, quad.Quad[3].y / texSize.y) + offset),
  948. 2 * (new Vector2(quad.Quad[2].x / texSize.x, quad.Quad[2].y / texSize.y) + offset)
  949. };
  950. }
  951. public Vector2[] ConvertPointsToCoordinates(Vector2[] points, Vector2 texSize, Vector2 pivot)
  952. {
  953. if (points == null || points.Length < 1)
  954. {
  955. Debug.LogWarning("Invalid point data provided.");
  956. return new Vector2[0]; // 返回空数组以避免异常
  957. }
  958. Vector2 offset = new Vector2(-0.5f, -0.5f); // 将坐标从中心对齐到左下角对齐
  959. List<Vector2> transformedPoints = new List<Vector2>();
  960. // 遍历所有传入的点进行转换
  961. foreach (var point in points)
  962. {
  963. // 转换每个点,考虑 texSize 和 pivot 偏移
  964. Vector2 transformedPoint = 2 * ((point / texSize) + offset + pivot);
  965. transformedPoints.Add(transformedPoint);
  966. }
  967. return transformedPoints.ToArray();
  968. }
  969. void initToggle()
  970. {
  971. // 监听 Toggle 值的变化
  972. if (curToggle != null)
  973. curToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(CurUILineGenerator, isOn));
  974. // 监听 Toggle 值的变化
  975. if (autoToggle != null)
  976. autoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(AutoUILineGenerator, isOn));
  977. if (semiAutoToggle != null)
  978. semiAutoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(SemiAutoUILineGenerator, isOn));
  979. if (manualToggle != null)
  980. manualToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(ManualUILineGenerator, isOn));
  981. }
  982. // 控制 LineGenerator 的启用/禁用
  983. private void ToggleLineGenerator(LineGenerator lineGenerator, bool isOn)
  984. {
  985. if (lineGenerator != null && lineGenerator.enabled != isOn)
  986. {
  987. lineGenerator.enabled = isOn;
  988. Debug.Log($"{lineGenerator.name} is now {(isOn ? "enabled" : "disabled")}");
  989. }
  990. }
  991. /// <summary>
  992. /// 设置全部显示
  993. /// </summary>
  994. /// <param name="value"></param>
  995. private void SetAllToggle(bool value) {
  996. ToggleLineGenerator(CurUILineGenerator, value);
  997. ToggleLineGenerator(AutoUILineGenerator, value);
  998. ToggleLineGenerator(SemiAutoUILineGenerator, value);
  999. ToggleLineGenerator(ManualUILineGenerator, value);
  1000. }
  1001. /// <summary>
  1002. /// 放大时候同步一次toggle
  1003. /// </summary>
  1004. private void SyncAllToggle()
  1005. {
  1006. ToggleLineGenerator(CurUILineGenerator, curToggle.isOn);
  1007. ToggleLineGenerator(AutoUILineGenerator, autoToggle.isOn);
  1008. ToggleLineGenerator(SemiAutoUILineGenerator, semiAutoToggle.isOn);
  1009. ToggleLineGenerator(ManualUILineGenerator, manualToggle.isOn);
  1010. }
  1011. // 下拉菜单用于显示纹理名称
  1012. public Dropdown textureDropdown;
  1013. // 按钮用于导出选中的纹理
  1014. public Button exportSelectedButton;
  1015. // 按钮用于导出所有纹理
  1016. public Button exportAllButton;
  1017. // 定义纹理名称
  1018. string[] textureNames;
  1019. /// <summary>
  1020. /// 更新一下菜单
  1021. /// </summary>
  1022. public void UpdateLanguage() {
  1023. string[] _textureNames = {
  1024. TextAutoLanguage2.GetTextByKey("ScreenAOriginal"), // "A屏幕原图"
  1025. TextAutoLanguage2.GetTextByKey("SemiAutoSegmentB"), // "B半自动识别线段"
  1026. TextAutoLanguage2.GetTextByKey("BlackWhiteContrastC"), // "C黑白色差"
  1027. TextAutoLanguage2.GetTextByKey("RecognitionResultD"), // "D识别结果"
  1028. TextAutoLanguage2.GetTextByKey("ColorContrastOverlayE"), // "E色差叠加识别结果"
  1029. TextAutoLanguage2.GetTextByKey("SemiAutoAlternativeF") // "F半自动备选线段"
  1030. };
  1031. textureNames = _textureNames;
  1032. // 设置下拉菜单的选项
  1033. textureDropdown.ClearOptions();
  1034. textureDropdown.AddOptions(new System.Collections.Generic.List<string>(textureNames));
  1035. }
  1036. void initExport() {
  1037. UpdateLanguage();
  1038. // 添加导出选中纹理的按钮点击事件
  1039. exportSelectedButton.onClick.AddListener(() => SaveTextureToLocal(textureDropdown.value));
  1040. // 添加导出所有纹理的按钮点击事件
  1041. exportAllButton.onClick.AddListener(SaveAllTexturesToLocal);
  1042. }
  1043. /// <summary>
  1044. /// 导出所有纹理
  1045. /// </summary>
  1046. public void SaveAllTexturesToLocal()
  1047. {
  1048. for (int i = 0; i < textureNames.Length; i++)
  1049. {
  1050. SaveTextureToLocal(i); // 调用之前定义的保存方法
  1051. }
  1052. }
  1053. /// <summary>
  1054. /// 导出图片
  1055. /// </summary>
  1056. /// <param name="index"></param>
  1057. public void SaveTextureToLocal(int index)
  1058. {
  1059. Texture2D[] outputTexture2D = ScreenLocate.Main.OutputTextures;
  1060. if (outputTexture2D == null || index >= outputTexture2D.Length || outputTexture2D[index] == null)
  1061. {
  1062. Debug.LogError("Invalid texture index or texture is null.index:"+ index);
  1063. return;
  1064. }
  1065. // 定义保存路径
  1066. string time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  1067. string baseName = $"{time}_Texture_{index}";
  1068. // 检查索引是否在命名数组内
  1069. string fileName = index < textureNames.Length ? textureNames[index] : $"Texture_{index}";
  1070. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1071. string path = System.IO.Path.Combine("/storage/emulated/0/Download", $"{baseName}_{fileName}.png"); //public
  1072. #else
  1073. string path = System.IO.Path.Combine(Application.persistentDataPath, $"{baseName}_{fileName}.png");
  1074. #endif
  1075. // 编码纹理为 PNG 格式
  1076. byte[] bytes = outputTexture2D[index].EncodeToPNG();
  1077. // 将字节写入文件
  1078. System.IO.File.WriteAllBytes(path, bytes);
  1079. Debug.Log($"Texture saved as: {path}");
  1080. }
  1081. //下面是处理对象放大缩小
  1082. public RectTransform cameraObj1; // 拖拽你的 CameraSize1 对象到此字段
  1083. public Button toggleButton; // 缩小时使用的按钮
  1084. private Vector2 originalSize;
  1085. private Vector2 originalAnchoredPosition; // 使用 anchoredPosition 代替 localPosition
  1086. private Vector2 originalAnchorMin;
  1087. private Vector2 originalAnchorMax;
  1088. private int originalSiblingIndex; // 保存初始的层级索引
  1089. private bool isFullscreen = false;
  1090. /// <summary>
  1091. /// 测试效果屏幕数据初始化
  1092. /// </summary>
  1093. void InitFullScreen() {
  1094. if (cameraObj1 != null)
  1095. {
  1096. // 保存初始大小、位置和层级索引
  1097. originalSize = cameraObj1.sizeDelta;
  1098. originalAnchoredPosition = cameraObj1.anchoredPosition;
  1099. originalAnchorMin = cameraObj1.anchorMin; // 记录初始 anchorMin
  1100. originalAnchorMax = cameraObj1.anchorMax; // 记录初始 anchorMax
  1101. originalSiblingIndex = cameraObj1.GetSiblingIndex();
  1102. // 为 cameraObj1 添加点击事件
  1103. cameraObj1.GetComponent<Button>().onClick.AddListener(ToggleFullscreen);
  1104. toggleButton.transform.parent.gameObject.SetActive(false);
  1105. }
  1106. if (toggleButton != null)
  1107. {
  1108. // 为按钮添加点击事件以恢复大小
  1109. toggleButton.onClick.AddListener(RestoreSize);
  1110. }
  1111. }
  1112. void ToggleFullscreen()
  1113. {
  1114. if (cameraObj1 == null) return;
  1115. if (!isFullscreen)
  1116. {
  1117. // 设置锚点为全屏,调整位置和偏移量
  1118. cameraObj1.anchorMin = Vector2.zero;
  1119. cameraObj1.anchorMax = Vector2.one;
  1120. cameraObj1.offsetMin = Vector2.zero;
  1121. cameraObj1.offsetMax = Vector2.zero;
  1122. cameraObj1.anchoredPosition = Vector3.zero;
  1123. cameraObj1.SetSiblingIndex(cameraObj1.parent.childCount - 1); // 设置为最上层
  1124. //刷新一次点
  1125. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1126. toggleButton.transform.parent.gameObject.SetActive(true);
  1127. isFullscreen = true;
  1128. //放大情况根据toggle来显示
  1129. SyncAllToggle();
  1130. }
  1131. }
  1132. void RestoreSize()
  1133. {
  1134. if (cameraObj1 == null || !isFullscreen) return;
  1135. // 恢复锚点和偏移量
  1136. cameraObj1.anchorMin = originalAnchorMin; // 使用在 Start() 中记录的初始锚点
  1137. cameraObj1.anchorMax = originalAnchorMax; // 使用在 Start() 中记录的初始锚点
  1138. cameraObj1.sizeDelta = originalSize;
  1139. cameraObj1.anchoredPosition = originalAnchoredPosition; // 恢复为初始 anchoredPosition
  1140. cameraObj1.SetSiblingIndex(originalSiblingIndex); // 恢复到原本的层级索引
  1141. //刷新一次点
  1142. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1143. toggleButton.transform.parent.gameObject.SetActive(false);
  1144. isFullscreen = false;
  1145. }
  1146. #endregion
  1147. public void SetLocatePointsToCameraRenderTest(List<Vector2> points, float w, float h)
  1148. {
  1149. Transform pointsTF2 = _cameraRender.transform.Find("PointsTest");
  1150. if (pointsTF2.childCount == points.Count)
  1151. {
  1152. Vector2 texSize = new Vector2(w, h);
  1153. for (int i = 0; i < pointsTF2.childCount; i++)
  1154. {
  1155. Transform pointTF = pointsTF2.GetChild(i);
  1156. Vector2 pos = points[i];
  1157. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  1158. pointTF.gameObject.SetActive(true);
  1159. }
  1160. }
  1161. else
  1162. {
  1163. for (int i = 0; i < pointsTF2.childCount; i++)
  1164. {
  1165. Transform pointTF = pointsTF2.GetChild(i);
  1166. pointTF.gameObject.SetActive(false);
  1167. }
  1168. }
  1169. }
  1170. void SetShakeFilterValue(float v)
  1171. {
  1172. shakeFilterValue.Set(v);
  1173. _sliderShakeFilter.SetValueWithoutNotify(shakeFilterValue.Get());
  1174. _sliderShakeFilter.transform.Find("Value").GetComponent<Text>().text = shakeFilterValue.Get().ToString("f1");
  1175. infraredCameraHelper.SetShakeFilterValue(shakeFilterValue.Get());
  1176. }
  1177. /// <summary>
  1178. /// 重新设置分辨率
  1179. /// </summary>
  1180. /// <param name="index"></param>
  1181. public void resolutionRestartApp(int index)
  1182. {
  1183. #if UNITY_ANDROID
  1184. //StartCoroutine(RestartOrKillApp());
  1185. //获取第一个分辨率设置后设置size
  1186. switch (index)
  1187. {
  1188. case 0:
  1189. infraredCameraHelper.SetHighCameraResolution();
  1190. resoution.Set(index);
  1191. _dropdownResolution2.SetValueWithoutNotify(index);
  1192. break;
  1193. case 1:
  1194. infraredCameraHelper.SetLowCameraResolution();
  1195. resoution.Set(index);
  1196. _dropdownResolution2.SetValueWithoutNotify(index);
  1197. break;
  1198. }
  1199. #endif
  1200. }
  1201. /// <summary>
  1202. /// 初始化时候,设置的值
  1203. /// </summary>
  1204. /// <param name="index"></param>
  1205. public Vector2 SetDefByIndex(int index = 0)
  1206. {
  1207. //SetResolutionNew 里面对应的下标
  1208. Vector2 vec2 = new Vector2(320, 240);
  1209. switch (index)
  1210. {
  1211. case 0:
  1212. vec2 = new Vector2(320, 240);
  1213. break;
  1214. case 1:
  1215. vec2 = new Vector2(160, 120);
  1216. break;
  1217. }
  1218. return vec2;
  1219. }
  1220. /// <summary>
  1221. /// 当 Dropdown 选择变化时的处理方法
  1222. /// </summary>
  1223. /// <param name="OnResolutionChanged">320x240</param>
  1224. private void OnResolutionChanged(int index)
  1225. {
  1226. #if UNITY_ANDROID
  1227. Debug.Log("Selected Resolution: " + index);
  1228. // 将选定的分辨率转换为实际的宽度和高度
  1229. // 并且需要判断是否存在最低分辨率
  1230. if (index == 1 && currentCameraInfo.ContainsResulutionKey("160x120"))
  1231. {
  1232. // 在这里你可以根据实际需要设置屏幕分辨率或进行其他操作
  1233. infraredCameraHelper.SetLowCameraResolution();
  1234. // 保存选择的分辨率到 PlayerPrefs
  1235. resoution.Set(index);
  1236. }
  1237. else if(index == 0){
  1238. //如果是0就 使用高分辨率
  1239. infraredCameraHelper.SetHighCameraResolution();
  1240. // 保存选择的分辨率到 PlayerPrefs
  1241. resoution.Set(index);
  1242. }
  1243. #endif
  1244. }
  1245. /// <summary>
  1246. /// 野鸭关卡测试初始值
  1247. /// </summary>
  1248. /// <param name="optionIndex"></param>
  1249. public void SetDuckLevelTest(int optionIndex)
  1250. {
  1251. //选择下标+1
  1252. int v = optionIndex + 1;
  1253. duckHunterLevel.Set(v);
  1254. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  1255. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  1256. //_duckLevelDropdown.transform.Find("Value").GetComponent<Text>().text = defLevel+"";
  1257. }
  1258. void OnClick_Reset()
  1259. {
  1260. //SetBrightness(1);
  1261. //SetSaturation(1);
  1262. //SetContrast(1);
  1263. SetShakeFilterValue(6);
  1264. SetLineWidth(4);
  1265. SetFanWidth(90);
  1266. SetInfraredFilterValue(0.8f);
  1267. SetCaptureValue(30.0f);
  1268. SetDelayValue(30.0f);
  1269. //重置为第一关
  1270. SetDuckLevelTest(0);
  1271. }
  1272. public void OnClickClearAll() {
  1273. PlayerPrefs.DeleteAll();
  1274. // 保存更改
  1275. PlayerPrefs.Save();
  1276. StartCoroutine(RestartOrKillApp());
  1277. }
  1278. void OnClick_ScreenLocateManual()
  1279. {
  1280. bool bEnter = true;
  1281. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1282. {
  1283. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1284. {
  1285. bEnter = true;
  1286. }
  1287. else
  1288. {
  1289. bEnter = false;
  1290. //只有红外设备才能进行屏幕识别
  1291. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1292. }
  1293. }
  1294. if (bEnter)
  1295. {
  1296. ViewManager2.ShowView(ViewManager2.Path_InfraredScreenPositioningView);
  1297. FindObjectOfType<InfraredScreenPositioningView>().enterFromInfraredDemo = true;
  1298. }
  1299. }
  1300. void OnClick_ScreenLocateManualAuto()
  1301. {
  1302. bool bEnter = true;
  1303. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1304. {
  1305. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1306. {
  1307. bEnter = true;
  1308. }
  1309. else
  1310. {
  1311. bEnter = false;
  1312. //只有红外设备才能进行屏幕识别
  1313. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1314. }
  1315. }
  1316. if (bEnter) {
  1317. ResetCenterOffset();
  1318. ResetPositioningData();
  1319. infraredCameraHelper.EnterScreenLocateManualAuto();
  1320. }
  1321. }
  1322. public void OnClick_SetAdjustPointsOffset()
  1323. {
  1324. var _sl = ScreenLocate.Main;
  1325. var buffer = _sl.infraredSpotBuffer;
  1326. if (buffer != null)
  1327. {
  1328. for (int i = 0; i < buffer.Length; i++)
  1329. {
  1330. if (buffer[i].CameraLocation != null)
  1331. {
  1332. Debug.Log("CameraLocation:"+buffer[i].CameraLocation.Value);
  1333. var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[i].CameraLocation.Value, "CameraLocation");
  1334. Debug.Log("CenterOffset: " + centerOffset);
  1335. cameraLocationValue.Set(centerOffset);
  1336. var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[i].ScreenUV.Value, "ScreenUV");
  1337. Debug.Log("UvCenterOffset: " + uvCenterOffset);
  1338. screenUVValue.Set(uvCenterOffset);
  1339. //如果是新手教程场景里面的校准
  1340. InfraredGuider infraredGuiderObj = FindObjectOfType<InfraredGuider>();
  1341. if (infraredGuiderObj != null)
  1342. {
  1343. GameObject infraredGuiderGameObject = infraredGuiderObj.gameObject;
  1344. infraredGuiderGameObject.GetComponent<InfraredGuider>().SetTitleAfterCalibration();
  1345. }
  1346. }
  1347. }
  1348. }
  1349. }
  1350. /// <summary>
  1351. /// 设置存储的中心偏移位置
  1352. /// </summary>
  1353. public void InitCenterOffset() {
  1354. infraredCameraHelper.SetCenterOffset(cameraLocationValue.Get(), "CameraLocation");
  1355. infraredCameraHelper.SetCenterOffset(screenUVValue.Get(), "ScreenUV");
  1356. }
  1357. /// <summary>
  1358. /// 重置中心点
  1359. /// </summary>
  1360. public void ResetCenterOffset() {
  1361. infraredCameraHelper.ResetCenterOffset();
  1362. }
  1363. /// <summary>
  1364. /// 撤销中心点
  1365. /// </summary>
  1366. public void RevokeCenterOffset()
  1367. {
  1368. infraredCameraHelper.RevokeCenterOffset();
  1369. }
  1370. /// <summary>
  1371. /// 重置定位数据
  1372. /// </summary>
  1373. public void ResetPositioningData(bool bSyncLocal = false) {
  1374. infraredCameraHelper.ClearInfraredPositioningData(bSyncLocal);
  1375. }
  1376. void SetCaptureValue(float v)
  1377. {
  1378. captureValue.Set(v);
  1379. _sliderCapture.SetValueWithoutNotify(captureValue.Get());
  1380. _sliderCapture.transform.Find("Value").GetComponent<Text>().text = captureValue.Get().ToString("f1");
  1381. infraredCameraHelper.SetCapture((int)captureValue.Get());
  1382. }
  1383. void SetDelayValue(float v)
  1384. {
  1385. delayValue.Set(v);
  1386. _sliderDelay.SetValueWithoutNotify(delayValue.Get());
  1387. _sliderDelay.transform.Find("Value").GetComponent<Text>().text = delayValue.Get().ToString("f1");
  1388. infraredCameraHelper.SetDelay((int)delayValue.Get());
  1389. }
  1390. #endregion
  1391. #region 相机感光度(默认修改对比度)
  1392. public void onSetSliderCustomValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1393. {
  1394. onSetSliderValue(_slider, "PU_CONTRAST", min, max);
  1395. }
  1396. public void onSliderCustomEvent(float value, float min = 0.0f, float max = 10.0f)
  1397. {
  1398. onSliderEvent(value, "PU_CONTRAST", min, max);
  1399. }
  1400. public void onSetSliderCustomBrightnessValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1401. {
  1402. onSetSliderValue(_slider, "PU_BRIGHTNESS", min, max);
  1403. }
  1404. public void onSliderCustomBrightnessEvent(float value, float min = 0.0f, float max = 10.0f)
  1405. {
  1406. onSliderEvent(value, "PU_BRIGHTNESS", min, max);
  1407. }
  1408. public void onSetSliderValue(Slider _slider,string typeStr = "PU_CONTRAST", float min = 0.0f, float max = 10.0f)
  1409. {
  1410. if (BluetoothWindows.IsWindows()) {
  1411. float v = typeStr == "PU_CONTRAST"?infraredCameraHelper.GetContrast(): infraredCameraHelper.GetBrightness();
  1412. // 目标区间 [0, 10] 的边界值
  1413. double targetMin = min;
  1414. double targetMax = max;
  1415. double originalMin = -1;
  1416. double originalMax = 1;
  1417. // 计算转换后的值
  1418. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1419. Debug.Log("PC获取相机的感光度 "+ typeStr + " :" + v + " = " + v2);
  1420. _slider.SetValueWithoutNotify((float)v2);
  1421. return;
  1422. }
  1423. //功能也改为UVC的对比度
  1424. if (running)
  1425. {
  1426. //string typeStr = "PU_CONTRAST";//"PU_BRIGHTNESS";
  1427. //UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1428. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1429. float v = currentCameraInfo.GetValue(typeStr); // infraredCameraHelper.GetBrightness();
  1430. //float v2 = (v / _UVCCtrlInfo.max) * 10;
  1431. // 目标区间 [0, 10] 的边界值
  1432. double targetMin = min;
  1433. double targetMax = max;
  1434. double originalMin = _UVCCtrlInfo.min;
  1435. double originalMax = _UVCCtrlInfo.max;
  1436. // 计算转换后的值
  1437. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1438. Debug.Log("获取相机的感光度" + typeStr + ": " + v + " = " + v2);
  1439. _slider.SetValueWithoutNotify((float)v2);
  1440. }
  1441. else _slider.SetValueWithoutNotify(5);
  1442. }
  1443. public void onSliderEvent(float value, string typeStr = "PU_CONTRAST", float min = 0.0f,float max = 10.0f)
  1444. {
  1445. // string typeStr = "PU_CONTRAST";// "PU_BRIGHTNESS";
  1446. //pc
  1447. if (BluetoothWindows.IsWindows())
  1448. {
  1449. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1450. Slider slider = trans.GetComponent<Slider>();
  1451. Text textObj = trans.Find("text").GetComponent<Text>();
  1452. // 原始区间和目标区间的边界值
  1453. double originalMin = min;
  1454. double originalMax = max;
  1455. double targetMin = -1;
  1456. double targetMax = 1;
  1457. // 计算转换后的值
  1458. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1459. float _current = (float)result;
  1460. //Debug.Log("_current:" + _current + " , result:" + result);
  1461. textObj.text = _current + "";
  1462. slider.value = _current;
  1463. if (typeStr == "PU_CONTRAST")
  1464. {
  1465. infraredCameraHelper.SetContrast(_current);
  1466. pcCONTRAST.Set(_current);
  1467. }
  1468. else {
  1469. infraredCameraHelper.SetBrightness(_current);
  1470. pcBRIGHTNESS.Set(_current);
  1471. }
  1472. return;
  1473. }
  1474. //修改亮度时,调试界面的亮度也应该一起修改
  1475. //功能也改为UVC的对比度
  1476. if (running)
  1477. {
  1478. //Slider slider = transform.Find("InfraredCamera/Layout/SliderBrightness")
  1479. // .GetComponent<Slider>();
  1480. // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1481. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1482. Slider slider = trans.GetComponent<Slider>();
  1483. Text textObj = trans.Find("text").GetComponent<Text>();
  1484. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1485. int _currentUVCValue = currentCameraInfo.GetValue(typeStr);
  1486. //value 0 ~ 10
  1487. // 原始区间和目标区间的边界值
  1488. double originalMin = min;
  1489. double originalMax = max;
  1490. double targetMin = _UVCCtrlInfo.min;
  1491. double targetMax = _UVCCtrlInfo.max;
  1492. // 计算转换后的值
  1493. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1494. int _current = (int)(result);
  1495. Debug.Log("_current:" + value + " , result:" + result);
  1496. textObj.text = _current + "";
  1497. slider.value = _current;
  1498. //dUVCParameters.GetValueOrDefault(typeStr).Set(_current);
  1499. //存储初始值,设置一次到UVC参数
  1500. if (_currentUVCValue != _current) currentCameraInfo.SetValue(typeStr, _current);
  1501. }
  1502. }
  1503. public static double MapValue(double value, double originalMin, double originalMax, double targetMin, double targetMax)
  1504. {
  1505. // 线性插值公式
  1506. return targetMin + (value - originalMin) * (targetMax - targetMin) / (originalMax - originalMin);
  1507. }
  1508. #endregion
  1509. #region 绘制线段部分
  1510. public void SetLineWidth(float v)
  1511. {
  1512. lineWidth.Set(v);
  1513. _sliderLineWidth.SetValueWithoutNotify(lineWidth.Get());
  1514. _sliderLineWidth.transform.Find("Value").GetComponent<Text>().text = lineWidth.Get().ToString("f1");
  1515. }
  1516. public void SetFanWidth(float v)
  1517. {
  1518. fanWidth.Set(v);
  1519. _fanWidth.SetValueWithoutNotify(fanWidth.Get());
  1520. _fanWidth.transform.Find("Value").GetComponent<Text>().text = fanWidth.Get().ToString("f1");
  1521. }
  1522. #endregion
  1523. #region 亮度检测部分
  1524. public void SetInfraredFilterValue(float v)
  1525. {
  1526. infraredFileterValue.Set(v);
  1527. _infraredFilter.SetValueWithoutNotify(infraredFileterValue.Get());
  1528. _infraredFilter.transform.Find("Value").GetComponent<Text>().text = infraredFileterValue.Get().ToString("f1");
  1529. infraredCameraHelper.SetInfraredLocateBrightnessThreshold(infraredFileterValue.Get());
  1530. }
  1531. #endregion
  1532. public void resetInfraredPlayerPrefs()
  1533. {
  1534. //测试用
  1535. PlayerPrefs.DeleteKey("entry-guider-infrared-" + LoginMgr.myUserInfo.id);
  1536. PlayerPrefs.DeleteKey("hideInfraredBowAndArrow");
  1537. }
  1538. #region 显示Log部分信息
  1539. [SerializeField] Text _calibrationFixedText;
  1540. [SerializeField] Text _cameraSizeText;
  1541. [SerializeField] Text _quadUnityVectorListText;
  1542. /// <summary>
  1543. /// 校准时候的固定值分辨率
  1544. /// </summary>
  1545. /// <param name="v"></param>
  1546. public void SetCalibrationFixedText(Vector2 v)
  1547. {
  1548. _calibrationFixedText.text = v.x + "*" + v.y;
  1549. }
  1550. /// <summary>
  1551. /// 渲染摄像机当前分辨率
  1552. /// </summary>
  1553. /// <param name="v"></param>
  1554. public void SetCameraSizeText(Vector2 v)
  1555. {
  1556. _cameraSizeText.text = v.x + "*" + v.y;
  1557. }
  1558. /// <summary>
  1559. /// 渲染摄像机识别点
  1560. /// </summary>
  1561. /// <param name="v"></param>
  1562. public void SetQuadUnityVectorListText(string v)
  1563. {
  1564. _quadUnityVectorListText.text = v;
  1565. }
  1566. #endregion
  1567. #region 错误日志
  1568. public void HandleLog(string logString, string stackTrace, LogType type)
  1569. {
  1570. if (type == LogType.Exception || type == LogType.Error)
  1571. {
  1572. SaveLogToFile(logString, stackTrace);
  1573. }
  1574. }
  1575. void SaveLogToFile(string message, string stackTrace)
  1576. {
  1577. string path;
  1578. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1579. // 保存到 Android 的公共 Download 文件夹,便于用户直接查看
  1580. path = System.IO.Path.Combine("/storage/emulated/0/Download", "crash_log.txt");
  1581. #else
  1582. // 其他平台使用 Application.persistentDataPath
  1583. path = System.IO.Path.Combine(Application.persistentDataPath, "crash_log.txt");
  1584. #endif
  1585. // 打印路径确认
  1586. Debug.Log($"Log file saved at: {path}");
  1587. // 将日志写入到指定路径的文件中
  1588. System.IO.File.AppendAllText(path, $"{message}\n{stackTrace}\n\n");
  1589. }
  1590. #endregion
  1591. }
  1592. public class ParamFloatValue
  1593. {
  1594. private string _saveKey;
  1595. private float _valueDefault;
  1596. private bool _valueLoaded;
  1597. private float _value;
  1598. public ParamFloatValue(string saveKey, float valueDefault)
  1599. {
  1600. _saveKey = saveKey;
  1601. _valueDefault = valueDefault;
  1602. }
  1603. public float Get()
  1604. {
  1605. if (!_valueLoaded) _value = PlayerPrefs.GetFloat(_saveKey, _valueDefault);
  1606. return _value;
  1607. }
  1608. public float GetDefault() {
  1609. return _valueDefault;
  1610. }
  1611. public string GetKey()
  1612. {
  1613. return _saveKey;
  1614. }
  1615. public void Set(float value)
  1616. {
  1617. _value = value;
  1618. PlayerPrefs.SetFloat(_saveKey, _value);
  1619. PlayerPrefs.Save();
  1620. }
  1621. /// <summary>
  1622. /// 重置成默认值
  1623. /// </summary>
  1624. public void Reset() {
  1625. PlayerPrefs.SetFloat(_saveKey, _valueDefault);
  1626. PlayerPrefs.Save();
  1627. }
  1628. }
  1629. /// <summary>
  1630. /// 存储Vector2
  1631. /// </summary>
  1632. public class ParamVector2Value
  1633. {
  1634. private string _saveKey;
  1635. private Vector2 _valueDefault;
  1636. private bool _valueLoaded;
  1637. private Vector2 _value;
  1638. public ParamVector2Value(string saveKey, Vector2 valueDefault)
  1639. {
  1640. _saveKey = saveKey;
  1641. _valueDefault = valueDefault;
  1642. }
  1643. public Vector2 Get()
  1644. {
  1645. if (!_valueLoaded)
  1646. {
  1647. float x = PlayerPrefs.GetFloat(_saveKey + "_x", _valueDefault.x);
  1648. float y = PlayerPrefs.GetFloat(_saveKey + "_y", _valueDefault.y);
  1649. _value = new Vector2(x, y);
  1650. _valueLoaded = true;
  1651. }
  1652. return _value;
  1653. }
  1654. public Vector2 GetDefault()
  1655. {
  1656. return _valueDefault;
  1657. }
  1658. public string GetKey()
  1659. {
  1660. return _saveKey;
  1661. }
  1662. public void Set(Vector2 value)
  1663. {
  1664. _value = value;
  1665. PlayerPrefs.SetFloat(_saveKey + "_x", _value.x);
  1666. PlayerPrefs.SetFloat(_saveKey + "_y", _value.y);
  1667. PlayerPrefs.Save();
  1668. }
  1669. /// <summary>
  1670. /// 重置成默认值
  1671. /// </summary>
  1672. public void Reset()
  1673. {
  1674. PlayerPrefs.SetFloat(_saveKey + "_x", _valueDefault.x);
  1675. PlayerPrefs.SetFloat(_saveKey + "_y", _valueDefault.y);
  1676. PlayerPrefs.Save();
  1677. }
  1678. }