blob: 0f5a975df31eb2b7e9eeb68150b141ea51928ce5 [file] [log] [blame]
Maxwell Hendersonad312342023-01-10 12:07:47 -08001import {ByteBuffer} from 'flatbuffers';
2import {Connection} from '../../aos/network/www/proxy';
James Kuszmaulfb894572023-02-23 17:25:06 -08003import {LocalizerOutput} from '../../frc971/control_loops/drivetrain/localization/localizer_output_generated';
4import {RejectionReason} from '../localizer/status_generated';
Maxwell Hendersonad312342023-01-10 12:07:47 -08005import {Status as DrivetrainStatus} from '../../frc971/control_loops/drivetrain/drivetrain_status_generated';
James Kuszmaulfb894572023-02-23 17:25:06 -08006import {Visualization, TargetEstimateDebug} from '../localizer/visualization_generated';
Maxwell Hendersonad312342023-01-10 12:07:47 -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
James Kuszmaulfb894572023-02-23 17:25:06 -080014const ROBOT_WIDTH = 25 * IN_TO_M;
15const ROBOT_LENGTH = 32 * IN_TO_M;
Maxwell Hendersonad312342023-01-10 12:07:47 -080016
17const PI_COLORS = ['#ff00ff', '#ffff00', '#00ffff', '#ffa500'];
James Kuszmaulfb894572023-02-23 17:25:06 -080018const PIS = ['pi1', 'pi2', 'pi3', 'pi4'];
Maxwell Hendersonad312342023-01-10 12:07:47 -080019
20export class FieldHandler {
21 private canvas = document.createElement('canvas');
James Kuszmaulfb894572023-02-23 17:25:06 -080022 private localizerOutput: LocalizerOutput|null = null;
Maxwell Hendersonad312342023-01-10 12:07:47 -080023 private drivetrainStatus: DrivetrainStatus|null = null;
Maxwell Hendersonad312342023-01-10 12:07:47 -080024
25 // Image information indexed by timestamp (seconds since the epoch), so that
26 // we can stop displaying images after a certain amount of time.
James Kuszmaulfb894572023-02-23 17:25:06 -080027 private localizerImageMatches = new Map<number, Visualization>();
28 private x: HTMLElement = (document.getElementById('x') as HTMLElement);
Maxwell Hendersonad312342023-01-10 12:07:47 -080029 private y: HTMLElement = (document.getElementById('y') as HTMLElement);
30 private theta: HTMLElement =
31 (document.getElementById('theta') as HTMLElement);
Maxwell Hendersonad312342023-01-10 12:07:47 -080032 private imagesAcceptedCounter: HTMLElement =
33 (document.getElementById('images_accepted') as HTMLElement);
James Kuszmaulfb894572023-02-23 17:25:06 -080034 private rejectionReasonCells: HTMLElement[] = [];
Maxwell Hendersonad312342023-01-10 12:07:47 -080035 private fieldImage: HTMLImageElement = new Image();
36
37 constructor(private readonly connection: Connection) {
38 (document.getElementById('field') as HTMLElement).appendChild(this.canvas);
39
James Kuszmaulfb894572023-02-23 17:25:06 -080040 this.fieldImage.src = "2023.png";
41
42 for (const value in RejectionReason) {
43 // Typescript generates an iterator that produces both numbers and
44 // strings... don't do anything on the string iterations.
45 if (isNaN(Number(value))) {
46 continue;
47 }
48 const row = document.createElement('div');
49 const nameCell = document.createElement('div');
50 nameCell.innerHTML = RejectionReason[value];
51 row.appendChild(nameCell);
52 const valueCell = document.createElement('div');
53 valueCell.innerHTML = 'NA';
54 this.rejectionReasonCells.push(valueCell);
55 row.appendChild(valueCell);
56 document.getElementById('vision_readouts').appendChild(row);
57 }
Maxwell Hendersonad312342023-01-10 12:07:47 -080058
59 for (let ii = 0; ii < PI_COLORS.length; ++ii) {
60 const legendEntry = document.createElement('div');
61 legendEntry.style.color = PI_COLORS[ii];
62 legendEntry.innerHTML = 'PI' + (ii + 1).toString()
63 document.getElementById('legend').appendChild(legendEntry);
64 }
65
66 this.connection.addConfigHandler(() => {
67 // Visualization message is reliable so that we can see *all* the vision
68 // matches.
James Kuszmaulfb894572023-02-23 17:25:06 -080069 for (const pi in PIS) {
70 this.connection.addReliableHandler(
71 '/' + PIS[pi] + '/camera', "y2023.localizer.Visualization",
72 (data) => {
73 this.handleLocalizerDebug(pi, data);
74 });
75 }
Maxwell Hendersonad312342023-01-10 12:07:47 -080076 this.connection.addHandler(
77 '/drivetrain', "frc971.control_loops.drivetrain.Status", (data) => {
78 this.handleDrivetrainStatus(data);
79 });
80 this.connection.addHandler(
James Kuszmaulfb894572023-02-23 17:25:06 -080081 '/localizer', "frc971.controls.LocalizerOutput", (data) => {
82 this.handleLocalizerOutput(data);
Maxwell Hendersonad312342023-01-10 12:07:47 -080083 });
84 });
85 }
86
James Kuszmaulfb894572023-02-23 17:25:06 -080087 private handleLocalizerDebug(pi: string, data: Uint8Array): void {
88 const now = Date.now() / 1000.0;
89
90 const fbBuffer = new ByteBuffer(data);
91 this.localizerImageMatches.set(
92 now, Visualization.getRootAsVisualization(fbBuffer));
93
94 const debug = this.localizerImageMatches.get(now);
95
96 if (debug.statistics()) {
97 if (debug.statistics().rejectionReasonsLength() ==
98 this.rejectionReasonCells.length) {
99 for (let ii = 0; ii < debug.statistics().rejectionReasonsLength();
100 ++ii) {
101 this.rejectionReasonCells[ii].innerHTML =
102 debug.statistics().rejectionReasons(ii).count().toString();
103 }
104 } else {
105 console.error('Unexpected number of rejection reasons in counter.');
106 }
107 }
108 }
109
110 private handleLocalizerOutput(data: Uint8Array): void {
111 const fbBuffer = new ByteBuffer(data);
112 this.localizerOutput = LocalizerOutput.getRootAsLocalizerOutput(fbBuffer);
113 }
114
Maxwell Hendersonad312342023-01-10 12:07:47 -0800115 private handleDrivetrainStatus(data: Uint8Array): void {
116 const fbBuffer = new ByteBuffer(data);
117 this.drivetrainStatus = DrivetrainStatus.getRootAsStatus(fbBuffer);
118 }
119
Maxwell Hendersonad312342023-01-10 12:07:47 -0800120 drawField(): void {
121 const ctx = this.canvas.getContext('2d');
122 ctx.save();
James Kuszmaulfb894572023-02-23 17:25:06 -0800123 ctx.scale(1.0, -1.0);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800124 ctx.drawImage(
125 this.fieldImage, 0, 0, this.fieldImage.width, this.fieldImage.height,
126 -FIELD_EDGE_X, -FIELD_SIDE_Y, FIELD_LENGTH, FIELD_WIDTH);
127 ctx.restore();
128 }
129
130 drawCamera(
James Kuszmaulfb894572023-02-23 17:25:06 -0800131 x: number, y: number, theta: number, color: string = 'blue'): void {
Maxwell Hendersonad312342023-01-10 12:07:47 -0800132 const ctx = this.canvas.getContext('2d');
133 ctx.save();
134 ctx.translate(x, y);
135 ctx.rotate(theta);
136 ctx.strokeStyle = color;
137 ctx.beginPath();
138 ctx.moveTo(0.5, 0.5);
139 ctx.lineTo(0, 0);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800140 ctx.lineTo(0.5, -0.5);
141 ctx.stroke();
142 ctx.beginPath();
143 ctx.arc(0, 0, 0.25, -Math.PI / 4, Math.PI / 4);
144 ctx.stroke();
145 ctx.restore();
146 }
147
148 drawRobot(
James Kuszmaulfb894572023-02-23 17:25:06 -0800149 x: number, y: number, theta: number,
150 color: string = 'blue', dashed: boolean = false): void {
Maxwell Hendersonad312342023-01-10 12:07:47 -0800151 const ctx = this.canvas.getContext('2d');
152 ctx.save();
153 ctx.translate(x, y);
154 ctx.rotate(theta);
155 ctx.strokeStyle = color;
156 ctx.lineWidth = ROBOT_WIDTH / 10.0;
157 if (dashed) {
158 ctx.setLineDash([0.05, 0.05]);
159 } else {
160 // Empty array = solid line.
161 ctx.setLineDash([]);
162 }
163 ctx.rect(-ROBOT_LENGTH / 2, -ROBOT_WIDTH / 2, ROBOT_LENGTH, ROBOT_WIDTH);
164 ctx.stroke();
165
166 // Draw line indicating which direction is forwards on the robot.
167 ctx.beginPath();
168 ctx.moveTo(0, 0);
James Kuszmaulfb894572023-02-23 17:25:06 -0800169 ctx.lineTo(ROBOT_LENGTH / 2.0, 0);
Maxwell Hendersonad312342023-01-10 12:07:47 -0800170 ctx.stroke();
171
172 ctx.restore();
173 }
174
175 setZeroing(div: HTMLElement): void {
176 div.innerHTML = 'zeroing';
177 div.classList.remove('faulted');
178 div.classList.add('zeroing');
179 div.classList.remove('near');
180 }
181
Maxwell Hendersonad312342023-01-10 12:07:47 -0800182 setValue(div: HTMLElement, val: number): void {
183 div.innerHTML = val.toFixed(4);
184 div.classList.remove('faulted');
185 div.classList.remove('zeroing');
186 div.classList.remove('near');
187 }
188
189 draw(): void {
190 this.reset();
191 this.drawField();
192
193 // Draw the matches with debugging information from the localizer.
194 const now = Date.now() / 1000.0;
James Kuszmaulfb894572023-02-23 17:25:06 -0800195
Maxwell Hendersonad312342023-01-10 12:07:47 -0800196 if (this.drivetrainStatus && this.drivetrainStatus.trajectoryLogging()) {
197 this.drawRobot(
198 this.drivetrainStatus.trajectoryLogging().x(),
199 this.drivetrainStatus.trajectoryLogging().y(),
James Kuszmaulfb894572023-02-23 17:25:06 -0800200 this.drivetrainStatus.trajectoryLogging().theta(), "#000000FF",
Maxwell Hendersonad312342023-01-10 12:07:47 -0800201 false);
202 }
203
James Kuszmaulfb894572023-02-23 17:25:06 -0800204 if (this.localizerOutput) {
205 if (!this.localizerOutput.zeroed()) {
206 this.setZeroing(this.x);
207 this.setZeroing(this.y);
208 this.setZeroing(this.theta);
209 } else {
210 this.setValue(this.x, this.localizerOutput.x());
211 this.setValue(this.y, this.localizerOutput.y());
212 this.setValue(this.theta, this.localizerOutput.theta());
213 }
214
215 this.drawRobot(
216 this.localizerOutput.x(), this.localizerOutput.y(),
217 this.localizerOutput.theta());
218
219 this.imagesAcceptedCounter.innerHTML =
220 this.localizerOutput.imageAcceptedCount().toString();
221 }
222
223 for (const [time, value] of this.localizerImageMatches) {
224 const age = now - time;
225 const kRemovalAge = 1.0;
226 if (age > kRemovalAge) {
227 this.localizerImageMatches.delete(time);
228 continue;
229 }
230 const kMaxImageAlpha = 0.5;
231 const ageAlpha = kMaxImageAlpha * (kRemovalAge - age) / kRemovalAge
232 for (let i = 0; i < value.targetsLength(); i++) {
233 const imageDebug = value.targets(i);
234 const x = imageDebug.impliedRobotX();
235 const y = imageDebug.impliedRobotY();
236 const theta = imageDebug.impliedRobotTheta();
237 const cameraX = imageDebug.cameraX();
238 const cameraY = imageDebug.cameraY();
239 const cameraTheta = imageDebug.cameraTheta();
240 const accepted = imageDebug.accepted();
241 // Make camera readings fade over time.
242 const alpha = Math.round(255 * ageAlpha).toString(16).padStart(2, '0');
243 const dashed = false;
244 const acceptedRgb = accepted ? '#00FF00' : '#FF0000';
245 const acceptedRgba = acceptedRgb + alpha;
246 const cameraRgb = PI_COLORS[imageDebug.camera()];
247 const cameraRgba = cameraRgb + alpha;
248 this.drawRobot(x, y, theta, acceptedRgba, dashed);
249 this.drawCamera(cameraX, cameraY, cameraTheta, cameraRgba);
250 }
251 }
252
Maxwell Hendersonad312342023-01-10 12:07:47 -0800253 window.requestAnimationFrame(() => this.draw());
254 }
255
256 reset(): void {
257 const ctx = this.canvas.getContext('2d');
258 ctx.setTransform(1, 0, 0, 1, 0, 0);
259 const size = window.innerHeight * 0.9;
260 ctx.canvas.height = size;
261 const width = size / 2 + 20;
262 ctx.canvas.width = width;
263 ctx.clearRect(0, 0, size, width);
264
265 // Translate to center of display.
266 ctx.translate(width / 2, size / 2);
267 // Coordinate system is:
268 // x -> forward.
269 // y -> to the left.
270 ctx.rotate(-Math.PI / 2);
271 ctx.scale(1, -1);
272
273 const M_TO_PX = (size - 10) / FIELD_LENGTH;
274 ctx.scale(M_TO_PX, M_TO_PX);
275 ctx.lineWidth = 1 / M_TO_PX;
276 }
277}