diff options
Diffstat (limited to 'src/BrushSelector.js')
-rw-r--r-- | src/BrushSelector.js | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/src/BrushSelector.js b/src/BrushSelector.js new file mode 100644 index 0000000..ea72990 --- /dev/null +++ b/src/BrushSelector.js @@ -0,0 +1,72 @@ +import { lerp } from './modules/Util.js'; + +class BrushSelector { + constructor(rootId, canvas, terrain) { + console.log('hi'); + this.canvas = canvas; + this.terrain = terrain; + this.div = document.createElement('div'); + this.div.setAttribute('style', 'position: absolute; padding: 10px; display: block; right: 10px; bottom: 10px;'); + + this.radiusSlider = this.addSlider('Brush Size', 0, 500); + this.strengthSlider = this.addSlider('Brush Strength', 0, 100); + + this.addBrush('Raise', (pt, str) => pt.height += 5 * str); + this.addBrush('Lower', (pt, str) => pt.height -= 5 * str); + this.addBrush('Round', (pt, str) => { + const neighbors = this.terrain.getNeighbors(pt); + let avg = 0; + for (let n of neighbors) avg += n.height; + avg /= neighbors.length; + pt.height = lerp(pt.height, avg, str); + }); + + const root = document.getElementById(rootId); + root.appendChild(this.div); + } + + addSlider(label, min, max) { + const l = document.createElement('label'); + const text = document.createTextNode(label); + l.appendChild(text); + this.div.appendChild(l); + + const s = document.createElement('input'); + s.type = 'range'; + s.min = min; + s.max = max; + s.value = 0.5 * (max + min); + this.div.appendChild(s); + return s; + } + + addBrush(name, f) { + const button = document.createElement('button'); + const text = document.createTextNode(name); + button.appendChild(text); + + button.onclick = () => { + if (this.button === button) return // already selected + if (this.button) this.button.classList.remove('selected'); + button.classList.add('selected'); + this.button = button; + this.f = f; + }; + + if (!this.button) button.onclick(); + + this.div.appendChild(button); + } + + apply() { + const radius = this.radiusSlider.value; + const str = this.strengthSlider.value/this.strengthSlider.max; + this.terrain.applyBrush( + this.canvas.mouse.drawingPos.x, + this.canvas.mouse.drawingPos.y, + this.f, str, this.canvas.pixelsToUnits(radius) + ); + } +} + +export default BrushSelector; |