Spaces:
Sleeping
Sleeping
# app.py | |
import streamlit as st | |
import streamlit.components.v1 as components | |
import os | |
import json | |
import pandas as pd | |
import uuid | |
from PIL import Image, ImageDraw # For minimap (using buttons instead now) | |
from streamlit_js_eval import streamlit_js_eval, sync # For JS communication | |
# --- Constants --- | |
SAVE_DIR = "saved_worlds" | |
PLOT_WIDTH = 50.0 # Width of each plot in 3D space (adjust as needed) | |
CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order'] | |
# --- Ensure Save Directory Exists --- | |
os.makedirs(SAVE_DIR, exist_ok=True) | |
# --- Helper Functions --- | |
# Cache plot list for an hour, or clear manually | |
def load_plot_metadata(): | |
"""Scans save dir, sorts plots, calculates metadata.""" | |
plots = [] | |
plot_files = sorted([f for f in os.listdir(SAVE_DIR) if f.endswith(".csv")]) | |
current_x_offset = 0.0 | |
for i, filename in enumerate(plot_files): | |
# Extract name - assumes format like 'plot_001_MyName.csv' or just 'plot_001.csv' | |
parts = filename[:-4].split('_') # Remove .csv and split by underscore | |
plot_id = parts[0] # Assume first part is ID/order | |
plot_name = " ".join(parts[1:]) if len(parts) > 1 else f"Plot {i+1}" | |
plots.append({ | |
'id': plot_id, | |
'name': plot_name, | |
'filename': filename, | |
'x_offset': current_x_offset | |
}) | |
current_x_offset += PLOT_WIDTH | |
return plots, current_x_offset # Return plots and the next available offset | |
def load_plot_objects(filename, x_offset): | |
"""Loads objects from a CSV, applying the plot's x_offset.""" | |
file_path = os.path.join(SAVE_DIR, filename) | |
objects = [] | |
try: | |
df = pd.read_csv(file_path) | |
if not all(col in df.columns for col in CSV_COLUMNS): | |
st.warning(f"CSV '{filename}' missing expected columns. Skipping.") | |
return [] | |
for _, row in df.iterrows(): | |
obj_data = row.to_dict() | |
# Apply world offset | |
obj_data['pos_x'] += x_offset | |
objects.append(obj_data) | |
return objects | |
except FileNotFoundError: | |
st.error(f"File not found during object load: {filename}") | |
return [] | |
except pd.errors.EmptyDataError: | |
st.info(f"Plot file '{filename}' is empty.") | |
return [] # Empty file is valid | |
except Exception as e: | |
st.error(f"Error loading objects from {filename}: {e}") | |
return [] | |
def save_plot_data(filename, objects_data_list, plot_x_offset): | |
"""Saves object data list to a new CSV file, making positions relative.""" | |
file_path = os.path.join(SAVE_DIR, filename) | |
relative_objects = [] | |
for obj in objects_data_list: | |
# Ensure required fields exist before proceeding | |
if not all(k in obj for k in ['position', 'rotation', 'type', 'obj_id']): | |
print(f"Skipping malformed object during save: {obj}") | |
continue | |
relative_obj = { | |
'obj_id': obj.get('obj_id', str(uuid.uuid4())), # Generate ID if missing | |
'type': obj.get('type', 'Unknown'), | |
'pos_x': obj['position'].get('x', 0.0) - plot_x_offset, # Make relative | |
'pos_y': obj['position'].get('y', 0.0), | |
'pos_z': obj['position'].get('z', 0.0), | |
'rot_x': obj['rotation'].get('_x', 0.0), | |
'rot_y': obj['rotation'].get('_y', 0.0), | |
'rot_z': obj['rotation'].get('_z', 0.0), | |
'rot_order': obj['rotation'].get('_order', 'XYZ') | |
} | |
relative_objects.append(relative_obj) | |
try: | |
df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS) | |
df.to_csv(file_path, index=False) | |
st.success(f"Saved plot data to {filename}") | |
return True | |
except Exception as e: | |
st.error(f"Failed to save plot data to {filename}: {e}") | |
return False | |
# --- Page Config --- | |
st.set_page_config( | |
page_title="Shared World Builder", | |
layout="wide" | |
) | |
# --- Initialize Session State --- | |
if 'selected_object' not in st.session_state: | |
st.session_state.selected_object = 'None' | |
if 'new_plot_name' not in st.session_state: | |
st.session_state.new_plot_name = "" | |
if 'save_request_data' not in st.session_state: # To store data back from JS | |
st.session_state.save_request_data = None | |
# --- Load Plot Metadata --- | |
# Cached function returns list of plots and the next starting x_offset | |
plots_metadata, next_plot_x_offset = load_plot_metadata() | |
# --- Load ALL Objects for Rendering --- | |
# This could be slow with many plots! Consider optimization later. | |
all_initial_objects = [] | |
for plot in plots_metadata: |