InfraredDemo.cs 69 KB

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