blob: 88c286410c4be14a3db4916383c872216e894eee [file] [log] [blame]
James Kuszmauldac091f2022-03-22 09:35:06 -07001import {ByteBuffer} from 'flatbuffers';
James Kuszmaulf3ef9e12022-03-05 17:13:00 -08002import {Connection} from 'org_frc971/aos/network/www/proxy';
James Kuszmauldac091f2022-03-22 09:35:06 -07003import {IntakeState, Status as SuperstructureStatus, SuperstructureState} from 'org_frc971/y2022/control_loops/superstructure/superstructure_status_generated'
4import {LocalizerOutput} from 'org_frc971/y2022/localizer/localizer_output_generated';
5import {RejectionReason} from 'org_frc971/y2022/localizer/localizer_status_generated';
6import {LocalizerVisualization, TargetEstimateDebug} from 'org_frc971/y2022/localizer/localizer_visualization_generated';
James Kuszmaulf3ef9e12022-03-05 17:13:00 -08007
8import {FIELD_LENGTH, FIELD_WIDTH, FT_TO_M, IN_TO_M} from './constants';
9
10// (0,0) is field center, +X is toward red DS
11const FIELD_SIDE_Y = FIELD_WIDTH / 2;
12const FIELD_EDGE_X = FIELD_LENGTH / 2;
13
14const ROBOT_WIDTH = 34 * IN_TO_M;
15const ROBOT_LENGTH = 36 * IN_TO_M;
16
17const PI_COLORS = ['#ff00ff', '#ffff00', '#00ffff', '#ffa500'];
18
19export class FieldHandler {
20 private canvas = document.createElement('canvas');
21 private localizerOutput: LocalizerOutput|null = null;
22 private superstructureStatus: SuperstructureStatus|null = null;
23
24 // Image information indexed by timestamp (seconds since the epoch), so that
25 // we can stop displaying images after a certain amount of time.
26 private localizerImageMatches = new Map<number, LocalizerVisualization>();
27 private outerTarget: HTMLElement =
28 (document.getElementById('outer_target') as HTMLElement);
29 private innerTarget: HTMLElement =
30 (document.getElementById('inner_target') as HTMLElement);
31 private x: HTMLElement = (document.getElementById('x') as HTMLElement);
32 private y: HTMLElement = (document.getElementById('y') as HTMLElement);
33 private theta: HTMLElement =
34 (document.getElementById('theta') as HTMLElement);
35 private shotDistance: HTMLElement =
36 (document.getElementById('shot_distance') as HTMLElement);
37 private turret: HTMLElement =
38 (document.getElementById('turret') as HTMLElement);
James Kuszmaula0871872022-03-05 22:12:39 -080039 private fire: HTMLElement =
40 (document.getElementById('fire') as HTMLElement);
41 private mpcSolveTime: HTMLElement =
42 (document.getElementById('mpc_solve_time') as HTMLElement);
Austin Schuh41472552022-03-13 18:09:41 -070043 private mpcHorizon: HTMLElement =
44 (document.getElementById('mpc_horizon') as HTMLElement);
James Kuszmaula0871872022-03-05 22:12:39 -080045 private shotCount: HTMLElement =
46 (document.getElementById('shot_count') as HTMLElement);
47 private catapult: HTMLElement =
48 (document.getElementById('catapult') as HTMLElement);
49 private superstructureState: HTMLElement =
50 (document.getElementById('superstructure_state') as HTMLElement);
51 private intakeState: HTMLElement =
52 (document.getElementById('intake_state') as HTMLElement);
53 private reseatingInCatapult: HTMLElement =
54 (document.getElementById('reseating_in_catapult') as HTMLElement);
55 private flippersOpen: HTMLElement =
56 (document.getElementById('flippers_open') as HTMLElement);
57 private climber: HTMLElement =
58 (document.getElementById('climber') as HTMLElement);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -080059 private frontIntake: HTMLElement =
60 (document.getElementById('front_intake') as HTMLElement);
61 private backIntake: HTMLElement =
62 (document.getElementById('back_intake') as HTMLElement);
63 private imagesAcceptedCounter: HTMLElement =
64 (document.getElementById('images_accepted') as HTMLElement);
65 private imagesRejectedCounter: HTMLElement =
66 (document.getElementById('images_rejected') as HTMLElement);
67 private rejectionReasonCells: HTMLElement[] = [];
68 private fieldImage: HTMLImageElement = new Image();
69
70 constructor(private readonly connection: Connection) {
71 (document.getElementById('field') as HTMLElement).appendChild(this.canvas);
72
73 this.fieldImage.src = "2022.png";
74
75 for (const value in RejectionReason) {
76 // Typescript generates an iterator that produces both numbers and
77 // strings... don't do anything on the string iterations.
78 if (isNaN(Number(value))) {
79 continue;
80 }
81 const row = document.createElement('div');
82 const nameCell = document.createElement('div');
83 nameCell.innerHTML = RejectionReason[value];
84 row.appendChild(nameCell);
85 const valueCell = document.createElement('div');
86 valueCell.innerHTML = 'NA';
87 this.rejectionReasonCells.push(valueCell);
88 row.appendChild(valueCell);
89 document.getElementById('vision_readouts').appendChild(row);
90 }
91
92 for (let ii = 0; ii < PI_COLORS.length; ++ii) {
93 const legendEntry = document.createElement('div');
94 legendEntry.style.color = PI_COLORS[ii];
95 legendEntry.innerHTML = 'PI' + (ii + 1).toString()
96 document.getElementById('legend').appendChild(legendEntry);
97 }
98
99 this.connection.addConfigHandler(() => {
James Kuszmaul43c0f2c2022-04-03 16:17:26 -0700100 // Visualization message is reliable so that we can see *all* the vision
101 // matches.
102 this.connection.addReliableHandler(
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800103 '/localizer', LocalizerVisualization.getFullyQualifiedName(),
104 (data) => {
105 this.handleLocalizerDebug(data);
106 });
107 this.connection.addHandler(
108 '/localizer', LocalizerOutput.getFullyQualifiedName(), (data) => {
109 this.handleLocalizerOutput(data);
110 });
111 this.connection.addHandler(
112 '/superstructure', SuperstructureStatus.getFullyQualifiedName(),
113 (data) => {
114 this.handleSuperstructureStatus(data);
115 });
116 });
117 }
118
119 private handleLocalizerDebug(data: Uint8Array): void {
120 const now = Date.now() / 1000.0;
121
122 const fbBuffer = new ByteBuffer(data);
123 this.localizerImageMatches.set(
James Kuszmauldac091f2022-03-22 09:35:06 -0700124 now, LocalizerVisualization.getRootAsLocalizerVisualization(fbBuffer));
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800125
126 const debug = this.localizerImageMatches.get(now);
127
128 if (debug.statistics()) {
129 this.imagesAcceptedCounter.innerHTML =
130 debug.statistics().totalAccepted().toString();
131 this.imagesRejectedCounter.innerHTML =
132 (debug.statistics().totalCandidates() -
133 debug.statistics().totalAccepted())
134 .toString();
135 if (debug.statistics().rejectionReasonCountLength() ==
136 this.rejectionReasonCells.length) {
137 for (let ii = 0; ii < debug.statistics().rejectionReasonCountLength();
138 ++ii) {
139 this.rejectionReasonCells[ii].innerHTML =
140 debug.statistics().rejectionReasonCount(ii).toString();
141 }
142 } else {
143 console.error('Unexpected number of rejection reasons in counter.');
144 }
145 this.imagesRejectedCounter.innerHTML =
146 (debug.statistics().totalCandidates() -
147 debug.statistics().totalAccepted())
148 .toString();
149 }
150 }
151
152 private handleLocalizerOutput(data: Uint8Array): void {
153 const fbBuffer = new ByteBuffer(data);
James Kuszmauldac091f2022-03-22 09:35:06 -0700154 this.localizerOutput = LocalizerOutput.getRootAsLocalizerOutput(fbBuffer);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800155 }
156
157 private handleSuperstructureStatus(data: Uint8Array): void {
158 const fbBuffer = new ByteBuffer(data);
James Kuszmauldac091f2022-03-22 09:35:06 -0700159 this.superstructureStatus = SuperstructureStatus.getRootAsStatus(fbBuffer);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800160 }
161
162 drawField(): void {
163 const ctx = this.canvas.getContext('2d');
James Kuszmauldee532c2022-04-16 14:43:06 -0700164 ctx.save();
165 ctx.scale(-1.0, 1.0);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800166 ctx.drawImage(
167 this.fieldImage, 0, 0, this.fieldImage.width, this.fieldImage.height,
168 -FIELD_EDGE_X, -FIELD_SIDE_Y, FIELD_LENGTH, FIELD_WIDTH);
James Kuszmauldee532c2022-04-16 14:43:06 -0700169 ctx.restore();
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800170 }
171
172 drawCamera(
173 x: number, y: number, theta: number, color: string = 'blue',
174 extendLines: boolean = true): void {
175 const ctx = this.canvas.getContext('2d');
176 ctx.save();
177 ctx.translate(x, y);
178 ctx.rotate(theta);
179 ctx.strokeStyle = color;
180 ctx.beginPath();
181 ctx.moveTo(0.5, 0.5);
182 ctx.lineTo(0, 0);
183 if (extendLines) {
184 ctx.lineTo(100.0, 0);
185 ctx.lineTo(0, 0);
186 }
187 ctx.lineTo(0.5, -0.5);
188 ctx.stroke();
189 ctx.beginPath();
190 ctx.arc(0, 0, 0.25, -Math.PI / 4, Math.PI / 4);
191 ctx.stroke();
192 ctx.restore();
193 }
194
195 drawRobot(
196 x: number, y: number, theta: number, turret: number|null,
197 color: string = 'blue', dashed: boolean = false,
198 extendLines: boolean = true): void {
199 const ctx = this.canvas.getContext('2d');
200 ctx.save();
201 ctx.translate(x, y);
202 ctx.rotate(theta);
203 ctx.strokeStyle = color;
204 ctx.lineWidth = ROBOT_WIDTH / 10.0;
205 if (dashed) {
206 ctx.setLineDash([0.05, 0.05]);
207 } else {
208 // Empty array = solid line.
209 ctx.setLineDash([]);
210 }
211 ctx.rect(-ROBOT_LENGTH / 2, -ROBOT_WIDTH / 2, ROBOT_LENGTH, ROBOT_WIDTH);
212 ctx.stroke();
213
214 // Draw line indicating which direction is forwards on the robot.
215 ctx.beginPath();
216 ctx.moveTo(0, 0);
217 if (extendLines) {
218 ctx.lineTo(1000.0, 0);
219 } else {
220 ctx.lineTo(ROBOT_LENGTH / 2.0, 0);
221 }
222 ctx.stroke();
223
224 if (turret !== null) {
225 ctx.save();
226 ctx.rotate(turret);
227 const turretRadius = ROBOT_WIDTH / 3.0;
228 ctx.strokeStyle = 'red';
229 // Draw circle for turret.
230 ctx.beginPath();
231 ctx.arc(0, 0, turretRadius, 0, 2.0 * Math.PI);
232 ctx.stroke();
233 // Draw line in circle to show forwards.
234 ctx.beginPath();
235 ctx.moveTo(0, 0);
236 if (extendLines) {
237 ctx.lineTo(1000.0, 0);
238 } else {
239 ctx.lineTo(turretRadius, 0);
240 }
241 ctx.stroke();
242 ctx.restore();
243 }
244 ctx.restore();
245 }
246
247 setZeroing(div: HTMLElement): void {
248 div.innerHTML = 'zeroing';
249 div.classList.remove('faulted');
250 div.classList.add('zeroing');
251 div.classList.remove('near');
252 }
253
254 setEstopped(div: HTMLElement): void {
255 div.innerHTML = 'estopped';
256 div.classList.add('faulted');
257 div.classList.remove('zeroing');
258 div.classList.remove('near');
259 }
260
261 setTargetValue(
262 div: HTMLElement, target: number, val: number, tolerance: number): void {
263 div.innerHTML = val.toFixed(4);
264 div.classList.remove('faulted');
265 div.classList.remove('zeroing');
266 if (Math.abs(target - val) < tolerance) {
267 div.classList.add('near');
268 } else {
269 div.classList.remove('near');
270 }
271 }
272
273 setValue(div: HTMLElement, val: number): void {
274 div.innerHTML = val.toFixed(4);
275 div.classList.remove('faulted');
276 div.classList.remove('zeroing');
277 div.classList.remove('near');
278 }
279
280 draw(): void {
281 this.reset();
282 this.drawField();
283
284 // Draw the matches with debugging information from the localizer.
285 const now = Date.now() / 1000.0;
James Kuszmaula0871872022-03-05 22:12:39 -0800286 if (this.superstructureStatus) {
287 this.shotDistance.innerHTML = this.superstructureStatus.aimer() ?
Austin Schuh0a732cd2022-03-29 21:19:59 -0700288 (this.superstructureStatus.aimer().shotDistance() /
289 0.0254).toFixed(2) +
290 'in, ' +
291 this.superstructureStatus.aimer().shotDistance().toFixed(2) +
292 'm' :
James Kuszmaula0871872022-03-05 22:12:39 -0800293 'NA';
294
295 this.fire.innerHTML = this.superstructureStatus.fire() ? 'true' : 'false';
296
Austin Schuh41472552022-03-13 18:09:41 -0700297 this.mpcHorizon.innerHTML =
298 this.superstructureStatus.mpcHorizon().toFixed(2);
James Kuszmaula0871872022-03-05 22:12:39 -0800299
300 this.setValue(this.mpcSolveTime, this.superstructureStatus.solveTime());
301
302 this.shotCount.innerHTML =
303 this.superstructureStatus.shotCount().toFixed(0);
304
305 this.superstructureState.innerHTML =
306 SuperstructureState[this.superstructureStatus.state()];
307
308 this.intakeState.innerHTML =
309 IntakeState[this.superstructureStatus.intakeState()];
310
311 this.reseatingInCatapult.innerHTML =
312 this.superstructureStatus.reseatingInCatapult() ? 'true' : 'false';
313
314 this.flippersOpen.innerHTML =
315 this.superstructureStatus.flippersOpen() ? 'true' : 'false';
316
317 if (!this.superstructureStatus.catapult() ||
318 !this.superstructureStatus.catapult().zeroed()) {
319 this.setZeroing(this.catapult);
320 } else if (this.superstructureStatus.catapult().estopped()) {
321 this.setEstopped(this.catapult);
322 } else {
323 this.setTargetValue(
324 this.catapult,
325 this.superstructureStatus.catapult().unprofiledGoalPosition(),
326 this.superstructureStatus.catapult().estimatorState().position(),
327 1e-3);
328 }
329
330 if (!this.superstructureStatus.climber() ||
331 !this.superstructureStatus.climber().zeroed()) {
332 this.setZeroing(this.climber);
333 } else if (this.superstructureStatus.climber().estopped()) {
334 this.setEstopped(this.climber);
335 } else {
336 this.setTargetValue(
337 this.climber,
338 this.superstructureStatus.climber().unprofiledGoalPosition(),
339 this.superstructureStatus.climber().estimatorState().position(),
340 1e-3);
341 }
342
343
344
345 if (!this.superstructureStatus.turret() ||
346 !this.superstructureStatus.turret().zeroed()) {
347 this.setZeroing(this.turret);
348 } else if (this.superstructureStatus.turret().estopped()) {
349 this.setEstopped(this.turret);
350 } else {
351 this.setTargetValue(
352 this.turret,
353 this.superstructureStatus.turret().unprofiledGoalPosition(),
354 this.superstructureStatus.turret().estimatorState().position(),
355 1e-3);
356 }
357
358 if (!this.superstructureStatus.intakeBack() ||
359 !this.superstructureStatus.intakeBack().zeroed()) {
360 this.setZeroing(this.backIntake);
361 } else if (this.superstructureStatus.intakeBack().estopped()) {
362 this.setEstopped(this.backIntake);
363 } else {
364 this.setValue(
365 this.backIntake,
366 this.superstructureStatus.intakeBack().estimatorState().position());
367 }
368
369 if (!this.superstructureStatus.intakeFront() ||
370 !this.superstructureStatus.intakeFront().zeroed()) {
371 this.setZeroing(this.frontIntake);
372 } else if (this.superstructureStatus.intakeFront().estopped()) {
373 this.setEstopped(this.frontIntake);
374 } else {
375 this.setValue(
376 this.frontIntake,
377 this.superstructureStatus.intakeFront()
378 .estimatorState()
379 .position());
380 }
381 }
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800382
383 if (this.localizerOutput) {
384 if (!this.localizerOutput.zeroed()) {
385 this.setZeroing(this.x);
386 this.setZeroing(this.y);
387 this.setZeroing(this.theta);
388 } else {
389 this.setValue(this.x, this.localizerOutput.x());
390 this.setValue(this.y, this.localizerOutput.y());
391 this.setValue(this.theta, this.localizerOutput.theta());
392 }
393
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800394 this.drawRobot(
395 this.localizerOutput.x(), this.localizerOutput.y(),
396 this.localizerOutput.theta(),
397 this.superstructureStatus ?
398 this.superstructureStatus.turret().position() :
399 null);
400 }
401
James Kuszmaul1bd41f72022-04-03 13:18:16 -0700402 for (const [time, value] of this.localizerImageMatches) {
403 const age = now - time;
404 const kRemovalAge = 1.0;
405 if (age > kRemovalAge) {
406 this.localizerImageMatches.delete(time);
407 continue;
408 }
409 const kMaxImageAlpha = 0.5;
410 const ageAlpha = kMaxImageAlpha * (kRemovalAge - age) / kRemovalAge
411 for (let i = 0; i < value.targetsLength(); i++) {
412 const imageDebug = value.targets(i);
413 const x = imageDebug.impliedRobotX();
414 const y = imageDebug.impliedRobotY();
415 const theta = imageDebug.impliedRobotTheta();
416 const cameraX = imageDebug.cameraX();
417 const cameraY = imageDebug.cameraY();
418 const cameraTheta = imageDebug.cameraTheta();
419 const accepted = imageDebug.accepted();
420 // Make camera readings fade over time.
421 const alpha = Math.round(255 * ageAlpha).toString(16).padStart(2, '0');
422 const dashed = false;
423 const acceptedRgb = accepted ? '#00FF00' : '#FF0000';
424 const acceptedRgba = acceptedRgb + alpha;
425 const cameraRgb = PI_COLORS[imageDebug.camera()];
426 const cameraRgba = cameraRgb + alpha;
427 this.drawRobot(x, y, theta, null, acceptedRgba, dashed, false);
428 this.drawCamera(cameraX, cameraY, cameraTheta, cameraRgba, false);
429 }
430 }
431
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800432 window.requestAnimationFrame(() => this.draw());
433 }
434
435 reset(): void {
436 const ctx = this.canvas.getContext('2d');
437 ctx.setTransform(1, 0, 0, 1, 0, 0);
438 const size = window.innerHeight * 0.9;
439 ctx.canvas.height = size;
440 const width = size / 2 + 20;
441 ctx.canvas.width = width;
442 ctx.clearRect(0, 0, size, width);
443
444 // Translate to center of display.
445 ctx.translate(width / 2, size / 2);
446 // Coordinate system is:
447 // x -> forward.
448 // y -> to the left.
449 ctx.rotate(-Math.PI / 2);
450 ctx.scale(1, -1);
451
452 const M_TO_PX = (size - 10) / FIELD_LENGTH;
453 ctx.scale(M_TO_PX, M_TO_PX);
454 ctx.lineWidth = 1 / M_TO_PX;
455 }
456}