InfraredScreenPositioningView.cs 67 KB

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