blob: 22989bef90ef86b9e3c9817b352f554c3b41f5a9 [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');
164 ctx.drawImage(
165 this.fieldImage, 0, 0, this.fieldImage.width, this.fieldImage.height,
166 -FIELD_EDGE_X, -FIELD_SIDE_Y, FIELD_LENGTH, FIELD_WIDTH);
167 }
168
169 drawCamera(
170 x: number, y: number, theta: number, color: string = 'blue',
171 extendLines: boolean = true): void {
172 const ctx = this.canvas.getContext('2d');
173 ctx.save();
174 ctx.translate(x, y);
175 ctx.rotate(theta);
176 ctx.strokeStyle = color;
177 ctx.beginPath();
178 ctx.moveTo(0.5, 0.5);
179 ctx.lineTo(0, 0);
180 if (extendLines) {
181 ctx.lineTo(100.0, 0);
182 ctx.lineTo(0, 0);
183 }
184 ctx.lineTo(0.5, -0.5);
185 ctx.stroke();
186 ctx.beginPath();
187 ctx.arc(0, 0, 0.25, -Math.PI / 4, Math.PI / 4);
188 ctx.stroke();
189 ctx.restore();
190 }
191
192 drawRobot(
193 x: number, y: number, theta: number, turret: number|null,
194 color: string = 'blue', dashed: boolean = false,
195 extendLines: boolean = true): void {
196 const ctx = this.canvas.getContext('2d');
197 ctx.save();
198 ctx.translate(x, y);
199 ctx.rotate(theta);
200 ctx.strokeStyle = color;
201 ctx.lineWidth = ROBOT_WIDTH / 10.0;
202 if (dashed) {
203 ctx.setLineDash([0.05, 0.05]);
204 } else {
205 // Empty array = solid line.
206 ctx.setLineDash([]);
207 }
208 ctx.rect(-ROBOT_LENGTH / 2, -ROBOT_WIDTH / 2, ROBOT_LENGTH, ROBOT_WIDTH);
209 ctx.stroke();
210
211 // Draw line indicating which direction is forwards on the robot.
212 ctx.beginPath();
213 ctx.moveTo(0, 0);
214 if (extendLines) {
215 ctx.lineTo(1000.0, 0);
216 } else {
217 ctx.lineTo(ROBOT_LENGTH / 2.0, 0);
218 }
219 ctx.stroke();
220
221 if (turret !== null) {
222 ctx.save();
223 ctx.rotate(turret);
224 const turretRadius = ROBOT_WIDTH / 3.0;
225 ctx.strokeStyle = 'red';
226 // Draw circle for turret.
227 ctx.beginPath();
228 ctx.arc(0, 0, turretRadius, 0, 2.0 * Math.PI);
229 ctx.stroke();
230 // Draw line in circle to show forwards.
231 ctx.beginPath();
232 ctx.moveTo(0, 0);
233 if (extendLines) {
234 ctx.lineTo(1000.0, 0);
235 } else {
236 ctx.lineTo(turretRadius, 0);
237 }
238 ctx.stroke();
239 ctx.restore();
240 }
241 ctx.restore();
242 }
243
244 setZeroing(div: HTMLElement): void {
245 div.innerHTML = 'zeroing';
246 div.classList.remove('faulted');
247 div.classList.add('zeroing');
248 div.classList.remove('near');
249 }
250
251 setEstopped(div: HTMLElement): void {
252 div.innerHTML = 'estopped';
253 div.classList.add('faulted');
254 div.classList.remove('zeroing');
255 div.classList.remove('near');
256 }
257
258 setTargetValue(
259 div: HTMLElement, target: number, val: number, tolerance: number): void {
260 div.innerHTML = val.toFixed(4);
261 div.classList.remove('faulted');
262 div.classList.remove('zeroing');
263 if (Math.abs(target - val) < tolerance) {
264 div.classList.add('near');
265 } else {
266 div.classList.remove('near');
267 }
268 }
269
270 setValue(div: HTMLElement, val: number): void {
271 div.innerHTML = val.toFixed(4);
272 div.classList.remove('faulted');
273 div.classList.remove('zeroing');
274 div.classList.remove('near');
275 }
276
277 draw(): void {
278 this.reset();
279 this.drawField();
280
281 // Draw the matches with debugging information from the localizer.
282 const now = Date.now() / 1000.0;
James Kuszmaula0871872022-03-05 22:12:39 -0800283 if (this.superstructureStatus) {
284 this.shotDistance.innerHTML = this.superstructureStatus.aimer() ?
Austin Schuh0a732cd2022-03-29 21:19:59 -0700285 (this.superstructureStatus.aimer().shotDistance() /
286 0.0254).toFixed(2) +
287 'in, ' +
288 this.superstructureStatus.aimer().shotDistance().toFixed(2) +
289 'm' :
James Kuszmaula0871872022-03-05 22:12:39 -0800290 'NA';
291
292 this.fire.innerHTML = this.superstructureStatus.fire() ? 'true' : 'false';
293
Austin Schuh41472552022-03-13 18:09:41 -0700294 this.mpcHorizon.innerHTML =
295 this.superstructureStatus.mpcHorizon().toFixed(2);
James Kuszmaula0871872022-03-05 22:12:39 -0800296
297 this.setValue(this.mpcSolveTime, this.superstructureStatus.solveTime());
298
299 this.shotCount.innerHTML =
300 this.superstructureStatus.shotCount().toFixed(0);
301
302 this.superstructureState.innerHTML =
303 SuperstructureState[this.superstructureStatus.state()];
304
305 this.intakeState.innerHTML =
306 IntakeState[this.superstructureStatus.intakeState()];
307
308 this.reseatingInCatapult.innerHTML =
309 this.superstructureStatus.reseatingInCatapult() ? 'true' : 'false';
310
311 this.flippersOpen.innerHTML =
312 this.superstructureStatus.flippersOpen() ? 'true' : 'false';
313
314 if (!this.superstructureStatus.catapult() ||
315 !this.superstructureStatus.catapult().zeroed()) {
316 this.setZeroing(this.catapult);
317 } else if (this.superstructureStatus.catapult().estopped()) {
318 this.setEstopped(this.catapult);
319 } else {
320 this.setTargetValue(
321 this.catapult,
322 this.superstructureStatus.catapult().unprofiledGoalPosition(),
323 this.superstructureStatus.catapult().estimatorState().position(),
324 1e-3);
325 }
326
327 if (!this.superstructureStatus.climber() ||
328 !this.superstructureStatus.climber().zeroed()) {
329 this.setZeroing(this.climber);
330 } else if (this.superstructureStatus.climber().estopped()) {
331 this.setEstopped(this.climber);
332 } else {
333 this.setTargetValue(
334 this.climber,
335 this.superstructureStatus.climber().unprofiledGoalPosition(),
336 this.superstructureStatus.climber().estimatorState().position(),
337 1e-3);
338 }
339
340
341
342 if (!this.superstructureStatus.turret() ||
343 !this.superstructureStatus.turret().zeroed()) {
344 this.setZeroing(this.turret);
345 } else if (this.superstructureStatus.turret().estopped()) {
346 this.setEstopped(this.turret);
347 } else {
348 this.setTargetValue(
349 this.turret,
350 this.superstructureStatus.turret().unprofiledGoalPosition(),
351 this.superstructureStatus.turret().estimatorState().position(),
352 1e-3);
353 }
354
355 if (!this.superstructureStatus.intakeBack() ||
356 !this.superstructureStatus.intakeBack().zeroed()) {
357 this.setZeroing(this.backIntake);
358 } else if (this.superstructureStatus.intakeBack().estopped()) {
359 this.setEstopped(this.backIntake);
360 } else {
361 this.setValue(
362 this.backIntake,
363 this.superstructureStatus.intakeBack().estimatorState().position());
364 }
365
366 if (!this.superstructureStatus.intakeFront() ||
367 !this.superstructureStatus.intakeFront().zeroed()) {
368 this.setZeroing(this.frontIntake);
369 } else if (this.superstructureStatus.intakeFront().estopped()) {
370 this.setEstopped(this.frontIntake);
371 } else {
372 this.setValue(
373 this.frontIntake,
374 this.superstructureStatus.intakeFront()
375 .estimatorState()
376 .position());
377 }
378 }
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800379
380 if (this.localizerOutput) {
381 if (!this.localizerOutput.zeroed()) {
382 this.setZeroing(this.x);
383 this.setZeroing(this.y);
384 this.setZeroing(this.theta);
385 } else {
386 this.setValue(this.x, this.localizerOutput.x());
387 this.setValue(this.y, this.localizerOutput.y());
388 this.setValue(this.theta, this.localizerOutput.theta());
389 }
390
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800391 this.drawRobot(
392 this.localizerOutput.x(), this.localizerOutput.y(),
393 this.localizerOutput.theta(),
394 this.superstructureStatus ?
395 this.superstructureStatus.turret().position() :
396 null);
397 }
398
James Kuszmaul1bd41f72022-04-03 13:18:16 -0700399 for (const [time, value] of this.localizerImageMatches) {
400 const age = now - time;
401 const kRemovalAge = 1.0;
402 if (age > kRemovalAge) {
403 this.localizerImageMatches.delete(time);
404 continue;
405 }
406 const kMaxImageAlpha = 0.5;
407 const ageAlpha = kMaxImageAlpha * (kRemovalAge - age) / kRemovalAge
408 for (let i = 0; i < value.targetsLength(); i++) {
409 const imageDebug = value.targets(i);
410 const x = imageDebug.impliedRobotX();
411 const y = imageDebug.impliedRobotY();
412 const theta = imageDebug.impliedRobotTheta();
413 const cameraX = imageDebug.cameraX();
414 const cameraY = imageDebug.cameraY();
415 const cameraTheta = imageDebug.cameraTheta();
416 const accepted = imageDebug.accepted();
417 // Make camera readings fade over time.
418 const alpha = Math.round(255 * ageAlpha).toString(16).padStart(2, '0');
419 const dashed = false;
420 const acceptedRgb = accepted ? '#00FF00' : '#FF0000';
421 const acceptedRgba = acceptedRgb + alpha;
422 const cameraRgb = PI_COLORS[imageDebug.camera()];
423 const cameraRgba = cameraRgb + alpha;
424 this.drawRobot(x, y, theta, null, acceptedRgba, dashed, false);
425 this.drawCamera(cameraX, cameraY, cameraTheta, cameraRgba, false);
426 }
427 }
428
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800429 window.requestAnimationFrame(() => this.draw());
430 }
431
432 reset(): void {
433 const ctx = this.canvas.getContext('2d');
434 ctx.setTransform(1, 0, 0, 1, 0, 0);
435 const size = window.innerHeight * 0.9;
436 ctx.canvas.height = size;
437 const width = size / 2 + 20;
438 ctx.canvas.width = width;
439 ctx.clearRect(0, 0, size, width);
440
441 // Translate to center of display.
442 ctx.translate(width / 2, size / 2);
443 // Coordinate system is:
444 // x -> forward.
445 // y -> to the left.
446 ctx.rotate(-Math.PI / 2);
447 ctx.scale(1, -1);
448
449 const M_TO_PX = (size - 10) / FIELD_LENGTH;
450 ctx.scale(M_TO_PX, M_TO_PX);
451 ctx.lineWidth = 1 / M_TO_PX;
452 }
453}