ewebspace commited on
Commit
76b1098
·
verified ·
1 Parent(s): cb078c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -39
app.py CHANGED
@@ -3,7 +3,11 @@ import numpy as np
3
  from typing import Optional
4
  import json
5
  from pathlib import Path
 
 
 
6
 
 
7
  THREE_JS_TEMPLATE = """
8
  <!DOCTYPE html>
9
  <html>
@@ -12,17 +16,25 @@ THREE_JS_TEMPLATE = """
12
  <style>
13
  body {{ margin: 0; overflow: hidden; }}
14
  canvas {{ display: block; }}
 
 
 
 
 
 
 
 
15
  </style>
16
  </head>
17
  <body>
 
18
  <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
19
  <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
20
- <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/loaders/GLTFLoader.js"></script>
21
 
22
  <script>
23
  // Scene setup
24
  const scene = new THREE.Scene();
25
- const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
26
  const renderer = new THREE.WebGLRenderer({{ antialias: true }});
27
  renderer.setSize(window.innerWidth, window.innerHeight);
28
  document.body.appendChild(renderer.domElement);
@@ -30,18 +42,82 @@ THREE_JS_TEMPLATE = """
30
  // Universe data
31
  const universeData = {universe_json};
32
 
33
- // Rest of your Three.js code...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  </script>
35
  </body>
36
  </html>
37
  """
38
 
39
- def get_threejs_app():
40
- """Generate the Three.js HTML with current universe data"""
41
- # Escape curly braces in the template first
42
- template = THREE_JS_TEMPLATE.replace('{', '{{').replace('}', '}}')
43
- # Then format only the universe_json part
44
- return template.replace('{universe_json}', json.dumps(universe))
45
  class UniverseGenerator:
46
  def __init__(self, seed=42):
47
  self.rng = np.random.RandomState(seed)
@@ -90,15 +166,13 @@ universe = generator.generate_universe()
90
 
91
  def get_threejs_app():
92
  """Generate the Three.js HTML with current universe data"""
93
- return THREE_JS_TEMPLATE.format(universe_json=json.dumps(universe))
94
 
95
- def travel_to_system(system_index: int):
96
- """Handle system transition"""
97
- system_index = max(0, min(system_index, len(universe['systems'])-1))
98
- return {
99
- 'system': universe['systems'][system_index],
100
- 'html': get_threejs_app()
101
- }
102
 
103
  with gr.Blocks(title="Webspace Network 3D") as demo:
104
  gr.Markdown("# 🚀 Webspace Network 3D")
@@ -117,40 +191,30 @@ with gr.Blocks(title="Webspace Network 3D") as demo:
117
  # Planet info display
118
  planet_info = gr.JSON(label="Selected Planet")
119
  system_info = gr.JSON(label="Current System", value=universe['systems'][0])
120
-
121
- # Debug info
122
- debug = gr.Textbox(label="Debug Console")
123
 
124
- # Handle planet selection from Three.js
125
- demo.load(
126
- None,
127
  None,
128
  None,
 
129
  _js="""
130
  () => {
131
- window.addEventListener('message', (event) => {
132
- if (event.data.type === 'planetSelected') {
133
- return event.data.data;
134
- }
 
 
135
  });
136
- return null;
137
  }
138
- """,
139
- outputs=planet_info
140
  )
141
 
142
  # Handle system travel
143
  travel_btn.click(
144
- travel_to_system,
145
  inputs=system_slider,
146
- outputs=[system_info, html],
147
- _js="""
148
- (index) => {
149
- const iframe = document.querySelector('#threejs-container iframe');
150
- iframe.contentWindow.postMessage({type: 'travelToSystem', systemIndex: index}, '*');
151
- return index;
152
- }
153
- """
154
  )
155
 
156
  if __name__ == "__main__":
 
3
  from typing import Optional
4
  import json
5
  from pathlib import Path
6
+ import gradio as gr
7
+ import numpy as np
8
+ import json
9
 
10
+ # Three.js template with proper escaping
11
  THREE_JS_TEMPLATE = """
12
  <!DOCTYPE html>
13
  <html>
 
16
  <style>
17
  body {{ margin: 0; overflow: hidden; }}
18
  canvas {{ display: block; }}
19
+ #info {{
20
+ position: absolute;
21
+ top: 10px;
22
+ left: 10px;
23
+ color: white;
24
+ background: rgba(0,0,0,0.5);
25
+ padding: 10px;
26
+ }}
27
  </style>
28
  </head>
29
  <body>
30
+ <div id="info">Click on planets to see details</div>
31
  <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
32
  <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
 
33
 
34
  <script>
35
  // Scene setup
36
  const scene = new THREE.Scene();
37
+ const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
38
  const renderer = new THREE.WebGLRenderer({{ antialias: true }});
39
  renderer.setSize(window.innerWidth, window.innerHeight);
40
  document.body.appendChild(renderer.domElement);
 
42
  // Universe data
43
  const universeData = {universe_json};
44
 
45
+ // Create star system
46
+ function createSystem(systemData) {{
47
+ // Create star
48
+ const starGeometry = new THREE.SphereGeometry(2, 32, 32);
49
+ const starMaterial = new THREE.MeshBasicMaterial({{
50
+ color: new THREE.Color(...systemData.star_color),
51
+ emissive: new THREE.Color(...systemData.star_color).multiplyScalar(0.5)
52
+ }});
53
+ const star = new THREE.Mesh(starGeometry, starMaterial);
54
+ scene.add(star);
55
+
56
+ // Create planets
57
+ systemData.planets.forEach((planet, i) => {{
58
+ const planetGeometry = new THREE.SphereGeometry(planet.size, 32, 32);
59
+ const planetMaterial = new THREE.MeshStandardMaterial({{
60
+ color: new THREE.Color(...planet.color),
61
+ roughness: 0.8,
62
+ metalness: 0.2
63
+ }});
64
+ const planetMesh = new THREE.Mesh(planetGeometry, planetMaterial);
65
+
66
+ // Position in orbit
67
+ const orbitRadius = 5 + (i * 3);
68
+ planetMesh.position.x = orbitRadius;
69
+ planetMesh.userData = planet;
70
+
71
+ // Add click handler
72
+ planetMesh.addEventListener('click', (event) => {{
73
+ window.parent.postMessage({{
74
+ type: 'planetSelected',
75
+ data: event.target.userData
76
+ }}, '*');
77
+ event.stopPropagation();
78
+ }});
79
+
80
+ // Create orbit path
81
+ const orbit = new THREE.Line(
82
+ new THREE.BufferGeometry().setFromPoints(
83
+ new THREE.EllipseCurve(0, 0, orbitRadius, orbitRadius, 0, Math.PI * 2, false).getPoints(100)
84
+ ),
85
+ new THREE.LineBasicMaterial({{ color: 0x888888 }})
86
+ );
87
+ orbit.rotation.x = Math.PI / 2;
88
+
89
+ scene.add(planetMesh);
90
+ scene.add(orbit);
91
+ }});
92
+ }}
93
+
94
+ // Initialize first system
95
+ createSystem(universeData.systems[0]);
96
+
97
+ // Camera controls
98
+ const controls = new THREE.OrbitControls(camera, renderer.domElement);
99
+ camera.position.set(0, 20, 30);
100
+ controls.update();
101
+
102
+ // Animation loop
103
+ function animate() {{
104
+ requestAnimationFrame(animate);
105
+ controls.update();
106
+ renderer.render(scene, camera);
107
+ }}
108
+ animate();
109
+
110
+ // Handle window resize
111
+ window.addEventListener('resize', () => {{
112
+ camera.aspect = window.innerWidth / window.innerHeight;
113
+ camera.updateProjectionMatrix();
114
+ renderer.setSize(window.innerWidth, window.innerHeight);
115
+ }});
116
  </script>
117
  </body>
118
  </html>
119
  """
120
 
 
 
 
 
 
 
121
  class UniverseGenerator:
122
  def __init__(self, seed=42):
123
  self.rng = np.random.RandomState(seed)
 
166
 
167
  def get_threejs_app():
168
  """Generate the Three.js HTML with current universe data"""
169
+ return THREE_JS_TEMPLATE.replace('{universe_json}', json.dumps(universe))
170
 
171
+ def handle_planet_select(data: gr.SelectData):
172
+ """Handle planet selection from Three.js"""
173
+ if hasattr(data, 'value'):
174
+ return data.value
175
+ return None
 
 
176
 
177
  with gr.Blocks(title="Webspace Network 3D") as demo:
178
  gr.Markdown("# 🚀 Webspace Network 3D")
 
191
  # Planet info display
192
  planet_info = gr.JSON(label="Selected Planet")
193
  system_info = gr.JSON(label="Current System", value=universe['systems'][0])
 
 
 
194
 
195
+ # Handle planet selection via custom JS
196
+ html.change(
 
197
  None,
198
  None,
199
+ planet_info,
200
  _js="""
201
  () => {
202
+ return new Promise((resolve) => {
203
+ window.addEventListener('message', (event) => {
204
+ if (event.data.type === 'planetSelected') {
205
+ resolve(event.data.data);
206
+ }
207
+ });
208
  });
 
209
  }
210
+ """
 
211
  )
212
 
213
  # Handle system travel
214
  travel_btn.click(
215
+ lambda x: universe['systems'][x],
216
  inputs=system_slider,
217
+ outputs=system_info
 
 
 
 
 
 
 
218
  )
219
 
220
  if __name__ == "__main__":