webview.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. import notifyCenter from 'global';
  2. var ActionJump = require('jump-0.3');
  3. import { KalmanModel, KalmanObservation } from "../js/kalman/kalman";
  4. import { mVector, mMatrix } from "../js/kalman/sylvester"
  5. cc.Class({
  6. extends: cc.Component,
  7. properties: {
  8. playerContro: {
  9. default: null,
  10. type: cc.Node,
  11. serializable: true,
  12. },
  13. playerControScript: {
  14. default: null,
  15. visible: false,
  16. serializable: true,
  17. },
  18. mass: {
  19. default: 50,
  20. type: cc.Integer,
  21. tooltip: "物体质量/kg",
  22. serializable: true,
  23. },
  24. xLCount: {
  25. default: 0,
  26. type: cc.Float,
  27. tooltip: "x轴负向",
  28. visible: false,
  29. serializable: false,
  30. },
  31. xRCount: {
  32. default: 0,
  33. type: cc.Float,
  34. tooltip: "x轴正向",
  35. visible: false,
  36. serializable: false,
  37. },
  38. yLCount: {
  39. default: 0,
  40. type: cc.Float,
  41. tooltip: "y轴负向",
  42. visible: false,
  43. serializable: false,
  44. },
  45. yRCount: {
  46. default: 0,
  47. type: cc.Float,
  48. tooltip: "y轴正向",
  49. visible: false,
  50. serializable: false,
  51. },
  52. zLCount: {
  53. default: 0,
  54. type: cc.Float,
  55. tooltip: "z轴负向",
  56. visible: false,
  57. serializable: false,
  58. },
  59. zRCount: {
  60. default: 0,
  61. type: cc.Float,
  62. tooltip: "z轴正向",
  63. visible: false,
  64. serializable: false,
  65. },
  66. //记录一次打击,如果通方向就更新最大值
  67. hitFirst: {
  68. default: null,
  69. visible: false,
  70. serializable: true,
  71. },
  72. //锁住hit update 更新情况
  73. bLock: {
  74. default: false,
  75. visible: false,
  76. serializable: false,
  77. },
  78. //定义一个状态字典
  79. hitState: {
  80. default: null,
  81. serializable: false,
  82. visible: false,
  83. },
  84. staticTime: {
  85. default: 1,
  86. type: cc.Float,
  87. serializable: true,
  88. tooltip: "立柱静止的检测时间"
  89. },
  90. bSwing: {
  91. default: false,
  92. serializable: true,
  93. tooltip: "是否摆动"
  94. },
  95. showCalorieLabel: {
  96. default: null,
  97. type: cc.Label,
  98. serializable: true
  99. },
  100. LCount: {
  101. default: 0,
  102. type: cc.Integer,
  103. tooltip: "左勾拳打击次数",
  104. visible: false,
  105. serializable: false,
  106. },
  107. RCount: {
  108. default: 0,
  109. type: cc.Integer,
  110. tooltip: "右勾拳打击次数",
  111. visible: false,
  112. serializable: false,
  113. },
  114. ZCount: {
  115. default: 0,
  116. type: cc.Integer,
  117. tooltip: "直拳打击次数",
  118. visible: false,
  119. serializable: false,
  120. },
  121. AllCalorie: {
  122. default: 0,
  123. type: cc.Integer,
  124. tooltip: "总共的卡路里",
  125. visible: false,
  126. serializable: false,
  127. },
  128. AllPower: {
  129. default: 0,
  130. type: cc.Integer,
  131. tooltip: "三次下来的总力量",
  132. visible: false,
  133. serializable: false,
  134. },
  135. bRAnimation: false,
  136. bLAnimation: false,
  137. bMAnimation: false,
  138. currentLimitValue: {
  139. default: 8,
  140. type: cc.Integer,
  141. tooltip: "限制值",
  142. visible: false,
  143. serializable: false,
  144. },
  145. currentLimitDireValue: {
  146. default: 1,
  147. type: cc.Float,
  148. tooltip: "角度限制值",
  149. visible: false,
  150. serializable: false,
  151. },
  152. drawNodeX: {
  153. default: null,
  154. type: cc.Node,
  155. tooltip: "绘制节点",
  156. },
  157. drawNodeZ: {
  158. default: null,
  159. type: cc.Node,
  160. tooltip: "绘制Z节点",
  161. },
  162. drawNodeY: {
  163. default: null,
  164. type: cc.Node,
  165. tooltip: "绘制Y节点",
  166. },
  167. drawNodeLinearX: {
  168. default: null,
  169. type: cc.Node,
  170. tooltip: "绘制节点",
  171. },
  172. drawNodeLinearZ: {
  173. default: null,
  174. type: cc.Node,
  175. tooltip: "绘制Z节点",
  176. },
  177. drawNodeLinearY: {
  178. default: null,
  179. type: cc.Node,
  180. tooltip: "绘制Y节点",
  181. },
  182. drawNodeSqrt: {
  183. default: null,
  184. type: cc.Node,
  185. tooltip: "绘制开平方的节点",
  186. },
  187. drawNodeLinearSqrt: {
  188. default: null,
  189. type: cc.Node,
  190. tooltip: "绘制开平方的节点",
  191. },
  192. drawNodeOriSqrt: {
  193. default: null,
  194. type: cc.Node,
  195. tooltip: "绘制开平方的节点",
  196. },
  197. drawTip: {
  198. default: null,
  199. type: cc.Node,
  200. tooltip: "提示点",
  201. },
  202. //X轴的变化数组值
  203. xAccArray: [],
  204. xMax: 0,
  205. maxTimeoutId: null,
  206. bMaxPause: false,
  207. xMin: 0,
  208. minTimeoutId: null,
  209. bMinPause: false,
  210. bCalculation: false,
  211. calTimeout: null,
  212. //波动判断打击部分
  213. //记录打击的x 轴数据
  214. xArray: [],
  215. //z轴的变化数组值
  216. zArray: [],
  217. //更新的下标
  218. updateIndex: 0,
  219. //是否正在计算对应的值
  220. bCalX: false,
  221. bCalZ: false,
  222. xDifference: 0,
  223. zDifference: 0,
  224. xMaxDifference: 0,
  225. zMaxDifference: 0,
  226. xMaxAddCount: 0,
  227. xAddDifferenceCount: 0,
  228. zMaxAddCount: 0,
  229. zAddDifferenceCount: 0,
  230. hitCountL: 0,
  231. hitCountZ: 0,
  232. //是否判断
  233. bJudging: false,
  234. //z和x系数转换
  235. ratio: 0.5,
  236. //合力计算
  237. oldResultantDifference: 0,
  238. resultantDifference: 0,
  239. bCalResultant: false,
  240. //最大的差值
  241. resultantMaxDifference: 0,
  242. //最大的加速度
  243. resultantMaxX: 0,
  244. resultantMaxZ: 0,
  245. resultantMaxAddCount: 0,
  246. resultAddDifferenceCount: 0,
  247. //传感器部分
  248. sensorHit: false,
  249. phoneAccIndex: 0,
  250. BLEAccIndex: 0,
  251. oldPhoneIndex: 0,
  252. oldBLEAccIndex: 0,
  253. alpha: 0,
  254. beta: 0,
  255. gamma: 0,
  256. oldOriAlpha: 0,
  257. oldOriBeta: 0,
  258. oldOriGamma: 0,
  259. oldOriCount: 0,
  260. jump: false,//是否是跳
  261. jumpCount: 0,
  262. runCount: 0,
  263. bGyroDraw: true,
  264. bAccDraw: true,
  265. gyroDrawLabel: {
  266. default: null,
  267. type: cc.Label,
  268. serializable: true,
  269. },
  270. accDrawLabel: {
  271. default: null,
  272. type: cc.Label,
  273. serializable: true,
  274. },
  275. bGyroLog: false,
  276. bAccLog: false,
  277. gyroLogLabel: {
  278. default: null,
  279. type: cc.Label,
  280. serializable: true,
  281. },
  282. accLogLabel: {
  283. default: null,
  284. type: cc.Label,
  285. serializable: true,
  286. },
  287. rotate: { default: null, type: cc.Node },
  288. //记录当前数据
  289. currentGameDataArray: [],
  290. currentInterval: null,
  291. currentDataArray: [],
  292. //是否先手原始数据
  293. bShowOri: true,
  294. bShowIndex: 0,
  295. //游戏节点
  296. gameNode: {
  297. default: null,
  298. type: cc.Node,
  299. tooltip: "游戏节点",
  300. },
  301. axisLabel: {
  302. default: null,
  303. type: cc.Label,
  304. serializable: true,
  305. },
  306. isY: true,
  307. LastMS: 0,
  308. LastTime: 0,
  309. /**
  310. * 融合算法部分使用的参数
  311. */
  312. //记录时间
  313. timestamp: 0,
  314. //ms转s
  315. MS2S: 0.001,
  316. //开始初始化bool
  317. initState: true,
  318. // angular speeds from gyro
  319. gyro: new Array(3),
  320. // rotation matrix from gyro data
  321. gyroMatrix: new Array(9),
  322. // orientation angles from gyro matrix
  323. gyroOrientation: new Array(3),
  324. // magnetic field vector
  325. magnet: new Array(3),
  326. // accelerometer vector
  327. accel: new Array(3),
  328. // orientation angles from accel and magnet
  329. accMagOrientation: new Array(3),
  330. // final orientation angles from sensor fusion
  331. fusedOrientation: new Array(3),
  332. // accelerometer and magnetometer based rotation matrix
  333. rotationMatrix: new Array(9),
  334. /**
  335. * 波形
  336. */
  337. drawX: {
  338. default: null,
  339. type: cc.Node,
  340. tooltip: "绘制X节点",
  341. },
  342. },
  343. onChangeAxis(event) {
  344. // console.log(event);
  345. this.isY = event.isChecked
  346. this.axisLabel.string = this.isY ? 'y' : 'x';
  347. },
  348. // LIFE-CYCLE CALLBACKS:
  349. onLoad() {
  350. //关闭渲染
  351. // this.bAccDraw = false;
  352. window.webView = this;
  353. this.playerControScript = this.playerContro.getComponent("PlayerController");
  354. //游戏节点
  355. if (this.gameNode != null) {
  356. this.gameScript = this.gameNode.getComponent("game");
  357. }
  358. this.hitState = {
  359. "xLCount": 0,
  360. "xRCount": 0,
  361. "zLCount": 0,
  362. "zRCount": 0
  363. }
  364. this.oldxA = 0;
  365. this.oldzA = 0;
  366. this.bUpdateOnce = false;
  367. this.bDelayOnce = false;
  368. this.lineX = this.drawNodeX.getComponent("line");
  369. this.lineZ = this.drawNodeZ.getComponent("line");
  370. this.lineY = this.drawNodeY.getComponent("line");
  371. this.lineLinearX = this.drawNodeLinearX.getComponent("line");
  372. this.lineLinearZ = this.drawNodeLinearZ.getComponent("line");
  373. this.lineLinearY = this.drawNodeLinearY.getComponent("line");
  374. this.drawXScript = this.drawX.getComponent("heartBeat");
  375. this.lineSqrt = this.drawNodeSqrt.getComponent("line");
  376. this.lineSqrtLinear = this.drawNodeLinearSqrt.getComponent("line");
  377. this.lineOriSqrt = this.drawNodeOriSqrt.getComponent("line");
  378. this.lineDrawTip = this.drawTip.getComponent("line");
  379. //判断左右勾拳 z
  380. this.oldAlpha = 0;
  381. this.oldGamma = 0;
  382. this.oldBeta = 0;
  383. this.xA = 0;
  384. this.yA = 0;
  385. this.zA = 0;
  386. this.bJump = false;
  387. this.linear_acceleration_z = 0;
  388. // this.isY = true;
  389. /**
  390. * 算法初始参数
  391. */
  392. this.gyroOrientation[0] = 0.0;
  393. this.gyroOrientation[1] = 0.0;
  394. this.gyroOrientation[2] = 0.0;
  395. // initialise gyroMatrix with identity matrix
  396. this.gyroMatrix[0] = 1.0; this.gyroMatrix[1] = 0.0; this.gyroMatrix[2] = 0.0;
  397. this.gyroMatrix[3] = 0.0; this.gyroMatrix[4] = 1.0; this.gyroMatrix[5] = 0.0;
  398. this.gyroMatrix[6] = 0.0; this.gyroMatrix[7] = 0.0; this.gyroMatrix[8] = 1.0;
  399. this.schedule(() => {
  400. this.calculateFusedOrientationTask();
  401. }, 0.03, 0, 1)
  402. },
  403. start() {
  404. // 卡曼尔滤波
  405. this.x_0 = mVector([0]);
  406. this.P_0 = mMatrix([[1]]);
  407. this.F_k = mMatrix([[1]]);
  408. this.Q_k = mMatrix([[0.1]]);
  409. this.KM = new KalmanModel(this.x_0, this.P_0, this.F_k, this.Q_k);
  410. // console.log(this.KM);
  411. this.z_k = mVector([1]);
  412. this.H_k = mMatrix([[1]]);
  413. this.R_k = mMatrix([[4]]);
  414. this.KO = new KalmanObservation(this.z_k, this.H_k, this.R_k);
  415. // for (var i = 0; i < 100; i++) {
  416. // let _temp = 0.5 + Math.random();
  417. // _temp *= 9.8;
  418. // if (i == 30)
  419. // _temp = 60;
  420. // if(i == 31)
  421. // _temp = -70;
  422. // if (i > 50) {
  423. // _temp = -100;
  424. // }
  425. // this.z_k = mVector([_temp]);
  426. // this.KO.z_k = this.z_k;
  427. // this.KM.update(this.KO);
  428. // console.log(this.KM.x_k.elements[0], i, _temp);
  429. // this.lineZ.onUpdateIndex();
  430. // this.lineZ.onUpdateDraw(this.KM.x_k.elements[0]);
  431. // }
  432. this.rotate.angle = 90;
  433. this.actionJump = new ActionJump();
  434. this.actionJump.addEventListener('resultant', (e) => {
  435. // console.log(e.type);
  436. if (e.type == 'jump') {
  437. this.jumpCount++;
  438. this.playerControScript.onJumpCount(this.jumpCount);
  439. // this.lineSqrt.onUpdateDrawFromColor(e.value, cc.Color.RED, 5);
  440. this.bJump = true;
  441. } else if (e.type == 'peakOfWave') {
  442. if (this.bAccDraw) {
  443. this.lineSqrt.onUpdateDrawLastValueFromColor(e.oldValue, cc.Color.WHITE, 5, e.lastIndex);
  444. }
  445. } else if (e.type == 'valleyOfWave') {
  446. if (this.bAccDraw) {
  447. this.lineSqrt.onUpdateDrawLastValueFromColor(e.oldValue, cc.Color.BLUE, 5, e.lastIndex);
  448. }
  449. } else if (e.type == 'curAngle') {
  450. // this.playerControScript.onHandleState(e.value);
  451. if (e.value > 0) {
  452. this.rotate.angle = 180;
  453. this.playerControScript.leftJump();
  454. } else {
  455. this.rotate.angle = 0;
  456. this.playerControScript.rightJump();
  457. }
  458. } else if (e.type == 'rotate') {
  459. // if (allOGyroValue > 0) {
  460. // console.log('right:', allOGyroValue);
  461. // } else {
  462. // console.log('left:', allOGyroValue);
  463. // }
  464. } else if (e.type == 'stateDataOfJump') {
  465. console.log('stateDataOfJump:', JSON.stringify(e));
  466. // this.event.trigger('resultant', {
  467. // type: "stateDataOfJump",
  468. // currentMaxValue: _frameMaxValue,
  469. // currentMinValue: _frameMinValue,
  470. // peakOfWaveMaxValue: this.peakOfWaveMaxValue,
  471. // valleyOfWaveMinValue: this.valleyOfWaveMinValue,
  472. // oGyroValue: _frameGyroValue,
  473. // resultant: resultant,
  474. // tempIndex: i, //触发了多少次
  475. // name: "highestCountEnd"
  476. // });
  477. console.log(Math.abs(e.currentMaxValue) > Math.abs(e.currentMinValue) ? "左方向" : "右方向");
  478. console.log(Math.abs(e.oGyroValue) > Math.abs(e.oGyroMinValue) ? "右旋转" : "左旋转");
  479. if (e.oGyroValue > 1000) {
  480. this.rotate.angle = 0;
  481. } else if (e.oGyroMinValue < -1000) {
  482. this.rotate.angle = 180;
  483. }
  484. //发送给game,在game里面处理判断
  485. // if (this.gameScript)
  486. // this.gameScript.listenStateDataOfJump(e, this.isY);
  487. } else if (e.type == 'bUpdateDraw') {
  488. if (this.bAccDraw) {
  489. let { lAccX, lAccY, lAccZ } = e.data.linearAcc;
  490. let { oAccX, oAccY, oAccZ } = e.data.oriAcc;
  491. // if (lAccX > 0)
  492. // this.lineX.onUpdateDraw(lAccX);
  493. // else
  494. // this.lineX.onUpdateDrawFromColor(lAccX, cc.Color.WHITE, 2);
  495. // this.lineLinearX.onUpdateDrawFromColor(oAccX, "#00F0FF", 2);
  496. // this.z_k = mVector([e.linearZ]);
  497. // this.KO.z_k = this.z_k;
  498. // this.KM.update(this.KO);
  499. // // console.log(this.KM.x_k.elements[0], e.linearZ);
  500. // if (this.KM.x_k.elements[0] > 0)
  501. // this.lineZ.onUpdateDraw(this.KM.x_k.elements[0]);
  502. // else
  503. // this.lineZ.onUpdateDrawFromColor(this.KM.x_k.elements[0], cc.Color.WHITE, 2);
  504. // if (lAccZ > 0)
  505. // this.lineZ.onUpdateDraw(lAccZ);
  506. // else
  507. // this.lineZ.onUpdateDrawFromColor(lAccZ, cc.Color.WHITE, 2);
  508. this.lineZ.onUpdateDraw(oAccZ);
  509. this.lineLinearZ.onUpdateDrawFromColor(lAccZ, "#00F0FF", 2);
  510. }
  511. } else if (e.type == 'stop') {
  512. console.log('stop');
  513. this.onSaveData(this.currentGameDataArray);
  514. this.lineX.clear();
  515. this.lineY.clear();
  516. this.lineLinearY.clear();
  517. //
  518. let tempArray = e.tempDataArray[0];
  519. for (let i = 0; i < tempArray.length; i++) {
  520. //绘制读取的数据
  521. this.lineY.onUpdateIndex();
  522. this.lineY.onUpdateDraw(tempArray[i].oriAcc.oAccZ);
  523. this.lineLinearY.onUpdateIndex();
  524. this.lineLinearY.onUpdateDraw(tempArray[i].linearAcc.lAccZ);
  525. if (i < 30) {
  526. this.lineX.onUpdateIndex();
  527. this.lineX.onUpdateDraw(tempArray[i].oriAcc.oAccZ);
  528. }
  529. }
  530. }
  531. })
  532. this.onBind();
  533. setInterval(() => {
  534. let ave = this.phoneAccIndex - this.oldPhoneIndex;
  535. this.playerControScript.onAvePhoneIndex(ave);
  536. this.oldPhoneIndex = this.phoneAccIndex;
  537. let ave2 = this.BLEAccIndex - this.oldBLEAccIndex;
  538. this.playerControScript.onAveBLEIndex(ave2);
  539. this.oldBLEAccIndex = this.BLEAccIndex;
  540. }, 1000)
  541. // for (let i = 0; i < 300; i++) {
  542. // let box = {};
  543. // box["acc"] = {
  544. // ax: -9 * Math.random() + 0.1,
  545. // ay: -9 * Math.random() + 0.1,
  546. // az: 9 * Math.random() + 0.1
  547. // };
  548. // box["gyro"] = {
  549. // gx: -9 * Math.random() + 0.1,
  550. // gy: -9 * Math.random() + 0.1,
  551. // gz: 9 * Math.random() + 0.1
  552. // };
  553. // box["min"] = 0;
  554. // box["s"] = 0;
  555. // box["ms"] = 10 * i + 10;
  556. // this.onBLEBoxUpdate(box);
  557. // }
  558. // let index = 0;
  559. // this.schedule(() => {
  560. // let box = {};
  561. // box["acc"] = {
  562. // ax: -9 * Math.random() + 0.1,
  563. // ay: -9 * Math.random() + 0.1,
  564. // az: 9 * Math.random() + 0.1
  565. // };
  566. // box["gyro"] = {
  567. // gx: -9 * Math.random() + 0.1,
  568. // gy: -9 * Math.random() + 0.1,
  569. // gz: 9 * Math.random() + 0.1
  570. // };
  571. // box["min"] = 0;
  572. // box["s"] = 0;
  573. // box["ms"] = 10 * index + 10;
  574. // index ++ ;
  575. // this.onBLEBoxUpdate(box);
  576. // }, 0.03)
  577. },
  578. //重置一下,记录的数据
  579. onResetAccState() {
  580. console.log("重置 onResetAccState");
  581. this.hitFirst = null;
  582. this.bLock = false;
  583. this.hitState = {
  584. "xLCount": 0,
  585. "xRCount": 0,
  586. "zLCount": 0,
  587. "zRCount": 0
  588. }
  589. },
  590. onBind() {
  591. notifyCenter.on('webViewMessage', (data) => {
  592. let name = data.funName;
  593. if (name == "onWatchAccelerometer") {
  594. /**
  595. * 返回加速计的数据
  596. * {
  597. * xAxis
  598. * yAxis
  599. * zAxis
  600. * }
  601. */
  602. webView.onUpdateAcc(data);
  603. } else if (name == "onWatchOrientation") {
  604. } else if (name == "onDeviceUpdateData") {
  605. webView.sensorHit = true;
  606. let gameData = data.gameData;
  607. // console.log(gameData.data);
  608. if (gameData.dataType == "Box") {
  609. webView.onBLEBoxUpdate(gameData.data, true);
  610. }
  611. } else if (name == "onDeviceUpdateJson") {
  612. let gameData = data.gameData;
  613. if (gameData.dataType == "Json") {
  614. webView.onBLEJsonUpdate(gameData.data);
  615. }
  616. } else if (name == 'saveData') {
  617. let gameData = data.gameData;
  618. // console.log("saveData:", gameData.length);
  619. //停止硬件更新
  620. webView.onSendWriteBLEDataValue(null, 4);
  621. let saveArrayData = gameData;
  622. // for (let i = 0; i < saveArrayData.length; i++) {
  623. // console.log(saveArrayData[i]);
  624. // //绘制读取的数据
  625. // }
  626. if (this.currentInterval) {
  627. this.currentInterval = null;
  628. clearInterval(this.currentInterval);
  629. }
  630. let _index = 60;
  631. let _length = saveArrayData.length - 370;
  632. // this.currentInterval = setInterval(() => {
  633. // webView.onBLEBoxUpdate(saveArrayData[_index]);
  634. // _index++;
  635. // if (_index >= _length) {
  636. // clearInterval(this.currentInterval);
  637. // }
  638. // }, 0, 0.006)
  639. for (let i = _index; i < _length; i++) {
  640. //绘制读取的数据
  641. webView.onBLEBoxUpdate(saveArrayData[i]);
  642. }
  643. this.actionJump.setEndUpdate();
  644. }
  645. });
  646. // 监听蓝牙设备刷新
  647. uni.postMessage({
  648. data: {
  649. funName: "addDeviceUpdateListener",
  650. gameData: {}
  651. }
  652. })
  653. //监听蓝牙设备刷新
  654. uni.postMessage({
  655. data: {
  656. funName: "addDeviceJsonUpdateListener",
  657. gameData: {}
  658. }
  659. })
  660. },
  661. onUnBind() {
  662. notifyCenter.off('webViewMessage');
  663. uni.postMessage({
  664. data: {
  665. funName: "closeAccelerometer",
  666. gameData: {}
  667. }
  668. })
  669. uni.postMessage({
  670. data: {
  671. funName: "closeOrientation",
  672. gameData: {}
  673. }
  674. })
  675. },
  676. //返回一个json对象
  677. onBLEJsonUpdate(gameData) {
  678. // console.log("json:", gameData);
  679. },
  680. //手柄盒子数据处理
  681. /**
  682. * 计算数据不能为 0, gx, gy, gz
  683. * @param {*} gameData
  684. * @returns
  685. */
  686. onBLEBoxUpdate(gameData, bAdd) {
  687. //记录最近的500帧原始设备数据
  688. if (bAdd) {
  689. if (this.currentGameDataArray.length <= 500) {
  690. this.currentGameDataArray.push(gameData);
  691. } else {
  692. this.currentGameDataArray.shift();
  693. this.currentGameDataArray.push(gameData);
  694. }
  695. }
  696. // console.log(gameData);
  697. //********传感器数值********
  698. let { ax, ay, az } = gameData.acc;
  699. let { gx, gy, gz } = gameData.gyro;
  700. let { min, s, ms } = gameData;
  701. // //更新
  702. // //更新Accl
  703. // this.accel = [ax, ay, az];
  704. // this.calculateAccMagOrientation();
  705. // //更新计算gyro
  706. // this.gyroFunction([gx, gy, gz], ms);
  707. //更新index
  708. if (this.bAccDraw) {
  709. // this.lineX.onUpdateIndex();
  710. this.lineZ.onUpdateIndex();
  711. // this.lineY.onUpdateIndex();
  712. this.lineLinearX.onUpdateIndex();
  713. // this.lineLinearY.onUpdateIndex();
  714. this.lineLinearZ.onUpdateIndex();
  715. this.lineSqrt.onUpdateIndex();
  716. this.lineOriSqrt.onUpdateIndex();
  717. // if (this.bGyroDraw) {
  718. // this.lineX.onUpdateDrawOriBeta(gx);
  719. // this.lineX.onUpdateDrawOriGamma(gy);
  720. // this.lineX.onUpdateDrawOriAlpha(gz);
  721. // this.lineOriSqrt.onUpdateDraw(oriNew);
  722. // }
  723. // this.playerControScript.updateOriSqrt(oriNew);
  724. }
  725. // var msGap = ms - this.LastMS;
  726. // if (msGap < 0) {
  727. // msGap += 1000;
  728. // }
  729. // this.LastMS = ms;
  730. // let _ax = gameData.acc.ax * 10;
  731. // let _ay = gameData.acc.ay * 10;
  732. // let _az = gameData.acc.az * 10;
  733. // //低通滤波分离重力
  734. // let curTime = new Date().getTime();
  735. // let alpha = 1000 / (1000 + msGap); // 0.8;
  736. // this.LastTime = curTime;
  737. // this.xA = alpha * this.xA + (1 - alpha) * _ax;
  738. // this.yA = alpha * this.yA + (1 - alpha) * _ay;
  739. // this.zA = alpha * this.zA + (1 - alpha) * _az;
  740. //高通滤波获取线性速度
  741. // let linear_acceleration_x = _ax - this.xA;
  742. // let linear_acceleration_y = _ay - this.yA;
  743. // let linear_acceleration_z = _az - this.zA;
  744. // let _temp = {
  745. // oriAcc: {
  746. // oAccX: _ax,
  747. // oAccY: _ay,
  748. // oAccZ: _az
  749. // },
  750. // linearAcc: {
  751. // lAccX: linear_acceleration_x,
  752. // lAccY: linear_acceleration_y,
  753. // lAccZ: linear_acceleration_z
  754. // },
  755. // gravityAcc: {
  756. // gravityX: this.xA,
  757. // gravityY: this.yA,
  758. // gravityZ: this.zA
  759. // },
  760. // bLimitRebound: false,
  761. // resultant: Math.sqrt(_ax * _ax
  762. // + _ay * _ay + _az * _az),
  763. // runIndex: this.BLEAccIndex,
  764. // //陀螺仪
  765. // oriGyro: {
  766. // oGyroX: gx,
  767. // oGyroY: gy,
  768. // oGyroZ: gz
  769. // },
  770. // //输入当前轴
  771. // bYAxis: this.isY,
  772. // };
  773. gameData.BLEAccIndex = this.BLEAccIndex;
  774. gameData.bYAxis = this.isY;
  775. this.actionJump.updateJump(gameData);
  776. // this.currentDataArray.push(_temp);
  777. // this.drawXScript.addPoint(_temp.oriAcc.oAccX);
  778. if (this.bAccDraw) {
  779. //显示
  780. // this.playerControScript.updateAcc({ xAxis: _ax, yAxis: _ay, zAxis: _az });
  781. // this.playerControScript.updateAcc({ xAxis: deltaVector[0], yAxis: deltaVector[1], zAxis: deltaVector[2] });
  782. // this.playerControScript.updateStr(deltaVector[3]);
  783. // this.playerControScript.updateAcc({ xAxis: this.gyroOrientation[0], yAxis: this.gyroOrientation[1], zAxis: this.gyroOrientation[2] });
  784. // this.playerControScript.updateSqrt(_temp.resultant);
  785. this.lineOriSqrt.onUpdateDraw(gy);
  786. }
  787. // if (this.bAccDraw) {
  788. // this.lineSqrt.onUpdateDraw(_temp.resultant);
  789. // }
  790. // if (this.bAccLog) {
  791. // console.log("acc:" + JSON.stringify(gameData.acc));
  792. // }
  793. this.playerControScript.updateBLEIndex(this.BLEAccIndex);
  794. if (this.BLEAccIndex > 150) {
  795. this.onClear();
  796. this.bJump = false;
  797. }
  798. this.BLEAccIndex++;
  799. this.oldxA = this.xA;
  800. },
  801. onClear() {
  802. // this.lineX.clear();
  803. this.lineZ.clear();
  804. // this.lineY.clear();
  805. this.lineLinearX.clear();
  806. // this.lineLinearY.clear();
  807. this.lineLinearZ.clear();
  808. this.lineSqrt.clear();
  809. this.lineOriSqrt.clear();
  810. this.BLEAccIndex = 0;
  811. this.oldBLEAccIndex = 0;
  812. this.currentDataArray = [];
  813. this.rotate.angle = 90;
  814. },
  815. onSendWriteBLEData() {
  816. uni.postMessage({
  817. data: {
  818. funName: "writeBLEConnectionValue",
  819. gameData: {
  820. value: this.playerControScript.writeValue
  821. }
  822. }
  823. })
  824. },
  825. onSendWriteBLEDataValue(event, data) {
  826. console.log(data);
  827. this.onClear();
  828. this.bJump = false;
  829. uni.postMessage({
  830. data: {
  831. funName: "writeBLEConnectionValue",
  832. gameData: {
  833. value: data
  834. }
  835. }
  836. })
  837. console.log(this.gyroMatrix);
  838. console.log(this.gyroMatrix.length);
  839. },
  840. onSaveData(data) {
  841. uni.postMessage({
  842. data: {
  843. funName: "saveData",
  844. gameData: {
  845. value: data
  846. }
  847. }
  848. })
  849. },
  850. onGetData() {
  851. uni.postMessage({
  852. data: {
  853. funName: "getData",
  854. gameData: {}
  855. }
  856. })
  857. },
  858. onOnlySendWriteBLEDataValue(event, data) {
  859. console.log(data);
  860. uni.postMessage({
  861. data: {
  862. funName: "writeBLEConnectionValue",
  863. gameData: {
  864. value: data
  865. }
  866. }
  867. })
  868. },
  869. //在app 端输出log
  870. onLog(str) {
  871. uni.postMessage({
  872. data: {
  873. funName: "log",
  874. gameData: str
  875. }
  876. })
  877. },
  878. onChangeAccDraw() {
  879. console.log("this.bAccDraw", this.bAccDraw);
  880. this.bAccDraw = !this.bAccDraw;
  881. this.accDrawLabel.string = this.bAccDraw ? "关闭渲染加速计" : "开启渲染加速计";
  882. },
  883. onChangeGyroDraw() {
  884. this.bGyroDraw = !this.bGyroDraw;
  885. this.gyroDrawLabel.string = this.bGyroDraw ? "关闭渲染陀螺仪" : "开启渲染陀螺仪";
  886. },
  887. onShowAccLog() {
  888. this.bAccLog = !this.bAccLog;
  889. this.accLogLabel.string = this.bAccLog ? "关闭加速计日志" : "开启加速计日志";
  890. },
  891. onShowGyroLog() {
  892. this.bGyroLog = !this.bGyroLog;
  893. this.gyroLogLabel.string = this.bGyroLog ? "关闭陀螺仪日志" : "开启陀螺仪日志";
  894. },
  895. onSlideEvent(data) {
  896. this.bShowIndex = data.progress;
  897. this.onUpdateShowData(this.bShowIndex);
  898. },
  899. onSwitchData(data) {
  900. // console.log(data.node);
  901. this.bShowOri = data.isChecked;
  902. data.node.getChildByName('label').getComponent(cc.Label).string = this.bShowOri ? '原始数据' : '线性加速度';
  903. this.onUpdateShowData(this.bShowIndex);
  904. },
  905. onUpdateShowData(_progress) {
  906. let _length = this.currentDataArray.length;
  907. let index = Math.ceil(_progress * _length);
  908. let _data = this.currentDataArray[index - 1 < 0 ? 0 : index - 1];
  909. let currentX = _data.oriAcc.x;
  910. let currentZ = _data.oriAcc.z;
  911. let currentY = _data.oriAcc.y;
  912. if (!this.bShowOri) {
  913. currentX = _data.linearAcc.ax;
  914. currentZ = _data.linearAcc.az;
  915. currentY = _data.linearAcc.ay;
  916. }
  917. //显示
  918. this.playerControScript.updateAcc({ xAxis: currentX, yAxis: currentY, zAxis: currentZ });
  919. this.playerControScript.updateSqrt(_data.resultant);
  920. this.lineDrawTip.drawCicleFromIndex(index);
  921. },
  922. /**
  923. *
  924. * 处理陀螺仪数据
  925. *
  926. */
  927. getRotationVectorFromGyro(gyroValues, deltaRotationVector, timeFactor) {
  928. // console.log("gyroValues:", gyroValues);
  929. let EPSILON = 0.001;
  930. let normValues = new Array(3);;
  931. // Calculate the angular speed of the sample
  932. let omegaMagnitude = Math.sqrt(gyroValues[0] * gyroValues[0] +
  933. gyroValues[1] * gyroValues[1] +
  934. gyroValues[2] * gyroValues[2]);
  935. // Normalize the rotation vector if it's big enough to get the axis
  936. if (omegaMagnitude > EPSILON) {
  937. normValues[0] = gyroValues[0] / omegaMagnitude;
  938. normValues[1] = gyroValues[1] / omegaMagnitude;
  939. normValues[2] = gyroValues[2] / omegaMagnitude;
  940. }
  941. // Integrate around this axis with the angular speed by the timestep
  942. // in order to get a delta rotation from this sample over the timestep
  943. // We will convert this axis-angle representation of the delta rotation
  944. // into a quaternion before turning it into the rotation matrix.
  945. let thetaOverTwo = omegaMagnitude * timeFactor;
  946. let sinThetaOverTwo = Math.sin(thetaOverTwo);
  947. let cosThetaOverTwo = Math.cos(thetaOverTwo);
  948. // console.log(sinThetaOverTwo, "==", normValues[0]);
  949. deltaRotationVector[0] = sinThetaOverTwo * normValues[0];
  950. deltaRotationVector[1] = sinThetaOverTwo * normValues[1];
  951. deltaRotationVector[2] = sinThetaOverTwo * normValues[2];
  952. deltaRotationVector[3] = cosThetaOverTwo;
  953. },
  954. /** Helper function to convert a rotation vector to a rotation matrix.
  955. * Given a rotation vector (presumably from a ROTATION_VECTOR sensor), returns a
  956. * 9 or 16 element rotation matrix in the array R. R must have length 9 or 16.
  957. * If R.length == 9, the following matrix is returned:
  958. * <pre>
  959. * / R[ 0] R[ 1] R[ 2] \
  960. * | R[ 3] R[ 4] R[ 5] |
  961. * \ R[ 6] R[ 7] R[ 8] /
  962. *</pre>
  963. * If R.length == 16, the following matrix is returned:
  964. * <pre>
  965. * / R[ 0] R[ 1] R[ 2] 0 \
  966. * | R[ 4] R[ 5] R[ 6] 0 |
  967. * | R[ 8] R[ 9] R[10] 0 |
  968. * \ 0 0 0 1 /
  969. *</pre>
  970. * @param rotationVector the rotation vector to convert
  971. * @param R an array of floats in which to store the rotation matrix
  972. */
  973. getRotationMatrixFromVector(R, rotationVector) {
  974. let q0;
  975. let q1 = rotationVector[0];
  976. let q2 = rotationVector[1];
  977. let q3 = rotationVector[2];
  978. if (rotationVector.length >= 4) {
  979. q0 = rotationVector[3];
  980. } else {
  981. q0 = 1 - q1 * q1 - q2 * q2 - q3 * q3;
  982. q0 = (q0 > 0) ? Math.sqrt(q0) : 0;
  983. }
  984. let sq_q1 = 2 * q1 * q1;
  985. let sq_q2 = 2 * q2 * q2;
  986. let sq_q3 = 2 * q3 * q3;
  987. let q1_q2 = 2 * q1 * q2;
  988. let q3_q0 = 2 * q3 * q0;
  989. let q1_q3 = 2 * q1 * q3;
  990. let q2_q0 = 2 * q2 * q0;
  991. let q2_q3 = 2 * q2 * q3;
  992. let q1_q0 = 2 * q1 * q0;
  993. if (R.length == 9) {
  994. R[0] = 1 - sq_q2 - sq_q3;
  995. R[1] = q1_q2 - q3_q0;
  996. R[2] = q1_q3 + q2_q0;
  997. R[3] = q1_q2 + q3_q0;
  998. R[4] = 1 - sq_q1 - sq_q3;
  999. R[5] = q2_q3 - q1_q0;
  1000. R[6] = q1_q3 - q2_q0;
  1001. R[7] = q2_q3 + q1_q0;
  1002. R[8] = 1 - sq_q1 - sq_q2;
  1003. } else if (R.length == 16) {
  1004. R[0] = 1 - sq_q2 - sq_q3;
  1005. R[1] = q1_q2 - q3_q0;
  1006. R[2] = q1_q3 + q2_q0;
  1007. R[3] = 0.0;
  1008. R[4] = q1_q2 + q3_q0;
  1009. R[5] = 1 - sq_q1 - sq_q3;
  1010. R[6] = q2_q3 - q1_q0;
  1011. R[7] = 0.0;
  1012. R[8] = q1_q3 - q2_q0;
  1013. R[9] = q2_q3 + q1_q0;
  1014. R[10] = 1 - sq_q1 - sq_q2;
  1015. R[11] = 0.0;
  1016. R[12] = R[13] = R[14] = 0.0;
  1017. R[15] = 1.0;
  1018. }
  1019. },
  1020. matrixMultiplication(A, B) {
  1021. let result = new Array(9);
  1022. result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
  1023. result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
  1024. result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
  1025. result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
  1026. result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
  1027. result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
  1028. result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
  1029. result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
  1030. result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
  1031. return result;
  1032. },
  1033. /**
  1034. * Computes the device's orientation based on the rotation matrix.
  1035. * <p>
  1036. * When it returns, the array values are as follows:
  1037. * <ul>
  1038. * <li>values[0]: <i>Azimuth</i>, angle of rotation about the -z axis.
  1039. * This value represents the angle between the device's y
  1040. * axis and the magnetic north pole. When facing north, this
  1041. * angle is 0, when facing south, this angle is &pi;.
  1042. * Likewise, when facing east, this angle is &pi;/2, and
  1043. * when facing west, this angle is -&pi;/2. The range of
  1044. * values is -&pi; to &pi;.</li>
  1045. * <li>values[1]: <i>Pitch</i>, angle of rotation about the x axis.
  1046. * This value represents the angle between a plane parallel
  1047. * to the device's screen and a plane parallel to the ground.
  1048. * Assuming that the bottom edge of the device faces the
  1049. * user and that the screen is face-up, tilting the top edge
  1050. * of the device toward the ground creates a positive pitch
  1051. * angle. The range of values is -&pi; to &pi;.</li>
  1052. * <li>values[2]: <i>Roll</i>, angle of rotation about the y axis. This
  1053. * value represents the angle between a plane perpendicular
  1054. * to the device's screen and a plane perpendicular to the
  1055. * ground. Assuming that the bottom edge of the device faces
  1056. * the user and that the screen is face-up, tilting the left
  1057. * edge of the device toward the ground creates a positive
  1058. * roll angle. The range of values is -&pi;/2 to &pi;/2.</li>
  1059. * </ul>
  1060. * <p>
  1061. * Applying these three rotations in the azimuth, pitch, roll order
  1062. * transforms an identity matrix to the rotation matrix passed into this
  1063. * method. Also, note that all three orientation angles are expressed in
  1064. * <b>radians</b>.
  1065. *
  1066. * @param R
  1067. * rotation matrix see {@link #getRotationMatrix}.
  1068. *
  1069. * @param values
  1070. * an array of 3 floats to hold the result.
  1071. *
  1072. * @return The array values passed as argument.
  1073. *
  1074. * @see #getRotationMatrix(float[], float[], float[], float[])
  1075. * @see GeomagneticField
  1076. */
  1077. getOrientation(R, values) {
  1078. /*
  1079. * 4x4 (length=16) case:
  1080. * / R[ 0] R[ 1] R[ 2] 0 \
  1081. * | R[ 4] R[ 5] R[ 6] 0 |
  1082. * | R[ 8] R[ 9] R[10] 0 |
  1083. * \ 0 0 0 1 /
  1084. *
  1085. * 3x3 (length=9) case:
  1086. * / R[ 0] R[ 1] R[ 2] \
  1087. * | R[ 3] R[ 4] R[ 5] |
  1088. * \ R[ 6] R[ 7] R[ 8] /
  1089. *
  1090. */
  1091. if (R.length == 9) {
  1092. values[0] = Math.atan2(R[1], R[4]);
  1093. values[1] = Math.asin(-R[7]);
  1094. values[2] = Math.atan2(-R[6], R[8]);
  1095. } else {
  1096. values[0] = Math.atan2(R[1], R[5]);
  1097. values[1] = Math.asin(-R[9]);
  1098. values[2] = Math.atan2(-R[8], R[10]);
  1099. }
  1100. return values;
  1101. },
  1102. getRotationMatrixFromOrientation(o) {
  1103. let xM = new Array(9);
  1104. let yM = new Array(9);
  1105. let zM = new Array(9);
  1106. let sinX = Math.sin(o[1]);
  1107. let cosX = Math.cos(o[1]);
  1108. let sinY = Math.sin(o[2]);
  1109. let cosY = Math.cos(o[2]);
  1110. let sinZ = Math.sin(o[0]);
  1111. let cosZ = Math.cos(o[0]);
  1112. // rotation about x-axis (pitch)
  1113. xM[0] = 1.0; xM[1] = 0.0; xM[2] = 0.0;
  1114. xM[3] = 0.0; xM[4] = cosX; xM[5] = sinX;
  1115. xM[6] = 0.0; xM[7] = -sinX; xM[8] = cosX;
  1116. // rotation about y-axis (roll)
  1117. yM[0] = cosY; yM[1] = 0.0; yM[2] = sinY;
  1118. yM[3] = 0.0; yM[4] = 1.0; yM[5] = 0.0;
  1119. yM[6] = -sinY; yM[7] = 0.0; yM[8] = cosY;
  1120. // rotation about z-axis (azimuth)
  1121. zM[0] = cosZ; zM[1] = sinZ; zM[2] = 0.0;
  1122. zM[3] = -sinZ; zM[4] = cosZ; zM[5] = 0.0;
  1123. zM[6] = 0.0; zM[7] = 0.0; zM[8] = 1.0;
  1124. // rotation order is y, x, z (roll, pitch, azimuth)
  1125. let resultMatrix = this.matrixMultiplication(xM, yM);
  1126. resultMatrix = this.matrixMultiplication(zM, resultMatrix);
  1127. return resultMatrix;
  1128. },
  1129. calculateAccMagOrientation() {
  1130. // magnet
  1131. if (this.getRotationMatrix(this.rotationMatrix, null, this.accel, [1, 1, 1])) {
  1132. this.getOrientation(this.rotationMatrix, this.accMagOrientation);
  1133. }
  1134. // this.getOrientation(this.rotationMatrix, this.accel);
  1135. },
  1136. getRotationMatrix(R, I, gravity, geomagnetic) {
  1137. // TODO: move this to native code for efficiency
  1138. let Ax = gravity[0];
  1139. let Ay = gravity[1];
  1140. let Az = gravity[2];
  1141. let normsqA = (Ax * Ax + Ay * Ay + Az * Az);
  1142. let g = 9.81;
  1143. let freeFallGravitySquared = 0.01 * g * g;
  1144. if (normsqA < freeFallGravitySquared) {
  1145. // gravity less than 10% of normal value
  1146. return false;
  1147. }
  1148. let Ex = geomagnetic[0];
  1149. let Ey = geomagnetic[1];
  1150. let Ez = geomagnetic[2];
  1151. let Hx = Ey * Az - Ez * Ay;
  1152. let Hy = Ez * Ax - Ex * Az;
  1153. let Hz = Ex * Ay - Ey * Ax;
  1154. let normH = Math.sqrt(Hx * Hx + Hy * Hy + Hz * Hz);
  1155. if (normH < 0.1) {
  1156. // device is close to free fall (or in space?), or close to
  1157. // magnetic north pole. Typical values are > 100.
  1158. return false;
  1159. }
  1160. let invH = 1.0 / normH;
  1161. Hx *= invH;
  1162. Hy *= invH;
  1163. Hz *= invH;
  1164. let invA = 1.0 / Math.sqrt(Ax * Ax + Ay * Ay + Az * Az);
  1165. Ax *= invA;
  1166. Ay *= invA;
  1167. Az *= invA;
  1168. let Mx = Ay * Hz - Az * Hy;
  1169. let My = Az * Hx - Ax * Hz;
  1170. let Mz = Ax * Hy - Ay * Hx;
  1171. if (R != null) {
  1172. if (R.length == 9) {
  1173. R[0] = Hx; R[1] = Hy; R[2] = Hz;
  1174. R[3] = Mx; R[4] = My; R[5] = Mz;
  1175. R[6] = Ax; R[7] = Ay; R[8] = Az;
  1176. } else if (R.length == 16) {
  1177. R[0] = Hx; R[1] = Hy; R[2] = Hz; R[3] = 0;
  1178. R[4] = Mx; R[5] = My; R[6] = Mz; R[7] = 0;
  1179. R[8] = Ax; R[9] = Ay; R[10] = Az; R[11] = 0;
  1180. R[12] = 0; R[13] = 0; R[14] = 0; R[15] = 1;
  1181. }
  1182. }
  1183. if (I != null) {
  1184. // compute the inclination matrix by projecting the geomagnetic
  1185. // vector onto the Z (gravity) and X (horizontal component
  1186. // of geomagnetic vector) axes.
  1187. let invE = 1.0 / Math.sqrt(Ex * Ex + Ey * Ey + Ez * Ez);
  1188. let c = (Ex * Mx + Ey * My + Ez * Mz) * invE;
  1189. let s = (Ex * Ax + Ey * Ay + Ez * Az) * invE;
  1190. if (I.length == 9) {
  1191. I[0] = 1; I[1] = 0; I[2] = 0;
  1192. I[3] = 0; I[4] = c; I[5] = s;
  1193. I[6] = 0; I[7] = -s; I[8] = c;
  1194. } else if (I.length == 16) {
  1195. I[0] = 1; I[1] = 0; I[2] = 0;
  1196. I[4] = 0; I[5] = c; I[6] = s;
  1197. I[8] = 0; I[9] = -s; I[10] = c;
  1198. I[3] = I[7] = I[11] = I[12] = I[13] = I[14] = 0;
  1199. I[15] = 1;
  1200. }
  1201. }
  1202. return true;
  1203. },
  1204. gyroFunction(gyroValues, timeMs) {
  1205. // don't start until first accelerometer/magnetometer orientation has been acquired
  1206. if (this.accMagOrientation == null)
  1207. return;
  1208. // initialisation of the gyroscope based rotation matrix
  1209. if (this.initState) {
  1210. let initMatrix = new Array(9);
  1211. initMatrix = this.getRotationMatrixFromOrientation(this.accMagOrientation);
  1212. let test = new Array(3);
  1213. this.getOrientation(initMatrix, test);
  1214. this.gyroMatrix = this.matrixMultiplication(this.gyroMatrix, initMatrix);
  1215. this.initState = false;
  1216. }
  1217. // copy the new gyro values into the gyro array
  1218. // convert the raw gyro data into a rotation vector
  1219. let deltaVector = new Array(4);
  1220. // if (this.timestamp != 0) {
  1221. // }
  1222. let dT = (timeMs - this.timestamp) * this.MS2S;
  1223. this.gyro = [];
  1224. gyroValues.forEach((item) => this.gyro.push(item));
  1225. this.getRotationVectorFromGyro(this.gyro, deltaVector, dT / 2.0);
  1226. // measurement done, save current time for next interval
  1227. this.timestamp = timeMs;
  1228. // convert rotation vector into rotation matrix
  1229. let deltaMatrix = new Array(9);
  1230. // console.log("deltaVector1:" + deltaVector);
  1231. // console.log("deltaMatrix1:" + deltaMatrix);
  1232. this.getRotationMatrixFromVector(deltaMatrix, deltaVector);
  1233. // console.log("deltaVector2:" + deltaVector);
  1234. // console.log("deltaMatrix2:" + deltaMatrix);
  1235. // apply the new rotation interval on the gyroscope based rotation matrix
  1236. this.gyroMatrix = this.matrixMultiplication(this.gyroMatrix, deltaMatrix);
  1237. // console.log(this.gyroMatrix);
  1238. // console.log(this.gyroMatrix.length);
  1239. // get the gyroscope based orientation from the rotation matrix
  1240. this.getOrientation(this.gyroMatrix, this.gyroOrientation);
  1241. },
  1242. /**
  1243. * 主要计算
  1244. */
  1245. calculateFusedOrientationTask() {
  1246. let FILTER_COEFFICIENT = 0.98;
  1247. let oneMinusCoeff = 1.0 - FILTER_COEFFICIENT;
  1248. this.fusedOrientation[0] =
  1249. FILTER_COEFFICIENT * this.gyroOrientation[0]
  1250. + oneMinusCoeff * this.accMagOrientation[0];
  1251. this.fusedOrientation[1] =
  1252. FILTER_COEFFICIENT * this.gyroOrientation[1]
  1253. + oneMinusCoeff * this.accMagOrientation[1];
  1254. this.fusedOrientation[2] =
  1255. FILTER_COEFFICIENT * this.gyroOrientation[2]
  1256. + oneMinusCoeff * this.accMagOrientation[2];
  1257. // overwrite gyro matrix and orientation with fused orientation
  1258. // to comensate gyro drift
  1259. this.gyroMatrix = this.getRotationMatrixFromOrientation(this.fusedOrientation);
  1260. // System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3);
  1261. this.gyroOrientation = [];
  1262. this.fusedOrientation.forEach((item) => this.gyroOrientation.push(item));
  1263. }
  1264. });