code stash
This commit is contained in:
commit
9c77cf3e30
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/node_modules/
|
||||
/dist/
|
21
index.html
Normal file
21
index.html
Normal file
@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" dir="ltr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>voxeltest</title>
|
||||
<style media="screen">
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
body, html {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script src="./index.js" charset="utf-8" type="module"></script>
|
||||
</body>
|
||||
</html>
|
6665
package-lock.json
generated
Normal file
6665
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
package.json
Normal file
19
package.json
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "voxeltest",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"watch": "webpack -w --mode=development"
|
||||
},
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"simplex-noise": "^2.4.0",
|
||||
"three": "^0.121.1",
|
||||
"webpack": "^5.1.3",
|
||||
"webpack-cli": "^4.0.0",
|
||||
"worker-loader": "^3.0.5"
|
||||
}
|
||||
}
|
178
src/chunk.worker.js
Normal file
178
src/chunk.worker.js
Normal file
@ -0,0 +1,178 @@
|
||||
import { BrownianSimplexNoise } from './noise.js'
|
||||
|
||||
const LEFT = 0
|
||||
const RIGHT = 1
|
||||
const FRONT = 2
|
||||
const BACK = 3
|
||||
const TOP = 4
|
||||
const BOTTOM = 5
|
||||
|
||||
class ChunkWorker {
|
||||
setNoise (params) {
|
||||
if (this.noise) return
|
||||
this.noise = new BrownianSimplexNoise(
|
||||
params.seed,
|
||||
params.amplitude,
|
||||
params.period,
|
||||
params.persistence,
|
||||
params.lacunarity,
|
||||
params.octaves
|
||||
)
|
||||
}
|
||||
|
||||
getBlockAt (voldata, dims, x, y, z) {
|
||||
if (voldata.neighbors) {
|
||||
if (x < 0) return this.getBlockAt(voldata.neighbors[RIGHT], dims, dims[0] - 1, y, z)
|
||||
if (x >= dims[0]) return this.getBlockAt(voldata.neighbors[LEFT], dims, 0, y, z)
|
||||
if (z < 0) return this.getBlockAt(voldata.neighbors[FRONT], dims, x, y, dims[2] - 1)
|
||||
if (z >= dims[2]) return this.getBlockAt(voldata.neighbors[BACK], dims, x, y, 0)
|
||||
if (y < 0 || y >= dims[1]) return null
|
||||
}
|
||||
return (voldata.volume ? voldata.volume : voldata)[x + dims[0] * (y + dims[1] * z)]
|
||||
}
|
||||
|
||||
generate (params) {
|
||||
const absposi = params.x * params.dims[0]
|
||||
const absposj = params.y * params.dims[2]
|
||||
|
||||
const volume = []
|
||||
for (let x = 0; x < params.dims[0]; x++) {
|
||||
for (let z = 0; z < params.dims[2]; z++) {
|
||||
const height = this.noise.getNoise2D(absposi + x, absposj + z) * 10 + 64
|
||||
for (let y = 0; y < params.dims[1]; y++) {
|
||||
volume[x + params.dims[0] * (y + params.dims[1] * z)] = (y < height) ? 1 : 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return volume
|
||||
}
|
||||
|
||||
mesh (params) {
|
||||
const dims = params.dims
|
||||
const vertices = []
|
||||
const indices = []
|
||||
const normals = []
|
||||
|
||||
for (let backFace = true, b = false; b !== backFace; backFace = backFace && b, b = !b) {
|
||||
// Sweep over 3-axes
|
||||
for (let d = 0; d < 3; ++d) {
|
||||
let i, j, k, l, w, h, side
|
||||
const u = (d + 1) % 3
|
||||
const v = (d + 2) % 3
|
||||
const x = [0, 0, 0]
|
||||
const q = [0, 0, 0]
|
||||
|
||||
// Here we're keeping track of the side that we're meshing.
|
||||
if (d === 0) side = backFace ? LEFT : RIGHT
|
||||
else if (d === 1) side = backFace ? BOTTOM : TOP
|
||||
else if (d === 2) side = backFace ? BACK : FRONT
|
||||
|
||||
const mask = new Int32Array(dims[u] * dims[v])
|
||||
q[d] = 1
|
||||
// Move through the dimension from front to back
|
||||
for (x[d] = -1; x[d] < dims[d];) {
|
||||
// Compute mask
|
||||
let n = 0
|
||||
for (x[v] = 0; x[v] < dims[v]; ++x[v]) {
|
||||
for (x[u] = 0; x[u] < dims[u]; ++x[u]) {
|
||||
const current = this.getBlockAt(params, dims, x[0], x[1], x[2])
|
||||
const ajacent = this.getBlockAt(params, dims, x[0] + q[0], x[1] + q[1], x[2] + q[2])
|
||||
mask[n++] = ((current && ajacent && current === ajacent)) ? null : (backFace ? ajacent : current)
|
||||
}
|
||||
}
|
||||
|
||||
// Increment x[d]
|
||||
++x[d]
|
||||
|
||||
// Generate mesh for mask using lexicographic ordering
|
||||
n = 0
|
||||
for (j = 0; j < dims[v]; ++j) {
|
||||
for (i = 0; i < dims[u];) {
|
||||
if (mask[n]) {
|
||||
// Compute width
|
||||
for (w = 1; mask[n + w] && mask[n + w] === mask[n] && i + w < dims[u]; ++w) {}
|
||||
|
||||
// Compute height
|
||||
let done = false
|
||||
for (h = 1; j + h < dims[v]; ++h) {
|
||||
for (k = 0; k < w; ++k) {
|
||||
if (!mask[n + k + h * dims[u]] || mask[n + k + h * dims[u]] !== mask[n]) {
|
||||
done = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (done) break
|
||||
}
|
||||
|
||||
// Create quad
|
||||
x[u] = i
|
||||
x[v] = j
|
||||
|
||||
const du = [0, 0, 0]
|
||||
du[u] = w
|
||||
|
||||
const dv = [0, 0, 0]
|
||||
dv[v] = h
|
||||
|
||||
const quad = [
|
||||
[x[0], x[1], x[2]],
|
||||
[x[0] + du[0], x[1] + du[1], x[2] + du[2]],
|
||||
[x[0] + du[0] + dv[0], x[1] + du[1] + dv[1], x[2] + du[2] + dv[2]],
|
||||
[x[0] + dv[0], x[1] + dv[1], x[2] + dv[2]]
|
||||
]
|
||||
|
||||
// Add vertices and normals
|
||||
const mul = backFace ? -1 : 1
|
||||
for (var qindex = 0; qindex < 4; ++qindex) {
|
||||
vertices.push(quad[qindex][0], quad[qindex][1], quad[qindex][2])
|
||||
normals.push(q[0] * mul, q[1] * mul, q[2] * mul)
|
||||
}
|
||||
|
||||
// Add indices
|
||||
const indexi = vertices.length / 3 - 4
|
||||
if (backFace) {
|
||||
indices.push(indexi + 2, indexi + 1, indexi)
|
||||
indices.push(indexi + 3, indexi + 2, indexi)
|
||||
} else {
|
||||
indices.push(indexi, indexi + 1, indexi + 2)
|
||||
indices.push(indexi, indexi + 2, indexi + 3)
|
||||
}
|
||||
|
||||
// Zero-out mask
|
||||
for (l = 0; l < h; ++l) {
|
||||
for (k = 0; k < w; ++k) {
|
||||
mask[n + k + l * dims[u]] = false
|
||||
}
|
||||
}
|
||||
|
||||
// Increment counters and continue
|
||||
i += w
|
||||
n += w
|
||||
} else {
|
||||
++i
|
||||
++n
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { vertices, indices, normals }
|
||||
}
|
||||
}
|
||||
|
||||
/* global self */
|
||||
const WORKER = new ChunkWorker()
|
||||
self.onmessage = function (e) {
|
||||
const data = JSON.parse(e.data)
|
||||
if (data.subject === 'gen') {
|
||||
WORKER.setNoise(data)
|
||||
const chunkData = WORKER.generate(data)
|
||||
self.postMessage(JSON.stringify({ subject: 'gen_result', data: chunkData }))
|
||||
} else if (data.subject === 'mesh') {
|
||||
const meshData = WORKER.mesh(data)
|
||||
self.postMessage(JSON.stringify({ subject: 'mesh_data', data: meshData }))
|
||||
}
|
||||
}
|
376
src/index.js
Normal file
376
src/index.js
Normal file
@ -0,0 +1,376 @@
|
||||
import * as THREE from 'three'
|
||||
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
|
||||
import Worker from './chunk.worker.js'
|
||||
|
||||
const renderer = new THREE.WebGLRenderer()
|
||||
renderer.setSize(window.innerWidth, window.innerHeight)
|
||||
|
||||
const div = document.createElement('div')
|
||||
div.appendChild(renderer.domElement)
|
||||
document.body.appendChild(div)
|
||||
|
||||
renderer.setClearColor(0x00aaff)
|
||||
|
||||
const scene = new THREE.Scene()
|
||||
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
|
||||
|
||||
const controls = new OrbitControls(camera, renderer.domElement)
|
||||
|
||||
class GeometryFromArrays extends THREE.BufferGeometry {
|
||||
constructor (vertices, indices, normals) {
|
||||
super()
|
||||
this.setIndex(indices)
|
||||
this.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3))
|
||||
this.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3))
|
||||
// this.computeVertexNormals()
|
||||
}
|
||||
}
|
||||
|
||||
const mat = new THREE.MeshStandardMaterial()
|
||||
mat.color = new THREE.Color(0x02ff02)
|
||||
// mat.wireframe = true
|
||||
// mat.side = THREE.DoubleSide
|
||||
/*
|
||||
mat.vertexShader = `
|
||||
void main (void) {
|
||||
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position,1);
|
||||
}
|
||||
`
|
||||
|
||||
mat.fragmentShader = `
|
||||
void main (void) {
|
||||
gl_FragColor = vec4(0.2, 1.0, 0.2, 1.0);
|
||||
}
|
||||
`
|
||||
*/
|
||||
const LEFT = 0
|
||||
const RIGHT = 1
|
||||
const FRONT = 2
|
||||
const BACK = 3
|
||||
const TOP = 4
|
||||
const BOTTOM = 5
|
||||
|
||||
let workerIDs = 0
|
||||
let chunkIDs = 0
|
||||
|
||||
class WorkerThread {
|
||||
constructor (script) {
|
||||
this.worker = new Worker(script)
|
||||
this.worker.onmessage = (e) => this.onMessage(e)
|
||||
this.resolve = null
|
||||
this.id = workerIDs++
|
||||
this.worker.onerror = function (event) {
|
||||
console.log(event.message, event)
|
||||
}
|
||||
}
|
||||
|
||||
onMessage (e) {
|
||||
const resolve = this.resolve
|
||||
this.resolve = null
|
||||
resolve(e.data)
|
||||
}
|
||||
|
||||
postMessage (data, resolve) {
|
||||
this.resolve = resolve
|
||||
this.worker.postMessage(data)
|
||||
}
|
||||
}
|
||||
|
||||
class WorkerThreadPool {
|
||||
constructor (workers, script) {
|
||||
this.workers = [...Array(workers)].map(_ => new WorkerThread(script))
|
||||
this.free = [...this.workers]
|
||||
this.busy = {}
|
||||
this.queue = []
|
||||
}
|
||||
|
||||
enqueue (data, resolve) {
|
||||
this.queue.push([data, resolve])
|
||||
this.pump()
|
||||
}
|
||||
|
||||
pump () {
|
||||
while (this.free.length > 0 && this.queue.length > 0) {
|
||||
const w = this.free.pop()
|
||||
this.busy[w.id] = w
|
||||
|
||||
const [workItem, workResolve] = this.queue.shift()
|
||||
w.postMessage(workItem, (v) => {
|
||||
delete this.busy[w.id]
|
||||
this.free.push(w)
|
||||
workResolve(v)
|
||||
this.pump()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Chunk {
|
||||
constructor (w, x, y, dims) {
|
||||
this.world = w
|
||||
this.volume = []
|
||||
this.dims = dims
|
||||
this.x = x
|
||||
this.y = y
|
||||
this.dirty = false
|
||||
this.id = chunkIDs++
|
||||
this.generatorWaiting = false
|
||||
this.mesherWaiting = false
|
||||
this.disposed = false
|
||||
this.meshReady = false
|
||||
}
|
||||
|
||||
generate () {
|
||||
if (this.volume.length || this.generatorWaiting || this.disposed) return
|
||||
this.generatorWaiting = true
|
||||
this.world.thread.enqueue(JSON.stringify(Object.assign({
|
||||
subject: 'gen',
|
||||
x: this.x,
|
||||
y: this.y,
|
||||
dims: this.dims
|
||||
}, this.world.noiseParams)), (e) => {
|
||||
e = JSON.parse(e)
|
||||
this.generatorWaiting = false
|
||||
if (e.subject !== 'gen_result' || this.disposed) return
|
||||
this.volume = e.data
|
||||
this.dirty = true
|
||||
this.notifyNeighbors()
|
||||
})
|
||||
}
|
||||
|
||||
getBlockAt (x, y, z) {
|
||||
if (x < 0) return this.getNeighbor(LEFT).getBlockAt(this.dims[0] - 1, y, z)
|
||||
if (x >= this.dims[0]) return this.getNeighbor(RIGHT).getBlockAt(0, y, z)
|
||||
if (z < 0) return this.getNeighbor(FRONT).getBlockAt(x, y, this.dims[2] - 1)
|
||||
if (z >= this.dims[2]) return this.getNeighbor(BACK).getBlockAt(x, y, 0)
|
||||
if (y < 0 || y >= this.dims[1]) return null
|
||||
return this.volume[x + this.dims[0] * (y + this.dims[1] * z)]
|
||||
}
|
||||
|
||||
getNeighbor (side) {
|
||||
let neighbor
|
||||
switch (side) {
|
||||
case LEFT:
|
||||
neighbor = this.world.getChunkByPosition(this.x - 1, this.y)
|
||||
break
|
||||
case RIGHT:
|
||||
neighbor = this.world.getChunkByPosition(this.x + 1, this.y)
|
||||
break
|
||||
case FRONT:
|
||||
neighbor = this.world.getChunkByPosition(this.x, this.y - 1)
|
||||
break
|
||||
case BACK:
|
||||
neighbor = this.world.getChunkByPosition(this.x, this.y + 1)
|
||||
break
|
||||
}
|
||||
return neighbor
|
||||
}
|
||||
|
||||
hasNeighbors () {
|
||||
let has = true
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const n = this.getNeighbor(i)
|
||||
if (!n || !n.isGenerated()) {
|
||||
has = false
|
||||
break
|
||||
}
|
||||
}
|
||||
return has
|
||||
}
|
||||
|
||||
notifyNeighbors () {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const n = this.getNeighbor(i)
|
||||
if (n) n.markDirty()
|
||||
}
|
||||
}
|
||||
|
||||
isGenerated () {
|
||||
return this.volume.length > 0
|
||||
}
|
||||
|
||||
isMeshed () {
|
||||
return this.mesh != null
|
||||
}
|
||||
|
||||
markDirty () {
|
||||
this.dirty = true
|
||||
}
|
||||
|
||||
createMesh () {
|
||||
if (this.meshReady) {
|
||||
if (this.disposed) return this.destroyMesh()
|
||||
scene.add(this.mesh)
|
||||
this.dirty = false
|
||||
this.meshReady = false
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.hasNeighbors() || this.disposed || this.mesherWaiting) return false
|
||||
this.mesherWaiting = true
|
||||
this.world.thread.enqueue(JSON.stringify({
|
||||
subject: 'mesh',
|
||||
dims: this.dims,
|
||||
volume: this.volume,
|
||||
neighbors: [
|
||||
this.getNeighbor(RIGHT).volume,
|
||||
this.getNeighbor(LEFT).volume,
|
||||
this.getNeighbor(FRONT).volume,
|
||||
this.getNeighbor(BACK).volume
|
||||
]
|
||||
}), (e) => {
|
||||
e = JSON.parse(e)
|
||||
this.mesherWaiting = false
|
||||
if (e.subject !== 'mesh_data' || this.disposed) return
|
||||
|
||||
const geom = new GeometryFromArrays(e.data.vertices, e.data.indices, e.data.normals)
|
||||
const mesh = new THREE.Mesh(geom, mat)
|
||||
|
||||
mesh.position.set(this.x * this.dims[0], 0, this.y * this.dims[2])
|
||||
|
||||
if (this.mesh) this.destroyMesh()
|
||||
this.mesh = mesh
|
||||
this.meshReady = true
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
dispose () {
|
||||
this.disposed = true
|
||||
this.destroyMesh()
|
||||
}
|
||||
|
||||
destroyMesh () {
|
||||
if (!this.mesh) return
|
||||
scene.remove(this.mesh)
|
||||
this.mesh.geometry.dispose()
|
||||
this.mesh = null
|
||||
}
|
||||
}
|
||||
|
||||
class ChunkWorld {
|
||||
constructor (dims) {
|
||||
this.dims = dims
|
||||
this.chunks = {}
|
||||
// amplitude - Controls the amount the height changes. The higher, the taller the hills.
|
||||
// period - Distance above which we start to see similarities. The higher, the longer "hills" will be on a terrain.
|
||||
// persistence - Controls details, value in [0,1]. Higher increases grain, lower increases smoothness.
|
||||
// lacunarity - Controls period change across octaves. 2 is usually a good value to address all detail levels.
|
||||
// octaves - Number of noise layers
|
||||
this.noiseParams = { seed: '123', amplitude: 15, period: 0.01, persistence: 0.4, lacunarity: 2, octaves: 5 }
|
||||
|
||||
this.thread = new WorkerThreadPool(4, 'src/chunk-worker.js')
|
||||
|
||||
this.generateQueue = []
|
||||
this.updateQueue = []
|
||||
this.rebuildQueue = []
|
||||
this.loadQueue = []
|
||||
this.unloadQueue = []
|
||||
}
|
||||
|
||||
getChunkByPosition (x, y) {
|
||||
return this.chunks[x + ';' + y]
|
||||
}
|
||||
|
||||
updateChunks (cam) {
|
||||
for (const ch in this.chunks) {
|
||||
const chunk = this.chunks[ch]
|
||||
const dist = cam.position.distanceTo(new THREE.Vector3(chunk.x * this.dims[0], cam.position.y, chunk.y * this.dims[2]))
|
||||
if (dist < 256) {
|
||||
if (chunk.dirty && chunk.isGenerated()) this.rebuildQueue.push(chunk)
|
||||
if (!chunk.isGenerated()) this.generateQueue.push(chunk)
|
||||
} else {
|
||||
this.unloadQueue.push(chunk)
|
||||
}
|
||||
}
|
||||
|
||||
const grid = new THREE.Vector3(
|
||||
Math.floor(cam.position.x / this.dims[0]),
|
||||
Math.floor(cam.position.y / this.dims[1]),
|
||||
Math.floor(cam.position.z / this.dims[2])
|
||||
)
|
||||
|
||||
for (let x = grid.x - 6; x < grid.x + 6; x++) {
|
||||
for (let y = grid.z - 6; y < grid.z + 6; y++) {
|
||||
if (this.getChunkByPosition(x, y)) continue
|
||||
const c = new Chunk(this, x, y, this.dims)
|
||||
this.chunks[x + ';' + y] = c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rebuildChunks () {
|
||||
for (const i in this.rebuildQueue) {
|
||||
const c = this.rebuildQueue[i]
|
||||
c.createMesh()
|
||||
}
|
||||
this.rebuildQueue = []
|
||||
}
|
||||
|
||||
generateChunks () {
|
||||
for (const i in this.generateQueue) {
|
||||
const c = this.generateQueue[i]
|
||||
c.generate()
|
||||
}
|
||||
this.generateQueue = []
|
||||
}
|
||||
|
||||
unloadChunks () {
|
||||
for (const i in this.unloadQueue) {
|
||||
const c = this.unloadQueue[i]
|
||||
c.dispose()
|
||||
delete this.chunks[c.x + ';' + c.y]
|
||||
}
|
||||
this.unloadQueue = []
|
||||
}
|
||||
|
||||
update (cam) {
|
||||
this.updateChunks(cam)
|
||||
this.generateChunks()
|
||||
this.rebuildChunks()
|
||||
this.unloadChunks()
|
||||
}
|
||||
}
|
||||
|
||||
const cw = new ChunkWorld([16, 256, 16])
|
||||
|
||||
camera.position.x = 0
|
||||
camera.position.y = 150
|
||||
camera.position.z = 0
|
||||
|
||||
const light = new THREE.DirectionalLight(0xffffff, 0.5)
|
||||
light.position.set(1, 1, 1)
|
||||
scene.add(light)
|
||||
|
||||
const alight = new THREE.AmbientLight(0x202020)
|
||||
scene.add(alight)
|
||||
|
||||
controls.update()
|
||||
|
||||
function loop () {
|
||||
window.requestAnimationFrame(loop)
|
||||
controls.update()
|
||||
cw.update(camera)
|
||||
renderer.render(scene, camera)
|
||||
}
|
||||
|
||||
function start () {
|
||||
let mpos = new THREE.Vector2(0, 0)
|
||||
|
||||
div.addEventListener('pointerdown', function (e) {
|
||||
console.log('?')
|
||||
})
|
||||
|
||||
div.addEventListener('mousemove', function (e) {
|
||||
})
|
||||
|
||||
div.addEventListener('mouseup', function (e) {
|
||||
})
|
||||
loop()
|
||||
}
|
||||
|
||||
renderer.domElement.addEventListener('keyup', function (e) {
|
||||
if (e.key === 'x') mat.wireframe = !mat.wireframe
|
||||
})
|
||||
start()
|
55
src/noise.js
Normal file
55
src/noise.js
Normal file
@ -0,0 +1,55 @@
|
||||
import * as SimplexNoise from 'simplex-noise'
|
||||
|
||||
class BrownianSimplexNoise extends SimplexNoise {
|
||||
// amplitude - Controls the amount the height changes. The higher, the taller the hills.
|
||||
// persistence - Controls details, value in [0,1]. Higher increases grain, lower increases smoothness.
|
||||
// octaves - Number of noise layers
|
||||
// period - Distance above which we start to see similarities. The higher, the longer "hills" will be on a terrain.
|
||||
// lacunarity - Controls period change across octaves. 2 is usually a good value to address all detail levels.
|
||||
constructor (rand, amplitude = 15, period = 0.01, persistence = 0.4, lacunarity = 2, octaves = 5) {
|
||||
super(rand)
|
||||
|
||||
this.amplitude = amplitude
|
||||
this.period = period
|
||||
this.lacunarity = lacunarity
|
||||
this.persistence = persistence
|
||||
this.octaves = octaves
|
||||
}
|
||||
|
||||
// Fractal/Fractional Brownian Motion (fBm) summation of 3D Perlin Simplex noise
|
||||
getNoise3D (x, y, z) {
|
||||
let output = 0.0
|
||||
let denom = 0.0
|
||||
let frequency = this.period
|
||||
let amplitude = this.amplitude
|
||||
|
||||
for (let i = 0; i < this.octaves; i++) {
|
||||
output += (amplitude * this.noise3D(x * frequency, y * frequency, z * frequency))
|
||||
denom += amplitude
|
||||
|
||||
frequency *= this.lacunarity
|
||||
amplitude *= this.persistence
|
||||
}
|
||||
|
||||
return (output / denom)
|
||||
}
|
||||
|
||||
getNoise2D (x, y) {
|
||||
let output = 0.0
|
||||
let denom = 0.0
|
||||
let frequency = this.period
|
||||
let amplitude = this.amplitude
|
||||
|
||||
for (let i = 0; i < this.octaves; i++) {
|
||||
output += (amplitude * this.noise2D(x * frequency, y * frequency))
|
||||
denom += amplitude
|
||||
|
||||
frequency *= this.lacunarity
|
||||
amplitude *= this.persistence
|
||||
}
|
||||
|
||||
return (output / denom)
|
||||
}
|
||||
}
|
||||
|
||||
export { BrownianSimplexNoise }
|
239
src/seedrandom.js
Normal file
239
src/seedrandom.js
Normal file
@ -0,0 +1,239 @@
|
||||
/*
|
||||
Copyright 2019 David Bau.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
(function (global, pool, math) {
|
||||
//
|
||||
// The following constants are related to IEEE 754 limits.
|
||||
//
|
||||
|
||||
var width = 256, // each RC4 output is 0 <= x < 256
|
||||
chunks = 6, // at least six RC4 outputs for each double
|
||||
digits = 52, // there are 52 significant digits in a double
|
||||
rngname = 'random', // rngname: name for Math.random and Math.seedrandom
|
||||
startdenom = math.pow(width, chunks),
|
||||
significance = math.pow(2, digits),
|
||||
overflow = significance * 2,
|
||||
mask = width - 1,
|
||||
nodecrypto; // node.js crypto module, initialized at the bottom.
|
||||
|
||||
//
|
||||
// seedrandom()
|
||||
// This is the seedrandom function described above.
|
||||
//
|
||||
function seedrandom(seed, options, callback) {
|
||||
var key = [];
|
||||
options = (options == true) ? { entropy: true } : (options || {});
|
||||
|
||||
// Flatten the seed string or build one from local entropy if needed.
|
||||
var shortseed = mixkey(flatten(
|
||||
options.entropy ? [seed, tostring(pool)] :
|
||||
(seed == null) ? autoseed() : seed, 3), key);
|
||||
|
||||
// Use the seed to initialize an ARC4 generator.
|
||||
var arc4 = new ARC4(key);
|
||||
|
||||
// This function returns a random double in [0, 1) that contains
|
||||
// randomness in every bit of the mantissa of the IEEE 754 value.
|
||||
var prng = function() {
|
||||
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
|
||||
d = startdenom, // and denominator d = 2 ^ 48.
|
||||
x = 0; // and no 'extra last byte'.
|
||||
while (n < significance) { // Fill up all significant digits by
|
||||
n = (n + x) * width; // shifting numerator and
|
||||
d *= width; // denominator and generating a
|
||||
x = arc4.g(1); // new least-significant-byte.
|
||||
}
|
||||
while (n >= overflow) { // To avoid rounding up, before adding
|
||||
n /= 2; // last byte, shift everything
|
||||
d /= 2; // right using integer math until
|
||||
x >>>= 1; // we have exactly the desired bits.
|
||||
}
|
||||
return (n + x) / d; // Form the number within [0, 1).
|
||||
};
|
||||
|
||||
prng.int32 = function() { return arc4.g(4) | 0; }
|
||||
prng.quick = function() { return arc4.g(4) / 0x100000000; }
|
||||
prng.double = prng;
|
||||
|
||||
// Mix the randomness into accumulated entropy.
|
||||
mixkey(tostring(arc4.S), pool);
|
||||
|
||||
// Calling convention: what to return as a function of prng, seed, is_math.
|
||||
return (options.pass || callback ||
|
||||
function(prng, seed, is_math_call, state) {
|
||||
if (state) {
|
||||
// Load the arc4 state from the given state if it has an S array.
|
||||
if (state.S) { copy(state, arc4); }
|
||||
// Only provide the .state method if requested via options.state.
|
||||
prng.state = function() { return copy(arc4, {}); }
|
||||
}
|
||||
|
||||
// If called as a method of Math (Math.seedrandom()), mutate
|
||||
// Math.random because that is how seedrandom.js has worked since v1.0.
|
||||
if (is_math_call) { math[rngname] = prng; return seed; }
|
||||
|
||||
// Otherwise, it is a newer calling convention, so return the
|
||||
// prng directly.
|
||||
else return prng;
|
||||
})(
|
||||
prng,
|
||||
shortseed,
|
||||
'global' in options ? options.global : (this == math),
|
||||
options.state);
|
||||
}
|
||||
|
||||
//
|
||||
// ARC4
|
||||
//
|
||||
// An ARC4 implementation. The constructor takes a key in the form of
|
||||
// an array of at most (width) integers that should be 0 <= x < (width).
|
||||
//
|
||||
// The g(count) method returns a pseudorandom integer that concatenates
|
||||
// the next (count) outputs from ARC4. Its return value is a number x
|
||||
// that is in the range 0 <= x < (width ^ count).
|
||||
//
|
||||
function ARC4(key) {
|
||||
var t, keylen = key.length,
|
||||
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
|
||||
|
||||
// The empty key [] is treated as [0].
|
||||
if (!keylen) { key = [keylen++]; }
|
||||
|
||||
// Set up S using the standard key scheduling algorithm.
|
||||
while (i < width) {
|
||||
s[i] = i++;
|
||||
}
|
||||
for (i = 0; i < width; i++) {
|
||||
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
|
||||
s[j] = t;
|
||||
}
|
||||
|
||||
// The "g" method returns the next (count) outputs as one number.
|
||||
(me.g = function(count) {
|
||||
// Using instance members instead of closure state nearly doubles speed.
|
||||
var t, r = 0,
|
||||
i = me.i, j = me.j, s = me.S;
|
||||
while (count--) {
|
||||
t = s[i = mask & (i + 1)];
|
||||
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
|
||||
}
|
||||
me.i = i; me.j = j;
|
||||
return r;
|
||||
// For robust unpredictability, the function call below automatically
|
||||
// discards an initial batch of values. This is called RC4-drop[256].
|
||||
// See http://google.com/search?q=rsa+fluhrer+response&btnI
|
||||
})(width);
|
||||
}
|
||||
|
||||
//
|
||||
// copy()
|
||||
// Copies internal state of ARC4 to or from a plain object.
|
||||
//
|
||||
function copy(f, t) {
|
||||
t.i = f.i;
|
||||
t.j = f.j;
|
||||
t.S = f.S.slice();
|
||||
return t;
|
||||
};
|
||||
|
||||
//
|
||||
// flatten()
|
||||
// Converts an object tree to nested arrays of strings.
|
||||
//
|
||||
function flatten(obj, depth) {
|
||||
var result = [], typ = (typeof obj), prop;
|
||||
if (depth && typ == 'object') {
|
||||
for (prop in obj) {
|
||||
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
|
||||
}
|
||||
}
|
||||
return (result.length ? result : typ == 'string' ? obj : obj + '\0');
|
||||
}
|
||||
|
||||
//
|
||||
// mixkey()
|
||||
// Mixes a string seed into a key that is an array of integers, and
|
||||
// returns a shortened string seed that is equivalent to the result key.
|
||||
//
|
||||
function mixkey(seed, key) {
|
||||
var stringseed = seed + '', smear, j = 0;
|
||||
while (j < stringseed.length) {
|
||||
key[mask & j] =
|
||||
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
|
||||
}
|
||||
return tostring(key);
|
||||
}
|
||||
|
||||
//
|
||||
// autoseed()
|
||||
// Returns an object for autoseeding, using window.crypto and Node crypto
|
||||
// module if available.
|
||||
//
|
||||
function autoseed() {
|
||||
try {
|
||||
var out;
|
||||
if (nodecrypto && (out = nodecrypto.randomBytes)) {
|
||||
// The use of 'out' to remember randomBytes makes tight minified code.
|
||||
out = out(width);
|
||||
} else {
|
||||
out = new Uint8Array(width);
|
||||
(global.crypto || global.msCrypto).getRandomValues(out);
|
||||
}
|
||||
return tostring(out);
|
||||
} catch (e) {
|
||||
var browser = global.navigator,
|
||||
plugins = browser && browser.plugins;
|
||||
return [+new Date, global, plugins, global.screen, tostring(pool)];
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// tostring()
|
||||
// Converts an array of charcodes to a string
|
||||
//
|
||||
function tostring(a) {
|
||||
return String.fromCharCode.apply(0, a);
|
||||
}
|
||||
|
||||
//
|
||||
// When seedrandom.js is loaded, we immediately mix a few bits
|
||||
// from the built-in RNG into the entropy pool. Because we do
|
||||
// not want to interfere with deterministic PRNG state later,
|
||||
// seedrandom will not call math.random on its own again after
|
||||
// initialization.
|
||||
//
|
||||
mixkey(math.random(), pool);
|
||||
|
||||
// When included as a plain script, set up Math.seedrandom global.
|
||||
math['seed' + rngname] = seedrandom;
|
||||
|
||||
|
||||
// End anonymous scope, and pass initial values.
|
||||
})(
|
||||
// global: `self` in browsers (including strict mode and web workers),
|
||||
// otherwise `this` in Node and other environments
|
||||
(typeof self !== 'undefined') ? self : this,
|
||||
[], // pool: entropy pool starts empty
|
||||
Math // math: package containing random, pow, and seedrandom
|
||||
);
|
18
webpack.config.js
Normal file
18
webpack.config.js
Normal file
@ -0,0 +1,18 @@
|
||||
const path = require('path')
|
||||
|
||||
module.exports = {
|
||||
entry: './src/index.js',
|
||||
output: {
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
filename: 'index.js'
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.worker\.js$/,
|
||||
use: { loader: 'worker-loader' }
|
||||
}
|
||||
]
|
||||
},
|
||||
devtool: 'inline-source-map'
|
||||
}
|
Loading…
Reference in New Issue
Block a user