awacke1 commited on
Commit
e6bd8ca
·
verified ·
1 Parent(s): 046998c

Update backup1.app.py

Browse files
Files changed (1) hide show
  1. backup1.app.py +266 -309
backup1.app.py CHANGED
@@ -3,358 +3,316 @@ import streamlit as st
3
  import streamlit.components.v1 as components
4
  import os
5
  import json
 
6
  import uuid
7
- from PIL import Image, ImageDraw # For minimap
8
- import urllib.parse # For decoding save data
9
 
10
  # --- Constants ---
11
  SAVE_DIR = "saved_worlds"
12
- WORLD_MAP_FILE = os.path.join(SAVE_DIR, "world_map.json")
13
- DEFAULT_SPACE_SIZE = 50 # Matches ground plane size in JS (approx)
14
- MINIMAP_CELL_SIZE = 10 # Pixels per cell in minimap image
15
 
16
  # --- Ensure Save Directory Exists ---
17
  os.makedirs(SAVE_DIR, exist_ok=True)
18
 
19
- # --- Helper Functions for Persistence ---
20
-
21
- def load_world_map():
22
- """Loads the world map metadata."""
23
- if os.path.exists(WORLD_MAP_FILE):
24
- try:
25
- with open(WORLD_MAP_FILE, 'r') as f:
26
- return json.load(f)
27
- except json.JSONDecodeError:
28
- st.error("Error reading world map file. Starting fresh.")
29
- return {"spaces": {}} # Return empty if corrupt
30
- return {"spaces": {}} # SpaceID -> {"grid_x": int, "grid_y": int, "name": str}
31
-
32
- def save_world_map(world_data):
33
- """Saves the world map metadata."""
34
  try:
35
- with open(WORLD_MAP_FILE, 'w') as f:
36
- json.dump(world_data, f, indent=4)
 
 
37
  except Exception as e:
38
- st.error(f"Error saving world map: {e}")
39
-
40
-
41
- def save_space_data(space_id, objects_data):
42
- """Saves the object data for a specific space."""
43
- file_path = os.path.join(SAVE_DIR, f"{space_id}.json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  try:
45
- with open(file_path, 'w') as f:
46
- # Store objects directly, could add metadata later
47
- json.dump({"objects": objects_data}, f, indent=4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  except Exception as e:
49
- st.error(f"Error saving space data for {space_id}: {e}")
50
-
51
-
52
- def load_space_data(space_id):
53
- """Loads object data for a specific space."""
54
- file_path = os.path.join(SAVE_DIR, f"{space_id}.json")
55
- if os.path.exists(file_path):
56
- try:
57
- with open(file_path, 'r') as f:
58
- data = json.load(f)
59
- return data.get("objects", []) # Return objects list or empty
60
- except json.JSONDecodeError:
61
- st.error(f"Error reading space file {space_id}.json.")
62
- return []
63
- except Exception as e:
64
- st.error(f"Error loading space data for {space_id}: {e}")
65
- return []
66
- return [] # Return empty list if file doesn't exist
67
-
68
- def find_next_available_grid_slot(world_data):
69
- """Finds the next empty slot in a spiral pattern (simple version)."""
70
- occupied = set((d["grid_x"], d["grid_y"]) for d in world_data.get("spaces", {}).values())
71
- x, y = 0, 0
72
- dx, dy = 0, -1
73
- limit = 1 # How many steps in current direction
74
- steps = 0 # Steps taken in current direction
75
- leg = 0 # Current leg of the spiral (0=right, 1=up, 2=left, 3=down)
76
-
77
- while True:
78
- if (x, y) not in occupied:
79
- return x, y
80
-
81
- # Move
82
- x, y = x + dx, y + dy
83
- steps += 1
84
-
85
- # Check if direction needs changing
86
- if steps == limit:
87
- steps = 0
88
- leg = (leg + 1) % 4
89
- if leg == 0: # Right
90
- dx, dy = 1, 0
91
- elif leg == 1: # Up
92
- dx, dy = 0, 1
93
- limit += 1 # Increase steps after moving up
94
- elif leg == 2: # Left
95
- dx, dy = -1, 0
96
- elif leg == 3: # Down
97
- dx, dy = 0, -1
98
- limit += 1 # Increase steps after moving down
99
-
100
- # Safety break (increase if expecting huge maps)
101
- if limit > 100:
102
- st.error("Could not find empty grid slot easily! Map too full?")
103
- return None, None
104
-
105
-
106
- # --- Minimap Generation ---
107
- def generate_minimap(world_data, current_space_id=None):
108
- spaces = world_data.get("spaces", {})
109
- if not spaces:
110
- return None # No map if no spaces saved
111
 
112
  try:
113
- coords = [(d["grid_x"], d["grid_y"]) for d in spaces.values()]
114
- # Handle case where coords might be empty if spaces dict is malformed
115
- if not coords: return None
116
-
117
- min_x = min(c[0] for c in coords)
118
- max_x = max(c[0] for c in coords)
119
- min_y = min(c[1] for c in coords)
120
- max_y = max(c[1] for c in coords)
121
-
122
- # Add padding around the edges
123
- padding = 1
124
- img_width = (max_x - min_x + 1 + 2 * padding) * MINIMAP_CELL_SIZE
125
- img_height = (max_y - min_y + 1 + 2 * padding) * MINIMAP_CELL_SIZE
126
-
127
- img = Image.new('RGB', (img_width, img_height), color = 'lightgrey')
128
- draw = ImageDraw.Draw(img)
129
-
130
- for space_id, data in spaces.items():
131
- # Calculate position including padding offset
132
- cell_x = (data["grid_x"] - min_x + padding) * MINIMAP_CELL_SIZE
133
- cell_y = (data["grid_y"] - min_y + padding) * MINIMAP_CELL_SIZE
134
- color = "blue"
135
- if space_id == current_space_id:
136
- color = "red" # Highlight current space
137
-
138
- draw.rectangle(
139
- [cell_x, cell_y, cell_x + MINIMAP_CELL_SIZE -1, cell_y + MINIMAP_CELL_SIZE -1],
140
- fill=color, outline="black"
141
- )
142
- # Optional: Draw space name/ID lightly
143
- # draw.text((cell_x + 1, cell_y + 1), data.get("name", sid[:2]), fill="white", font_size=8)
144
-
145
-
146
- return img
147
  except Exception as e:
148
- st.error(f"Error generating minimap: {e}")
149
- return None
150
-
151
 
152
  # --- Page Config ---
153
  st.set_page_config(
154
- page_title="Multiplayer World Builder",
155
  layout="wide"
156
  )
157
 
158
  # --- Initialize Session State ---
159
  if 'selected_object' not in st.session_state:
160
  st.session_state.selected_object = 'None'
161
- if 'current_space_id' not in st.session_state:
162
- st.session_state.current_space_id = None # Will be set when loading/creating
163
- if 'space_name' not in st.session_state:
164
- st.session_state.space_name = ""
165
- if 'initial_objects' not in st.session_state:
166
- st.session_state.initial_objects = [] # Objects to load into JS
167
- if 'trigger_rerun' not in st.session_state:
168
- st.session_state.trigger_rerun = 0 # Counter to force reruns cleanly
169
-
170
-
171
- # --- Load initial world data ---
172
- world_data = load_world_map()
173
-
174
- # --- Handle Save Data from JS (Query Param Workaround) ---
175
- query_params = st.query_params.to_dict()
176
- save_data_encoded = query_params.get("save_data")
177
-
178
-
179
- if save_data_encoded:
180
- st.session_state.trigger_rerun += 1 # Increment to signal change
181
- save_successful = False
182
- try:
183
- save_data_json = urllib.parse.unquote(save_data_encoded[0]) # Get first value if list
184
- objects_to_save = json.loads(save_data_json)
185
-
186
- # Get ID/Name from URL or fall back to session state if not in URL (e.g., if redirect failed partially)
187
- space_id_to_save = query_params.get("space_id", [st.session_state.current_space_id])[0]
188
- space_name_to_save = urllib.parse.unquote(query_params.get("space_name", [st.session_state.space_name])[0])
189
-
190
-
191
- if not space_id_to_save or space_id_to_save == 'null': # JS might send 'null' string
192
- space_id_to_save = str(uuid.uuid4()) # Create new ID
193
- is_new_space = True
194
- st.session_state.current_space_id = space_id_to_save # Update state
195
- else:
196
- is_new_space = False
197
-
198
- # Save the actual object data
199
- save_space_data(space_id_to_save, objects_to_save)
200
-
201
- # Update world map only if needed (new space or name change)
202
- map_updated = False
203
- world_spaces = world_data.setdefault("spaces", {})
204
-
205
- if is_new_space:
206
- grid_x, grid_y = find_next_available_grid_slot(world_data)
207
- if grid_x is not None:
208
- world_spaces[space_id_to_save] = {
209
- "grid_x": grid_x,
210
- "grid_y": grid_y,
211
- "name": space_name_to_save or f"Space_{space_id_to_save[:6]}"
212
- }
213
- map_updated = True
214
- else:
215
- st.error("Failed to assign grid position!")
216
- elif space_id_to_save in world_spaces and world_spaces[space_id_to_save].get("name") != space_name_to_save:
217
- # Update name if it changed for existing space
218
- world_spaces[space_id_to_save]["name"] = space_name_to_save
219
- map_updated = True
220
-
221
- if map_updated:
222
- save_world_map(world_data)
223
-
224
- st.session_state.space_name = space_name_to_save # Ensure state matches saved name
225
-
226
- st.success(f"Space '{space_name_to_save or space_id_to_save}' saved successfully!")
227
- save_successful = True
228
-
229
-
230
- except Exception as e:
231
- st.error(f"Error processing save data: {e}")
232
- st.exception(e) # Show full traceback for debugging
233
-
234
- # IMPORTANT: Clear query param to prevent resave on refresh/rerun
235
- st.query_params.clear()
236
-
237
- # Force a rerun IF save was processed, to reload objects and clear URL state visually
238
- # Do this AFTER clearing query_params
239
- if save_successful:
240
- # No need to explicitly call st.rerun() here, Streamlit's flow after
241
- # clearing query params and updating state often handles it.
242
- # If visual updates lag, uncommenting st.rerun() might be necessary,
243
- # but can sometimes cause double reruns.
244
- # st.rerun()
245
- pass
246
-
247
-
248
- # --- Load Space Data if ID is set ---
249
- # This runs on every script execution, including after save/load actions
250
- if st.session_state.current_space_id:
251
- st.session_state.initial_objects = load_space_data(st.session_state.current_space_id)
252
- # Ensure name is loaded if space ID exists but name state is empty
253
- if not st.session_state.space_name and st.session_state.current_space_id in world_data.get("spaces", {}):
254
- st.session_state.space_name = world_data["spaces"][st.session_state.current_space_id].get("name", "")
255
-
256
-
257
- # --- Sidebar Controls ---
258
  with st.sidebar:
259
  st.title("🏗️ World Controls")
260
 
261
- # --- Space Management ---
262
- st.subheader("Manage Spaces")
263
- saved_spaces = list(world_data.get("spaces", {}).items()) # List of (id, data) tuples
264
- space_options = {sid: data.get("name", f"Unnamed ({sid[:6]}...)") for sid, data in saved_spaces}
265
- options_list = ["_new_"] + list(space_options.keys())
266
-
267
- # Determine current index for selectbox
268
- current_selection_index = 0 # Default to "Create New"
269
- if st.session_state.current_space_id in space_options:
270
- try:
271
- current_selection_index = options_list.index(st.session_state.current_space_id)
272
- except ValueError:
273
- current_selection_index = 0 # Fallback if ID somehow not in list
274
-
275
- selected_space_option = st.selectbox(
276
- "Load or Create Space:",
277
- options = options_list,
278
- format_func = lambda x: space_options.get(x, "Select...") if x != "_new_" else "✨ Create New Space ✨",
279
- index=current_selection_index,
280
- key="space_selection_widget" # Use a dedicated key for the widget
281
- )
282
-
283
- # --- Handle Load/Create Logic ---
284
- # Compare widget state to session state to detect user change
285
- if selected_space_option != st.session_state.get('_last_selected_space', None):
286
- st.session_state._last_selected_space = selected_space_option # Track selection change
287
- if selected_space_option == "_new_":
288
- # User explicitly selected "Create New"
289
- if st.session_state.current_space_id is not None: # Check if switching *from* an existing space
290
- st.session_state.current_space_id = None
291
- st.session_state.initial_objects = []
292
- st.session_state.space_name = ""
293
- st.rerun() # Rerun to clear the space
294
- else:
295
- # User selected an existing space
296
- if st.session_state.current_space_id != selected_space_option:
297
- st.session_state.current_space_id = selected_space_option
298
- # Loading data and name happens naturally at top of script now
299
- st.rerun() # Rerun to reflect the load
300
-
301
- # --- Name Input ---
302
- current_name = st.text_input(
303
- "Current Space Name:",
304
- value=st.session_state.space_name, # Reflect current loaded/new name state
305
- key="current_space_name_input"
306
- )
307
- # Update session state if user types a new name
308
- if current_name != st.session_state.space_name:
309
- st.session_state.space_name = current_name
310
- # Note: The name is only saved to world_map.json when the JS save is triggered
311
 
312
- st.info(f"Current Space ID: {st.session_state.current_space_id or 'None (New)'}")
313
- st.caption("Click 'Save Work' in the 3D view to save changes.")
314
  st.markdown("---")
315
 
316
-
317
- # --- Object Placement Controls ---
318
- st.subheader("Place Objects")
319
  object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
320
- # Ensure selectbox reflects current state
321
  current_object_index = 0
322
  try:
 
323
  current_object_index = object_types.index(st.session_state.selected_object)
324
  except ValueError:
325
- st.session_state.selected_object = "None" # Reset if invalid
 
326
 
327
  selected_object_type_widget = st.selectbox(
328
- "Select Object to Place:",
329
  options=object_types,
330
  index=current_object_index,
331
- key="selected_object_widget"
332
  )
333
- # Update state based on widget interaction
 
 
334
  if selected_object_type_widget != st.session_state.selected_object:
335
  st.session_state.selected_object = selected_object_type_widget
336
- st.rerun() # Rerun to update JS injection
 
 
 
337
 
338
  st.markdown("---")
339
 
340
- # --- Minimap ---
341
- st.subheader("World Minimap")
342
- # Regenerate map data fresh each time
343
- current_world_data_for_map = load_world_map()
344
- minimap_img = generate_minimap(current_world_data_for_map, st.session_state.current_space_id)
345
- if minimap_img:
346
- st.image(minimap_img, caption="Blue: Saved Spaces, Red: Current", use_column_width=True)
347
- else:
348
- st.caption("No spaces saved yet.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
 
351
  # --- Main Area ---
352
- st.header("3D Space Editor")
353
- st.caption(f"Editing: {st.session_state.space_name or 'New Space'}")
354
 
355
  # --- Load and Prepare HTML ---
356
  html_file_path = 'index.html'
357
- html_content_with_state = None # Initialize to None
358
 
359
  try:
360
  # --- Read the HTML template file ---
@@ -366,16 +324,16 @@ try:
366
  js_injection_script = f"""
367
  <script>
368
  // Set global variables BEFORE the main script runs
 
369
  window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
370
- window.INITIAL_OBJECTS = {json.dumps(st.session_state.initial_objects)};
371
- window.CURRENT_SPACE_ID = {json.dumps(st.session_state.current_space_id)};
372
- window.CURRENT_SPACE_NAME = {json.dumps(st.session_state.space_name)};
373
  // Basic logging to verify state in browser console
374
  console.log("Streamlit State Injected:", {{
375
  selectedObject: window.SELECTED_OBJECT_TYPE,
376
- initialObjectsCount: window.INITIAL_OBJECTS ? window.INITIAL_OBJECTS.length : 0,
377
- spaceId: window.CURRENT_SPACE_ID,
378
- spaceName: window.CURRENT_SPACE_NAME
379
  }});
380
  </script>
381
  """
@@ -396,5 +354,4 @@ except FileNotFoundError:
396
  st.warning(f"Please make sure `{html_file_path}` is in the same directory as `app.py` and that the `{SAVE_DIR}` directory exists.")
397
  except Exception as e:
398
  st.error(f"An critical error occurred during HTML preparation or component rendering: {e}")
399
- st.exception(e) # Show full traceback for debugging
400
- # Do NOT attempt to render components.html if html_content_with_state is not defined
 
3
  import streamlit.components.v1 as components
4
  import os
5
  import json
6
+ import pandas as pd
7
  import uuid
8
+ from PIL import Image, ImageDraw # Not used for minimap anymore, but kept just in case
9
+ from streamlit_js_eval import streamlit_js_eval # For JS communication
10
 
11
  # --- Constants ---
12
  SAVE_DIR = "saved_worlds"
13
+ PLOT_WIDTH = 50.0 # Width of each plot in 3D space (adjust as needed)
14
+ CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
 
15
 
16
  # --- Ensure Save Directory Exists ---
17
  os.makedirs(SAVE_DIR, exist_ok=True)
18
 
19
+ # --- Helper Functions ---
20
+
21
+ @st.cache_data(ttl=3600) # Cache plot list for an hour, or clear manually
22
+ def load_plot_metadata():
23
+ """Scans save dir, sorts plots, calculates metadata."""
24
+ plots = []
25
+ # Ensure consistent sorting, e.g., alphabetically which often aligns with plot_001, plot_002 etc.
 
 
 
 
 
 
 
 
26
  try:
27
+ plot_files = sorted([f for f in os.listdir(SAVE_DIR) if f.endswith(".csv")])
28
+ except FileNotFoundError:
29
+ st.error(f"Save directory '{SAVE_DIR}' not found.")
30
+ return [], 0.0 # Return empty if dir doesn't exist
31
  except Exception as e:
32
+ st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
33
+ return [], 0.0
34
+
35
+
36
+ current_x_offset = 0.0
37
+ for i, filename in enumerate(plot_files):
38
+ # Extract name - assumes format like 'plot_001_MyName.csv' or just 'plot_001.csv'
39
+ parts = filename[:-4].split('_') # Remove .csv and split by underscore
40
+ plot_id = filename[:-4] # Use filename (without ext) as a unique ID for now
41
+ plot_name = " ".join(parts[1:]) if len(parts) > 1 else f"Plot {i+1}" # Try to extract name
42
+
43
+ plots.append({
44
+ 'id': plot_id, # Use filename as ID
45
+ 'name': plot_name,
46
+ 'filename': filename,
47
+ 'x_offset': current_x_offset
48
+ })
49
+ current_x_offset += PLOT_WIDTH
50
+ # Also return the offset where the next plot would start
51
+ return plots, current_x_offset
52
+
53
+ def load_plot_objects(filename, x_offset):
54
+ """Loads objects from a CSV, applying the plot's x_offset."""
55
+ file_path = os.path.join(SAVE_DIR, filename)
56
+ objects = []
57
  try:
58
+ df = pd.read_csv(file_path)
59
+ # Check if required columns exist, handle gracefully if not
60
+ if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
61
+ st.warning(f"CSV '{filename}' missing essential columns (type, pos_x/y/z). Skipping.")
62
+ return []
63
+ # Ensure optional columns default to something sensible if missing
64
+ # Use vectorized operations for defaults where possible
65
+ df['obj_id'] = df.get('obj_id', pd.Series([str(uuid.uuid4()) for _ in range(len(df))]))
66
+ for col, default in [('rot_x', 0.0), ('rot_y', 0.0), ('rot_z', 0.0), ('rot_order', 'XYZ')]:
67
+ if col not in df.columns: df[col] = default
68
+
69
+
70
+ for _, row in df.iterrows():
71
+ obj_data = row.to_dict()
72
+ # Apply world offset accumulated during loading
73
+ obj_data['pos_x'] += x_offset
74
+ objects.append(obj_data)
75
+ return objects
76
+ except FileNotFoundError:
77
+ # This shouldn't happen if called via load_plot_metadata results, but handle anyway
78
+ st.error(f"File not found during object load: {filename}")
79
+ return []
80
+ except pd.errors.EmptyDataError:
81
+ # An empty file is valid, represents an empty plot
82
+ return []
83
  except Exception as e:
84
+ st.error(f"Error loading objects from {filename}: {e}")
85
+ return []
86
+
87
+
88
+ def save_plot_data(filename, objects_data_list, plot_x_offset):
89
+ """Saves object data list to a new CSV file, making positions relative."""
90
+ file_path = os.path.join(SAVE_DIR, filename)
91
+ relative_objects = []
92
+ # Ensure objects_data_list is actually a list
93
+ if not isinstance(objects_data_list, list):
94
+ st.error("Invalid data format received for saving (expected a list).")
95
+ print("Invalid save data:", objects_data_list) # Log for debugging
96
+ return False
97
+
98
+ for obj in objects_data_list:
99
+ # Validate incoming object structure more carefully
100
+ pos = obj.get('position', {})
101
+ rot = obj.get('rotation', {})
102
+ obj_type = obj.get('type', 'Unknown')
103
+ obj_id = obj.get('obj_id', str(uuid.uuid4())) # Generate ID if missing from JS
104
+
105
+ if not all(k in pos for k in ['x', 'y', 'z']) or obj_type == 'Unknown':
106
+ print(f"Skipping malformed object during save prep: {obj}")
107
+ continue
108
+
109
+ relative_obj = {
110
+ 'obj_id': obj_id,
111
+ 'type': obj_type,
112
+ 'pos_x': pos.get('x', 0.0) - plot_x_offset, # Make relative to plot start
113
+ 'pos_y': pos.get('y', 0.0),
114
+ 'pos_z': pos.get('z', 0.0),
115
+ 'rot_x': rot.get('_x', 0.0),
116
+ 'rot_y': rot.get('_y', 0.0),
117
+ 'rot_z': rot.get('_z', 0.0),
118
+ 'rot_order': rot.get('_order', 'XYZ')
119
+ }
120
+ relative_objects.append(relative_obj)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  try:
123
+ # Only save if there are objects to save
124
+ if relative_objects:
125
+ df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
126
+ df.to_csv(file_path, index=False)
127
+ st.success(f"Saved {len(relative_objects)} objects to {filename}")
128
+ else:
129
+ # Create an empty file with headers if nothing new was placed
130
+ pd.DataFrame(columns=CSV_COLUMNS).to_csv(file_path, index=False)
131
+ st.info(f"Saved empty plot file: {filename}")
132
+ return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  except Exception as e:
134
+ st.error(f"Failed to save plot data to {filename}: {e}")
135
+ return False
 
136
 
137
  # --- Page Config ---
138
  st.set_page_config(
139
+ page_title="Shared World Builder",
140
  layout="wide"
141
  )
142
 
143
  # --- Initialize Session State ---
144
  if 'selected_object' not in st.session_state:
145
  st.session_state.selected_object = 'None'
146
+ if 'new_plot_name' not in st.session_state:
147
+ st.session_state.new_plot_name = ""
148
+ # Use a more descriptive key for clarity
149
+ if 'js_save_data_result' not in st.session_state:
150
+ st.session_state.js_save_data_result = None
151
+
152
+ # --- Load Plot Metadata ---
153
+ # Cached function returns list of plots and the next starting x_offset
154
+ plots_metadata, next_plot_x_offset = load_plot_metadata()
155
+
156
+ # --- Load ALL Objects for Rendering ---
157
+ # This could be slow with many plots!
158
+ all_initial_objects = []
159
+ for plot in plots_metadata:
160
+ all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset']))
161
+
162
+ # --- Sidebar ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  with st.sidebar:
164
  st.title("🏗️ World Controls")
165
 
166
+ st.header("Navigation (Plots)")
167
+ st.caption("Click to teleport player to the start of a plot.")
168
+
169
+ # Use columns for a horizontal button layout if desired
170
+ max_cols = 3 # Adjust number of columns
171
+ cols = st.columns(max_cols)
172
+ col_idx = 0
173
+ for plot in plots_metadata:
174
+ # Use an emoji + name for the button
175
+ button_label = f"➡️ {plot.get('name', plot['id'])}" # Fallback to id if name missing
176
+ # Use plot filename (unique) as key
177
+ if cols[col_idx].button(button_label, key=f"nav_{plot['filename']}"):
178
+ # Send command to JS to move the player
179
+ target_x = plot['x_offset']
180
+ try:
181
+ streamlit_js_eval(js_code=f"teleportPlayer({target_x});", key=f"teleport_{plot['filename']}")
182
+ except Exception as e:
183
+ st.error(f"Failed to send teleport command: {e}")
184
+ # No rerun needed here, JS handles the move instantly
185
+
186
+ col_idx = (col_idx + 1) % max_cols # Cycle through columns
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
 
 
188
  st.markdown("---")
189
 
190
+ # --- Object Placement ---
191
+ st.header("Place Objects")
 
192
  object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
 
193
  current_object_index = 0
194
  try:
195
+ # Ensure robustness if selected_object is somehow not in list
196
  current_object_index = object_types.index(st.session_state.selected_object)
197
  except ValueError:
198
+ st.session_state.selected_object = "None" # Reset to default
199
+ current_object_index = 0
200
 
201
  selected_object_type_widget = st.selectbox(
202
+ "Select Object:",
203
  options=object_types,
204
  index=current_object_index,
205
+ key="selected_object_widget" # Use a distinct key for the widget
206
  )
207
+ # Update session state only if the widget's value actually changes
208
+ # This change WILL trigger a rerun because Streamlit tracks widget state.
209
+ # The JS side now handles preserving its state across the resulting reload via sessionStorage.
210
  if selected_object_type_widget != st.session_state.selected_object:
211
  st.session_state.selected_object = selected_object_type_widget
212
+ # We don't *need* to force a rerun here, Streamlit handles it.
213
+ # The important part is that the NEXT run will inject the new selected type,
214
+ # and the JS will restore placed objects from sessionStorage.
215
+
216
 
217
  st.markdown("---")
218
 
219
+ # --- Saving ---
220
+ st.header("Save New Plot")
221
+ # Ensure text input reflects current state value
222
+ st.session_state.new_plot_name = st.text_input(
223
+ "Name for New Plot:",
224
+ value=st.session_state.new_plot_name,
225
+ placeholder="My Awesome Creation",
226
+ key="new_plot_name_input" # Use distinct key
227
+ )
228
+
229
+ if st.button("💾 Save Current Work as New Plot", key="save_button"):
230
+ # 1. Trigger JS function `getSaveData()` defined in index.html
231
+ # This function collects data for newly placed objects and returns a JSON string.
232
+ # The key argument ('js_save_processor') stores the JS result in session_state.
233
+ streamlit_js_eval(
234
+ js_code="getSaveData();",
235
+ key="js_save_processor" # Store result under this key
236
+ )
237
+ # Small delay MAY sometimes help ensure the value is set before rerun, but usually not needed
238
+ # import time
239
+ # time.sleep(0.1)
240
+ st.rerun() # Rerun to process the result in the next step
241
+
242
+
243
+ # --- Process Save Data (if received from JS via the key) ---
244
+ # Check the session state key set by the streamlit_js_eval call
245
+ save_data_from_js = st.session_state.get("js_save_processor", None)
246
+
247
+ if save_data_from_js is not None: # Process only if data is present
248
+ st.info("Received save data from client...")
249
+ save_processed_successfully = False
250
+ try:
251
+ # Ensure data is treated as a string before loading json
252
+ if isinstance(save_data_from_js, str):
253
+ objects_to_save = json.loads(save_data_from_js)
254
+ else:
255
+ # Handle case where it might already be parsed by chance (less likely)
256
+ objects_to_save = save_data_from_js
257
+
258
+ # Proceed only if we have a list (even an empty one is ok now)
259
+ if isinstance(objects_to_save, list):
260
+ # Determine filename for the new plot
261
+ new_plot_index = len(plots_metadata) # 0-based index -> number of plots
262
+ # Sanitize name: replace spaces, keep only alphanumeric/underscore
263
+ plot_name_sanitized = "".join(c for c in st.session_state.new_plot_name if c.isalnum() or c in (' ')).strip().replace(' ', '_')
264
+ if not plot_name_sanitized: # Ensure there is a name part
265
+ plot_name_sanitized = f"Plot_{new_plot_index + 1}"
266
+
267
+ new_filename = f"plot_{new_plot_index:03d}_{plot_name_sanitized}.csv"
268
+
269
+ # Save the data, converting world coords to relative coords inside the func
270
+ save_ok = save_plot_data(new_filename, objects_to_save, next_plot_x_offset)
271
+
272
+ if save_ok:
273
+ # Clear the plot metadata cache so it reloads with the new file
274
+ load_plot_metadata.clear()
275
+ # Reset the new plot name field for next time
276
+ st.session_state.new_plot_name = ""
277
+ # Reset newly placed objects in JS AFTER successful save
278
+ try:
279
+ # This call tells JS to clear its internal 'newlyPlacedObjects' array AND sessionStorage
280
+ streamlit_js_eval(js_code="resetNewlyPlacedObjects();", key="reset_js_state")
281
+ except Exception as js_e:
282
+ st.warning(f"Could not reset JS state after save: {js_e}")
283
+
284
+ st.success(f"New plot '{plot_name_sanitized}' saved!")
285
+ save_processed_successfully = True
286
+ else:
287
+ st.error("Failed to save plot data to file.")
288
+
289
+ else:
290
+ st.error(f"Received invalid save data format from client (expected list): {type(objects_to_save)}")
291
+
292
+
293
+ except json.JSONDecodeError:
294
+ st.error("Failed to decode save data from client. Data might be corrupted or empty.")
295
+ print("Received raw data:", save_data_from_js) # Log raw data
296
+ except Exception as e:
297
+ st.error(f"Error processing save: {e}")
298
+ st.exception(e)
299
+
300
+ # IMPORTANT: Clear the session state key regardless of success/failure
301
+ # to prevent reprocessing on the next rerun unless the button is clicked again.
302
+ st.session_state.js_save_processor = None
303
+
304
+ # Rerun AGAIN after processing save to reflect changes (new plot loaded, cache cleared etc.)
305
+ if save_processed_successfully:
306
+ st.rerun()
307
 
308
 
309
  # --- Main Area ---
310
+ st.header("Shared 3D World")
311
+ st.caption("Build side-by-side with others. Saving adds a new plot to the right.")
312
 
313
  # --- Load and Prepare HTML ---
314
  html_file_path = 'index.html'
315
+ html_content_with_state = None # Initialize
316
 
317
  try:
318
  # --- Read the HTML template file ---
 
324
  js_injection_script = f"""
325
  <script>
326
  // Set global variables BEFORE the main script runs
327
+ window.ALL_INITIAL_OBJECTS = {json.dumps(all_initial_objects)}; // All objects from all plots
328
  window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
329
+ window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
330
+ window.NEXT_PLOT_X_OFFSET = {json.dumps(next_plot_x_offset)}; // Needed for save calculation & ground size
 
331
  // Basic logging to verify state in browser console
332
  console.log("Streamlit State Injected:", {{
333
  selectedObject: window.SELECTED_OBJECT_TYPE,
334
+ initialObjectsCount: window.ALL_INITIAL_OBJECTS ? window.ALL_INITIAL_OBJECTS.length : 0,
335
+ plotWidth: window.PLOT_WIDTH,
336
+ nextPlotX: window.NEXT_PLOT_X_OFFSET
337
  }});
338
  </script>
339
  """
 
354
  st.warning(f"Please make sure `{html_file_path}` is in the same directory as `app.py` and that the `{SAVE_DIR}` directory exists.")
355
  except Exception as e:
356
  st.error(f"An critical error occurred during HTML preparation or component rendering: {e}")
357
+ st.exception(e) # Show full traceback for debugging