AimHandler.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine.UI;
  6. using Newtonsoft.Json;
  7. using o0._9Axis;
  8. /* 瞄准处理器 */
  9. public class AimHandler : MonoBehaviour
  10. {
  11. Transform controlObj {
  12. get {
  13. if (CameraToLook.ins) {
  14. return CameraToLook.ins.transform;
  15. }
  16. return null;
  17. }
  18. }
  19. [SerializeField] Button SetIdentityButton;
  20. [SerializeField] Button MagCalibrationButton;
  21. [SerializeField] Button GyrCalibrationButton;
  22. [SerializeField] Text MagScaleText;
  23. [SerializeField] Text GyrScaleText;
  24. //椭圆对象
  25. [SerializeField] Ellipse ellipseScript;
  26. [SerializeField] GameObject AccObj;
  27. [SerializeField] GameObject MagObj;
  28. [SerializeField] GameObject AccMesh;
  29. [SerializeField] GameObject GryMesh;
  30. [SerializeField] GameObject MagMesh;
  31. [SerializeField] GameObject AMesh;
  32. [SerializeField] Transform DebugTexts;
  33. [SerializeField] Transform DrawImage;
  34. long TimeGap = default;
  35. Vector3 Acc = default;
  36. Vector3 Gyr = default;
  37. Vector3 Mag = default;
  38. public o09Axis _9Axis = new o09Axis();
  39. Vector3 cMaxVector = new Vector3(0,0,0);
  40. Vector3 cMinVector = new Vector3(0, 0, 0);
  41. [o0.Serialize]
  42. public MagnetometerAutoCalibrater MagCalibrater;
  43. o0GyrCalibrater GyrCalibrater;
  44. //陀螺仪校准进度记录
  45. [NonSerialized] public int gyrCalibrateCompleteCount = 0;
  46. [NonSerialized] public int gyrCalibrateTotalCount = 2000;
  47. [NonSerialized] public long msOld = 0;
  48. public static AimHandler ins;
  49. void Start()
  50. {
  51. ins = this;
  52. BluetoothDispatcher.aim = OnDataReceived;
  53. //初始化
  54. _9Axis.LoadIdentity();
  55. _9Axis.AccMesh = AccMesh;
  56. _9Axis.GryMesh = GryMesh;
  57. _9Axis.MagMesh = MagMesh;
  58. for (var i = 0; i < 9; ++i)
  59. {
  60. _9Axis.Tester.Add(DrawImage.Find(i.ToString()).gameObject.AddComponent<o0UIRawImageTester>());
  61. }
  62. for (var i = 0; i < 15; ++i)
  63. {
  64. _9Axis.TextTester.Add(DebugTexts.transform.Find("Text" + i.ToString()).gameObject.GetComponent<Text>());
  65. }
  66. if (SetIdentityButton)
  67. {
  68. SetIdentityButton.onClick.AddListener(DoIdentity);
  69. }
  70. // try
  71. // {
  72. // string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  73. // MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  74. // }
  75. // catch(Exception)
  76. // {
  77. // MagCalibrater = null;
  78. // }
  79. if (MagCalibrater == null)
  80. {
  81. // MagCalibrater = new o0MagneticCalibraterEllipsoidFitting();
  82. MagCalibrater = new MagnetometerAutoCalibrater();
  83. }
  84. if (MagCalibrationButton)
  85. {
  86. MagCalibrationButton.onClick.AddListener(delegate {
  87. // CalibrateMag(!MagCalibrater.Calibration);
  88. });
  89. }
  90. try {
  91. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  92. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  93. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  94. } catch(Exception) {
  95. GyrCalibrater = null;
  96. }
  97. if (GyrCalibrater == null)
  98. {
  99. GyrCalibrater = new o0GyrCalibrater();
  100. }
  101. if (GyrCalibrationButton)
  102. {
  103. GyrCalibrationButton.onClick.AddListener(delegate() {
  104. CalibrateGyr(!GyrCalibrater.Calibration);
  105. });
  106. }
  107. }
  108. public void CalibrateGyr(bool calibration) {
  109. try {
  110. GyrCalibrater.Calibration = calibration;
  111. if (calibration)
  112. {
  113. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  114. }
  115. else
  116. {
  117. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  118. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  119. }
  120. } catch (Exception e) { Debug.LogError(e.Message); }
  121. }
  122. [NonSerialized] public bool isCalibrateMagPerfect = false;
  123. public void CalibrateMag(bool calibration) {
  124. // try {
  125. // if (calibration)
  126. // {
  127. // PointCorrector.ins = new PointCorrector(this.ellipseScript, this.MagCalibrater);
  128. // MagCalibrater.Calibration = calibration;
  129. // MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  130. // this.cMaxVector = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  131. // this.cMinVector = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  132. // this.ellipseScript.ellipseTran.gameObject.SetActive(false);
  133. // }
  134. // else
  135. // {
  136. // PointCorrector.ins = null;
  137. // List<Vector3> list = MagCalibrater.getRecords();
  138. // //停止校准时候,看看数组值
  139. // float maxDistance = 0f,ratio = 1f;
  140. // Vector3 maxVector3 = new Vector3(0,0,0);
  141. // List<Vector3> endRecords = new List<Vector3>();
  142. // foreach (Vector3 i in list)
  143. // {
  144. // Vector3 v = i - MagCalibrater._Center;
  145. // if (Math.Abs(v.magnitude) > maxDistance)
  146. // {
  147. // maxVector3 = v;
  148. // maxDistance = Math.Abs(v.magnitude);
  149. // if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  150. // ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  151. // else
  152. // ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  153. // }
  154. // }
  155. // Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  156. // //如果比例效果不理想。可以设置为ratio=0.5f
  157. // foreach (Vector3 i in list)
  158. // {
  159. // //- MagCalibrater._Center
  160. // Vector3 v = i ;
  161. // v *= ratio;
  162. // if(endRecords.Count>3000)
  163. // {
  164. // endRecords.RemoveAt(0);
  165. // }
  166. // endRecords.Add(v);
  167. // }
  168. // this.ellipseScript.ClearAndUpdatePointArray();
  169. // // this.ellipseScript.DrawPointCloud(endRecords);
  170. // MagCalibrater.Calibration = calibration;
  171. // this.ellipseScript.ellipseTran.gameObject.SetActive(true);
  172. // //绘制椭圆形
  173. // if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  174. // {
  175. // this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center * ratio);
  176. // //设置绘制图像相机的对应位置
  177. // this.ellipseScript.setCameraPos(MagCalibrater._Center * ratio);
  178. // this.ellipseScript.setCameraSize(MagCalibrater._Radius);
  179. // }
  180. // MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  181. // PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  182. // #region 看校准是否完美,求Records方差
  183. // if (list == null || list.Count == 0) isCalibrateMagPerfect = false;
  184. // else
  185. // {
  186. // double sumV = 0;
  187. // double[] listArray = new double[list.Count];
  188. // for (int i = 0; i < list.Count; i++)
  189. // {
  190. // listArray[i] = MagCalibrater.Update(list[i]).magnitude;
  191. // sumV += listArray[i];
  192. // }
  193. // double avarageV = sumV / listArray.Length;
  194. // double varianceV = 0;
  195. // foreach (double vvv in listArray)
  196. // {
  197. // varianceV += Math.Pow(vvv - avarageV, 2);
  198. // }
  199. // varianceV /= listArray.Length;
  200. // isCalibrateMagPerfect = varianceV < 0.001;
  201. // PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("tip_mag-calibrate-variance-equal") + varianceV);
  202. // }
  203. // #endregion
  204. // }
  205. // } catch (Exception e) { Debug.LogError(e.Message); }
  206. }
  207. //转换读取的数据,无符号->有符号
  208. float TwoByteToFloat(byte b1, byte b2)
  209. {
  210. ushort twoByte = (ushort) (b1 * 256 + b2);
  211. short shortNum = (short) twoByte;
  212. return (float) shortNum;
  213. }
  214. public void OnDataReceived(byte[] bytes)
  215. {
  216. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  217. if (bytes.Length != 27)
  218. {
  219. if (bytes.Length == 2) {
  220. if (bytes[0] == 0x66 && bytes[1] == 0x31) {
  221. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  222. //鼠标居中
  223. SB_EventSystem.ins.MakeMouseToScreenCenter();
  224. //视角回正
  225. DoIdentity();
  226. } else {
  227. AutoResetView.DoIdentity();
  228. }
  229. } else if (bytes[0] == 0x66 && bytes[1] == 0x32) {
  230. if (SB_EventSystem.ins) {
  231. // if (SB_EventSystem.ins && !CommonConfig.SpecialVersion1) {
  232. //唤起/隐藏虚拟鼠标
  233. SB_EventSystem.ins.AwakenSimulateMouse();
  234. }
  235. } else if (bytes[1] == 10) {
  236. //显示电量
  237. DeviceBatteryView.ins.RenderBattery(1, bytes[0]);
  238. }
  239. } else if (bytes[0] == 0x5b) {
  240. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  241. //点击鼠标
  242. SB_EventSystem.ins.ClickMouse();
  243. } else {
  244. //红外射击检测
  245. ShootCheck.ins.ShootByInfrared(bytes);
  246. }
  247. }
  248. return;
  249. }
  250. // if (DeviceBatteryView.ins) {
  251. // DeviceBatteryView.ins.labelTemperature.text = (TwoByteToFloat(bytes[5], bytes[6]) / 100).ToString("#0.00") + "℃";
  252. // }
  253. if (bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0 && bytes[10] == 0 && bytes[11] == 0 && bytes[12] == 0)
  254. return;
  255. if (bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0 && bytes[22] == 0 && bytes[23] == 0 && bytes[24] == 0)
  256. return;
  257. //if (ban9AxisCalculate) //如果箭射出后禁止九轴计算,就缓存最新几帧九轴数据
  258. //{
  259. //
  260. // if (cached9AxisFrames.Count < 2)
  261. // {
  262. // cached9AxisFrames.Enqueue(bytes);
  263. // }
  264. // else
  265. // {
  266. // cached9AxisFrames.Dequeue();
  267. // cached9AxisFrames.Enqueue(bytes);
  268. // }
  269. // return;
  270. //}
  271. float ax = TwoByteToFloat(bytes[7], bytes[8]);
  272. float ay = TwoByteToFloat(bytes[9], bytes[10]);
  273. float az = TwoByteToFloat(bytes[11], bytes[12]);
  274. float roll = TwoByteToFloat(bytes[13], bytes[14]);
  275. float pitch = TwoByteToFloat(bytes[15], bytes[16]);
  276. float yaw = TwoByteToFloat(bytes[17], bytes[18]);
  277. float x = TwoByteToFloat(bytes[19], bytes[20]);
  278. float y = TwoByteToFloat(bytes[21], bytes[22]);
  279. float z = TwoByteToFloat(bytes[23], bytes[24]);
  280. float mxr = TwoByteToFloat(bytes[20], bytes[19]);
  281. float myr = TwoByteToFloat(bytes[22], bytes[21]);
  282. float mzr = TwoByteToFloat(bytes[24], bytes[23]);
  283. if (CommonConfig.devicePlan == 0) {
  284. Acc = new Vector3(-az, ay, -ax) / 32768 * 16;
  285. Gyr = new Vector3(yaw, -pitch, roll) / 32768 * 2;
  286. Mag = new Vector3(-z, y, x) / 32768 * 256; //旧版
  287. mag0o = UnityVectorTo0o(Mag);
  288. if (!MagCalibrater.Update(mag0o)) {
  289. isCalibrateMagPerfect = false;
  290. return;
  291. }
  292. isCalibrateMagPerfect = true;
  293. mag0o = MagCalibrater.EllipsoidFitting.Map(mag0o);
  294. Mag = o0VectorToUnity(mag0o);
  295. } else if (CommonConfig.devicePlan == 1) {
  296. Acc = new Vector3(ax, ay, az) / 32768 * 16;
  297. Gyr = new Vector3(roll, pitch, yaw) / 32768 * 2;
  298. Mag = new Vector3(z, x, -y) / 32768 * 256;//第一个6+3硬件
  299. } else if (CommonConfig.devicePlan == 2) {
  300. Acc = new Vector3(-az, ax, -ay) / 32768 * 16;
  301. Gyr = new Vector3(-yaw, roll, -pitch) / 32768 * 2;
  302. Mag = new Vector3(mzr, mxr, -myr) / 32768 * 256;//第二个6+3硬件
  303. }
  304. AccObj.transform.GetChild(0).localPosition = Acc;
  305. Gyr = GyrCalibrater.Update(Gyr);
  306. if (GyrCalibrater.Calibration)
  307. {
  308. if (gyrCalibrateCompleteCount < gyrCalibrateTotalCount) {
  309. gyrCalibrateCompleteCount++;
  310. }
  311. }
  312. if (GyrScaleText && GyrCalibrater.Calibration)
  313. {
  314. GyrScaleText.text = "" + (_9Axis.getGyrOld() * 1000000).ToString();
  315. }
  316. // if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  317. // {
  318. // //绘制地磁计点
  319. // if (MagCalibrater.Calibration)
  320. // {
  321. // this.ellipseScript.AddAndUpdatePointArray(Mag);
  322. // if (Mag.x > cMaxVector.x) cMaxVector.x = Mag.x;
  323. // if (Mag.y > cMaxVector.y) cMaxVector.y = Mag.y;
  324. // if (Mag.z > cMaxVector.z) cMaxVector.z = Mag.z;
  325. // if (Mag.x < cMinVector.x) cMinVector.x = Mag.x;
  326. // if (Mag.y < cMinVector.y) cMinVector.y = Mag.y;
  327. // if (Mag.z < cMinVector.z) cMinVector.z = Mag.z;
  328. // Vector3 centerPoint = (this.cMaxVector + this.cMinVector) / 2;
  329. // //设置绘制图像相机的对应位置
  330. // this.ellipseScript.setCameraPos(centerPoint);
  331. // this.ellipseScript.setCameraSize(this.cMaxVector - this.cMinVector);
  332. // PointCorrector.ins?.Update(centerPoint);
  333. // }
  334. // Mag = MagCalibrater.Update(Mag);
  335. // if (MagScaleText)
  336. // {
  337. // MagScaleText.text = MagCalibrater._Radius.ToString();
  338. // }
  339. // }
  340. MagObj.transform.GetChild(0).localPosition = Mag;
  341. var ms = (((long)bytes[1]) *60 + bytes[2])*1000 + (long)TwoByteToFloat(bytes[3], bytes[4]);
  342. if(msOld == default)
  343. {
  344. msOld = ms;
  345. return;
  346. }
  347. TimeGap = ms - msOld;
  348. msOld = ms;
  349. GapMs = TimeGap;
  350. gyr0o = UnityVectorTo0o(Gyr);
  351. acc0o = UnityVectorTo0o(Acc);
  352. distanceToAxis.Update(gyr0o, acc0o, mag0o, GapMs);
  353. acc0o = distanceToAxis.AccCorrection(gyr0o, acc0o, GapMs);/**///轴心偏离矫正
  354. Acc = o0VectorToUnity(acc0o);
  355. var GyrOperator = new Quaternion();
  356. GyrOperator.eulerAngles = Gyr * TimeGap;
  357. GryMesh.transform.localRotation *= GyrOperator;
  358. AMesh.transform.localRotation = newRotation = _9Axis.update(Acc, Gyr, Mag, TimeGap);
  359. if (BowQuatDebug.ins) BowQuatDebug.ins.ShowModuleQuat(newRotation.eulerAngles);
  360. if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) {
  361. SB_EventSystem.ins.MoveSimulateMouse(newRotation);
  362. }
  363. }
  364. o0.Bow.DistanceToAxis distanceToAxis = new o0.Bow.DistanceToAxis();
  365. double GapMs;
  366. o0.Geometry.Vector<double> gyr0o;
  367. o0.Geometry.Vector<double> acc0o;
  368. o0.Geometry.Vector<double> mag0o;
  369. o0.Geometry.Vector<double> UnityVectorTo0o(Vector3 src) {
  370. return new o0.Geometry.Vector<double>(double.Parse(src.x.ToString()), double.Parse(src.y.ToString()), double.Parse(src.z.ToString()));
  371. }
  372. Vector3 o0VectorToUnity(o0.Geometry.Vector<double> src) {
  373. return new Vector3(float.Parse(src.x.ToString()), float.Parse(src.y.ToString()), float.Parse(src.z.ToString()));
  374. }
  375. [NonSerialized] public bool lerpForRotation = true;
  376. [NonSerialized] public float lerpTimeRate = 7;
  377. public void Update()
  378. {
  379. if (controlObj && !ban9AxisCalculate)
  380. {
  381. if (lerpForRotation)
  382. {
  383. controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * lerpTimeRate);
  384. }
  385. else
  386. {
  387. controlObj.localRotation = newRotation;
  388. }
  389. }
  390. }
  391. private bool ban9AxisCalculate = false;
  392. private Queue<byte[]> cached9AxisFrames = new Queue<byte[]>();
  393. public void Ban9AxisCalculate(bool ban) {
  394. ban9AxisCalculate = ban;
  395. if (!ban) {
  396. msOld = default;
  397. // try
  398. // {
  399. // if (StatesBackDebug.ins) _9Axis.DeleteStatesFromTail(StatesBackDebug.ins.val);
  400. // }
  401. // catch (Exception) { }
  402. //恢复九轴计算时,把缓存的最新几帧计算了
  403. // bool isFirstFrame = true;
  404. while (cached9AxisFrames.Count > 0)
  405. {
  406. try
  407. {
  408. OnDataReceived(cached9AxisFrames.Dequeue());
  409. //最初的一帧是用来顶掉msOld的,不会进state数组,因此不需要设置方差
  410. // if (!isFirstFrame) {
  411. // _9Axis.SetAccMagVariance(10000);
  412. // }
  413. // isFirstFrame = false;
  414. }
  415. catch (Exception) { }
  416. }
  417. //立马应用到控制物体中
  418. if (controlObj) controlObj.localRotation = newRotation;
  419. }
  420. }
  421. Quaternion newRotation = Quaternion.identity;
  422. public void DoIdentity()
  423. {
  424. _9Axis.SetIdentityAndSave();
  425. Quaternion qua = _9Axis.getLastState().Qua;
  426. newRotation = qua;
  427. if (controlObj) controlObj.localRotation = qua;
  428. }
  429. }