Spaces:
Running
Running
File size: 8,360 Bytes
4d125bc 3554ac8 4d125bc 3554ac8 16e6b88 3554ac8 d88550f b8df290 16e6b88 c8b3c4e 16e6b88 d88550f 3554ac8 16e6b88 b8df290 d88550f 16e6b88 750e754 3554ac8 750e754 16e6b88 750e754 c8b3c4e 750e754 b8df290 c8b3c4e 16e6b88 3554ac8 750e754 16e6b88 750e754 16e6b88 c8b3c4e 16e6b88 c8b3c4e 3554ac8 86942ee 3554ac8 16e6b88 b8df290 16e6b88 750e754 3554ac8 16e6b88 86942ee 16e6b88 750e754 16e6b88 c8b3c4e 16e6b88 750e754 16e6b88 3554ac8 c8b3c4e 750e754 16e6b88 3554ac8 86942ee 16e6b88 86942ee 16e6b88 390ce77 c8b3c4e 750e754 b8df290 3554ac8 16e6b88 3554ac8 4d125bc 86942ee |
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 |
import streamlit as st
import os, base64, shutil, random
from pathlib import Path
@st.cache_data
def load_aframe_and_extras():
return """
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/aframe-event-set-component.min.js"></script>
<script>
let score = 0;
/* Draggable, bouncing, moving-light components unchanged */
AFRAME.registerComponent('draggable', {/* … */});
AFRAME.registerComponent('bouncing', {/* … */});
AFRAME.registerComponent('moving-light', {/* … */});
function moveCamera(direction) {
var rig = document.querySelector('#rig');
var pos = rig.getAttribute('position');
var rot = rig.getAttribute('rotation');
var speed = 0.5, rSpeed = 5;
switch(direction) {
case 'forward': pos.z -= speed; break;
case 'backward': pos.z += speed; break;
case 'left': pos.x -= speed; break;
case 'right': pos.x += speed; break;
case 'up': pos.y += speed; break;
case 'down': pos.y -= speed; break;
case 'reset': pos = {x:0,y:1.6,z:0}; rot = {x:0,y:0,z:0}; break;
case 'rotateY+': rot.y += rSpeed; break;
case 'rotateY-': rot.y -= rSpeed; break;
case 'rotateZ+': rot.z += rSpeed; break;
case 'rotateZ-': rot.z -= rSpeed; break;
}
rig.setAttribute('position', pos);
rig.setAttribute('rotation', rot);
}
function fireRaycast() {
var cam = document.querySelector('[camera]');
var dir = new THREE.Vector3(); cam.object3D.getWorldDirection(dir);
var rc = new THREE.Raycaster(cam.object3D.position, dir);
var hits = rc.intersectObjects(
Array.from(document.querySelectorAll('.raycastable')).map(e=>e.object3D), true
);
if (hits.length>0) {
var el = hits[0].object.el;
if (el.components.bouncing) {
el.components.bouncing.boost();
score += 10;
document.getElementById('score').setAttribute('value','Score: '+score);
}
}
}
document.addEventListener('keydown', e => {
switch(e.key.toLowerCase()){
case 'w': moveCamera('forward'); break;
case 'x': moveCamera('backward'); break;
case 'a': moveCamera('left'); break;
case 'd': moveCamera('right'); break;
case 's': moveCamera('reset'); break;
case 'q': moveCamera('rotateY+'); break;
case 'e': moveCamera('rotateY-'); break;
case 'z': moveCamera('rotateZ+'); break;
case 'c': moveCamera('rotateZ-'); break;
case ' ': fireRaycast(); break;
}
});
</script>
"""
@st.cache_data
def encode_file(path):
with open(path,'rb') as f: return base64.b64encode(f.read()).decode()
def create_aframe_entity(stem, ext, pos):
# static random Y rotation, scale fills 1×1 tile
ry = random.uniform(0,360)
if ext == 'obj':
return (f'<a-entity obj-model="obj:#{stem}" '
f'position="{pos}" rotation="0 {ry} 0" scale="1 1 1" '
'class="raycastable" draggable></a-entity>')
if ext in ('glb','gltf'):
return (f'<a-entity gltf-model="#{stem}" '
f'position="{pos}" rotation="0 {ry} 0" scale="1 1 1" '
'class="raycastable" draggable></a-entity>')
return ''
@st.cache_data
def generate_tilemap(files, dirpath, gw=8, gh=8):
img_exts = ['webp','png']
model_exts = ['obj','glb','gltf']
vid_exts = ['mp4']
imgs = [f for f in files if f.split('.')[-1] in img_exts]
models = [f for f in files if f.split('.')[-1] in model_exts]
vids = [f for f in files if f.split('.')[-1] in vid_exts]
assets = "<a-assets>"
for f in files:
stem = Path(f).stem; ext=f.split('.')[-1]
data=encode_file(os.path.join(dirpath,f))
if ext in model_exts:
assets += (f'<a-asset-item id="{stem}" '
f'src="data:application/octet-stream;base64,{data}"></a-asset-item>')
elif ext in img_exts:
assets += f'<img id="{stem}" src="data:image/{ext};base64,{data}">'
elif ext in vid_exts:
assets += (f'<video id="{stem}" '
f'src="data:video/mp4;base64,{data}" '
'loop autoplay muted></video>')
assets += "</a-assets>"
entities = ""
sx=-gw/2; sz=-gh/2
for i in range(gw):
for j in range(gh):
x,y,z = sx+i,0,sz+j
# ground image
if imgs:
img=random.choice(imgs); s=Path(img).stem
entities += (f'<a-plane src="#{s}" width="1" height="1" '
f'rotation="-90 0 0" position="{x} 0.01 {z}"></a-plane>')
# model
if models:
m=random.choice(models); ext=m.split('.')[-1]; s=Path(m).stem
entities += create_aframe_entity(s,ext,f"{x} 0.5 {z}")
# video
if vids:
v=random.choice(vids); s=Path(v).stem
entities += (f'<a-video src="#{s}" width="1" height="1" '
f'rotation="-90 0 0" position="{x} 0.2 {z}" '
'class="raycastable" draggable></a-video>')
return assets, entities
def main():
st.set_page_config(layout="wide")
with st.sidebar:
st.markdown("### ⬆️ Upload 3D / media files")
ups = st.file_uploader("Add files:", accept_multiple_files=True)
st.markdown("### 🎮 Camera Buttons")
# 3×3 grid of buttons for qwe/asd/zxc
rows = [
[('Q','rotateY+'), ('W','forward'), ('E','rotateY-')],
[('A','left'), ('S','reset'), ('D','right')],
[('Z','rotateZ+'),('X','backward'),('C','rotateZ-')]
]
for row in rows:
cols = st.columns(3)
for (btn,cmd),col in zip(row, cols):
col.button(btn, on_click=lambda c=cmd: st.session_state.update({'camera_move':c}))
st.markdown("### 🗺️ Grid is fixed at 8×8")
st.markdown("### 📁 Directory")
directory = st.text_input("Path:", ".", key="dir")
if not os.path.isdir(directory):
st.sidebar.error("Invalid directory")
return
types = ['obj','glb','gltf','webp','png','mp4']
if ups:
for up in ups:
ext=Path(up.name).suffix.lower()[1:]
if ext in types:
with open(os.path.join(directory,up.name),'wb') as f:
shutil.copyfileobj(up,f)
st.sidebar.success(f"Uploaded {up.name}")
else:
st.sidebar.warning(f"Skipped {up.name}")
files = [f for f in os.listdir(directory) if f.split('.')[-1] in types]
# spotlight height
spot_h = max(8,8)*1.5
# build scene
scene = f"""
<a-scene embedded style="height:600px; width:100%;">
<a-entity id="rig" position="0 1.6 0" rotation="0 0 0">
<a-camera fov="60" look-controls wasd-controls="enabled:true"
cursor="rayOrigin:mouse" raycaster="objects:.raycastable">
</a-camera>
</a-entity>
<a-sky color="#87CEEB"></a-sky>
<!-- moving lights -->
<a-entity moving-light="color:#FFD700; speed:0.07 0.05 0.06; bounds:4 3 4" position="2 2 -2"></a-entity>
<a-entity moving-light="color:#FF6347; speed:0.06 0.08 0.05; bounds:4 3 4" position="-2 1 2"></a-entity>
<a-entity moving-light="color:#00CED1; speed:0.05 0.06 0.07; bounds:4 3 4" position="0 3 0"></a-entity>
<!-- top-down spotlight -->
<a-entity light="type:spot; color:#FFF; intensity:1; angle:45; penumbra:0.2"
position="0 {spot_h} 0" rotation="-90 0 0"></a-entity>
<a-text id="score" value="Score:0" position="-1.5 2 -3" scale="0.5 0.5 0.5" color="white"></a-text>
"""
assets, ents = generate_tilemap(files, directory, 8, 8)
scene += assets + ents + "</a-scene>"
# apply button or key moves
cmd = st.session_state.get('camera_move')
if cmd:
scene += f"<script>moveCamera('{cmd}');</script>"
st.session_state.pop('camera_move')
# loader for OBJ/glTF
loader = '<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/aframe-extras.loaders.min.js"></script>'
st.components.v1.html(
load_aframe_and_extras() + loader + scene,
height=650
)
if __name__ == "__main__":
main()
|