feature: lyric smooth scrolling using new arch

todo: var `nextUpdate`'s assignment when backtracking
This commit is contained in:
alikia2x (寒寒) 2024-10-24 00:44:17 +08:00
parent 0c315972c1
commit 10c5ea3916
Signed by: alikia2x
GPG Key ID: 56209E0CCD8420C6
4 changed files with 197 additions and 181 deletions

View File

@ -7,7 +7,6 @@
export let line: ScriptItem;
export let index: number;
export let debugMode: Boolean;
export let initPos: LyricPos;
let ref: HTMLDivElement;
let time = 0;
@ -21,25 +20,18 @@
let springX: Spring | undefined = undefined;
let isCurrentLyric = false;
$: {
if (initPos) {
positionX = initPos.x;
positionY = initPos.y;
}
}
function updateY(timestamp: number) {
if (lastUpdateY === undefined) {
lastUpdateY = timestamp;
lastUpdateY = new Date().getTime();
}
if (springY === undefined) return;
time = (timestamp - lastUpdateY) / 1000;
time = (new Date().getTime() - lastUpdateY) / 1000;
springY.update(time);
positionY = springY.getCurrentPosition();
if (!springY.arrived()) {
requestAnimationFrame(updateY);
}
lastUpdateY = timestamp;
lastUpdateY = new Date().getTime();
}
function updateX(timestamp: number) {
@ -47,7 +39,7 @@
lastUpdateX = timestamp;
}
if (springX === undefined) return;
time = (timestamp - lastUpdateX) / 1000;
time = (new Date().getTime() - lastUpdateX) / 1000;
springX.update(time);
positionX = springX.getCurrentPosition();
if (!springX.arrived()) {
@ -77,16 +69,18 @@
};
export const update = (pos: LyricPos, delay: number = 0) => {
if (lastPosX === undefined) {
if (lastPosX === undefined || lastPosY === undefined) {
lastPosX = pos.x;
}
if (lastPosY === undefined) {
lastPosY = pos.y;
}
springY = createSpring(lastPosY, pos.y, 0.12, 0.7, delay);
springX = createSpring(lastPosX, pos.x, 0.12, 0.7, delay);
springY = createSpring(lastPosY, pos.y, .126, .85, delay);
springX = createSpring(lastPosX, pos.x, .126, .85, delay);
lastUpdateY = new Date().getTime();
lastUpdateX = new Date().getTime();
requestAnimationFrame(updateY);
requestAnimationFrame(updateX);
lastPosX = pos.x;
lastPosY = pos.y;
};
export const getInfo = () => {
@ -109,7 +103,7 @@
<div style="transform: translateY({positionY}px) translateX({positionX}px);" class="absolute z-50" bind:this={ref}>
{#if debugMode}
<span class="text-lg absolute -translate-y-7">Line idx: {index}</span>
<span class="text-lg absolute -translate-y-7">Line idx: {index}, duration: {(line.end - line.start).toFixed(3)}</span>
{/if}
<span class={`text-white text-5xl font-semibold text-shadow-lg ${!isCurrentLyric && 'opacity-50'} `}>
{line.text}

View File

@ -3,7 +3,8 @@
import { onMount } from 'svelte';
import type { ScriptItem } from '$lib/lyrics/type';
import LyricLine from './lyricLine.svelte';
import type { LyricPos } from './type';
import type { LyricLayout, LyricPos } from './type';
import createLyricsSearcher from '$lib/lyrics/lyricSearcher';
// Props
export let originalLyrics: LrcJsonData;
@ -14,23 +15,28 @@
let lyricLines: ScriptItem[] = [];
let lyricExists = false;
let lyricsContainer: HTMLDivElement | null;
let lyricLayouts: LyricLayout[] = [];
let debugMode = false;
let showTranslation = false;
// Exlpaination:
// The hot module reloading makes the each lyric component position to be re-initialized,
// which causes the lyrics are all at {x: 0, y: 0},
// instead of the value calculated in the initLyricComponents.
// So, we need to store the initial position of each lyric component and restore it.
let lyricComponentInitPos = Array<LyricPos>(lyricLines.length).fill({ x: 0, y: 0 });
// References to lyric elements
let lyricElements: HTMLDivElement[] = [];
let lyricComponents: LyricLine[] = [];
let lyricTopList: number[] = [];
let nextUpdate = 0;
const marginY = 48;
$: getLyricIndex = createLyricsSearcher(originalLyrics);
function initLyricComponents() {
initLyricTopList();
for (let i = 0; i < lyricComponents.length; i++) {
lyricComponents[i].init({ x: 0, y: lyricTopList[i] });
}
}
function initLyricTopList() {
let cumulativeHeight = 0;
const marginY = 48;
for (let i = 0; i < lyricLines.length; i++) {
const c = lyricComponents[i];
lyricElements.push(c.getRef());
@ -38,10 +44,37 @@
const elementHeight = e.getBoundingClientRect().height;
const elementTargetTop = cumulativeHeight;
cumulativeHeight += elementHeight + marginY;
lyricComponentInitPos[i] = { x: 0, y: elementTargetTop };
lyricTopList.push(elementTargetTop);
}
}
function computeLayout(progress: number) {
if (!originalLyrics.scripts) return;
const currentLyricIndex = getLyricIndex(progress);
const currentLyricDuration =
originalLyrics.scripts[currentLyricIndex].end - originalLyrics.scripts[currentLyricIndex].start;
const relativeOrigin = lyricTopList[currentLyricIndex];
for (let i = 0; i < lyricElements.length; i++) {
const currentLyricComponent = lyricComponents[i];
lyricLayouts[i] = {
blur: 0,
scale: 1,
pos: {
y: lyricTopList[i] - relativeOrigin,
x: 0
}
};
let delay = 0;
if (i <= currentLyricIndex) {
delay = 0;
} else {
delay = 0.013 + Math.min(Math.min(currentLyricDuration, 0.3), 0.075 * (i - currentLyricIndex));
}
currentLyricComponent.update({ x: 0, y: lyricTopList[i] - relativeOrigin }, delay);
}
nextUpdate = originalLyrics.scripts[currentLyricIndex + 1].start;
}
$: {
if (originalLyrics && originalLyrics.scripts) {
lyricExists = true;
@ -55,6 +88,12 @@
}
}
$: {
if (lyricsContainer && lyricComponents.length > 0) {
if (progress >= nextUpdate) computeLayout(progress);
}
}
onMount(() => {
// Initialize
if (localStorage.getItem('debugMode') == null) {
@ -72,13 +111,7 @@
bind:this={lyricsContainer}
>
{#each lyricLines as lyric, i}
<LyricLine
line={lyric}
index={i}
bind:this={lyricComponents[i]}
{debugMode}
initPos={lyricComponentInitPos[i]}
/>
<LyricLine line={lyric} index={i} bind:this={lyricComponents[i]} {debugMode} />
{/each}
<div class="relative w-full h-[50rem]"></div>
</div>

View File

@ -1,158 +1,147 @@
import { getVelocity } from "./derivative";
import { getVelocity } from './derivative';
/** MIT License github.com/pushkine/ */
export interface SpringParams {
mass: number; // = 1.0
damping: number; // = 10.0
stiffness: number; // = 100.0
soft: boolean; // = false
mass: number; // = 1.0
damping: number; // = 10.0
stiffness: number; // = 100.0
soft: boolean; // = false
}
type seconds = number;
export class Spring {
private currentPosition = 0;
private targetPosition = 0;
private currentTime = 0;
private params: Partial<SpringParams> = {};
private currentSolver: (t: seconds) => number;
private getV: (t: seconds) => number;
private getV2: (t: seconds) => number;
private queueParams:
| (Partial<SpringParams> & {
time: number;
})
| undefined;
private queuePosition:
| {
time: number;
position: number;
}
| undefined;
constructor(currentPosition = 0) {
this.targetPosition = currentPosition;
this.currentPosition = this.targetPosition;
this.currentSolver = () => this.targetPosition;
this.getV = () => 0;
this.getV2 = () => 0;
}
private resetSolver() {
const curV = this.getV(this.currentTime);
this.currentTime = 0;
this.currentSolver = solveSpring(
this.currentPosition,
curV,
this.targetPosition,
0,
this.params,
);
this.getV = getVelocity(this.currentSolver);
this.getV2 = getVelocity(this.getV);
}
arrived() {
return (
Math.abs(this.targetPosition - this.currentPosition) < 0.01 &&
this.getV(this.currentTime) < 0.01 &&
this.getV2(this.currentTime) < 0.01 &&
this.queueParams === undefined &&
this.queuePosition === undefined
);
}
setPosition(targetPosition: number) {
this.targetPosition = targetPosition;
this.currentPosition = targetPosition;
this.currentSolver = () => this.targetPosition;
this.getV = () => 0;
this.getV2 = () => 0;
}
update(delta = 0) {
this.currentTime += delta;
this.currentPosition = this.currentSolver(this.currentTime);
if (this.queueParams) {
this.queueParams.time -= delta;
if (this.queueParams.time <= 0) {
this.updateParams({
...this.queueParams,
});
}
}
if (this.queuePosition) {
this.queuePosition.time -= delta;
if (this.queuePosition.time <= 0) {
this.setTargetPosition(this.queuePosition.position);
}
}
if (this.arrived()) {
this.setPosition(this.targetPosition);
}
}
updateParams(params: Partial<SpringParams>, delay = 0) {
if (delay > 0) {
this.queueParams = {
...(this.queuePosition ?? {}),
...params,
time: delay,
};
} else {
this.queuePosition = undefined;
this.params = {
...this.params,
...params,
};
this.resetSolver();
}
}
setTargetPosition(targetPosition: number, delay = 0) {
if (delay > 0) {
this.queuePosition = {
...(this.queuePosition ?? {}),
position: targetPosition,
time: delay,
};
} else {
this.queuePosition = undefined;
this.targetPosition = targetPosition;
this.resetSolver();
}
}
getCurrentPosition() {
return this.currentPosition;
}
private currentPosition = 0;
private targetPosition = 0;
private currentTime = 0;
private params: Partial<SpringParams> = {};
private currentSolver: (t: seconds) => number;
private getV: (t: seconds) => number;
private getV2: (t: seconds) => number;
private queueParams:
| (Partial<SpringParams> & {
time: number;
})
| undefined;
private queuePosition:
| {
time: number;
position: number;
}
| undefined;
constructor(currentPosition = 0) {
this.targetPosition = currentPosition;
this.currentPosition = this.targetPosition;
this.currentSolver = () => this.targetPosition;
this.getV = () => 0;
this.getV2 = () => 0;
}
private resetSolver() {
const curV = this.getV(this.currentTime);
this.currentTime = 0;
this.currentSolver = solveSpring(this.currentPosition, curV, this.targetPosition, 0, this.params);
this.getV = getVelocity(this.currentSolver);
this.getV2 = getVelocity(this.getV);
}
arrived() {
return (
Math.abs(this.targetPosition - this.currentPosition) < 0.01 &&
this.getV(this.currentTime) < 0.01 &&
this.getV2(this.currentTime) < 0.01 &&
this.queueParams === undefined &&
this.queuePosition === undefined
);
}
setPosition(targetPosition: number) {
this.targetPosition = targetPosition;
this.currentPosition = targetPosition;
this.currentSolver = () => this.targetPosition;
this.getV = () => 0;
this.getV2 = () => 0;
}
update(delta = 0) {
this.currentTime += delta;
this.currentPosition = this.currentSolver(this.currentTime);
if (this.queueParams) {
this.queueParams.time -= delta;
if (this.queueParams.time <= 0) {
this.updateParams({
...this.queueParams
});
}
}
if (this.queuePosition) {
this.queuePosition.time -= delta;
if (this.queuePosition.time <= 0) {
this.setTargetPosition(this.queuePosition.position);
}
}
if (this.arrived()) {
this.setPosition(this.targetPosition);
}
}
updateParams(params: Partial<SpringParams>, delay = 0) {
if (delay > 0) {
this.queueParams = {
...(this.queuePosition ?? {}),
...params,
time: delay
};
} else {
this.queuePosition = undefined;
this.params = {
...this.params,
...params
};
this.resetSolver();
}
}
setTargetPosition(targetPosition: number, delay = 0) {
if (delay > 0) {
this.queuePosition = {
...(this.queuePosition ?? {}),
position: targetPosition,
time: delay
};
} else {
this.queuePosition = undefined;
this.targetPosition = targetPosition;
this.resetSolver();
}
}
getCurrentPosition() {
return this.currentPosition;
}
}
function solveSpring(
from: number,
velocity: number,
to: number,
delay: seconds = 0,
params?: Partial<SpringParams>,
from: number,
velocity: number,
to: number,
delay: seconds = 0,
params?: Partial<SpringParams>
): (t: seconds) => number {
const soft = params?.soft ?? false;
const stiffness = params?.stiffness ?? 100;
const damping = params?.damping ?? 10;
const mass = params?.mass ?? 1;
const delta = to - from;
if (soft || 1.0 <= damping / (2.0 * Math.sqrt(stiffness * mass))) {
const angular_frequency = -Math.sqrt(stiffness / mass);
const leftover = -angular_frequency * delta - velocity;
return (t: seconds) => {
t -= delay;
if (t < 0) return from;
return to - (delta + t * leftover) * Math.E ** (t * angular_frequency);
};
}
const damping_frequency = Math.sqrt(4.0 * mass * stiffness - damping ** 2.0);
const leftover =
(damping * delta - 2.0 * mass * velocity) / damping_frequency;
const dfm = (0.5 * damping_frequency) / mass;
const dm = -(0.5 * damping) / mass;
return (t: seconds) => {
t -= delay;
if (t < 0) return from;
return (
to -
(Math.cos(t * dfm) * delta + Math.sin(t * dfm) * leftover) *
Math.E ** (t * dm)
);
};
const soft = params?.soft ?? false;
const stiffness = params?.stiffness ?? 100;
const damping = params?.damping ?? 10;
const mass = params?.mass ?? 1;
const delta = to - from;
if (soft || 1.0 <= damping / (2.0 * Math.sqrt(stiffness * mass))) {
const angular_frequency = -Math.sqrt(stiffness / mass);
const leftover = -angular_frequency * delta - velocity;
return (t: seconds) => {
t -= delay;
if (t < 0) return from;
return to - (delta + t * leftover) * Math.E ** (t * angular_frequency);
};
}
const damping_frequency = Math.sqrt(4.0 * mass * stiffness - damping ** 2.0);
const leftover = (damping * delta - 2.0 * mass * velocity) / damping_frequency;
const dfm = (0.5 * damping_frequency) / mass;
const dm = -(0.5 * damping) / mass;
return (t: seconds) => {
t -= delay;
if (t < 0) return from;
return to - (Math.cos(t * dfm) * delta + Math.sin(t * dfm) * leftover) * Math.E ** (t * dm);
};
}

View File

@ -214,7 +214,7 @@
<NewLyrics {originalLyrics} progress={currentProgress} player={audioPlayer}/>
<Lyrics lyrics={lyricsText} {originalLyrics} progress={currentProgress} player={audioPlayer} class="hidden" />
<!-- <Lyrics lyrics={lyricsText} {originalLyrics} progress={currentProgress} player={audioPlayer} class="hidden" /> -->
<audio
bind:this={audioPlayer}