InfraredDemo.cs 69 KB

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