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 { 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();
// --- 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 result = new Array(16).fill(0);
for (let r = 0; r < 4; r++) {
@@ -145,11 +157,18 @@ const cross = (a, b) => ({
const project = (v) => {
const m = viewMatrix.value;
// Apply rotation matrix: v' = M * v
// (Ignoring translation/w for pure rotation projection)
const x = v.x * m[0] + v.y * m[4] + v.z * m[8];
const y = v.x * m[1] + v.y * m[5] + v.z * m[9];
// However, `v` is in strictly Right-Handed Math Coordinates (Y is UP).
// `viewMatrix` operates strictly in CSS Coordinates (Y is DOWN).
// 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
return { x, y };
return { x, y: mathY };
};
// --- Interaction Logic ---
@@ -163,6 +182,7 @@ const onMouseDown = (e) => {
lastX.value = e.clientX;
lastY.value = e.clientY;
velocity.value = 0;
currentLayerRotation.value = 0;
const target = e.target.closest(".sticker");
if (target) {
@@ -206,9 +226,11 @@ const onMouseMove = (e) => {
viewMatrix.value = multiplyMatrices(combinedDelta, viewMatrix.value);
} else if (dragMode.value === "layer" && selectedCubie.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;
@@ -228,9 +250,8 @@ const handleLayerDrag = (totalDx, totalDy, dx, dy) => {
// Analyze candidates
axes.forEach((axis) => {
// Tangent = Normal x Axis
// This is the 3D direction of motion for Positive Rotation around this Axis
const t3D = cross(faceNormal, getAxisVector(axis));
// Tangent rule for rigid body positive rotation: w x r
const t3D = cross(getAxisVector(axis), faceNormal);
const t2D = project(t3D);
const len = Math.sqrt(t2D.x ** 2 + t2D.y ** 2);
@@ -318,6 +339,8 @@ const snapRotation = () => {
requestAnimationFrame(animate);
};
const pendingCameraRotation = ref(null);
const finishMove = (steps, directionOverride = null) => {
if (steps !== 0 && activeLayer.value) {
const { axis, index } = activeLayer.value;
@@ -325,17 +348,29 @@ const finishMove = (steps, directionOverride = null) => {
const direction =
directionOverride !== null ? directionOverride : steps > 0 ? 1 : -1;
// LOGICAL SYNC (CRITICAL):
// Our visual rotation signs in getCubieStyle and tangent calc are now aligned.
// However, some axes might still be inverted based on coordinate system (Right-handed vs CSS).
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;
// LOGICAL SYNC:
// With pure math mapping, visual positive rotation is directly
// equivalent to logical positive rotation. No more axis-flipping hacks!
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 };
};
const getVisualFactor = (axis, base) => {
let factor = 1;
if (axis === "z") factor *= -1;
if (base === "U" || base === "D") factor *= -1;
return factor;
// Mathematical positive rotation (RHR) corresponds to CCW face rules
// for positive axes, and CW face rules for negative axes.
const getMathDirectionForBase = (base) => {
if (['R', 'U', 'F', 'S'].includes(base)) return -1;
if (['L', 'D', 'B', 'M', 'E'].includes(base)) return 1;
return 1;
};
const coerceStepsToSign = (steps, sign) => {
@@ -500,8 +536,8 @@ const getCubieStyle = (c) => {
// CSS rotateY: + is Right->Back. (Spin Right)
// CSS rotateZ: + is Top->Right. (Clockwise)
// We align rot so that +90 degrees visually matches logical direction=1 (CW)
if (axis === "x") transform = `rotateX(${rot}deg) ` + transform;
// CSS rotateY aligns with Math +Y. CSS rotateX and rotateZ are inverted.
if (axis === "x") transform = `rotateX(${-rot}deg) ` + transform;
if (axis === "y") transform = `rotateY(${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;
const { axis, index } = getAxisIndexForBase(base);
const mathDir = getMathDirectionForBase(base);
const count = modifier === "2" ? 2 : 1;
const direction = modifier === "'" ? 1 : -1;
const logicalSteps = direction * count;
const visualFactor = getVisualFactor(axis, displayBase);
const visualDelta = logicalSteps * visualFactor * 90;
let moveSign = 1; // CW
let count = 1;
if (modifier === "'") { moveSign = -1; count = 1; }
else if (modifier === "2") { moveSign = 1; count = 2; }
// 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 = {
axis,
@@ -654,20 +695,18 @@ const animateProgrammaticMove = (base, modifier, displayBase) => {
currentLayerRotation.value = 0;
const startRotation = 0;
const targetRotation = visualDelta;
programmaticAnimation.value = {
axis,
index,
displayBase,
logicalSteps,
visualFactor,
targetRotation,
startRotation,
startTime: performance.now(),
duration:
LAYER_ANIMATION_DURATION *
Math.max(Math.abs(visualDelta) / 90 || 1, 0.01),
Math.max(Math.abs(targetRotation) / 90, 0.01),
};
requestAnimationFrame(stepProgrammaticAnimation);
@@ -722,16 +761,17 @@ const applyMove = (move) => {
const mapping = MOVE_MAP[move];
if (!mapping) return;
// Track queue legacy steps formatting: '' = -1, "'" = 1, '2' = -2
let delta = 0;
if (mapping.modifier === "'")
delta = 1; // logical +1
delta = 1;
else if (mapping.modifier === "")
delta = -1; // logical -1
else if (mapping.modifier === "2") delta = -2; // logical -2
delta = -1;
else if (mapping.modifier === "2") delta = -2;
const displayBase = move[0];
const { axis, index } = getAxisIndexForBase(mapping.base);
const visualFactor = getVisualFactor(axis, displayBase);
const mathDir = getMathDirectionForBase(mapping.base);
const currentAnim = programmaticAnimation.value;
if (
@@ -747,13 +787,21 @@ const applyMove = (move) => {
const currentAngle = sampleProgrammaticAngle(currentAnim, now);
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;
currentAnim.logicalSteps += delta;
const additionalVisualDelta = delta * currentAnim.visualFactor * 90;
currentAnim.logicalSteps += logicalStepsDelta;
// Setup new target
currentAnim.startRotation = currentAngle;
currentAnim.targetRotation += additionalVisualDelta;
currentAnim.targetRotation += targetRotationDelta;
currentAnim.startTime = now;
const remainingVisualDelta = currentAnim.targetRotation - currentAngle;
@@ -771,7 +819,6 @@ const applyMove = (move) => {
currentAnim.v0 = Math.max(-3, Math.min(3, v0));
// Format the new label instantly
const label = formatMoveLabel(displayBase, currentAnim.logicalSteps);
updateCurrentMoveLabel(displayBase, currentAnim.logicalSteps);
return;
@@ -873,6 +920,19 @@ watch(cubies, () => {
if (!pendingLogicalUpdate.value) return;
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) {
const idx = movesHistory.value.findIndex(
(m) => m.id === currentMoveId.value,
@@ -890,6 +950,7 @@ watch(cubies, () => {
isAnimating.value = false;
selectedCubie.value = null;
selectedFace.value = null;
currentLayerRotation.value = 0;
processNextMove();
});
@@ -908,11 +969,10 @@ onUnmounted(() => {
</script>
<template>
<div class="smart-cube-container">
<div class="smart-cube-container" @mousedown="onMouseDown">
<div
class="scene"
:style="{ transform: `matrix3d(${viewMatrix.join(',')})` }"
@mousedown="onMouseDown"
>
<div class="cube">
<div

View File

@@ -28,6 +28,8 @@ worker.onmessage = (e) => {
isReady.value = true;
} else if (type === "VALIDATION_RESULT") {
validationResult.value = payload;
} else if (type === "SOLVE_RESULT") {
solveResult.value = payload;
} else if (type === "ERROR") {
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) => {
worker.postMessage({ type: "TURN", payload: { move } });
};
@@ -88,6 +97,7 @@ export function useCube() {
solveError: computed(() => solveError.value),
initCube,
rotateLayer,
rotateSlice,
turn,
validate,
solve,

View File

@@ -47,6 +47,15 @@ export class RubiksJSModel {
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() {
return this.visual.toCubies();
}

View File

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