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