Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use d3 #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
708 changes: 708 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@types/node": "^16.11.43",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"d3": "^7.6.1",
"knex": "^2.2.0",
"moment": "^2.29.4",
"next": "^12.2.3",
Expand Down
8 changes: 5 additions & 3 deletions src/components/Stats/RaceSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ interface RaceSummaryProps {
}[];
}

const RaceSummary = ({ startingGrid, time, tires }: RaceSummaryProps) => {
export const RaceSummary = ({
startingGrid,
time,
tires,
}: RaceSummaryProps) => {
return (
<div className="flex flex-col gap-10">
<div className="grid grid-cols-2 gap-4 grid-flow-row">
Expand All @@ -33,5 +37,3 @@ const RaceSummary = ({ startingGrid, time, tires }: RaceSummaryProps) => {
</div>
);
};

export default RaceSummary;
4 changes: 1 addition & 3 deletions src/components/Stats/Slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface SliderProps {
totalParticipants: number;
}

const Slider = (props: SliderProps) => {
export const Slider = (props: SliderProps) => {
const rankPercent =
((props.totalParticipants - props.rank) / (props.totalParticipants - 1)) *
100;
Expand Down Expand Up @@ -62,5 +62,3 @@ const Slider = (props: SliderProps) => {
</div>
);
};

export default Slider;
4 changes: 1 addition & 3 deletions src/components/Stats/ThreeBars.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ interface ThreeBarsProps {
leader: Driver;
}

const ThreeBars = ({
export const ThreeBars = ({
title,
driver1,
driver2,
Expand Down Expand Up @@ -88,5 +88,3 @@ const ThreeBars = ({
</div>
);
};

export default ThreeBars;
4 changes: 1 addition & 3 deletions src/components/Stats/Tire.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const compoundMap = {
},
};

const Tire = ({ compound, laps }: TireProps) => {
export const Tire = ({ compound, laps }: TireProps) => {
const altSrc = compoundMap[compound];

return (
Expand All @@ -32,5 +32,3 @@ const Tire = ({ compound, laps }: TireProps) => {
</div>
);
};

export default Tire;
6 changes: 3 additions & 3 deletions src/components/Stats/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Slider from "./Slider";
import RaceSummary from "./RaceSummary";
import ThreeBars from "./ThreeBars";
import { Slider } from "./Slider";
import { RaceSummary } from "./RaceSummary";
import { ThreeBars } from "./ThreeBars";
import { TrackMap } from "./TrackMap";
import { CornerAnalysis } from "./CornerAnalysis";

Expand Down
99 changes: 99 additions & 0 deletions src/components/_experimental/CornerAnalysis.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import * as d3 from "d3";
import React, { useRef, useEffect, useMemo } from "react";
import { useRefDimensions } from "libs/react/dimensions";
import type { DriverData, Telemetry } from "libs/types";

interface CornerAnalysisProps {
turnNumber: number;
driverData: DriverData[];
distanceFrom: number;
distanceTo: number;
}

export const CornerAnalysis = (props: CornerAnalysisProps) => {
const ref = useRef(null);
const dimensions = useRefDimensions(ref);
const svgRef = useRef(null);
const allDriverData: DriverTelemetry[] = props.driverData
.map((d) => {
return d.data.map((tel) => {
return {
...tel,
Code: d.driverCode,
Color: d.driverColor,
};
});
})
.flat();

const [mx, my] = [14, 14];

// x scale bounds
const distanceScale = useMemo(() => {
const [xMin, xMax] = [props.distanceFrom, props.distanceTo];
return d3
.scaleLinear()
.domain([xMin ?? 0, xMax ?? 0])
.range([mx, dimensions.width - mx]);
}, [allDriverData, dimensions.width, mx]);

// y scale bounds
const speedScale = useMemo(() => {
const [yMin, yMax] = d3.extent(allDriverData, (d) => d.Speed);
return d3
.scaleLinear()
.domain([yMin ?? 0, yMax ?? 0])
.range([dimensions.height - my, my]);
}, [allDriverData, dimensions.height, my]);

// draw
useEffect(() => {
if (!distanceScale || !speedScale) {
return;
}

d3.select(svgRef.current).selectAll("*").remove();
drawSpeedGraph(allDriverData);
}, [props, distanceScale, speedScale]);

const drawSpeedGraph = () => {
const color = d3
.scaleOrdinal()
.domain(props.driverData.map((d) => d.driverCode))
.range(props.driverData.map((d) => d.driverColor));

const g = d3
.select(svgRef.current)
.selectAll(`.speed-graph`)
.data<DriverData>(props.driverData)
.enter()
.append("g")
.attr("class", "speed-graph");

g.append("path")
.attr("d", (d) => {
return d3
.line<Telemetry>()
.x((d) => {
return distanceScale(d.Distance);
})
.y((d) => speedScale(d.Speed))(d.data);
})
.attr("fill", "none")
.attr("stroke-width", 2)
.attr("stroke", (d) => color(d.driverCode));
};

return (
<div className="w-full h-full">
<div className="bg-oldLavender">
<p className="text-3xl px-5 py-2 mb-5 tracking-wider">
Corner Analysis - Turn {props.turnNumber} 🏎️ 🏎️ 🏎️
</p>
</div>
<div ref={ref} className="h-full w-full">
<svg width="100%" height="100%" ref={svgRef}></svg>
</div>
</div>
);
};
210 changes: 210 additions & 0 deletions src/components/_experimental/TrackMap.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import * as d3 from "d3";
import React, { useRef, useEffect, useState, useMemo } from "react";
import { useRefDimensions } from "libs/react/dimensions";
import type { TrackData, DriverData, Telemetry } from "libs/types";

type DriverTelemetry = Partial<Telemetry> & {
Code?: string;
X: number;
Y: number;
};

const pickTelemetryAtDistance = (
distance: number,
data: Telemetry[]
): Telemetry | undefined => {
for (let i = 1; i < data.length; i++) {
if (data[i].Distance >= distance) {
// TODO: need to interpolate distance...?
return data[i];
}
}
};

const pickFastest = (drivers: DriverData[]): DriverTelemetry[] => {
const tel: DriverTelemetry[] = [];
const fastest = drivers[0].data.forEach((d) => {
const { Speed: speed, Distance: distance } = d;
// TODO: support more than 2 drivers?
const telOtherDriver = pickTelemetryAtDistance(distance, drivers[1].data);
const row: DriverTelemetry = {
X: d.X,
Y: d.Y,
};

if (telOtherDriver === undefined) {
tel.push(row);
return;
}

if (speed > telOtherDriver.Speed) {
tel.push({
Code: drivers[0].driverCode,
...d,
});
} else if (telOtherDriver.Speed > speed) {
tel.push({
Code: drivers[1].driverCode,
...telOtherDriver,
...row,
});
} else {
tel.push(row);
}
});
return tel;
};

interface TrackMapProps {
color: string;
driverData: DriverData[];
telemetryOverlay?: "none" | "fastest";
}

export const TrackMap = (props: TrackMapProps) => {
const ref = useRef(null);
const dimensions = useRefDimensions(ref);
const svgRef = useRef(null);
const map = props.driverData[0].data;

const [mx, my] = [14, 14];

// x scale bounds
const xScale = useMemo(() => {
const [xMin, xMax] = d3.extent(map, (m) => {
return m.X;
});
return d3
.scaleLinear()
.domain([xMin ?? 0, xMax ?? 0])
.range([mx, dimensions.width - mx]);
}, [map, dimensions.width, mx]);

// y scale bounds
const yScale = useMemo(() => {
const [yMin, yMax] = d3.extent(map, (m) => m.Y);
return d3
.scaleLinear()
.domain([yMin ?? 0, yMax ?? 0])
.range([dimensions.height - my, my]);
}, [map, dimensions.height, my]);

// draw when scales have changed
useEffect(() => {
if (!xScale || !yScale) {
return;
}

d3.select(svgRef.current).selectAll("*").remove();
drawMap(map);

if (props.telemetryOverlay === "fastest") {
drawFastestOverlay(props.driverData);
}
}, [props, xScale, yScale]);

// draw track map
const drawMap = (map: TrackData[]) => {
const g = d3
.select(svgRef.current)
.selectAll(".track-map")
.data<TrackData[]>([map])
.enter()
.append("g")
.attr("class", "track-map");

g.append("path")
.attr(
"d",
d3
.line<TrackData>()
.x((d) => xScale(d.X))
.y((d) => yScale(d.Y))
)
.attr("fill", "none")
.attr("stroke", props.color)
.attr("shape-rendering", "gerometricPrecision")
.attr("stroke-width", 12)
.exit()
.remove();
};

const drawFastestOverlay = (drivers: DriverData[]) => {
const fastest = pickFastest(drivers);

drivers.forEach((driver, driverIdx) => {
const data = fastest.map((d) =>
d.Code === driver.driverCode ? d : null
);

const terminated: DriverTelemetry[][] = [[]];
let idx = 0;
let prevNull = true;
data.forEach((d) => {
if (d === null) {
if (!prevNull) {
idx++;
}
prevNull = true;
return;
}
if (terminated.length === idx) {
terminated.push([]);
}
prevNull = false;
terminated[idx].push(d);
});

const g = d3
.select(svgRef.current)
.selectAll(`.fastest-overlay-${driver.driverCode}`)
.data<DriverTelemetry[]>(terminated)
.enter()
.append("g")
.attr("class", `fastest-overlay-${driver.driverCode}`);

g.append("path")
.attr(
"d",
d3
.line<DriverTelemetry>()
.x((d) => xScale(d.X))
.y((d) => yScale(d.Y))
)
.attr("fill", "none")
.attr("stroke", driver.driverColor)
.attr("stroke-width", 8)
.attr("shape-rendering", "geometricPrecision");

const legend = d3.select(svgRef.current);
const margin = 22;
const radius = 6;
const x = mx;
const y = dimensions.height - my - driverIdx * margin;
legend
.append("circle")
.attr("cx", x)
.attr("cy", y - 5)
.attr("r", radius)
.attr("shape-rendering", "geometricPrecision")
.style("fill", driver.driverColor);
legend
.append("text")
.attr("x", x + radius + 10)
.attr("y", y)
.style("fill", driver.driverColor)
.text(`${driver.driverCode} is faster`)
.style("alignment-baseline", "middle");
});
};

return (
<div ref={ref} className="h-full w-full">
<svg width="100%" height="100%" ref={svgRef}></svg>
</div>
);
};

TrackMap.defaultProps = {
telemetryOverlay: "none",
};
Loading