AimHandler.cs 12 KB

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