Files

390 lines
14 KiB
JavaScript

import * as THREE from '../vendor/three.module.min.js'
import { World, CX, CZ, CY, SEA, geometryOf } from './world.js'
import { makeAtlas, HOTBAR, BLOCKS, tileIndexOf } from './blocks.js'
import { createPlayer, stepPlayer, raycast, dirFromAngles, canPlaceAt, PLAYER_H, PLAYER_W } from './player.js'
const SAVE_KEY = 'mc.save.v3'
const PARAMS = new URLSearchParams(location.search)
const VIEW = Math.max(1, Math.min(8, Number(PARAMS.get('view') || 5)))
const app = document.getElementById('app')
const $ = (id) => document.getElementById(id)
// ---------- 渲染 ----------
let renderer
try {
renderer = new THREE.WebGLRenderer({ antialias: false, preserveDrawingBuffer: PARAMS.has('pb') })
} catch (e) {
try { renderer = new THREE.WebGLRenderer() } catch (e2) { renderer = null }
}
if (!renderer) {
const box = document.createElement('div')
box.className = 'nogl'
box.innerHTML = '<h1>这个浏览器没开 WebGL</h1><p>在设置里打开「硬件加速」,或者换 Chrome / Safari / Edge 最新版。</p>'
document.body.appendChild(box)
throw new Error('WebGL unavailable')
}
renderer.domElement.addEventListener('webglcontextlost', (e) => {
e.preventDefault()
const el = document.getElementById('toast')
if (el) { el.textContent = '显卡上下文丢了,刷新一下页面'; el.classList.add('show') }
})
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, Number(PARAMS.get('dpr') || 2)))
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.domElement.id = 'gl'
app.appendChild(renderer.domElement)
const SKY = 0x9fd4ff
const scene = new THREE.Scene()
scene.background = new THREE.Color(SKY)
scene.fog = new THREE.Fog(SKY, 55, 110)
const camera = new THREE.PerspectiveCamera(74, window.innerWidth / window.innerHeight, 0.08, 500)
camera.rotation.order = 'YXZ'
const atlasCanvas = makeAtlas()
const atlas = new THREE.CanvasTexture(atlasCanvas)
atlas.magFilter = THREE.NearestFilter
atlas.minFilter = THREE.NearestFilter
atlas.generateMipmaps = false
atlas.colorSpace = THREE.SRGBColorSpace
const solidMat = new THREE.MeshBasicMaterial({ map: atlas, vertexColors: true })
const waterMat = new THREE.MeshBasicMaterial({ map: atlas, vertexColors: true, transparent: true, opacity: 0.72, depthWrite: false })
// 选中方块的高亮框
const hlGeo = new THREE.BoxGeometry(1.002, 1.002, 1.002)
const hlMat = new THREE.LineBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.55 })
const highlight = new THREE.LineSegments(new THREE.EdgesGeometry(hlGeo), hlMat)
highlight.visible = false
scene.add(highlight)
window.__init = 'world-start'
// ---------- 世界 ----------
let save = null
try { save = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null') } catch {}
const seed = save?.seed ?? (Math.floor(Math.random() * 1e9) + 1)
const world = new World(seed)
if (save?.edits) for (const [k, id] of save.edits) world.edits.set(k, id)
world.applyEdits()
window.__init = 'world-created'
const meshes = new Map()
const keyOf = (cx, cz) => cx + ',' + cz
function rebuild(c) {
const { solid, water } = world.buildMesh(c)
let m = meshes.get(keyOf(c.cx, c.cz))
if (!m) { m = { solid: null, water: null }; meshes.set(keyOf(c.cx, c.cz), m) }
const put = (bucket, mat, old) => {
if (old) { scene.remove(old); old.geometry.dispose() }
if (!bucket.pos.length) return null
const mesh = new THREE.Mesh(geometryOf(bucket), mat)
mesh.position.set(c.cx * CX, 0, c.cz * CZ)
mesh.frustumCulled = true
scene.add(mesh)
return mesh
}
m.solid = put(solid, solidMat, m.solid)
m.water = put(water, waterMat, m.water)
c.dirty = false
}
function unloadFar(px, pz) {
const R = VIEW + 3
for (const [k, m] of meshes) {
const [cx, cz] = k.split(',').map(Number)
if (Math.abs(cx * CX + 8 - px) > R * CX || Math.abs(cz * CZ + 8 - pz) > R * CZ) {
if (m.solid) { scene.remove(m.solid); m.solid.geometry.dispose() }
if (m.water) { scene.remove(m.water); m.water.geometry.dispose() }
meshes.delete(k)
}
}
}
window.__init = 'chunk-helpers'
let buildQueue = []
function updateChunks(px, pz) {
const pcx = Math.floor(px / CX), pcz = Math.floor(pz / CZ)
buildQueue = []
for (let dz = -VIEW; dz <= VIEW; dz++) for (let dx = -VIEW; dx <= VIEW; dx++) {
if (dx * dx + dz * dz > (VIEW + 0.5) * (VIEW + 0.5)) continue
const cx = pcx + dx, cz = pcz + dz
const c = world.chunkAt(cx, cz)
if (!c.generated) world.generate(c)
if (c.dirty || !meshes.has(keyOf(cx, cz))) buildQueue.push([dx * dx + dz * dz, c])
}
buildQueue.sort((a, b) => a[0] - b[0])
}
function flushBuilds(budget = 2) {
let n = 0
while (buildQueue.length && n < budget) {
const [, c] = buildQueue.shift()
rebuild(c)
n++
}
}
window.__init = 'player'
// ---------- 玩家 ----------
const P = createPlayer({ x: save?.pos?.[0] ?? 8, y: save?.pos?.[1] ?? 40, z: save?.pos?.[2] ?? 8 })
P.yaw = save?.yaw ?? 0
P.pitch = save?.pitch ?? 0
const keys = new Set()
const input = { fwd: 0, side: 0, jump: false }
function readInput() {
return {
fwd: (keys.has('KeyW') ? 1 : 0) - (keys.has('KeyS') ? 1 : 0) + input.fwd,
side: (keys.has('KeyD') ? 1 : 0) - (keys.has('KeyA') ? 1 : 0) + input.side,
jump: keys.has('Space') || input.jump,
sprint: keys.has('ShiftLeft') || keys.has('ShiftRight'),
flyUp: keys.has('Space') || input.jump,
flyDown: keys.has('ControlLeft') || keys.has('KeyC'),
}
}
let bob = 0
function updatePlayer(dt) {
const r = stepPlayer(world, P, readInput(), dt)
bob = r.bob
if (P.pos.y < -30) { P.pos = { x: 8, y: 50, z: 8 }; P.vel = { x: 0, y: 0, z: 0 } }
camera.position.set(P.pos.x, P.pos.y + PLAYER_H * 0.86 + (r.moving && !P.fly ? bob : 0), P.pos.z)
camera.rotation.set(P.pitch, P.yaw, 0)
}
// ---------- 射线选取 ----------
let selected = 0
let target = null
function updateHighlight() {
const d = dirFromAngles(P.pitch, P.yaw)
target = raycast(world, camera.position, d)
if (!target) { highlight.visible = false; return }
highlight.visible = true
highlight.position.set(target.x + 0.5, target.y + 0.5, target.z + 0.5)
}
function breakBlock() {
if (!target) return
if (target.id === 11) { toast('基岩敲不动'); return }
world.set(target.x, target.y, target.z, 0)
world.mark(Math.floor(target.x / CX), Math.floor(target.z / CZ))
sfx('break')
}
function placeBlock() {
if (!target?.prev) return
const { x, y, z } = target.prev
if (!canPlaceAt(world, P, x, y, z)) return
world.set(x, y, z, HOTBAR[selected])
sfx('place')
}
// ---------- 声音(WebAudio 合成,不要素材) ----------
let actx = null
function sfx(kind) {
try {
actx = actx || new (window.AudioContext || window.webkitAudioContext)()
const o = actx.createOscillator(), g = actx.createGain()
o.type = kind === 'break' ? 'triangle' : 'sine'
o.frequency.value = kind === 'break' ? 190 : 320
g.gain.value = 0.06
o.connect(g); g.connect(actx.destination)
const t = actx.currentTime
o.frequency.exponentialRampToValueAtTime(kind === 'break' ? 90 : 220, t + 0.09)
g.gain.exponentialRampToValueAtTime(0.001, t + 0.12)
o.start(t); o.stop(t + 0.13)
} catch {}
}
// ---------- HUD ----------
const hotbarEl = $('hotbar')
function paintHotbar() {
hotbarEl.innerHTML = ''
HOTBAR.forEach((id, i) => {
const slot = document.createElement('button')
slot.className = 'slot' + (i === selected ? ' on' : '')
const name = BLOCKS[id].tiles[0]
const c = document.createElement('canvas')
c.width = c.height = 16
const ti = tileIndexOf(name)
const g2 = c.getContext('2d')
g2.imageSmoothingEnabled = false
g2.drawImage(atlasCanvas, (ti % 4) * 16, Math.floor(ti / 4) * 16, 16, 16, 0, 0, 16, 16)
slot.appendChild(c)
slot.append(document.createTextNode(String(i + 1)))
slot.title = BLOCKS[id].name
slot.onclick = () => { selected = i; paintHotbar() }
hotbarEl.appendChild(slot)
})
const cur = $('curBlock')
if (cur) cur.textContent = BLOCKS[HOTBAR[selected]].name
}
let toastTimer = 0
function toast(msg) {
const el = $('toast')
el.textContent = msg
el.classList.add('show')
clearTimeout(toastTimer)
toastTimer = setTimeout(() => el.classList.remove('show'), 1600)
}
// ---------- 输入 ----------
const canvas = renderer.domElement
let locked = false
canvas.addEventListener('click', () => { if (!isTouch && !locked) canvas.requestPointerLock() })
document.addEventListener('pointerlockchange', () => {
locked = document.pointerLockElement === canvas
$('pause').hidden = locked || isTouch
})
document.addEventListener('mousemove', (e) => {
if (!locked) return
P.yaw -= e.movementX * 0.0022
P.pitch -= e.movementY * 0.0022
P.pitch = Math.max(-1.54, Math.min(1.54, P.pitch))
})
document.addEventListener('mousedown', (e) => {
if (!locked && !isTouch) return
if (e.button === 0) breakBlock()
else if (e.button === 2) placeBlock()
})
document.addEventListener('contextmenu', (e) => e.preventDefault())
document.addEventListener('keydown', (e) => {
keys.add(e.code)
if (e.code === 'Space') e.preventDefault()
if (e.code === 'KeyF') { P.fly = !P.fly; P.vel.y = 0; toast(P.fly ? '飞行模式开' : '飞行模式关') }
if (e.code.startsWith('Digit')) {
const n = Number(e.code.slice(5)) - 1
if (n >= 0 && n < HOTBAR.length) { selected = n; paintHotbar() }
}
if (e.code === 'KeyR') resetWorld()
if (e.code === 'KeyH') $('help').hidden = !$('help').hidden
})
document.addEventListener('keyup', (e) => keys.delete(e.code))
document.addEventListener('wheel', (e) => {
if (!locked) return
selected = (selected + (e.deltaY > 0 ? 1 : -1) + HOTBAR.length) % HOTBAR.length
paintHotbar()
}, { passive: true })
// 触屏
const isTouch = matchMedia('(pointer: coarse)').matches || 'ontouchstart' in window
const touch = { joy: null, look: null, jx: 0, jy: 0 }
const joyEl = $('joy'), stickEl = $('stick')
function onTouchStart(e) {
for (const t of e.changedTouches) {
const r = document.body.getBoundingClientRect()
const leftHalf = t.clientX < window.innerWidth * 0.45
if (leftHalf && !touch.joy) { touch.joy = t.identifier; touch.cx = t.clientX; touch.cy = t.clientY; joyEl.style.left = t.clientX - 54 + 'px'; joyEl.style.top = t.clientY - 54 + 'px'; joyEl.hidden = false }
else if (!leftHalf && !touch.look) { touch.look = t.identifier; touch.lx = t.clientX; touch.ly = t.clientY }
}
}
function onTouchMove(e) {
for (const t of e.changedTouches) {
if (t.identifier === touch.joy) {
const dx = t.clientX - touch.cx, dy = t.clientY - touch.cy
const len = Math.hypot(dx, dy) || 1
const k = Math.min(1, len / 48) / len
touch.jx = dx * k; touch.jy = dy * k
stickEl.style.transform = `translate(${dx * Math.min(1, 48 / len)}px,${dy * Math.min(1, 48 / len)}px)`
} else if (t.identifier === touch.look) {
P.yaw -= (t.clientX - touch.lx) * 0.006
P.pitch -= (t.clientY - touch.ly) * 0.006
P.pitch = Math.max(-1.54, Math.min(1.54, P.pitch))
touch.lx = t.clientX; touch.ly = t.clientY
}
}
}
function onTouchEnd(e) {
for (const t of e.changedTouches) {
if (t.identifier === touch.joy) { touch.joy = null; touch.jx = touch.jy = 0; joyEl.hidden = true; stickEl.style.transform = '' }
if (t.identifier === touch.look) touch.look = null
}
}
if (isTouch) {
document.body.classList.add('touch')
document.addEventListener('touchstart', onTouchStart, { passive: true })
document.addEventListener('touchmove', onTouchMove, { passive: true })
document.addEventListener('touchend', onTouchEnd, { passive: true })
document.addEventListener('touchcancel', onTouchEnd, { passive: true })
setInterval(() => { input.fwd = -touch.jy; input.side = touch.jx }, 16)
$('tbreak').onclick = breakBlock
$('tplace').onclick = placeBlock
$('tjump').onpointerdown = () => { input.jump = true }
$('tjump').onpointerup = () => { input.jump = false }
$('tfly').onclick = () => { P.fly = !P.fly; toast(P.fly ? '飞行模式开' : '飞行模式关') }
$('pause').hidden = true
}
// ---------- 存档 ----------
function snapshot() {
return {
seed: world.seed,
pos: [P.pos.x, P.pos.y, P.pos.z],
yaw: P.yaw, pitch: P.pitch,
edits: [...world.edits.entries()].slice(-4000),
}
}
function saveNow() {
try { localStorage.setItem(SAVE_KEY, JSON.stringify(snapshot())) } catch {}
}
setInterval(saveNow, 4000)
window.addEventListener('beforeunload', saveNow)
function resetWorld() {
if (!confirm('重开一个世界?现在的改动会清空。')) return
localStorage.removeItem(SAVE_KEY)
location.reload()
}
$('resetBtn').onclick = resetWorld
$('pause').addEventListener('click', (e) => {
if (e.target.closest('button')) return
$('pause').hidden = true
if (!isTouch) canvas.requestPointerLock()
})
$('helpBtn').onclick = () => { $('help').hidden = false }
$('helpClose').onclick = () => { $('help').hidden = true }
// ---------- 主循环 ----------
let last = performance.now(), fps = 60, acc = 0, frames = 0
function frame(now) {
const dt = Math.min(0.05, (now - last) / 1000)
last = now
updatePlayer(dt)
updateHighlight()
updateChunks(P.pos.x, P.pos.z)
flushBuilds(2)
if ((frames++ & 15) === 0) unloadFar(P.pos.x, P.pos.z)
renderer.render(scene, camera)
acc += dt
if (acc > 0.5) {
fps = Math.round(frames / acc)
frames = 0; acc = 0
$('hud').textContent = `X ${P.pos.x.toFixed(1)} Y ${P.pos.y.toFixed(1)} Z ${P.pos.z.toFixed(1)} · ${fps} fps · ${P.fly ? '飞行' : '步行'}`
}
requestAnimationFrame(frame)
}
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth, window.innerHeight)
})
// 初始位置:站到地表
const startY = world.heightAt(Math.floor(P.pos.x), Math.floor(P.pos.z)) + 1.2
if (!save?.pos) P.pos = { x: P.pos.x + 0.5, y: startY, z: P.pos.z + 0.5 }
camera.position.set(P.pos.x, P.pos.y + PLAYER_H * 0.86, P.pos.z)
window.__init = 'before-init-chunks'
paintHotbar()
$('seed').textContent = String(seed)
updateChunks(P.pos.x, P.pos.z)
for (let i = 0; i < 60; i++) flushBuilds(3)
window.__init = 'ready'
$('pause').hidden = false
requestAnimationFrame(frame)
// 给自动化测试用
window.__mc = { world, P, camera, scene, renderer, get fps() { return fps }, setBlock: (x, y, z, id) => world.set(x, y, z, id), selected: (i) => { selected = i; paintHotbar() } }