AimHandler.cs 19 KB

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