InfraredDemo.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  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. }
  590. private void updateDropdownResolution2()
  591. {
  592. string[] resolutions = {
  593. TextAutoLanguage2.GetTextByKey("HighResolution"),
  594. TextAutoLanguage2.GetTextByKey("LowResolution")
  595. };
  596. // 清除默认选项
  597. _dropdownResolution2.ClearOptions();
  598. // 将分辨率字符串数组转换为 Dropdown 选项
  599. _dropdownResolution2.AddOptions(new List<string>(resolutions));
  600. }
  601. /// <summary>
  602. /// 初始化一些游戏配置
  603. /// </summary>
  604. /// <returns></returns>
  605. IEnumerator delayInitOhterInfo(UVCManager.CameraInfo camera) {
  606. //yield return new WaitForSeconds(1f);
  607. yield return new WaitForEndOfFrame();
  608. #if UNITY_ANDROID
  609. initSlider(camera);
  610. camera.GetResolutionsStrs();
  611. // 默认设置
  612. updateDropdownResolution2();
  613. int index = (int)resoution.Get();
  614. _dropdownResolution2.value = index;
  615. _dropdownResolution2.RefreshShownValue();
  616. // 处理 Dropdown 的选择变化
  617. _dropdownResolution2.onValueChanged.AddListener(index => { OnResolutionChanged(index); });
  618. #endif
  619. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  620. initSliderPC();
  621. //隐藏不需要的设置
  622. _btnAdjusting.transform.Find("Text").GetComponent<Text>().text = "调整PC参数";
  623. _dropdownResolution.gameObject.SetActive(false);
  624. _dropdownResolution2.gameObject.SetActive(false);
  625. #endif
  626. //震动阈值
  627. SetShakeFilterValue(shakeFilterValue.Get());
  628. _sliderShakeFilter.onValueChanged.AddListener(SetShakeFilterValue);
  629. //功能按钮
  630. //重置触发测试
  631. _btnReset.onClick.AddListener(OnClick_Reset);
  632. _btnScreenLocateManual.onClick.AddListener(OnClick_ScreenLocateManual);
  633. _btnScreenLocateManualAuto.onClick.AddListener(OnClick_ScreenLocateManualAuto);
  634. SetCaptureValue(captureValue.Get());
  635. _sliderCapture.onValueChanged.AddListener(SetCaptureValue);
  636. SetDelayValue(delayValue.Get());
  637. _sliderDelay.onValueChanged.AddListener(SetDelayValue);
  638. //绘制线段
  639. SetLineWidth(lineWidth.Get());
  640. _sliderLineWidth.onValueChanged.AddListener(SetLineWidth);
  641. SetFanWidth(fanWidth.Get());
  642. _fanWidth.onValueChanged.AddListener(SetFanWidth);
  643. //检测红外亮度阈值
  644. SetInfraredFilterValue(infraredFileterValue.Get());
  645. _infraredFilter.onValueChanged.AddListener(SetInfraredFilterValue);
  646. //野鸭设置初始关卡
  647. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  648. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  649. _duckLevelDropdown.onValueChanged.AddListener(SetDuckLevelTest);
  650. //b端设置偏移值
  651. if (CommonConfig.StandaloneModeOrPlatformB) {
  652. InitCenterOffset();
  653. }
  654. }
  655. /// <summary>
  656. /// 初始化时候获取设置和存储来控制显示准心
  657. /// </summary>
  658. /// <returns></returns>
  659. public bool bInitCrosshairShow() {
  660. return UserSettings.ins.openCrossHair && getCrosshairValue() == 1 ? true : false;
  661. }
  662. /// <summary>
  663. /// 获取弓箭准心存储值
  664. /// </summary>
  665. /// <returns></returns>
  666. public int getCrosshairValue() {
  667. return (int)crosshairValue.Get();
  668. }
  669. public void setCrosshairValue(bool bshow) {
  670. crosshairValue.Set(bshow ? 1 : 0);
  671. }
  672. public void onStartPreview()
  673. {
  674. infraredCameraHelper.onStartPreview();
  675. }
  676. public void onStopPreview()
  677. {
  678. infraredCameraHelper.onStopPreview();
  679. }
  680. /// <summary>
  681. /// 获取并且初始化一次记录点的数据
  682. /// </summary>
  683. /// <returns></returns>
  684. IEnumerator initScreenLocateManual()
  685. {
  686. yield return new WaitForSeconds(1f);
  687. infraredCameraHelper.InitScreenLocateManual();
  688. }
  689. IEnumerator RestartOrKillApp()
  690. {
  691. yield return new WaitForSeconds(0.3f);
  692. if (Application.isEditor) yield break;
  693. if (Application.platform == RuntimePlatform.Android)
  694. {
  695. using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  696. {
  697. const int kIntent_FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
  698. const int kIntent_FLAG_ACTIVITY_NEW_TASK = 0x10000000;
  699. var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  700. var pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
  701. var intent = pm.Call<AndroidJavaObject>("getLaunchIntentForPackage", Application.identifier);
  702. intent.Call<AndroidJavaObject>("setFlags", kIntent_FLAG_ACTIVITY_NEW_TASK | kIntent_FLAG_ACTIVITY_CLEAR_TASK);
  703. currentActivity.Call("startActivity", intent);
  704. currentActivity.Call("finish");
  705. var process = new AndroidJavaClass("android.os.Process");
  706. int pid = process.CallStatic<int>("myPid");
  707. process.CallStatic("killProcess", pid);
  708. }
  709. }
  710. else {
  711. // 获取当前应用程序的可执行文件路径
  712. string executablePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  713. // 重启应用程序
  714. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
  715. {
  716. FileName = executablePath,
  717. UseShellExecute = false
  718. };
  719. System.Diagnostics.Process.Start(startInfo);
  720. // 退出当前应用程序
  721. Application.Quit();
  722. };
  723. }
  724. void UpdateInfraredCamera()
  725. {
  726. if (!_visiable) return;
  727. if (!_inited) return;
  728. if (infraredCameraHelper == null) return;
  729. //渲染相机画面
  730. //_cameraRender.texture = infraredCameraHelper.GetCameraTexture();
  731. //_cameraRender.material = infraredCameraHelper.GetCameraMaterial();
  732. if (ScreenLocate.Main.getUVCTexture)
  733. {
  734. if (isFullscreen || ScreenLocate.Main.OutputTextures[4] == null)
  735. {
  736. if (_cameraRender.texture == null || ScreenLocate.Main.getUVCTexture.GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  737. _cameraRender.texture = ScreenLocate.Main.getUVCTexture;
  738. //ScreenLocate.Main.OutputTextures[4] == null 并且 摄像机缩小的情况下。显示适配线段
  739. if (!isFullscreen) SetAllToggle(true);
  740. }
  741. else if (ScreenLocate.Main.OutputTextures[4] != null)
  742. {
  743. //缩小的情况下。显示黑白色差的合成图
  744. if (_cameraRender.texture == null || ScreenLocate.Main.OutputTextures[4] != null && ScreenLocate.Main.OutputTextures[4].GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  745. _cameraRender.texture = ScreenLocate.Main.OutputTextures[4];
  746. //底图缩小的情况下。不显示适配线段,并且隐藏points
  747. if (!isFullscreen) {
  748. if (showPoints) {
  749. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  750. for (int i = 0; i < pointsTF2.childCount; i++)
  751. {
  752. Transform pointTF = pointsTF2.GetChild(i);
  753. pointTF.gameObject.SetActive(false);
  754. showPoints = false;
  755. }
  756. }
  757. SetAllToggle(false);
  758. }
  759. }
  760. //_cameraRender.SetNativeSize();
  761. // _MaintainAspectRatio.AdjustSize();
  762. }
  763. //在相机画面显示准心
  764. if (ScreenLocate.Main)
  765. {
  766. var _sl = ScreenLocate.Main;
  767. var buffer = _sl.infraredSpotBuffer;
  768. if (buffer != null)
  769. {
  770. for (int i = 0; i < buffer.Length; i++)
  771. {
  772. if (buffer[i].CameraLocation != null)
  773. {
  774. //添加一个偏移量,使得最后输出的准心是指向正中心
  775. Vector2 newPoint2 = _sl.GetOffsetCameraLocation(buffer[i].CameraLocation.Value);
  776. // 检测到光点
  777. var pos = newPoint2.pixelToLocalPosition_AnchorCenter(_sl.mUVCCameraInfo.Size, _cameraRender.rectTransform.rect);
  778. _crosshairsInCamera[i].gameObject.SetActive(true);
  779. _crosshairsInCamera[i].anchoredPosition = pos;
  780. }
  781. else
  782. _crosshairsInCamera[i].gameObject.SetActive(false);
  783. }
  784. }
  785. //渲染固定摄像机分辨率
  786. SetCalibrationFixedText(_sl.mUVCCameraInfo.CurrentCalibrationResolution);
  787. //渲染摄像机大小
  788. if (_sl.mUVCCameraInfo != null) SetCameraSizeText(_sl.mUVCCameraInfo.Size);
  789. //渲染摄像机识别点位置
  790. SetQuadUnityVectorListText(_sl.PrintVector2List(ScreenLocate.quadUnityVectorList));
  791. }
  792. }
  793. bool showPoints = false;
  794. public void SetLocatePointsToCameraRender(List<Vector2> points, float w, float h)
  795. {
  796. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  797. if (pointsTF2.childCount == points.Count)
  798. {
  799. Vector2 texSize = new Vector2(w, h);
  800. for (int i = 0; i < pointsTF2.childCount; i++)
  801. {
  802. Transform pointTF = pointsTF2.GetChild(i);
  803. Vector2 pos = points[i];
  804. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  805. pointTF.gameObject.SetActive(true);
  806. showPoints = true;
  807. }
  808. }
  809. else {
  810. for (int i = 0; i < pointsTF2.childCount; i++)
  811. {
  812. Transform pointTF = pointsTF2.GetChild(i);
  813. pointTF.gameObject.SetActive(false);
  814. showPoints = false;
  815. }
  816. }
  817. //绘制数据
  818. DrawTestLine();
  819. }
  820. #region 测试数据绘制
  821. [SerializeField] private Toggle curToggle;
  822. [SerializeField] private Toggle autoToggle; // 控制 AutoUILineGenerator 的 Toggle
  823. [SerializeField] private Toggle semiAutoToggle; // 控制 SemiAutoUILineGenerator 的 Toggle
  824. [SerializeField] private Toggle manualToggle; // 控制 ManualUILineGenerator 的 Toggle
  825. [SerializeField] LineGenerator CurUILineGenerator;//当前结果屏幕线条
  826. [SerializeField] LineGenerator AutoUILineGenerator;//第一个结果屏幕线条
  827. [SerializeField] LineGenerator SemiAutoUILineGenerator;//第二个结果屏幕线条
  828. [SerializeField] LineGenerator ManualUILineGenerator;//第三个结果屏幕线条
  829. [SerializeField] private Dropdown dropdown; // 引用场景中的 Dropdown 组件
  830. [SerializeField] RawImage _cameraRenderTest5;
  831. [SerializeField] RawImage _cameraRenderTest6;
  832. void DrawTestLine()
  833. {
  834. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  835. // 判断 texSize 是否为有效值
  836. if (texSize == Vector2.zero)
  837. {
  838. Debug.LogWarning("Texture size is zero, cannot proceed with line drawing.");
  839. return;
  840. }
  841. // 设置三个屏幕四边形和线条生成器
  842. QuadrilateralInCamera[] screenQuads = new QuadrilateralInCamera[] {
  843. ScreenLocate.Main.ScreenIdentification?.QuadAuto,
  844. ScreenLocate.Main.ScreenIdentification?.QuadSemiAuto,
  845. ScreenLocate.Main.ScreenIdentification?.QuadManual
  846. };
  847. LineGenerator[] lineGenerators = new LineGenerator[] {
  848. AutoUILineGenerator,
  849. SemiAutoUILineGenerator,
  850. ManualUILineGenerator
  851. };
  852. for (int i = 0; i < screenQuads.Length; i++)
  853. {
  854. if (screenQuads[i] == null)
  855. {
  856. Debug.LogWarning($"Screen quadrilateral {i} is null, skipping this line.");
  857. continue;
  858. }
  859. if (lineGenerators[i] == null)
  860. {
  861. Debug.LogWarning($"Line generator {i} is null, skipping this line.");
  862. continue;
  863. }
  864. lineGenerators[i].Points = ConvertQuadToPoints(screenQuads[i], texSize);
  865. }
  866. // 清除旧选项并填充新的选项
  867. dropdown.ClearOptions();
  868. List<string> options = new List<string>();
  869. //for (int i = 0; i < screenQuads.Length; i++)
  870. //{
  871. // options.Add($"Quad {i + 1}");
  872. //}
  873. //options.Add("自动识别");
  874. //options.Add("半自动识别");
  875. //options.Add("手动识别");
  876. options.Add(TextAutoLanguage2.GetTextByKey("AutoRecognition")); // "自动识别"
  877. options.Add(TextAutoLanguage2.GetTextByKey("SemiAutoRecognition")); // "半自动识别"
  878. options.Add(TextAutoLanguage2.GetTextByKey("ManualRecognition")); // "手动识别"
  879. dropdown.AddOptions(options);
  880. // 添加监听器来处理选择事件
  881. dropdown.onValueChanged.AddListener((index) => {
  882. OnDropdownValueChanged(index, screenQuads);
  883. });
  884. if (screenQuads[0] != null || screenQuads[1] != null)
  885. {
  886. Texture texImage6 = ScreenLocate.Main.OutputTextures[5];
  887. if (texImage6 != null) _cameraRenderTest6.texture = texImage6;
  888. }
  889. if (ScreenLocate.quadUnityVectorList.Count == 4) {
  890. //绘制白色线段
  891. var lo = new Vector2(-0.5f, -0.5f);
  892. CurUILineGenerator.Points = new Vector2[4] {
  893. 2 * (ScreenLocate.quadUnityVectorList[0] + lo),
  894. 2 * (ScreenLocate.quadUnityVectorList[1] + lo),
  895. 2 * (ScreenLocate.quadUnityVectorList[3] + lo),
  896. 2 * (ScreenLocate.quadUnityVectorList[2] + lo) };
  897. }
  898. }
  899. // 当下拉框选项更改时调用的方法
  900. private void OnDropdownValueChanged(int index, QuadrilateralInCamera[] screenQuads)
  901. {
  902. if (index >= 0 && index < screenQuads.Length)
  903. {
  904. if (screenQuads[index] != null)
  905. {
  906. QuadrilateralInCamera selectedQuad = screenQuads[index];
  907. Debug.Log($"Selected Quad {index + 1}: {selectedQuad}");
  908. CurUILineGenerator.Points = ConvertQuadToPoints(selectedQuad, ScreenLocate.Main.getUVCCameraInfoSize);
  909. }
  910. else
  911. {
  912. Debug.LogWarning($"Selected Quad {index + 1} is null.");
  913. }
  914. }
  915. else
  916. {
  917. Debug.LogWarning("所选索引超出范围!");
  918. }
  919. }
  920. /// <summary>
  921. /// 提取转换四边形的方法
  922. /// </summary>
  923. /// <param name="quad"></param>
  924. /// <param name="texSize"></param>
  925. /// <returns></returns>
  926. public Vector2[] ConvertQuadToPoints(QuadrilateralInCamera quad, Vector2 texSize)
  927. {
  928. if (quad == null || quad.Quad == null || quad.Quad.Count < 4)
  929. {
  930. Debug.LogWarning("Invalid quadrilateral data provided.");
  931. return new Vector2[0]; // 返回空数组以避免异常
  932. }
  933. Vector2 offset = new Vector2(-0.5f, -0.5f); // 假设 'lo' 是某个已定义的偏移量
  934. return new Vector2[4] {
  935. 2 * (new Vector2(quad.Quad[0].x / texSize.x, quad.Quad[0].y / texSize.y) + offset),
  936. 2 * (new Vector2(quad.Quad[1].x / texSize.x, quad.Quad[1].y / texSize.y) + offset),
  937. 2 * (new Vector2(quad.Quad[3].x / texSize.x, quad.Quad[3].y / texSize.y) + offset),
  938. 2 * (new Vector2(quad.Quad[2].x / texSize.x, quad.Quad[2].y / texSize.y) + offset)
  939. };
  940. }
  941. public Vector2[] ConvertPointsToCoordinates(Vector2[] points, Vector2 texSize, Vector2 pivot)
  942. {
  943. if (points == null || points.Length < 1)
  944. {
  945. Debug.LogWarning("Invalid point data provided.");
  946. return new Vector2[0]; // 返回空数组以避免异常
  947. }
  948. Vector2 offset = new Vector2(-0.5f, -0.5f); // 将坐标从中心对齐到左下角对齐
  949. List<Vector2> transformedPoints = new List<Vector2>();
  950. // 遍历所有传入的点进行转换
  951. foreach (var point in points)
  952. {
  953. // 转换每个点,考虑 texSize 和 pivot 偏移
  954. Vector2 transformedPoint = 2 * ((point / texSize) + offset + pivot);
  955. transformedPoints.Add(transformedPoint);
  956. }
  957. return transformedPoints.ToArray();
  958. }
  959. void initToggle()
  960. {
  961. // 监听 Toggle 值的变化
  962. if (curToggle != null)
  963. curToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(CurUILineGenerator, isOn));
  964. // 监听 Toggle 值的变化
  965. if (autoToggle != null)
  966. autoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(AutoUILineGenerator, isOn));
  967. if (semiAutoToggle != null)
  968. semiAutoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(SemiAutoUILineGenerator, isOn));
  969. if (manualToggle != null)
  970. manualToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(ManualUILineGenerator, isOn));
  971. }
  972. // 控制 LineGenerator 的启用/禁用
  973. private void ToggleLineGenerator(LineGenerator lineGenerator, bool isOn)
  974. {
  975. if (lineGenerator != null && lineGenerator.enabled != isOn)
  976. {
  977. lineGenerator.enabled = isOn;
  978. Debug.Log($"{lineGenerator.name} is now {(isOn ? "enabled" : "disabled")}");
  979. }
  980. }
  981. /// <summary>
  982. /// 设置全部显示
  983. /// </summary>
  984. /// <param name="value"></param>
  985. private void SetAllToggle(bool value) {
  986. ToggleLineGenerator(CurUILineGenerator, value);
  987. ToggleLineGenerator(AutoUILineGenerator, value);
  988. ToggleLineGenerator(SemiAutoUILineGenerator, value);
  989. ToggleLineGenerator(ManualUILineGenerator, value);
  990. }
  991. /// <summary>
  992. /// 放大时候同步一次toggle
  993. /// </summary>
  994. private void SyncAllToggle()
  995. {
  996. ToggleLineGenerator(CurUILineGenerator, curToggle.isOn);
  997. ToggleLineGenerator(AutoUILineGenerator, autoToggle.isOn);
  998. ToggleLineGenerator(SemiAutoUILineGenerator, semiAutoToggle.isOn);
  999. ToggleLineGenerator(ManualUILineGenerator, manualToggle.isOn);
  1000. }
  1001. // 下拉菜单用于显示纹理名称
  1002. public Dropdown textureDropdown;
  1003. // 按钮用于导出选中的纹理
  1004. public Button exportSelectedButton;
  1005. // 按钮用于导出所有纹理
  1006. public Button exportAllButton;
  1007. // 定义纹理名称
  1008. string[] textureNames;
  1009. /// <summary>
  1010. /// 更新一下菜单
  1011. /// </summary>
  1012. public void UpdateLanguage() {
  1013. string[] _textureNames = {
  1014. TextAutoLanguage2.GetTextByKey("ScreenAOriginal"), // "A屏幕原图"
  1015. TextAutoLanguage2.GetTextByKey("SemiAutoSegmentB"), // "B半自动识别线段"
  1016. TextAutoLanguage2.GetTextByKey("BlackWhiteContrastC"), // "C黑白色差"
  1017. TextAutoLanguage2.GetTextByKey("RecognitionResultD"), // "D识别结果"
  1018. TextAutoLanguage2.GetTextByKey("ColorContrastOverlayE"), // "E色差叠加识别结果"
  1019. TextAutoLanguage2.GetTextByKey("SemiAutoAlternativeF") // "F半自动备选线段"
  1020. };
  1021. textureNames = _textureNames;
  1022. // 设置下拉菜单的选项
  1023. textureDropdown.ClearOptions();
  1024. textureDropdown.AddOptions(new System.Collections.Generic.List<string>(textureNames));
  1025. }
  1026. void initExport() {
  1027. UpdateLanguage();
  1028. // 添加导出选中纹理的按钮点击事件
  1029. exportSelectedButton.onClick.AddListener(() => SaveTextureToLocal(textureDropdown.value));
  1030. // 添加导出所有纹理的按钮点击事件
  1031. exportAllButton.onClick.AddListener(SaveAllTexturesToLocal);
  1032. }
  1033. /// <summary>
  1034. /// 导出所有纹理
  1035. /// </summary>
  1036. public void SaveAllTexturesToLocal()
  1037. {
  1038. for (int i = 0; i < textureNames.Length; i++)
  1039. {
  1040. SaveTextureToLocal(i); // 调用之前定义的保存方法
  1041. }
  1042. }
  1043. /// <summary>
  1044. /// 导出图片
  1045. /// </summary>
  1046. /// <param name="index"></param>
  1047. public void SaveTextureToLocal(int index)
  1048. {
  1049. Texture2D[] outputTexture2D = ScreenLocate.Main.OutputTextures;
  1050. if (outputTexture2D == null || index >= outputTexture2D.Length || outputTexture2D[index] == null)
  1051. {
  1052. Debug.LogError("Invalid texture index or texture is null.index:"+ index);
  1053. return;
  1054. }
  1055. // 定义保存路径
  1056. string time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  1057. string baseName = $"{time}_Texture_{index}";
  1058. // 检查索引是否在命名数组内
  1059. string fileName = index < textureNames.Length ? textureNames[index] : $"Texture_{index}";
  1060. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1061. string path = System.IO.Path.Combine("/storage/emulated/0/Download", $"{baseName}_{fileName}.png"); //public
  1062. #else
  1063. string path = System.IO.Path.Combine(Application.persistentDataPath, $"{baseName}_{fileName}.png");
  1064. #endif
  1065. // 编码纹理为 PNG 格式
  1066. byte[] bytes = outputTexture2D[index].EncodeToPNG();
  1067. // 将字节写入文件
  1068. System.IO.File.WriteAllBytes(path, bytes);
  1069. Debug.Log($"Texture saved as: {path}");
  1070. }
  1071. //下面是处理对象放大缩小
  1072. public RectTransform cameraObj1; // 拖拽你的 CameraSize1 对象到此字段
  1073. public Button toggleButton; // 缩小时使用的按钮
  1074. private Vector2 originalSize;
  1075. private Vector2 originalAnchoredPosition; // 使用 anchoredPosition 代替 localPosition
  1076. private Vector2 originalAnchorMin;
  1077. private Vector2 originalAnchorMax;
  1078. private int originalSiblingIndex; // 保存初始的层级索引
  1079. private bool isFullscreen = false;
  1080. /// <summary>
  1081. /// 测试效果屏幕数据初始化
  1082. /// </summary>
  1083. void InitFullScreen() {
  1084. if (cameraObj1 != null)
  1085. {
  1086. // 保存初始大小、位置和层级索引
  1087. originalSize = cameraObj1.sizeDelta;
  1088. originalAnchoredPosition = cameraObj1.anchoredPosition;
  1089. originalAnchorMin = cameraObj1.anchorMin; // 记录初始 anchorMin
  1090. originalAnchorMax = cameraObj1.anchorMax; // 记录初始 anchorMax
  1091. originalSiblingIndex = cameraObj1.GetSiblingIndex();
  1092. // 为 cameraObj1 添加点击事件
  1093. cameraObj1.GetComponent<Button>().onClick.AddListener(ToggleFullscreen);
  1094. toggleButton.transform.parent.gameObject.SetActive(false);
  1095. }
  1096. if (toggleButton != null)
  1097. {
  1098. // 为按钮添加点击事件以恢复大小
  1099. toggleButton.onClick.AddListener(RestoreSize);
  1100. }
  1101. }
  1102. void ToggleFullscreen()
  1103. {
  1104. if (cameraObj1 == null) return;
  1105. if (!isFullscreen)
  1106. {
  1107. // 设置锚点为全屏,调整位置和偏移量
  1108. cameraObj1.anchorMin = Vector2.zero;
  1109. cameraObj1.anchorMax = Vector2.one;
  1110. cameraObj1.offsetMin = Vector2.zero;
  1111. cameraObj1.offsetMax = Vector2.zero;
  1112. cameraObj1.anchoredPosition = Vector3.zero;
  1113. cameraObj1.SetSiblingIndex(cameraObj1.parent.childCount - 1); // 设置为最上层
  1114. //刷新一次点
  1115. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1116. toggleButton.transform.parent.gameObject.SetActive(true);
  1117. isFullscreen = true;
  1118. //放大情况根据toggle来显示
  1119. SyncAllToggle();
  1120. }
  1121. }
  1122. void RestoreSize()
  1123. {
  1124. if (cameraObj1 == null || !isFullscreen) return;
  1125. // 恢复锚点和偏移量
  1126. cameraObj1.anchorMin = originalAnchorMin; // 使用在 Start() 中记录的初始锚点
  1127. cameraObj1.anchorMax = originalAnchorMax; // 使用在 Start() 中记录的初始锚点
  1128. cameraObj1.sizeDelta = originalSize;
  1129. cameraObj1.anchoredPosition = originalAnchoredPosition; // 恢复为初始 anchoredPosition
  1130. cameraObj1.SetSiblingIndex(originalSiblingIndex); // 恢复到原本的层级索引
  1131. //刷新一次点
  1132. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1133. toggleButton.transform.parent.gameObject.SetActive(false);
  1134. isFullscreen = false;
  1135. }
  1136. #endregion
  1137. public void SetLocatePointsToCameraRenderTest(List<Vector2> points, float w, float h)
  1138. {
  1139. Transform pointsTF2 = _cameraRender.transform.Find("PointsTest");
  1140. if (pointsTF2.childCount == points.Count)
  1141. {
  1142. Vector2 texSize = new Vector2(w, h);
  1143. for (int i = 0; i < pointsTF2.childCount; i++)
  1144. {
  1145. Transform pointTF = pointsTF2.GetChild(i);
  1146. Vector2 pos = points[i];
  1147. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  1148. pointTF.gameObject.SetActive(true);
  1149. }
  1150. }
  1151. else
  1152. {
  1153. for (int i = 0; i < pointsTF2.childCount; i++)
  1154. {
  1155. Transform pointTF = pointsTF2.GetChild(i);
  1156. pointTF.gameObject.SetActive(false);
  1157. }
  1158. }
  1159. }
  1160. void SetShakeFilterValue(float v)
  1161. {
  1162. shakeFilterValue.Set(v);
  1163. _sliderShakeFilter.SetValueWithoutNotify(shakeFilterValue.Get());
  1164. _sliderShakeFilter.transform.Find("Value").GetComponent<Text>().text = shakeFilterValue.Get().ToString("f1");
  1165. infraredCameraHelper.SetShakeFilterValue(shakeFilterValue.Get());
  1166. }
  1167. /// <summary>
  1168. /// 重新设置分辨率
  1169. /// </summary>
  1170. /// <param name="index"></param>
  1171. public void resolutionRestartApp(int index)
  1172. {
  1173. #if UNITY_ANDROID
  1174. //StartCoroutine(RestartOrKillApp());
  1175. //获取第一个分辨率设置后设置size
  1176. switch (index)
  1177. {
  1178. case 0:
  1179. infraredCameraHelper.SetHighCameraResolution();
  1180. resoution.Set(index);
  1181. _dropdownResolution2.SetValueWithoutNotify(index);
  1182. break;
  1183. case 1:
  1184. infraredCameraHelper.SetLowCameraResolution();
  1185. resoution.Set(index);
  1186. _dropdownResolution2.SetValueWithoutNotify(index);
  1187. break;
  1188. }
  1189. #endif
  1190. }
  1191. /// <summary>
  1192. /// 初始化时候,设置的值
  1193. /// </summary>
  1194. /// <param name="index"></param>
  1195. public Vector2 SetDefByIndex(int index = 0)
  1196. {
  1197. //SetResolutionNew 里面对应的下标
  1198. Vector2 vec2 = new Vector2(320, 240);
  1199. switch (index)
  1200. {
  1201. case 0:
  1202. vec2 = new Vector2(320, 240);
  1203. break;
  1204. case 1:
  1205. vec2 = new Vector2(160, 120);
  1206. break;
  1207. }
  1208. return vec2;
  1209. }
  1210. /// <summary>
  1211. /// 当 Dropdown 选择变化时的处理方法
  1212. /// </summary>
  1213. /// <param name="OnResolutionChanged">320x240</param>
  1214. private void OnResolutionChanged(int index)
  1215. {
  1216. #if UNITY_ANDROID
  1217. Debug.Log("Selected Resolution: " + index);
  1218. // 将选定的分辨率转换为实际的宽度和高度
  1219. // 并且需要判断是否存在最低分辨率
  1220. if (index == 1 && currentCameraInfo.ContainsResulutionKey("160x120"))
  1221. {
  1222. // 在这里你可以根据实际需要设置屏幕分辨率或进行其他操作
  1223. infraredCameraHelper.SetLowCameraResolution();
  1224. // 保存选择的分辨率到 PlayerPrefs
  1225. resoution.Set(index);
  1226. }
  1227. else if(index == 0){
  1228. //如果是0就 使用高分辨率
  1229. infraredCameraHelper.SetHighCameraResolution();
  1230. // 保存选择的分辨率到 PlayerPrefs
  1231. resoution.Set(index);
  1232. }
  1233. #endif
  1234. }
  1235. /// <summary>
  1236. /// 野鸭关卡测试初始值
  1237. /// </summary>
  1238. /// <param name="optionIndex"></param>
  1239. public void SetDuckLevelTest(int optionIndex)
  1240. {
  1241. //选择下标+1
  1242. int v = optionIndex + 1;
  1243. duckHunterLevel.Set(v);
  1244. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  1245. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  1246. //_duckLevelDropdown.transform.Find("Value").GetComponent<Text>().text = defLevel+"";
  1247. }
  1248. void OnClick_Reset()
  1249. {
  1250. //SetBrightness(1);
  1251. //SetSaturation(1);
  1252. //SetContrast(1);
  1253. SetShakeFilterValue(6);
  1254. SetLineWidth(4);
  1255. SetFanWidth(90);
  1256. SetInfraredFilterValue(0.8f);
  1257. SetCaptureValue(30.0f);
  1258. SetDelayValue(30.0f);
  1259. //重置为第一关
  1260. SetDuckLevelTest(0);
  1261. }
  1262. public void OnClickClearAll() {
  1263. PlayerPrefs.DeleteAll();
  1264. // 保存更改
  1265. PlayerPrefs.Save();
  1266. StartCoroutine(RestartOrKillApp());
  1267. }
  1268. void OnClick_ScreenLocateManual()
  1269. {
  1270. bool bEnter = true;
  1271. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1272. {
  1273. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1274. {
  1275. bEnter = true;
  1276. }
  1277. else
  1278. {
  1279. bEnter = false;
  1280. //只有红外设备才能进行屏幕识别
  1281. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1282. }
  1283. }
  1284. if (bEnter)
  1285. {
  1286. ViewManager2.ShowView(ViewManager2.Path_InfraredScreenPositioningView);
  1287. FindObjectOfType<InfraredScreenPositioningView>().enterFromInfraredDemo = true;
  1288. }
  1289. }
  1290. void OnClick_ScreenLocateManualAuto()
  1291. {
  1292. bool bEnter = true;
  1293. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1294. {
  1295. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1296. {
  1297. bEnter = true;
  1298. }
  1299. else
  1300. {
  1301. bEnter = false;
  1302. //只有红外设备才能进行屏幕识别
  1303. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1304. }
  1305. }
  1306. if (bEnter) {
  1307. ResetCenterOffset();
  1308. ResetPositioningData();
  1309. infraredCameraHelper.EnterScreenLocateManualAuto();
  1310. }
  1311. }
  1312. public void OnClick_SetAdjustPointsOffset()
  1313. {
  1314. var _sl = ScreenLocate.Main;
  1315. var buffer = _sl.infraredSpotBuffer;
  1316. if (buffer != null)
  1317. {
  1318. for (int i = 0; i < buffer.Length; i++)
  1319. {
  1320. if (buffer[i].CameraLocation != null)
  1321. {
  1322. Debug.Log("CameraLocation:"+buffer[i].CameraLocation.Value);
  1323. var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[i].CameraLocation.Value, "CameraLocation");
  1324. Debug.Log("CenterOffset: " + centerOffset);
  1325. cameraLocationValue.Set(centerOffset);
  1326. var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[i].ScreenUV.Value, "ScreenUV");
  1327. Debug.Log("UvCenterOffset: " + uvCenterOffset);
  1328. screenUVValue.Set(uvCenterOffset);
  1329. //如果是新手教程场景里面的校准
  1330. InfraredGuider infraredGuiderObj = FindObjectOfType<InfraredGuider>();
  1331. if (infraredGuiderObj != null)
  1332. {
  1333. GameObject infraredGuiderGameObject = infraredGuiderObj.gameObject;
  1334. infraredGuiderGameObject.GetComponent<InfraredGuider>().SetTitleAfterCalibration();
  1335. }
  1336. }
  1337. }
  1338. }
  1339. }
  1340. /// <summary>
  1341. /// 设置存储的中心偏移位置
  1342. /// </summary>
  1343. public void InitCenterOffset() {
  1344. infraredCameraHelper.SetCenterOffset(cameraLocationValue.Get(), "CameraLocation");
  1345. infraredCameraHelper.SetCenterOffset(screenUVValue.Get(), "ScreenUV");
  1346. }
  1347. /// <summary>
  1348. /// 重置中心点
  1349. /// </summary>
  1350. public void ResetCenterOffset() {
  1351. infraredCameraHelper.ResetCenterOffset();
  1352. }
  1353. /// <summary>
  1354. /// 撤销中心点
  1355. /// </summary>
  1356. public void RevokeCenterOffset()
  1357. {
  1358. infraredCameraHelper.RevokeCenterOffset();
  1359. }
  1360. /// <summary>
  1361. /// 重置定位数据
  1362. /// </summary>
  1363. public void ResetPositioningData(bool bSyncLocal = false) {
  1364. infraredCameraHelper.ClearInfraredPositioningData(bSyncLocal);
  1365. }
  1366. void SetCaptureValue(float v)
  1367. {
  1368. captureValue.Set(v);
  1369. _sliderCapture.SetValueWithoutNotify(captureValue.Get());
  1370. _sliderCapture.transform.Find("Value").GetComponent<Text>().text = captureValue.Get().ToString("f1");
  1371. infraredCameraHelper.SetCapture((int)captureValue.Get());
  1372. }
  1373. void SetDelayValue(float v)
  1374. {
  1375. delayValue.Set(v);
  1376. _sliderDelay.SetValueWithoutNotify(delayValue.Get());
  1377. _sliderDelay.transform.Find("Value").GetComponent<Text>().text = delayValue.Get().ToString("f1");
  1378. infraredCameraHelper.SetDelay((int)delayValue.Get());
  1379. }
  1380. #endregion
  1381. #region 相机感光度(默认修改对比度)
  1382. public void onSetSliderCustomValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1383. {
  1384. onSetSliderValue(_slider, "PU_CONTRAST", min, max);
  1385. }
  1386. public void onSliderCustomEvent(float value, float min = 0.0f, float max = 10.0f)
  1387. {
  1388. onSliderEvent(value, "PU_CONTRAST", min, max);
  1389. }
  1390. public void onSetSliderCustomBrightnessValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1391. {
  1392. onSetSliderValue(_slider, "PU_BRIGHTNESS", min, max);
  1393. }
  1394. public void onSliderCustomBrightnessEvent(float value, float min = 0.0f, float max = 10.0f)
  1395. {
  1396. onSliderEvent(value, "PU_BRIGHTNESS", min, max);
  1397. }
  1398. public void onSetSliderValue(Slider _slider,string typeStr = "PU_CONTRAST", float min = 0.0f, float max = 10.0f)
  1399. {
  1400. if (BluetoothWindows.IsWindows()) {
  1401. float v = typeStr == "PU_CONTRAST"?infraredCameraHelper.GetContrast(): infraredCameraHelper.GetBrightness();
  1402. // 目标区间 [0, 10] 的边界值
  1403. double targetMin = min;
  1404. double targetMax = max;
  1405. double originalMin = -1;
  1406. double originalMax = 1;
  1407. // 计算转换后的值
  1408. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1409. Debug.Log("PC获取相机的感光度 "+ typeStr + " :" + v + " = " + v2);
  1410. _slider.SetValueWithoutNotify((float)v2);
  1411. return;
  1412. }
  1413. //功能也改为UVC的对比度
  1414. if (running)
  1415. {
  1416. //string typeStr = "PU_CONTRAST";//"PU_BRIGHTNESS";
  1417. //UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1418. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1419. float v = currentCameraInfo.GetValue(typeStr); // infraredCameraHelper.GetBrightness();
  1420. //float v2 = (v / _UVCCtrlInfo.max) * 10;
  1421. // 目标区间 [0, 10] 的边界值
  1422. double targetMin = min;
  1423. double targetMax = max;
  1424. double originalMin = _UVCCtrlInfo.min;
  1425. double originalMax = _UVCCtrlInfo.max;
  1426. // 计算转换后的值
  1427. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1428. Debug.Log("获取相机的感光度" + typeStr + ": " + v + " = " + v2);
  1429. _slider.SetValueWithoutNotify((float)v2);
  1430. }
  1431. else _slider.SetValueWithoutNotify(5);
  1432. }
  1433. public void onSliderEvent(float value, string typeStr = "PU_CONTRAST", float min = 0.0f,float max = 10.0f)
  1434. {
  1435. // string typeStr = "PU_CONTRAST";// "PU_BRIGHTNESS";
  1436. //pc
  1437. if (BluetoothWindows.IsWindows())
  1438. {
  1439. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1440. Slider slider = trans.GetComponent<Slider>();
  1441. Text textObj = trans.Find("text").GetComponent<Text>();
  1442. // 原始区间和目标区间的边界值
  1443. double originalMin = min;
  1444. double originalMax = max;
  1445. double targetMin = -1;
  1446. double targetMax = 1;
  1447. // 计算转换后的值
  1448. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1449. float _current = (float)result;
  1450. //Debug.Log("_current:" + _current + " , result:" + result);
  1451. textObj.text = _current + "";
  1452. slider.value = _current;
  1453. if (typeStr == "PU_CONTRAST")
  1454. {
  1455. infraredCameraHelper.SetContrast(_current);
  1456. pcCONTRAST.Set(_current);
  1457. }
  1458. else {
  1459. infraredCameraHelper.SetBrightness(_current);
  1460. pcBRIGHTNESS.Set(_current);
  1461. }
  1462. return;
  1463. }
  1464. //修改亮度时,调试界面的亮度也应该一起修改
  1465. //功能也改为UVC的对比度
  1466. if (running)
  1467. {
  1468. //Slider slider = transform.Find("InfraredCamera/Layout/SliderBrightness")
  1469. // .GetComponent<Slider>();
  1470. // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1471. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1472. Slider slider = trans.GetComponent<Slider>();
  1473. Text textObj = trans.Find("text").GetComponent<Text>();
  1474. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1475. int _currentUVCValue = currentCameraInfo.GetValue(typeStr);
  1476. //value 0 ~ 10
  1477. // 原始区间和目标区间的边界值
  1478. double originalMin = min;
  1479. double originalMax = max;
  1480. double targetMin = _UVCCtrlInfo.min;
  1481. double targetMax = _UVCCtrlInfo.max;
  1482. // 计算转换后的值
  1483. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1484. int _current = (int)(result);
  1485. Debug.Log("_current:" + value + " , result:" + result);
  1486. textObj.text = _current + "";
  1487. slider.value = _current;
  1488. //dUVCParameters.GetValueOrDefault(typeStr).Set(_current);
  1489. //存储初始值,设置一次到UVC参数
  1490. if (_currentUVCValue != _current) currentCameraInfo.SetValue(typeStr, _current);
  1491. }
  1492. }
  1493. public static double MapValue(double value, double originalMin, double originalMax, double targetMin, double targetMax)
  1494. {
  1495. // 线性插值公式
  1496. return targetMin + (value - originalMin) * (targetMax - targetMin) / (originalMax - originalMin);
  1497. }
  1498. #endregion
  1499. #region 绘制线段部分
  1500. public void SetLineWidth(float v)
  1501. {
  1502. lineWidth.Set(v);
  1503. _sliderLineWidth.SetValueWithoutNotify(lineWidth.Get());
  1504. _sliderLineWidth.transform.Find("Value").GetComponent<Text>().text = lineWidth.Get().ToString("f1");
  1505. }
  1506. public void SetFanWidth(float v)
  1507. {
  1508. fanWidth.Set(v);
  1509. _fanWidth.SetValueWithoutNotify(fanWidth.Get());
  1510. _fanWidth.transform.Find("Value").GetComponent<Text>().text = fanWidth.Get().ToString("f1");
  1511. }
  1512. #endregion
  1513. #region 亮度检测部分
  1514. public void SetInfraredFilterValue(float v)
  1515. {
  1516. infraredFileterValue.Set(v);
  1517. _infraredFilter.SetValueWithoutNotify(infraredFileterValue.Get());
  1518. _infraredFilter.transform.Find("Value").GetComponent<Text>().text = infraredFileterValue.Get().ToString("f1");
  1519. infraredCameraHelper.SetInfraredLocateBrightnessThreshold(infraredFileterValue.Get());
  1520. }
  1521. #endregion
  1522. public void resetInfraredPlayerPrefs()
  1523. {
  1524. //测试用
  1525. PlayerPrefs.DeleteKey("entry-guider-infrared-" + LoginMgr.myUserInfo.id);
  1526. PlayerPrefs.DeleteKey("hideInfraredBowAndArrow");
  1527. }
  1528. #region 显示Log部分信息
  1529. [SerializeField] Text _calibrationFixedText;
  1530. [SerializeField] Text _cameraSizeText;
  1531. [SerializeField] Text _quadUnityVectorListText;
  1532. /// <summary>
  1533. /// 校准时候的固定值分辨率
  1534. /// </summary>
  1535. /// <param name="v"></param>
  1536. public void SetCalibrationFixedText(Vector2 v)
  1537. {
  1538. _calibrationFixedText.text = v.x + "*" + v.y;
  1539. }
  1540. /// <summary>
  1541. /// 渲染摄像机当前分辨率
  1542. /// </summary>
  1543. /// <param name="v"></param>
  1544. public void SetCameraSizeText(Vector2 v)
  1545. {
  1546. _cameraSizeText.text = v.x + "*" + v.y;
  1547. }
  1548. /// <summary>
  1549. /// 渲染摄像机识别点
  1550. /// </summary>
  1551. /// <param name="v"></param>
  1552. public void SetQuadUnityVectorListText(string v)
  1553. {
  1554. _quadUnityVectorListText.text = v;
  1555. }
  1556. #endregion
  1557. #region 错误日志
  1558. public void HandleLog(string logString, string stackTrace, LogType type)
  1559. {
  1560. if (type == LogType.Exception || type == LogType.Error)
  1561. {
  1562. SaveLogToFile(logString, stackTrace);
  1563. }
  1564. }
  1565. void SaveLogToFile(string message, string stackTrace)
  1566. {
  1567. string path;
  1568. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1569. // 保存到 Android 的公共 Download 文件夹,便于用户直接查看
  1570. path = System.IO.Path.Combine("/storage/emulated/0/Download", "crash_log.txt");
  1571. #else
  1572. // 其他平台使用 Application.persistentDataPath
  1573. path = System.IO.Path.Combine(Application.persistentDataPath, "crash_log.txt");
  1574. #endif
  1575. // 打印路径确认
  1576. Debug.Log($"Log file saved at: {path}");
  1577. // 将日志写入到指定路径的文件中
  1578. System.IO.File.AppendAllText(path, $"{message}\n{stackTrace}\n\n");
  1579. }
  1580. #endregion
  1581. }
  1582. public class ParamFloatValue
  1583. {
  1584. private string _saveKey;
  1585. private float _valueDefault;
  1586. private bool _valueLoaded;
  1587. private float _value;
  1588. public ParamFloatValue(string saveKey, float valueDefault)
  1589. {
  1590. _saveKey = saveKey;
  1591. _valueDefault = valueDefault;
  1592. }
  1593. public float Get()
  1594. {
  1595. if (!_valueLoaded) _value = PlayerPrefs.GetFloat(_saveKey, _valueDefault);
  1596. return _value;
  1597. }
  1598. public float GetDefault() {
  1599. return _valueDefault;
  1600. }
  1601. public string GetKey()
  1602. {
  1603. return _saveKey;
  1604. }
  1605. public void Set(float value)
  1606. {
  1607. _value = value;
  1608. PlayerPrefs.SetFloat(_saveKey, _value);
  1609. PlayerPrefs.Save();
  1610. }
  1611. /// <summary>
  1612. /// 重置成默认值
  1613. /// </summary>
  1614. public void Reset() {
  1615. PlayerPrefs.SetFloat(_saveKey, _valueDefault);
  1616. PlayerPrefs.Save();
  1617. }
  1618. }
  1619. /// <summary>
  1620. /// 存储Vector2
  1621. /// </summary>
  1622. public class ParamVector2Value
  1623. {
  1624. private string _saveKey;
  1625. private Vector2 _valueDefault;
  1626. private bool _valueLoaded;
  1627. private Vector2 _value;
  1628. public ParamVector2Value(string saveKey, Vector2 valueDefault)
  1629. {
  1630. _saveKey = saveKey;
  1631. _valueDefault = valueDefault;
  1632. }
  1633. public Vector2 Get()
  1634. {
  1635. if (!_valueLoaded)
  1636. {
  1637. float x = PlayerPrefs.GetFloat(_saveKey + "_x", _valueDefault.x);
  1638. float y = PlayerPrefs.GetFloat(_saveKey + "_y", _valueDefault.y);
  1639. _value = new Vector2(x, y);
  1640. _valueLoaded = true;
  1641. }
  1642. return _value;
  1643. }
  1644. public Vector2 GetDefault()
  1645. {
  1646. return _valueDefault;
  1647. }
  1648. public string GetKey()
  1649. {
  1650. return _saveKey;
  1651. }
  1652. public void Set(Vector2 value)
  1653. {
  1654. _value = value;
  1655. PlayerPrefs.SetFloat(_saveKey + "_x", _value.x);
  1656. PlayerPrefs.SetFloat(_saveKey + "_y", _value.y);
  1657. PlayerPrefs.Save();
  1658. }
  1659. /// <summary>
  1660. /// 重置成默认值
  1661. /// </summary>
  1662. public void Reset()
  1663. {
  1664. PlayerPrefs.SetFloat(_saveKey + "_x", _valueDefault.x);
  1665. PlayerPrefs.SetFloat(_saveKey + "_y", _valueDefault.y);
  1666. PlayerPrefs.Save();
  1667. }
  1668. }