-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvoxelcraft.html
More file actions
617 lines (577 loc) · 32.3 KB
/
Copy pathvoxelcraft.html
File metadata and controls
617 lines (577 loc) · 32.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<title>VoxelCraft - 单文件体素世界(三维像素风)</title>
<style>
html, body { height: 100%; }
body { margin: 0; overflow: hidden; background: #87CEEB; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Helvetica Neue', Arial, 'Noto Sans SC', 'Microsoft Yahei', sans-serif; }
canvas { display: block; image-rendering: pixelated; }
.ui { position: fixed; pointer-events: none; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,.6); font-size: 12px; }
.hud-top { top: 10px; left: 12px; display: flex; gap: 12px; align-items: center; }
.panel { background: rgba(0,0,0,.35); border: 1px solid rgba(255,255,255,.15); border-radius: 6px; padding: 8px 10px; }
#fps { min-width: 64px; text-align: center; }
#seed { opacity: .9; }
#help { position: fixed; right: 12px; top: 10px; max-width: 360px; }
#cross { position: fixed; top: 50%; left: 50%; width: 20px; height: 20px; margin-left: -10px; margin-top: -10px; opacity: .9; }
#cross::before, #cross::after { content: ''; position: absolute; background: rgba(255,255,255,.9); }
#cross::before { left: 9px; top: 0; width: 2px; height: 20px; }
#cross::after { top: 9px; left: 0; height: 2px; width: 20px; }
#hotbar { position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); display: flex; gap: 6px; }
.slot { width: 42px; height: 42px; border-radius: 6px; border: 2px solid rgba(255,255,255,.25); background: rgba(0,0,0,.35); box-shadow: inset 0 0 0 2px rgba(0,0,0,.25); display: grid; place-items: center; }
.slot.sel { border-color: #ffd86b; box-shadow: 0 0 6px rgba(255,216,107,.8), inset 0 0 0 2px rgba(0,0,0,.25); }
.chip { width: 28px; height: 28px; border-radius: 4px; box-shadow: inset 0 0 0 2px rgba(0,0,0,.25); image-rendering: pixelated; background-size: cover; }
#lock-cover { position: fixed; inset: 0; display: grid; place-items: center; background: radial-gradient(1200px 600px at 50% 50%, rgba(0,0,0,.35), rgba(0,0,0,.6)); color: #fff; }
#lock-card { pointer-events: auto; background: rgba(0,0,0,.55); border: 1px solid rgba(255,255,255,.2); border-radius: 12px; padding: 18px 20px; max-width: 560px; }
#lock-card h1 { margin: 0 0 8px; font-size: 20px; }
#lock-card p { margin: 6px 0; line-height: 1.5; opacity: .95; }
#startBtn { margin-top: 10px; padding: 8px 14px; border-radius: 8px; border: 0; background: #ffd86b; color: #222; font-weight: 700; cursor: pointer; }
#startBtn:hover { filter: brightness(1.05); }
</style>
</head>
<body>
<div class="ui hud-top">
<div id="fps" class="panel">FPS 0</div>
<div id="seed" class="panel">SEED -</div>
</div>
<div id="help" class="ui panel">
<div><strong>操作</strong></div>
<div>点击画面锁定鼠标;W/A/S/D 移动,空格跳,Shift 下蹲,F 飞行切换</div>
<div>鼠标左键:挖掘;右键:放置;滚轮切换;数字键 1-8 切换方块</div>
<div>E:简易背包提示;T:生成树;R:刷新附近区块</div>
</div>
<div id="cross"></div>
<div id="hotbar"></div>
<div id="lock-cover">
<div id="lock-card">
<h1>VoxelCraft · 三维像素世界</h1>
<p>一个使用 three.js 的小型“类 Minecraft”体验:无限体素地形(分区块)、树木生成、水面、简单怪物、昼夜循环、选中/破坏/放置方块、第一人称指针锁定控制与基础碰撞。</p>
<p>提示:为获得像素观感,本页使用最近邻采样与像素纹理。渲染依赖网络加载 three.js(CDN)。</p>
<button id="startBtn">开始游戏(锁定鼠标)</button>
</div>
</div>
<!-- 兼容更广的浏览器对 import map 的支持 -->
<script async src="https://unpkg.com/es-module-shims@1.10.0/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.158.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.158.0/examples/jsm/"
}
}
</script>
<script type="module">
// 通过 import map 使用别名导入 three.js 及其附加模块
import * as THREE from 'three';
import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js';
// =============== 基础常量 ===============
const WORLD = { CHUNK: 16, HEIGHT: 96, RENDER_DIST: 3, SEA: 46 };
const PLAYER = { H: 1.8, W: 0.6, SPEED: 5.0, JUMP: 8.5, FLY: false };
const PHYS = { GRAV: 18.0, FRICTION: 8.0, AIR: 1.0 };
const RAY_DIST = 6.0;
const DAY_LEN = 180; // 秒
// 方块 ID
const BID = {
AIR: 0,
GRASS: 1,
DIRT: 2,
STONE: 3,
WOOD: 4,
LEAF: 5,
SAND: 6,
WATER: 7,
PLANK: 8,
TORCH: 9
};
// 材质图块索引(生成图集后赋值)
const TILE = {};
// 方块定义(是否固体、是否透明、每个朝向对应的 tile)
const BLOCKS = {
[BID.AIR]: { solid: false, opaque: false },
[BID.GRASS]: {
solid: true, opaque: true, tiles: { px:'grass_side', nx:'grass_side', pz:'grass_side', nz:'grass_side', py:'grass_top', ny:'dirt' }
},
[BID.DIRT]: { solid: true, opaque: true, tiles: { all:'dirt' } },
[BID.STONE]: { solid: true, opaque: true, tiles: { all:'stone' } },
[BID.SAND]: { solid: true, opaque: true, tiles: { all:'sand' } },
[BID.WOOD]: { solid: true, opaque: true, tiles: { px:'log_side', nx:'log_side', pz:'log_side', nz:'log_side', py:'log_top', ny:'log_top' } },
[BID.LEAF]: { solid: true, opaque: true, tiles: { all:'leaf' } },
[BID.PLANK]: { solid: true, opaque: true, tiles: { all:'plank' } },
[BID.WATER]: { solid: false, opaque: false, water: true, tiles: { all:'water' } },
[BID.TORCH]: { solid: true, opaque: false, tiles: { all:'torch' } }
};
// =============== 工具:随机与噪声 ===============
function mulberry32(a){ return function(){ let t=a+=0x6D2B79F5; t=Math.imul(t^t>>>15, t|1); t^=t+Math.imul(t^t>>>7, t|61); return ((t^t>>>14)>>>0)/4294967296; } }
function hashStr(str){ let h=2166136261>>>0; for(let i=0;i<str.length;i++){h^=str.charCodeAt(i); h=Math.imul(h,16777619);} return h>>>0; }
const SEED_STR = 'voxelcraft-'+Math.floor(Math.random()*1e9);
const RAND = mulberry32(hashStr(SEED_STR));
document.getElementById('seed').textContent = 'SEED '+SEED_STR;
// 简易 Perlin2D
function Perlin2D(seedRand){
const p = new Uint8Array(512);
const perm = new Uint8Array(256);
for(let i=0;i<256;i++) perm[i]=i;
for(let i=255;i>0;i--){ const j=Math.floor(seedRand()* (i+1)); [perm[i],perm[j]]=[perm[j],perm[i]]; }
for(let i=0;i<512;i++) p[i]=perm[i & 255];
function fade(t){ return t*t*t*(t*(t*6-15)+10); }
function lerp(a,b,t){ return a+(b-a)*t; }
function grad(hash, x, y){ const h=hash&3; const u=h<2?x:y; const v=h<2?y:x; return ((h&1)?-u:u)+((h&2)?-2*v:2*v); }
return function(x,y){
const X=Math.floor(x)&255, Y=Math.floor(y)&255;
x-=Math.floor(x); y-=Math.floor(y);
const u=fade(x), v=fade(y);
const aa=p[p[X]+Y], ab=p[p[X]+Y+1], ba=p[p[X+1]+Y], bb=p[p[X+1]+Y+1];
return lerp( lerp(grad(aa,x,y), grad(ba,x-1,y), u), lerp(grad(ab,x,y-1), grad(bb,x-1,y-1), u), v );
}
}
const perlin = Perlin2D(RAND);
function octaveNoise(x,z, oct=4, scale=64, p=0.5){
let amp=1, freq=1/scale, sum=0, norm=0;
for(let i=0;i<oct;i++){ sum += perlin(x*freq, z*freq) * amp; norm+=amp; amp*=p; freq*=2; }
return sum/norm; // [-1,1]
}
// =============== 像素图集生成 ===============
const atlas = createAtlas();
const atlasTex = new THREE.CanvasTexture(atlas.canvas);
atlasTex.magFilter = THREE.NearestFilter;
atlasTex.minFilter = THREE.NearestFilter;
atlasTex.wrapS = atlasTex.wrapT = THREE.RepeatWrapping;
function createAtlas(){
const names = [
'grass_top','grass_side','dirt','stone','log_side','log_top','leaf','sand','water','plank','torch'
];
const size = 16; const cols = 8; const rows = Math.ceil(names.length/cols);
const canvas = document.createElement('canvas'); canvas.width = cols*size; canvas.height = rows*size;
const ctx = canvas.getContext('2d');
function noiseColor(x,y, base, varr, seedMul=1){ const r=base[0]+Math.floor((RAND()*2-1)*varr); const g=base[1]+Math.floor((RAND()*2-1)*varr); const b=base[2]+Math.floor((RAND()*2-1)*varr); return `rgb(${clamp(r,0,255)},${clamp(g,0,255)},${clamp(b,0,255)})`; }
function clamp(v,a,b){ return Math.max(a,Math.min(b,v)); }
function drawTile(ix, fn){ const x=(ix%cols)*size; const y=Math.floor(ix/cols)*size; fn(ctx,x,y,size); }
function dRect(x,y,w,h, c){ ctx.fillStyle=c; ctx.fillRect(x,y,w,h); }
function hatch(x,y,size,c1,c2){ for(let i=0;i<size;i++){ for(let j=0;j<size;j++){ ctx.fillStyle = ((i+j)&1)?c1:c2; ctx.fillRect(x+i,y+j,1,1); } } }
const idx = {}; names.forEach((n,i)=> idx[n]=i);
TILE.index = idx; TILE.size=size; TILE.cols=cols; TILE.rows=rows;
TILE.uv = (name)=>{ const i=idx[name]; const u0=(i%cols)/cols, v0=(Math.floor(i/cols))/rows; const du=1/cols, dv=1/rows; return [u0,v0,du,dv]; };
// grass_top
drawTile(idx['grass_top'], (c,x,y,s)=>{
for(let i=0;i<s;i++) for(let j=0;j<s;j++){
const shade = 80 + Math.floor((Math.sin((i+j)*0.6)+1)*30) + Math.floor(RAND()*8);
c.fillStyle = `rgb(${40},${shade+60},${40})`;
c.fillRect(x+i,y+j,1,1);
}
});
// grass_side (上草下土)
drawTile(idx['grass_side'], (c,x,y,s)=>{
for(let i=0;i<s;i++) for(let j=0;j<s;j++){
let col;
if(j<5){ const shade = 90+((i^j)&3)*8; col = `rgb(40,${shade+60},40)`; }
else { const d=60+((i*j)&7); col=`rgb(${90-d/3},${60-d/5},${30})`; }
c.fillStyle=col; c.fillRect(x+i,y+j,1,1);
}
});
// dirt
drawTile(idx['dirt'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const d=50+((i*7+j*13)&15); dRect(x+i,y+j,1,1,`rgb(${100+d/5},${70+d/6},${40+d/8})`); } });
// stone
drawTile(idx['stone'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const d=((i*31+j*17)&31); dRect(x+i,y+j,1,1,`rgb(${110+d/6},${110+d/6},${110+d/6})`); } });
// log_side
drawTile(idx['log_side'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const b = 80+((i*13+j*7)&15); dRect(x+i,y+j,1,1,`rgb(${120+b/10},${90+b/10},${40})`); } });
// log_top
drawTile(idx['log_top'], (c,x,y,s)=>{ hatch(x,y,s,'#b98a55','#8a5e2f'); });
// leaf
drawTile(idx['leaf'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const g=120+((i*5+j*11)&31); dRect(x+i,y+j,1,1,`rgb(${40},${g},${40})`); } });
// sand
drawTile(idx['sand'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const d=((i*19+j*23)&15); dRect(x+i,y+j,1,1,`rgb(${235-d},${220-d},${170-d})`); } });
// water(半透明纹理,颜色供视觉参考)
drawTile(idx['water'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const b=180+((i*9+j*7)&31); dRect(x+i,y+j,1,1,`rgb(${30},${80},${b})`); } });
// plank
drawTile(idx['plank'], (c,x,y,s)=>{ hatch(x,y,s,'#b58c59','#996c3a'); });
// torch
drawTile(idx['torch'], (c,x,y,s)=>{ for(let i=0;i<s;i++) for(let j=0;j<s;j++){ const d=((i*13+j*29)&7); dRect(x+i,y+j,1,1,`rgb(${200+d*4},${170+d*3},${60+d*6})`); } });
// 同步给 hotbar 预览(每个 chip 背景图)
return { canvas, names, size, cols, rows };
}
// =============== three.js 场景搭建 ===============
const renderer = new THREE.WebGLRenderer({ antialias: false, alpha: false });
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio||1));
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.05, 1000);
camera.position.set(0, 72, 0);
const controls = new PointerLockControls(camera, renderer.domElement);
const lockCover = document.getElementById('lock-cover');
const startBtn = document.getElementById('startBtn');
startBtn.addEventListener('click', ()=>{ controls.lock(); });
controls.addEventListener('lock', ()=>{ lockCover.style.display='none'; });
controls.addEventListener('unlock', ()=>{ lockCover.style.display='grid'; });
// 光照与环境
const sun = new THREE.DirectionalLight(0xffffff, 1.0);
sun.position.set(100, 150, 60);
sun.castShadow = false;
scene.add(sun);
const hemi = new THREE.HemisphereLight(0xbfd8ff, 0x334422, 0.5);
scene.add(hemi);
const ambientTorch = new THREE.PointLight(0xffaa55, 0.0, 10, 2.0); // 玩家近光
scene.add(ambientTorch);
// =============== 方块几何(面片构建) ===============
const DIRS = {
px: { n:[ 1,0,0], v:[ [0,0,1],[0,1,1],[0,1,0],[0,0,0] ] },
nx: { n:[-1,0,0], v:[ [1,0,0],[1,1,0],[1,1,1],[1,0,1] ] },
py: { n:[ 0,1,0], v:[ [0,1,1],[1,1,1],[1,1,0],[0,1,0] ] },
ny: { n:[ 0,-1,0],v:[ [0,0,0],[1,0,0],[1,0,1],[0,0,1] ] },
pz: { n:[ 0,0,1], v:[ [1,0,0],[1,1,0],[0,1,0],[0,0,0] ] },
nz: { n:[ 0,0,-1],v:[ [0,0,1],[0,1,1],[1,1,1],[1,0,1] ] },
};
function pushFace(dst, x,y,z, dir, tileName){
const {positions, normals, uvs, indices} = dst;
const baseIndex = (positions.length/3);
const verts = DIRS[dir].v;
const n = DIRS[dir].n;
// 顶点
for(let i=0;i<4;i++){
positions.push(x+verts[i][0], y+verts[i][1], z+verts[i][2]);
normals.push(n[0], n[1], n[2]);
}
// 索引(两个三角形)
indices.push(baseIndex, baseIndex+1, baseIndex+2, baseIndex, baseIndex+2, baseIndex+3);
// UV(按 tileName 定位)
const [u0,v0,du,dv] = TILE.uv(tileName);
// 注意 Three.js UV v 轴方向同纹理一致(此处构造正向)
uvs.push(u0+du, v0, u0+du, v0+dv, u0, v0+dv, u0, v0);
}
function makeGeometry(){
return { positions:[], normals:[], uvs:[], indices:[] };
}
function toBufferGeometry(src){
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(src.positions, 3));
geo.setAttribute('normal', new THREE.Float32BufferAttribute(src.normals, 3));
geo.setAttribute('uv', new THREE.Float32BufferAttribute(src.uvs, 2));
geo.setIndex(src.indices);
geo.computeBoundingSphere();
return geo;
}
// 材质(固体与水面分离,保证透明排序)
const matSolid = new THREE.MeshStandardMaterial({ map: atlasTex, roughness: 1.0, metalness: 0.0 });
const matWater = new THREE.MeshStandardMaterial({ map: atlasTex, roughness: 0.9, metalness: 0.0, transparent: true, opacity: 0.65, depthWrite: false });
// =============== 世界数据与区块 ===============
class Chunk {
constructor(cx, cz){
this.cx=cx; this.cz=cz; this.size = WORLD.CHUNK; this.height = WORLD.HEIGHT;
this.data = new Uint8Array(this.size*this.height*this.size); // x + z*size + y*size*size
this.meshSolid = null; this.meshWater = null; this.built=false;
}
idx(x,y,z){ return x + z*this.size + y*this.size*this.size; }
get(x,y,z){ if(x<0||z<0||y<0||x>=this.size||z>=this.size||y>=this.height) return BID.AIR; return this.data[this.idx(x,y,z)]||0; }
set(x,y,z,v){ if(x<0||z<0||y<0||x>=this.size||z>=this.size||y>=this.height) return; this.data[this.idx(x,y,z)]=v; }
}
class World {
constructor(){ this.chunks = new Map(); }
key(cx,cz){ return cx+","+cz; }
hasChunk(cx,cz){ return this.chunks.has(this.key(cx,cz)); }
getChunk(cx,cz){ return this.chunks.get(this.key(cx,cz)); }
ensureChunk(cx,cz){ if(!this.hasChunk(cx,cz)){ const ch=new Chunk(cx,cz); this.generateChunk(ch); this.chunks.set(this.key(cx,cz), ch); } return this.getChunk(cx,cz); }
getBlock(wx,wy,wz){ const cx=Math.floor(wx/WORLD.CHUNK), cz=Math.floor(wz/WORLD.CHUNK); const ch=this.getChunk(cx,cz); if(!ch) return BID.AIR; const x=wx - cx*WORLD.CHUNK, z=wz - cz*WORLD.CHUNK; return ch.get(x,wy,z); }
setBlock(wx,wy,wz,id){ const cx=Math.floor(wx/WORLD.CHUNK), cz=Math.floor(wz/WORLD.CHUNK); const ch=this.ensureChunk(cx,cz); const x=wx - cx*WORLD.CHUNK, z=wz - cz*WORLD.CHUNK; ch.set(x,wy,z,id); this.scheduleRebuild(cx,cz); // 邻接面可能变化
if(x===0) this.scheduleRebuild(cx-1,cz); if(x===WORLD.CHUNK-1) this.scheduleRebuild(cx+1,cz);
if(z===0) this.scheduleRebuild(cx,cz-1); if(z===WORLD.CHUNK-1) this.scheduleRebuild(cx,cz+1);
}
scheduleRebuild(cx,cz){ const ch=this.getChunk(cx,cz); if(ch) ch.built=false; }
generateChunk(ch){
const baseX=ch.cx*ch.size, baseZ=ch.cz*ch.size;
for(let x=0;x<ch.size;x++){
for(let z=0;z<ch.size;z++){
const wx=baseX+x, wz=baseZ+z;
const n = octaveNoise(wx, wz, 5, 120, 0.55); // [-1,1]
const h = Math.floor( WORLD.SEA + 18*n + 10*octaveNoise(wx+1000,wz-1000,3,40,0.5) );
const beach = Math.abs(h - WORLD.SEA) <= 2;
for(let y=0;y<ch.height;y++){
let id=BID.AIR;
if(y<=h){
if(y===h){ id = beach? BID.SAND : BID.GRASS; }
else if(y>=h-3){ id = beach? BID.SAND : BID.DIRT; }
else { id = BID.STONE; }
} else if(y<=WORLD.SEA && y>=h){ id = BID.WATER; }
ch.set(x,y,z,id);
}
// 稀疏树木
if(Math.random() < 0.05 && h>WORLD.SEA && !beach){ this.placeTree(baseX+x, h+1, baseZ+z); }
}
}
}
placeTree(wx, wy, wz){
// 简单检查:需在草上
if(this.getBlock(wx,wy-1,wz)!==BID.GRASS) return;
const trunkH = 4 + Math.floor(RAND()*3);
for(let i=0;i<trunkH;i++) this.setBlock(wx, wy+i, wz, BID.WOOD);
const topY = wy+trunkH;
for(let dx=-2;dx<=2;dx++) for(let dy=-2;dy<=2;dy++) for(let dz=-2;dz<=2;dz++){
const dist = Math.abs(dx)+Math.abs(dy)+Math.abs(dz);
if(dist<=4 && !(dy<-1 && Math.abs(dx)+Math.abs(dz)===0)){
if(this.getBlock(wx+dx, topY+dy, wz+dz)===BID.AIR){ this.setBlock(wx+dx, topY+dy, wz+dz, BID.LEAF); }
}
}
}
buildChunkMesh(ch){
if(ch.built) return; ch.built=true;
if(ch.meshSolid){ scene.remove(ch.meshSolid); ch.meshSolid.geometry.dispose(); ch.meshSolid=null; }
if(ch.meshWater){ scene.remove(ch.meshWater); ch.meshWater.geometry.dispose(); ch.meshWater=null; }
const solid = makeGeometry(); const water = makeGeometry();
const size=ch.size, h=ch.height;
const wx0=ch.cx*size, wz0=ch.cz*size;
for(let y=0;y<h;y++){
for(let z=0;z<size;z++){
for(let x=0;x<size;x++){
const id = ch.get(x,y,z); if(id===BID.AIR) continue;
const def = BLOCKS[id]; const target = def.water? water : solid;
const tiles = def.tiles;
// 邻接检查
const worldX=wx0+x, worldZ=wz0+z;
// 每个方向,如果邻居为空/非不透明则添加该面
function visible(nx,ny,nz){ const b=world.getBlock(worldX+nx, y+ny, worldZ+nz); if(b===BID.AIR) return true; const d=BLOCKS[b]; return !d.opaque; }
if(visible( 1,0,0)) pushFace(target, worldX, y, worldZ, 'px', tiles.px||tiles.all);
if(visible(-1,0,0)) pushFace(target, worldX, y, worldZ, 'nx', tiles.nx||tiles.all);
if(visible(0, 1,0)) pushFace(target, worldX, y, worldZ, 'py', tiles.py||tiles.all);
if(visible(0,-1,0)) pushFace(target, worldX, y, worldZ, 'ny', tiles.ny||tiles.all);
if(visible(0,0, 1)) pushFace(target, worldX, y, worldZ, 'pz', tiles.pz||tiles.all);
if(visible(0,0,-1)) pushFace(target, worldX, y, worldZ, 'nz', tiles.nz||tiles.all);
}
}
}
if(solid.indices.length){ ch.meshSolid = new THREE.Mesh(toBufferGeometry(solid), matSolid); ch.meshSolid.frustumCulled=true; scene.add(ch.meshSolid); }
if(water.indices.length){ ch.meshWater = new THREE.Mesh(toBufferGeometry(water), matWater); ch.meshWater.renderOrder=1; scene.add(ch.meshWater); }
}
}
const world = new World();
// =============== 玩家控制与碰撞 ===============
const keys = new Set(); let onGround=false; let vel = new THREE.Vector3(); let wantJump=false; let fly=false; let sprint=false; let crouch=false;
const player = { pos: new THREE.Vector3(0, 80, 0) };
function aabbOverlaps(x,y,z){
// 检查玩家胶囊的 AABB 与固体方块碰撞
const hx=PLAYER.W*0.5, hy=PLAYER.H; const minX=Math.floor(x-hx), maxX=Math.floor(x+hx);
const minY=Math.floor(y), maxY=Math.floor(y+hy);
const minZ=Math.floor(z-hx), maxZ=Math.floor(z+hx);
for(let yy=minY;yy<=maxY;yy++){
for(let zz=minZ;zz<=maxZ;zz++){
for(let xx=minX;xx<=maxX;xx++){
const id=world.getBlock(xx,yy,zz); if(id!==BID.AIR && BLOCKS[id].solid){ return true; }
}
}
}
return false;
}
function stepPhysics(dt){
ambientTorch.position.copy(camera.position);
const spd = (sprint?1.8:1.0) * (crouch?0.5:1.0) * PLAYER.SPEED;
const dir = new THREE.Vector3();
const forward = new THREE.Vector3(); camera.getWorldDirection(forward); forward.y=0; forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0,1,0)).negate();
if(keys.has('KeyW')) dir.add(forward);
if(keys.has('KeyS')) dir.sub(forward);
if(keys.has('KeyA')) dir.sub(right);
if(keys.has('KeyD')) dir.add(right);
dir.normalize();
if(fly){
if(keys.has('Space')) dir.y+=1; if(keys.has('ShiftLeft')) dir.y-=1; dir.normalize();
vel.copy(dir.multiplyScalar(spd));
} else {
// 地面运动与重力
vel.x += dir.x*spd*6*dt; vel.z += dir.z*spd*6*dt;
const fr = onGround? PHYS.FRICTION : PHYS.AIR;
vel.x -= vel.x*Math.min(1, fr*dt); vel.z -= vel.z*Math.min(1, fr*dt);
vel.y -= PHYS.GRAV*dt; if(onGround && wantJump){ vel.y = PLAYER.JUMP; wantJump=false; }
}
// 逐轴碰撞
const pos=camera.position; const hx=PLAYER.W*0.5; const h=PLAYER.H;
// X
let nx = pos.x + vel.x*dt; if(aabbOverlaps(nx, pos.y, pos.z)){ nx = pos.x; vel.x=0; }
pos.x = nx;
// Z
let nz = pos.z + vel.z*dt; if(aabbOverlaps(pos.x, pos.y, nz)){ nz = pos.z; vel.z=0; }
pos.z = nz;
// Y
let ny = pos.y + vel.y*dt; const prevY=pos.y; if(aabbOverlaps(pos.x, ny, pos.z)){ if(vel.y>0){ ny=Math.floor(ny)+ (1-1e-3); } else { ny=Math.floor(prevY)+1e-3; onGround=true; } vel.y=0; } else { onGround=false; }
pos.y = ny;
}
// =============== 射线体素遍历(选方块) ===============
function raycastVoxel(origin, dir, maxDist){
// 3D DDA
let x=Math.floor(origin.x), y=Math.floor(origin.y), z=Math.floor(origin.z);
const stepX = dir.x>0?1:-1, stepY = dir.y>0?1:-1, stepZ = dir.z>0?1:-1;
const tDeltaX = Math.abs(1/ (dir.x||1e-6));
const tDeltaY = Math.abs(1/ (dir.y||1e-6));
const tDeltaZ = Math.abs(1/ (dir.z||1e-6));
const tx0 = (dir.x>0? (x+1-origin.x):(origin.x-x)) * tDeltaX;
const ty0 = (dir.y>0? (y+1-origin.y):(origin.y-y)) * tDeltaY;
const tz0 = (dir.z>0? (z+1-origin.z):(origin.z-z)) * tDeltaZ;
let tMaxX=tx0, tMaxY=ty0, tMaxZ=tz0;
let t=0; let lastN=[0,0,0];
while(t<=maxDist){
const id=world.getBlock(x,y,z); if(id!==BID.AIR && BLOCKS[id].opaque){ return { x,y,z, normal: lastN, id, dist:t }; }
if(tMaxX < tMaxY){ if(tMaxX < tMaxZ){ x+=stepX; t=tMaxX; tMaxX+=tDeltaX; lastN=[-stepX,0,0]; } else { z+=stepZ; t=tMaxZ; tMaxZ+=tDeltaZ; lastN=[0,0,-stepZ]; } }
else { if(tMaxY < tMaxZ){ y+=stepY; t=tMaxY; tMaxY+=tDeltaY; lastN=[0,-stepY,0]; } else { z+=stepZ; t=tMaxZ; tMaxZ+=tDeltaZ; lastN=[0,0,-stepZ]; } }
}
return null;
}
// =============== 区块加载与管理 ===============
function updateChunksAround(){
const cx = Math.floor(camera.position.x/WORLD.CHUNK);
const cz = Math.floor(camera.position.z/WORLD.CHUNK);
for(let dz=-WORLD.RENDER_DIST; dz<=WORLD.RENDER_DIST; dz++)
for(let dx=-WORLD.RENDER_DIST; dx<=WORLD.RENDER_DIST; dx++){
const ch = world.ensureChunk(cx+dx, cz+dz);
world.buildChunkMesh(ch);
}
}
// 初次加载一定范围
updateChunksAround();
// 根据地面高度微调初始 Y,避免出生在方块内部或水下
(function adjustSpawn(){
const wx=Math.floor(camera.position.x), wz=Math.floor(camera.position.z);
let sy = WORLD.HEIGHT-2; while(sy>1 && world.getBlock(wx,sy,wz)===BID.AIR) sy--; sy=Math.max(2, sy);
if(sy < WORLD.SEA-1) sy = WORLD.SEA+2; // 避免水下出生
camera.position.y = sy + 2.2;
})();
// =============== 怪物(简易 AI) ===============
class Mob {
constructor(x,y,z, color=0x55aa55){
this.pos=new THREE.Vector3(x,y,z);
this.vel=new THREE.Vector3();
const geo=new THREE.BoxGeometry(0.8,0.8,0.8);
const mat=new THREE.MeshStandardMaterial({ color });
this.mesh=new THREE.Mesh(geo,mat); this.mesh.position.copy(this.pos).add(new THREE.Vector3(0,0.4,0));
scene.add(this.mesh);
this.timer=0; this.target=null;
}
update(dt){
const toPlayer = new THREE.Vector3().subVectors(camera.position, this.pos); const dist = toPlayer.length();
if(dist<10){ toPlayer.y=0; toPlayer.normalize(); this.vel.x+=toPlayer.x*2*dt; this.vel.z+=toPlayer.z*2*dt; }
else {
this.timer-=dt; if(this.timer<=0){ this.timer= 1.5 + Math.random()*2.0; const a=Math.random()*Math.PI*2; this.target=[Math.cos(a), Math.sin(a)]; }
if(this.target){ this.vel.x += this.target[0]*1.2*dt; this.vel.z += this.target[1]*1.2*dt; }
}
// 简单重力与阻尼
this.vel.y -= PHYS.GRAV*dt*0.5; this.vel.x*= (1-2*dt); this.vel.z*=(1-2*dt);
// 碰撞(近似方块中心)
const tryMove=(dx,dy,dz)=>{ const nx=this.pos.x+dx, ny=this.pos.y+dy, nz=this.pos.z+dz; const bx=Math.floor(nx), by=Math.floor(ny), bz=Math.floor(nz); const id=world.getBlock(bx,by,bz); if(id!==BID.AIR && BLOCKS[id].solid) return false; this.pos.set(nx,ny,nz); return true; }
tryMove(this.vel.x*dt,0,0); tryMove(0,this.vel.y*dt,0); tryMove(0,0,this.vel.z*dt);
// 防止掉出世界
if(this.pos.y<1){ this.pos.y=1; this.vel.y=0; }
this.mesh.position.set(this.pos.x, this.pos.y+0.4, this.pos.z);
}
}
const mobs=[];
function spawnMobs(n=8){
for(let i=0;i<n;i++){
const x = camera.position.x + (Math.random()*40-20);
const z = camera.position.z + (Math.random()*40-20);
let y= WORLD.HEIGHT-2; while(y>0 && world.getBlock(Math.floor(x),y,Math.floor(z))===BID.AIR) y--; y++;
mobs.push(new Mob(x,y,z, (Math.random()<0.5)?0x66aa66:0xaa6666));
}
}
spawnMobs(6);
// =============== UI 与背包/热键 ===============
const selectableBlocks = [BID.GRASS,BID.DIRT,BID.STONE,BID.WOOD,BID.LEAF,BID.SAND,BID.PLANK,BID.TORCH];
let selIndex = 0;
const hotbar = document.getElementById('hotbar');
function refreshHotbar(){
hotbar.innerHTML='';
selectableBlocks.forEach((bid,i)=>{
const tileName = (BLOCKS[bid].tiles.py||BLOCKS[bid].tiles.px||BLOCKS[bid].tiles.all);
const idx = TILE.index[tileName];
const col=TILE.cols, row=TILE.rows, s=TILE.size;
const u = (idx%col)*s, v = Math.floor(idx/col)*s;
const chip = document.createElement('div'); chip.className='chip';
chip.style.backgroundImage = `url(${atlas.canvas.toDataURL()})`;
chip.style.backgroundPosition = `-${u}px -${v}px`;
chip.style.backgroundSize = `${col*s}px ${row*s}px`;
const slot = document.createElement('div'); slot.className='slot'+(i===selIndex?' sel':''); slot.appendChild(chip); hotbar.appendChild(slot);
});
}
refreshHotbar();
window.addEventListener('keydown', (e)=>{
if(e.code==='KeyF'){ fly=!fly; PLAYER.FLY=fly; }
if(e.code==='KeyE'){ /* 预留:背包开关 */ }
if(e.code==='KeyT'){ // 在视线处尝试生成树
const r = raycastVoxel(camera.position, camera.getWorldDirection(new THREE.Vector3()), 12);
if(r){ world.placeTree(r.x, r.y+1, r.z); updateChunksAround(); }
}
if(e.code==='KeyR'){ updateChunksAround(); }
if(e.code==='ShiftLeft'){ crouch=true; }
if(e.code==='Space'){ if(!fly) wantJump=true; }
if(e.code==='ControlLeft'){ sprint=true; }
// 数字选择
if(/^Digit[1-8]$/.test(e.code)){
selIndex = parseInt(e.code.slice(5))-1; refreshHotbar();
}
keys.add(e.code);
});
window.addEventListener('keyup', (e)=>{ keys.delete(e.code); if(e.code==='ShiftLeft') crouch=false; if(e.code==='ControlLeft') sprint=false; });
// 鼠标点击:破坏与放置
renderer.domElement.addEventListener('mousedown', (e)=>{
if(!controls.isLocked) return;
const dir = camera.getWorldDirection(new THREE.Vector3());
const hit = raycastVoxel(camera.position, dir, RAY_DIST);
if(e.button===0){ // 左键破坏
if(hit){ world.setBlock(hit.x, hit.y, hit.z, BID.AIR); updateChunksAround(); }
} else if(e.button===2){ // 右键放置
e.preventDefault();
if(hit){ const place = { x: hit.x + hit.normal[0], y: hit.y + hit.normal[1], z: hit.z + hit.normal[2] };
const bid = selectableBlocks[selIndex];
// 防止放到玩家体内
const cam = camera.position; const hx=PLAYER.W*0.5, h=PLAYER.H;
if(!(place.x>=Math.floor(cam.x-hx)&&place.x<=Math.floor(cam.x+hx)&& place.y>=Math.floor(cam.y)&&place.y<=Math.floor(cam.y+h)&& place.z>=Math.floor(cam.z-hx)&&place.z<=Math.floor(cam.z+hx))){
world.setBlock(place.x, place.y, place.z, bid); updateChunksAround();
}
}
}
});
// 禁用右键菜单(在画布上)
renderer.domElement.addEventListener('contextmenu', e=> e.preventDefault());
// =============== 昼夜循环 ===============
let worldTime = 8*60; // 起始 8:00 (分钟)
function updateDayNight(dt){
worldTime += dt* (1440/DAY_LEN); // 映射到游戏天
const t = (worldTime%1440)/1440; // [0,1)
const angle = t*2*Math.PI;
const sunH = Math.sin(angle);
const sunX = Math.cos(angle)*200, sunY = sunH*200, sunZ = Math.sin(angle*0.7)*100;
sun.position.set(sunX, sunY, sunZ);
const day = Math.max(0, sunH);
sun.intensity = 0.2 + day*0.9;
hemi.intensity = 0.2 + day*0.6;
scene.background.setHSL(0.6, 0.5, 0.6*day + 0.05);
ambientTorch.intensity = 0.0 + (1-day)*0.8; // 夜晚略亮些
}
// =============== 主循环 ===============
let last=performance.now(); let fpsSpan=document.getElementById('fps'); let fpsAcc=0, fpsCnt=0;
function loop(now){
const dt=Math.min(0.05, (now-last)/1000); last=now;
if(controls.isLocked){ stepPhysics(dt); }
updateDayNight(dt);
// 区块加载(低频)
chunkTick += dt; if(chunkTick>0.25){ updateChunksAround(); chunkTick=0; }
for(const m of mobs) m.update(dt);
// 选中高亮(简化:用辅助线框)
updateTargetHighlight();
renderer.render(scene,camera);
// FPS
fpsAcc+=dt; fpsCnt++; if(fpsAcc>=0.5){ fpsSpan.textContent = 'FPS '+Math.round(fpsCnt/fpsAcc); fpsAcc=0; fpsCnt=0; }
requestAnimationFrame(loop);
}
let chunkTick=0; requestAnimationFrame(loop);
// =============== 选中方块高亮 ===============
const hlGeo = new THREE.BoxGeometry(1.002,1.002,1.002);
const hlMat = new THREE.MeshBasicMaterial({ color: 0xffff00, wireframe:true });
const hlMesh = new THREE.Mesh(hlGeo, hlMat); hlMesh.visible=false; scene.add(hlMesh);
function updateTargetHighlight(){
const hit = raycastVoxel(camera.position, camera.getWorldDirection(new THREE.Vector3()), RAY_DIST);
if(hit){ hlMesh.visible=true; hlMesh.position.set(hit.x+0.5, hit.y+0.5, hit.z+0.5); }
else { hlMesh.visible=false; }
}
// =============== 视口与窗口 ===============
window.addEventListener('resize', ()=>{ renderer.setSize(window.innerWidth, window.innerHeight); camera.aspect = window.innerWidth/window.innerHeight; camera.updateProjectionMatrix(); });
</script>
</body>
</html>