Py.Cafe

jackparmer/

voxel-worlds

Voxel World Generator Demo using Dash

DocsPricing
  • app.py
  • requirements.txt
app.py
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
from dash import Dash, Output, Input, html, callback
import base64
from PIL import Image
import requests
from io import BytesIO
from voxel_world import Volume
import vnoise
import numpy as np
import random

url = 'https://i.giphy.com/okfvUCpgArv3y.webp'

response = requests.get(url)

pil_img = Image.open(BytesIO(response.content))

# Using base64 encoding and decoding
def b64_image(image_filename):
    with open(image_filename, 'rb') as f:
        image = f.read()
    return 'data:image/png;base64,' + base64.b64encode(image).decode('utf-8')


app = Dash(__name__)

app.layout = html.Div([
    html.Button('Generate world', id='submit-val', style={'position':'absolute'}),
    html.Img(src=pil_img, id='voxel-world', style={'width':'100%'}),                          
])

@callback(
    Output('voxel-world', 'src'),
    Input('submit-val', 'n_clicks'),
)
def update_output(value):
    """ Generate voxel world """
    noise = vnoise.Noise()
    im = Volume(
        np.array([[[1 if noise.noise3(x / 10.0, y / 10.0, z / 10.0) > random.uniform(-0.2, 0.2) else 0 for z in range(16)] for y in range(16)] for x in range(16)], dtype=np.uint8),
        theme=random.choice(list(Volume.themes.keys())),
        resolution=10,
        viewing_angle=(random.randint(0, 90), random.randint(0, 90)),
        zoom=2.0,
        show_light_source=False,
        dark_bg=False
    ).byte_stream().getvalue()

    return 'data:image/png;base64,' + base64.b64encode(im).decode('utf-8')

if __name__ == '__main__':
    app.run(debug=True)