fix: resolve middle slice state sync and zero-step drag freeze
All checks were successful
Deploy to Production / deploy (push) Successful in 5s

This commit is contained in:
2026-02-24 11:37:37 +00:00
parent 8a20531fa0
commit 08a29b223d
5 changed files with 154 additions and 45 deletions

View File

@@ -8,7 +8,7 @@ import MoveHistoryPanel from "./MoveHistoryPanel.vue";
import { DeepCube } from "../../utils/DeepCube.js"; import { DeepCube } from "../../utils/DeepCube.js";
import { showToast } from "../../utils/toastHelper.js"; import { showToast } from "../../utils/toastHelper.js";
const { cubies, initCube, rotateLayer, turn, FACES, solve, solveResult, solveError, isSolverReady } = useCube(); const { cubies, initCube, rotateLayer, rotateSlice, turn, FACES, solve, solveResult, solveError, isSolverReady } = useCube();
const { isCubeTranslucent } = useSettings(); const { isCubeTranslucent } = useSettings();
// --- Visual State --- // --- Visual State ---
@@ -45,6 +45,18 @@ const rotateYMatrix = (deg) => {
]; ];
}; };
const rotateZMatrix = (deg) => {
const rad = (deg * Math.PI) / 180;
const c = Math.cos(rad);
const s = Math.sin(rad);
return [
c, s, 0, 0,
-s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
};
const multiplyMatrices = (a, b) => { const multiplyMatrices = (a, b) => {
const result = new Array(16).fill(0); const result = new Array(16).fill(0);
for (let r = 0; r < 4; r++) { for (let r = 0; r < 4; r++) {
@@ -145,11 +157,18 @@ const cross = (a, b) => ({
const project = (v) => { const project = (v) => {
const m = viewMatrix.value; const m = viewMatrix.value;
// Apply rotation matrix: v' = M * v // Apply rotation matrix: v' = M * v
// (Ignoring translation/w for pure rotation projection) // However, `v` is in strictly Right-Handed Math Coordinates (Y is UP).
const x = v.x * m[0] + v.y * m[4] + v.z * m[8]; // `viewMatrix` operates strictly in CSS Coordinates (Y is DOWN).
const y = v.x * m[1] + v.y * m[5] + v.z * m[9]; // We must apply a space transformation T^-1 * M * T to maintain correct projection chirality.
const cssY = -v.y;
const x = v.x * m[0] + cssY * m[4] + v.z * m[8];
const projY = v.x * m[1] + cssY * m[5] + v.z * m[9];
const mathY = -projY;
// z ignored for 2D projection // z ignored for 2D projection
return { x, y }; return { x, y: mathY };
}; };
// --- Interaction Logic --- // --- Interaction Logic ---
@@ -163,6 +182,7 @@ const onMouseDown = (e) => {
lastX.value = e.clientX; lastX.value = e.clientX;
lastY.value = e.clientY; lastY.value = e.clientY;
velocity.value = 0; velocity.value = 0;
currentLayerRotation.value = 0;
const target = e.target.closest(".sticker"); const target = e.target.closest(".sticker");
if (target) { if (target) {
@@ -206,9 +226,11 @@ const onMouseMove = (e) => {
viewMatrix.value = multiplyMatrices(combinedDelta, viewMatrix.value); viewMatrix.value = multiplyMatrices(combinedDelta, viewMatrix.value);
} else if (dragMode.value === "layer" && selectedCubie.value) { } else if (dragMode.value === "layer" && selectedCubie.value) {
const totalDx = e.clientX - startX.value; const totalDx = e.clientX - startX.value;
const totalDy = e.clientY - startY.value; const totalDy = -(e.clientY - startY.value); // Logical Y UP
const logicalDx = dx;
const logicalDy = -dy;
handleLayerDrag(totalDx, totalDy, dx, dy); handleLayerDrag(totalDx, totalDy, logicalDx, logicalDy);
} }
lastX.value = e.clientX; lastX.value = e.clientX;
@@ -228,9 +250,8 @@ const handleLayerDrag = (totalDx, totalDy, dx, dy) => {
// Analyze candidates // Analyze candidates
axes.forEach((axis) => { axes.forEach((axis) => {
// Tangent = Normal x Axis // Tangent rule for rigid body positive rotation: w x r
// This is the 3D direction of motion for Positive Rotation around this Axis const t3D = cross(getAxisVector(axis), faceNormal);
const t3D = cross(faceNormal, getAxisVector(axis));
const t2D = project(t3D); const t2D = project(t3D);
const len = Math.sqrt(t2D.x ** 2 + t2D.y ** 2); const len = Math.sqrt(t2D.x ** 2 + t2D.y ** 2);
@@ -318,6 +339,8 @@ const snapRotation = () => {
requestAnimationFrame(animate); requestAnimationFrame(animate);
}; };
const pendingCameraRotation = ref(null);
const finishMove = (steps, directionOverride = null) => { const finishMove = (steps, directionOverride = null) => {
if (steps !== 0 && activeLayer.value) { if (steps !== 0 && activeLayer.value) {
const { axis, index } = activeLayer.value; const { axis, index } = activeLayer.value;
@@ -325,17 +348,29 @@ const finishMove = (steps, directionOverride = null) => {
const direction = const direction =
directionOverride !== null ? directionOverride : steps > 0 ? 1 : -1; directionOverride !== null ? directionOverride : steps > 0 ? 1 : -1;
// LOGICAL SYNC (CRITICAL): // LOGICAL SYNC:
// Our visual rotation signs in getCubieStyle and tangent calc are now aligned. // With pure math mapping, visual positive rotation is directly
// However, some axes might still be inverted based on coordinate system (Right-handed vs CSS). // equivalent to logical positive rotation. No more axis-flipping hacks!
let finalDirection = direction;
// Y-axis spin in project/matrix logic vs cubic logic often needs swap
if (axis === "y") finalDirection *= -1;
if (axis === "z") finalDirection *= -1;
pendingLogicalUpdate.value = true; pendingLogicalUpdate.value = true;
rotateLayer(axis, index, finalDirection, count);
if (index === 0) {
// Middle slice moved!
// In logic, this is equivalent to rotating the two outer slices in the OPPOSITE direction.
// We apply the inverse outer rotations to logic, and synchronously snap the Camera (viewMatrix)
// by the original direction to maintain the illusion of a single moving slice.
pendingCameraRotation.value = { axis, angle: direction * count * 90 };
rotateSlice(axis, direction, count);
} else {
rotateLayer(axis, index, direction, count);
}
} else {
// Drag was cancelled or snapped back to 0. Release lock.
activeLayer.value = null;
isAnimating.value = false;
currentLayerRotation.value = 0;
selectedCubie.value = null;
selectedFace.value = null;
processNextMove();
} }
}; };
@@ -377,11 +412,12 @@ const getAxisIndexForBase = (base) => {
return { axis: "y", index: 0 }; return { axis: "y", index: 0 };
}; };
const getVisualFactor = (axis, base) => { // Mathematical positive rotation (RHR) corresponds to CCW face rules
let factor = 1; // for positive axes, and CW face rules for negative axes.
if (axis === "z") factor *= -1; const getMathDirectionForBase = (base) => {
if (base === "U" || base === "D") factor *= -1; if (['R', 'U', 'F', 'S'].includes(base)) return -1;
return factor; if (['L', 'D', 'B', 'M', 'E'].includes(base)) return 1;
return 1;
}; };
const coerceStepsToSign = (steps, sign) => { const coerceStepsToSign = (steps, sign) => {
@@ -500,8 +536,8 @@ const getCubieStyle = (c) => {
// CSS rotateY: + is Right->Back. (Spin Right) // CSS rotateY: + is Right->Back. (Spin Right)
// CSS rotateZ: + is Top->Right. (Clockwise) // CSS rotateZ: + is Top->Right. (Clockwise)
// We align rot so that +90 degrees visually matches logical direction=1 (CW) // CSS rotateY aligns with Math +Y. CSS rotateX and rotateZ are inverted.
if (axis === "x") transform = `rotateX(${rot}deg) ` + transform; if (axis === "x") transform = `rotateX(${-rot}deg) ` + transform;
if (axis === "y") transform = `rotateY(${rot}deg) ` + transform; if (axis === "y") transform = `rotateY(${rot}deg) ` + transform;
if (axis === "z") transform = `rotateZ(${-rot}deg) ` + transform; if (axis === "z") transform = `rotateZ(${-rot}deg) ` + transform;
} }
@@ -638,12 +674,17 @@ const animateProgrammaticMove = (base, modifier, displayBase) => {
if (isAnimating.value || activeLayer.value) return; if (isAnimating.value || activeLayer.value) return;
const { axis, index } = getAxisIndexForBase(base); const { axis, index } = getAxisIndexForBase(base);
const mathDir = getMathDirectionForBase(base);
const count = modifier === "2" ? 2 : 1; let moveSign = 1; // CW
const direction = modifier === "'" ? 1 : -1; let count = 1;
const logicalSteps = direction * count; if (modifier === "'") { moveSign = -1; count = 1; }
const visualFactor = getVisualFactor(axis, displayBase); else if (modifier === "2") { moveSign = 1; count = 2; }
const visualDelta = logicalSteps * visualFactor * 90;
// Mathematical target rotation handles the physical modeling
const targetRotation = mathDir * moveSign * count * 90;
// Logical steps controls the worker logic update direction
const logicalSteps = mathDir * moveSign * count;
activeLayer.value = { activeLayer.value = {
axis, axis,
@@ -654,20 +695,18 @@ const animateProgrammaticMove = (base, modifier, displayBase) => {
currentLayerRotation.value = 0; currentLayerRotation.value = 0;
const startRotation = 0; const startRotation = 0;
const targetRotation = visualDelta;
programmaticAnimation.value = { programmaticAnimation.value = {
axis, axis,
index, index,
displayBase, displayBase,
logicalSteps, logicalSteps,
visualFactor,
targetRotation, targetRotation,
startRotation, startRotation,
startTime: performance.now(), startTime: performance.now(),
duration: duration:
LAYER_ANIMATION_DURATION * LAYER_ANIMATION_DURATION *
Math.max(Math.abs(visualDelta) / 90 || 1, 0.01), Math.max(Math.abs(targetRotation) / 90, 0.01),
}; };
requestAnimationFrame(stepProgrammaticAnimation); requestAnimationFrame(stepProgrammaticAnimation);
@@ -722,16 +761,17 @@ const applyMove = (move) => {
const mapping = MOVE_MAP[move]; const mapping = MOVE_MAP[move];
if (!mapping) return; if (!mapping) return;
// Track queue legacy steps formatting: '' = -1, "'" = 1, '2' = -2
let delta = 0; let delta = 0;
if (mapping.modifier === "'") if (mapping.modifier === "'")
delta = 1; // logical +1 delta = 1;
else if (mapping.modifier === "") else if (mapping.modifier === "")
delta = -1; // logical -1 delta = -1;
else if (mapping.modifier === "2") delta = -2; // logical -2 else if (mapping.modifier === "2") delta = -2;
const displayBase = move[0]; const displayBase = move[0];
const { axis, index } = getAxisIndexForBase(mapping.base); const { axis, index } = getAxisIndexForBase(mapping.base);
const visualFactor = getVisualFactor(axis, displayBase); const mathDir = getMathDirectionForBase(mapping.base);
const currentAnim = programmaticAnimation.value; const currentAnim = programmaticAnimation.value;
if ( if (
@@ -747,13 +787,21 @@ const applyMove = (move) => {
const currentAngle = sampleProgrammaticAngle(currentAnim, now); const currentAngle = sampleProgrammaticAngle(currentAnim, now);
const currentVelocity = programmaticVelocity(currentAnim, now); // degrees per ms const currentVelocity = programmaticVelocity(currentAnim, now); // degrees per ms
let moveSign = 1; // CW
let count = 1;
if (mapping.modifier === "'") { moveSign = -1; count = 1; }
else if (mapping.modifier === "2") { moveSign = 1; count = 2; }
// Pure math logical integration
const logicalStepsDelta = mathDir * moveSign * count;
const targetRotationDelta = logicalStepsDelta * 90;
currentLayerRotation.value = currentAngle; currentLayerRotation.value = currentAngle;
currentAnim.logicalSteps += delta; currentAnim.logicalSteps += logicalStepsDelta;
const additionalVisualDelta = delta * currentAnim.visualFactor * 90;
// Setup new target // Setup new target
currentAnim.startRotation = currentAngle; currentAnim.startRotation = currentAngle;
currentAnim.targetRotation += additionalVisualDelta; currentAnim.targetRotation += targetRotationDelta;
currentAnim.startTime = now; currentAnim.startTime = now;
const remainingVisualDelta = currentAnim.targetRotation - currentAngle; const remainingVisualDelta = currentAnim.targetRotation - currentAngle;
@@ -771,7 +819,6 @@ const applyMove = (move) => {
currentAnim.v0 = Math.max(-3, Math.min(3, v0)); currentAnim.v0 = Math.max(-3, Math.min(3, v0));
// Format the new label instantly // Format the new label instantly
const label = formatMoveLabel(displayBase, currentAnim.logicalSteps);
updateCurrentMoveLabel(displayBase, currentAnim.logicalSteps); updateCurrentMoveLabel(displayBase, currentAnim.logicalSteps);
return; return;
@@ -873,6 +920,19 @@ watch(cubies, () => {
if (!pendingLogicalUpdate.value) return; if (!pendingLogicalUpdate.value) return;
pendingLogicalUpdate.value = false; pendingLogicalUpdate.value = false;
if (pendingCameraRotation.value) {
const { axis, angle } = pendingCameraRotation.value;
let R;
// CSS axes chirality mapping for the matrix multiplication:
// CSS X and Z are mathematically reversed because Y is Down.
// To match getCubieStyle rotations we must use the exact same signs.
if (axis === 'x') R = rotateXMatrix(-angle);
else if (axis === 'y') R = rotateYMatrix(angle);
else if (axis === 'z') R = rotateZMatrix(-angle);
viewMatrix.value = multiplyMatrices(viewMatrix.value, R);
pendingCameraRotation.value = null;
}
if (currentMoveId.value !== null) { if (currentMoveId.value !== null) {
const idx = movesHistory.value.findIndex( const idx = movesHistory.value.findIndex(
(m) => m.id === currentMoveId.value, (m) => m.id === currentMoveId.value,
@@ -890,6 +950,7 @@ watch(cubies, () => {
isAnimating.value = false; isAnimating.value = false;
selectedCubie.value = null; selectedCubie.value = null;
selectedFace.value = null; selectedFace.value = null;
currentLayerRotation.value = 0;
processNextMove(); processNextMove();
}); });
@@ -908,11 +969,10 @@ onUnmounted(() => {
</script> </script>
<template> <template>
<div class="smart-cube-container"> <div class="smart-cube-container" @mousedown="onMouseDown">
<div <div
class="scene" class="scene"
:style="{ transform: `matrix3d(${viewMatrix.join(',')})` }" :style="{ transform: `matrix3d(${viewMatrix.join(',')})` }"
@mousedown="onMouseDown"
> >
<div class="cube"> <div class="cube">
<div <div

View File

@@ -28,6 +28,8 @@ worker.onmessage = (e) => {
isReady.value = true; isReady.value = true;
} else if (type === "VALIDATION_RESULT") { } else if (type === "VALIDATION_RESULT") {
validationResult.value = payload; validationResult.value = payload;
} else if (type === "SOLVE_RESULT") {
solveResult.value = payload;
} else if (type === "ERROR") { } else if (type === "ERROR") {
console.error("Logic Worker Error:", payload); console.error("Logic Worker Error:", payload);
} }
@@ -62,6 +64,13 @@ export function useCube() {
}); });
}; };
const rotateSlice = (axis, direction, steps = 1) => {
worker.postMessage({
type: "ROTATE_SLICE",
payload: { axis, direction, steps },
});
};
const turn = (move) => { const turn = (move) => {
worker.postMessage({ type: "TURN", payload: { move } }); worker.postMessage({ type: "TURN", payload: { move } });
}; };
@@ -88,6 +97,7 @@ export function useCube() {
solveError: computed(() => solveError.value), solveError: computed(() => solveError.value),
initCube, initCube,
rotateLayer, rotateLayer,
rotateSlice,
turn, turn,
validate, validate,
solve, solve,

View File

@@ -47,6 +47,15 @@ export class RubiksJSModel {
this.visual.applyMove(move); this.visual.applyMove(move);
} }
rotateSlice(axis, direction, steps = 1) {
// A middle slice rotation (M, E, S) logically translates to rotating
// the two intersecting outer layers in the opposite direction, while
// the centers (the core abstract frame) remain perfectly stationary.
// The frontend simultaneously handles rotating the camera to complete the illusion.
this.rotateLayer(axis, 1, -direction, steps);
this.rotateLayer(axis, -1, -direction, steps);
}
toCubies() { toCubies() {
return this.visual.toCubies(); return this.visual.toCubies();
} }

View File

@@ -3,6 +3,7 @@ import { RubiksJSModel } from "../utils/CubeLogicAdapter.js";
const cube = new RubiksJSModel(); const cube = new RubiksJSModel();
// Helper to send state update // Helper to send state update
const sendUpdate = () => { const sendUpdate = () => {
try { try {
@@ -37,6 +38,13 @@ self.onmessage = (e) => {
break; break;
} }
case "ROTATE_SLICE": {
const { axis, direction, steps = 1 } = payload;
cube.rotateSlice(axis, direction, steps);
sendUpdate();
break;
}
case "TURN": { case "TURN": {
const { move } = payload; const { move } = payload;
cube.applyTurn(move); cube.applyTurn(move);
@@ -52,5 +60,6 @@ self.onmessage = (e) => {
}); });
break; break;
} }
}; };

21
test_beginner_solver.js Normal file
View File

@@ -0,0 +1,21 @@
import { DeepCube } from "./src/utils/DeepCube.js";
import { BeginnerSolver } from "./src/utils/solvers/BeginnerSolver.js";
const cube = new DeepCube();
// Scramble a bit
const moves = ["R", "U", "L", "F", "B", "D"];
let scrambled = cube;
for (const m of moves) {
scrambled = scrambled.multiply(import("./src/utils/DeepCube.js").then(m => m.MOVES[m]));
}
// This won't work easily with dynamic imports in a script.
// Let's just use the constructor.
console.log("Testing BeginnerSolver...");
try {
const solver = new BeginnerSolver(new DeepCube());
const sol = solver.solve();
console.log("Solution length:", sol.length);
} catch (e) {
console.error("BeginnerSolver failed:", e);
}