| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using InfraredManager;
- using ZIM;
- using System.Linq;
- using SLAMUVC;
- using System;
- using SmartBowSDK;
- using ZIM.Unity;
- public class InfraredDemo : JCUnityLib.ViewBase
- {
- public static bool DebugInEditor = true;
- public static InfraredDemo _ins;
- [SerializeField]
- RectTransform canvasRectTransform;
- public Button mBtnSee;
- public static void Create()
- {
- if (_ins) return;
- GameObject o = Instantiate(Resources.Load<GameObject>("InfraredDemo"));
- DontDestroyOnLoad(o);
- _ins = o.GetComponent<InfraredDemo>();
- //添加一个父物体
- o.transform.SetParent(ViewMgr.Instance.transform.Find("1").transform);
- CanvasScaler canvasScaler = o.GetComponent<CanvasScaler>();
- if (canvasScaler != null)
- {
- Destroy(canvasScaler);
- }
- RectTransform rectTransform = o.GetComponent<RectTransform>();
- rectTransform.anchorMin = Vector2.zero; // 左下角对齐父级
- rectTransform.anchorMax = Vector2.one; // 右上角对齐父级
- rectTransform.offsetMin = Vector2.zero; // 移除左下角偏移
- rectTransform.offsetMax = Vector2.zero; // 移除右上角偏移
- rectTransform.localScale = Vector3.one; // 确保缩放为 1
- //直接初始化一次
- _ins.InitInfraredCamera();
- //生成一个控制台
- UserPlayer.InitLogReporter();
- }
- void Start()
- {
- if (Application.platform != RuntimePlatform.WindowsEditor) DebugInEditor = false;
- SetVisiable(false);
- InitDebugScreenPoint();
- gameObject.AddComponent<FPSTester>();
- if (CommonConfig.StandaloneModeOrPlatformB)
- {
- mBtnSee.gameObject.SetActive(false);
- }
- else {
- mBtnSee.interactable = false;
- mBtnSee.transform.Find("Text").GetComponent<Text>().text = TextAutoLanguage2.GetTextByKey("WaitingForInitialization"); // "等待初始化..";
- }
- //直接初始化一次
- //InitInfraredCamera();
- Debug.Log("[InfraredDemo] Start Function!");
- initToggle();
- initExport();
- InitFullScreen();
- #if UNITY_STANDALONE_WIN
- _calibrationFixedText.transform.parent.gameObject.SetActive(false);
- #endif
- }
- void OnGUI()
- {
- ShowVersionCode();
- }
- private void ShowVersionCode()
- {
- GUIStyle labelFont = new GUIStyle();
- labelFont.normal.textColor = new Color(1, 0.6f, 0.6f);
- labelFont.fontSize = Mathf.CeilToInt(Screen.height * 0.03f);
- GUI.Label(new Rect(Screen.width / 100, Screen.height / 100, 100, 100), "game-20241111-1740-5-1", labelFont);
- }
- void Update()
- {
- UpdateInfraredCamera();
- //UpdateDebugScreenPoint();
- }
- public void OnClick_See()
- {
- SetVisiable(!_visiable);
- }
- //初始化一次 initScreenLocateManual
- bool hasCalled = false;
- bool _visiable;
- void SetVisiable(bool value)
- {
- _visiable = value;
- transform.Find("Background").gameObject.SetActive(value);
- transform.Find("InfraredCamera").gameObject.SetActive(value);
- //如果是b端,控制这里按钮显示
- if (CommonConfig.StandaloneModeOrPlatformB)
- {
- mBtnSee.gameObject.SetActive(value);
- }
- updateBtnSee();
- Action<Text> onApplyToNext = (t) => {
- updateBtnSee();
- };
- mBtnSee.GetComponentInChildren<TextAutoLanguage2>().onApplyToNext += onApplyToNext;
- //if (value) InitInfraredCamera();
- //刷新翻译的Dropdown
- if (value) {
- UpdateLanguage();
- updateDropdownResolution2();
- }
- //if (!hasCalled && value)
- //{
- // hasCalled = true;
- // //如果本地有记录,初始化一次
- // StartCoroutine(initScreenLocateManual());
- // Debug.Log("[InfraredDemo] SetVisiable Function!");
- //}
- }
- void updateBtnSee() {
- mBtnSee.GetComponentInChildren<Text>().text = _visiable ? TextAutoLanguage2.GetTextByKey("HideInterface") : TextAutoLanguage2.GetTextByKey("DebugInfrared");//"隐藏界面" : "调试红外";
- }
-
- Text _spText;
- Vector2 _screenPoint;
- void InitDebugScreenPoint()
- {
- _spText = transform.Find("SPText").GetComponent<Text>();
- //_spText.gameObject.SetActive(DebugInEditor);
- _spText.gameObject.SetActive(false);
- }
- void UpdateDebugScreenPoint()
- {
- if (!DebugInEditor) return;
- if (infraredCameraHelper == null) return;
- _screenPoint.x = Mathf.Clamp(
- _screenPoint.x + Input.GetAxis("Horizontal") * Screen.width / 400f,
- 0, Screen.width);
- _screenPoint.y = Mathf.Clamp(
- _screenPoint.y + Input.GetAxis("Vertical") * Screen.height / 400f,
- 0, Screen.height);
- infraredCameraHelper.InvokeOnPositionUpdate(_screenPoint);
- _spText.text = _screenPoint.ToString();
- }
- #region 红外摄像
- [SerializeField] RawImage _cameraRender;
- [SerializeField] RawImage _cameraRender2;
- /// <summary>
- /// 测试texture
- /// </summary>
- public RawImage MyCameraRender2
- {
- get { return _cameraRender2; }
- set { _cameraRender2 = value; }
- }
- //[SerializeField] MaintainAspectRatio _MaintainAspectRatio;
- [SerializeField] List<RectTransform> _crosshairsInCamera;
- [SerializeField] Slider _sliderShakeFilter;
- [SerializeField] Button _btnReset;
- [SerializeField] Button _btnScreenLocateManual;
- [SerializeField] Button _btnScreenLocateManualAuto;
- [SerializeField] Slider _sliderCapture;
- [SerializeField] Slider _sliderDelay;
- [SerializeField] Dropdown _dropdownResolution;
- [SerializeField] Dropdown _dropdownResolution2;
- [SerializeField] Slider _sliderLineWidth;
- [SerializeField] Slider _fanWidth;
- //红外线阈值
- [SerializeField] Slider _infraredFilter;
- //调试UVC参数
- [SerializeField] GameObject _cameraParameterPanel;
- [SerializeField] Button _btnAdjusting;
- //野鸭选择
- [SerializeField] Dropdown _duckLevelDropdown;
- //Dictionary<string, ParamFloatValue> dUVCParameters = new Dictionary<string, ParamFloatValue>();
- //public ParamFloatValue brightness = new ParamFloatValue("ic_brightness", 1.0f);
- //public ParamFloatValue saturation = new ParamFloatValue("ic_saturation", 1.0f);
- //public ParamFloatValue contrast = new ParamFloatValue("ic_contrast", 1.0f);
- #if UNITY_ANDROID
- //初始化纹理-1280*720,index = 0
- // public ParamFloatValue resoution = new ParamFloatValue("ic_resoution2", 0);
- //摄像机分辨率 -320*240,index = 10
- public ParamFloatValue resoutionNew = new ParamFloatValue("ic_resoutionNew", 10);
- //摄像机分辨率 -只处理高低分辨率情况
- public ParamFloatValue resoution = new ParamFloatValue("ic_resoution", 0);
- //string[] resolutions = { "高分辨率", "低分辨率" };
- #endif
- //抖动过滤值 - 6.0
- public ParamFloatValue shakeFilterValue = new ParamFloatValue("ic_shakeFilterValue2", 6.0f);
- //亮度过滤阈值 - 0.8
- public ParamFloatValue infraredFileterValue = new ParamFloatValue("ic_infraredFileterValue", 0.8f);
- //线段宽度阈值
- public ParamFloatValue lineWidth = new ParamFloatValue("ic_lineWidth", 4.0f);
- //扇形宽度
- public ParamFloatValue fanWidth = new ParamFloatValue("ic_fanWidth", 90.0f);
- public ParamFloatValue captureValue = new ParamFloatValue("ic_captureValue", 30.0f);
- public ParamFloatValue delayValue = new ParamFloatValue("ic_delayValue", 30.0f);
- //红外准心,默认打开吧
- public ParamFloatValue crosshairValue = new ParamFloatValue("ic_crosshairValue", 1);
- //野鸭测试存储
- public ParamFloatValue duckHunterLevel = new ParamFloatValue("test_duckHunterLevelValue", 1);
- //存储滑块信息。camera
- public Dictionary<string ,ParamFloatValue> ParamFloatValueCameraSlider = new Dictionary<string, ParamFloatValue>();
- public static InfraredCameraHelper infraredCameraHelper;
- public static bool running { get => infraredCameraHelper != null; }
- private bool _inited;
- #region 参数控制
- public GameObject togglePrefab; // 拖入一个Toggle预设体
- public GameObject sliderPrefab; // 拖入一个Slider预设体
- public GameObject spawnPoint;
- //自动曝光
- bool bAutoAE = false;
- Toggle CTRLAEToggle;
- Slider CTRLAEABSSlider;
- string[] sliderNameArray = new string[]{
- "自动曝光模式",
- "曝光时间(绝对)",
- "亮度", //
- "对比度",
- "色调",
- "饱和度",
- "锐度",
- "伽玛",
- //"白平衡温度",
- //"白平衡分量",
- "背光补偿",
- "增益" };
- string[] sliderStrArray = new string[]{
- "CTRL_AE",
- "CTRL_AE_ABS",
- "PU_BRIGHTNESS",
- "PU_CONTRAST",
- "PU_HUE",
- "PU_SATURATION",
- "PU_SHARPNESS",
- "PU_GAMMA",
- //"PU_WB_TEMP",
- //"PU_WB_COMPO",
- "PU_BACKLIGHT",
- "PU_GAIN" };
- UVCManager.CameraInfo currentCameraInfo;
- //初始化相机参数
- public void initSlider(UVCManager.CameraInfo cameraInfo)
- {
- if (currentCameraInfo != null) return;
- currentCameraInfo = cameraInfo;
- string[] sliderNameArrayKey = new string[] {
- "AutoExposureMode", // "自动曝光模式"
- "ExposureTimeAbsolute", // "曝光时间(绝对)"
- "Brightness", // "亮度"
- "Contrast", // "对比度"
- "Hue", // "色调"
- "Saturation", // "饱和度"
- "Sharpness", // "锐度"
- "Gamma", // "伽玛"
- "BacklightCompensation", // "背光补偿"
- "Gain" // "增益"
- };
- for (int i = 0; i < sliderStrArray.Length; i++)
- {
- string typeStr = sliderStrArray[i];
- // UInt64 _VALUE = cameraInfo.GetTypeByName(typeStr);
- //不支持的,跳过
- bool bContains = cameraInfo.ContainsKey(typeStr);
- if (!bContains) continue;
- if (typeStr == "CTRL_AE")
- {
- //曝光Toggle
- GameObject toggleObject = Instantiate(togglePrefab, spawnPoint.transform);
- toggleObject.SetActive(true);
- toggleObject.name = typeStr;
- Text labelObj = toggleObject.transform.Find("Label").GetComponent<Text>();
- //labelObj.text = sliderNameArray[i];
- labelObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayKey[i]);
- Toggle toggle = toggleObject.GetComponent<Toggle>();
- CTRLAEToggle = toggle;
- UVCCtrlInfo _AEInfo = cameraInfo.GetInfo(typeStr);
- Debug.Log("UVCCtrlInfo:" + _AEInfo.ToString());
- int _currentValue = cameraInfo.GetValue(typeStr);
- bAutoAE = _currentValue == 8 ? true : false; //如果当前值是 8,则当前摄像机是自动曝光模式
- toggle.isOn = bAutoAE;
- //cameraInfo.SetValue(_VALUE, _currentValue!=8? 8:1);
- toggle.onValueChanged.AddListener((bool bValue) =>
- {
- //Debug.Log("Toggle value changed to: " + bValue + " from " + _VALUE);
- if (typeStr == "CTRL_AE")
- {
- //开关控制是否自动曝光
- bAutoAE = bValue;
- if (CTRLAEABSSlider) CTRLAEABSSlider.interactable = !bAutoAE;
- int _value = bValue ? 8 : 1;
- //Debug.Log("_value " + _value);
- cameraInfo.SetValue(typeStr, _value);
- }
- });
- }
- else
- {
- //其余使用slider
- GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
- sliderObject.SetActive(true);
- sliderObject.name = typeStr;
- Slider slider = sliderObject.GetComponent<Slider>();
- Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
- Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
- //titleTextObj.text = sliderNameArray[i];//类型名字
- titleTextObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayKey[i]);
- if (slider != null)
- {
- UVCCtrlInfo _UVCCtrlInfo = cameraInfo.GetInfo(typeStr);
- slider.minValue = _UVCCtrlInfo.min;
- slider.maxValue = _UVCCtrlInfo.max;
- slider.wholeNumbers = true;
- int _defValue = _UVCCtrlInfo.def;
- //指定默认值
- //5、UVC亮度 - 50
- //6、UVC对比度 - 50
- if (typeStr == "PU_BRIGHTNESS") {
- _defValue = 50;
- } else if (typeStr == "PU_CONTRAST") {
- _defValue = 50;
- }
- //记录一个typeStr类型的数据存储操作对象
- ParamFloatValue paramFloatValue = new ParamFloatValue("ic_uvc_" + typeStr, _defValue);
- ParamFloatValueCameraSlider.Add(typeStr, paramFloatValue);
- if (typeStr == "PU_BRIGHTNESS" || typeStr == "PU_CONTRAST")
- {
- //获取设置默认存储的值
- int _Value = (int)paramFloatValue.Get();
- cameraInfo.SetValue(typeStr, _Value);
- Debug.Log("[InfraredDemo] UVC 设置" + typeStr + "默认值:" + _Value);
- slider.value = _Value;
- textObj.text = _Value + "";
- }
- else {
- //获取设置当前值
- int _currentValue = cameraInfo.GetValue(typeStr);
- slider.value = _currentValue;
- textObj.text = _currentValue + "";
- }
- //如果是曝光slider
- if (typeStr == "CTRL_AE_ABS")
- {
- CTRLAEABSSlider = slider;
- slider.interactable = !bAutoAE;
- }
- slider.onValueChanged.AddListener((newValue) =>
- {
- var _value = Mathf.FloorToInt(newValue);
- textObj.text = _value + "";
- //Debug.Log("Slider value changed to: " + newValue + " from " + _VALUE);
- cameraInfo.SetValue(typeStr, _value);
- paramFloatValue.Set(_value);
- });
- }
- }
- }
- }
- public void OpenUVCPanel()
- {
- _cameraParameterPanel.SetActive(true);
- }
- public void CloseUVCPanel()
- {
- _cameraParameterPanel.SetActive(false);
- }
- public void onResetUVCData()
- {
- #if UNITY_ANDROID
- resetUVCData();
- #endif
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- resetPCData();
- #endif
- }
- void resetUVCData() {
- if (currentCameraInfo == null) return;
- for (int i = 0; i < sliderStrArray.Length; i++)
- {
- string typeStr = sliderStrArray[i];
- // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
- bool bContains = currentCameraInfo.ContainsKey(typeStr);
- if (!bContains) continue;
- if (typeStr == "CTRL_AE")
- {
- //toggle值不进行重置
- Debug.Log("CTRL_AE 不需要重置");
- }
- else if (typeStr == "CTRL_AE_ABS")
- {
- if (!bAutoAE)
- {
- //如果是手动曝光,重置值
- Transform trans = _cameraParameterPanel.transform.Find(typeStr);
- Slider slider = trans.GetComponent<Slider>();
- Text textObj = trans.Find("text").GetComponent<Text>();
- UVCCtrlInfo _AEInfo = currentCameraInfo.GetInfo(typeStr);
- //获取当前值
- int _currentValue = currentCameraInfo.GetValue(typeStr);
- Debug.Log("CTRL_AE_ABS:" + _currentValue + " = " + _AEInfo.def + " = " + ",bAutoAE:" + bAutoAE);
- textObj.text = _AEInfo.def + "";
- slider.value = _AEInfo.def;
- if (_AEInfo.def != _currentValue) currentCameraInfo.SetValue(typeStr, _AEInfo.def);
- }
- }
- else
- {
- Transform trans = _cameraParameterPanel.transform.Find(typeStr);
- Slider slider = trans.GetComponent<Slider>();
- Text textObj = trans.Find("text").GetComponent<Text>();
- UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
- ParamFloatValue paramFloatValue = ParamFloatValueCameraSlider.GetValueOrDefault(typeStr);
- //重置的值
- int _defValue = _UVCCtrlInfo.def;
- if (typeStr == "PU_BRIGHTNESS")
- {
- _defValue = (int)paramFloatValue.GetDefault();
- }
- else if (typeStr == "PU_CONTRAST")
- {
- _defValue = (int)paramFloatValue.GetDefault();
- }
- textObj.text = _defValue + "";
- slider.value = _defValue;
- //获取当前值
- int _currentValue = currentCameraInfo.GetValue(typeStr);
- //重置存储值
- paramFloatValue.Reset();
- //存储初始值,设置一次到UVC参数
- if (_defValue != _currentValue) currentCameraInfo.SetValue(typeStr, _defValue);
- }
- }
- }
- //windows 相机
- string[] sliderNameArrayPC = new string[]{
- "亮度",
- "对比度",};
- string[] sliderNameArrayPCKey = new string[]{
- "Brightness",
- "Contrast",};
- string[] sliderStrArrayPC = new string[]{
- "PU_BRIGHTNESS",
- "PU_CONTRAST"};
- //记录一个typeStr类型的数据存储操作对象
- ParamFloatValue pcBRIGHTNESS = new ParamFloatValue("ic_pc_PU_BRIGHTNESS", 0);
- ParamFloatValue pcCONTRAST = new ParamFloatValue("ic_pc_PU_CONTRAST", 0);
- public void initSliderPC()
- {
- for (int i = 0; i < sliderStrArrayPC.Length; i++)
- {
- string typeStr = sliderStrArrayPC[i];
- GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
- sliderObject.SetActive(true);
- sliderObject.name = typeStr;
- Slider slider = sliderObject.GetComponent<Slider>();
- Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
- Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
- //titleTextObj.text = TextAutoLanguage2.GetTextByKey(sliderNameArrayPCKey[i]);// sliderNameArrayPC[i];//类型名字
- titleTextObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayPCKey[i]);
- if (slider != null)
- {
- slider.minValue = -1;
- slider.maxValue = 1;
- //记录一个typeStr类型的数据存储操作对象
- if (typeStr == "PU_BRIGHTNESS")
- {
- //获取设置默认存储的值
- float _Value = pcBRIGHTNESS.Get();
- infraredCameraHelper.SetBrightness(_Value);
- Debug.Log("[InfraredDemo] PC 设置 PU_BRIGHTNESS:" + typeStr + "默认值:" + _Value);
- slider.value = _Value;
- textObj.text = _Value + "";
- slider.onValueChanged.AddListener((newValue) =>
- {
- var _value = newValue;
- textObj.text = _value + "";
- infraredCameraHelper.SetBrightness(_value);
- pcBRIGHTNESS.Set(_value);
- });
- }
- else if (typeStr == "PU_CONTRAST")
- {
- //获取设置默认存储的值
- float _Value = pcCONTRAST.Get();
- infraredCameraHelper.SetContrast(_Value);
- Debug.Log("[InfraredDemo] PC 设置 PU_CONTRAST:" + typeStr + "默认值:" + _Value);
- slider.value = _Value;
- textObj.text = _Value + "";
- slider.onValueChanged.AddListener((newValue) =>
- {
- var _value = newValue;
- textObj.text = _value + "";
- infraredCameraHelper.SetContrast(_value);
- pcCONTRAST.Set(_value);
- });
- }
- }
- }
- }
- void resetPCData() {
- for (int i = 0; i < sliderStrArrayPC.Length; i++)
- {
- string typeStr = sliderStrArrayPC[i];
- Transform trans = _cameraParameterPanel.transform.Find(typeStr);
- Slider slider = trans.GetComponent<Slider>();
- Text textObj = trans.Find("text").GetComponent<Text>();
- //重置的值
- int _defValue = 0;
- if (typeStr == "PU_BRIGHTNESS")
- {
- _defValue = 0;
- infraredCameraHelper.SetBrightness(_defValue);
- }
- else if (typeStr == "PU_CONTRAST")
- {
- _defValue = 0;
- infraredCameraHelper.SetContrast(_defValue);
- }
- textObj.text = _defValue + "";
- slider.value = _defValue;
- }
- }
- #endregion
- void InitInfraredCamera()
- {
- if (_inited) return;
- _inited = true;
- //SDK创建
- if (infraredCameraHelper == null)
- {
- infraredCameraHelper = InfraredCameraHelper.GetInstance();
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- infraredCameraHelper.CreateToPc();
- #endif
- #if UNITY_ANDROID
- //开始时候设置一个默认分辨率
- Debug.Log("开始时候的分辨率下标:" + resoution.Get());
- Vector2 resoutionVec2 = SetDefByIndex((int)resoution.Get());
- infraredCameraHelper.Create((int)resoutionVec2.x, (int)resoutionVec2.y);
- #endif
- infraredCameraHelper.OnPositionUpdate += (Vector2 point) =>
- {
- //跑九轴时候,不处理这里位置
- if (AimHandler.ins && AimHandler.ins.bRuning9Axis()) return;
- if (Camera.main == null) return;
- Ray ray = Camera.main.ScreenPointToRay(point);
- Vector3 rayEndPoint = ray.GetPoint(200);
- Quaternion quat = Quaternion.LookRotation(rayEndPoint - Camera.main.transform.position);
- // 挑战场景中其相机的父级有旋转,需要换算
- if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "GameChallenge")
- {
- quat = Quaternion.AngleAxis(-180, Vector3.up) * quat;
- }
- if (CameraToLook.ins != null) CameraToLook.ins.localRotation = quat;
- if (SB_EventSystem.ins) SB_EventSystem.ins.MoveSimulateMouseByInfrared(point);
- //移动目标游戏
- if (GeneratingTarget.gm != null) GeneratingTarget.gm.shootingEvent.OnPositionUpdate(point);
- };
- infraredCameraHelper.OnUVCIsReady += (UVCManager.CameraInfo camera) =>
- {
- //生成控制摄像机的参数滑条
- Debug.Log("初始化摄像机!");
- //可以操作按钮
- mBtnSee.interactable = true;
- //mBtnSee.transform.Find("Text").GetComponent<Text>().text = "调试红外";
- updateBtnSee();
- //延迟重新设置一次分辨率
- StartCoroutine(delayInitOhterInfo(camera));
- };
- //屏幕变化时候
- infraredCameraHelper.OnUVCPosUpdate += (list) =>
- {
- Debug.Log("OnUVCPosUpdate list.Count" + list.Count);
- SetLocatePointsToCameraRender(list, 1, 1);
- //InfraredScreenPositioningView 页面
- if (list.Count == 4)
- {
- FindObjectOfType<InfraredScreenPositioningView>()?.SyncScreenPosition();
- }
- else {
- FindObjectOfType<InfraredScreenPositioningView>()?.onReset();
- }
- };
- }
- }
- private void updateDropdownResolution2()
- {
- string[] resolutions = {
- TextAutoLanguage2.GetTextByKey("HighResolution"),
- TextAutoLanguage2.GetTextByKey("LowResolution")
- };
- // 清除默认选项
- _dropdownResolution2.ClearOptions();
- // 将分辨率字符串数组转换为 Dropdown 选项
- _dropdownResolution2.AddOptions(new List<string>(resolutions));
- }
- /// <summary>
- /// 初始化一些游戏配置
- /// </summary>
- /// <returns></returns>
- IEnumerator delayInitOhterInfo(UVCManager.CameraInfo camera) {
- //yield return new WaitForSeconds(1f);
- yield return new WaitForEndOfFrame();
- #if UNITY_ANDROID
- initSlider(camera);
- camera.GetResolutionsStrs();
- // 默认设置
- updateDropdownResolution2();
- int index = (int)resoution.Get();
- _dropdownResolution2.value = index;
- _dropdownResolution2.RefreshShownValue();
- // 处理 Dropdown 的选择变化
- _dropdownResolution2.onValueChanged.AddListener(index => { OnResolutionChanged(index); });
- #endif
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- initSliderPC();
- //隐藏不需要的设置
- _btnAdjusting.transform.Find("Text").GetComponent<Text>().text = "调整PC参数";
- _dropdownResolution.gameObject.SetActive(false);
- _dropdownResolution2.gameObject.SetActive(false);
- #endif
- //震动阈值
- SetShakeFilterValue(shakeFilterValue.Get());
- _sliderShakeFilter.onValueChanged.AddListener(SetShakeFilterValue);
- //功能按钮
- //重置触发测试
- _btnReset.onClick.AddListener(OnClick_Reset);
- _btnScreenLocateManual.onClick.AddListener(OnClick_ScreenLocateManual);
- _btnScreenLocateManualAuto.onClick.AddListener(OnClick_ScreenLocateManualAuto);
- SetCaptureValue(captureValue.Get());
- _sliderCapture.onValueChanged.AddListener(SetCaptureValue);
- SetDelayValue(delayValue.Get());
- _sliderDelay.onValueChanged.AddListener(SetDelayValue);
- //绘制线段
- SetLineWidth(lineWidth.Get());
- _sliderLineWidth.onValueChanged.AddListener(SetLineWidth);
- SetFanWidth(fanWidth.Get());
- _fanWidth.onValueChanged.AddListener(SetFanWidth);
- //检测红外亮度阈值
- SetInfraredFilterValue(infraredFileterValue.Get());
- _infraredFilter.onValueChanged.AddListener(SetInfraredFilterValue);
- //野鸭设置初始关卡
- int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
- _duckLevelDropdown.SetValueWithoutNotify(defLevel);
- _duckLevelDropdown.onValueChanged.AddListener(SetDuckLevelTest);
- if (!hasCalled)
- {
- hasCalled = true;
- //如果本地有记录,初始化一次算法坐标值
- StartCoroutine(initScreenLocateManual());
- Debug.Log("[InfraredDemo] SetVisiable Function!");
- }
- }
- /// <summary>
- /// 初始化时候获取设置和存储来控制显示准心
- /// </summary>
- /// <returns></returns>
- public bool bInitCrosshairShow() {
- return UserSettings.ins.openCrossHair && getCrosshairValue() == 1 ? true : false;
- }
- /// <summary>
- /// 获取弓箭准心存储值
- /// </summary>
- /// <returns></returns>
- public int getCrosshairValue() {
- return (int)crosshairValue.Get();
- }
- public void setCrosshairValue(bool bshow) {
- crosshairValue.Set(bshow ? 1 : 0);
- }
- public void onStartPreview()
- {
- infraredCameraHelper.onStartPreview();
- }
- public void onStopPreview()
- {
- infraredCameraHelper.onStopPreview();
- }
- /// <summary>
- /// 获取并且初始化一次记录点的数据
- /// </summary>
- /// <returns></returns>
- IEnumerator initScreenLocateManual()
- {
- yield return new WaitForSeconds(1f);
- infraredCameraHelper.InitScreenLocateManual();
- }
- IEnumerator RestartOrKillApp()
- {
- yield return new WaitForSeconds(0.3f);
- if (Application.isEditor) yield break;
- if (Application.platform == RuntimePlatform.Android)
- {
- using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
- {
- const int kIntent_FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
- const int kIntent_FLAG_ACTIVITY_NEW_TASK = 0x10000000;
- var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
- var pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
- var intent = pm.Call<AndroidJavaObject>("getLaunchIntentForPackage", Application.identifier);
- intent.Call<AndroidJavaObject>("setFlags", kIntent_FLAG_ACTIVITY_NEW_TASK | kIntent_FLAG_ACTIVITY_CLEAR_TASK);
- currentActivity.Call("startActivity", intent);
- currentActivity.Call("finish");
- var process = new AndroidJavaClass("android.os.Process");
- int pid = process.CallStatic<int>("myPid");
- process.CallStatic("killProcess", pid);
- }
- }
- else {
- // 获取当前应用程序的可执行文件路径
- string executablePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
- // 重启应用程序
- System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
- {
- FileName = executablePath,
- UseShellExecute = false
- };
- System.Diagnostics.Process.Start(startInfo);
- // 退出当前应用程序
- Application.Quit();
- };
- }
- void UpdateInfraredCamera()
- {
- if (!_visiable) return;
- if (!_inited) return;
- if (infraredCameraHelper == null) return;
- //渲染相机画面
- //_cameraRender.texture = infraredCameraHelper.GetCameraTexture();
- //_cameraRender.material = infraredCameraHelper.GetCameraMaterial();
- if (ScreenLocate.Main.getUVCTexture)
- {
- if (isFullscreen || ScreenLocate.Main.OutputTextures[4] == null)
- {
- if (_cameraRender.texture == null || ScreenLocate.Main.getUVCTexture.GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
- _cameraRender.texture = ScreenLocate.Main.getUVCTexture;
- //ScreenLocate.Main.OutputTextures[4] == null 并且 摄像机缩小的情况下。显示适配线段
- if (!isFullscreen) SetAllToggle(true);
- }
- else if (ScreenLocate.Main.OutputTextures[4] != null)
- {
- //缩小的情况下。显示黑白色差的合成图
- if (_cameraRender.texture == null || ScreenLocate.Main.OutputTextures[4] != null && ScreenLocate.Main.OutputTextures[4].GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
- _cameraRender.texture = ScreenLocate.Main.OutputTextures[4];
- //底图缩小的情况下。不显示适配线段,并且隐藏points
- if (!isFullscreen) {
- if (showPoints) {
- Transform pointsTF2 = _cameraRender.transform.Find("Points");
- for (int i = 0; i < pointsTF2.childCount; i++)
- {
- Transform pointTF = pointsTF2.GetChild(i);
- pointTF.gameObject.SetActive(false);
- showPoints = false;
- }
- }
- SetAllToggle(false);
- }
- }
-
- //_cameraRender.SetNativeSize();
- // _MaintainAspectRatio.AdjustSize();
- }
- //在相机画面显示准心
- if (ScreenLocate.Main)
- {
- var _sl = ScreenLocate.Main;
- var buffer = _sl.infraredSpotBuffer;
- if (buffer != null)
- {
- for (int i = 0; i < buffer.Length; i++)
- {
- if (buffer[i].CameraLocation != null)
- {
- //添加一个偏移量,使得最后输出的准心是指向正中心
- Vector2 newPoint2 = _sl.GetOffsetCameraLocation(buffer[i].CameraLocation.Value);
- // 检测到光点
- var pos = newPoint2.pixelToLocalPosition_AnchorCenter(_sl.mUVCCameraInfo.Size, _cameraRender.rectTransform.rect);
- _crosshairsInCamera[i].gameObject.SetActive(true);
- _crosshairsInCamera[i].anchoredPosition = pos;
- }
- else
- _crosshairsInCamera[i].gameObject.SetActive(false);
- }
- }
- //渲染固定摄像机分辨率
- SetCalibrationFixedText(_sl.mUVCCameraInfo.CurrentCalibrationResolution);
- //渲染摄像机大小
- if (_sl.mUVCCameraInfo != null) SetCameraSizeText(_sl.mUVCCameraInfo.Size);
- //渲染摄像机识别点位置
- SetQuadUnityVectorListText(_sl.PrintVector2List(ScreenLocate.quadUnityVectorList));
- }
- }
- bool showPoints = false;
- public void SetLocatePointsToCameraRender(List<Vector2> points, float w, float h)
- {
- Transform pointsTF2 = _cameraRender.transform.Find("Points");
- if (pointsTF2.childCount == points.Count)
- {
- Vector2 texSize = new Vector2(w, h);
- for (int i = 0; i < pointsTF2.childCount; i++)
- {
- Transform pointTF = pointsTF2.GetChild(i);
- Vector2 pos = points[i];
- pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
- pointTF.gameObject.SetActive(true);
- showPoints = true;
- }
- }
- else {
- for (int i = 0; i < pointsTF2.childCount; i++)
- {
- Transform pointTF = pointsTF2.GetChild(i);
- pointTF.gameObject.SetActive(false);
- showPoints = false;
- }
- }
- //绘制数据
- DrawTestLine();
- }
- #region 测试数据绘制
- [SerializeField] private Toggle curToggle;
- [SerializeField] private Toggle autoToggle; // 控制 AutoUILineGenerator 的 Toggle
- [SerializeField] private Toggle semiAutoToggle; // 控制 SemiAutoUILineGenerator 的 Toggle
- [SerializeField] private Toggle manualToggle; // 控制 ManualUILineGenerator 的 Toggle
- [SerializeField] LineGenerator CurUILineGenerator;//当前结果屏幕线条
- [SerializeField] LineGenerator AutoUILineGenerator;//第一个结果屏幕线条
- [SerializeField] LineGenerator SemiAutoUILineGenerator;//第二个结果屏幕线条
- [SerializeField] LineGenerator ManualUILineGenerator;//第三个结果屏幕线条
- [SerializeField] private Dropdown dropdown; // 引用场景中的 Dropdown 组件
- [SerializeField] RawImage _cameraRenderTest5;
- [SerializeField] RawImage _cameraRenderTest6;
- void DrawTestLine()
- {
- Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
- // 判断 texSize 是否为有效值
- if (texSize == Vector2.zero)
- {
- Debug.LogWarning("Texture size is zero, cannot proceed with line drawing.");
- return;
- }
- // 设置三个屏幕四边形和线条生成器
- QuadrilateralInCamera[] screenQuads = new QuadrilateralInCamera[] {
- ScreenLocate.Main.ScreenIdentification?.QuadAuto,
- ScreenLocate.Main.ScreenIdentification?.QuadSemiAuto,
- ScreenLocate.Main.ScreenIdentification?.QuadManual
- };
- LineGenerator[] lineGenerators = new LineGenerator[] {
- AutoUILineGenerator,
- SemiAutoUILineGenerator,
- ManualUILineGenerator
- };
- for (int i = 0; i < screenQuads.Length; i++)
- {
- if (screenQuads[i] == null)
- {
- Debug.LogWarning($"Screen quadrilateral {i} is null, skipping this line.");
- continue;
- }
- if (lineGenerators[i] == null)
- {
- Debug.LogWarning($"Line generator {i} is null, skipping this line.");
- continue;
- }
- lineGenerators[i].Points = ConvertQuadToPoints(screenQuads[i], texSize);
- }
- // 清除旧选项并填充新的选项
- dropdown.ClearOptions();
- List<string> options = new List<string>();
- //for (int i = 0; i < screenQuads.Length; i++)
- //{
- // options.Add($"Quad {i + 1}");
- //}
- //options.Add("自动识别");
- //options.Add("半自动识别");
- //options.Add("手动识别");
- options.Add(TextAutoLanguage2.GetTextByKey("AutoRecognition")); // "自动识别"
- options.Add(TextAutoLanguage2.GetTextByKey("SemiAutoRecognition")); // "半自动识别"
- options.Add(TextAutoLanguage2.GetTextByKey("ManualRecognition")); // "手动识别"
- dropdown.AddOptions(options);
- // 添加监听器来处理选择事件
- dropdown.onValueChanged.AddListener((index) => {
- OnDropdownValueChanged(index, screenQuads);
- });
- if (screenQuads[0] != null || screenQuads[1] != null)
- {
- Texture texImage6 = ScreenLocate.Main.OutputTextures[5];
- if (texImage6 != null) _cameraRenderTest6.texture = texImage6;
- }
- if (ScreenLocate.quadUnityVectorList.Count == 4) {
- //绘制白色线段
- var lo = new Vector2(-0.5f, -0.5f);
- CurUILineGenerator.Points = new Vector2[4] {
- 2 * (ScreenLocate.quadUnityVectorList[0] + lo),
- 2 * (ScreenLocate.quadUnityVectorList[1] + lo),
- 2 * (ScreenLocate.quadUnityVectorList[3] + lo),
- 2 * (ScreenLocate.quadUnityVectorList[2] + lo) };
- }
- }
- // 当下拉框选项更改时调用的方法
- private void OnDropdownValueChanged(int index, QuadrilateralInCamera[] screenQuads)
- {
- if (index >= 0 && index < screenQuads.Length)
- {
- if (screenQuads[index] != null)
- {
- QuadrilateralInCamera selectedQuad = screenQuads[index];
- Debug.Log($"Selected Quad {index + 1}: {selectedQuad}");
- CurUILineGenerator.Points = ConvertQuadToPoints(selectedQuad, ScreenLocate.Main.getUVCCameraInfoSize);
- }
- else
- {
- Debug.LogWarning($"Selected Quad {index + 1} is null.");
- }
- }
- else
- {
- Debug.LogWarning("所选索引超出范围!");
- }
- }
- /// <summary>
- /// 提取转换四边形的方法
- /// </summary>
- /// <param name="quad"></param>
- /// <param name="texSize"></param>
- /// <returns></returns>
- public Vector2[] ConvertQuadToPoints(QuadrilateralInCamera quad, Vector2 texSize)
- {
- if (quad == null || quad.Quad == null || quad.Quad.Count < 4)
- {
- Debug.LogWarning("Invalid quadrilateral data provided.");
- return new Vector2[0]; // 返回空数组以避免异常
- }
- Vector2 offset = new Vector2(-0.5f, -0.5f); // 假设 'lo' 是某个已定义的偏移量
- return new Vector2[4] {
- 2 * (new Vector2(quad.Quad[0].x / texSize.x, quad.Quad[0].y / texSize.y) + offset),
- 2 * (new Vector2(quad.Quad[1].x / texSize.x, quad.Quad[1].y / texSize.y) + offset),
- 2 * (new Vector2(quad.Quad[3].x / texSize.x, quad.Quad[3].y / texSize.y) + offset),
- 2 * (new Vector2(quad.Quad[2].x / texSize.x, quad.Quad[2].y / texSize.y) + offset)
- };
- }
- public Vector2[] ConvertPointsToCoordinates(Vector2[] points, Vector2 texSize, Vector2 pivot)
- {
- if (points == null || points.Length < 1)
- {
- Debug.LogWarning("Invalid point data provided.");
- return new Vector2[0]; // 返回空数组以避免异常
- }
- Vector2 offset = new Vector2(-0.5f, -0.5f); // 将坐标从中心对齐到左下角对齐
- List<Vector2> transformedPoints = new List<Vector2>();
- // 遍历所有传入的点进行转换
- foreach (var point in points)
- {
- // 转换每个点,考虑 texSize 和 pivot 偏移
- Vector2 transformedPoint = 2 * ((point / texSize) + offset + pivot);
- transformedPoints.Add(transformedPoint);
- }
- return transformedPoints.ToArray();
- }
- void initToggle()
- {
- // 监听 Toggle 值的变化
- if (curToggle != null)
- curToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(CurUILineGenerator, isOn));
- // 监听 Toggle 值的变化
- if (autoToggle != null)
- autoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(AutoUILineGenerator, isOn));
- if (semiAutoToggle != null)
- semiAutoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(SemiAutoUILineGenerator, isOn));
- if (manualToggle != null)
- manualToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(ManualUILineGenerator, isOn));
- }
- // 控制 LineGenerator 的启用/禁用
- private void ToggleLineGenerator(LineGenerator lineGenerator, bool isOn)
- {
- if (lineGenerator != null && lineGenerator.enabled != isOn)
- {
- lineGenerator.enabled = isOn;
- Debug.Log($"{lineGenerator.name} is now {(isOn ? "enabled" : "disabled")}");
- }
- }
- /// <summary>
- /// 设置全部显示
- /// </summary>
- /// <param name="value"></param>
- private void SetAllToggle(bool value) {
- ToggleLineGenerator(CurUILineGenerator, value);
- ToggleLineGenerator(AutoUILineGenerator, value);
- ToggleLineGenerator(SemiAutoUILineGenerator, value);
- ToggleLineGenerator(ManualUILineGenerator, value);
- }
- /// <summary>
- /// 放大时候同步一次toggle
- /// </summary>
- private void SyncAllToggle()
- {
- ToggleLineGenerator(CurUILineGenerator, curToggle.isOn);
- ToggleLineGenerator(AutoUILineGenerator, autoToggle.isOn);
- ToggleLineGenerator(SemiAutoUILineGenerator, semiAutoToggle.isOn);
- ToggleLineGenerator(ManualUILineGenerator, manualToggle.isOn);
- }
- // 下拉菜单用于显示纹理名称
- public Dropdown textureDropdown;
- // 按钮用于导出选中的纹理
- public Button exportSelectedButton;
- // 按钮用于导出所有纹理
- public Button exportAllButton;
- // 定义纹理名称
- string[] textureNames;
- /// <summary>
- /// 更新一下菜单
- /// </summary>
- public void UpdateLanguage() {
- string[] _textureNames = {
- TextAutoLanguage2.GetTextByKey("ScreenAOriginal"), // "A屏幕原图"
- TextAutoLanguage2.GetTextByKey("SemiAutoSegmentB"), // "B半自动识别线段"
- TextAutoLanguage2.GetTextByKey("BlackWhiteContrastC"), // "C黑白色差"
- TextAutoLanguage2.GetTextByKey("RecognitionResultD"), // "D识别结果"
- TextAutoLanguage2.GetTextByKey("ColorContrastOverlayE"), // "E色差叠加识别结果"
- TextAutoLanguage2.GetTextByKey("SemiAutoAlternativeF") // "F半自动备选线段"
- };
- textureNames = _textureNames;
- // 设置下拉菜单的选项
- textureDropdown.ClearOptions();
- textureDropdown.AddOptions(new System.Collections.Generic.List<string>(textureNames));
- }
- void initExport() {
- UpdateLanguage();
- // 添加导出选中纹理的按钮点击事件
- exportSelectedButton.onClick.AddListener(() => SaveTextureToLocal(textureDropdown.value));
- // 添加导出所有纹理的按钮点击事件
- exportAllButton.onClick.AddListener(SaveAllTexturesToLocal);
- }
- /// <summary>
- /// 导出所有纹理
- /// </summary>
- public void SaveAllTexturesToLocal()
- {
- for (int i = 0; i < textureNames.Length; i++)
- {
- SaveTextureToLocal(i); // 调用之前定义的保存方法
- }
- }
- /// <summary>
- /// 导出图片
- /// </summary>
- /// <param name="index"></param>
- public void SaveTextureToLocal(int index)
- {
- Texture2D[] outputTexture2D = ScreenLocate.Main.OutputTextures;
- if (outputTexture2D == null || index >= outputTexture2D.Length || outputTexture2D[index] == null)
- {
- Debug.LogError("Invalid texture index or texture is null.index:"+ index);
- return;
- }
- // 定义保存路径
- string time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
- string baseName = $"{time}_Texture_{index}";
- // 检查索引是否在命名数组内
- string fileName = index < textureNames.Length ? textureNames[index] : $"Texture_{index}";
- #if UNITY_ANDROID && !UNITY_EDITOR_WIN
- string path = System.IO.Path.Combine("/storage/emulated/0/Download", $"{baseName}_{fileName}.png"); //public
- #else
- string path = System.IO.Path.Combine(Application.persistentDataPath, $"{baseName}_{fileName}.png");
- #endif
- // 编码纹理为 PNG 格式
- byte[] bytes = outputTexture2D[index].EncodeToPNG();
- // 将字节写入文件
- System.IO.File.WriteAllBytes(path, bytes);
- Debug.Log($"Texture saved as: {path}");
- }
- //下面是处理对象放大缩小
- public RectTransform cameraObj1; // 拖拽你的 CameraSize1 对象到此字段
- public Button toggleButton; // 缩小时使用的按钮
- private Vector2 originalSize;
- private Vector2 originalAnchoredPosition; // 使用 anchoredPosition 代替 localPosition
- private Vector2 originalAnchorMin;
- private Vector2 originalAnchorMax;
- private int originalSiblingIndex; // 保存初始的层级索引
- private bool isFullscreen = false;
- /// <summary>
- /// 测试效果屏幕数据初始化
- /// </summary>
- void InitFullScreen() {
- if (cameraObj1 != null)
- {
- // 保存初始大小、位置和层级索引
- originalSize = cameraObj1.sizeDelta;
- originalAnchoredPosition = cameraObj1.anchoredPosition;
- originalAnchorMin = cameraObj1.anchorMin; // 记录初始 anchorMin
- originalAnchorMax = cameraObj1.anchorMax; // 记录初始 anchorMax
- originalSiblingIndex = cameraObj1.GetSiblingIndex();
- // 为 cameraObj1 添加点击事件
- cameraObj1.GetComponent<Button>().onClick.AddListener(ToggleFullscreen);
- toggleButton.transform.parent.gameObject.SetActive(false);
- }
- if (toggleButton != null)
- {
- // 为按钮添加点击事件以恢复大小
- toggleButton.onClick.AddListener(RestoreSize);
- }
- }
- void ToggleFullscreen()
- {
- if (cameraObj1 == null) return;
- if (!isFullscreen)
- {
- // 设置锚点为全屏,调整位置和偏移量
- cameraObj1.anchorMin = Vector2.zero;
- cameraObj1.anchorMax = Vector2.one;
- cameraObj1.offsetMin = Vector2.zero;
- cameraObj1.offsetMax = Vector2.zero;
- cameraObj1.anchoredPosition = Vector3.zero;
- cameraObj1.SetSiblingIndex(cameraObj1.parent.childCount - 1); // 设置为最上层
- //刷新一次点
- SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
- toggleButton.transform.parent.gameObject.SetActive(true);
- isFullscreen = true;
- //放大情况根据toggle来显示
- SyncAllToggle();
- }
- }
- void RestoreSize()
- {
- if (cameraObj1 == null || !isFullscreen) return;
- // 恢复锚点和偏移量
- cameraObj1.anchorMin = originalAnchorMin; // 使用在 Start() 中记录的初始锚点
- cameraObj1.anchorMax = originalAnchorMax; // 使用在 Start() 中记录的初始锚点
- cameraObj1.sizeDelta = originalSize;
- cameraObj1.anchoredPosition = originalAnchoredPosition; // 恢复为初始 anchoredPosition
- cameraObj1.SetSiblingIndex(originalSiblingIndex); // 恢复到原本的层级索引
- //刷新一次点
- SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
- toggleButton.transform.parent.gameObject.SetActive(false);
- isFullscreen = false;
- }
- #endregion
- public void SetLocatePointsToCameraRenderTest(List<Vector2> points, float w, float h)
- {
- Transform pointsTF2 = _cameraRender.transform.Find("PointsTest");
- if (pointsTF2.childCount == points.Count)
- {
- Vector2 texSize = new Vector2(w, h);
- for (int i = 0; i < pointsTF2.childCount; i++)
- {
- Transform pointTF = pointsTF2.GetChild(i);
- Vector2 pos = points[i];
- pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
- pointTF.gameObject.SetActive(true);
- }
- }
- else
- {
- for (int i = 0; i < pointsTF2.childCount; i++)
- {
- Transform pointTF = pointsTF2.GetChild(i);
- pointTF.gameObject.SetActive(false);
- }
- }
- }
- void SetShakeFilterValue(float v)
- {
- shakeFilterValue.Set(v);
- _sliderShakeFilter.SetValueWithoutNotify(shakeFilterValue.Get());
- _sliderShakeFilter.transform.Find("Value").GetComponent<Text>().text = shakeFilterValue.Get().ToString("f1");
- infraredCameraHelper.SetShakeFilterValue(shakeFilterValue.Get());
- }
- /// <summary>
- /// 重新设置分辨率
- /// </summary>
- /// <param name="index"></param>
- public void resolutionRestartApp(int index)
- {
- #if UNITY_ANDROID
- //StartCoroutine(RestartOrKillApp());
- //获取第一个分辨率设置后设置size
- switch (index)
- {
- case 0:
- infraredCameraHelper.SetHighCameraResolution();
- resoution.Set(index);
- _dropdownResolution2.SetValueWithoutNotify(index);
- break;
- case 1:
- infraredCameraHelper.SetLowCameraResolution();
- resoution.Set(index);
- _dropdownResolution2.SetValueWithoutNotify(index);
- break;
- }
- #endif
- }
- /// <summary>
- /// 初始化时候,设置的值
- /// </summary>
- /// <param name="index"></param>
- public Vector2 SetDefByIndex(int index = 0)
- {
- //SetResolutionNew 里面对应的下标
- Vector2 vec2 = new Vector2(320, 240);
- switch (index)
- {
- case 0:
- vec2 = new Vector2(320, 240);
- break;
- case 1:
- vec2 = new Vector2(160, 120);
- break;
- }
- return vec2;
- }
- /// <summary>
- /// 当 Dropdown 选择变化时的处理方法
- /// </summary>
- /// <param name="OnResolutionChanged">320x240</param>
- private void OnResolutionChanged(int index)
- {
- #if UNITY_ANDROID
- Debug.Log("Selected Resolution: " + index);
- // 将选定的分辨率转换为实际的宽度和高度
- // 并且需要判断是否存在最低分辨率
- if (index == 1 && currentCameraInfo.ContainsResulutionKey("160x120"))
- {
- // 在这里你可以根据实际需要设置屏幕分辨率或进行其他操作
- infraredCameraHelper.SetLowCameraResolution();
- // 保存选择的分辨率到 PlayerPrefs
- resoution.Set(index);
- }
- else if(index == 0){
- //如果是0就 使用高分辨率
- infraredCameraHelper.SetHighCameraResolution();
- // 保存选择的分辨率到 PlayerPrefs
- resoution.Set(index);
- }
- #endif
- }
- /// <summary>
- /// 野鸭关卡测试初始值
- /// </summary>
- /// <param name="optionIndex"></param>
- public void SetDuckLevelTest(int optionIndex)
- {
- //选择下标+1
- int v = optionIndex + 1;
- duckHunterLevel.Set(v);
- int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
- _duckLevelDropdown.SetValueWithoutNotify(defLevel);
- //_duckLevelDropdown.transform.Find("Value").GetComponent<Text>().text = defLevel+"";
- }
- void OnClick_Reset()
- {
- //SetBrightness(1);
- //SetSaturation(1);
- //SetContrast(1);
- SetShakeFilterValue(6);
- SetLineWidth(4);
- SetFanWidth(90);
- SetInfraredFilterValue(0.8f);
- SetCaptureValue(30.0f);
- SetDelayValue(30.0f);
- //重置为第一关
- SetDuckLevelTest(0);
- }
- public void OnClickClearAll() {
- PlayerPrefs.DeleteAll();
- // 保存更改
- PlayerPrefs.Save();
- StartCoroutine(RestartOrKillApp());
- }
- void OnClick_ScreenLocateManual()
- {
- bool bEnter = true;
- if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
- {
- if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
- {
- bEnter = true;
- }
- else
- {
- bEnter = false;
- //只有红外设备才能进行屏幕识别
- PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
- }
- }
- if (bEnter)
- {
- ViewManager2.ShowView(ViewManager2.Path_InfraredScreenPositioningView);
- FindObjectOfType<InfraredScreenPositioningView>().enterFromInfraredDemo = true;
- }
- }
- void OnClick_ScreenLocateManualAuto()
- {
- bool bEnter = true;
- if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
- {
- if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
- {
- bEnter = true;
-
- }
- else
- {
- bEnter = false;
- //只有红外设备才能进行屏幕识别
- PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
- }
- }
- if (bEnter) {
- ResetCenterOffset();
- ResetPositioningData();
- infraredCameraHelper.EnterScreenLocateManualAuto();
- }
-
- }
- public void OnClick_SetAdjustPointsOffset()
- {
- var _sl = ScreenLocate.Main;
- var buffer = _sl.infraredSpotBuffer;
- if (buffer != null)
- {
- for (int i = 0; i < buffer.Length; i++)
- {
- if (buffer[i].CameraLocation != null)
- {
- Debug.Log("CameraLocation:"+buffer[i].CameraLocation.Value);
- var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[i].CameraLocation.Value, "CameraLocation");
- Debug.Log("CenterOffset: " + centerOffset);
- var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[i].ScreenUV.Value, "ScreenUV");
- Debug.Log("UvCenterOffset: " + uvCenterOffset);
- //如果是新手教程场景里面的校准
- InfraredGuider infraredGuiderObj = FindObjectOfType<InfraredGuider>();
- if (infraredGuiderObj != null)
- {
- GameObject infraredGuiderGameObject = infraredGuiderObj.gameObject;
- infraredGuiderGameObject.GetComponent<InfraredGuider>().SetTitleAfterCalibration();
- }
- }
- }
- }
- }
- /// <summary>
- /// 重置中心点
- /// </summary>
- public void ResetCenterOffset() {
- infraredCameraHelper.ResetCenterOffset();
- }
- /// <summary>
- /// 撤销中心点
- /// </summary>
- public void RevokeCenterOffset()
- {
- infraredCameraHelper.RevokeCenterOffset();
- }
- /// <summary>
- /// 重置定位数据
- /// </summary>
- public void ResetPositioningData(bool bSyncLocal = false) {
- infraredCameraHelper.ClearInfraredPositioningData(bSyncLocal);
- }
- void SetCaptureValue(float v)
- {
- captureValue.Set(v);
- _sliderCapture.SetValueWithoutNotify(captureValue.Get());
- _sliderCapture.transform.Find("Value").GetComponent<Text>().text = captureValue.Get().ToString("f1");
- infraredCameraHelper.SetCapture((int)captureValue.Get());
- }
- void SetDelayValue(float v)
- {
- delayValue.Set(v);
- _sliderDelay.SetValueWithoutNotify(delayValue.Get());
- _sliderDelay.transform.Find("Value").GetComponent<Text>().text = delayValue.Get().ToString("f1");
- infraredCameraHelper.SetDelay((int)delayValue.Get());
- }
- #endregion
- #region 相机感光度(默认修改对比度)
- public void onSetSliderCustomValue(Slider _slider, float min = 0.0f, float max = 10.0f)
- {
- onSetSliderValue(_slider, "PU_CONTRAST", min, max);
- }
- public void onSliderCustomEvent(float value, float min = 0.0f, float max = 10.0f)
- {
- onSliderEvent(value, "PU_CONTRAST", min, max);
- }
- public void onSetSliderCustomBrightnessValue(Slider _slider, float min = 0.0f, float max = 10.0f)
- {
- onSetSliderValue(_slider, "PU_BRIGHTNESS", min, max);
- }
- public void onSliderCustomBrightnessEvent(float value, float min = 0.0f, float max = 10.0f)
- {
- onSliderEvent(value, "PU_BRIGHTNESS", min, max);
- }
- public void onSetSliderValue(Slider _slider,string typeStr = "PU_CONTRAST", float min = 0.0f, float max = 10.0f)
- {
- if (BluetoothWindows.IsWindows()) {
- float v = typeStr == "PU_CONTRAST"?infraredCameraHelper.GetContrast(): infraredCameraHelper.GetBrightness();
- // 目标区间 [0, 10] 的边界值
- double targetMin = min;
- double targetMax = max;
- double originalMin = -1;
- double originalMax = 1;
- // 计算转换后的值
- double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
- Debug.Log("PC获取相机的感光度 "+ typeStr + " :" + v + " = " + v2);
- _slider.SetValueWithoutNotify((float)v2);
- return;
- }
- //功能也改为UVC的对比度
- if (running)
- {
- //string typeStr = "PU_CONTRAST";//"PU_BRIGHTNESS";
- //UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
- UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
- float v = currentCameraInfo.GetValue(typeStr); // infraredCameraHelper.GetBrightness();
- //float v2 = (v / _UVCCtrlInfo.max) * 10;
- // 目标区间 [0, 10] 的边界值
- double targetMin = min;
- double targetMax = max;
- double originalMin = _UVCCtrlInfo.min;
- double originalMax = _UVCCtrlInfo.max;
- // 计算转换后的值
- double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
- Debug.Log("获取相机的感光度" + typeStr + ": " + v + " = " + v2);
- _slider.SetValueWithoutNotify((float)v2);
- }
- else _slider.SetValueWithoutNotify(5);
- }
-
- public void onSliderEvent(float value, string typeStr = "PU_CONTRAST", float min = 0.0f,float max = 10.0f)
- {
- // string typeStr = "PU_CONTRAST";// "PU_BRIGHTNESS";
- //pc
- if (BluetoothWindows.IsWindows())
- {
- Transform trans = _cameraParameterPanel.transform.Find(typeStr);
- Slider slider = trans.GetComponent<Slider>();
- Text textObj = trans.Find("text").GetComponent<Text>();
- // 原始区间和目标区间的边界值
- double originalMin = min;
- double originalMax = max;
- double targetMin = -1;
- double targetMax = 1;
- // 计算转换后的值
- double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
- float _current = (float)result;
- //Debug.Log("_current:" + _current + " , result:" + result);
- textObj.text = _current + "";
- slider.value = _current;
- if (typeStr == "PU_CONTRAST")
- {
- infraredCameraHelper.SetContrast(_current);
- pcCONTRAST.Set(_current);
- }
- else {
- infraredCameraHelper.SetBrightness(_current);
- pcBRIGHTNESS.Set(_current);
- }
- return;
- }
- //修改亮度时,调试界面的亮度也应该一起修改
- //功能也改为UVC的对比度
- if (running)
- {
- //Slider slider = transform.Find("InfraredCamera/Layout/SliderBrightness")
- // .GetComponent<Slider>();
- // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
- Transform trans = _cameraParameterPanel.transform.Find(typeStr);
- Slider slider = trans.GetComponent<Slider>();
- Text textObj = trans.Find("text").GetComponent<Text>();
- UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
- int _currentUVCValue = currentCameraInfo.GetValue(typeStr);
- //value 0 ~ 10
- // 原始区间和目标区间的边界值
- double originalMin = min;
- double originalMax = max;
- double targetMin = _UVCCtrlInfo.min;
- double targetMax = _UVCCtrlInfo.max;
- // 计算转换后的值
- double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
- int _current = (int)(result);
- Debug.Log("_current:" + value + " , result:" + result);
- textObj.text = _current + "";
- slider.value = _current;
- //dUVCParameters.GetValueOrDefault(typeStr).Set(_current);
- //存储初始值,设置一次到UVC参数
- if (_currentUVCValue != _current) currentCameraInfo.SetValue(typeStr, _current);
- }
- }
- public static double MapValue(double value, double originalMin, double originalMax, double targetMin, double targetMax)
- {
- // 线性插值公式
- return targetMin + (value - originalMin) * (targetMax - targetMin) / (originalMax - originalMin);
- }
- #endregion
- #region 绘制线段部分
- public void SetLineWidth(float v)
- {
- lineWidth.Set(v);
- _sliderLineWidth.SetValueWithoutNotify(lineWidth.Get());
- _sliderLineWidth.transform.Find("Value").GetComponent<Text>().text = lineWidth.Get().ToString("f1");
- }
- public void SetFanWidth(float v)
- {
- fanWidth.Set(v);
- _fanWidth.SetValueWithoutNotify(fanWidth.Get());
- _fanWidth.transform.Find("Value").GetComponent<Text>().text = fanWidth.Get().ToString("f1");
- }
-
- #endregion
- #region 亮度检测部分
- public void SetInfraredFilterValue(float v)
- {
- infraredFileterValue.Set(v);
- _infraredFilter.SetValueWithoutNotify(infraredFileterValue.Get());
- _infraredFilter.transform.Find("Value").GetComponent<Text>().text = infraredFileterValue.Get().ToString("f1");
- infraredCameraHelper.SetInfraredLocateBrightnessThreshold(infraredFileterValue.Get());
- }
- #endregion
- public void resetInfraredPlayerPrefs()
- {
- //测试用
- PlayerPrefs.DeleteKey("entry-guider-infrared-" + LoginMgr.myUserInfo.id);
- PlayerPrefs.DeleteKey("hideInfraredBowAndArrow");
- }
- #region 显示Log部分信息
- [SerializeField] Text _calibrationFixedText;
- [SerializeField] Text _cameraSizeText;
- [SerializeField] Text _quadUnityVectorListText;
- /// <summary>
- /// 校准时候的固定值分辨率
- /// </summary>
- /// <param name="v"></param>
- public void SetCalibrationFixedText(Vector2 v)
- {
- _calibrationFixedText.text = v.x + "*" + v.y;
- }
- /// <summary>
- /// 渲染摄像机当前分辨率
- /// </summary>
- /// <param name="v"></param>
- public void SetCameraSizeText(Vector2 v)
- {
- _cameraSizeText.text = v.x + "*" + v.y;
- }
- /// <summary>
- /// 渲染摄像机识别点
- /// </summary>
- /// <param name="v"></param>
- public void SetQuadUnityVectorListText(string v)
- {
- _quadUnityVectorListText.text = v;
- }
- #endregion
- }
- public class ParamFloatValue
- {
- private string _saveKey;
- private float _valueDefault;
- private bool _valueLoaded;
- private float _value;
- public ParamFloatValue(string saveKey, float valueDefault)
- {
- _saveKey = saveKey;
- _valueDefault = valueDefault;
- }
- public float Get()
- {
- if (!_valueLoaded) _value = PlayerPrefs.GetFloat(_saveKey, _valueDefault);
- return _value;
- }
- public float GetDefault() {
- return _valueDefault;
- }
- public string GetKey()
- {
- return _saveKey;
- }
- public void Set(float value)
- {
- _value = value;
- PlayerPrefs.SetFloat(_saveKey, _value);
- PlayerPrefs.Save();
- }
- /// <summary>
- /// 重置成默认值
- /// </summary>
- public void Reset() {
- PlayerPrefs.SetFloat(_saveKey, _valueDefault);
- PlayerPrefs.Save();
- }
- }
|