world.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. /*
  2. Blocky - world.js
  3. Chunk storage and the simulation of the block world:
  4. - chunks are 16 x 128 x 16 columns (index (x << 11) | (z << 7) | y),
  5. rendered as eight 16-high sections
  6. - light: sky light and block light (0-15 each) packed in one byte per
  7. voxel, filled by a breadth first flood when a chunk is first lit and
  8. updated incrementally (removal + refill) when a block changes
  9. - block updates: water flow, falling sand and gravel, plants and torches
  10. losing their support, leaf decay, crop / reed / cactus growth, grass
  11. spreading, furnaces
  12. - save data: only chunks that changed are stored, run-length encoded
  13. The world never touches the renderer; it raises dirty flags per section
  14. and the renderer rebuilds what it needs.
  15. */
  16. import {
  17. B, BLOCKS, LIGHT_OPACITY, LIGHT_EMIT, SHAPE, SOLID, RAIN_BLOCKING, isOpaqueAt,
  18. blockDrops, SMELTING, SMELT_TICKS, fuelTicks, ITEMS
  19. } from "./blocks.js";
  20. import { TerrainGen, WORLD_H, SEA, idx } from "./worldgen.js";
  21. import { chunkKey, rleEncode, rleDecode, bytesToBase64, base64ToBytes, mulberry32 } from "./util.js";
  22. import { FACE_DIR } from "./shapes.js";
  23. export const SECTIONS = WORLD_H / 16;
  24. const IS_SLAB = new Uint8Array(256);
  25. const WASHABLE = new Uint8Array(256);
  26. for (let i = 0; i < 256; i++) {
  27. IS_SLAB[i] = SHAPE[i] === "slab" ? 1 : 0;
  28. WASHABLE[i] = (SHAPE[i] === "cross" || SHAPE[i] === "crop" || SHAPE[i] === "torch") && i !== B.REEDS ? 1 : 0;
  29. }
  30. function opacityOf(id, meta) {
  31. const o = LIGHT_OPACITY[id];
  32. if (o === 0 && IS_SLAB[id] === 1 && meta === 2) {
  33. return 15;
  34. }
  35. return o;
  36. }
  37. const DIRS = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  38. export class Chunk {
  39. constructor(cx, cz) {
  40. this.cx = cx;
  41. this.cz = cz;
  42. this.key = chunkKey(cx, cz);
  43. this.blocks = new Uint8Array(16 * 16 * WORLD_H);
  44. this.meta = new Uint8Array(16 * 16 * WORLD_H);
  45. this.light = new Uint8Array(16 * 16 * WORLD_H);
  46. this.biome = new Uint8Array(256);
  47. this.tint = new Float32Array(256 * 6);
  48. this.hmLight = new Uint8Array(256);
  49. this.hmRain = new Uint8Array(256);
  50. this.generated = false;
  51. this.lit = false;
  52. this.modified = false;
  53. this.dirty = new Uint8Array(SECTIONS).fill(1);
  54. this.meshes = null; //owned by the renderer
  55. }
  56. }
  57. export class World {
  58. constructor(seed, opts = {}) {
  59. this.seed = seed | 0;
  60. this.gen = new TerrainGen(this.seed);
  61. this.chunks = new Map();
  62. this.saved = new Map();
  63. this.tileEntities = new Map();
  64. this.schedBuckets = new Map();
  65. this.schedSet = new Set();
  66. this.tickCount = 0;
  67. this.rng = mulberry32(this.seed ^ 0x51ed);
  68. this.lastChunk = null;
  69. this.skyDarken = 0;
  70. this.raining = false;
  71. this.order = null;
  72. this.orderKey = "";
  73. //Callbacks wired up by the game
  74. this.onDrop = opts.onDrop || null;
  75. this.onFalling = opts.onFalling || null;
  76. this.onBlockBroken = opts.onBlockBroken || null;
  77. }
  78. /* ---------------- chunk access ---------------- */
  79. chunkAt(cx, cz) {
  80. const lc = this.lastChunk;
  81. if (lc !== null && lc.cx === cx && lc.cz === cz) {
  82. return lc;
  83. }
  84. const c = this.chunks.get(chunkKey(cx, cz));
  85. if (c !== undefined) {
  86. this.lastChunk = c;
  87. }
  88. return c;
  89. }
  90. isLoaded(x, z) {
  91. const c = this.chunkAt(x >> 4, z >> 4);
  92. return c !== undefined && c.generated;
  93. }
  94. getBlock(x, y, z) {
  95. if (y < 0) {
  96. return B.BEDROCK;
  97. }
  98. if (y >= WORLD_H) {
  99. return B.AIR;
  100. }
  101. const c = this.chunkAt(x >> 4, z >> 4);
  102. if (c === undefined || !c.generated) {
  103. return B.AIR;
  104. }
  105. return c.blocks[((x & 15) << 11) | ((z & 15) << 7) | y];
  106. }
  107. getMeta(x, y, z) {
  108. if (y < 0 || y >= WORLD_H) {
  109. return 0;
  110. }
  111. const c = this.chunkAt(x >> 4, z >> 4);
  112. if (c === undefined || !c.generated) {
  113. return 0;
  114. }
  115. return c.meta[((x & 15) << 11) | ((z & 15) << 7) | y];
  116. }
  117. getSky(x, y, z) {
  118. if (y >= WORLD_H) {
  119. return 15;
  120. }
  121. if (y < 0) {
  122. return 0;
  123. }
  124. const c = this.chunkAt(x >> 4, z >> 4);
  125. if (c === undefined || !c.lit) {
  126. return 15;
  127. }
  128. return c.light[((x & 15) << 11) | ((z & 15) << 7) | y] >> 4;
  129. }
  130. getBlockLight(x, y, z) {
  131. if (y < 0 || y >= WORLD_H) {
  132. return 0;
  133. }
  134. const c = this.chunkAt(x >> 4, z >> 4);
  135. if (c === undefined) {
  136. return 0;
  137. }
  138. return c.light[((x & 15) << 11) | ((z & 15) << 7) | y] & 15;
  139. }
  140. //Light level the way plants see it (sky dims at night)
  141. effectiveLight(x, y, z) {
  142. return Math.max(this.getSky(x, y, z) - this.skyDarken, this.getBlockLight(x, y, z));
  143. }
  144. biomeAt(x, z) {
  145. const c = this.chunkAt(x >> 4, z >> 4);
  146. if (c === undefined || !c.generated) {
  147. return this.gen.column(x, z).biome;
  148. }
  149. return c.biome[(z & 15) * 16 + (x & 15)];
  150. }
  151. //First y above everything that stops rain in this column
  152. rainTop(x, z) {
  153. const c = this.chunkAt(x >> 4, z >> 4);
  154. if (c === undefined || !c.generated) {
  155. return -1;
  156. }
  157. return c.hmRain[(z & 15) * 16 + (x & 15)];
  158. }
  159. /* ---------------- generation & streaming ---------------- */
  160. getOrCreate(cx, cz) {
  161. let c = this.chunkAt(cx, cz);
  162. if (c === undefined) {
  163. c = new Chunk(cx, cz);
  164. this.chunks.set(c.key, c);
  165. }
  166. return c;
  167. }
  168. generateChunk(c) {
  169. const saved = this.saved.get(c.key);
  170. if (saved !== undefined) {
  171. rleDecode(base64ToBytes(saved), c.blocks, c.meta);
  172. for (let lz = 0; lz < 16; lz++) {
  173. for (let lx = 0; lx < 16; lx++) {
  174. const col = this.gen.columnCached(c.cx * 16 + lx, c.cz * 16 + lz);
  175. c.biome[lz * 16 + lx] = col.biome;
  176. c.tint.set(col.grass, (lz * 16 + lx) * 6);
  177. c.tint.set(col.leaf, (lz * 16 + lx) * 6 + 3);
  178. }
  179. }
  180. c.modified = true;
  181. this.saved.delete(c.key);
  182. } else {
  183. this.gen.generate(c);
  184. }
  185. this.computeHeightmaps(c);
  186. c.generated = true;
  187. }
  188. computeHeightmaps(c) {
  189. for (let lz = 0; lz < 16; lz++) {
  190. for (let lx = 0; lx < 16; lx++) {
  191. const base = (lx << 11) | (lz << 7);
  192. let hl = 0, hr = 0;
  193. for (let y = WORLD_H - 1; y >= 0; y--) {
  194. if (opacityOf(c.blocks[base | y], c.meta[base | y]) > 0) {
  195. hl = y + 1;
  196. break;
  197. }
  198. }
  199. for (let y = WORLD_H - 1; y >= 0; y--) {
  200. if (RAIN_BLOCKING[c.blocks[base | y]]) {
  201. hr = y + 1;
  202. break;
  203. }
  204. }
  205. c.hmLight[lz * 16 + lx] = hl;
  206. c.hmRain[lz * 16 + lx] = hr;
  207. }
  208. }
  209. }
  210. neighborsReady(c, flag) {
  211. for (let dx = -1; dx <= 1; dx++) {
  212. for (let dz = -1; dz <= 1; dz++) {
  213. if (dx === 0 && dz === 0) {
  214. continue;
  215. }
  216. const n = this.chunkAt(c.cx + dx, c.cz + dz);
  217. if (n === undefined || !n[flag]) {
  218. return false;
  219. }
  220. }
  221. }
  222. return true;
  223. }
  224. isMeshable(c) {
  225. return c.lit && this.neighborsReady(c, "lit");
  226. }
  227. //Generate and light chunks around (pcx, pcz) until the deadline.
  228. //Returns true when everything in range is ready.
  229. stream(pcx, pcz, radius, deadline) {
  230. const key = pcx + "," + pcz + "," + radius;
  231. if (key !== this.orderKey) {
  232. this.orderKey = key;
  233. const list = [];
  234. const R = radius + 2;
  235. for (let dx = -R; dx <= R; dx++) {
  236. for (let dz = -R; dz <= R; dz++) {
  237. list.push([dx, dz, dx * dx + dz * dz, Math.max(Math.abs(dx), Math.abs(dz))]);
  238. }
  239. }
  240. list.sort((a, b) => a[2] - b[2]);
  241. this.order = list;
  242. this.streamDone = false;
  243. }
  244. if (this.streamDone) {
  245. return true;
  246. }
  247. let allDone = true;
  248. for (const [dx, dz, , cheb] of this.order) {
  249. const c = this.getOrCreate(pcx + dx, pcz + dz);
  250. if (!c.generated) {
  251. if (performance.now() > deadline) {
  252. return false;
  253. }
  254. this.generateChunk(c);
  255. }
  256. if (cheb <= radius + 1 && !c.lit) {
  257. if (this.neighborsReady(c, "generated")) {
  258. if (performance.now() > deadline) {
  259. return false;
  260. }
  261. this.lightChunk(c);
  262. } else {
  263. allDone = false;
  264. }
  265. }
  266. }
  267. if (allDone) {
  268. this.streamDone = true;
  269. }
  270. return allDone;
  271. }
  272. //Drop chunks far from the player; returns the removed chunks
  273. unloadFar(pcx, pcz, radius) {
  274. const out = [];
  275. const R = radius + 4;
  276. for (const c of this.chunks.values()) {
  277. if (Math.abs(c.cx - pcx) > R || Math.abs(c.cz - pcz) > R) {
  278. if (c.modified && c.generated) {
  279. this.saved.set(c.key, bytesToBase64(rleEncode(c.blocks, c.meta)));
  280. }
  281. out.push(c);
  282. }
  283. }
  284. for (const c of out) {
  285. this.chunks.delete(c.key);
  286. }
  287. if (out.length) {
  288. this.lastChunk = null;
  289. this.orderKey = "";
  290. }
  291. return out;
  292. }
  293. /* ---------------- lighting ---------------- */
  294. lightChunk(c) {
  295. const x0 = c.cx * 16, z0 = c.cz * 16;
  296. //Straight down sky light
  297. for (let lz = 0; lz < 16; lz++) {
  298. for (let lx = 0; lx < 16; lx++) {
  299. let level = 15;
  300. for (let y = WORLD_H - 1; y >= 0; y--) {
  301. const i = (lx << 11) | (lz << 7) | y;
  302. const op = opacityOf(c.blocks[i], c.meta[i]);
  303. if (op >= 15) {
  304. break;
  305. }
  306. if (!(level === 15 && op === 0)) {
  307. level = level - 1 - op;
  308. if (level <= 0) {
  309. break;
  310. }
  311. }
  312. if (level > (c.light[i] >> 4)) {
  313. c.light[i] = (level << 4) | (c.light[i] & 15);
  314. }
  315. }
  316. }
  317. }
  318. //Seeds: open sky voxels next to taller neighbouring columns
  319. const sky = [];
  320. for (let lz = 0; lz < 16; lz++) {
  321. for (let lx = 0; lx < 16; lx++) {
  322. const h = c.hmLight[lz * 16 + lx];
  323. let maxN = h;
  324. for (let d = 0; d < 4; d++) {
  325. const nx = x0 + lx + (d === 0 ? 1 : d === 1 ? -1 : 0);
  326. const nz = z0 + lz + (d === 2 ? 1 : d === 3 ? -1 : 0);
  327. const nc = this.chunkAt(nx >> 4, nz >> 4);
  328. if (nc !== undefined && nc.generated) {
  329. const nh = nc.hmLight[(nz & 15) * 16 + (nx & 15)];
  330. if (nh > maxN) {
  331. maxN = nh;
  332. }
  333. }
  334. }
  335. for (let y = h; y < maxN; y++) {
  336. sky.push(x0 + lx, y, z0 + lz);
  337. }
  338. }
  339. }
  340. //Block light sources
  341. const blk = [];
  342. const blocks = c.blocks;
  343. for (let i = 0; i < blocks.length; i++) {
  344. const em = LIGHT_EMIT[blocks[i]];
  345. if (em > 0) {
  346. c.light[i] = (c.light[i] & 0xf0) | em;
  347. blk.push(x0 + (i >> 11), i & 127, z0 + ((i >> 7) & 15));
  348. }
  349. }
  350. c.lit = true;
  351. this.propagate(sky, true);
  352. this.propagate(blk, false);
  353. c.dirty.fill(1);
  354. }
  355. propagate(q, isSky) {
  356. let i = 0;
  357. while (i < q.length) {
  358. const x = q[i++], y = q[i++], z = q[i++];
  359. const c = this.chunkAt(x >> 4, z >> 4);
  360. if (c === undefined || !c.generated) {
  361. continue;
  362. }
  363. const li = ((x & 15) << 11) | ((z & 15) << 7) | y;
  364. const level = isSky ? c.light[li] >> 4 : c.light[li] & 15;
  365. if (level <= 1) {
  366. continue;
  367. }
  368. for (let d = 0; d < 18; d += 3) {
  369. const ny = y + DIRS[d + 1];
  370. if (ny < 0 || ny >= WORLD_H) {
  371. continue;
  372. }
  373. const nx = x + DIRS[d], nz = z + DIRS[d + 2];
  374. const nc = (DIRS[d] !== 0 || DIRS[d + 2] !== 0) ? this.chunkAt(nx >> 4, nz >> 4) : c;
  375. if (nc === undefined || !nc.generated) {
  376. continue;
  377. }
  378. const ni = ((nx & 15) << 11) | ((nz & 15) << 7) | ny;
  379. const op = opacityOf(nc.blocks[ni], nc.meta[ni]);
  380. if (op >= 15) {
  381. continue;
  382. }
  383. const nl = (isSky && d === 9 && level === 15 && op === 0) ? 15 : level - 1 - op;
  384. if (nl <= 0) {
  385. continue;
  386. }
  387. const cur = isSky ? nc.light[ni] >> 4 : nc.light[ni] & 15;
  388. if (nl > cur) {
  389. nc.light[ni] = isSky ? (nl << 4) | (nc.light[ni] & 15) : (nc.light[ni] & 0xf0) | nl;
  390. this.markDirtyAround(nx, ny, nz, nc);
  391. q.push(nx, ny, nz);
  392. }
  393. }
  394. if (i > 300000) {
  395. q.splice(0, i);
  396. i = 0;
  397. }
  398. }
  399. }
  400. //Clear the light a voxel used to spread; refill candidates go to add
  401. removeLight(x, y, z, level, isSky, add) {
  402. const c0 = this.chunkAt(x >> 4, z >> 4);
  403. const li0 = ((x & 15) << 11) | ((z & 15) << 7) | y;
  404. c0.light[li0] = isSky ? c0.light[li0] & 15 : c0.light[li0] & 0xf0;
  405. const rq = [x, y, z, level];
  406. let i = 0;
  407. while (i < rq.length) {
  408. const cx = rq[i++], cy = rq[i++], cz = rq[i++], lv = rq[i++];
  409. for (let d = 0; d < 18; d += 3) {
  410. const ny = cy + DIRS[d + 1];
  411. if (ny < 0 || ny >= WORLD_H) {
  412. continue;
  413. }
  414. const nx = cx + DIRS[d], nz = cz + DIRS[d + 2];
  415. const nc = this.chunkAt(nx >> 4, nz >> 4);
  416. if (nc === undefined || !nc.generated) {
  417. continue;
  418. }
  419. const ni = ((nx & 15) << 11) | ((nz & 15) << 7) | ny;
  420. const nl = isSky ? nc.light[ni] >> 4 : nc.light[ni] & 15;
  421. if (nl === 0) {
  422. continue;
  423. }
  424. if (!isSky) {
  425. const em = LIGHT_EMIT[nc.blocks[ni]];
  426. if (em > 0) {
  427. if (nl < lv && nl > em) {
  428. nc.light[ni] = (nc.light[ni] & 0xf0) | em;
  429. this.markDirtyAround(nx, ny, nz, nc);
  430. }
  431. add.push(nx, ny, nz);
  432. continue;
  433. }
  434. }
  435. const straightDown = isSky && d === 9 && lv === 15 && nl === 15;
  436. if (nl < lv || straightDown) {
  437. nc.light[ni] = isSky ? nc.light[ni] & 15 : nc.light[ni] & 0xf0;
  438. this.markDirtyAround(nx, ny, nz, nc);
  439. rq.push(nx, ny, nz, nl);
  440. } else {
  441. add.push(nx, ny, nz);
  442. }
  443. }
  444. }
  445. }
  446. relight(x, y, z, oldId, oldMeta, newId, newMeta) {
  447. const oldOp = opacityOf(oldId, oldMeta), newOp = opacityOf(newId, newMeta);
  448. const oldEm = LIGHT_EMIT[oldId], newEm = LIGHT_EMIT[newId];
  449. const c = this.chunkAt(x >> 4, z >> 4);
  450. const li = ((x & 15) << 11) | ((z & 15) << 7) | y;
  451. const pushNeighbors = (arr) => {
  452. for (let d = 0; d < 18; d += 3) {
  453. const ny = y + DIRS[d + 1];
  454. if (ny >= 0 && ny < WORLD_H) {
  455. arr.push(x + DIRS[d], ny, z + DIRS[d + 2]);
  456. }
  457. }
  458. };
  459. if (oldEm !== newEm || oldOp !== newOp) {
  460. const add = [];
  461. const cur = c.light[li] & 15;
  462. if (cur > 0) {
  463. this.removeLight(x, y, z, cur, false, add);
  464. }
  465. if (newEm > 0) {
  466. c.light[li] = (c.light[li] & 0xf0) | newEm;
  467. add.push(x, y, z);
  468. } else if (newOp < 15) {
  469. pushNeighbors(add);
  470. }
  471. this.propagate(add, false);
  472. }
  473. if (oldOp !== newOp) {
  474. const add = [];
  475. const cur = c.light[li] >> 4;
  476. if (newOp > oldOp) {
  477. if (cur > 0) {
  478. this.removeLight(x, y, z, cur, true, add);
  479. }
  480. } else {
  481. pushNeighbors(add);
  482. }
  483. this.propagate(add, true);
  484. }
  485. }
  486. markDirtyAround(x, y, z, c) {
  487. const lx = x & 15, lz = z & 15, ly = y & 15;
  488. const sec = y >> 4;
  489. c.dirty[sec] = 1;
  490. if (lx !== 0 && lx !== 15 && lz !== 0 && lz !== 15 && ly !== 0 && ly !== 15) {
  491. return;
  492. }
  493. const xa = lx === 0 ? -1 : lx === 15 ? 1 : 0;
  494. const za = lz === 0 ? -1 : lz === 15 ? 1 : 0;
  495. const ya = ly === 0 ? -1 : ly === 15 ? 1 : 0;
  496. for (let dx = 0; dx <= 1; dx++) {
  497. if (dx === 1 && xa === 0) {
  498. break;
  499. }
  500. for (let dz = 0; dz <= 1; dz++) {
  501. if (dz === 1 && za === 0) {
  502. break;
  503. }
  504. for (let dy = 0; dy <= 1; dy++) {
  505. if (dy === 1 && ya === 0) {
  506. break;
  507. }
  508. const ns = sec + (dy ? ya : 0);
  509. if (ns < 0 || ns >= SECTIONS) {
  510. continue;
  511. }
  512. const nc = (dx || dz) ? this.chunkAt(c.cx + (dx ? xa : 0), c.cz + (dz ? za : 0)) : c;
  513. if (nc !== undefined) {
  514. nc.dirty[ns] = 1;
  515. }
  516. }
  517. }
  518. }
  519. }
  520. /* ---------------- block changes ---------------- */
  521. setBlock(x, y, z, id, meta = 0, notify = true) {
  522. if (y < 0 || y >= WORLD_H) {
  523. return false;
  524. }
  525. const c = this.chunkAt(x >> 4, z >> 4);
  526. if (c === undefined || !c.generated) {
  527. return false;
  528. }
  529. const i = ((x & 15) << 11) | ((z & 15) << 7) | y;
  530. const oldId = c.blocks[i], oldMeta = c.meta[i];
  531. if (oldId === id && oldMeta === meta) {
  532. return false;
  533. }
  534. c.blocks[i] = id;
  535. c.meta[i] = meta;
  536. //Grass spreading and plants growing in a chunk nobody touched are
  537. //not worth a save entry; the chunk simply regenerates
  538. if (!this.quiet) {
  539. c.modified = true;
  540. }
  541. this.updateHeightmaps(c, x & 15, y, z & 15);
  542. if (c.lit) {
  543. this.relight(x, y, z, oldId, oldMeta, id, meta);
  544. }
  545. this.markDirtyAround(x, y, z, c);
  546. if (oldId !== id) {
  547. if ((oldId === B.LOG || oldId === B.LEAVES) && id !== B.LOG) {
  548. this.scheduleLeafChecks(x, y, z);
  549. }
  550. if (oldId === B.FURNACE || oldId === B.FURNACE_LIT || oldId === B.CHEST) {
  551. if (id !== B.FURNACE && id !== B.FURNACE_LIT) {
  552. this.dropTileEntity(x, y, z);
  553. }
  554. }
  555. }
  556. if (notify) {
  557. this.notifyNeighbors(x, y, z);
  558. }
  559. return true;
  560. }
  561. setMeta(x, y, z, meta) {
  562. return this.setBlock(x, y, z, this.getBlock(x, y, z), meta, false);
  563. }
  564. updateHeightmaps(c, lx, y, lz) {
  565. const ci = lz * 16 + lx;
  566. const base = (lx << 11) | (lz << 7);
  567. const id = c.blocks[base | y];
  568. if (opacityOf(id, c.meta[base | y]) > 0) {
  569. if (y + 1 > c.hmLight[ci]) {
  570. c.hmLight[ci] = y + 1;
  571. }
  572. } else if (y + 1 === c.hmLight[ci]) {
  573. let yy = y - 1;
  574. while (yy >= 0 && opacityOf(c.blocks[base | yy], c.meta[base | yy]) === 0) {
  575. yy--;
  576. }
  577. c.hmLight[ci] = yy + 1;
  578. }
  579. if (RAIN_BLOCKING[id]) {
  580. if (y + 1 > c.hmRain[ci]) {
  581. c.hmRain[ci] = y + 1;
  582. }
  583. } else if (y + 1 === c.hmRain[ci]) {
  584. let yy = y - 1;
  585. while (yy >= 0 && !RAIN_BLOCKING[c.blocks[base | yy]]) {
  586. yy--;
  587. }
  588. c.hmRain[ci] = yy + 1;
  589. }
  590. }
  591. notifyNeighbors(x, y, z) {
  592. this.neighborChanged(x, y, z);
  593. for (let d = 0; d < 18; d += 3) {
  594. this.neighborChanged(x + DIRS[d], y + DIRS[d + 1], z + DIRS[d + 2]);
  595. }
  596. }
  597. neighborChanged(x, y, z) {
  598. if (y < 0 || y >= WORLD_H || !this.isLoaded(x, z)) {
  599. return;
  600. }
  601. const id = this.getBlock(x, y, z);
  602. if (id === B.AIR) {
  603. return;
  604. }
  605. const def = BLOCKS[id];
  606. if (id === B.WATER) {
  607. this.schedule(x, y, z, 5);
  608. } else if (def.gravity) {
  609. if (this.canFallInto(this.getBlock(x, y - 1, z))) {
  610. this.schedule(x, y, z, 2);
  611. }
  612. } else if (def.support) {
  613. this.schedule(x, y, z, 1);
  614. } else if (id === B.FARMLAND) {
  615. const above = this.getBlock(x, y + 1, z);
  616. if (isOpaqueAt(above, this.getMeta(x, y + 1, z))) {
  617. this.setBlock(x, y, z, B.DIRT);
  618. }
  619. }
  620. }
  621. canFallInto(id) {
  622. return id === B.AIR || id === B.WATER || WASHABLE[id] === 1;
  623. }
  624. hasSupport(x, y, z, id, meta) {
  625. const below = this.getBlock(x, y - 1, z);
  626. const belowMeta = this.getMeta(x, y - 1, z);
  627. switch (BLOCKS[id].support) {
  628. case "soil":
  629. return below === B.GRASS || below === B.DIRT || below === B.FARMLAND;
  630. case "solid":
  631. return isOpaqueAt(below, belowMeta);
  632. case "sand":
  633. return below === B.SAND || below === B.GRASS || below === B.DIRT;
  634. case "farmland":
  635. return below === B.FARMLAND;
  636. case "reeds":
  637. if (below === B.REEDS) {
  638. return true;
  639. }
  640. if (below !== B.GRASS && below !== B.DIRT && below !== B.SAND) {
  641. return false;
  642. }
  643. return this.waterBeside(x, y - 1, z);
  644. case "cactus":
  645. if (below !== B.CACTUS && below !== B.SAND) {
  646. return false;
  647. }
  648. for (let d = 0; d < 18; d += 3) {
  649. if (DIRS[d + 1] !== 0) {
  650. continue;
  651. }
  652. if (SOLID[this.getBlock(x + DIRS[d], y, z + DIRS[d + 2])]) {
  653. return false;
  654. }
  655. }
  656. return true;
  657. case "torch":
  658. case "wall": {
  659. const n = FACE_DIR[meta] || FACE_DIR[2];
  660. const ax = x - n[0], ay = y - n[1], az = z - n[2];
  661. const aid = this.getBlock(ax, ay, az), am = this.getMeta(ax, ay, az);
  662. if (isOpaqueAt(aid, am)) {
  663. return true;
  664. }
  665. //Torches also stand on top slabs
  666. return BLOCKS[id].support === "torch" && meta === 2 && IS_SLAB[aid] === 1 && am === 1;
  667. }
  668. default:
  669. return true;
  670. }
  671. }
  672. waterBeside(x, y, z) {
  673. for (let d = 0; d < 18; d += 3) {
  674. if (DIRS[d + 1] === 0 && this.getBlock(x + DIRS[d], y, z + DIRS[d + 2]) === B.WATER) {
  675. return true;
  676. }
  677. }
  678. return false;
  679. }
  680. //Break a block as if it broke by itself (drops items)
  681. breakNaturally(x, y, z) {
  682. const id = this.getBlock(x, y, z);
  683. const meta = this.getMeta(x, y, z);
  684. if (id === B.AIR || id === B.WATER) {
  685. return;
  686. }
  687. const drops = blockDrops(id, meta, this.rng, 0);
  688. this.setBlock(x, y, z, B.AIR, 0);
  689. if (this.onDrop) {
  690. for (const [did, n] of drops) {
  691. this.onDrop(x + 0.5, y + 0.4, z + 0.5, did, n);
  692. }
  693. }
  694. if (this.onBlockBroken) {
  695. this.onBlockBroken(x, y, z, id, true);
  696. }
  697. }
  698. /* ---------------- scheduled ticks ---------------- */
  699. schedule(x, y, z, delay) {
  700. const key = x + "," + y + "," + z;
  701. if (this.schedSet.has(key)) {
  702. return;
  703. }
  704. this.schedSet.add(key);
  705. const t = this.tickCount + Math.max(1, delay | 0);
  706. let b = this.schedBuckets.get(t);
  707. if (b === undefined) {
  708. b = [];
  709. this.schedBuckets.set(t, b);
  710. }
  711. b.push(x, y, z);
  712. }
  713. runScheduled() {
  714. const b = this.schedBuckets.get(this.tickCount);
  715. if (b === undefined) {
  716. return;
  717. }
  718. this.schedBuckets.delete(this.tickCount);
  719. const limit = Math.min(b.length, 3 * 600);
  720. for (let i = 0; i < limit; i += 3) {
  721. const x = b[i], y = b[i + 1], z = b[i + 2];
  722. this.schedSet.delete(x + "," + y + "," + z);
  723. if (this.isLoaded(x, z)) {
  724. this.scheduledTick(x, y, z);
  725. }
  726. }
  727. if (limit < b.length) {
  728. //Too much at once: carry the rest over to the next tick
  729. const rest = b.slice(limit);
  730. const nb = this.schedBuckets.get(this.tickCount + 1) || [];
  731. this.schedBuckets.set(this.tickCount + 1, nb.concat(rest));
  732. }
  733. }
  734. scheduledTick(x, y, z) {
  735. const id = this.getBlock(x, y, z);
  736. const meta = this.getMeta(x, y, z);
  737. const def = BLOCKS[id];
  738. if (id === B.WATER) {
  739. this.waterTick(x, y, z, meta);
  740. } else if (def.gravity) {
  741. if (this.canFallInto(this.getBlock(x, y - 1, z)) && y > 0) {
  742. if (this.onFalling) {
  743. this.setBlock(x, y, z, B.AIR, 0);
  744. this.onFalling(x, y, z, id, meta);
  745. }
  746. }
  747. } else if (def.support) {
  748. if (!this.hasSupport(x, y, z, id, meta)) {
  749. this.breakNaturally(x, y, z);
  750. }
  751. } else if (id === B.LEAVES && (meta & 1) === 0) {
  752. if (!this.logNearby(x, y, z)) {
  753. this.breakNaturally(x, y, z);
  754. }
  755. }
  756. }
  757. /* ---------------- water ---------------- */
  758. flowInto(x, y, z, level) {
  759. const id = this.getBlock(x, y, z);
  760. if (WASHABLE[id] === 1) {
  761. this.breakNaturally(x, y, z);
  762. }
  763. this.setBlock(x, y, z, B.WATER, level);
  764. }
  765. canFlow(id) {
  766. return id === B.AIR || WASHABLE[id] === 1;
  767. }
  768. waterTick(x, y, z, m) {
  769. if (m !== 0) {
  770. let newM;
  771. if (this.getBlock(x, y + 1, z) === B.WATER) {
  772. newM = 8;
  773. } else {
  774. let best = 99, sources = 0;
  775. for (let d = 0; d < 18; d += 3) {
  776. if (DIRS[d + 1] !== 0) {
  777. continue;
  778. }
  779. const nx = x + DIRS[d], nz = z + DIRS[d + 2];
  780. if (this.getBlock(nx, y, nz) === B.WATER) {
  781. const nm = this.getMeta(nx, y, nz);
  782. if (nm === 0) {
  783. sources++;
  784. }
  785. const eff = nm === 8 ? 0 : nm;
  786. if (eff + 1 < best) {
  787. best = eff + 1;
  788. }
  789. }
  790. }
  791. const below = this.getBlock(x, y - 1, z);
  792. if (sources >= 2 && (isOpaqueAt(below, this.getMeta(x, y - 1, z)) || (below === B.WATER && this.getMeta(x, y - 1, z) === 0))) {
  793. newM = 0;
  794. } else {
  795. newM = best <= 7 ? best : -1;
  796. }
  797. }
  798. if (newM === -1) {
  799. this.setBlock(x, y, z, B.AIR, 0);
  800. return;
  801. }
  802. if (newM !== m) {
  803. this.setBlock(x, y, z, B.WATER, newM);
  804. m = newM;
  805. }
  806. }
  807. const below = this.getBlock(x, y - 1, z);
  808. if (y > 0 && this.canFlow(below)) {
  809. this.flowInto(x, y - 1, z, 8);
  810. return;
  811. }
  812. if (below === B.WATER) {
  813. return;
  814. }
  815. const next = (m === 0 || m === 8) ? 1 : m + 1;
  816. if (next > 7) {
  817. return;
  818. }
  819. for (let d = 0; d < 18; d += 3) {
  820. if (DIRS[d + 1] !== 0) {
  821. continue;
  822. }
  823. const nx = x + DIRS[d], nz = z + DIRS[d + 2];
  824. if (!this.isLoaded(nx, nz)) {
  825. continue;
  826. }
  827. const nid = this.getBlock(nx, y, nz);
  828. if (this.canFlow(nid)) {
  829. this.flowInto(nx, y, nz, next);
  830. } else if (nid === B.WATER) {
  831. const nm = this.getMeta(nx, y, nz);
  832. if (nm !== 0 && nm !== 8 && nm > next) {
  833. this.setBlock(nx, y, nz, B.WATER, next);
  834. }
  835. }
  836. }
  837. }
  838. /* ---------------- leaves ---------------- */
  839. scheduleLeafChecks(x, y, z) {
  840. for (let dx = -4; dx <= 4; dx++) {
  841. for (let dy = -4; dy <= 4; dy++) {
  842. for (let dz = -4; dz <= 4; dz++) {
  843. const yy = y + dy;
  844. if (yy < 0 || yy >= WORLD_H) {
  845. continue;
  846. }
  847. if (this.getBlock(x + dx, yy, z + dz) === B.LEAVES && (this.getMeta(x + dx, yy, z + dz) & 1) === 0) {
  848. this.schedule(x + dx, yy, z + dz, 10 + Math.floor(this.rng() * 70));
  849. }
  850. }
  851. }
  852. }
  853. }
  854. logNearby(x, y, z) {
  855. const R = 4, W = 9;
  856. const seen = new Uint8Array(W * W * W);
  857. const q = [x, y, z, 0];
  858. seen[(R * W + R) * W + R] = 1;
  859. let i = 0;
  860. while (i < q.length) {
  861. const cx = q[i++], cy = q[i++], cz = q[i++], dist = q[i++];
  862. for (let d = 0; d < 18; d += 3) {
  863. const nx = cx + DIRS[d], ny = cy + DIRS[d + 1], nz = cz + DIRS[d + 2];
  864. const ox = nx - x + R, oy = ny - y + R, oz = nz - z + R;
  865. if (ox < 0 || oy < 0 || oz < 0 || ox >= W || oy >= W || oz >= W) {
  866. continue;
  867. }
  868. const si = (ox * W + oy) * W + oz;
  869. if (seen[si]) {
  870. continue;
  871. }
  872. seen[si] = 1;
  873. const id = this.getBlock(nx, ny, nz);
  874. if (id === B.LOG) {
  875. return true;
  876. }
  877. if (id === B.LEAVES && dist + 1 < R) {
  878. q.push(nx, ny, nz, dist + 1);
  879. }
  880. }
  881. }
  882. return false;
  883. }
  884. /* ---------------- random ticks ---------------- */
  885. randomTicks(pcx, pcz, radius) {
  886. const rng = this.rng;
  887. for (const c of this.chunks.values()) {
  888. if (!c.lit || Math.abs(c.cx - pcx) > radius || Math.abs(c.cz - pcz) > radius) {
  889. continue;
  890. }
  891. for (let s = 0; s < SECTIONS; s++) {
  892. for (let k = 0; k < 3; k++) {
  893. const r = (rng() * 4096) | 0;
  894. const lx = r & 15, lz = (r >> 4) & 15, y = s * 16 + (r >> 8);
  895. const id = c.blocks[(lx << 11) | (lz << 7) | y];
  896. if (id === B.GRASS || id === B.SAPLING || id === B.WHEAT || id === B.FARMLAND || id === B.REEDS || id === B.CACTUS) {
  897. this.randomTick(c.cx * 16 + lx, y, c.cz * 16 + lz, id);
  898. }
  899. }
  900. }
  901. }
  902. }
  903. randomTick(x, y, z, id) {
  904. if (id === B.GRASS || id === B.REEDS || id === B.CACTUS) {
  905. this.quiet = true;
  906. try {
  907. this.naturalTick(x, y, z, id);
  908. } finally {
  909. this.quiet = false;
  910. }
  911. return;
  912. }
  913. const rng = this.rng;
  914. const meta = this.getMeta(x, y, z);
  915. if (id === B.SAPLING) {
  916. if (this.effectiveLight(x, y, z) >= 9 && rng() < 0.07) {
  917. this.growTree(x, y, z);
  918. }
  919. } else if (id === B.WHEAT) {
  920. if (meta < 7 && this.effectiveLight(x, y, z) >= 9) {
  921. const wet = this.getMeta(x, y - 1, z) > 0;
  922. if (rng() < (wet ? 0.3 : 0.12)) {
  923. this.setBlock(x, y, z, B.WHEAT, meta + 1, false);
  924. }
  925. }
  926. } else if (id === B.FARMLAND) {
  927. let wet = this.raining && this.rainTop(x, z) <= y + 1;
  928. if (!wet) {
  929. for (let dx = -4; dx <= 4 && !wet; dx++) {
  930. for (let dz = -4; dz <= 4 && !wet; dz++) {
  931. for (let dy = 0; dy <= 1; dy++) {
  932. if (this.getBlock(x + dx, y + dy, z + dz) === B.WATER) {
  933. wet = true;
  934. break;
  935. }
  936. }
  937. }
  938. }
  939. }
  940. if (wet) {
  941. if (meta !== 7) {
  942. this.setBlock(x, y, z, B.FARMLAND, 7, false);
  943. }
  944. } else if (meta > 0) {
  945. this.setBlock(x, y, z, B.FARMLAND, meta - 1, false);
  946. } else if (this.getBlock(x, y + 1, z) !== B.WHEAT && rng() < 0.3) {
  947. this.setBlock(x, y, z, B.DIRT);
  948. }
  949. }
  950. }
  951. //Grass spreading / dying and reeds / cactus growing
  952. naturalTick(x, y, z, id) {
  953. const rng = this.rng;
  954. if (id === B.GRASS) {
  955. const above = this.getBlock(x, y + 1, z);
  956. if (isOpaqueAt(above, this.getMeta(x, y + 1, z)) || above === B.WATER) {
  957. this.setBlock(x, y, z, B.DIRT);
  958. return;
  959. }
  960. if (this.effectiveLight(x, y + 1, z) >= 9) {
  961. const tx = x + Math.floor(rng() * 3) - 1;
  962. const ty = y + Math.floor(rng() * 5) - 3;
  963. const tz = z + Math.floor(rng() * 3) - 1;
  964. if (this.getBlock(tx, ty, tz) === B.DIRT) {
  965. const a = this.getBlock(tx, ty + 1, tz);
  966. if (!isOpaqueAt(a, this.getMeta(tx, ty + 1, tz)) && a !== B.WATER && this.effectiveLight(tx, ty + 1, tz) >= 4) {
  967. this.setBlock(tx, ty, tz, B.GRASS);
  968. }
  969. }
  970. }
  971. return;
  972. }
  973. if (this.getBlock(x, y + 1, z) !== B.AIR || rng() > 0.08) {
  974. return;
  975. }
  976. let h = 1;
  977. while (h < 4 && this.getBlock(x, y - h, z) === id) {
  978. h++;
  979. }
  980. if (h < 3) {
  981. this.setBlock(x, y + 1, z, id, 0);
  982. }
  983. }
  984. growTree(x, y, z) {
  985. const plan = this.gen.treeBlocks(x, y, z, this.rng);
  986. if (y + plan.height >= WORLD_H - 1) {
  987. return false;
  988. }
  989. //Trunk needs free space
  990. for (const [bx, by, bz, id] of plan.blocks) {
  991. if (id === B.LOG && !(bx === x && by === y && bz === z)) {
  992. const cur = this.getBlock(bx, by, bz);
  993. if (cur !== B.AIR && cur !== B.LEAVES && cur !== B.TALL_GRASS) {
  994. return false;
  995. }
  996. }
  997. }
  998. this.setBlock(x, y, z, B.AIR, 0, false);
  999. if (this.getBlock(x, y - 1, z) === B.GRASS) {
  1000. this.setBlock(x, y - 1, z, B.DIRT, 0, false);
  1001. }
  1002. for (const [bx, by, bz, id] of plan.blocks) {
  1003. const cur = this.getBlock(bx, by, bz);
  1004. if (id === B.LOG || cur === B.AIR || cur === B.TALL_GRASS) {
  1005. this.setBlock(bx, by, bz, id, 0, false);
  1006. }
  1007. }
  1008. return true;
  1009. }
  1010. /* ---------------- tile entities ---------------- */
  1011. teKey(x, y, z) {
  1012. return x + "," + y + "," + z;
  1013. }
  1014. getTileEntity(x, y, z) {
  1015. return this.tileEntities.get(this.teKey(x, y, z)) || null;
  1016. }
  1017. createTileEntity(x, y, z, type) {
  1018. const te = type === "furnace"
  1019. ? { type, slots: [null, null, null], burn: 0, burnMax: 0, cook: 0 }
  1020. : { type, slots: new Array(27).fill(null) };
  1021. this.tileEntities.set(this.teKey(x, y, z), te);
  1022. return te;
  1023. }
  1024. dropTileEntity(x, y, z) {
  1025. const key = this.teKey(x, y, z);
  1026. const te = this.tileEntities.get(key);
  1027. if (!te) {
  1028. return;
  1029. }
  1030. this.tileEntities.delete(key);
  1031. if (this.onDrop) {
  1032. for (const s of te.slots) {
  1033. if (s && s.count > 0) {
  1034. this.onDrop(x + 0.5, y + 0.5, z + 0.5, s.id, s.count, s.dmg || 0);
  1035. }
  1036. }
  1037. }
  1038. }
  1039. tickFurnaces() {
  1040. for (const [key, te] of this.tileEntities) {
  1041. if (te.type !== "furnace") {
  1042. continue;
  1043. }
  1044. const p = key.split(",").map(Number);
  1045. if (!this.isLoaded(p[0], p[2])) {
  1046. continue;
  1047. }
  1048. const [input, fuel, output] = te.slots;
  1049. const result = input ? SMELTING.get(input.id) : undefined;
  1050. const canSmelt = result !== undefined &&
  1051. (!output || (output.id === result && output.count < ((ITEMS[result] && ITEMS[result].stack) || 64)));
  1052. const wasBurning = te.burn > 0;
  1053. if (te.burn > 0) {
  1054. te.burn--;
  1055. }
  1056. if (te.burn === 0 && canSmelt && fuel && fuelTicks(fuel.id) > 0) {
  1057. te.burn = te.burnMax = fuelTicks(fuel.id);
  1058. fuel.count--;
  1059. if (fuel.count <= 0) {
  1060. te.slots[1] = null;
  1061. }
  1062. }
  1063. if (te.burn > 0 && canSmelt) {
  1064. te.cook++;
  1065. if (te.cook >= SMELT_TICKS) {
  1066. te.cook = 0;
  1067. input.count--;
  1068. if (input.count <= 0) {
  1069. te.slots[0] = null;
  1070. }
  1071. if (output) {
  1072. output.count++;
  1073. } else {
  1074. te.slots[2] = { id: result, count: 1 };
  1075. }
  1076. }
  1077. } else {
  1078. te.cook = Math.max(0, te.cook - 2);
  1079. }
  1080. const burning = te.burn > 0;
  1081. if (burning !== wasBurning) {
  1082. const id = this.getBlock(p[0], p[1], p[2]);
  1083. if (id === B.FURNACE || id === B.FURNACE_LIT) {
  1084. this.setBlock(p[0], p[1], p[2], burning ? B.FURNACE_LIT : B.FURNACE, this.getMeta(p[0], p[1], p[2]), false);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. /* ---------------- per tick ---------------- */
  1090. tick(pcx, pcz) {
  1091. this.tickCount++;
  1092. this.runScheduled();
  1093. this.randomTicks(pcx, pcz, 6);
  1094. this.tickFurnaces();
  1095. }
  1096. /* ---------------- raycast ---------------- */
  1097. //Voxel walk from origin along dir; boxes(id, meta) gives hit boxes
  1098. raycast(ox, oy, oz, dx, dy, dz, maxDist, boxes) {
  1099. let x = Math.floor(ox), y = Math.floor(oy), z = Math.floor(oz);
  1100. const stepX = dx > 0 ? 1 : -1, stepY = dy > 0 ? 1 : -1, stepZ = dz > 0 ? 1 : -1;
  1101. const tDeltaX = dx !== 0 ? Math.abs(1 / dx) : Infinity;
  1102. const tDeltaY = dy !== 0 ? Math.abs(1 / dy) : Infinity;
  1103. const tDeltaZ = dz !== 0 ? Math.abs(1 / dz) : Infinity;
  1104. let tMaxX = dx !== 0 ? ((dx > 0 ? x + 1 - ox : ox - x) * tDeltaX) : Infinity;
  1105. let tMaxY = dy !== 0 ? ((dy > 0 ? y + 1 - oy : oy - y) * tDeltaY) : Infinity;
  1106. let tMaxZ = dz !== 0 ? ((dz > 0 ? z + 1 - oz : oz - z) * tDeltaZ) : Infinity;
  1107. for (let guard = 0; guard < 64; guard++) {
  1108. const id = this.getBlock(x, y, z);
  1109. if (id !== B.AIR && y >= 0 && y < WORLD_H) {
  1110. const box = boxes(id, this.getMeta(x, y, z));
  1111. if (box) {
  1112. const hit = rayBox(ox - x, oy - y, oz - z, dx, dy, dz, box);
  1113. if (hit && hit.t <= maxDist) {
  1114. return { x, y, z, id, meta: this.getMeta(x, y, z), face: hit.face, t: hit.t, box,
  1115. point: [ox + dx * hit.t, oy + dy * hit.t, oz + dz * hit.t] };
  1116. }
  1117. }
  1118. }
  1119. if (tMaxX < tMaxY && tMaxX < tMaxZ) {
  1120. if (tMaxX > maxDist) {
  1121. break;
  1122. }
  1123. x += stepX;
  1124. tMaxX += tDeltaX;
  1125. } else if (tMaxY < tMaxZ) {
  1126. if (tMaxY > maxDist) {
  1127. break;
  1128. }
  1129. y += stepY;
  1130. tMaxY += tDeltaY;
  1131. } else {
  1132. if (tMaxZ > maxDist) {
  1133. break;
  1134. }
  1135. z += stepZ;
  1136. tMaxZ += tDeltaZ;
  1137. }
  1138. }
  1139. return null;
  1140. }
  1141. /* ---------------- save data ---------------- */
  1142. serialize() {
  1143. const chunks = {};
  1144. for (const [k, v] of this.saved) {
  1145. chunks[keyName(k)] = v;
  1146. }
  1147. for (const c of this.chunks.values()) {
  1148. if (c.modified && c.generated) {
  1149. chunks[keyName(c.key)] = bytesToBase64(rleEncode(c.blocks, c.meta));
  1150. }
  1151. }
  1152. const tileEntities = {};
  1153. for (const [k, v] of this.tileEntities) {
  1154. tileEntities[k] = v;
  1155. }
  1156. return { chunks, tileEntities };
  1157. }
  1158. load(data) {
  1159. this.saved.clear();
  1160. if (data && data.chunks) {
  1161. for (const name of Object.keys(data.chunks)) {
  1162. const [cx, cz] = name.split(",").map(Number);
  1163. this.saved.set(chunkKey(cx, cz), data.chunks[name]);
  1164. }
  1165. }
  1166. this.tileEntities.clear();
  1167. if (data && data.tileEntities) {
  1168. for (const k of Object.keys(data.tileEntities)) {
  1169. this.tileEntities.set(k, data.tileEntities[k]);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. function keyName(key) {
  1175. return (Math.floor(key / 65536) - 32768) + "," + ((key % 65536) - 32768);
  1176. }
  1177. //Ray against an axis aligned box in block local space
  1178. function rayBox(ox, oy, oz, dx, dy, dz, b) {
  1179. let tmin = -Infinity, tmax = Infinity, face = -1;
  1180. const axes = [[ox, dx, b[0], b[3], 1, 0], [oy, dy, b[1], b[4], 3, 2], [oz, dz, b[2], b[5], 5, 4]];
  1181. for (const [o, d, lo, hi, faceLo, faceHi] of axes) {
  1182. if (Math.abs(d) < 1e-9) {
  1183. if (o < lo || o > hi) {
  1184. return null;
  1185. }
  1186. continue;
  1187. }
  1188. let t1 = (lo - o) / d, t2 = (hi - o) / d;
  1189. let f1 = faceLo, f2 = faceHi;
  1190. if (t1 > t2) {
  1191. [t1, t2] = [t2, t1];
  1192. [f1, f2] = [f2, f1];
  1193. }
  1194. if (t1 > tmin) {
  1195. tmin = t1;
  1196. face = f1;
  1197. }
  1198. if (t2 < tmax) {
  1199. tmax = t2;
  1200. }
  1201. if (tmin > tmax) {
  1202. return null;
  1203. }
  1204. }
  1205. if (tmax < 0) {
  1206. return null;
  1207. }
  1208. return { t: Math.max(0, tmin), face };
  1209. }
  1210. export { opacityOf, SEA, WORLD_H };