InfraredDemo.cs 67 KB

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