Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | 37x 69x 69x 69x 23x 23x 37x 37x 72x 66x 24x 24x 42x 42x 3x 3x 3x 3x 3x 3x 30x 30x 30x 30x 30x 1x 1x 1x 47x 47x 47x 47x 46x 46x 46x 46x 46x 46x 46x 47x 46x 46x 46x 46x 47x 1x 1x 47x 1x 1x 23x 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 5x 5x 5x 5x 23x 23x 23x 23x 16x 16x 1x 16x 1x 16x 16x 16x 16x 1x 1x 16x 1x 1x 1x 1x 1x 16x 2x 2x 2x 2x 178x 30x 30x 1x 1x 1x 1x 1x 11x 11x 1x 1x 1x 1x 1x 47x 47x 47x 23x 23x 23x 16x 16x 16x 48x 48x 48x 1x 1x 1x 2x 2x 2x 37x | import type {
SmartCubeCubieState,
SmartCubeEvent,
} from '@wstein/regrip-core/bindings/smartCubeTransport';
import * as GyroOrientation from '@wstein/regrip-core/domain/GyroOrientation';
import * as PlayerSync from '@wstein/regrip-core/domain/PlayerSync';
import * as CubeFacelets from '@wstein/regrip-core/domain/CubeFacelets';
import * as Quaternion from '@wstein/regrip-core/domain/Quaternion';
import { formatOfflineStats, formatSingmasterCycles } from './cubeInfo';
import type {
CustomTriggerEvent,
MoveGapEvent,
SessionGyroEvent,
ShakeTriggerEvent,
SmartCubeSessionEvent,
VirtualRegripEvent,
} from '@wstein/regrip-core/session/smartCubeSession';
import type { regripToken as RegripToken } from '@wstein/regrip-core/domain/CubeNotation';
export type ScrambleSolver = (facelets: string) => Promise<string>;
export type SolveDetector = (facelets: string) => boolean;
export const defaultSolveDetector: SolveDetector = CubeFacelets.isSolvedFacelets;
function cubieStateFromPattern(pattern: CubeFacelets.patternData): SmartCubeCubieState {
const decoded = CubeFacelets.faceletsToKociembaState(
CubeFacelets.patternDataToFaceletsExn(pattern),
);
if (decoded.TAG !== 'Ok') throw new Error(decoded._0);
return decoded._0;
}
function patternFromFacelets(facelets: string): CubeFacelets.patternData | undefined {
const decoded = CubeFacelets.decodeFacelets(facelets);
return decoded.TAG === 'Ok' ? decoded._0 : undefined;
}
type CubeEventControllerOptions = {
homeOrientation?: Quaternion.t;
solveScramble: ScrambleSolver;
/** Adapter-owned body-frame permutation reconciliation for the 3D player. */
shouldReconcilePlayer?: (facelets: string) => Promise<boolean>;
trackPlayerMove?: (move: string) => void;
resetPlayerTracking?: () => void;
invalidatePlayerTracking?: () => void;
/** Translate a protocol-body move into the displayed solver frame. */
projectMove?: (move: string) => string;
/** Always records detected notation, including while the 3D player is untrusted. */
recordMove?: (move: string, rawMove?: string) => void;
/** Translate a detected body-frame regrip before applying it to the solver frame. */
projectRegrip?: (token: RegripToken) => string;
applyRegrip?: (token: RegripToken) => void;
onRegrip?: (event: VirtualRegripEvent, solverToken: string) => void;
onCustomTrigger?: (event: CustomTriggerEvent, solverMove: string) => void;
onShake?: (event: ShakeTriggerEvent) => void;
onMoveGap?: (event: MoveGapEvent) => void;
/** Raw transport events suitable for capture before their UI effects are applied. */
onProtocolEvent?: (event: NonGyroSmartCubeEvent) => void;
addMove: (move: string) => void;
setOrientation: (quaternion: { x: number; y: number; z: number; w: number }) => void;
setPlayerAlgorithm: (algorithm: string) => void;
setInfo: (id: string, value: string) => void;
showInfo: (id: string) => void;
onDisconnect: () => void;
onSolved?: () => void;
onGyro?: (sample: { event: SessionGyroEvent }) => void;
onHardware?: (event: Extract<SmartCubeEvent, { type: 'HARDWARE' }>) => void;
/** Canonical URFDLB body-frame state; virtual regrips never alter copy/export data. */
onFacelets?: (source: { facelets: string; state?: SmartCubeCubieState }) => void;
solveDetector?: SolveDetector;
onUnknownEvent?: (event: unknown) => void;
};
type NonGyroSmartCubeEvent = Exclude<SmartCubeEvent, { type: 'GYRO' }>;
export function createCubeEventController(options: CubeEventControllerOptions) {
let playerSyncState = PlayerSync.initial;
let playerUntrusted = false;
// Copy/export state is always normalized to the protocol's canonical URFDLB
// frame, matching the body-frame 3D player and incoming FACELETS snapshots.
let normalizedPattern: CubeFacelets.patternData | undefined;
function applyPlayerEffects(effects: PlayerSync.effect[]): void {
for (const effect of effects) {
switch (effect.kind) {
case 'setAlgorithm':
options.setPlayerAlgorithm(effect.algorithm);
break;
case 'addMove':
options.addMove(effect.move);
break;
}
}
}
function reset(): void {
const [nextState, effects] = PlayerSync.reset(playerSyncState);
playerSyncState = nextState;
playerUntrusted = false;
normalizedPattern = undefined;
options.resetPlayerTracking?.();
applyPlayerEffects(effects);
}
function handleGyro(event: SessionGyroEvent): void {
const { x, y, z, w } = event.quaternion;
options.setOrientation(
Quaternion.multiply(options.homeOrientation ?? GyroOrientation.home, event.stabilized),
);
options.onGyro?.({ event });
options.setInfo(
'quaternion',
`x: ${x.toFixed(3)}, y: ${y.toFixed(3)}, z: ${z.toFixed(3)}, w: ${w.toFixed(3)}`,
);
if (event.velocity) {
const { x: vx, y: vy, z: vz } = event.velocity;
options.showInfo('velocity');
options.setInfo('velocity', `x: ${vx}, y: ${vy}, z: ${vz}`);
}
}
function handleMove(event: Extract<SmartCubeEvent, { type: 'MOVE' }>): void {
const displayedMove = options.projectMove?.(event.move) ?? event.move;
options.recordMove?.(displayedMove, event.move);
const nextPattern = normalizedPattern && CubeFacelets.applyMove(normalizedPattern, event.move);
if (nextPattern) {
normalizedPattern = nextPattern;
const state = cubieStateFromPattern(nextPattern);
const facelets = CubeFacelets.patternDataToFaceletsExn(nextPattern);
options.showInfo('cubieState');
options.setInfo('cubieState', formatSingmasterCycles(state));
options.onFacelets?.({
facelets,
state,
});
if ((options.solveDetector ?? defaultSolveDetector)(facelets)) options.onSolved?.();
}
if (!playerUntrusted) {
options.trackPlayerMove?.(event.move);
const [nextState, effects] = PlayerSync.move(playerSyncState, event.move);
playerSyncState = nextState;
applyPlayerEffects(effects);
}
if (event.serial !== undefined) {
options.showInfo('eventSerial');
options.setInfo('eventSerial', String(event.serial));
}
if (event.goCubeCenterOrientation !== undefined) {
options.showInfo('centerOrientation');
options.setInfo('centerOrientation', String(event.goCubeCenterOrientation));
}
}
async function handleFacelets(
event: Extract<SmartCubeEvent, { type: 'FACELETS' }>,
): Promise<void> {
if (event.serial !== undefined) {
options.showInfo('eventSerial');
options.setInfo('eventSerial', String(event.serial));
}
normalizedPattern = patternFromFacelets(event.facelets);
const state = normalizedPattern ? cubieStateFromPattern(normalizedPattern) : event.state;
if (state) {
options.showInfo('cubieState');
options.setInfo('cubieState', formatSingmasterCycles(state));
}
options.onFacelets?.({ facelets: event.facelets, state });
const [nextState, syncGeneration] = PlayerSync.beginSnapshot(playerSyncState);
playerSyncState = nextState;
// This packet is authoritative. Moves following it are safe to buffer for
// its async solve, even when a prior packet gap made the player untrusted.
playerUntrusted = false;
const solved = (options.solveDetector ?? defaultSolveDetector)(event.facelets);
if (solved) options.onSolved?.();
const needsReconcile = await (options.shouldReconcilePlayer?.(event.facelets) ?? true);
if (!needsReconcile) {
const [confirmedState, effects] = PlayerSync.confirm(playerSyncState, syncGeneration);
playerSyncState = confirmedState;
applyPlayerEffects(effects);
return;
}
const algorithm = solved ? '' : await options.solveScramble(event.facelets);
const [resolvedState, effects] = PlayerSync.resolve(playerSyncState, syncGeneration, algorithm);
playerSyncState = resolvedState;
applyPlayerEffects(effects);
}
function handleHardware(event: Extract<SmartCubeEvent, { type: 'HARDWARE' }>): void {
if (event.hardwareName !== undefined) options.setInfo('hardwareName', event.hardwareName);
if (event.hardwareVersion !== undefined)
options.setInfo('hardwareVersion', event.hardwareVersion);
if (event.softwareVersion !== undefined)
options.setInfo('softwareVersion', event.softwareVersion);
if (event.productDate !== undefined) options.setInfo('productDate', event.productDate);
if (event.gyroSupported !== undefined)
options.setInfo('gyroSupported', event.gyroSupported ? 'YES' : 'NO');
if (event.goCubeType) {
options.showInfo('goCubeType');
options.setInfo('goCubeType', `${event.goCubeType.name} (${event.goCubeType.code})`);
}
if (event.goCubeOfflineStats) {
const stats = formatOfflineStats(event.goCubeOfflineStats);
['offlineMoves', 'offlineDuration', 'offlineSolves'].forEach(options.showInfo);
options.setInfo('offlineMoves', stats.moves);
options.setInfo('offlineDuration', stats.duration);
options.setInfo('offlineSolves', stats.solves);
}
options.onHardware?.(event);
}
function invalidatePlayerState(): void {
playerUntrusted = true;
normalizedPattern = undefined;
playerSyncState = PlayerSync.invalidate(playerSyncState);
options.invalidatePlayerTracking?.();
}
function handle(event: SmartCubeSessionEvent): void {
switch (event.type) {
case 'GYRO':
handleGyro(event);
break;
case 'REGRIP': {
// World gyro only detects the gesture. Integer Body→Solver frame
// permutations, never quaternions, rename subsequent BLE moves.
const solverToken = options.projectRegrip?.(event.notationToken) ?? event.notationToken;
options.recordMove?.(solverToken);
options.applyRegrip?.(event.notationToken);
options.onRegrip?.(event, solverToken);
break;
}
case 'CUSTOM_TRIGGER':
options.onCustomTrigger?.(event, options.projectMove?.(event.move) ?? event.move);
break;
case 'SHAKE':
options.onShake?.(event);
break;
case 'MOVE_GAP':
invalidatePlayerState();
options.onMoveGap?.(event);
break;
case 'MOVE':
options.onProtocolEvent?.(event);
handleMove(event);
break;
case 'FACELETS':
options.onProtocolEvent?.(event);
handleFacelets(event).catch((error) => console.error('facelets handler failed', error));
break;
case 'HARDWARE':
options.onProtocolEvent?.(event);
handleHardware(event);
break;
case 'BATTERY':
options.onProtocolEvent?.(event);
options.setInfo('batteryLevel', `${event.batteryLevel}%`);
break;
case 'DISCONNECT':
options.onProtocolEvent?.(event);
options.onDisconnect();
break;
default:
options.onProtocolEvent?.(event as NonGyroSmartCubeEvent);
options.onUnknownEvent?.(event);
break;
}
}
return { handle, invalidatePlayerState, reset };
}
|