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; using o0InfraredLocate.ZIM; public class InfraredDemo : JCUnityLib.ViewBase { public static bool DebugInEditor = true; public static InfraredDemo _ins; [SerializeField] RectTransform canvasRectTransform; public Button mBtnSee; Reporter reporter; public Text FPSText; public static void Create() { if (_ins) return; GameObject o = Instantiate(Resources.Load("InfraredDemo")); DontDestroyOnLoad(o); _ins = o.GetComponent(); //添加一个父物体 o.transform.SetParent(ViewMgr.Instance.transform.Find("1").transform); CanvasScaler canvasScaler = o.GetComponent(); if (canvasScaler != null) { Destroy(canvasScaler); } RectTransform rectTransform = o.GetComponent(); rectTransform.anchorMin = Vector2.zero; // 左下角对齐父级 rectTransform.anchorMax = Vector2.one; // 右上角对齐父级 rectTransform.offsetMin = Vector2.zero; // 移除左下角偏移 rectTransform.offsetMax = Vector2.zero; // 移除右上角偏移 rectTransform.localScale = Vector3.one; // 确保缩放为 1 //直接初始化一次 _ins.InitInfraredCamera(); } void Start() { //生成一个控制台 GameObject obj = UserPlayer.InitReturnLogReporter() as GameObject; if (obj != null) { reporter = obj.GetComponent(); Application.logMessageReceived += HandleLog; // 模拟错误日志 // Debug.LogError("Test Error: This is a simulated error message."); // 模拟异常日志 // Debug.LogException(new System.Exception("Test Exception: This is a simulated exception.")); } if (Application.platform != RuntimePlatform.WindowsEditor) DebugInEditor = false; SetVisiable(false); InitDebugScreenPoint(); // gameObject.AddComponent(); if (CommonConfig.StandaloneModeOrPlatformB) { mBtnSee.gameObject.SetActive(false); } else { mBtnSee.interactable = false; mBtnSee.transform.Find("Text").GetComponent().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 OnDestroy() { if(reporter!= null) Application.logMessageReceived -= HandleLog; } void Update() { UpdateInfraredCamera(); //UpdateDebugScreenPoint(); if(reporter!=null) FPSText.text = "FPS:" + reporter.fps; } 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 onApplyToNext = (t) => { updateBtnSee(); }; mBtnSee.GetComponentInChildren().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 = _visiable ? TextAutoLanguage2.GetTextByKey("HideInterface") : TextAutoLanguage2.GetTextByKey("DebugInfrared");//"隐藏界面" : "调试红外"; } Text _spText; Vector2 _screenPoint; void InitDebugScreenPoint() { _spText = transform.Find("SPText").GetComponent(); //_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; /// /// 测试texture /// public RawImage MyCameraRender2 { get { return _cameraRender2; } set { _cameraRender2 = value; } } //[SerializeField] MaintainAspectRatio _MaintainAspectRatio; [SerializeField] List _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 dUVCParameters = new Dictionary(); //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 ParamVector2Value cameraLocationValue = new ParamVector2Value("ic_cameraLocation", Vector2.zero); public ParamVector2Value screenUVValue = new ParamVector2Value("ic_screenUV", Vector2.zero); //线段宽度阈值 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 ParamFloatValueCameraSlider = new Dictionary(); 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(); //labelObj.text = sliderNameArray[i]; labelObj.gameObject.AddComponent().SetTextKey(sliderNameArrayKey[i]); Toggle toggle = toggleObject.GetComponent(); 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(); Text textObj = sliderObject.transform.Find("text").GetComponent(); Text titleTextObj = sliderObject.transform.Find("title").GetComponent(); //titleTextObj.text = sliderNameArray[i];//类型名字 titleTextObj.gameObject.AddComponent().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(); Text textObj = trans.Find("text").GetComponent(); 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(); Text textObj = trans.Find("text").GetComponent(); 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(); Text textObj = sliderObject.transform.Find("text").GetComponent(); Text titleTextObj = sliderObject.transform.Find("title").GetComponent(); //titleTextObj.text = TextAutoLanguage2.GetTextByKey(sliderNameArrayPCKey[i]);// sliderNameArrayPC[i];//类型名字 titleTextObj.gameObject.AddComponent().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(); Text textObj = trans.Find("text").GetComponent(); //重置的值 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 = "调试红外"; updateBtnSee(); //延迟重新设置一次分辨率 StartCoroutine(delayInitOhterInfo(camera)); }; //屏幕变化时候 infraredCameraHelper.OnUVCPosUpdate += (list) => { Debug.Log("OnUVCPosUpdate list.Count" + list.Count); SetLocatePointsToCameraRender(list, 1, 1); //InfraredScreenPositioningView 页面 if (list.Count == 4) { FindObjectOfType()?.SyncScreenPosition(); } else { FindObjectOfType()?.onReset(); } }; //算法准备事件 infraredCameraHelper.OnScreenLocateIsReady += () => { Debug.Log("OnScreenLocateIsReady."); //b端设置偏移值 if (CommonConfig.StandaloneModeOrPlatformB) { InitCenterOffset(); } //设置双点数据 InitCenterOffsets(PlayerType.FirstPlayer); InitCenterOffsets(PlayerType.SecondPlayer); }; } } private void updateDropdownResolution2() { string[] resolutions = { TextAutoLanguage2.GetTextByKey("HighResolution"), TextAutoLanguage2.GetTextByKey("LowResolution") }; // 清除默认选项 _dropdownResolution2.ClearOptions(); // 将分辨率字符串数组转换为 Dropdown 选项 _dropdownResolution2.AddOptions(new List(resolutions)); } /// /// 初始化一些游戏配置 /// /// 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 = "调整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); ////b端设置偏移值 //if (CommonConfig.StandaloneModeOrPlatformB) { // InitCenterOffset(); //} } /// /// 初始化时候获取设置和存储来控制显示准心 /// /// public bool bInitCrosshairShow() { return UserSettings.ins.openCrossHair && getCrosshairValue() == 1 ? true : false; } /// /// 获取弓箭准心存储值 /// /// 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(); } /// /// 获取并且初始化一次记录点的数据 /// /// 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("currentActivity"); var pm = currentActivity.Call("getPackageManager"); var intent = pm.Call("getLaunchIntentForPackage", Application.identifier); intent.Call("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("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 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 options = new List(); //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("所选索引超出范围!"); } } /// /// 提取转换四边形的方法 /// /// /// /// 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 transformedPoints = new List(); // 遍历所有传入的点进行转换 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")}"); } } /// /// 设置全部显示 /// /// private void SetAllToggle(bool value) { ToggleLineGenerator(CurUILineGenerator, value); ToggleLineGenerator(AutoUILineGenerator, value); ToggleLineGenerator(SemiAutoUILineGenerator, value); ToggleLineGenerator(ManualUILineGenerator, value); } /// /// 放大时候同步一次toggle /// 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; /// /// 更新一下菜单 /// 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(textureNames)); } void initExport() { UpdateLanguage(); // 添加导出选中纹理的按钮点击事件 exportSelectedButton.onClick.AddListener(() => SaveTextureToLocal(textureDropdown.value)); // 添加导出所有纹理的按钮点击事件 exportAllButton.onClick.AddListener(SaveAllTexturesToLocal); } /// /// 导出所有纹理 /// public void SaveAllTexturesToLocal() { for (int i = 0; i < textureNames.Length; i++) { SaveTextureToLocal(i); // 调用之前定义的保存方法 } } /// /// 导出图片 /// /// 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; /// /// 测试效果屏幕数据初始化 /// 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