AimHandler.cs 12 KB

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