InfraredScreenPositioningView.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using LineUI;
  5. using UnityEngine.UI;
  6. using System.Linq;
  7. using ZIM;
  8. using o0;
  9. using Color = UnityEngine.Color;
  10. using InfraredManager;
  11. using Org.BouncyCastle.Asn1.Crmf;
  12. using ZIM.Unity;
  13. using o0.Project;
  14. using UnityEngine.SceneManagement;
  15. public enum ScreenPositioningStep {
  16. None, //
  17. Start,//开始界面
  18. AutoEnd,//自动定位结束后界面
  19. Marker,//进行标记界面
  20. LightCtrl,//灯光调整界面
  21. Successful,//结果选择界面
  22. }
  23. public class LinePosition
  24. {
  25. public int index;
  26. public List<Vector3> pos;
  27. }
  28. public class InfraredScreenPositioningView : JCUnityLib.ViewBase
  29. {
  30. [SerializeField]
  31. RectTransform canvasRectTransform;
  32. [SerializeField]
  33. RectTransform draggableParent;
  34. [SerializeField]
  35. GameObject cameraLight;
  36. [SerializeField]
  37. RectTransform pointsParent;
  38. [SerializeField]
  39. RectTransform pos1;
  40. [SerializeField]
  41. RectTransform pos2;
  42. [SerializeField]
  43. RectTransform pos3;
  44. [SerializeField]
  45. RectTransform pos4;
  46. //画线时候的点偏移量
  47. float offset = 10;
  48. [SerializeField]
  49. Line line;
  50. List<LinePosition> oldLinePosition;
  51. Vector3 beginPos;
  52. Vector3 endPos;
  53. //相机感光部分
  54. [SerializeField]
  55. Slider slider;
  56. [SerializeField]
  57. GameObject textTip1;
  58. [SerializeField]
  59. GameObject textTip2;
  60. [SerializeField]
  61. Button btnAuto;
  62. [SerializeField]
  63. Button btnHandMovement;
  64. [SerializeField]
  65. BtnRecordInfrared btnRecordInfrared;
  66. bool bAuto = true;
  67. [SerializeField] Color normalColor = Color.white;
  68. [SerializeField] Color highlightedColor = Color.green;
  69. [SerializeField] Color normalTextColor = Color.black;
  70. [SerializeField] Color highlightedTextColor = Color.white;
  71. [Header("Common Layout Group")]
  72. [SerializeField]
  73. GameObject mask;
  74. [SerializeField]
  75. Line maskLine;
  76. [SerializeField]
  77. RawImage rawImage;
  78. [SerializeField]
  79. RectTransform crosshair;
  80. [Tooltip("存在校准数据时候显示")]
  81. [SerializeField] LineGenerator CurrentUILineGenerator;//开始显示屏幕线条
  82. [Header("Start Layout Group")]
  83. [SerializeField]
  84. GameObject LayoutStart;
  85. [SerializeField]
  86. GameObject StartTextTip1;
  87. [SerializeField]
  88. GameObject StartTextTipHasData;
  89. [Tooltip("没有存在校准数据时候显示")]
  90. [SerializeField]
  91. GameObject BottomAutoBtn;
  92. [Tooltip("存在校准数据时候显示")]
  93. [SerializeField]
  94. GameObject BottomConfirmBtn;
  95. [Header("AutoEnd Layout Group")]
  96. [SerializeField]
  97. GameObject LayoutAutoEnd;
  98. [Header("Marker Layout Group")]
  99. [SerializeField]
  100. GameObject LayoutMarker;
  101. [SerializeField]
  102. RectTransform crosshairSmall;
  103. [Tooltip("标记页面标题提示")]
  104. [SerializeField] TextAutoLanguage2 markerTextAutoLanguage2;
  105. [Header("LightCtrl Layout Group")]
  106. [SerializeField]
  107. GameObject LayoutLightCtrl;
  108. [SerializeField] Slider sliderContrast;
  109. //亮度
  110. [SerializeField] Slider sliderBrightness;
  111. [Header("Successful Layout Group")]
  112. [SerializeField]
  113. GameObject LayoutSuccessful;
  114. [Tooltip("选择框的Line")]
  115. [SerializeField]
  116. Sprite[] ResultLines;// 0: 选中状态, 1: 未选中状态
  117. [Tooltip("选择框图片")]
  118. [SerializeField]
  119. Image[] ResultImages;
  120. [Tooltip("选择框按钮")]
  121. [SerializeField]
  122. Button[] ResultImagesButtons;
  123. [SerializeField]
  124. Button[] ResultButtons; // 结果选择按钮
  125. [SerializeField]
  126. RawImage CameraFirstImage; //第一个结果屏幕
  127. [SerializeField]
  128. RawImage CameraSecondImage; //第二个结果屏幕
  129. [SerializeField] LineGenerator FirstUILineGenerator;//第一个结果屏幕线条
  130. [SerializeField] LineGenerator SecondUILineGenerator;//第二个结果屏幕线条
  131. //标记当前页面情况
  132. ScreenPositioningStep curStepView = ScreenPositioningStep.Start;//设置一个开始页面
  133. InfraredDemo infraredDemo;
  134. bool doLocateAuto;
  135. int DefaultResolutionIndex;
  136. private void Awake()
  137. {
  138. //设置一次显示相机的image 的颜色
  139. rawImage.color = Color.white;
  140. offset = line.MyThickness;
  141. }
  142. void Start()
  143. {
  144. //获取InfraredDemo
  145. infraredDemo = InfraredDemo._ins;
  146. doLocateAuto = false;
  147. textTip1.SetActive(true);
  148. //设置btnAuto 高亮
  149. //OnButtonClick(btnAuto);
  150. textTip2.SetActive(false);
  151. //动态设置marker的提示语
  152. //if (BluetoothAim.ins!=null && markerTextAutoLanguage2 != null)
  153. //{
  154. // string name = "";
  155. // bool switchValue = false;
  156. // if (BluetoothAim.ins.isMainConnectToHOUYIPRO())
  157. // {
  158. // name = TextAutoLanguage2.GetTextByKey("TitleTipMarker-HOUYIPro");
  159. // }
  160. // else if (BluetoothAim.ins.isMainConnectToARTEMISPRO())
  161. // {
  162. // name = TextAutoLanguage2.GetTextByKey("TitleTipMarker-ArtemisPro");
  163. // }
  164. // else if (BluetoothAim.ins.isMainConnectToGun())
  165. // {
  166. // //name = TextAutoLanguage2.GetTextByKey("TitleTipMarker-M9");
  167. // switchValue = true;
  168. // }
  169. // if (switchValue)
  170. // {
  171. // markerTextAutoLanguage2.SetTextKey("TitleTipMarker-M9");
  172. // }
  173. // else {
  174. // markerTextAutoLanguage2.textFormatArgs = new object[] { name };
  175. // }
  176. //}
  177. //手动不高亮
  178. //ResetButton(btnHandMovement);
  179. //quadUnityVectorList.Clear();
  180. //quadUnityVectorList.Add(new Vector2(16.39f, 35.91f));
  181. //quadUnityVectorList.Add(new Vector2(233.35f, 51.08f));
  182. //quadUnityVectorList.Add(new Vector2(94.15f, 219.11f));
  183. //quadUnityVectorList.Add(new Vector2(243.12f, 237.40f));
  184. Debug.Log("quadUnityVectorList count:" + ScreenLocate.quadUnityVectorList.Count);
  185. if (ScreenLocate.quadUnityVectorList.Count == 0)
  186. {
  187. Debug.Log("GetLocalPos");
  188. GetLocalPos();
  189. }
  190. else
  191. {
  192. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  193. Debug.Log("texSize:" + texSize + " = " + canvasRectTransform.rect);
  194. //自动识别时候四个点
  195. SyncQuadUnityVectorListToPos();
  196. //pos1.anchoredPosition = ScreenLocate.quadUnityVectorList[0].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  197. //pos2.anchoredPosition = ScreenLocate.quadUnityVectorList[1].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  198. //pos4.anchoredPosition = ScreenLocate.quadUnityVectorList[2].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  199. //pos3.anchoredPosition = ScreenLocate.quadUnityVectorList[3].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  200. }
  201. //更新start相关ui
  202. UpdateStartUI();
  203. //记录操作的位置信息
  204. oldLinePosition = new List<LinePosition>();
  205. SetLinePos();
  206. //相机感光度
  207. if (infraredDemo)
  208. {
  209. ////重置偏移量
  210. //infraredDemo.ResetCenterOffset();
  211. //////重置识别点
  212. ////ScreenLocate.Main.ScreenIdentification.ClearQuadCache();
  213. //////清除一下记录的点
  214. ////ScreenLocate.quadUnityVectorList.Clear();
  215. //infraredDemo.ResetPositioningData();
  216. slider.onValueChanged.AddListener((value) =>
  217. {
  218. infraredDemo.onSliderEvent(value);
  219. });
  220. infraredDemo.onSetSliderValue(slider);
  221. //对比度
  222. sliderContrast.onValueChanged.AddListener((value) =>
  223. {
  224. infraredDemo.onSliderCustomEvent(value, -20.0f, 20.0f);
  225. });
  226. infraredDemo.onSetSliderCustomValue(sliderContrast, -20.0f, 20.0f);
  227. //亮度
  228. sliderBrightness.onValueChanged.AddListener((value) =>
  229. {
  230. infraredDemo.onSliderCustomBrightnessEvent(value, -20.0f, 20.0f);
  231. });
  232. infraredDemo.onSetSliderCustomBrightnessValue(sliderBrightness, -20.0f, 20.0f);
  233. offset = line.MyThickness = infraredDemo.lineWidth.Get();
  234. ZIM.Unity.QuadrilateralInCamera screen = ScreenLocate.Main.ScreenIdentification.Screen.QuadInCamera;
  235. CurrentUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screen, ScreenLocate.Main.getUVCCameraInfoSize);
  236. }
  237. else {
  238. //编辑器使用
  239. if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer) {
  240. slider.onValueChanged.AddListener((value) =>
  241. {
  242. double originalMin = 0.0;
  243. double originalMax = 10.0;
  244. double targetMin = -1;
  245. double targetMax = 1;
  246. // 计算转换后的值
  247. double result = InfraredDemo.MapValue(value, originalMin, originalMax, targetMin, targetMax);
  248. //int _current = (int)(result);
  249. Debug.Log("_current:" + value + " , result:" + result);
  250. ScreenLocate.Main.pcContrast = (float)result;
  251. });
  252. float v = ScreenLocate.Main.pcContrast;
  253. // 目标区间 [0, 10] 的边界值
  254. double targetMin = 0.0;
  255. double targetMax = 10.0;
  256. double originalMin = -1;
  257. double originalMax = 1;
  258. // 计算转换后的值
  259. double v2 = InfraredDemo.MapValue(v, originalMin, originalMax, targetMin, targetMax);
  260. Debug.Log("PC获取相机的感光度:" + v + " = " + v2);
  261. slider.SetValueWithoutNotify((float)v2);
  262. // 对 sliderContrast 和 sliderBrightness 调用统一的处理函数
  263. HandleSliderValueChanged(sliderContrast, value => ScreenLocate.Main.pcContrast = value, ScreenLocate.Main.pcContrast);
  264. HandleSliderValueChanged(sliderBrightness, value => ScreenLocate.Main.pcBrightness = value, ScreenLocate.Main.pcBrightness);
  265. }
  266. }
  267. initSelectInfo();
  268. //if (ScreenLocate.Main.getUVCTexture)
  269. //{
  270. // //渲染相机画面
  271. // rawImage.texture = ScreenLocate.Main.getUVCTexture;
  272. // //Debug.Log("rawImage.texture:" + rawImage.texture.name);
  273. //}
  274. //slider.onValueChanged.AddListener((value) => {
  275. // //onSliderEvent(value);
  276. // infraredDemo.SetBrightness(value);
  277. //});
  278. //slider.value = infraredDemo.brightness.Get();
  279. //修改分辨率。是否清晰一点?
  280. //DefaultResolutionIndex = infraredDemo?.ResolutionIndex ?? 0;
  281. //Debug.Log("[InfraredScreenPositioningView]开始记录进入时候的分辨率:" + DefaultResolutionIndex);
  282. //infraredDemo?.SetResolutionNew(ScreenLocate.Main.HighScreenLocateResolutionIndex);
  283. //if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked)
  284. //{
  285. // SB_EventSystem.ins.AwakenSimulateMouse();
  286. // // Debug.Log("simulate-mouse-close");
  287. //}
  288. }
  289. // 两个滑块值处理
  290. void HandleSliderValueChanged(UnityEngine.UI.Slider slider, System.Action<float> setValue, float pcValue)
  291. {
  292. double targetMin2 = -20.0;
  293. double targetMax2 = 20.0;
  294. double originalMin2 = -1;
  295. double originalMax2 = 1;
  296. slider.onValueChanged.AddListener((value) =>
  297. {
  298. double result = InfraredDemo.MapValue(value, targetMin2, targetMax2, originalMin2, originalMax2);
  299. Debug.Log($"{slider.name}_current: {value}, result: {result}");
  300. setValue((float)result);
  301. });
  302. double mappedValue = InfraredDemo.MapValue(pcValue, originalMin2, originalMax2, targetMin2, targetMax2);
  303. Debug.Log($"{slider.name} PC获取相机的感光度: {pcValue} = {mappedValue}");
  304. slider.SetValueWithoutNotify((float)mappedValue);
  305. }
  306. private void OnDestroy()
  307. {
  308. //修改回进入手动调节页面时候的分辨率
  309. //infraredDemo?.SetResolutionNew(DefaultResolutionIndex);
  310. Debug.Log("OnDestroy*********************************AwakenSimulateMouse:" + SB_EventSystem.ins.simulateMouseIsAwaked);
  311. if (SB_EventSystem.ins && !SB_EventSystem.ins.simulateMouseIsAwaked)
  312. {
  313. SB_EventSystem.ins.AwakenSimulateMouse();
  314. }
  315. }
  316. public RawImage Bg => rawImage;
  317. void Update()
  318. {
  319. if (enterFromZimWebCamera && ScreenLocate.Main.DebugOnZIMDemo) {
  320. // ZimWebCamera场景测试
  321. rawImage.texture = ScreenLocate.Main.outputRawImages[7].texture;
  322. if (ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.HasValue)
  323. {
  324. // 检测到光点
  325. var posInCanvas = ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(ScreenLocate.Main.CameraSize, rawImage.rectTransform.rect);
  326. crosshair.gameObject.SetActive(true);
  327. crosshair.anchoredPosition = posInCanvas;
  328. }
  329. else
  330. crosshair.gameObject.SetActive(false);
  331. //渲染相机画面
  332. CameraSecondImage.texture = rawImage.texture;
  333. CameraFirstImage.texture = rawImage.texture;
  334. }
  335. else if (InfraredDemo.running)
  336. {
  337. //渲染相机画面
  338. Texture texture = InfraredDemo.infraredCameraHelper.GetCameraTexture();
  339. if (rawImage.texture == null || texture.GetNativeTexturePtr() != rawImage.texture.GetNativeTexturePtr())
  340. {
  341. rawImage.texture = texture;
  342. //渲染相机画面
  343. CameraSecondImage.texture = rawImage.texture;
  344. CameraFirstImage.texture = rawImage.texture;
  345. }
  346. if (ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.HasValue)
  347. {
  348. // 检测到光点
  349. var posInCanvas = ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(ScreenLocate.Main.CameraSize, rawImage.rectTransform.rect);
  350. crosshairSmall.gameObject.SetActive(true);
  351. crosshairSmall.anchoredPosition = posInCanvas;
  352. }
  353. else
  354. crosshairSmall.gameObject.SetActive(false);
  355. //rawImage.material = InfraredDemo.infraredCameraHelper.GetCameraMaterial();
  356. }
  357. }
  358. /// <summary>
  359. /// 根据enum操作ui
  360. /// </summary>
  361. /// <param name="step"></param>
  362. public void SetScreenPositioningStepState(ScreenPositioningStep step = ScreenPositioningStep.None)
  363. {
  364. curStepView = step;
  365. AllScreenPositioningStepFalse();
  366. switch (step)
  367. {
  368. case ScreenPositioningStep.Start:
  369. mask.SetActive(true);
  370. maskLine.SetDrawMask(true);
  371. LayoutStart.SetActive(true);
  372. UpdateStartUI();
  373. break;
  374. case ScreenPositioningStep.AutoEnd:
  375. mask.SetActive(true);
  376. maskLine.SetDrawMask(true);
  377. LayoutAutoEnd.SetActive(true);
  378. break;
  379. case ScreenPositioningStep.Marker:
  380. mask.SetActive(true);
  381. maskLine.SetDrawMask(true);
  382. LayoutMarker.SetActive(true);
  383. break;
  384. case ScreenPositioningStep.LightCtrl:
  385. mask.SetActive(true);
  386. maskLine.SetDrawMask(false);
  387. LayoutLightCtrl.SetActive(true);
  388. break;
  389. case ScreenPositioningStep.Successful:
  390. mask.SetActive(false);
  391. LayoutSuccessful.SetActive(true);
  392. break;
  393. }
  394. }
  395. void AllScreenPositioningStepFalse()
  396. {
  397. LayoutStart.SetActive(false);
  398. LayoutMarker.SetActive(false);
  399. LayoutAutoEnd.SetActive(false);
  400. LayoutLightCtrl.SetActive(false);
  401. LayoutSuccessful.SetActive(false);
  402. }
  403. /// <summary>
  404. /// 开始页面时候ui
  405. /// </summary>
  406. void UpdateStartUI() {
  407. if (ScreenLocate.quadUnityVectorList.Count == 0)
  408. {
  409. //存在数据,显示确认按钮,确认按钮直接跳转到游戏
  410. BottomConfirmBtn.SetActive(false);
  411. StartTextTip1.SetActive(false);
  412. StartTextTipHasData.SetActive(true);
  413. }
  414. else
  415. {
  416. BottomConfirmBtn.SetActive(true);
  417. StartTextTip1.SetActive(true);
  418. StartTextTipHasData.SetActive(false);
  419. }
  420. }
  421. public void OnClick_Back()
  422. {
  423. AudioMgr.ins.PlayBtn();
  424. ViewMgr.Instance.DestroyView<InfraredScreenPositioningView>();
  425. }
  426. /// <summary>
  427. /// 返回最开始页面
  428. /// </summary>
  429. public void OnClick_BackLayoutStart()
  430. {
  431. //返回上一步操作
  432. infraredDemo.RevokeCenterOffset();
  433. SetScreenPositioningStepState(ScreenPositioningStep.Start);
  434. }
  435. /// <summary>
  436. /// 进入环境光测试
  437. /// </summary>
  438. public void OnClick_EnterLightCtrl() {
  439. SetScreenPositioningStepState(ScreenPositioningStep.LightCtrl);
  440. }
  441. /// <summary>
  442. /// 进入屏幕标记
  443. /// </summary>
  444. public void OnClick_EnterMarker() {
  445. SetScreenPositioningStepState(ScreenPositioningStep.Marker);
  446. }
  447. /// <summary>
  448. /// 直接进入游戏流程
  449. /// </summary>
  450. public void OnClick_EnterGame()
  451. {
  452. //对比确认效果。直接进入游戏引导页面
  453. EnterGame();
  454. }
  455. /// <summary>
  456. /// 进入自动流程校准操作
  457. /// </summary>
  458. public void OnClick_EnterAuto()
  459. {
  460. //自动按钮时候进入之前的校准流程
  461. //重置偏移量
  462. infraredDemo.ResetCenterOffset();
  463. infraredDemo.ResetPositioningData();
  464. OnClick_Auto();
  465. }
  466. /// <summary>
  467. /// 自动识别
  468. /// </summary>
  469. public void OnClick_Auto()
  470. {
  471. bAuto = true;
  472. doLocateAuto = true;
  473. //textTip1.SetActive(false);
  474. //textTip2.SetActive(true);
  475. //ResetButton(btnAuto);
  476. if (enterFromZimWebCamera)
  477. {
  478. ScreenLocate _screenLocate = FindAnyObjectByType<ScreenLocate>();
  479. _screenLocate.EnterScreenLocateManualAuto();
  480. return;
  481. }
  482. if (InfraredDemo.running)
  483. {
  484. InfraredDemo.infraredCameraHelper.EnterScreenLocateManualAuto();
  485. }
  486. }
  487. /// <summary>
  488. /// 切换成手动方式
  489. /// </summary>
  490. public void onHandMovement()
  491. {
  492. bAuto = false;
  493. doLocateAuto = false;
  494. draggableParent.gameObject.SetActive(true);
  495. pointsParent.gameObject.SetActive(false);
  496. mask.SetActive(false);
  497. cameraLight.SetActive(true);
  498. }
  499. /// <summary>
  500. /// 自动识别后同步
  501. /// </summary>
  502. public void SyncScreenPosition()
  503. {
  504. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  505. Debug.Log("texSize:" + texSize + " = " + canvasRectTransform.rect);
  506. SyncQuadUnityVectorListToPos();
  507. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  508. if (curStepView == ScreenPositioningStep.Start || curStepView == ScreenPositioningStep.AutoEnd) {
  509. //如果是开始页面进行自动定位的
  510. if(curStepView != ScreenPositioningStep.AutoEnd) SetScreenPositioningStepState(ScreenPositioningStep.AutoEnd);
  511. QuadrilateralInCamera screenAuto = ScreenLocate.Main.ScreenIdentification.QuadAuto;
  512. if (screenAuto != null)
  513. {
  514. Debug.Log("[校准流程] AutoEnd 自动识别screenAuto信息 ------------ ");
  515. CurrentUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screenAuto, texSize);
  516. }
  517. else
  518. {
  519. Debug.LogError("screenAuto 不存在!");
  520. }
  521. }
  522. else if (curStepView == ScreenPositioningStep.Marker) {
  523. //显示最后结果
  524. SetScreenPositioningStepState(ScreenPositioningStep.Successful);
  525. //设置两个线段
  526. QuadrilateralInCamera screenAuto = ScreenLocate.Main.ScreenIdentification.QuadAuto;
  527. QuadrilateralInCamera screenSemiAuto = ScreenLocate.Main.ScreenIdentification.QuadSemiAuto;
  528. if (screenAuto != null)
  529. {
  530. Debug.Log("[校准流程]Successful自动识别screenAuto信息 ------------ ");
  531. FirstUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screenAuto, texSize);
  532. }
  533. else
  534. {
  535. Debug.LogError("screenAuto 不存在!");
  536. }
  537. if (screenSemiAuto != null)
  538. {
  539. Debug.Log("[校准流程]Successful半自动识别screenSemiAuto信息 ------------ ");
  540. SecondUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screenSemiAuto, texSize);
  541. }
  542. else
  543. {
  544. Debug.LogError("screenSemiAuto 不存在!");
  545. }
  546. }
  547. }
  548. #region 绘制线段部分
  549. //点击拖拽的开始位置
  550. public void onBeginPos(int index, Vector3 pos)
  551. {
  552. Debug.Log("pos begin: " + pos);
  553. beginPos = pos;
  554. }
  555. public void onDragPos(int index, Vector3 pos)
  556. {
  557. //设置线段的点
  558. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  559. }
  560. //点击拖拽的结束位置
  561. public void onEndPos(int index, Vector3 pos)
  562. {
  563. Debug.Log("pos end: " + pos);
  564. endPos = pos;
  565. if (beginPos == endPos) return;
  566. //Debug.Log(index+",最后的点:" + pos);
  567. //再记录一次最后的点
  568. SetLinePos();
  569. }
  570. //同步设置图片对应的位置到line
  571. public void SetLinePos()
  572. {
  573. //记录一个操作点的操作位置
  574. AddOldLinePosition();
  575. //设置线段的点
  576. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  577. }
  578. void AddOldLinePosition()
  579. {
  580. Vector3[] v = new Vector3[4];
  581. pos1.GetWorldCorners(v);
  582. Vector3[] v1 = new Vector3[4];
  583. pos1.GetLocalCorners(v1);
  584. //for (int i = 0; i < 4; i++)
  585. //{
  586. // Debug.Log(i + " =1= " + v[i]);
  587. // Debug.Log(i + " =2= " + v1[i]);
  588. //}
  589. //记录一个操作点的操作位置
  590. List<Vector3> screenPositions = new List<Vector3>();
  591. screenPositions.Add(pos1.localPosition);
  592. screenPositions.Add(pos2.localPosition);
  593. screenPositions.Add(pos3.localPosition);
  594. screenPositions.Add(pos4.localPosition);
  595. LinePosition linePosition = new LinePosition();
  596. linePosition.index = oldLinePosition.Count;
  597. linePosition.pos = screenPositions;
  598. oldLinePosition.Add(linePosition);
  599. }
  600. //转换绘制线段的点
  601. List<Vector2> linePosConversion(Vector3 _pos1, Vector3 _pos2, Vector3 _pos3, Vector3 _pos4)
  602. {
  603. List<Vector2> _screenPositions = new List<Vector2>();
  604. //点为负数的增大 offset,正数减少 offset
  605. //Vector2 startPos1 = new Vector2(_pos1.x - pos1.rect.width * 0.5f + offset, _pos1.y - pos1.rect.height * 0.5f + offset);
  606. //Vector2 startPos2 = new Vector2(_pos2.x + pos2.rect.width * 0.5f - offset, _pos2.y - pos2.rect.height * 0.5f + offset);
  607. //Vector2 startPos3 = new Vector2(_pos3.x + pos3.rect.width * 0.5f - offset, _pos3.y + pos3.rect.height * 0.5f - offset);
  608. //Vector2 startPos4 = new Vector2(_pos4.x - pos4.rect.width * 0.5f + offset, _pos4.y + pos4.rect.height * 0.5f - offset);
  609. Vector2 startPos1 = new Vector2(_pos1.x + offset, _pos1.y + offset);
  610. Vector2 startPos2 = new Vector2(_pos2.x - offset, _pos2.y + offset);
  611. Vector2 startPos3 = new Vector2(_pos3.x - offset, _pos3.y - offset);
  612. Vector2 startPos4 = new Vector2(_pos4.x + offset, _pos4.y - offset);
  613. _screenPositions.Add(startPos1);
  614. _screenPositions.Add(startPos2);
  615. _screenPositions.Add(startPos3);
  616. _screenPositions.Add(startPos4);
  617. return _screenPositions;
  618. }
  619. void SetRectanglePoints(List<Vector2> screenPositions)
  620. {
  621. line.SetLine(screenPositions);
  622. }
  623. //撤回上一个元素
  624. public void onRecall()
  625. {
  626. // 获取并删除最后一个元素,并且保留一个元素
  627. if (oldLinePosition.Count > 1) // 确保列表不为空
  628. {
  629. // 获取回退的那个元素点
  630. LinePosition lastElement_second = oldLinePosition[oldLinePosition.Count - 2];
  631. // 获取最后一个元素
  632. //LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  633. //Debug.Log(JsonUtility.ToJson(lastElement) + " = " + oldLinePosition.Count);
  634. oldLinePosition.RemoveAt(oldLinePosition.Count - 1); // 删除最后一个元素
  635. pos1.localPosition = lastElement_second.pos[0];
  636. pos2.localPosition = lastElement_second.pos[1];
  637. pos3.localPosition = lastElement_second.pos[2];
  638. pos4.localPosition = lastElement_second.pos[3];
  639. //设置线段的点
  640. SetRectanglePoints(linePosConversion(lastElement_second.pos[0], lastElement_second.pos[1], lastElement_second.pos[2], lastElement_second.pos[3]));
  641. }
  642. }
  643. //是不是从Demo界面进入该页面的
  644. public bool enterFromInfraredDemo { get; set; } = false;
  645. //是否从测试场景进入
  646. public bool enterFromZimWebCamera { get; set; } = false;
  647. //确认修改
  648. public void onConfirmation()
  649. {
  650. if (enterFromZimWebCamera)
  651. {
  652. ConfirmScreenLocateManualTest();
  653. if (oldLinePosition.Count > 1) // 确保列表不为空
  654. {
  655. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  656. oldLinePosition.Clear();
  657. oldLinePosition.Add(lastElement);
  658. }
  659. SaveLocalPos();
  660. AudioMgr.ins.PlayBtn();
  661. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  662. return;
  663. }
  664. if (!ConfirmScreenLocateManual()) return;
  665. if (oldLinePosition.Count > 1) // 确保列表不为空
  666. {
  667. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  668. oldLinePosition.Clear();
  669. oldLinePosition.Add(lastElement);
  670. }
  671. if (InfraredDemo.running)
  672. {
  673. //跳转入界面
  674. AudioMgr.ins.PlayBtn();
  675. if (!enterFromInfraredDemo)
  676. {
  677. //每次初始化重置一下引导
  678. infraredDemo.resetInfraredPlayerPrefs();
  679. //GameObject connectGuidanceView = ViewManager2.getGameObjectAndShowView(ViewManager2.Path_ConnectGuidanceView);
  680. //connectGuidanceView.GetComponent<ConnectGuidanceView>().showTextipInfrared();
  681. if (!PlayerPrefs.HasKey("hideInfraredBowAndArrow"))
  682. {
  683. //如果是红外连接成功,记录一个tag
  684. PlayerPrefs.SetInt("hideInfraredBowAndArrow", 1);
  685. }
  686. onEnterInfrared();
  687. }
  688. else {
  689. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  690. }
  691. }
  692. //存储一次节点
  693. SaveLocalPos();
  694. }
  695. //重置位置
  696. public void onReset()
  697. {
  698. oldLinePosition.Clear();
  699. // 获取屏幕的四个角的像素坐标
  700. Vector2 bottomLeft = new Vector2(0, 0);
  701. // 将屏幕像素坐标转换为 Canvas 的局部坐标
  702. Vector2 localBottomLeft;
  703. RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTransform, bottomLeft, null, out localBottomLeft);
  704. // 打印结果
  705. Debug.Log("Local Bottom Left: " + localBottomLeft);
  706. //int _x = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.x) - 120), _y = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.y) - 77);
  707. int _x = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.x)), _y = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.y));
  708. pos1.anchoredPosition = new Vector3(-_x, -_y, 0); //Bottom Left
  709. pos2.anchoredPosition = new Vector3(_x, -_y, 0); //Bottom Right
  710. pos3.anchoredPosition = new Vector3(_x, _y, 0); //Top Right
  711. pos4.anchoredPosition = new Vector3(-_x, _y, 0); //Top Left
  712. //pos1.anchoredPosition = new Vector3(_x, _y, 0);
  713. //pos2.anchoredPosition = new Vector3(-_x, _y, 0);
  714. //pos3.anchoredPosition = new Vector3(-_x, -_y, 0);
  715. //pos4.anchoredPosition = new Vector3(_x, -_y, 0);
  716. //设置一次位置
  717. SetLinePos();
  718. btnRecordInfrared.Reset();
  719. ScreenLocate.Main.ScreenIdentification.ClearQuadCache();
  720. if (enterFromZimWebCamera)
  721. {
  722. ScreenLocate.Main.ScreenQuad.gameObject.SetActive(false);
  723. ScreenLocate.Main.UILineGenerator.Points = new Vector2[0];
  724. }
  725. }
  726. /// <summary>
  727. /// 标准四个点
  728. /// </summary>
  729. /// <param name="index"></param>
  730. /// <param name="pos"></param>
  731. public void onManualNewPos(int index, Vector3 pos)
  732. {
  733. Debug.Log("pos end: " + pos);
  734. if (index == 0)
  735. pos1.localPosition = pos;
  736. else if (index == 1)
  737. pos2.localPosition = pos;
  738. else if (index == 2)
  739. pos3.localPosition = pos;
  740. else if (index == 3)
  741. pos4.localPosition = pos;
  742. //再记录一次最后的点
  743. SetLinePos();
  744. }
  745. /// <summary>
  746. /// 处理新流程,先记录手动,然后到自动识别处理
  747. /// </summary>
  748. public void onManualToAutomatic() {
  749. if (enterFromZimWebCamera)
  750. {
  751. ConfirmScreenLocateManualTest();
  752. if (oldLinePosition.Count > 1) // 确保列表不为空
  753. {
  754. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  755. oldLinePosition.Clear();
  756. oldLinePosition.Add(lastElement);
  757. }
  758. SaveLocalPos();
  759. //到自动
  760. OnClick_Auto();
  761. return;
  762. }
  763. if (!ConfirmScreenLocateManual()) {
  764. Debug.LogError("ConfirmScreenLocateManual is false!");
  765. return;
  766. }
  767. if (oldLinePosition.Count > 1) // 确保列表不为空
  768. {
  769. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  770. oldLinePosition.Clear();
  771. oldLinePosition.Add(lastElement);
  772. }
  773. //存储一次节点
  774. SaveLocalPos();
  775. Debug.Log("[校准流程]进入自动校准数据,调用EnterScreenLocateManualAuto");
  776. bAuto = true;
  777. doLocateAuto = true;
  778. //自动校准
  779. InfraredDemo.infraredCameraHelper.EnterScreenLocateManualAuto();
  780. }
  781. #endregion
  782. List<Vector2> _locatePointList = new();
  783. float _texWidth;
  784. float _texHeight;
  785. void RecordLocatePoint(RectTransform p, Vector2 pivot)
  786. {
  787. Vector2 pos = JCUnityLib.RectTransformUtils.GetPositionByPivot(p, pivot);
  788. pos.x = Mathf.Clamp01(pos.x / Screen.width);
  789. pos.y = Mathf.Clamp01(pos.y / Screen.height);
  790. _locatePointList.Add(pos);
  791. }
  792. bool ConfirmScreenLocateManual()
  793. {
  794. if (InfraredDemo.running)
  795. {
  796. //渲染截图
  797. Texture2D texture2D = InfraredDemo.infraredCameraHelper.EnterScreenLocateManual();
  798. if (texture2D == null)
  799. {
  800. Debug.Log("EnterScreenLocateManual = null");
  801. InfraredDemo.infraredCameraHelper.QuitScreenLocateManual(null);
  802. return false;
  803. }
  804. _locatePointList.Clear();
  805. _texWidth = texture2D.width;
  806. _texHeight = texture2D.height;
  807. RecordLocatePoint(pos1, new Vector2(0, 0));
  808. RecordLocatePoint(pos2, new Vector2(1, 0));
  809. RecordLocatePoint(pos3, new Vector2(1, 1));
  810. RecordLocatePoint(pos4, new Vector2(0, 1));
  811. //RecordLocatePoint(pos1, new Vector2(0.5f, 0.5f));
  812. //RecordLocatePoint(pos2, new Vector2(0.5f, 0.5f));
  813. //RecordLocatePoint(pos3, new Vector2(0.5f, 0.5f));
  814. //RecordLocatePoint(pos4, new Vector2(0.5f, 0.5f));
  815. InfraredDemo.infraredCameraHelper.QuitScreenLocateManual(_locatePointList);
  816. FindObjectOfType<InfraredDemo>().SetLocatePointsToCameraRender(_locatePointList, 1, 1);
  817. //同步数据
  818. ScreenLocate.quadUnityVectorList.Clear();
  819. ScreenLocate.quadUnityVectorList.Add(_locatePointList[0]);
  820. ScreenLocate.quadUnityVectorList.Add(_locatePointList[1]);
  821. //两个点切换,顺序不一样
  822. ScreenLocate.quadUnityVectorList.Add(_locatePointList[3]);
  823. ScreenLocate.quadUnityVectorList.Add(_locatePointList[2]);
  824. ScreenLocate.SaveScreenLocateVectorList();
  825. Debug.Log("[校准流程]设置QuitScreenLocateManual()手动数据,保存quadUnityVectorList");
  826. return true;
  827. }
  828. return false;
  829. }
  830. void ConfirmScreenLocateManualTest()
  831. {
  832. //渲染截图
  833. ScreenLocate _screenLocate = FindAnyObjectByType<ScreenLocate>();
  834. Texture2D texture2D = _screenLocate.EnterScreenLocateManual();
  835. if (texture2D == null)
  836. {
  837. _screenLocate.QuitScreenLocateManual(null);
  838. return;
  839. }
  840. _locatePointList.Clear();
  841. _texWidth = texture2D.width;
  842. _texHeight = texture2D.height;
  843. RecordLocatePoint(pos1, new Vector2(0, 0));
  844. RecordLocatePoint(pos2, new Vector2(1, 0));
  845. RecordLocatePoint(pos3, new Vector2(1, 1));
  846. RecordLocatePoint(pos4, new Vector2(0, 1));
  847. _screenLocate.QuitScreenLocateManual(_locatePointList);
  848. //FindObjectOfType<InfraredDemo>().SetLocatePointsToCameraRender(_locatePointList, _texWidth, _texHeight);
  849. setPointsLocation(_locatePointList,pointsParent.gameObject,!bAuto);
  850. if (!doLocateAuto) // 设置手动定位数据
  851. setPointsManual(_locatePointList, GameObject.Find("WebCameraView/CameraImage0/ScreenQuad"));
  852. //同步数据
  853. ScreenLocate.quadUnityVectorList.Clear();
  854. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[0].x, _locatePointList[0].y));
  855. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[1].x, _locatePointList[1].y));
  856. //两个点切换,顺序不一样
  857. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[3].x, _locatePointList[3].y));
  858. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[2].x, _locatePointList[2].y));
  859. ScreenLocate.SaveScreenLocateVectorList();
  860. }
  861. void setPointsLocation(List<Vector2> targetList, GameObject pointsTF2, bool active = true)
  862. {
  863. //GameObject pointsTF2 = GameObject.Find("WebCameraView/CameraImage0/ScreenQuad");
  864. pointsTF2.SetActive(active);
  865. if (pointsTF2.transform.childCount == targetList.Count)
  866. {
  867. for (int i = 0; i < pointsTF2.transform.childCount; i++)
  868. {
  869. Transform pointTF = pointsTF2.transform.GetChild(i);
  870. Vector2 pos = targetList[i];
  871. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(Vector2.one, pointsTF2.GetComponent<RectTransform>().rect);
  872. pointTF.gameObject.SetActive(true);
  873. }
  874. }
  875. }
  876. void setPointsManual(List<Vector2> targetList, GameObject pointsTF2, bool active = true)
  877. {
  878. setPointsLocation(targetList, pointsTF2, active);
  879. var lo = new Vector2(-0.5f, -0.5f);
  880. ScreenLocate.Main.UILineGenerator.Points = new Vector2[4] {
  881. 2 * (targetList[0] + lo),
  882. 2 * (targetList[1] + lo),
  883. 2 * (targetList[2] + lo),
  884. 2 * (targetList[3] + lo) };
  885. }
  886. void SaveLocalPos()
  887. {
  888. List<Vector3> screenPositions = new List<Vector3>();
  889. screenPositions.Add(pos1.anchoredPosition);
  890. screenPositions.Add(pos2.anchoredPosition);
  891. screenPositions.Add(pos3.anchoredPosition);
  892. screenPositions.Add(pos4.anchoredPosition);
  893. string saveStr = string.Join(';', screenPositions.Select(v => $"{v.x},{v.y}")); //,{v.z}
  894. Debug.Log("Local UI Position: " + saveStr);
  895. PlayerPrefs.SetString("ScreenPositioningView", saveStr);
  896. }
  897. void GetLocalPos()
  898. {
  899. string posListStr = PlayerPrefs.GetString("ScreenPositioningView", "");
  900. if (!string.IsNullOrWhiteSpace(posListStr))
  901. {
  902. List<Vector2> posList = posListStr.Split(';')
  903. .Select(s =>
  904. {
  905. string[] parts = s.Split(',');
  906. return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
  907. })
  908. .ToList();
  909. pos1.anchoredPosition = posList[0];
  910. pos2.anchoredPosition = posList[1];
  911. pos3.anchoredPosition = posList[2];
  912. pos4.anchoredPosition = posList[3];
  913. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  914. }
  915. }
  916. #region 按钮颜色切换
  917. private void OnButtonClick(Button button)
  918. {
  919. // 切换按钮颜色
  920. ColorBlock colors = button.colors;
  921. colors.normalColor = highlightedColor;
  922. colors.highlightedColor = highlightedColor;
  923. button.colors = colors;
  924. // 切换字体颜色
  925. Text buttonText = button.GetComponentInChildren<Text>();
  926. buttonText.color = highlightedTextColor;
  927. }
  928. private void ResetButton(Button button)
  929. {
  930. // 重置按钮颜色
  931. ColorBlock colors = button.colors;
  932. colors.normalColor = normalColor;
  933. colors.highlightedColor = normalColor;
  934. button.colors = colors;
  935. // 重置字体颜色
  936. Text buttonText = button.GetComponentInChildren<Text>();
  937. buttonText.color = normalTextColor;
  938. }
  939. #endregion
  940. #region 标定完成之后进入游戏界面
  941. void onEnterInfrared()
  942. {
  943. //添加进入射箭场景
  944. if (PlayerPrefs.GetInt("entry-guider-infrared-" + LoginMgr.myUserInfo.id, 0) == 0)
  945. {
  946. Debug.Log("-----进入射箭场景!");
  947. NewUserGuiderManager newUserGuiderManager = FindObjectOfType<NewUserGuiderManager>();
  948. newUserGuiderManager.curConfigKey = "开始-红外调整";
  949. //b端都是红外设备流程
  950. if (CommonConfig.StandaloneModeOrPlatformB)
  951. {
  952. newUserGuiderManager.isNewModule = true;
  953. }
  954. else {
  955. newUserGuiderManager.isNewModule = AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.HOUYIPRO || AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.Gun || AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.ARTEMISPRO;
  956. }
  957. //进入射箭场景
  958. GlobalData.pkMatchType = PKMatchType.None;
  959. GameMgr.gameType = 1;
  960. //射一箭回到连接页面,Device.view
  961. GameMgr.bNavBack = true;
  962. GameMgr.bShowDistance = false;
  963. if (!CommonConfig.StandaloneModeOrPlatformB)
  964. {
  965. AimHandler.ins.bInitOne = false;//true
  966. }
  967. //关闭计时器
  968. GameMgr.turnOffTimer = true;
  969. //关闭左边靶子和底部速度栏
  970. GameMgr.HideTargetView = true;
  971. GameMgr.HideBillboard = true;
  972. GameMgr.ButtonCount = 0;
  973. UnityEngine.SceneManagement.SceneManager.LoadScene(
  974. "Game", UnityEngine.SceneManagement.LoadSceneMode.Single);
  975. PlayerPrefs.SetInt("entry-guider-infrared-" + LoginMgr.myUserInfo.id, 1);
  976. }
  977. else
  978. {
  979. Debug.Log("-----跳转回连接界面!");
  980. //如不是第一次,则应该跳转回连接界面
  981. ViewMgr.Instance.DestroyView<SmartArcheryView>();
  982. ViewManager2.HideView(ViewManager2.Path_ConnectGuidanceView);
  983. }
  984. }
  985. #endregion
  986. #region 最后选择算法处理UI
  987. int selected = -1;
  988. void initSelectInfo() {
  989. for (int i = 0; i < 2; i++)
  990. {
  991. int currentIndex = i; // 将 i 赋值给局部变量
  992. ResultImagesButtons[currentIndex].onClick.AddListener(() => SelectImage(currentIndex));
  993. //ResultButtons[currentIndex].onClick.AddListener(() =>
  994. //{
  995. // if (currentIndex == 0)
  996. // {
  997. // OnFirstResult();
  998. // }
  999. // else if (currentIndex == 1)
  1000. // {
  1001. // OnSecondResult();
  1002. // }
  1003. //});
  1004. }
  1005. //默认选择1 自动
  1006. SelectImage(0);
  1007. }
  1008. // 添加一个选择函数
  1009. void SelectImage(int selectedIndex)
  1010. {
  1011. //如果重复选中则跳转
  1012. if (selected == selectedIndex) {
  1013. if (selected == 0)
  1014. {
  1015. OnFirstResult();
  1016. }
  1017. else if (selected == 1)
  1018. {
  1019. OnSecondResult();
  1020. }
  1021. return;
  1022. }
  1023. // 遍历所有图片
  1024. for (int i = 0; i < ResultImages.Length; i++)
  1025. {
  1026. // 如果是选中的 index,赋值为 ResultLines[0],否则赋值为 ResultLines[1]
  1027. if (i == selectedIndex)
  1028. {
  1029. selected = i;
  1030. ResultImages[i].sprite = ResultLines[0];
  1031. ResultButtons[i].interactable = true;
  1032. }
  1033. else
  1034. {
  1035. ResultImages[i].sprite = ResultLines[1];
  1036. ResultButtons[i].interactable = false;
  1037. }
  1038. }
  1039. }
  1040. //选择全自动结果后进入游戏
  1041. void OnFirstResult()
  1042. {
  1043. ScreenLocate.Main.SelectScreenAfterLocate(ScreenLocate.ScreenIdentificationTag.Auto);
  1044. UpdateQuadUnityVectorList();
  1045. onCompelete();
  1046. }
  1047. //选择半自动结果
  1048. void OnSecondResult()
  1049. {
  1050. ScreenLocate.Main.SelectScreenAfterLocate(ScreenLocate.ScreenIdentificationTag.SemiAuto);
  1051. UpdateQuadUnityVectorList();
  1052. onCompelete();
  1053. }
  1054. public void onCompelete()
  1055. {
  1056. if (enterFromZimWebCamera)
  1057. {
  1058. SaveLocalPos();
  1059. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  1060. return;
  1061. }
  1062. EnterGame();
  1063. //存储一次节点
  1064. SaveLocalPos();
  1065. }
  1066. void EnterGame() {
  1067. if (InfraredDemo.running)
  1068. {
  1069. //跳转入界面
  1070. AudioMgr.ins.PlayBtn();
  1071. if (!enterFromInfraredDemo)
  1072. {
  1073. //每次初始化重置一下引导
  1074. infraredDemo.resetInfraredPlayerPrefs();
  1075. //GameObject connectGuidanceView = ViewManager2.getGameObjectAndShowView(ViewManager2.Path_ConnectGuidanceView);
  1076. //connectGuidanceView.GetComponent<ConnectGuidanceView>().showTextipInfrared();
  1077. if (!PlayerPrefs.HasKey("hideInfraredBowAndArrow"))
  1078. {
  1079. //如果是红外连接成功,记录一个tag
  1080. PlayerPrefs.SetInt("hideInfraredBowAndArrow", 1);
  1081. }
  1082. onEnterInfrared();
  1083. }
  1084. else
  1085. {
  1086. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  1087. }
  1088. }
  1089. }
  1090. /// <summary>
  1091. /// 选择模式后更新 quadUnityVectorList
  1092. /// </summary>
  1093. void UpdateQuadUnityVectorList() {
  1094. ScreenLocate.Main.UpdateQuadUnityVectorList();
  1095. SyncQuadUnityVectorListToPos();
  1096. infraredDemo?.SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1097. _locatePointList.Clear();
  1098. }
  1099. void SyncQuadUnityVectorListToPos() {
  1100. Debug.Log("[ScreenLocate] SyncQuadUnityVectorListToPos quadUnityVectorList:" + ScreenLocate.Main.PrintVector2List(ScreenLocate.quadUnityVectorList));
  1101. pos1.anchoredPosition = ScreenLocate.quadUnityVectorList[0].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1102. pos2.anchoredPosition = ScreenLocate.quadUnityVectorList[1].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1103. pos4.anchoredPosition = ScreenLocate.quadUnityVectorList[2].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1104. pos3.anchoredPosition = ScreenLocate.quadUnityVectorList[3].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1105. }
  1106. //这个脚本存在时候。任何切换操作都直接处理删除
  1107. //void OnSceneUnloaded(Scene scene)
  1108. //{
  1109. // ViewManager2.HideView(ViewManager2.Path_ConnectGuidanceView);
  1110. // ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  1111. //}
  1112. //void OnEnable()
  1113. //{
  1114. // SceneManager.sceneUnloaded += OnSceneUnloaded;
  1115. //}
  1116. //void OnDisable()
  1117. //{
  1118. // SceneManager.sceneUnloaded -= OnSceneUnloaded;
  1119. //}
  1120. #endregion
  1121. #region 判断点是否在 quad 内部
  1122. //判断maskline
  1123. public bool IsPointInMaskLine(Vector2 point) {
  1124. return IsPointInQuad(point, maskLine.ScreenPositions);
  1125. }
  1126. //实现基于射线法,通过数交点的奇偶性来判断点是否在多边形内
  1127. bool IsPointInQuad(Vector2 point, List<Vector2> quadVertices)
  1128. {
  1129. if (quadVertices.Count != 4)
  1130. {
  1131. Debug.LogError("Quad must have exactly 4 vertices.");
  1132. return false;
  1133. }
  1134. bool isInside = false;
  1135. int vertexCount = quadVertices.Count;
  1136. for (int i = 0, j = vertexCount - 1; i < vertexCount; j = i++)
  1137. {
  1138. Vector2 vi = quadVertices[i];
  1139. Vector2 vj = quadVertices[j];
  1140. // 检查射线是否与边相交
  1141. if (((vi.y > point.y) != (vj.y > point.y)) &&
  1142. (point.x < (vj.x - vi.x) * (point.y - vi.y) / (vj.y - vi.y) + vi.x))
  1143. {
  1144. isInside = !isInside;
  1145. }
  1146. }
  1147. return isInside;
  1148. }
  1149. /// <summary>
  1150. /// 判断四个点是否能够形成有效的四边形,并根据面积阈值过滤小四边形
  1151. /// </summary>
  1152. /// <param name="points">四个点</param>
  1153. /// <param name="minArea">面积阈值,用于过滤面积太小的四边形</param>
  1154. /// <returns>是否是有效的四边形</returns>
  1155. public bool IsValidQuadrilateral(Vector2[] points, float minArea = 100000.0f)
  1156. {
  1157. if (points.Length != 4)
  1158. {
  1159. Debug.Log("四个点数不足,无法形成四边形。");
  1160. return false; // 如果点数不是4,直接返回false
  1161. }
  1162. // 计算四边形的面积
  1163. float area = CalculateArea(points);
  1164. Debug.Log($"四边形面积: {area}");
  1165. if (area < minArea)
  1166. {
  1167. Debug.Log($"面积小于阈值: {minArea},返回 false。");
  1168. return false; // 面积太小,返回 false
  1169. }
  1170. // 检查是否有三点共线
  1171. for (int i = 0; i < points.Length; i++)
  1172. {
  1173. Vector2 a = points[i];
  1174. Vector2 b = points[(i + 1) % points.Length];
  1175. Vector2 c = points[(i + 2) % points.Length];
  1176. if (ArePointsCollinear(a, b, c))
  1177. {
  1178. Debug.Log($"点 {a}, {b}, {c} 共线,返回 false。");
  1179. return false; // 存在共线点,返回 false
  1180. }
  1181. }
  1182. // 检查是否为矩形或接近矩形
  1183. if (!IsRectangle(points))
  1184. {
  1185. // 如果不是矩形,检查是否是梯形
  1186. if (!IsTrapezoid(points))
  1187. {
  1188. Debug.Log("既不是矩形,也不是梯形,返回 false。");
  1189. return false; // 不是矩形也不是梯形,返回 false
  1190. }
  1191. else
  1192. {
  1193. Debug.Log("是梯形。");
  1194. }
  1195. }
  1196. else
  1197. {
  1198. Debug.Log("是矩形。");
  1199. }
  1200. // 检查对角线是否相交
  1201. if (DoLinesIntersect(points[0], points[1], points[2], points[3]) ||
  1202. DoLinesIntersect(points[1], points[2], points[3], points[0]))
  1203. {
  1204. Debug.Log("对角线相交,返回 false。");
  1205. return false; // 对角线相交,返回 false
  1206. }
  1207. // 检查点的排列顺序,确保是顺时针或逆时针
  1208. if (!ArePointsClockwise(points) && !ArePointsClockwise(points.Reverse().ToArray()))
  1209. {
  1210. Debug.Log("点的排列顺序不正确,返回 false。");
  1211. return false; // 点的排列顺序不正确
  1212. }
  1213. Debug.Log("四边形有效,返回 true。");
  1214. return true; // 通过所有检查,返回 true
  1215. }
  1216. /// <summary>
  1217. /// 判断是否是矩形(近似90度角)
  1218. /// </summary>
  1219. private bool IsRectangle(Vector2[] points)
  1220. {
  1221. // 角度容差范围,允许夹角有小的偏差
  1222. const float dotProductThreshold = 0.1f;
  1223. for (int i = 0; i < points.Length; i++)
  1224. {
  1225. Vector2 a = points[i];
  1226. Vector2 b = points[(i + 1) % points.Length];
  1227. Vector2 c = points[(i + 2) % points.Length];
  1228. // 计算向量 AB 和 BC 的内积
  1229. Vector2 ab = b - a;
  1230. Vector2 bc = c - b;
  1231. float dotProduct = Vector2.Dot(ab.normalized, bc.normalized);
  1232. // 如果内积接近 0,表示夹角接近 90 度
  1233. if (Mathf.Abs(dotProduct) > dotProductThreshold)
  1234. {
  1235. Debug.Log($"点 {a}, {b}, {c} 的夹角不接近 90 度,返回 false。");
  1236. return false; // 角度不接近 90 度
  1237. }
  1238. }
  1239. return true;
  1240. }
  1241. /// <summary>
  1242. /// 判断是否是梯形
  1243. /// </summary>
  1244. private bool IsTrapezoid(Vector2[] points)
  1245. {
  1246. // 斜率容差范围,允许斜率差异较小
  1247. const float slopeThreshold = 0.2f;
  1248. // 计算对角线的斜率
  1249. float slope1 = (points[1].y - points[0].y) / (points[1].x - points[0].x);
  1250. float slope2 = (points[3].y - points[2].y) / (points[3].x - points[2].x);
  1251. // 如果对角线斜率差异小于容差范围,则认为是梯形
  1252. if (Mathf.Abs(slope1 - slope2) < slopeThreshold)
  1253. {
  1254. Debug.Log("对角线平行,判断为梯形。");
  1255. return true; // 对角线平行,返回 true
  1256. }
  1257. else
  1258. {
  1259. Debug.Log($"对角线斜率差异过大: {slope1} vs {slope2},不是梯形,返回 false。");
  1260. return false; // 斜率差异过大,不是梯形
  1261. }
  1262. }
  1263. //计算四边形面积
  1264. float CalculateArea(Vector2[] points)
  1265. {
  1266. float area = 0f;
  1267. int n = points.Length;
  1268. for (int i = 0; i < n; i++)
  1269. {
  1270. Vector2 current = points[i];
  1271. Vector2 next = points[(i + 1) % n];
  1272. area += current.x * next.y - current.y * next.x;
  1273. }
  1274. return Mathf.Abs(area) / 2f;
  1275. }
  1276. //确保点不共线
  1277. //判断点是否在同一条直线上(即共线),如果共线则无法形成四边形。可以通过计算任意三点的面积是否为 0 来验证是否共线:
  1278. bool ArePointsCollinear(Vector2 a, Vector2 b, Vector2 c)
  1279. {
  1280. float area = Mathf.Abs(a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)) / 2.0f;
  1281. return Mathf.Approximately(area, 0f);
  1282. }
  1283. //确保边不相交
  1284. bool DoLinesIntersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d)
  1285. {
  1286. float cross(Vector2 p1, Vector2 p2, Vector2 p3)
  1287. {
  1288. return (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x);
  1289. }
  1290. float d1 = cross(a, b, c);
  1291. float d2 = cross(a, b, d);
  1292. float d3 = cross(c, d, a);
  1293. float d4 = cross(c, d, b);
  1294. return d1 * d2 < 0 && d3 * d4 < 0;
  1295. }
  1296. //顺时针或逆时针排列顶点
  1297. bool ArePointsClockwise(Vector2[] points)
  1298. {
  1299. float sum = 0;
  1300. for (int i = 0; i < points.Length; i++)
  1301. {
  1302. Vector2 current = points[i];
  1303. Vector2 next = points[(i + 1) % points.Length];
  1304. sum += (next.x - current.x) * (next.y + current.y);
  1305. }
  1306. return sum < 0; // 小于0为顺时针,大于0为逆时针
  1307. }
  1308. #endregion
  1309. }