Spaces:
Sleeping
Sleeping
File size: 9,848 Bytes
1d5ce9c |
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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
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;
case 'zoomIn': rig.object3D.scale.multiplyScalar(0.9); break;
case 'zoomOut': rig.object3D.scale.multiplyScalar(1.1); 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 'arrowup': moveCamera('forward'); break;
case 'arrowdown': moveCamera('backward'); break;
case 'arrowleft': moveCamera('left'); break;
case 'arrowright': moveCamera('right'); break;
case 'r': moveCamera('reset'); break;
case 'q': moveCamera('rotateY+'); break;
case 'e': moveCamera('rotateY-'); break;
case 'z': moveCamera('rotateZ+'); break;
case 'c': moveCamera('rotateZ-'); break;
case 'pageup': moveCamera('zoomIn'); break;
case 'pagedown': moveCamera('zoomOut'); 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):
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
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>')
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}")
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("### 🧭 Navigation Controls")
# Pan the View
st.markdown("**Pan the View** ⬅️➡️")
cols = st.columns(4)
cols[0].button("⬅️", on_click=lambda: st.session_state.update({'camera_move': 'left'}))
cols[1].button("➡️", on_click=lambda: st.session_state.update({'camera_move': 'right'}))
cols[2].button("⬆️", on_click=lambda: st.session_state.update({'camera_move': 'forward'}))
cols[3].button("⬇️", on_click=lambda: st.session_state.update({'camera_move': 'backward'}))
# Rotate the 3D Scene
st.markdown("**Rotate the 3D Scene** 🔄")
cols = st.columns(4)
cols[0].button("⬅️ Rotate Y+", on_click=lambda: st.session_state.update({'camera_move': 'rotateY+'}))
cols[1].button("➡️ Rotate Y-", on_click=lambda: st.session_state.update({'camera_move': 'rotateY-'}))
cols[2].button("↖️ Rotate Z+", on_click=lambda: st.session_state.update({'camera_move': 'rotateZ+'}))
cols[3].button("↘️ Rotate Z-", on_click=lambda: st.session_state.update({'camera_move': 'rotateZ-'}))
# Zoom Controls
st.markdown("**Zoom** 🔎")
cols = st.columns(2)
cols[0].button("➕ Zoom In", on_click=lambda: st.session_state.update({'camera_move': 'zoomIn'}))
cols[1].button("➖ Zoom Out", on_click=lambda: st.session_state.update({'camera_move': 'zoomOut'}))
# Reset View
st.markdown("**Reset View** 🔄")
st.button("🔄 Reset", on_click=lambda: st.session_state.update({'camera_move': 'reset'}))
st.markdown("### ➕ Add Media Files")
ups = st.file_uploader("Add files (png, obj, glb, etc.):", accept_multiple_files=True)
st.markdown("### 📋 Uploaded Model Files")
directory = st.text_input("Path:", ".", key="dir")
if os.path.isdir(directory):
files = [f for f in os.listdir(directory) if f.split('.')[-1] in ['obj', 'glb', 'gltf']]
if files:
for i, f in enumerate(files, 1):
st.markdown(f"{i}. {f}")
else:
st.markdown("No model files found.")
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]
spot_h = max(8,8)*1.5
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>
<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>
<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>"
cmd = st.session_state.get('camera_move')
if cmd:
scene += f"<script>moveCamera('{cmd}');</script>"
st.session_state.pop('camera_move')
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() |