InfraredDemo.cs 69 KB

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