AimHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using System;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine.UI;
  6. using Newtonsoft.Json;
  7. public class AimHandler : MonoBehaviour
  8. {
  9. Transform controlObj {
  10. get {
  11. CameraToLook ctl = CameraToLook.ins;
  12. if (ctl && ctl.isNew)
  13. {
  14. ctl.isNew = false;
  15. InitAutoIdentity();
  16. }
  17. if (ctl) return ctl.transform;
  18. else 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 AMesh;
  31. [SerializeField] Transform DebugTexts;
  32. [SerializeField] Transform DrawImage;
  33. long TimeGap = default;
  34. Vector3 Acc = default;
  35. Vector3 Gyr = default;
  36. Vector3 Mag = default;
  37. o09Axis _9Axis = new o09Axis();
  38. Vector3 cMaxVector = new Vector3(0,0,0);
  39. Vector3 cMinVector = new Vector3(0, 0, 0);
  40. o0MagneticCalibraterEllipsoidFitting MagCalibrater;
  41. o0GyrCalibrater GyrCalibrater;
  42. //陀螺仪校准进度记录
  43. public int gyrCalibrateCompleteCount = 0;
  44. public int gyrCalibrateTotalCount = 300;
  45. long msOld = 0;
  46. public static AimHandler ins;
  47. void Start()
  48. {
  49. ins = this;
  50. BluetoothDispatcher.aim = OnDataReceived;
  51. //初始化
  52. for (var i = 0; i < 9; ++i)
  53. {
  54. _9Axis.Tester.Add(DrawImage.Find(i.ToString()).gameObject.AddComponent<o0UIRawImageTester>());
  55. }
  56. for (var i = 0; i < 15; ++i)
  57. {
  58. _9Axis.TextTester.Add(DebugTexts.transform.Find("Text" + i.ToString()).gameObject.GetComponent<Text>());
  59. }
  60. if (SetIdentityButton)
  61. {
  62. SetIdentityButton.onClick.AddListener(DoIdentity);
  63. }
  64. try
  65. {
  66. string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  67. MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  68. }
  69. catch(Exception)
  70. {
  71. MagCalibrater = null;
  72. }
  73. if (MagCalibrater == null)
  74. {
  75. MagCalibrater = new o0MagneticCalibraterEllipsoidFitting();
  76. }
  77. if (MagCalibrationButton)
  78. {
  79. MagCalibrationButton.onClick.AddListener(delegate {
  80. CalibrateMag(!MagCalibrater.Calibration);
  81. });
  82. }
  83. try {
  84. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  85. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  86. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  87. } catch(Exception) {
  88. GyrCalibrater = null;
  89. }
  90. if (GyrCalibrater == null)
  91. {
  92. GyrCalibrater = new o0GyrCalibrater();
  93. }
  94. if (GyrCalibrationButton)
  95. {
  96. GyrCalibrationButton.onClick.AddListener(delegate() {
  97. CalibrateGyr(!GyrCalibrater.Calibration);
  98. });
  99. }
  100. }
  101. public void CalibrateGyr(bool calibration) {
  102. try {
  103. GyrCalibrater.Calibration = calibration;
  104. if (calibration)
  105. {
  106. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  107. }
  108. else
  109. {
  110. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  111. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  112. }
  113. } catch (Exception e) { Debug.LogError(e.Message); }
  114. }
  115. public void CalibrateMag(bool calibration) {
  116. try {
  117. if (calibration)
  118. {
  119. MagCalibrater.Calibration = calibration;
  120. MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  121. this.cMaxVector = new Vector3(0, 0, 0);
  122. this.cMinVector = new Vector3(0, 0, 0);
  123. }
  124. else
  125. {
  126. List<Vector3> list = MagCalibrater.getRecords();
  127. //停止校准时候,看看数组值
  128. float maxDistance = 0f,ratio = 1f;
  129. Vector3 maxVector3 = new Vector3(0,0,0);
  130. List<Vector3> endRecords = new List<Vector3>();
  131. foreach (Vector3 i in list)
  132. {
  133. Vector3 v = i - MagCalibrater._Center;
  134. if (Math.Abs(v.magnitude) > maxDistance)
  135. {
  136. maxVector3 = v;
  137. maxDistance = Math.Abs(v.magnitude);
  138. if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  139. ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  140. else
  141. ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  142. }
  143. }
  144. Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  145. //如果比例效果不理想。可以设置为ratio=0.5f
  146. foreach (Vector3 i in list)
  147. {
  148. //- MagCalibrater._Center
  149. Vector3 v = i ;
  150. v *= ratio;
  151. if(endRecords.Count>3000)
  152. {
  153. endRecords.RemoveAt(0);
  154. }
  155. endRecords.Add(v);
  156. }
  157. this.ellipseScript.ClearAndUpdatePointArray();
  158. this.ellipseScript.DrawPointCloud(endRecords);
  159. //绘制椭圆形
  160. if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  161. {
  162. this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center* ratio);
  163. //设置绘制图像相机的对应位置
  164. this.ellipseScript.setCameraPos(MagCalibrater._Center * 0.5f);
  165. }
  166. MagCalibrater.Calibration = calibration;
  167. MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  168. PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  169. }
  170. } catch (Exception e) { Debug.LogError(e.Message); }
  171. }
  172. //转换读取的数据,无符号->有符号
  173. float TwoByteToFloat(byte b1, byte b2)
  174. {
  175. ushort twoByte = (ushort) (b1 * 256 + b2);
  176. short shortNum = (short) twoByte;
  177. return (float) shortNum;
  178. }
  179. public void OnDataReceived(byte[] bytes)
  180. {
  181. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  182. if (bytes.Length != 26)
  183. {
  184. if (bytes[3] == 125)
  185. {
  186. DoIdentity();
  187. }
  188. return;
  189. }
  190. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  191. return;
  192. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  193. return;
  194. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  195. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  196. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  197. ax = ax / 32768 * 16;
  198. ay = ay / 32768 * 16;
  199. az = az / 32768 * 16;
  200. Acc = new Vector3(ax, ay, az);
  201. AccObj.transform.GetChild(0).localPosition = Acc;
  202. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  203. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  204. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  205. roll = -roll / 32768 * 2000;
  206. pitch = pitch / 32768 * 2000;
  207. yaw = -yaw / 32768 * 2000;
  208. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  209. Gyr = GyrCalibrater.Update(Gyr);
  210. if (GyrCalibrater.Calibration)
  211. {
  212. if (gyrCalibrateCompleteCount < gyrCalibrateTotalCount) {
  213. gyrCalibrateCompleteCount++;
  214. }
  215. }
  216. if (GyrScaleText && GyrCalibrater.Calibration)
  217. {
  218. // GyrScaleText.text = GyrCalibrater._Average.x + "\n" + GyrCalibrater._Average.y + "\n" + GyrCalibrater._Average.z;
  219. // GyrScaleText.text = "Gyr*1000,000:" + (_9Axis.GyrOld * 1000000).ToString();
  220. GyrScaleText.text = "" + (_9Axis.GyrOld * 1000000).ToString();
  221. }
  222. float x = TwoByteToFloat(bytes[16], bytes[17]);
  223. float y = TwoByteToFloat(bytes[18], bytes[19]);
  224. float z = -TwoByteToFloat(bytes[20], bytes[21]);
  225. var mag = new Vector3(x, y, z);
  226. Mag = mag / 32768 * 256;
  227. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  228. {
  229. //绘制地磁计点
  230. if (MagCalibrater.Calibration)
  231. {
  232. this.ellipseScript.AddAndUpdatePointArray(Mag);
  233. if (Mag.magnitude > this.cMaxVector.magnitude)
  234. {
  235. this.cMaxVector = Mag;
  236. }
  237. else if (Mag.magnitude < this.cMinVector.magnitude) {
  238. this.cMinVector = Mag;
  239. }
  240. Vector3 _center = this.cMaxVector - this.cMinVector;
  241. Debug.LogWarning(_center + " == "+ _center.magnitude);
  242. //设置绘制图像相机的对应位置
  243. this.ellipseScript.setCameraPos(_center/2);
  244. }
  245. Mag = MagCalibrater.Update(Mag);
  246. if (MagScaleText)
  247. {
  248. MagScaleText.text = MagCalibrater._Radius.ToString();
  249. }
  250. }
  251. MagObj.transform.GetChild(0).localPosition = Mag;
  252. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  253. if(msOld == default)
  254. {
  255. msOld = ms;
  256. return;
  257. }
  258. TimeGap = ms - msOld;
  259. msOld = ms;
  260. AMesh.transform.localRotation = newRotation = _9Axis.Update(Acc * 10, Gyr, Mag, TimeGap);
  261. // 游戏处于暂停状态时,Update插值会失效,因此需要主动赋值新的角度
  262. if (GameMgr.ins && GameMgr.ins.gamePause) {
  263. controlObj.localRotation = newRotation;
  264. }
  265. // 记录一些旋转角---start
  266. if (ArmBow.ins) {
  267. for (int i = ArmBow.ins.recordRotations.Length - 1; i > 0 ; i--)
  268. {
  269. ArmBow.ins.recordRotations[i] = ArmBow.ins.recordRotations[i - 1];
  270. }
  271. ArmBow.ins.recordRotations[0] = newRotation;
  272. ArmBow.ins.recordCount++;
  273. }
  274. // 记录一些旋转角---end
  275. checkAutoIdentity();
  276. }
  277. public void Update()
  278. {
  279. if (controlObj && hasAutoIdentity)
  280. {
  281. // 最终结果进行lerp
  282. controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * 8);
  283. }
  284. }
  285. int receiveDataCount = 0;
  286. bool hasAutoIdentity = false;
  287. Quaternion newRotation;
  288. void InitAutoIdentity()
  289. {
  290. receiveDataCount = 0;
  291. hasAutoIdentity = false;
  292. }
  293. void checkAutoIdentity()
  294. {
  295. receiveDataCount++;
  296. if (!hasAutoIdentity && receiveDataCount == 5) {
  297. hasAutoIdentity = true;
  298. DoIdentity();
  299. }
  300. }
  301. public void DoIdentity()
  302. {
  303. if (!hasAutoIdentity) return;
  304. _9Axis.SetIdentity();
  305. if (controlObj) controlObj.localRotation = _9Axis.States.Last().Qua;
  306. }
  307. }