Compare commits
18 Commits
c7d369c46a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| a39ebd606f | |||
| 53fb65091c | |||
|
04c6934ad8
|
|||
|
97157ddb7a
|
|||
|
4be710a69f
|
|||
|
3bd919a1cf
|
|||
|
d82eef86f9
|
|||
|
54abcf3414
|
|||
|
68e163270e
|
|||
|
9b02b1d9d6
|
|||
|
b71594d0ab
|
|||
|
94e1cb7ed3
|
|||
|
fd090c6960
|
|||
|
fccc43d0eb
|
|||
|
8a20531fa0
|
|||
|
dc95b07188
|
|||
|
281614502e
|
|||
|
4ab408b329
|
12
README.md
12
README.md
@@ -19,3 +19,15 @@ The software operates entirely in the browser using a custom Group Theory mathem
|
||||
- **Beginner Method (Human):** Constructs the solution layer-by-layer simulating human heuristics natively with instantaneous $O(1)$ algorithmic macros.
|
||||
- **Kociemba's Algorithm (Optimal):** Offloads pruning tables and recursive heuristic searches to Web Workers to instantly calculate and stream back the objectively shortest path solution (typically <20 moves).
|
||||
- **High Performance:** Decoupling the single-threaded UI rendering stack from mathematical validations ensures 60 FPS 3D animations, even while executing computationally expensive analytical algorithms in the background.
|
||||
|
||||
## Development & Asset Generation
|
||||
|
||||
To keep the production build lightweight and avoid native dependency issues on servers (e.g. Docker), heavy packages like `canvas`, `puppeteer`, and `imagetracerjs` have been removed from the default `devDependencies`.
|
||||
|
||||
If you need to run the auxiliary scripts in `scripts/` (for screenshotting or regenerating `cube.svg`), you must install them manually:
|
||||
|
||||
```bash
|
||||
npm install -D canvas puppeteer imagetracerjs
|
||||
```
|
||||
|
||||
These are only required for offline asset optimization and are not needed to build or run the main application.
|
||||
|
||||
1934
package-lock.json
generated
1934
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "rubic-cube",
|
||||
"private": true,
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"cubejs": "^1.3.2",
|
||||
@@ -16,9 +17,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"canvas": "^3.2.1",
|
||||
"imagetracerjs": "^1.2.6",
|
||||
"puppeteer": "^24.37.5",
|
||||
"vite": "^6.2.0"
|
||||
"vite": "^6.2.0",
|
||||
"vitest": "^4.0.18"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ const version = __APP_VERSION__;
|
||||
<template>
|
||||
<footer class="app-footer glass-panel">
|
||||
<div class="footer-content">
|
||||
<p>© {{ currentYear }} Rubic Cube. Wersja {{ version }}</p>
|
||||
<p>© {{ currentYear }} Rubic Cube. v{{ version }}</p>
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup>
|
||||
import { Sun, Moon, Grid2x2 } from "lucide-vue-next";
|
||||
import { ref, onMounted } from "vue";
|
||||
import { Sun, Moon, Grid2x2, Layers, Layers2, LayersPlus } from "lucide-vue-next";
|
||||
import { ref, onMounted, computed } from "vue";
|
||||
import { useSettings } from "../composables/useSettings";
|
||||
|
||||
const { isCubeTranslucent, toggleCubeTranslucent } = useSettings();
|
||||
const { isCubeTranslucent, toggleCubeTranslucent, projectionMode, cycleProjectionMode } = useSettings();
|
||||
const isDark = ref(true);
|
||||
|
||||
const setTheme = (dark) => {
|
||||
@@ -17,6 +17,12 @@ const toggleTheme = () => {
|
||||
setTheme(!isDark.value);
|
||||
};
|
||||
|
||||
const projectionTitle = computed(() => {
|
||||
if (projectionMode.value === 0) return 'Show rear face projections';
|
||||
if (projectionMode.value === 1) return 'Enable animated projections';
|
||||
return 'Disable projections';
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
const savedTheme = localStorage.getItem("theme");
|
||||
if (savedTheme) {
|
||||
@@ -40,19 +46,31 @@ onMounted(() => {
|
||||
@click="toggleCubeTranslucent"
|
||||
:title="
|
||||
isCubeTranslucent
|
||||
? 'Wyłącz przezroczystość kostki'
|
||||
: 'Włącz przezroczystość kostki'
|
||||
? 'Disable cube transparency'
|
||||
: 'Enable cube transparency'
|
||||
"
|
||||
:class="{ active: isCubeTranslucent }"
|
||||
>
|
||||
<Grid2x2 :size="20" />
|
||||
</button>
|
||||
|
||||
<!-- Face Projections Toggle (3-state) -->
|
||||
<button
|
||||
class="btn-neon nav-btn icon-only"
|
||||
@click="cycleProjectionMode"
|
||||
:title="projectionTitle"
|
||||
:class="{ active: projectionMode > 0 }"
|
||||
>
|
||||
<Layers2 v-if="projectionMode === 0" :size="20" />
|
||||
<Layers v-else-if="projectionMode === 1" :size="20" />
|
||||
<LayersPlus v-else :size="20" />
|
||||
</button>
|
||||
|
||||
<!-- Theme Toggle -->
|
||||
<button
|
||||
class="btn-neon nav-btn icon-only"
|
||||
@click="toggleTheme"
|
||||
:title="isDark ? 'Przełącz na jasny' : 'Przełącz na ciemny'"
|
||||
:title="isDark ? 'Switch to light mode' : 'Switch to dark mode'"
|
||||
>
|
||||
<Sun v-if="isDark" :size="20" />
|
||||
<Moon v-else :size="20" />
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted } from "vue";
|
||||
const emit = defineEmits(["move", "scramble", "solve"]);
|
||||
import { Locate, LocateFixed } from "lucide-vue-next";
|
||||
|
||||
const props = defineProps({
|
||||
isViewDefault: { type: Boolean, default: true },
|
||||
});
|
||||
|
||||
const emit = defineEmits(["move", "scramble", "solve", "reset-camera"]);
|
||||
|
||||
const showSolveDropdown = ref(false);
|
||||
|
||||
@@ -109,6 +115,18 @@ onUnmounted(() => {
|
||||
Scramble
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="bottom-right-controls">
|
||||
<button
|
||||
class="btn-neon move-btn camera-reset-btn"
|
||||
:class="{ 'is-default': props.isViewDefault }"
|
||||
:disabled="props.isViewDefault"
|
||||
@click="emit('reset-camera')"
|
||||
>
|
||||
<LocateFixed v-if="props.isViewDefault" :size="18" />
|
||||
<Locate v-else :size="18" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -197,4 +215,39 @@ onUnmounted(() => {
|
||||
.dropdown-item:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.dropdown-item:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.bottom-right-controls {
|
||||
position: absolute;
|
||||
bottom: 72px;
|
||||
right: 24px;
|
||||
z-index: 50;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.camera-reset-btn {
|
||||
min-width: 40px;
|
||||
height: 40px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: opacity 0.3s, transform 0.2s;
|
||||
}
|
||||
|
||||
.camera-reset-btn.is-default {
|
||||
opacity: 0.3;
|
||||
cursor: default;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.camera-reset-btn:not(.is-default):hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
</style>
|
||||
|
||||
192
src/components/renderers/FaceProjections.vue
Normal file
192
src/components/renderers/FaceProjections.vue
Normal file
@@ -0,0 +1,192 @@
|
||||
<script setup>
|
||||
import { computed } from "vue";
|
||||
import { REAR_FACE_DISTANCE } from "../../config/settings.js";
|
||||
|
||||
const props = defineProps({
|
||||
cubies: { type: Array, required: true },
|
||||
viewMatrix: { type: Array, required: true },
|
||||
FACES: { type: Object, required: true },
|
||||
SCALE: { type: Number, default: 100 },
|
||||
activeLayer: { type: Object, default: null },
|
||||
currentLayerRotation: { type: Number, default: 0 },
|
||||
animateLayers: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
// Face definitions with logical normals and grid axes
|
||||
const FACE_DEFS = computed(() => {
|
||||
const F = props.FACES;
|
||||
return [
|
||||
{ face: F.FRONT, normal: [0, 0, 1], gridU: [1, 0, 0], gridV: [0, 1, 0], faceKey: 'front' },
|
||||
{ face: F.BACK, normal: [0, 0, -1], gridU: [-1, 0, 0], gridV: [0, 1, 0], faceKey: 'back' },
|
||||
{ face: F.RIGHT, normal: [1, 0, 0], gridU: [0, 0, -1], gridV: [0, 1, 0], faceKey: 'right' },
|
||||
{ face: F.LEFT, normal: [-1, 0, 0], gridU: [0, 0, 1], gridV: [0, 1, 0], faceKey: 'left' },
|
||||
{ face: F.UP, normal: [0, 1, 0], gridU: [1, 0, 0], gridV: [0, 0, -1], faceKey: 'up' },
|
||||
{ face: F.DOWN, normal: [0, -1, 0], gridU: [1, 0, 0], gridV: [0, 0, 1], faceKey: 'down' },
|
||||
];
|
||||
});
|
||||
|
||||
// Which faces are hidden (for static cells)
|
||||
const hiddenFaceKeys = computed(() => {
|
||||
const m = props.viewMatrix;
|
||||
const keys = new Set();
|
||||
for (const fd of FACE_DEFS.value) {
|
||||
const [nx, ny, nz] = fd.normal;
|
||||
const tz = nx * m[2] + (-ny) * m[6] + nz * m[10];
|
||||
if (tz < 0) keys.add(fd.faceKey);
|
||||
}
|
||||
return keys;
|
||||
});
|
||||
|
||||
// Orientation: cells face INWARD (toward cube center)
|
||||
// Combined with backface-visibility: hidden, this means:
|
||||
// - hidden face cells: front faces camera → visible
|
||||
// - visible face cells: front faces away → invisible
|
||||
// - rotating cells crossing the plane: naturally swap visibility
|
||||
const inwardRotation = (nx, ny, nz) => {
|
||||
if (nx === 1) return 'rotateY(-90deg)';
|
||||
if (nx === -1) return 'rotateY(90deg)';
|
||||
if (ny === 1) return 'rotateX(-90deg)';
|
||||
if (ny === -1) return 'rotateX(90deg)';
|
||||
if (nz === -1) return ''; // front faces +Z (toward camera)
|
||||
return 'rotateY(180deg)'; // nz === 1: flip to face -Z (toward center)
|
||||
};
|
||||
|
||||
// Build cells for one face
|
||||
const buildFaceCells = (fd, S, dist, al, rot, isRotatingOnly) => {
|
||||
const [nx, ny, nz] = fd.normal;
|
||||
const [gu, gv] = [fd.gridU, fd.gridV];
|
||||
const orient = inwardRotation(nx, ny, nz);
|
||||
const d = S * 1.5 + dist;
|
||||
const cells = [];
|
||||
|
||||
const faceCubies = props.cubies.filter((c) => {
|
||||
if (nx !== 0) return c.x === nx;
|
||||
if (ny !== 0) return c.y === ny;
|
||||
if (nz !== 0) return c.z === nz;
|
||||
return false;
|
||||
});
|
||||
|
||||
for (let v = 1; v >= -1; v--) {
|
||||
for (let u = -1; u <= 1; u++) {
|
||||
const cx = nx * Math.max(Math.abs(nx), 0) || u * gu[0] + v * gv[0];
|
||||
const cy = ny * Math.max(Math.abs(ny), 0) || u * gu[1] + v * gv[1];
|
||||
const cz = nz * Math.max(Math.abs(nz), 0) || u * gu[2] + v * gv[2];
|
||||
|
||||
const inLayer = al && (
|
||||
(al.axis === 'x' && cx === al.index) ||
|
||||
(al.axis === 'y' && cy === al.index) ||
|
||||
(al.axis === 'z' && cz === al.index)
|
||||
);
|
||||
|
||||
// Skip: if isRotatingOnly, only include rotating cells
|
||||
// If not isRotatingOnly (hidden face), include non-rotating cells
|
||||
if (isRotatingOnly && !inLayer) continue;
|
||||
if (!isRotatingOnly && inLayer && props.animateLayers) continue;
|
||||
|
||||
const cubie = faceCubies.find(
|
||||
(c) => c.x === cx && c.y === cy && c.z === cz
|
||||
);
|
||||
const color = cubie ? cubie.faces[fd.faceKey] || 'black' : 'black';
|
||||
|
||||
// 3D position
|
||||
const posX = nx * d + u * gu[0] * S + v * gv[0] * S;
|
||||
const posY = ny * d + u * gu[1] * S + v * gv[1] * S;
|
||||
const posZ = nz * d + u * gu[2] * S + v * gv[2] * S;
|
||||
|
||||
let transform = `translate3d(${posX}px, ${-posY}px, ${posZ}px) ${orient}`;
|
||||
|
||||
// Rotating cells: prepend rotation around scene center (only in advanced mode)
|
||||
if (props.animateLayers && inLayer && rot !== 0) {
|
||||
let rotPre = '';
|
||||
if (al.axis === 'x') rotPre = `rotateX(${-rot}deg)`;
|
||||
else if (al.axis === 'y') rotPre = `rotateY(${rot}deg)`;
|
||||
else if (al.axis === 'z') rotPre = `rotateZ(${-rot}deg)`;
|
||||
transform = `${rotPre} ${transform}`;
|
||||
}
|
||||
|
||||
cells.push({
|
||||
key: `${fd.faceKey}-${u}-${v}`,
|
||||
color,
|
||||
transform,
|
||||
});
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
};
|
||||
|
||||
// All cells to render
|
||||
const allCells = computed(() => {
|
||||
const S = props.SCALE;
|
||||
const dist = REAR_FACE_DISTANCE * S * 3;
|
||||
const al = props.activeLayer;
|
||||
const rot = props.currentLayerRotation;
|
||||
const cells = [];
|
||||
|
||||
for (const fd of FACE_DEFS.value) {
|
||||
const isHidden = hiddenFaceKeys.value.has(fd.faceKey);
|
||||
|
||||
if (isHidden) {
|
||||
// Hidden face: render non-rotating cells (static projections)
|
||||
cells.push(...buildFaceCells(fd, S, dist, al, rot, false));
|
||||
}
|
||||
|
||||
// ALL faces: render rotating-layer cells (they swap via backface-visibility)
|
||||
if (props.animateLayers && al && rot !== 0) {
|
||||
cells.push(...buildFaceCells(fd, S, dist, al, rot, true));
|
||||
}
|
||||
}
|
||||
|
||||
return cells;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="face-projections-root">
|
||||
<div
|
||||
v-for="cell in allCells"
|
||||
:key="cell.key"
|
||||
class="proj-cell"
|
||||
:class="cell.color"
|
||||
:style="{ transform: cell.transform }"
|
||||
></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.face-projections-root {
|
||||
position: absolute;
|
||||
transform-style: preserve-3d;
|
||||
}
|
||||
|
||||
.proj-cell {
|
||||
position: absolute;
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
margin-left: -50px;
|
||||
margin-top: -50px;
|
||||
box-sizing: border-box;
|
||||
background: #000;
|
||||
border: 1px solid #000;
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.proj-cell::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
right: 4px;
|
||||
bottom: 4px;
|
||||
border-radius: 8px;
|
||||
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
/* Colors - use global design system variables */
|
||||
.proj-cell.white::after { background: var(--sticker-white); }
|
||||
.proj-cell.yellow::after { background: var(--sticker-yellow); }
|
||||
.proj-cell.green::after { background: var(--sticker-green); }
|
||||
.proj-cell.blue::after { background: var(--sticker-blue); }
|
||||
.proj-cell.orange::after { background: var(--sticker-orange); }
|
||||
.proj-cell.red::after { background: var(--sticker-red); }
|
||||
.proj-cell.black::after { display: none; }
|
||||
</style>
|
||||
@@ -171,6 +171,8 @@ onUnmounted(() => {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
min-width: 16px;
|
||||
min-height: 24px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
|
||||
@@ -2,21 +2,64 @@
|
||||
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from "vue";
|
||||
import { useCube } from "../../composables/useCube";
|
||||
import { useSettings } from "../../composables/useSettings";
|
||||
import { LAYER_ANIMATION_DURATION } from "../../config/animationSettings";
|
||||
import { LAYER_ANIMATION_DURATION, MIDDLE_SLICES_ENABLED } from "../../config/settings";
|
||||
import CubeMoveControls from "./CubeMoveControls.vue";
|
||||
import MoveHistoryPanel from "./MoveHistoryPanel.vue";
|
||||
import FaceProjections from "./FaceProjections.vue";
|
||||
import { DeepCube } from "../../utils/DeepCube.js";
|
||||
import { KociembaSolver } from "../../utils/solvers/KociembaSolver.js";
|
||||
import { BeginnerSolver } from "../../utils/solvers/BeginnerSolver.js";
|
||||
import Toastify from "toastify-js";
|
||||
import { showToast } from "../../utils/toastHelper.js";
|
||||
import { identityMatrix, rotateXMatrix, rotateYMatrix, rotateZMatrix, multiplyMatrices, matToQuat, slerp, quatToMat } from "../../utils/matrix.js";
|
||||
import { MOVE_MAP, INTERNAL_TO_UI, getAxisIndexForBase, getMathDirectionForBase, getDragMoveLabel, coerceStepsToSign, formatMoveLabel } from "../../utils/moveMapping.js";
|
||||
import { easeInOutCubic, easeInOutCubicDerivative, cubicEaseWithInitialVelocity, cubicEaseWithInitialVelocityDerivative } from "../../utils/easing.js";
|
||||
import { getFaceNormal as getFaceNormalRaw, getAllowedAxes as getAllowedAxesRaw, getAxisVector, cross, project as projectRaw } from "../../utils/cubeProjection.js";
|
||||
import { tokenReducer } from "../../utils/tokenReducer.js";
|
||||
|
||||
const { cubies, initCube, rotateLayer, turn, FACES } = useCube();
|
||||
const { isCubeTranslucent } = useSettings();
|
||||
const { cubies, deepCubeState, initCube, rotateLayer, rotateSlice, turn, FACES, solve, solveResult, solveError, isSolverReady } = useCube();
|
||||
const { isCubeTranslucent, projectionMode } = useSettings();
|
||||
|
||||
// Bind FACES and viewMatrix to imported helpers
|
||||
const getFaceNormal = (face) => getFaceNormalRaw(face, FACES);
|
||||
const getAllowedAxes = (face) => getAllowedAxesRaw(face, FACES);
|
||||
const project = (v) => projectRaw(v, viewMatrix.value);
|
||||
|
||||
// --- Visual State ---
|
||||
const rx = ref(-25);
|
||||
const ry = ref(45);
|
||||
const rz = ref(0);
|
||||
|
||||
// Initial orientation: Tilt X, then Spin Y
|
||||
const viewMatrix = ref(multiplyMatrices(rotateXMatrix(-25), rotateYMatrix(45)));
|
||||
const DEFAULT_VIEW_MATRIX = multiplyMatrices(rotateXMatrix(-25), rotateYMatrix(45));
|
||||
const isResettingCamera = ref(false);
|
||||
|
||||
const isViewDefault = computed(() => {
|
||||
const m = viewMatrix.value;
|
||||
const d = DEFAULT_VIEW_MATRIX;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
if (Math.abs(m[i] - d[i]) > 0.001) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const resetCamera = () => {
|
||||
if (isViewDefault.value || isResettingCamera.value) return;
|
||||
isResettingCamera.value = true;
|
||||
const startQuat = matToQuat(viewMatrix.value);
|
||||
const targetQuat = matToQuat(DEFAULT_VIEW_MATRIX);
|
||||
const startTime = performance.now();
|
||||
const duration = 500;
|
||||
|
||||
const animate = (time) => {
|
||||
const p = Math.min((time - startTime) / duration, 1);
|
||||
const t = easeInOutCubic(p);
|
||||
const q = slerp(startQuat, targetQuat, t);
|
||||
viewMatrix.value = quatToMat(q);
|
||||
if (p < 1) {
|
||||
requestAnimationFrame(animate);
|
||||
} else {
|
||||
viewMatrix.value = [...DEFAULT_VIEW_MATRIX];
|
||||
isResettingCamera.value = false;
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(animate);
|
||||
};
|
||||
const SCALE = 100;
|
||||
const GAP = 0;
|
||||
const MIN_MOVES_COLUMN_GAP = 6;
|
||||
@@ -55,75 +98,10 @@ const rotationDebugCurrent = computed(() => {
|
||||
return Math.round(angle);
|
||||
});
|
||||
|
||||
// --- Constants & Helpers ---
|
||||
|
||||
const getFaceNormal = (face) => {
|
||||
const map = {
|
||||
[FACES.FRONT]: { x: 0, y: 0, z: 1 },
|
||||
[FACES.BACK]: { x: 0, y: 0, z: -1 },
|
||||
[FACES.RIGHT]: { x: 1, y: 0, z: 0 },
|
||||
[FACES.LEFT]: { x: -1, y: 0, z: 0 },
|
||||
[FACES.UP]: { x: 0, y: 1, z: 0 },
|
||||
[FACES.DOWN]: { x: 0, y: -1, z: 0 },
|
||||
};
|
||||
return map[face] || { x: 0, y: 0, z: 1 };
|
||||
};
|
||||
|
||||
const getAllowedAxes = (face) => {
|
||||
// Logic: Which axes can this face physically move along?
|
||||
switch (face) {
|
||||
case FACES.FRONT:
|
||||
case FACES.BACK:
|
||||
return ["x", "y"];
|
||||
case FACES.RIGHT:
|
||||
case FACES.LEFT:
|
||||
return ["z", "y"];
|
||||
case FACES.UP:
|
||||
case FACES.DOWN:
|
||||
return ["x", "z"];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const getAxisVector = (axis) => {
|
||||
if (axis === "x") return { x: 1, y: 0, z: 0 };
|
||||
if (axis === "y") return { x: 0, y: 1, z: 0 };
|
||||
if (axis === "z") return { x: 0, y: 0, z: 1 };
|
||||
return { x: 0, y: 0, z: 0 };
|
||||
};
|
||||
|
||||
// Cross Product: a x b
|
||||
const cross = (a, b) => ({
|
||||
x: a.y * b.z - a.z * b.y,
|
||||
y: a.z * b.x - a.x * b.z,
|
||||
z: a.x * b.y - a.y * b.x,
|
||||
});
|
||||
|
||||
// Project 3D vector to 2D screen space based on current view (rx, ry, rz)
|
||||
const project = (v) => {
|
||||
const radX = (rx.value * Math.PI) / 180;
|
||||
const radY = (ry.value * Math.PI) / 180;
|
||||
const radZ = (rz.value * Math.PI) / 180;
|
||||
|
||||
let x1 = v.x * Math.cos(radZ) - v.y * Math.sin(radZ);
|
||||
let y1 = v.x * Math.sin(radZ) + v.y * Math.cos(radZ);
|
||||
let z1 = v.z;
|
||||
|
||||
let x2 = x1 * Math.cos(radY) + z1 * Math.sin(radY);
|
||||
let y2 = y1;
|
||||
let z2 = -x1 * Math.sin(radY) + z1 * Math.cos(radY);
|
||||
|
||||
let x3 = x2;
|
||||
let y3 = y2 * Math.cos(radX) - z2 * Math.sin(radX);
|
||||
|
||||
return { x: x3, y: y3 };
|
||||
};
|
||||
|
||||
// --- Interaction Logic ---
|
||||
|
||||
const onMouseDown = (e) => {
|
||||
if (isAnimating.value) return;
|
||||
|
||||
isDragging.value = true;
|
||||
startX.value = e.clientX;
|
||||
startY.value = e.clientY;
|
||||
@@ -131,6 +109,15 @@ const onMouseDown = (e) => {
|
||||
lastY.value = e.clientY;
|
||||
velocity.value = 0;
|
||||
|
||||
// During animations, only allow view rotation (camera drag), not layer manipulation
|
||||
if (isAnimating.value) {
|
||||
dragMode.value = "view";
|
||||
selectedCubie.value = null;
|
||||
return;
|
||||
}
|
||||
|
||||
currentLayerRotation.value = 0;
|
||||
|
||||
const target = e.target.closest(".sticker");
|
||||
if (target) {
|
||||
const id = parseInt(target.dataset.id);
|
||||
@@ -140,16 +127,11 @@ const onMouseDown = (e) => {
|
||||
selectedCubie.value = { ...cubie }; // Snapshot position
|
||||
selectedFace.value = face;
|
||||
|
||||
// Check if center piece (has 2 zero coordinates)
|
||||
// Centers have sum of absolute coords = 1
|
||||
// Core (0,0,0) has sum = 0
|
||||
// Mechanical Realism Rules:
|
||||
// Centers (absSum <= 1) are "Stiff" (part of the core frame). Dragging them rotates the View.
|
||||
// Corners/Edges (absSum > 1) are "Moving Parts". Dragging them rotates the Layer.
|
||||
const absSum = Math.abs(cubie.x) + Math.abs(cubie.y) + Math.abs(cubie.z);
|
||||
const isCenterOrCore = absSum <= 1;
|
||||
|
||||
// Mechanical Realism:
|
||||
// Centers are "Stiff" (part of the core frame). Dragging them rotates the View.
|
||||
// Corners/Edges are "Moving Parts". Dragging them rotates the Layer.
|
||||
dragMode.value = isCenterOrCore ? "view" : "layer";
|
||||
dragMode.value = absSum <= 1 ? "view" : "layer";
|
||||
} else {
|
||||
dragMode.value = "view";
|
||||
selectedCubie.value = null;
|
||||
@@ -163,13 +145,26 @@ const onMouseMove = (e) => {
|
||||
const dy = e.clientY - lastY.value;
|
||||
|
||||
if (dragMode.value === "view") {
|
||||
ry.value += dx * 0.5;
|
||||
rx.value += dy * 0.5;
|
||||
// Relative View Rotation:
|
||||
// Dragging mouse Down (positive dy) should pull the TOP of the cube towards the user.
|
||||
// In standard math, rotating a cube around World X-axis by positive angle tilts it BACK.
|
||||
// So we use -dy for the rotation angle.
|
||||
const deltaX = rotateXMatrix(-dy * 0.5);
|
||||
const deltaY = rotateYMatrix(dx * 0.5);
|
||||
|
||||
// Order matters: Apply deltas on top of current orientation.
|
||||
// RotationY(dx) * RotationX(dy) * currentMatrix
|
||||
// Result: Horizontal dragging always spins around screen Y,
|
||||
// vertical dragging always tilts around screen X.
|
||||
const combinedDelta = multiplyMatrices(deltaY, deltaX);
|
||||
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;
|
||||
@@ -189,8 +184,7 @@ const handleLayerDrag = (totalDx, totalDy, dx, dy) => {
|
||||
|
||||
// Analyze candidates
|
||||
axes.forEach((axis) => {
|
||||
// Tangent = Axis x Normal
|
||||
// This is the 3D direction of motion for Positive Rotation around this 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);
|
||||
@@ -220,6 +214,12 @@ const handleLayerDrag = (totalDx, totalDy, dx, dy) => {
|
||||
if (best.axis === "y") index = selectedCubie.value.y;
|
||||
if (best.axis === "z") index = selectedCubie.value.z;
|
||||
|
||||
// If middle slice (index === 0) and middle slices are disabled, ignore the drag
|
||||
if (index === 0 && !MIDDLE_SLICES_ENABLED) {
|
||||
dragMode.value = "view";
|
||||
return;
|
||||
}
|
||||
|
||||
activeLayer.value = {
|
||||
axis: best.axis,
|
||||
index,
|
||||
@@ -246,7 +246,7 @@ const handleLayerDrag = (totalDx, totalDy, dx, dy) => {
|
||||
};
|
||||
|
||||
const onMouseUp = () => {
|
||||
if (isDragging.value && activeLayer.value) {
|
||||
if (isDragging.value && dragMode.value === "layer" && activeLayer.value) {
|
||||
snapRotation();
|
||||
}
|
||||
isDragging.value = false;
|
||||
@@ -279,6 +279,10 @@ const snapRotation = () => {
|
||||
requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
const pendingCameraRotation = ref(null);
|
||||
const pendingDragMoveLabel = ref(null);
|
||||
|
||||
|
||||
const finishMove = (steps, directionOverride = null) => {
|
||||
if (steps !== 0 && activeLayer.value) {
|
||||
const { axis, index } = activeLayer.value;
|
||||
@@ -286,16 +290,54 @@ const finishMove = (steps, directionOverride = null) => {
|
||||
const direction =
|
||||
directionOverride !== null ? directionOverride : steps > 0 ? 1 : -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, direction, count);
|
||||
|
||||
// Record the drag move in history
|
||||
const moveLabel = getDragMoveLabel(axis, index, direction, count);
|
||||
if (moveLabel) {
|
||||
pendingDragMoveLabel.value = moveLabel;
|
||||
}
|
||||
|
||||
if (index === 0) {
|
||||
// Middle slice moved!
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
const movesHistory = ref([]);
|
||||
|
||||
const displayMoves = computed(() => {
|
||||
const list = movesHistory.value.slice();
|
||||
// Reduce completed moves (consolidate consecutive same-face)
|
||||
const done = movesHistory.value.filter((m) => m.status === 'done');
|
||||
const inProgress = movesHistory.value.filter((m) => m.status === 'in_progress');
|
||||
const doneLabels = done.map((m) => m.label);
|
||||
const reduced = tokenReducer(doneLabels);
|
||||
|
||||
const list = reduced.tokens.map((label, idx) => ({
|
||||
id: `r-${idx}`,
|
||||
label,
|
||||
status: 'done',
|
||||
}));
|
||||
|
||||
// Append in-progress moves as-is
|
||||
inProgress.forEach((m) => list.push(m));
|
||||
|
||||
// Append pending queue moves
|
||||
moveQueue.value.forEach((q, idx) => {
|
||||
const stepsMod = ((q.steps % 4) + 4) % 4;
|
||||
if (stepsMod === 0) return;
|
||||
@@ -319,45 +361,6 @@ const displayMoves = computed(() => {
|
||||
return list;
|
||||
});
|
||||
|
||||
const getAxisIndexForBase = (base) => {
|
||||
if (base === "U") return { axis: "y", index: 1 };
|
||||
if (base === "D") return { axis: "y", index: -1 };
|
||||
if (base === "L") return { axis: "x", index: -1 };
|
||||
if (base === "R") return { axis: "x", index: 1 };
|
||||
if (base === "F") return { axis: "z", index: 1 };
|
||||
if (base === "B") return { axis: "z", index: -1 };
|
||||
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;
|
||||
};
|
||||
|
||||
const coerceStepsToSign = (steps, sign) => {
|
||||
if (steps === 0) return 0;
|
||||
const mod = ((steps % 4) + 4) % 4;
|
||||
if (sign < 0) {
|
||||
if (mod === 1) return -3;
|
||||
if (mod === 2) return -2;
|
||||
return -1;
|
||||
}
|
||||
if (mod === 1) return 1;
|
||||
if (mod === 2) return 2;
|
||||
return 3;
|
||||
};
|
||||
|
||||
const formatMoveLabel = (displayBase, steps) => {
|
||||
const stepsMod = ((steps % 4) + 4) % 4;
|
||||
if (stepsMod === 0) return displayBase;
|
||||
let modifier = "";
|
||||
if (stepsMod === 1) modifier = "'";
|
||||
else if (stepsMod === 2) modifier = "2";
|
||||
else if (stepsMod === 3) modifier = "";
|
||||
return displayBase + (modifier === "'" ? "'" : modifier === "2" ? "2" : "");
|
||||
};
|
||||
|
||||
const updateCurrentMoveLabel = (displayBase, steps) => {
|
||||
if (currentMoveId.value === null) return;
|
||||
@@ -448,13 +451,14 @@ const getCubieStyle = (c) => {
|
||||
// Logic X=1 (Right). CSS +X is Right.
|
||||
|
||||
// Rotations:
|
||||
// CSS rotateX: + is Top->Back.
|
||||
// CSS rotateY: + is Right->Back (Spin Right).
|
||||
// CSS rotateZ: + is Top->Right (Clockwise).
|
||||
// CSS rotateX: + is Top->Back. (Standard R direction)
|
||||
// CSS rotateY: + is Right->Back. (Spin Right)
|
||||
// CSS rotateZ: + is Top->Right. (Clockwise)
|
||||
|
||||
// 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;
|
||||
if (axis === "y") transform = `rotateY(${rot}deg) ` + transform;
|
||||
if (axis === "z") transform = `rotateZ(${-rot}deg) ` + transform;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,27 +503,6 @@ const processNextMove = () => {
|
||||
animateProgrammaticMove(next.base, next.modifier, baseLabel);
|
||||
};
|
||||
|
||||
const easeInOutCubic = (t) => {
|
||||
if (t < 0.5) return 4 * t * t * t;
|
||||
return 1 - Math.pow(-2 * t + 2, 3) / 2;
|
||||
};
|
||||
|
||||
// Derivative of standard easeInOutCubic for instantaneous velocity calculations
|
||||
const easeInOutCubicDerivative = (t) => {
|
||||
if (t < 0.5) return 12 * t * t;
|
||||
return 3 * Math.pow(-2 * t + 2, 2);
|
||||
};
|
||||
|
||||
// Custom easing function that preserves initial velocity $v_0$
|
||||
// The polynomial is $P(t) = (v_0 - 2)t^3 + (3 - 2v_0)t^2 + v_0 t$
|
||||
const cubicEaseWithInitialVelocity = (t, v0) => {
|
||||
return (v0 - 2) * t * t * t + (3 - 2 * v0) * t * t + v0 * t;
|
||||
};
|
||||
|
||||
// Derivative of the custom easing function
|
||||
const cubicEaseWithInitialVelocityDerivative = (t, v0) => {
|
||||
return 3 * (v0 - 2) * t * t + 2 * (3 - 2 * v0) * t + v0;
|
||||
};
|
||||
|
||||
const sampleProgrammaticAngle = (anim, time) => {
|
||||
const p = Math.min((time - anim.startTime) / anim.duration, 1);
|
||||
@@ -566,10 +549,8 @@ const stepProgrammaticAnimation = (time) => {
|
||||
(m) => m.id === currentMoveId.value,
|
||||
);
|
||||
if (idx !== -1) {
|
||||
movesHistory.value[idx] = {
|
||||
...movesHistory.value[idx],
|
||||
status: "done",
|
||||
};
|
||||
// 0 steps = full rotation, remove from history instead of marking done
|
||||
movesHistory.value.splice(idx, 1);
|
||||
}
|
||||
currentMoveId.value = null;
|
||||
}
|
||||
@@ -589,12 +570,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,
|
||||
@@ -605,51 +591,23 @@ 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);
|
||||
};
|
||||
|
||||
const MOVE_MAP = {
|
||||
U: { base: "U", modifier: "" },
|
||||
"U-prime": { base: "U", modifier: "'" },
|
||||
U2: { base: "U", modifier: "2" },
|
||||
|
||||
D: { base: "D", modifier: "'" },
|
||||
"D-prime": { base: "D", modifier: "" },
|
||||
D2: { base: "D", modifier: "2" },
|
||||
|
||||
L: { base: "B", modifier: "'" },
|
||||
"L-prime": { base: "B", modifier: "" },
|
||||
L2: { base: "B", modifier: "2" },
|
||||
|
||||
R: { base: "F", modifier: "" },
|
||||
"R-prime": { base: "F", modifier: "'" },
|
||||
R2: { base: "F", modifier: "2" },
|
||||
|
||||
F: { base: "L", modifier: "'" },
|
||||
"F-prime": { base: "L", modifier: "" },
|
||||
F2: { base: "L", modifier: "2" },
|
||||
|
||||
B: { base: "R", modifier: "" },
|
||||
"B-prime": { base: "R", modifier: "'" },
|
||||
B2: { base: "R", modifier: "2" },
|
||||
};
|
||||
|
||||
const isAddModalOpen = ref(false);
|
||||
const addMovesText = ref("");
|
||||
|
||||
@@ -673,16 +631,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 (
|
||||
@@ -698,13 +657,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;
|
||||
@@ -721,9 +688,10 @@ 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);
|
||||
// Convert logicalSteps (math convention) to label steps (UI convention)
|
||||
// For mathDir=-1 faces (R/U/F): display = logicalSteps (same sign)
|
||||
// For mathDir=1 faces (D/L/B): display = -logicalSteps (inverted sign)
|
||||
updateCurrentMoveLabel(displayBase, -mathDir * currentAnim.logicalSteps);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -750,7 +718,27 @@ const scramble = () => {
|
||||
const handleSolve = async (solverType) => {
|
||||
if (isAnimating.value) return;
|
||||
|
||||
const currentCube = DeepCube.fromCubies(cubies.value);
|
||||
if (solverType === "kociemba" && !isSolverReady.value) {
|
||||
showToast("wait for solver initialization", "info", {
|
||||
style: {
|
||||
background: "linear-gradient(to right, #b45309, #d97706)",
|
||||
color: "#ffffff"
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!deepCubeState.value) {
|
||||
console.error("DeepCube state not available yet");
|
||||
return;
|
||||
}
|
||||
|
||||
const currentCube = new DeepCube(
|
||||
deepCubeState.value.cp,
|
||||
deepCubeState.value.co,
|
||||
deepCubeState.value.ep,
|
||||
deepCubeState.value.eo,
|
||||
);
|
||||
|
||||
if (!currentCube.isValid()) {
|
||||
console.error("Cube is physically impossible!");
|
||||
@@ -759,47 +747,24 @@ const handleSolve = async (solverType) => {
|
||||
|
||||
// Already solved? (Identity check)
|
||||
if (currentCube.isSolved()) {
|
||||
Toastify({
|
||||
text: "scramble cube first",
|
||||
duration: 3000,
|
||||
gravity: "top",
|
||||
position: "center",
|
||||
style: {
|
||||
background: "rgba(255, 255, 255, 0.1)",
|
||||
color: "#fff",
|
||||
backdropFilter: "blur(8px)",
|
||||
borderRadius: "8px",
|
||||
border: "1px solid rgba(255, 255, 255, 0.2)",
|
||||
boxShadow: "0 4px 12px rgba(0, 0, 0, 0.5)",
|
||||
},
|
||||
}).showToast();
|
||||
showToast("scramble cube first", "info");
|
||||
return;
|
||||
}
|
||||
|
||||
let solution = [];
|
||||
try {
|
||||
if (solverType === "kociemba") {
|
||||
const solver = new KociembaSolver(currentCube);
|
||||
solution = solver.solve();
|
||||
} else if (solverType === "beginner") {
|
||||
const solver = new BeginnerSolver(currentCube);
|
||||
solution = solver.solve();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Solver exception:", e);
|
||||
return;
|
||||
}
|
||||
solve(solverType, {
|
||||
cp: currentCube.cp,
|
||||
co: currentCube.co,
|
||||
ep: currentCube.ep,
|
||||
eo: currentCube.eo,
|
||||
});
|
||||
};
|
||||
|
||||
// Listen for solution from worker
|
||||
watch(solveResult, (solution) => {
|
||||
if (solution && solution.length > 0) {
|
||||
const uiMoves = solution.map((m) => {
|
||||
const solverBase = m[0];
|
||||
let solverModifier = m.slice(1);
|
||||
|
||||
// Topological neg-axes (D, L, B) require visually inverted dir mapping for CW/CCW
|
||||
if (["D", "L", "B"].includes(solverBase)) {
|
||||
if (solverModifier === "") solverModifier = "'";
|
||||
else if (solverModifier === "'") solverModifier = "";
|
||||
}
|
||||
const solverModifier = m.slice(1);
|
||||
|
||||
for (const [uiKey, mapping] of Object.entries(MOVE_MAP)) {
|
||||
if (
|
||||
@@ -809,17 +774,51 @@ const handleSolve = async (solverType) => {
|
||||
return uiKey;
|
||||
}
|
||||
}
|
||||
return m;
|
||||
});
|
||||
return null;
|
||||
}).filter(m => m !== null);
|
||||
|
||||
uiMoves.forEach((m) => applyMove(m));
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
watch(solveError, (err) => {
|
||||
if (err) {
|
||||
showToast(err, "info", {
|
||||
style: {
|
||||
background: "linear-gradient(to right, #b45309, #d97706)",
|
||||
color: "#ffffff"
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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 (pendingDragMoveLabel.value) {
|
||||
const id = `drag-${Date.now()}`;
|
||||
movesHistory.value.push({
|
||||
id,
|
||||
label: pendingDragMoveLabel.value,
|
||||
status: 'done',
|
||||
});
|
||||
pendingDragMoveLabel.value = null;
|
||||
}
|
||||
|
||||
if (currentMoveId.value !== null) {
|
||||
const idx = movesHistory.value.findIndex(
|
||||
(m) => m.id === currentMoveId.value,
|
||||
@@ -837,6 +836,7 @@ watch(cubies, () => {
|
||||
isAnimating.value = false;
|
||||
selectedCubie.value = null;
|
||||
selectedFace.value = null;
|
||||
currentLayerRotation.value = 0;
|
||||
processNextMove();
|
||||
});
|
||||
|
||||
@@ -855,10 +855,10 @@ onUnmounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="smart-cube-container">
|
||||
<div class="smart-cube-container" @mousedown="onMouseDown">
|
||||
<div
|
||||
class="scene"
|
||||
:style="{ transform: `rotateX(${rx}deg) rotateY(${ry}deg)` }"
|
||||
:style="{ transform: `matrix3d(${viewMatrix.join(',')})` }"
|
||||
>
|
||||
<div class="cube">
|
||||
<div
|
||||
@@ -879,12 +879,25 @@ onUnmounted(() => {
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FaceProjections
|
||||
v-if="projectionMode > 0"
|
||||
:cubies="cubies"
|
||||
:view-matrix="viewMatrix"
|
||||
:FACES="FACES"
|
||||
:SCALE="SCALE"
|
||||
:active-layer="activeLayer"
|
||||
:current-layer-rotation="currentLayerRotation"
|
||||
:animate-layers="projectionMode === 2"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CubeMoveControls
|
||||
:is-view-default="isViewDefault"
|
||||
@move="applyMove"
|
||||
@scramble="scramble"
|
||||
@solve="handleSolve"
|
||||
@reset-camera="resetCamera"
|
||||
/>
|
||||
|
||||
<MoveHistoryPanel
|
||||
@@ -894,6 +907,8 @@ onUnmounted(() => {
|
||||
@add-moves="handleAddMoves"
|
||||
@open-add-modal="openAddModal"
|
||||
/>
|
||||
|
||||
|
||||
<div
|
||||
v-if="isAddModalOpen"
|
||||
class="moves-modal-backdrop"
|
||||
@@ -910,7 +925,7 @@ onUnmounted(() => {
|
||||
</button>
|
||||
<button
|
||||
class="btn-neon move-btn moves-modal-button"
|
||||
@click="handleAddMoves(addMovesText)"
|
||||
@click="handleAddMoves(addMovesText); closeAddModal()"
|
||||
>
|
||||
add moves
|
||||
</button>
|
||||
@@ -1143,22 +1158,22 @@ onUnmounted(() => {
|
||||
|
||||
/* Colors - apply to the pseudo-element */
|
||||
.white::after {
|
||||
background: #e0e0e0;
|
||||
background: var(--sticker-white);
|
||||
}
|
||||
.yellow::after {
|
||||
background: #ffd500;
|
||||
background: var(--sticker-yellow);
|
||||
}
|
||||
.green::after {
|
||||
background: #009e60;
|
||||
background: var(--sticker-green);
|
||||
}
|
||||
.blue::after {
|
||||
background: #0051ba;
|
||||
background: var(--sticker-blue);
|
||||
}
|
||||
.orange::after {
|
||||
background: #ff5800;
|
||||
background: var(--sticker-orange);
|
||||
}
|
||||
.red::after {
|
||||
background: #c41e3a;
|
||||
background: var(--sticker-red);
|
||||
}
|
||||
|
||||
/* Black internal faces - no sticker needed */
|
||||
|
||||
@@ -1,26 +1,53 @@
|
||||
import { ref, computed } from "vue";
|
||||
import { COLORS, FACES } from "../utils/CubeModel";
|
||||
|
||||
// Singleton worker
|
||||
// Singleton logic worker
|
||||
const worker = new Worker(
|
||||
new URL("../workers/Cube.worker.js", import.meta.url),
|
||||
{ type: "module" },
|
||||
);
|
||||
|
||||
// Singleton solver worker
|
||||
const solverWorker = new Worker(
|
||||
new URL("../workers/Solver.worker.js", import.meta.url),
|
||||
{ type: "module" },
|
||||
);
|
||||
|
||||
// Reactive state
|
||||
const cubies = ref([]);
|
||||
const deepCubeState = ref(null);
|
||||
const isReady = ref(false);
|
||||
const isSolverReady = ref(false);
|
||||
const validationResult = ref(null);
|
||||
const solveResult = ref(null);
|
||||
const solveError = ref(null);
|
||||
|
||||
worker.onmessage = (e) => {
|
||||
const { type, payload } = e.data;
|
||||
if (type === "STATE_UPDATE") {
|
||||
cubies.value = payload.cubies;
|
||||
deepCubeState.value = payload.deepCubeState;
|
||||
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("Worker Error:", payload);
|
||||
console.error("Logic Worker Error:", payload);
|
||||
}
|
||||
};
|
||||
|
||||
solverWorker.onmessage = (e) => {
|
||||
const { type, payload } = e.data;
|
||||
if (type === "SOLVE_RESULT") {
|
||||
solveResult.value = payload;
|
||||
} else if (type === "SOLVE_ERROR") {
|
||||
// Error doesn't necessarily block execution, it just provides UI feedback
|
||||
solveError.value = payload;
|
||||
} else if (type === "INIT_DONE") {
|
||||
isSolverReady.value = true;
|
||||
} else if (type === "ERROR") {
|
||||
console.error("Solver Worker Error:", payload);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -39,6 +66,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 } });
|
||||
};
|
||||
@@ -47,14 +81,29 @@ export function useCube() {
|
||||
worker.postMessage({ type: "VALIDATE" });
|
||||
};
|
||||
|
||||
const solve = (solverType, cubeState) => {
|
||||
solveResult.value = null;
|
||||
solveError.value = null;
|
||||
solverWorker.postMessage({
|
||||
type: "SOLVE",
|
||||
payload: { solverType, cubeState },
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
cubies: computed(() => cubies.value),
|
||||
deepCubeState: computed(() => deepCubeState.value),
|
||||
isReady: computed(() => isReady.value),
|
||||
isSolverReady: computed(() => isSolverReady.value),
|
||||
validationResult: computed(() => validationResult.value),
|
||||
solveResult: computed(() => solveResult.value),
|
||||
solveError: computed(() => solveError.value),
|
||||
initCube,
|
||||
rotateLayer,
|
||||
rotateSlice,
|
||||
turn,
|
||||
validate,
|
||||
solve,
|
||||
COLORS,
|
||||
FACES,
|
||||
};
|
||||
|
||||
@@ -6,20 +6,39 @@ try {
|
||||
if (stored !== null) {
|
||||
initialCubeTranslucent = stored === "true";
|
||||
}
|
||||
} catch (e) {}
|
||||
} catch (e) { }
|
||||
|
||||
// 0 = off, 1 = simple projections, 2 = advanced (animated layers)
|
||||
let initialProjectionMode = 0;
|
||||
try {
|
||||
const stored = localStorage.getItem("projectionMode");
|
||||
if (stored !== null) {
|
||||
initialProjectionMode = Math.min(2, Math.max(0, parseInt(stored, 10) || 0));
|
||||
}
|
||||
} catch (e) { }
|
||||
|
||||
const isCubeTranslucent = ref(initialCubeTranslucent);
|
||||
const projectionMode = ref(initialProjectionMode);
|
||||
|
||||
export function useSettings() {
|
||||
const toggleCubeTranslucent = () => {
|
||||
isCubeTranslucent.value = !isCubeTranslucent.value;
|
||||
try {
|
||||
localStorage.setItem("cubeTranslucent", String(isCubeTranslucent.value));
|
||||
} catch (e) {}
|
||||
} catch (e) { }
|
||||
};
|
||||
|
||||
const cycleProjectionMode = () => {
|
||||
projectionMode.value = (projectionMode.value + 1) % 3;
|
||||
try {
|
||||
localStorage.setItem("projectionMode", String(projectionMode.value));
|
||||
} catch (e) { }
|
||||
};
|
||||
|
||||
return {
|
||||
isCubeTranslucent,
|
||||
toggleCubeTranslucent,
|
||||
projectionMode,
|
||||
cycleProjectionMode,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export const LAYER_ANIMATION_DURATION = 200;
|
||||
8
src/config/settings.js
Normal file
8
src/config/settings.js
Normal file
@@ -0,0 +1,8 @@
|
||||
|
||||
export const LAYER_ANIMATION_DURATION = 200;
|
||||
|
||||
export const MIDDLE_SLICES_ENABLED = false;
|
||||
|
||||
// Distance of rear face projections from cube center (in cube-size units)
|
||||
// 1.0 = one cube width, 0.5 = half cube width
|
||||
export const REAR_FACE_DISTANCE = 1.0;
|
||||
@@ -42,6 +42,14 @@
|
||||
--button-active-shadow: 0 0 20px rgba(79, 172, 254, 0.4);
|
||||
--cube-edge-color: #333333;
|
||||
--title-gradient: linear-gradient(45deg, #00f2fe, #4facfe);
|
||||
|
||||
/* Cube sticker colors */
|
||||
--sticker-white: #e0e0e0;
|
||||
--sticker-yellow: #ffd500;
|
||||
--sticker-green: #009e60;
|
||||
--sticker-blue: #0051ba;
|
||||
--sticker-orange: #ff5800;
|
||||
--sticker-red: #c41e3a;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
@@ -81,6 +89,7 @@ a {
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
@@ -113,9 +122,11 @@ button {
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
@@ -191,9 +202,11 @@ button.btn-neon.icon-only {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
58
src/utils/cubeProjection.js
Normal file
58
src/utils/cubeProjection.js
Normal file
@@ -0,0 +1,58 @@
|
||||
// 3D geometry helpers for cube face/axis operations and screen projection
|
||||
|
||||
export const getFaceNormal = (face, FACES) => {
|
||||
const map = {
|
||||
[FACES.FRONT]: { x: 0, y: 0, z: 1 },
|
||||
[FACES.BACK]: { x: 0, y: 0, z: -1 },
|
||||
[FACES.RIGHT]: { x: 1, y: 0, z: 0 },
|
||||
[FACES.LEFT]: { x: -1, y: 0, z: 0 },
|
||||
[FACES.UP]: { x: 0, y: 1, z: 0 },
|
||||
[FACES.DOWN]: { x: 0, y: -1, z: 0 },
|
||||
};
|
||||
return map[face] || { x: 0, y: 0, z: 1 };
|
||||
};
|
||||
|
||||
// Which axes can this face physically rotate along?
|
||||
export const getAllowedAxes = (face, FACES) => {
|
||||
switch (face) {
|
||||
case FACES.FRONT:
|
||||
case FACES.BACK:
|
||||
return ["x", "y"];
|
||||
case FACES.RIGHT:
|
||||
case FACES.LEFT:
|
||||
return ["z", "y"];
|
||||
case FACES.UP:
|
||||
case FACES.DOWN:
|
||||
return ["x", "z"];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
export const getAxisVector = (axis) => {
|
||||
if (axis === "x") return { x: 1, y: 0, z: 0 };
|
||||
if (axis === "y") return { x: 0, y: 1, z: 0 };
|
||||
if (axis === "z") return { x: 0, y: 0, z: 1 };
|
||||
return { x: 0, y: 0, z: 0 };
|
||||
};
|
||||
|
||||
// Cross product: a × b
|
||||
export const cross = (a, b) => ({
|
||||
x: a.y * b.z - a.z * b.y,
|
||||
y: a.z * b.x - a.x * b.z,
|
||||
z: a.x * b.y - a.y * b.x,
|
||||
});
|
||||
|
||||
// Project 3D vector to 2D screen space using a viewMatrix (column-major 4x4).
|
||||
// Input v is in Right-Handed Math Coordinates (Y up).
|
||||
// viewMatrix operates in CSS Coordinates (Y down).
|
||||
// Applies T⁻¹ * M * T to maintain correct projection chirality.
|
||||
export const project = (v, viewMatrix) => {
|
||||
const m = viewMatrix;
|
||||
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;
|
||||
|
||||
return { x, y: mathY };
|
||||
};
|
||||
23
src/utils/easing.js
Normal file
23
src/utils/easing.js
Normal file
@@ -0,0 +1,23 @@
|
||||
// Animation easing functions and their derivatives
|
||||
|
||||
export const easeInOutCubic = (t) => {
|
||||
if (t < 0.5) return 4 * t * t * t;
|
||||
return 1 - Math.pow(-2 * t + 2, 3) / 2;
|
||||
};
|
||||
|
||||
// Derivative of standard easeInOutCubic for instantaneous velocity calculations
|
||||
export const easeInOutCubicDerivative = (t) => {
|
||||
if (t < 0.5) return 12 * t * t;
|
||||
return 3 * Math.pow(-2 * t + 2, 2);
|
||||
};
|
||||
|
||||
// Custom easing function that preserves initial velocity v₀
|
||||
// The polynomial is P(t) = (v₀ - 2)t³ + (3 - 2v₀)t² + v₀t
|
||||
export const cubicEaseWithInitialVelocity = (t, v0) => {
|
||||
return (v0 - 2) * t * t * t + (3 - 2 * v0) * t * t + v0 * t;
|
||||
};
|
||||
|
||||
// Derivative of the custom easing function
|
||||
export const cubicEaseWithInitialVelocityDerivative = (t, v0) => {
|
||||
return 3 * (v0 - 2) * t * t + 2 * (3 - 2 * v0) * t + v0;
|
||||
};
|
||||
133
src/utils/matrix.js
Normal file
133
src/utils/matrix.js
Normal file
@@ -0,0 +1,133 @@
|
||||
// 4x4 matrix operations for 3D transformations (column-major, CSS/WebGL convention)
|
||||
|
||||
export const identityMatrix = () => [
|
||||
1, 0, 0, 0,
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 0, 0, 1
|
||||
];
|
||||
|
||||
export const rotateXMatrix = (deg) => {
|
||||
const rad = (deg * Math.PI) / 180;
|
||||
const c = Math.cos(rad);
|
||||
const s = Math.sin(rad);
|
||||
return [
|
||||
1, 0, 0, 0,
|
||||
0, c, s, 0,
|
||||
0, -s, c, 0,
|
||||
0, 0, 0, 1
|
||||
];
|
||||
};
|
||||
|
||||
export const rotateYMatrix = (deg) => {
|
||||
const rad = (deg * Math.PI) / 180;
|
||||
const c = Math.cos(rad);
|
||||
const s = Math.sin(rad);
|
||||
return [
|
||||
c, 0, -s, 0,
|
||||
0, 1, 0, 0,
|
||||
s, 0, c, 0,
|
||||
0, 0, 0, 1
|
||||
];
|
||||
};
|
||||
|
||||
export 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
|
||||
];
|
||||
};
|
||||
|
||||
export const multiplyMatrices = (a, b) => {
|
||||
const result = new Array(16).fill(0);
|
||||
for (let r = 0; r < 4; r++) {
|
||||
for (let c = 0; c < 4; c++) {
|
||||
for (let k = 0; k < 4; k++) {
|
||||
result[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// --- Quaternion helpers for distortion-free rotation interpolation (SLERP) ---
|
||||
|
||||
export const matToQuat = (m) => {
|
||||
const trace = m[0] + m[5] + m[10];
|
||||
let w, x, y, z;
|
||||
if (trace > 0) {
|
||||
const s = 0.5 / Math.sqrt(trace + 1);
|
||||
w = 0.25 / s;
|
||||
x = (m[6] - m[9]) * s;
|
||||
y = (m[8] - m[2]) * s;
|
||||
z = (m[1] - m[4]) * s;
|
||||
} else if (m[0] > m[5] && m[0] > m[10]) {
|
||||
const s = 2 * Math.sqrt(1 + m[0] - m[5] - m[10]);
|
||||
w = (m[6] - m[9]) / s;
|
||||
x = 0.25 * s;
|
||||
y = (m[4] + m[1]) / s;
|
||||
z = (m[8] + m[2]) / s;
|
||||
} else if (m[5] > m[10]) {
|
||||
const s = 2 * Math.sqrt(1 + m[5] - m[0] - m[10]);
|
||||
w = (m[8] - m[2]) / s;
|
||||
x = (m[4] + m[1]) / s;
|
||||
y = 0.25 * s;
|
||||
z = (m[6] + m[9]) / s;
|
||||
} else {
|
||||
const s = 2 * Math.sqrt(1 + m[10] - m[0] - m[5]);
|
||||
w = (m[1] - m[4]) / s;
|
||||
x = (m[8] + m[2]) / s;
|
||||
y = (m[6] + m[9]) / s;
|
||||
z = 0.25 * s;
|
||||
}
|
||||
return { w, x, y, z };
|
||||
};
|
||||
|
||||
export const slerp = (q1, q2, t) => {
|
||||
let dot = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z;
|
||||
let q2n = q2;
|
||||
if (dot < 0) {
|
||||
q2n = { w: -q2.w, x: -q2.x, y: -q2.y, z: -q2.z };
|
||||
dot = -dot;
|
||||
}
|
||||
if (dot > 0.9995) {
|
||||
const len = Math.sqrt(
|
||||
(q1.w + t * (q2n.w - q1.w)) ** 2 + (q1.x + t * (q2n.x - q1.x)) ** 2 +
|
||||
(q1.y + t * (q2n.y - q1.y)) ** 2 + (q1.z + t * (q2n.z - q1.z)) ** 2
|
||||
);
|
||||
return {
|
||||
w: (q1.w + t * (q2n.w - q1.w)) / len,
|
||||
x: (q1.x + t * (q2n.x - q1.x)) / len,
|
||||
y: (q1.y + t * (q2n.y - q1.y)) / len,
|
||||
z: (q1.z + t * (q2n.z - q1.z)) / len,
|
||||
};
|
||||
}
|
||||
const theta = Math.acos(dot);
|
||||
const sinTheta = Math.sin(theta);
|
||||
const a = Math.sin((1 - t) * theta) / sinTheta;
|
||||
const b = Math.sin(t * theta) / sinTheta;
|
||||
return {
|
||||
w: a * q1.w + b * q2n.w,
|
||||
x: a * q1.x + b * q2n.x,
|
||||
y: a * q1.y + b * q2n.y,
|
||||
z: a * q1.z + b * q2n.z,
|
||||
};
|
||||
};
|
||||
|
||||
export const quatToMat = (q) => {
|
||||
const { w, x, y, z } = q;
|
||||
const xx = x * x, yy = y * y, zz = z * z;
|
||||
const xy = x * y, xz = x * z, yz = y * z;
|
||||
const wx = w * x, wy = w * y, wz = w * z;
|
||||
return [
|
||||
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
|
||||
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
|
||||
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
|
||||
0, 0, 0, 1,
|
||||
];
|
||||
};
|
||||
116
src/utils/moveMapping.js
Normal file
116
src/utils/moveMapping.js
Normal file
@@ -0,0 +1,116 @@
|
||||
// Move notation mapping between UI labels, internal logic axes, and solver output.
|
||||
// The UI coordinate system is rotated 90° around Y from internal coordinates.
|
||||
|
||||
// UI button key → internal base + modifier
|
||||
export const MOVE_MAP = {
|
||||
U: { base: "U", modifier: "" },
|
||||
"U-prime": { base: "U", modifier: "'" },
|
||||
U2: { base: "U", modifier: "2" },
|
||||
|
||||
D: { base: "D", modifier: "" },
|
||||
"D-prime": { base: "D", modifier: "'" },
|
||||
D2: { base: "D", modifier: "2" },
|
||||
|
||||
L: { base: "B", modifier: "" },
|
||||
"L-prime": { base: "B", modifier: "'" },
|
||||
L2: { base: "B", modifier: "2" },
|
||||
|
||||
R: { base: "F", modifier: "" },
|
||||
"R-prime": { base: "F", modifier: "'" },
|
||||
R2: { base: "F", modifier: "2" },
|
||||
|
||||
F: { base: "L", modifier: "" },
|
||||
"F-prime": { base: "L", modifier: "'" },
|
||||
F2: { base: "L", modifier: "2" },
|
||||
|
||||
B: { base: "R", modifier: "" },
|
||||
"B-prime": { base: "R", modifier: "'" },
|
||||
B2: { base: "R", modifier: "2" },
|
||||
};
|
||||
|
||||
// Internal face name → UI face name
|
||||
export const INTERNAL_TO_UI = {
|
||||
'F': 'R', 'B': 'L', 'R': 'B', 'L': 'F',
|
||||
'U': 'U', 'D': 'D',
|
||||
'M': 'M', 'E': 'E', 'S': 'S',
|
||||
};
|
||||
|
||||
// Internal base → axis and layer index
|
||||
export const getAxisIndexForBase = (base) => {
|
||||
if (base === "U") return { axis: "y", index: 1 };
|
||||
if (base === "D") return { axis: "y", index: -1 };
|
||||
if (base === "L") return { axis: "x", index: -1 };
|
||||
if (base === "R") return { axis: "x", index: 1 };
|
||||
if (base === "F") return { axis: "z", index: 1 };
|
||||
if (base === "B") return { axis: "z", index: -1 };
|
||||
return { axis: "y", index: 0 };
|
||||
};
|
||||
|
||||
// Mathematical positive rotation direction (Right-Hand Rule)
|
||||
export const getMathDirectionForBase = (base) => {
|
||||
if (['R', 'U', 'F', 'S'].includes(base)) return -1;
|
||||
if (['L', 'D', 'B', 'M', 'E'].includes(base)) return 1;
|
||||
return 1;
|
||||
};
|
||||
|
||||
// Convert axis/index/direction to a standard Rubik's notation label (UI-facing)
|
||||
export const getDragMoveLabel = (axis, index, direction, count) => {
|
||||
const OUTER_MAP = {
|
||||
'y_1': { base: 'U', dir: -1 },
|
||||
'y_-1': { base: 'D', dir: 1 },
|
||||
'x_1': { base: 'R', dir: -1 },
|
||||
'x_-1': { base: 'L', dir: 1 },
|
||||
'z_1': { base: 'F', dir: -1 },
|
||||
'z_-1': { base: 'B', dir: 1 },
|
||||
};
|
||||
const SLICE_MAP = {
|
||||
'x_0': { base: 'M', dir: 1 },
|
||||
'y_0': { base: 'E', dir: 1 },
|
||||
'z_0': { base: 'S', dir: -1 },
|
||||
};
|
||||
|
||||
const key = `${axis}_${index}`;
|
||||
const mapping = OUTER_MAP[key] || SLICE_MAP[key];
|
||||
if (!mapping) return null;
|
||||
|
||||
const effective = direction * mapping.dir;
|
||||
const stepsMod = ((count % 4) + 4) % 4;
|
||||
if (stepsMod === 0) return null;
|
||||
|
||||
let modifier = '';
|
||||
if (stepsMod === 2) {
|
||||
modifier = '2';
|
||||
} else if ((effective > 0 && stepsMod === 1) || (effective < 0 && stepsMod === 3)) {
|
||||
modifier = '';
|
||||
} else {
|
||||
modifier = "'";
|
||||
}
|
||||
|
||||
const uiBase = INTERNAL_TO_UI[mapping.base] || mapping.base;
|
||||
return uiBase + modifier;
|
||||
};
|
||||
|
||||
// Coerce rotation step count to match a desired sign direction
|
||||
export const coerceStepsToSign = (steps, sign) => {
|
||||
if (steps === 0) return 0;
|
||||
const mod = ((steps % 4) + 4) % 4;
|
||||
if (sign < 0) {
|
||||
if (mod === 1) return -3;
|
||||
if (mod === 2) return -2;
|
||||
return -1;
|
||||
}
|
||||
if (mod === 1) return 1;
|
||||
if (mod === 2) return 2;
|
||||
return 3;
|
||||
};
|
||||
|
||||
// Format a move label from a display base and step count
|
||||
export const formatMoveLabel = (displayBase, steps) => {
|
||||
const stepsMod = ((steps % 4) + 4) % 4;
|
||||
if (stepsMod === 0) return '';
|
||||
let modifier = "";
|
||||
if (stepsMod === 1) modifier = "'";
|
||||
else if (stepsMod === 2) modifier = "2";
|
||||
else if (stepsMod === 3) modifier = "";
|
||||
return displayBase + (modifier === "'" ? "'" : modifier === "2" ? "2" : "");
|
||||
};
|
||||
@@ -1,10 +1,11 @@
|
||||
import Cube from "cubejs";
|
||||
|
||||
// Initialize the core pruning tables on module load
|
||||
Cube.initSolver();
|
||||
import { DeepCube, CORNERS, EDGES } from "../DeepCube.js";
|
||||
|
||||
export class KociembaSolver {
|
||||
static init() {
|
||||
Cube.initSolver();
|
||||
}
|
||||
constructor(cube) {
|
||||
this.cube = cube.clone();
|
||||
}
|
||||
|
||||
31
src/utils/toastHelper.js
Normal file
31
src/utils/toastHelper.js
Normal file
@@ -0,0 +1,31 @@
|
||||
import Toastify from "toastify-js";
|
||||
|
||||
const ICONS = {
|
||||
info: '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
|
||||
alert: '<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',
|
||||
check: '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/>'
|
||||
};
|
||||
|
||||
export const createToastHtml = (text, iconName = 'info') => {
|
||||
const innerHtml = ICONS[iconName] || ICONS.info;
|
||||
const size = 26; // Powiększona ikona
|
||||
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-${iconName}">${innerHtml}</svg>`;
|
||||
|
||||
return `<div style="display: flex; align-items: center; gap: 8px;">
|
||||
${svg}
|
||||
<span>${text}</span>
|
||||
</div>`;
|
||||
};
|
||||
|
||||
export const showToast = (text, iconName = 'info', options = {}) => {
|
||||
Toastify({
|
||||
text: createToastHtml(text, iconName),
|
||||
escapeMarkup: false,
|
||||
duration: 3000,
|
||||
gravity: "top",
|
||||
position: "center",
|
||||
stopOnFocus: true,
|
||||
...options
|
||||
}).showToast();
|
||||
};
|
||||
36
src/utils/tokenReducer.js
Normal file
36
src/utils/tokenReducer.js
Normal file
@@ -0,0 +1,36 @@
|
||||
// Reduces consecutive same-face moves into their net rotation.
|
||||
// Agnostic to move names — works with any single-letter move notation.
|
||||
|
||||
const EMPTY = 'E';
|
||||
const MODS = [EMPTY, '', '2', "'"];
|
||||
|
||||
const reduceGroup = (group) => {
|
||||
const sum = group.reduce((acc, curr) => acc + MODS.indexOf(curr.mod), 0);
|
||||
const mod = MODS[sum % 4];
|
||||
return mod === EMPTY ? '' : `${group[0].name}${mod}`;
|
||||
};
|
||||
|
||||
export const parseToken = (token) => {
|
||||
const match = token.match(/^(\w)(.?)$/);
|
||||
if (!match) return null;
|
||||
return { token, name: match[1], mod: match[2] };
|
||||
};
|
||||
|
||||
export const tokenReducer = (tokens) => {
|
||||
const parsed = tokens.map(parseToken).filter(Boolean);
|
||||
const desc = [];
|
||||
const res = [];
|
||||
let lastPos = 0;
|
||||
|
||||
for (let i = 0; i <= parsed.length; i++) {
|
||||
if (i === parsed.length || (i > lastPos && parsed[i].name !== parsed[lastPos].name)) {
|
||||
const group = parsed.slice(lastPos, i);
|
||||
const reduced = reduceGroup(group);
|
||||
desc.push({ reduced, group });
|
||||
if (reduced !== '') res.push(reduced);
|
||||
lastPos = i;
|
||||
}
|
||||
}
|
||||
|
||||
return { desc, tokens: res };
|
||||
};
|
||||
@@ -3,15 +3,22 @@ import { RubiksJSModel } from "../utils/CubeLogicAdapter.js";
|
||||
const cube = new RubiksJSModel();
|
||||
|
||||
|
||||
|
||||
// Helper to send state update
|
||||
const sendUpdate = () => {
|
||||
try {
|
||||
const cubies = cube.toCubies();
|
||||
// console.log('[Worker] Sending update with cubies:', cubies.length);
|
||||
const { cp, co, ep, eo } = cube.state;
|
||||
postMessage({
|
||||
type: "STATE_UPDATE",
|
||||
payload: {
|
||||
cubies,
|
||||
deepCubeState: {
|
||||
cp: [...cp],
|
||||
co: [...co],
|
||||
ep: [...ep],
|
||||
eo: [...eo],
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -37,6 +44,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);
|
||||
@@ -51,5 +65,7 @@ self.onmessage = (e) => {
|
||||
payload: { valid: validation.valid, errors: validation.errors },
|
||||
});
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
58
src/workers/Solver.worker.js
Normal file
58
src/workers/Solver.worker.js
Normal file
@@ -0,0 +1,58 @@
|
||||
import { DeepCube } from "../utils/DeepCube.js";
|
||||
import { KociembaSolver } from "../utils/solvers/KociembaSolver.js";
|
||||
import { BeginnerSolver } from "../utils/solvers/BeginnerSolver.js";
|
||||
|
||||
let isKociembaReady = false;
|
||||
|
||||
// Defer heavy initialization to allow the worker to be responsive initially
|
||||
setTimeout(() => {
|
||||
console.log("[SolverWorker] Kociemba solver initialization");
|
||||
console.time("[SolverWorker] Kociemba solver initialized");
|
||||
KociembaSolver.init();
|
||||
console.timeEnd("[SolverWorker] Kociemba solver initialized");
|
||||
isKociembaReady = true;
|
||||
postMessage({ type: "INIT_DONE" });
|
||||
}, 50);
|
||||
|
||||
self.onmessage = (e) => {
|
||||
const { type, payload } = e.data;
|
||||
|
||||
if (type === "SOLVE") {
|
||||
const { solverType, cubeState } = payload;
|
||||
|
||||
if (solverType === "kociemba" && !isKociembaReady) {
|
||||
postMessage({ type: "SOLVE_ERROR", payload: "wait for initialize solver" });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Reconstruct DeepCube state from payload
|
||||
const dc = new DeepCube(
|
||||
new Int8Array(cubeState.cp),
|
||||
new Int8Array(cubeState.co),
|
||||
new Int8Array(cubeState.ep),
|
||||
new Int8Array(cubeState.eo)
|
||||
);
|
||||
|
||||
let solution = [];
|
||||
if (solverType === "kociemba") {
|
||||
const solver = new KociembaSolver(dc);
|
||||
solution = solver.solve();
|
||||
} else if (solverType === "beginner") {
|
||||
const solver = new BeginnerSolver(dc);
|
||||
solution = solver.solve();
|
||||
} else {
|
||||
throw new Error(`Unknown solver type: ${solverType}`);
|
||||
}
|
||||
|
||||
postMessage({
|
||||
type: "SOLVE_RESULT",
|
||||
payload: solution,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[SolverWorker] Solve error:", err);
|
||||
postMessage({ type: "SOLVE_ERROR", payload: err.message });
|
||||
postMessage({ type: "SOLVE_RESULT", payload: [] });
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,166 +0,0 @@
|
||||
import { Cube, FACES, COLORS } from "../src/utils/Cube.js";
|
||||
import assert from "assert";
|
||||
|
||||
console.log("Running Cube Integrity Tests...");
|
||||
|
||||
const cube = new Cube();
|
||||
|
||||
// Helper: Count colors on all faces
|
||||
const countColors = () => {
|
||||
const counts = {
|
||||
[COLORS.WHITE]: 0,
|
||||
[COLORS.YELLOW]: 0,
|
||||
[COLORS.ORANGE]: 0,
|
||||
[COLORS.RED]: 0,
|
||||
[COLORS.GREEN]: 0,
|
||||
[COLORS.BLUE]: 0,
|
||||
[COLORS.BLACK]: 0, // Should be ignored or internal
|
||||
};
|
||||
|
||||
cube.cubies.forEach((cubie) => {
|
||||
Object.values(cubie.faces).forEach((color) => {
|
||||
if (counts[color] !== undefined) {
|
||||
counts[color]++;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return counts;
|
||||
};
|
||||
|
||||
// Helper: Verify solved state counts
|
||||
const verifyCounts = (counts) => {
|
||||
// Each face has 9 stickers. 6 faces.
|
||||
// 9 * 6 = 54 colored stickers.
|
||||
// 27 cubies * 6 faces = 162 total faces.
|
||||
// 162 - 54 = 108 black faces (internal).
|
||||
|
||||
assert.strictEqual(counts[COLORS.WHITE], 9, "White count should be 9");
|
||||
assert.strictEqual(counts[COLORS.YELLOW], 9, "Yellow count should be 9");
|
||||
assert.strictEqual(counts[COLORS.ORANGE], 9, "Orange count should be 9");
|
||||
assert.strictEqual(counts[COLORS.RED], 9, "Red count should be 9");
|
||||
assert.strictEqual(counts[COLORS.GREEN], 9, "Green count should be 9");
|
||||
assert.strictEqual(counts[COLORS.BLUE], 9, "Blue count should be 9");
|
||||
};
|
||||
|
||||
// Helper: Verify piece integrity
|
||||
// Corners: 8 corners, each has 3 colors.
|
||||
// Edges: 12 edges, each has 2 colors.
|
||||
// Centers: 6 centers, each has 1 color.
|
||||
// Core: 1 core, 0 colors.
|
||||
const verifyPieceTypes = () => {
|
||||
let corners = 0;
|
||||
let edges = 0;
|
||||
let centers = 0;
|
||||
let cores = 0;
|
||||
|
||||
cube.cubies.forEach((cubie) => {
|
||||
const coloredFaces = Object.values(cubie.faces).filter(
|
||||
(c) => c !== COLORS.BLACK,
|
||||
).length;
|
||||
if (coloredFaces === 3) corners++;
|
||||
else if (coloredFaces === 2) edges++;
|
||||
else if (coloredFaces === 1) centers++;
|
||||
else if (coloredFaces === 0) cores++;
|
||||
else
|
||||
assert.fail(
|
||||
`Invalid cubie with ${coloredFaces} colors at (${cubie.x},${cubie.y},${cubie.z})`,
|
||||
);
|
||||
});
|
||||
|
||||
assert.strictEqual(corners, 8, "Should have 8 corners");
|
||||
assert.strictEqual(edges, 12, "Should have 12 edges");
|
||||
assert.strictEqual(centers, 6, "Should have 6 centers");
|
||||
assert.strictEqual(cores, 1, "Should have 1 core");
|
||||
};
|
||||
|
||||
// Helper: Verify specific relative positions of centers (they never change relative to each other)
|
||||
// Up (White) opposite Down (Yellow)
|
||||
// Front (Green) opposite Back (Blue)
|
||||
// Left (Orange) opposite Right (Red)
|
||||
const verifyCenters = () => {
|
||||
const centers = cube.cubies.filter(
|
||||
(c) =>
|
||||
Object.values(c.faces).filter((f) => f !== COLORS.BLACK).length === 1,
|
||||
);
|
||||
|
||||
// Find center by color
|
||||
const findCenter = (color) =>
|
||||
centers.find((c) => Object.values(c.faces).includes(color));
|
||||
|
||||
const white = findCenter(COLORS.WHITE);
|
||||
const yellow = findCenter(COLORS.YELLOW);
|
||||
const green = findCenter(COLORS.GREEN);
|
||||
const blue = findCenter(COLORS.BLUE);
|
||||
const orange = findCenter(COLORS.ORANGE);
|
||||
const red = findCenter(COLORS.RED);
|
||||
|
||||
// Check opposites
|
||||
// Distance between opposites should be 2 (e.g. y=1 and y=-1)
|
||||
// And they should be on same axis
|
||||
|
||||
// Note: After rotations, x/y/z coordinates change.
|
||||
// But relative vectors should hold?
|
||||
// Actually, centers DO rotate around the core.
|
||||
// But White is always opposite Yellow.
|
||||
// So vector(White) + vector(Yellow) == (0,0,0).
|
||||
|
||||
const checkOpposite = (c1, c2, name) => {
|
||||
assert.strictEqual(c1.x + c2.x, 0, `${name} X mismatch`);
|
||||
assert.strictEqual(c1.y + c2.y, 0, `${name} Y mismatch`);
|
||||
assert.strictEqual(c1.z + c2.z, 0, `${name} Z mismatch`);
|
||||
};
|
||||
|
||||
checkOpposite(white, yellow, "White-Yellow");
|
||||
checkOpposite(green, blue, "Green-Blue");
|
||||
checkOpposite(orange, red, "Orange-Red");
|
||||
};
|
||||
|
||||
// --- Test Execution ---
|
||||
|
||||
// 1. Initial State
|
||||
console.log("Test 1: Initial State Integrity");
|
||||
verifyCounts(countColors());
|
||||
verifyPieceTypes();
|
||||
verifyCenters();
|
||||
console.log("PASS Initial State");
|
||||
|
||||
// 2. Single Rotation (R)
|
||||
console.log("Test 2: Single Rotation (R)");
|
||||
cube.rotateLayer("x", 1, -1); // R
|
||||
verifyCounts(countColors());
|
||||
verifyPieceTypes();
|
||||
verifyCenters();
|
||||
console.log("PASS Single Rotation");
|
||||
|
||||
// 3. Multiple Rotations (R U R' U')
|
||||
console.log("Test 3: Sexy Move (R U R' U')");
|
||||
cube.reset();
|
||||
cube.move("R");
|
||||
cube.move("U");
|
||||
cube.move("R'");
|
||||
cube.move("U'");
|
||||
verifyCounts(countColors());
|
||||
verifyPieceTypes();
|
||||
verifyCenters();
|
||||
console.log("PASS Sexy Move");
|
||||
|
||||
// 4. Random Rotations (Fuzzing)
|
||||
console.log("Test 4: 100 Random Moves");
|
||||
cube.reset();
|
||||
const axes = ["x", "y", "z"];
|
||||
const indices = [-1, 0, 1];
|
||||
const dirs = [1, -1];
|
||||
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const axis = axes[Math.floor(Math.random() * axes.length)];
|
||||
const index = indices[Math.floor(Math.random() * indices.length)];
|
||||
const dir = dirs[Math.floor(Math.random() * dirs.length)];
|
||||
cube.rotateLayer(axis, index, dir);
|
||||
}
|
||||
verifyCounts(countColors());
|
||||
verifyPieceTypes();
|
||||
verifyCenters();
|
||||
console.log("PASS 100 Random Moves");
|
||||
|
||||
console.log("ALL INTEGRITY TESTS PASSED");
|
||||
@@ -1,117 +0,0 @@
|
||||
import { Cube, FACES, COLORS } from "../src/utils/Cube.js";
|
||||
import assert from "assert";
|
||||
|
||||
console.log("Running Cube Logic Tests...");
|
||||
|
||||
const cube = new Cube();
|
||||
|
||||
// Helper to check a specific face color at a position
|
||||
const checkFace = (x, y, z, face, expectedColor, message) => {
|
||||
const cubie = cube.cubies.find((c) => c.x === x && c.y === y && c.z === z);
|
||||
if (!cubie) {
|
||||
console.error(`Cubie not found at ${x}, ${y}, ${z}`);
|
||||
return false;
|
||||
}
|
||||
const color = cubie.faces[face];
|
||||
if (color !== expectedColor) {
|
||||
console.error(
|
||||
`FAIL: ${message}. Expected ${expectedColor} at ${face} of (${x},${y},${z}), got ${color}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Test 1: Initial State
|
||||
console.log("Test 1: Initial State");
|
||||
// Top-Front-Right corner (1, 1, 1) should have Up=White, Front=Green, Right=Red
|
||||
checkFace(1, 1, 1, FACES.UP, COLORS.WHITE, "Initial Top-Right-Front UP");
|
||||
checkFace(1, 1, 1, FACES.FRONT, COLORS.GREEN, "Initial Top-Right-Front FRONT");
|
||||
checkFace(1, 1, 1, FACES.RIGHT, COLORS.RED, "Initial Top-Right-Front RIGHT");
|
||||
|
||||
// Test 2: Rotate Right Face (R) -> Axis X, index 1, direction -1 (based on previous mapping)
|
||||
// Wait, let's test `rotateLayer` directly first with axis 'x'.
|
||||
// Axis X Positive Rotation (direction 1).
|
||||
// Up (y=1) -> Front (z=1).
|
||||
// The cubie at (1, 1, 1) (Top-Front-Right)
|
||||
// Should move to (1, 0, 1)? No.
|
||||
// (x, y, z) -> (x, -z, y).
|
||||
// (1, 1, 1) -> (1, -1, 1). (Bottom-Front-Right).
|
||||
// Let's trace the color.
|
||||
// The White color was on UP.
|
||||
// The cubie moves to Bottom-Front.
|
||||
// The UP face of the cubie now points FRONT.
|
||||
// So the cubie at (1, -1, 1) should have FRONT = WHITE.
|
||||
|
||||
console.log("Test 2: Rotate X Axis +90 (Right Layer)");
|
||||
cube.rotateLayer("x", 1, 1);
|
||||
|
||||
// Cubie originally at (1, 1, 1) [White Up] moves to (1, -1, 1).
|
||||
// Check (1, -1, 1).
|
||||
// Its Front face should be White.
|
||||
const result1 = checkFace(
|
||||
1,
|
||||
-1,
|
||||
1,
|
||||
FACES.FRONT,
|
||||
COLORS.WHITE,
|
||||
"After X+90: Old Up(White) should be on Front",
|
||||
);
|
||||
|
||||
// Cubie originally at (1, 1, -1) [Blue Back, White Up] (Top-Back-Right)
|
||||
// (1, 1, -1) -> (1, 1, 1). (Top-Front-Right).
|
||||
// Wait. ny = -z = -(-1) = 1. nz = y = 1.
|
||||
// So Top-Back moves to Top-Front.
|
||||
// Its UP face (White) moves to FRONT?
|
||||
// No. The rotation is around X.
|
||||
// Top-Back (y=1, z=-1).
|
||||
// Rot +90 X: y->z, z->-y ? No.
|
||||
// ny = -z = 1. nz = y = 1.
|
||||
// New pos: (1, 1, 1).
|
||||
// The cubie moves from Top-Back to Top-Front.
|
||||
// Its Up face (White) stays Up?
|
||||
// No, the cubie rotates.
|
||||
// Up face rotates to Front?
|
||||
// Rotation around X axis.
|
||||
// Top (Y+) rotates to Front (Z+)?
|
||||
// Yes.
|
||||
// So the cubie at (1, 1, 1) (new position) should have FRONT = WHITE.
|
||||
const result2 = checkFace(
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
FACES.FRONT,
|
||||
COLORS.WHITE,
|
||||
"After X+90: Old Top-Back Up(White) should be on Front",
|
||||
);
|
||||
|
||||
if (result1 && result2) {
|
||||
console.log("PASS: X Axis Rotation Logic seems correct (if fixed)");
|
||||
} else {
|
||||
console.log("FAIL: X Axis Rotation Logic is broken");
|
||||
}
|
||||
|
||||
// Reset for Y test
|
||||
cube.reset();
|
||||
console.log("Test 3: Rotate Y Axis +90 (Top Layer)");
|
||||
// Top Layer (y=1).
|
||||
// Rotate Y+ (direction 1).
|
||||
// Front (z=1) -> Right (x=1).
|
||||
// Cubie at (0, 1, 1) (Front-Top-Center) [Green Front, White Up].
|
||||
// Moves to (1, 1, 0) (Right-Top-Center).
|
||||
// Its Front Face (Green) should move to Right Face.
|
||||
cube.rotateLayer("y", 1, 1);
|
||||
const resultY = checkFace(
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
FACES.RIGHT,
|
||||
COLORS.GREEN,
|
||||
"After Y+90: Old Front(Green) should be on Right",
|
||||
);
|
||||
|
||||
if (resultY) {
|
||||
console.log("PASS: Y Axis Rotation Logic seems correct");
|
||||
} else {
|
||||
console.log("FAIL: Y Axis Rotation Logic is broken");
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { Cube, FACES, COLORS } from "../src/utils/Cube.js";
|
||||
import assert from "assert";
|
||||
|
||||
console.log("Running Cube Matrix Rotation Tests...");
|
||||
|
||||
const cube = new Cube();
|
||||
|
||||
// Helper to check position and face
|
||||
const checkCubie = (origX, origY, origZ, newX, newY, newZ, faceCheck) => {
|
||||
const cubie = cube.cubies.find(
|
||||
(c) => c.x === newX && c.y === newY && c.z === newZ,
|
||||
);
|
||||
if (!cubie) {
|
||||
console.error(`FAIL: Cubie not found at ${newX}, ${newY}, ${newZ}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify it's the correct original cubie (tracking ID would be better, but position logic is enough if unique)
|
||||
// Let's assume we track a specific cubie.
|
||||
return true;
|
||||
};
|
||||
|
||||
// Test 1: Z-Axis Rotation (Front Face)
|
||||
// Front Face is z=1.
|
||||
// Top-Left (x=-1, y=1) -> Top-Right (x=1, y=1)?
|
||||
// Physical CW (Z-Axis): Up -> Right.
|
||||
// Top-Middle (0, 1) -> Right-Middle (1, 0).
|
||||
console.log("Test 1: Z-Axis CW (Front)");
|
||||
cube.reset();
|
||||
// Find Top-Middle of Front Face: (0, 1, 1). White Up, Green Front.
|
||||
const topMid = cube.cubies.find((c) => c.x === 0 && c.y === 1 && c.z === 1);
|
||||
assert.strictEqual(topMid.faces[FACES.UP], COLORS.WHITE);
|
||||
assert.strictEqual(topMid.faces[FACES.FRONT], COLORS.GREEN);
|
||||
|
||||
cube.rotateLayer("z", 1, -1); // CW (direction -1 in move(), but rotateLayer takes direction. Standard move F is direction -1?)
|
||||
// move('F') calls rotateLayer('z', 1, -1).
|
||||
// So let's test rotateLayer('z', 1, -1).
|
||||
|
||||
// Expect: (0, 1, 1) -> (1, 0, 1). (Right-Middle of Front).
|
||||
// Faces: Old Up (White) becomes Right?
|
||||
// Z-Axis CW: Up -> Right.
|
||||
// So new pos should have Right=White.
|
||||
// Old Front (Green) stays Front.
|
||||
const newPos = cube.cubies.find((c) => c.id === topMid.id);
|
||||
console.log(`Moved to: (${newPos.x}, ${newPos.y}, ${newPos.z})`);
|
||||
assert.strictEqual(newPos.x, 1);
|
||||
assert.strictEqual(newPos.y, 0);
|
||||
assert.strictEqual(newPos.z, 1);
|
||||
assert.strictEqual(newPos.faces[FACES.RIGHT], COLORS.WHITE);
|
||||
assert.strictEqual(newPos.faces[FACES.FRONT], COLORS.GREEN);
|
||||
console.log("PASS Z-Axis CW");
|
||||
|
||||
// Test 2: X-Axis Rotation (Right Face)
|
||||
// Right Face is x=1.
|
||||
// Top-Front (1, 1, 1) -> Top-Back (1, 1, -1)?
|
||||
// Physical CW (X-Axis): Up -> Front.
|
||||
// Top-Middle (1, 1, 0) -> Front-Middle (1, 0, 1).
|
||||
console.log("Test 2: X-Axis CW (Right)");
|
||||
cube.reset();
|
||||
// Find Top-Middle of Right Face: (1, 1, 0). White Up, Red Right.
|
||||
const rightTop = cube.cubies.find((c) => c.x === 1 && c.y === 1 && c.z === 0);
|
||||
|
||||
cube.rotateLayer("x", 1, -1); // CW (direction -1 for R in move()?)
|
||||
// move('R') calls rotateLayer('x', 1, -1).
|
||||
// So let's test -1.
|
||||
|
||||
// Expect: (1, 1, 0) -> (1, 0, -1).
|
||||
// Faces: Old Up (White) becomes Back?
|
||||
// X-Axis CW (Right Face): Up -> Back.
|
||||
// So new pos should have Back=White.
|
||||
// Old Right (Red) stays Right.
|
||||
const newRightPos = cube.cubies.find((c) => c.id === rightTop.id);
|
||||
console.log(`Moved to: (${newRightPos.x}, ${newRightPos.y}, ${newRightPos.z})`);
|
||||
assert.strictEqual(newRightPos.x, 1);
|
||||
assert.strictEqual(newRightPos.y, 0);
|
||||
assert.strictEqual(newRightPos.z, -1);
|
||||
assert.strictEqual(newRightPos.faces[FACES.BACK], COLORS.WHITE);
|
||||
assert.strictEqual(newRightPos.faces[FACES.RIGHT], COLORS.RED);
|
||||
console.log("PASS X-Axis CW");
|
||||
|
||||
// Test 3: Y-Axis Rotation (Up Face)
|
||||
// Up Face is y=1.
|
||||
// Front-Middle (0, 1, 1) -> Left-Middle (-1, 1, 0).
|
||||
// Physical CW (Y-Axis): Front -> Left.
|
||||
// Wait. move('U') calls rotateLayer('y', 1, -1).
|
||||
// Standard U is CW. Y-Axis direction?
|
||||
// move('U'): dir = -1.
|
||||
console.log("Test 3: Y-Axis CW (Up)");
|
||||
cube.reset();
|
||||
// Find Front-Middle of Up Face: (0, 1, 1). Green Front, White Up.
|
||||
const upFront = cube.cubies.find((c) => c.x === 0 && c.y === 1 && c.z === 1);
|
||||
|
||||
cube.rotateLayer("y", 1, -1); // CW (direction -1).
|
||||
|
||||
// Expect: (0, 1, 1) -> (-1, 1, 0). (Left-Middle).
|
||||
// Faces: Old Front (Green) becomes Left?
|
||||
// Y-Axis CW (U): Front -> Left.
|
||||
// So new pos should have Left=Green.
|
||||
// Old Up (White) stays Up.
|
||||
const newUpPos = cube.cubies.find((c) => c.id === upFront.id);
|
||||
console.log(`Moved to: (${newUpPos.x}, ${newUpPos.y}, ${newUpPos.z})`);
|
||||
assert.strictEqual(newUpPos.x, -1);
|
||||
assert.strictEqual(newUpPos.y, 1);
|
||||
assert.strictEqual(newUpPos.z, 0);
|
||||
assert.strictEqual(newUpPos.faces[FACES.LEFT], COLORS.GREEN);
|
||||
assert.strictEqual(newUpPos.faces[FACES.UP], COLORS.WHITE);
|
||||
console.log("PASS Y-Axis CW");
|
||||
70
test/tokenReducer.test.js
Normal file
70
test/tokenReducer.test.js
Normal file
@@ -0,0 +1,70 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { tokenReducer, parseToken } from '../src/utils/tokenReducer.js';
|
||||
|
||||
describe('parseToken', () => {
|
||||
it('parses simple move', () => {
|
||||
expect(parseToken('D')).toEqual({ token: 'D', name: 'D', mod: '' });
|
||||
});
|
||||
|
||||
it('parses prime move', () => {
|
||||
expect(parseToken("U'")).toEqual({ token: "U'", name: 'U', mod: "'" });
|
||||
});
|
||||
|
||||
it('parses double move', () => {
|
||||
expect(parseToken('R2')).toEqual({ token: 'R2', name: 'R', mod: '2' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('tokenReducer', () => {
|
||||
it('user example: mixed faces', () => {
|
||||
const result = tokenReducer(['D', 'U2', 'U2', 'B2', "B'", 'B2', "U'", 'U2']);
|
||||
expect(result.tokens).toEqual(['D', "B'", 'U']);
|
||||
});
|
||||
|
||||
it('cancellation: same move 4 times = identity', () => {
|
||||
expect(tokenReducer(['R', 'R', 'R', 'R']).tokens).toEqual([]);
|
||||
});
|
||||
|
||||
it('cancellation: move + inverse = identity', () => {
|
||||
expect(tokenReducer(["F'", 'F']).tokens).toEqual([]);
|
||||
});
|
||||
|
||||
it('cancellation: double move twice = identity', () => {
|
||||
expect(tokenReducer(['D2', 'D2']).tokens).toEqual([]);
|
||||
});
|
||||
|
||||
it('merge: move + move = double', () => {
|
||||
expect(tokenReducer(['U', 'U']).tokens).toEqual(['U2']);
|
||||
});
|
||||
|
||||
it('merge: double + move = prime', () => {
|
||||
expect(tokenReducer(['R2', 'R']).tokens).toEqual(["R'"]);
|
||||
});
|
||||
|
||||
it('D2 D2 D\' D cancels to empty', () => {
|
||||
expect(tokenReducer(['D2', 'D2', "D'", 'D']).tokens).toEqual([]);
|
||||
});
|
||||
|
||||
it('preserves non-adjacent different faces', () => {
|
||||
expect(tokenReducer(['R', 'U', 'R']).tokens).toEqual(['R', 'U', 'R']);
|
||||
});
|
||||
|
||||
it('reduces only consecutive same-face groups', () => {
|
||||
expect(tokenReducer(['F', 'F', 'U', "U'"]).tokens).toEqual(['F2']);
|
||||
});
|
||||
|
||||
it('handles single move unchanged', () => {
|
||||
expect(tokenReducer(['B']).tokens).toEqual(['B']);
|
||||
});
|
||||
|
||||
it('handles empty input', () => {
|
||||
expect(tokenReducer([]).tokens).toEqual([]);
|
||||
});
|
||||
|
||||
it('desc contains group info', () => {
|
||||
const result = tokenReducer(['R', 'R']);
|
||||
expect(result.desc).toHaveLength(1);
|
||||
expect(result.desc[0].reduced).toBe('R2');
|
||||
expect(result.desc[0].group).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
21
test_beginner_solver.js
Normal file
21
test_beginner_solver.js
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user