InfraredScreenPositioningView.cs 65 KB

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