добавил страницу выбора модели, добавил механизм
загрузки изображения для модели, добавил механизм удаления модели из конфига отредактировал README.md изменил окно вывода модели в PotreeViewer.tsx добавив кнопку выхода в меню выбора модели
This commit is contained in:
parent
5bcc928405
commit
68cf3dca22
79
COPC_CONVERSION.md
Normal file
79
COPC_CONVERSION.md
Normal file
@ -0,0 +1,79 @@
|
||||
# Конвертация LAZ файлов в COPC для Potree
|
||||
|
||||
## Проблема
|
||||
|
||||
Обычные LAZ/LAS файлы не поддерживаются напрямую в Potree. Для корректной работы нужно использовать COPC (Cloud Optimized Point Cloud) формат.
|
||||
|
||||
## Решение
|
||||
|
||||
### Вариант 1: Конвертация через PDAL (рекомендуется)
|
||||
|
||||
1. **Установка PDAL**:
|
||||
```bash
|
||||
# macOS
|
||||
brew install pdal
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt-get install pdal
|
||||
|
||||
# Windows
|
||||
conda install -c conda-forge pdal
|
||||
```
|
||||
|
||||
2. **Конвертация файла**:
|
||||
```bash
|
||||
pdal translate input.laz output.copc.laz --writers.copc.forward=all
|
||||
```
|
||||
|
||||
3. **Пример для нашего файла**:
|
||||
```bash
|
||||
pdal translate lion_takanawa.laz lion_takanawa.copc.laz --writers.copc.forward=all
|
||||
```
|
||||
|
||||
### Вариант 2: Онлайн конвертация
|
||||
|
||||
Можно использовать онлайн сервисы для конвертации, но для больших файлов рекомендуется локальная конвертация.
|
||||
|
||||
### Вариант 3: Автоматическая конвертация в системе
|
||||
|
||||
Можно добавить в систему автоматическую конвертацию при загрузке файлов:
|
||||
|
||||
```javascript
|
||||
// Псевдокод для будущей реализации
|
||||
if (file.endsWith('.laz') && !file.endsWith('.copc.laz')) {
|
||||
// Проверить, является ли файл уже COPC
|
||||
// Если нет - показать сообщение о необходимости конвертации
|
||||
// Или автоматически конвертировать
|
||||
}
|
||||
```
|
||||
|
||||
## Проверка формата файла
|
||||
|
||||
Чтобы узнать, является ли файл COPC, можно использовать:
|
||||
|
||||
```bash
|
||||
pdal info your_file.laz --metadata
|
||||
```
|
||||
|
||||
В выводе должна быть информация о COPC, если файл в правильном формате.
|
||||
|
||||
## Преимущества COPC
|
||||
|
||||
- **Оптимизирован для веб-загрузки** - поддерживает Range запросы
|
||||
- **Лучшая производительность** - данные организованы для быстрого доступа
|
||||
- **Совместимость с Potree** - нативная поддержка без дополнительных конвертаций
|
||||
- **Стандартизированный формат** - открытый стандарт OGC
|
||||
|
||||
## Текущее состояние системы
|
||||
|
||||
✅ COPC файлы работают отлично
|
||||
❌ Обычные LAZ файлы требуют конвертации
|
||||
✅ Middleware поддерживает Range запросы для COPC
|
||||
✅ Авторизация и безопасность настроены
|
||||
|
||||
## Рекомендации
|
||||
|
||||
1. **Конвертировать все существующие LAZ файлы в COPC**
|
||||
2. **В будущем принимать только COPC файлы**
|
||||
3. **Добавить автоматическую проверку формата при загрузке**
|
||||
4. **Показывать пользователям сообщения о необходимости правильного формата**
|
||||
182
MODELS_SETUP.md
Normal file
182
MODELS_SETUP.md
Normal file
@ -0,0 +1,182 @@
|
||||
# Настройка системы выбора моделей
|
||||
|
||||
## Обзор
|
||||
|
||||
Система была обновлена для поддержки выбора моделей из внешней папки. Теперь после входа пользователь сначала попадает на страницу выбора модели, где может:
|
||||
|
||||
- Просматривать доступные модели с предпросмотром
|
||||
- Редактировать названия (алиасы) моделей
|
||||
- Выбирать модель для просмотра в Potree
|
||||
|
||||
## Структура файлов
|
||||
|
||||
### Папка моделей
|
||||
По умолчанию: `../models` (относительно проекта)
|
||||
|
||||
Можно изменить через переменную окружения:
|
||||
```bash
|
||||
export MODELS_PATH=/path/to/your/models
|
||||
```
|
||||
|
||||
### Файлы в папке моделей:
|
||||
- `*.laz`, `*.las`, `*.ply`, `*.copc.laz` - файлы моделей
|
||||
- `*.jpg`, `*.jpeg`, `*.png`, `*.webp` - изображения предпросмотра (опционально)
|
||||
- `models.json` - конфигурационный файл (создается автоматически)
|
||||
|
||||
## Формат изображений предпросмотра
|
||||
|
||||
Для модели `model.laz` система будет искать изображение предпросмотра в следующем порядке:
|
||||
- `model.jpg`
|
||||
- `model.jpeg`
|
||||
- `model.png`
|
||||
- `model.webp`
|
||||
|
||||
Если изображение не найдено, будет показан заглушка.
|
||||
|
||||
## Конфигурационный файл models.json
|
||||
|
||||
Автоматически создается и обновляется при сканировании папки. Содержит:
|
||||
|
||||
```json
|
||||
{
|
||||
"filename.laz": {
|
||||
"id": "filename.laz",
|
||||
"filename": "filename.laz",
|
||||
"alias": "Пользовательское название",
|
||||
"previewImage": "filename.jpg",
|
||||
"size": 1234567,
|
||||
"lastModified": "2024-06-04T15:12:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### GET /api/models
|
||||
Получить список всех доступных моделей
|
||||
|
||||
### PUT /api/models/:id/alias
|
||||
Обновить алиас модели
|
||||
```json
|
||||
{
|
||||
"alias": "Новое название"
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/models/:id/preview
|
||||
Получить изображение предпросмотра модели
|
||||
|
||||
### GET /api/models/:id/download
|
||||
Скачать файл модели
|
||||
|
||||
## Маршрутизация
|
||||
|
||||
1. `/login` - Страница входа
|
||||
2. `/models` - Выбор модели (после входа)
|
||||
3. `/viewer` - Просмотр выбранной модели в Potree
|
||||
|
||||
## Docker настройка
|
||||
|
||||
Для использования с Docker примонтируйте внешнюю папку:
|
||||
|
||||
```dockerfile
|
||||
# В Dockerfile
|
||||
ENV MODELS_PATH=/app/models
|
||||
|
||||
# При запуске контейнера
|
||||
docker run -v /host/path/to/models:/app/models your-app
|
||||
```
|
||||
|
||||
Или через docker-compose:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
potree-app:
|
||||
build: .
|
||||
volumes:
|
||||
- /host/path/to/models:/app/models
|
||||
environment:
|
||||
- MODELS_PATH=/app/models
|
||||
```
|
||||
|
||||
## Тестирование
|
||||
|
||||
1. Создайте папку `../models` относительно проекта
|
||||
2. Поместите туда файлы моделей (`.laz`, `.las`, `.ply`, `.copc.laz`)
|
||||
3. Опционально добавьте изображения предпросмотра
|
||||
4. Запустите приложение
|
||||
5. Войдите в систему (admin/secret)
|
||||
6. Выберите модель на странице выбора
|
||||
7. Наслаждайтесь просмотром в Potree!
|
||||
|
||||
## Поддерживаемые форматы
|
||||
|
||||
### Модели:
|
||||
- `.laz` - LAS сжатый (**требует конвертации в формат Potree**)
|
||||
- `.las` - LAS несжатый (**требует конвертации в формат Potree**)
|
||||
- `.ply` - Stanford PLY (**требует конвертации в формат Potree**)
|
||||
- `.copc.laz` - Cloud Optimized Point Cloud (**готов к использованию**)
|
||||
|
||||
### Изображения предпросмотра:
|
||||
- `.jpg`, `.jpeg` - JPEG
|
||||
- `.png` - PNG
|
||||
- `.webp` - WebP
|
||||
- `.svg` - SVG
|
||||
|
||||
## Конвертация файлов
|
||||
|
||||
### Обычные LAS/LAZ файлы
|
||||
Обычные LAS/LAZ файлы нужно сконвертировать в формат Potree:
|
||||
|
||||
```bash
|
||||
# Установка PotreeConverter (требует Node.js)
|
||||
npm install -g potree-converter
|
||||
|
||||
# Конвертация файла
|
||||
potree-converter input.laz -o output_directory
|
||||
|
||||
# Результат: папка с файлами для Potree
|
||||
# Поместите содержимое в папку моделей
|
||||
```
|
||||
|
||||
### COPC файлы
|
||||
COPC (Cloud Optimized Point Cloud) файлы готовы к использованию без конвертации.
|
||||
|
||||
Можно создать COPC файлы с помощью PDAL:
|
||||
|
||||
```bash
|
||||
# Установка PDAL
|
||||
conda install -c conda-forge pdal
|
||||
|
||||
# Конвертация в COPC
|
||||
pdal translate input.laz output.copc.laz \
|
||||
--writers.copc.chunk_size=1000 \
|
||||
--writers.copc.cube_size=50000
|
||||
```
|
||||
|
||||
### Рекомендации
|
||||
- **Для простоты использования**: Используйте COPC файлы (*.copc.laz)
|
||||
- **Для максимальной производительности**: Используйте предконвертированные файлы Potree
|
||||
- **Небольшие файлы**: Можно попробовать загрузить как есть (.laz/.las)
|
||||
|
||||
## Функции
|
||||
|
||||
### Автоматическое сканирование
|
||||
- Система автоматически сканирует папку при запросе `/api/models`
|
||||
- Обновляет размеры файлов и даты изменения
|
||||
- Создает записи для новых файлов
|
||||
|
||||
### Управление алиасами
|
||||
- Клик на ✏️ для редактирования названия
|
||||
- Enter для сохранения, Escape для отмены
|
||||
- Алиасы сохраняются в `models.json`
|
||||
|
||||
### Отзывчивый дизайн
|
||||
- Адаптируется под мобильные устройства
|
||||
- Красивые анимации и переходы
|
||||
- Современный Material Design
|
||||
|
||||
### Безопасность
|
||||
- Проверка авторизации для доступа к моделям
|
||||
- Валидация типов файлов
|
||||
- Защита от SQL-инъекций и XSS
|
||||
1
POTREE_CONVERSION.md
Normal file
1
POTREE_CONVERSION.md
Normal file
@ -0,0 +1 @@
|
||||
|
||||
183
README.md
183
README.md
@ -1,15 +1,190 @@
|
||||
# potree_build
|
||||
# Potree Model Viewer
|
||||
|
||||
To install dependencies:
|
||||
Современное веб-приложение для просмотра облаков точек с использованием Potree, React и Vite.
|
||||
|
||||
## Основные возможности
|
||||
|
||||
- **Аутентификация**: Система входа для защиты доступа к моделям
|
||||
- **Выбор моделей**: Красивая страница с превью моделей и возможностью редактирования названий
|
||||
- **Загрузка изображений**: Возможность загружать собственные изображения предпросмотра для моделей
|
||||
- **Просмотр 3D**: Полнофункциональный Potree viewer с современным интерфейсом
|
||||
- **Внешнее хранение**: Модели хранятся во внешней папке для Docker-совместимости
|
||||
- **Современный UI**: Красивые анимации, градиенты и отзывчивый дизайн
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### 1. Установка зависимостей
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
To run:
|
||||
### 2. Настройка моделей
|
||||
|
||||
Создайте папку для моделей и добавьте файлы:
|
||||
|
||||
```bash
|
||||
mkdir ../models
|
||||
cp your-point-cloud.laz ../models/
|
||||
# Опционально: добавьте изображения предпросмотра
|
||||
cp your-preview.jpg ../models/your-point-cloud.jpg
|
||||
```
|
||||
|
||||
### 3. Запуск
|
||||
|
||||
```bash
|
||||
# Режим разработки
|
||||
bun run dev
|
||||
|
||||
# Или продакшн сервер
|
||||
bun run index.ts
|
||||
```
|
||||
|
||||
This project was created using `bun init` in bun v1.1.43. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
||||
### 4. Использование
|
||||
|
||||
1. Откройте http://localhost:5173
|
||||
2. Войдите в систему (логин: `admin`, пароль: `secret`)
|
||||
3. Выберите модель на странице выбора
|
||||
4. Наслаждайтесь просмотром в Potree!
|
||||
|
||||
## Поддерживаемые форматы
|
||||
|
||||
**Модели:**
|
||||
- `.laz` - LAS сжатый
|
||||
- `.las` - LAS несжатый
|
||||
- `.ply` - Stanford PLY
|
||||
- `.copc.laz` - Cloud Optimized Point Cloud
|
||||
|
||||
**Изображения предпросмотра:**
|
||||
- `.jpg`, `.jpeg`, `.png`, `.webp`, `.svg`
|
||||
|
||||
## Конфигурация
|
||||
|
||||
### Переменные окружения
|
||||
|
||||
```bash
|
||||
# Путь к папке с моделями (по умолчанию: ../models)
|
||||
export MODELS_PATH=/path/to/your/models
|
||||
|
||||
# Порт сервера (по умолчанию: 5173)
|
||||
export PORT=3000
|
||||
```
|
||||
|
||||
Скопируйте `env.example` в `.env` для локальных настроек.
|
||||
|
||||
### Docker
|
||||
|
||||
```dockerfile
|
||||
# Dockerfile пример
|
||||
FROM node:18-alpine
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN npm install
|
||||
ENV MODELS_PATH=/app/models
|
||||
EXPOSE 5173
|
||||
CMD ["npm", "start"]
|
||||
```
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
version: '3.8'
|
||||
services:
|
||||
potree-viewer:
|
||||
build: .
|
||||
ports:
|
||||
- "5173:5173"
|
||||
volumes:
|
||||
- /host/path/to/models:/app/models
|
||||
environment:
|
||||
- MODELS_PATH=/app/models
|
||||
```
|
||||
|
||||
## Архитектура
|
||||
|
||||
- **Frontend**: React + TypeScript + Vite
|
||||
- **Backend**: Elysia (Bun)
|
||||
- **3D Engine**: Potree + Three.js
|
||||
- **Styling**: Custom CSS с современным дизайном
|
||||
- **Аутентификация**: Session-based с cookies
|
||||
|
||||
## API
|
||||
|
||||
### Модели
|
||||
- `GET /api/models` - Список моделей
|
||||
- `PUT /api/models/:id/alias` - Обновить название
|
||||
- `GET /api/models/:id/preview` - Изображение предпросмотра
|
||||
- `GET /api/models/:id/download` - Скачать модель
|
||||
|
||||
### Аутентификация
|
||||
- `POST /api/login` - Вход в систему
|
||||
- `POST /api/logout` - Выход
|
||||
- `GET /api/check-session` - Проверка сессии
|
||||
|
||||
## Разработка
|
||||
|
||||
```bash
|
||||
# Установка зависимостей
|
||||
bun install
|
||||
|
||||
# Запуск в режиме разработки
|
||||
bun run dev
|
||||
|
||||
# Сборка для продакшна
|
||||
bun run build
|
||||
|
||||
# Предпросмотр сборки
|
||||
bun run preview
|
||||
```
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
potree_build/
|
||||
├── src/
|
||||
│ ├── api/handlers/ # API обработчики
|
||||
│ ├── components/ # React компоненты
|
||||
│ ├── pages/ # Страницы приложения
|
||||
│ └── main.tsx # Точка входа
|
||||
├── public/ # Статические файлы Potree
|
||||
├── protected/ # Защищенные файлы
|
||||
└── ../models/ # Внешняя папка с моделями
|
||||
└── ../image_model_preview/ # Пользовательские изображения
|
||||
```
|
||||
|
||||
## Подробная документация
|
||||
|
||||
Смотрите [MODELS_SETUP.md](./MODELS_SETUP.md) для детальной настройки системы моделей.
|
||||
|
||||
## Технологии
|
||||
|
||||
- [Bun](https://bun.sh) - JavaScript runtime
|
||||
- [React](https://react.dev) - UI библиотека
|
||||
- [Vite](https://vitejs.dev) - Сборщик и dev сервер
|
||||
- [Potree](https://potree.org) - WebGL облака точек
|
||||
- [Elysia](https://elysiajs.com) - Web framework
|
||||
- [TypeScript](https://typescriptlang.org) - Типизация
|
||||
|
||||
---
|
||||
|
||||
*Создано с ❤️ для работы с облаками точек*
|
||||
|
||||
### Добавление моделей
|
||||
|
||||
1. Поместите файлы моделей в папку `../models/` (поддерживаемые форматы: .laz, .las, .ply, .copc.laz)
|
||||
2. При желании, добавьте изображения предпросмотра с тем же именем и расширением .jpg/.png/.webp/.svg
|
||||
3. Перезапустите приложение или нажмите кнопку обновления на странице выбора моделей
|
||||
|
||||
### Загрузка пользовательских изображений
|
||||
|
||||
Вы можете загружать собственные изображения предпросмотра для моделей:
|
||||
|
||||
1. На странице выбора моделей нажмите кнопку 📷 на карточке модели
|
||||
2. Выберите изображение (поддерживаемые форматы: JPG, PNG, WebP, SVG)
|
||||
3. Изображение автоматически сохранится в папке `../image_model_preview/`
|
||||
4. Модели с пользовательскими изображениями отмечаются золотой звездочкой ⭐
|
||||
|
||||
**Особенности:**
|
||||
- Максимальный размер файла: 10MB
|
||||
- Пользовательские изображения имеют приоритет над стандартными
|
||||
- При загрузке нового изображения старое автоматически удаляется
|
||||
- Изображения именуются по базовому имени модели
|
||||
|
||||
14
env.example
Normal file
14
env.example
Normal file
@ -0,0 +1,14 @@
|
||||
# Путь к папке с моделями (относительно корня проекта)
|
||||
MODELS_PATH=../models
|
||||
|
||||
# Путь к папке с пользовательскими изображениями предпросмотра
|
||||
IMAGES_PATH=../image_model_preview
|
||||
|
||||
# Порт для разработки (по умолчанию 5173)
|
||||
VITE_PORT=5173
|
||||
|
||||
# Уровень логирования (debug, info, warn, error)
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Включить/отключить подробные логи Potree
|
||||
POTREE_DEBUG=false
|
||||
@ -2,6 +2,7 @@ import React from 'react';
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
import ModelSelection from './pages/ModelSelection';
|
||||
import PotreeViewer from './pages/PotreeViewer';
|
||||
import './App.css';
|
||||
|
||||
@ -12,6 +13,7 @@ export default function App() {
|
||||
<Route path="/" element={<Navigate to="/login" />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/models" element={<ModelSelection />} />
|
||||
<Route path="/viewer" element={<PotreeViewer />} />
|
||||
{/* Все остальные маршруты ведут на логин */}
|
||||
<Route path="*" element={<Navigate to="/login" />} />
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { handleLoginRequest, handleLogoutRequest, checkSessionRequest } from '../auth';
|
||||
import { getViewerPage } from '../viewer';
|
||||
import { handleModelsApi } from './models';
|
||||
|
||||
// Обработчик API запросов
|
||||
export async function apiHandler(request: Request, url: URL): Promise<Response> {
|
||||
@ -7,6 +8,11 @@ export async function apiHandler(request: Request, url: URL): Promise<Response>
|
||||
|
||||
console.log('API запрос:', path, request.method);
|
||||
|
||||
// Обработка запросов к моделям
|
||||
if (path.startsWith('/api/models')) {
|
||||
return handleModelsApi(request, url);
|
||||
}
|
||||
|
||||
// Авторизация (основной путь)
|
||||
if (path === '/api/login' && request.method === 'POST') {
|
||||
console.log('Обрабатываю запрос на /api/login');
|
||||
|
||||
414
src/api/handlers/models.ts
Normal file
414
src/api/handlers/models.ts
Normal file
@ -0,0 +1,414 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Получаем пути к папкам из переменных окружения или используем значения по умолчанию
|
||||
const MODELS_DIR = process.env.MODELS_PATH || path.join(process.cwd(), '..', 'models');
|
||||
const IMAGES_DIR = process.env.IMAGES_PATH || path.join(process.cwd(), '..', 'image_model_preview');
|
||||
const CONFIG_FILE = path.join(MODELS_DIR, 'models.json');
|
||||
|
||||
interface ModelInfo {
|
||||
id: string;
|
||||
filename: string;
|
||||
alias: string;
|
||||
previewImage?: string;
|
||||
hasCustomPreview?: boolean; // флаг для отличия пользовательских изображений
|
||||
size?: number;
|
||||
lastModified?: string;
|
||||
}
|
||||
|
||||
// Функция для загрузки конфигурации моделей
|
||||
function loadModelsConfig(): Record<string, ModelInfo> {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_FILE)) {
|
||||
const configData = fs.readFileSync(CONFIG_FILE, 'utf-8');
|
||||
return JSON.parse(configData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при загрузке конфигурации моделей:', error);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// Функция для сохранения конфигурации моделей
|
||||
function saveModelsConfig(config: Record<string, ModelInfo>): void {
|
||||
try {
|
||||
// Создаем папку моделей если её нет
|
||||
if (!fs.existsSync(MODELS_DIR)) {
|
||||
fs.mkdirSync(MODELS_DIR, { recursive: true });
|
||||
}
|
||||
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
|
||||
} catch (error) {
|
||||
console.error('Ошибка при сохранении конфигурации моделей:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция для сканирования папки моделей
|
||||
function scanModelsDirectory(): ModelInfo[] {
|
||||
console.log('Сканирование папки моделей:', MODELS_DIR);
|
||||
|
||||
if (!fs.existsSync(MODELS_DIR)) {
|
||||
console.log('Папка моделей не существует, создаем:', MODELS_DIR);
|
||||
try {
|
||||
fs.mkdirSync(MODELS_DIR, { recursive: true });
|
||||
} catch (error) {
|
||||
console.error('Не удалось создать папку моделей:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const config = loadModelsConfig();
|
||||
const models: ModelInfo[] = [];
|
||||
|
||||
try {
|
||||
const files = fs.readdirSync(MODELS_DIR);
|
||||
const modelFiles = files.filter(file =>
|
||||
file.endsWith('.laz') ||
|
||||
file.endsWith('.las') ||
|
||||
file.endsWith('.ply') ||
|
||||
file.endsWith('.copc.laz')
|
||||
);
|
||||
|
||||
for (const filename of modelFiles) {
|
||||
const fullPath = path.join(MODELS_DIR, filename);
|
||||
const stats = fs.statSync(fullPath);
|
||||
const id = filename;
|
||||
|
||||
// Получаем информацию из конфига или создаем новую запись
|
||||
const existingInfo = config[id] || {
|
||||
id,
|
||||
filename,
|
||||
alias: filename.replace(/\.(laz|las|ply|copc\.laz)$/, ''), // убираем расширение для алиаса по умолчанию
|
||||
};
|
||||
|
||||
const modelInfo: ModelInfo = {
|
||||
...existingInfo,
|
||||
size: stats.size,
|
||||
lastModified: stats.mtime.toISOString(),
|
||||
};
|
||||
|
||||
// Проверяем наличие файла предпросмотра
|
||||
const previewExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.svg'];
|
||||
const baseFilename = filename.replace(/\.(laz|las|ply|copc\.laz)$/, '');
|
||||
|
||||
// Сначала проверяем пользовательские изображения в image_model_preview
|
||||
let foundCustomPreview = false;
|
||||
if (fs.existsSync(IMAGES_DIR)) {
|
||||
for (const ext of previewExtensions) {
|
||||
const customPreviewPath = path.join(IMAGES_DIR, `${baseFilename}${ext}`);
|
||||
if (fs.existsSync(customPreviewPath)) {
|
||||
modelInfo.previewImage = `${baseFilename}${ext}`;
|
||||
modelInfo.hasCustomPreview = true;
|
||||
foundCustomPreview = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Если пользовательское изображение не найдено, ищем в папке моделей
|
||||
if (!foundCustomPreview) {
|
||||
for (const ext of previewExtensions) {
|
||||
const previewPath = path.join(MODELS_DIR, `${baseFilename}${ext}`);
|
||||
if (fs.existsSync(previewPath)) {
|
||||
modelInfo.previewImage = `${baseFilename}${ext}`;
|
||||
modelInfo.hasCustomPreview = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
models.push(modelInfo);
|
||||
config[id] = modelInfo;
|
||||
}
|
||||
|
||||
// Удаляем из конфига записи для файлов, которых больше нет
|
||||
const existingModelIds = modelFiles;
|
||||
Object.keys(config).forEach(configId => {
|
||||
if (!existingModelIds.includes(configId)) {
|
||||
console.log(`Удаляем устаревшую запись из конфигурации: ${configId}`);
|
||||
delete config[configId];
|
||||
}
|
||||
});
|
||||
|
||||
// Сохраняем обновленную конфигурацию
|
||||
saveModelsConfig(config);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при сканировании папки моделей:', error);
|
||||
}
|
||||
|
||||
return models;
|
||||
}
|
||||
|
||||
export async function handleModelsApi(request: Request, url: URL): Promise<Response> {
|
||||
const pathname = url.pathname;
|
||||
const method = request.method;
|
||||
|
||||
// GET /api/models - получить список моделей
|
||||
if (pathname === '/api/models' && method === 'GET') {
|
||||
try {
|
||||
const models = scanModelsDirectory();
|
||||
return new Response(JSON.stringify({
|
||||
success: true,
|
||||
models,
|
||||
modelsPath: MODELS_DIR
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении списка моделей:', error);
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Не удалось получить список моделей'
|
||||
}), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/models/:id/alias - обновить алиас модели
|
||||
if (pathname.startsWith('/api/models/') && pathname.endsWith('/alias') && method === 'PUT') {
|
||||
try {
|
||||
const modelId = pathname.split('/')[3]; // /api/models/:id/alias
|
||||
const { alias } = await request.json();
|
||||
|
||||
if (!alias || alias.trim() === '') {
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Алиас не может быть пустым'
|
||||
}), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
const config = loadModelsConfig();
|
||||
if (!config[modelId]) {
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Модель не найдена'
|
||||
}), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
config[modelId].alias = alias.trim();
|
||||
saveModelsConfig(config);
|
||||
|
||||
return new Response(JSON.stringify({
|
||||
success: true,
|
||||
model: config[modelId]
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обновлении алиаса:', error);
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Не удалось обновить алиас'
|
||||
}), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/models/:id/preview - получить изображение предпросмотра
|
||||
if (pathname.startsWith('/api/models/') && pathname.endsWith('/preview') && method === 'GET') {
|
||||
try {
|
||||
const modelId = pathname.split('/')[3]; // /api/models/:id/preview
|
||||
const config = loadModelsConfig();
|
||||
const modelInfo = config[modelId];
|
||||
|
||||
console.log(`Запрос предпросмотра для модели: ${modelId}`);
|
||||
console.log(`Информация о модели:`, modelInfo);
|
||||
|
||||
if (!modelInfo || !modelInfo.previewImage) {
|
||||
console.log('Изображение предпросмотра не найдено для модели:', modelId);
|
||||
return new Response('Preview not found', { status: 404 });
|
||||
}
|
||||
|
||||
// Определяем путь к изображению в зависимости от того, пользовательское ли оно
|
||||
let previewPath: string;
|
||||
if (modelInfo.hasCustomPreview) {
|
||||
previewPath = path.join(IMAGES_DIR, modelInfo.previewImage);
|
||||
console.log(`Используем пользовательское изображение: ${previewPath}`);
|
||||
} else {
|
||||
previewPath = path.join(MODELS_DIR, modelInfo.previewImage);
|
||||
console.log(`Используем стандартное изображение: ${previewPath}`);
|
||||
}
|
||||
|
||||
if (!fs.existsSync(previewPath)) {
|
||||
console.log(`Файл изображения не найден: ${previewPath}`);
|
||||
return new Response('Preview file not found', { status: 404 });
|
||||
}
|
||||
|
||||
console.log(`Отправляем изображение: ${previewPath}`);
|
||||
const imageBuffer = fs.readFileSync(previewPath);
|
||||
const ext = path.extname(modelInfo.previewImage).toLowerCase();
|
||||
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml'
|
||||
};
|
||||
|
||||
const mimeType = mimeTypes[ext] || 'image/jpeg';
|
||||
|
||||
return new Response(imageBuffer, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': mimeType,
|
||||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||
'Pragma': 'no-cache',
|
||||
'Expires': '0'
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении предпросмотра:', error);
|
||||
return new Response('Internal server error', { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/models/:id/download - получить файл модели
|
||||
if (pathname.startsWith('/api/models/') && pathname.endsWith('/download') && method === 'GET') {
|
||||
try {
|
||||
const modelId = pathname.split('/')[3]; // /api/models/:id/download
|
||||
const config = loadModelsConfig();
|
||||
const modelInfo = config[modelId];
|
||||
|
||||
if (!modelInfo) {
|
||||
return new Response('Model not found', { status: 404 });
|
||||
}
|
||||
|
||||
const modelPath = path.join(MODELS_DIR, modelInfo.filename);
|
||||
if (!fs.existsSync(modelPath)) {
|
||||
return new Response('Model file not found', { status: 404 });
|
||||
}
|
||||
|
||||
const fileBuffer = fs.readFileSync(modelPath);
|
||||
const ext = path.extname(modelInfo.filename).toLowerCase();
|
||||
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'.laz': 'application/octet-stream',
|
||||
'.las': 'application/octet-stream',
|
||||
'.ply': 'application/octet-stream'
|
||||
};
|
||||
|
||||
const mimeType = mimeTypes[ext] || 'application/octet-stream';
|
||||
|
||||
return new Response(fileBuffer, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': mimeType,
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
'Content-Disposition': `inline; filename="${modelInfo.filename}"`
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при скачивании модели:', error);
|
||||
return new Response('Internal server error', { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/models/:id/upload-preview - загрузить изображение предпросмотра
|
||||
if (pathname.startsWith('/api/models/') && pathname.endsWith('/upload-preview') && method === 'POST') {
|
||||
try {
|
||||
const modelId = pathname.split('/')[3]; // /api/models/:id/upload-preview
|
||||
const config = loadModelsConfig();
|
||||
|
||||
if (!config[modelId]) {
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Модель не найдена'
|
||||
}), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
// Создаем папку для изображений если её нет
|
||||
if (!fs.existsSync(IMAGES_DIR)) {
|
||||
fs.mkdirSync(IMAGES_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
// Получаем данные файла из FormData
|
||||
const formData = await request.formData();
|
||||
const imageFile = formData.get('image') as File;
|
||||
|
||||
if (!imageFile) {
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Файл изображения не найден'
|
||||
}), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
// Проверяем тип файла
|
||||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/svg+xml'];
|
||||
if (!allowedTypes.includes(imageFile.type)) {
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Неподдерживаемый тип файла. Разрешены: JPG, PNG, WebP, SVG'
|
||||
}), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
// Определяем расширение файла
|
||||
let extension = '.jpg';
|
||||
if (imageFile.type === 'image/png') extension = '.png';
|
||||
else if (imageFile.type === 'image/webp') extension = '.webp';
|
||||
else if (imageFile.type === 'image/svg+xml') extension = '.svg';
|
||||
|
||||
// Генерируем имя файла на основе модели
|
||||
const baseFilename = config[modelId].filename.replace(/\.(laz|las|ply|copc\.laz)$/, '');
|
||||
const newImageName = `${baseFilename}${extension}`;
|
||||
const imagePath = path.join(IMAGES_DIR, newImageName);
|
||||
|
||||
// Удаляем старое пользовательское изображение если есть
|
||||
if (config[modelId].hasCustomPreview && config[modelId].previewImage) {
|
||||
const oldImagePath = path.join(IMAGES_DIR, config[modelId].previewImage);
|
||||
if (fs.existsSync(oldImagePath)) {
|
||||
fs.unlinkSync(oldImagePath);
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем новое изображение
|
||||
const imageBuffer = Buffer.from(await imageFile.arrayBuffer());
|
||||
fs.writeFileSync(imagePath, imageBuffer);
|
||||
|
||||
// Обновляем конфигурацию модели
|
||||
config[modelId].previewImage = newImageName;
|
||||
config[modelId].hasCustomPreview = true;
|
||||
saveModelsConfig(config);
|
||||
|
||||
return new Response(JSON.stringify({
|
||||
success: true,
|
||||
message: 'Изображение успешно загружено',
|
||||
model: config[modelId]
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при загрузке изображения:', error);
|
||||
return new Response(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Не удалось загрузить изображение'
|
||||
}), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
710
src/components/ModelSelection.css
Normal file
710
src/components/ModelSelection.css
Normal file
@ -0,0 +1,710 @@
|
||||
/* Страница выбора моделей в фирменном стиле */
|
||||
.model-selection-page {
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 50%, #1a1a1a 100%);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
/* Анимированный фон */
|
||||
.model-selection-page::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background:
|
||||
radial-gradient(circle at 20% 80%, rgba(76, 175, 80, 0.1) 0%, transparent 50%),
|
||||
radial-gradient(circle at 80% 20%, rgba(76, 175, 80, 0.1) 0%, transparent 50%),
|
||||
radial-gradient(circle at 40% 40%, rgba(76, 175, 80, 0.05) 0%, transparent 50%);
|
||||
animation: backgroundPulse 8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes backgroundPulse {
|
||||
0%, 100% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
/* Основной контейнер */
|
||||
.model-selection-container {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
animation: containerSlideIn 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
|
||||
}
|
||||
|
||||
/* Заголовок страницы */
|
||||
.model-selection-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 3rem;
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 16px;
|
||||
padding: 2rem;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
box-shadow:
|
||||
0 20px 40px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||
animation: headerFadeIn 1s ease-out both;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.model-selection-title {
|
||||
font-size: 2.5rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
margin: 0 0 0.5rem 0;
|
||||
background: linear-gradient(135deg, #4CAF50, #45a049);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
text-shadow: 0 2px 10px rgba(76, 175, 80, 0.3);
|
||||
}
|
||||
|
||||
.model-selection-subtitle {
|
||||
font-size: 1.1rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
margin: 0;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
/* Кнопка выхода справа сверху */
|
||||
.logout-btn {
|
||||
background: rgba(244, 67, 54, 0.2);
|
||||
border: 1px solid rgba(244, 67, 54, 0.4);
|
||||
border-radius: 12px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #ff6b6b;
|
||||
backdrop-filter: blur(10px);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.logout-btn::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(244, 67, 54, 0.1), transparent);
|
||||
transition: left 0.5s ease;
|
||||
}
|
||||
|
||||
.logout-btn:hover::before {
|
||||
left: 100%;
|
||||
}
|
||||
|
||||
.logout-btn:hover {
|
||||
background: rgba(244, 67, 54, 0.3);
|
||||
border-color: rgba(244, 67, 54, 0.6);
|
||||
transform: scale(1.05);
|
||||
box-shadow: 0 4px 15px rgba(244, 67, 54, 0.4);
|
||||
color: #ff4444;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Кнопки в фирменном стиле */
|
||||
.model-btn {
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
backdrop-filter: blur(10px);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.model-btn::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
|
||||
transition: left 0.5s ease;
|
||||
}
|
||||
|
||||
.model-btn:hover::before {
|
||||
left: 100%;
|
||||
}
|
||||
|
||||
.model-btn-primary {
|
||||
background: linear-gradient(135deg, #4CAF50, #45a049);
|
||||
color: white;
|
||||
box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
|
||||
}
|
||||
|
||||
.model-btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
|
||||
}
|
||||
|
||||
.model-btn-secondary {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: white;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.model-btn-secondary:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.model-btn-danger {
|
||||
background: linear-gradient(135deg, #f44336, #d32f2f);
|
||||
color: white;
|
||||
box-shadow: 0 4px 15px rgba(244, 67, 54, 0.3);
|
||||
}
|
||||
|
||||
.model-btn-danger:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(244, 67, 54, 0.4);
|
||||
}
|
||||
|
||||
/* Сетка моделей */
|
||||
.models-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
|
||||
gap: 2rem;
|
||||
animation: gridFadeIn 1.2s ease-out both;
|
||||
}
|
||||
|
||||
/* Карточка модели */
|
||||
.model-card {
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 16px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
box-shadow:
|
||||
0 20px 40px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||
transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
animation: cardSlideUp 0.8s ease-out both;
|
||||
}
|
||||
|
||||
.model-card:nth-child(1) { animation-delay: 0.1s; }
|
||||
.model-card:nth-child(2) { animation-delay: 0.2s; }
|
||||
.model-card:nth-child(3) { animation-delay: 0.3s; }
|
||||
.model-card:nth-child(4) { animation-delay: 0.4s; }
|
||||
.model-card:nth-child(5) { animation-delay: 0.5s; }
|
||||
.model-card:nth-child(6) { animation-delay: 0.6s; }
|
||||
|
||||
.model-card:hover {
|
||||
transform: translateY(-8px) scale(1.02);
|
||||
box-shadow:
|
||||
0 30px 60px rgba(0, 0, 0, 0.4),
|
||||
0 0 30px rgba(76, 175, 80, 0.2),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
/* Предпросмотр модели */
|
||||
.model-preview {
|
||||
position: relative;
|
||||
height: 220px;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(135deg, rgba(76, 175, 80, 0.1), rgba(76, 175, 80, 0.05));
|
||||
}
|
||||
|
||||
.preview-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: transform 0.4s ease;
|
||||
}
|
||||
|
||||
.model-card:hover .preview-image {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.preview-placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
background: linear-gradient(135deg, rgba(76, 175, 80, 0.1), rgba(76, 175, 80, 0.05));
|
||||
}
|
||||
|
||||
.preview-placeholder.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.preview-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 10px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* Контролы предпросмотра */
|
||||
.preview-controls {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.btn-upload-image {
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.btn-upload-image:hover {
|
||||
background: rgba(76, 175, 80, 0.8);
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 4px 15px rgba(76, 175, 80, 0.4);
|
||||
}
|
||||
|
||||
.btn-upload-image:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.custom-preview-badge {
|
||||
background: linear-gradient(135deg, #FFD700, #FFA500);
|
||||
color: white;
|
||||
border-radius: 50%;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
box-shadow: 0 4px 15px rgba(255, 215, 0, 0.4);
|
||||
animation: sparkle 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes sparkle {
|
||||
0%, 100% { transform: scale(1); }
|
||||
50% { transform: scale(1.1); }
|
||||
}
|
||||
|
||||
/* Информация о модели */
|
||||
.model-info {
|
||||
padding: 2rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.model-alias {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.alias-display {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.alias-display h3 {
|
||||
margin: 0;
|
||||
color: white;
|
||||
font-size: 1.4rem;
|
||||
font-weight: 600;
|
||||
flex: 1;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.btn-edit-alias {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
font-size: 16px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
opacity: 0.7;
|
||||
transition: all 0.3s ease;
|
||||
border-radius: 6px;
|
||||
color: white;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.btn-edit-alias:hover {
|
||||
opacity: 1;
|
||||
background: rgba(76, 175, 80, 0.2);
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
/* Редактирование алиаса */
|
||||
.alias-edit {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.alias-input {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid rgba(76, 175, 80, 0.5);
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
outline: none;
|
||||
transition: all 0.3s ease;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
color: white;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.alias-input:focus {
|
||||
border-color: #4CAF50;
|
||||
box-shadow: 0 0 20px rgba(76, 175, 80, 0.3);
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.alias-input::placeholder {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.alias-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.btn-save {
|
||||
background: linear-gradient(135deg, #4CAF50, #45a049);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-save:hover {
|
||||
transform: scale(1.05);
|
||||
box-shadow: 0 4px 15px rgba(76, 175, 80, 0.4);
|
||||
}
|
||||
|
||||
.btn-cancel {
|
||||
background: linear-gradient(135deg, #f44336, #d32f2f);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-cancel:hover {
|
||||
transform: scale(1.05);
|
||||
box-shadow: 0 4px 15px rgba(244, 67, 54, 0.4);
|
||||
}
|
||||
|
||||
/* Детали модели */
|
||||
.model-details {
|
||||
margin-bottom: 2rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
padding: 1.5rem;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.detail-row:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.detail-label {
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.detail-value {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
text-align: right;
|
||||
max-width: 200px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* Кнопка выбора модели */
|
||||
.btn-select {
|
||||
width: 100%;
|
||||
padding: 16px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
background: linear-gradient(135deg, #4CAF50, #45a049);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.btn-select::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
|
||||
transition: left 0.5s ease;
|
||||
}
|
||||
|
||||
.btn-select:hover::before {
|
||||
left: 100%;
|
||||
}
|
||||
|
||||
.btn-select:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(76, 175, 80, 0.4);
|
||||
}
|
||||
|
||||
/* Состояние отсутствия моделей */
|
||||
.no-models {
|
||||
text-align: center;
|
||||
padding: 4rem 2rem;
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 16px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
box-shadow:
|
||||
0 20px 40px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||
margin: 0 auto;
|
||||
max-width: 600px;
|
||||
animation: containerSlideIn 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
|
||||
}
|
||||
|
||||
.no-models-icon {
|
||||
font-size: 72px;
|
||||
margin-bottom: 2rem;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.no-models h3 {
|
||||
color: white;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.no-models p {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
margin-bottom: 1rem;
|
||||
line-height: 1.6;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
/* Контейнер ошибки */
|
||||
.error-container {
|
||||
text-align: center;
|
||||
padding: 4rem 2rem;
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 16px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(244, 67, 54, 0.3);
|
||||
box-shadow:
|
||||
0 20px 40px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||
margin: 0 auto;
|
||||
max-width: 600px;
|
||||
animation: containerSlideIn 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
|
||||
}
|
||||
|
||||
.error-container h2 {
|
||||
color: #ff6b6b;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
.error-container p {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
margin-bottom: 2rem;
|
||||
line-height: 1.6;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Анимации */
|
||||
@keyframes containerSlideIn {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(50px) scale(0.9);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes headerFadeIn {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-30px);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes gridFadeIn {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(40px);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes cardSlideUp {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(60px) scale(0.8);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Адаптивность */
|
||||
@media (max-width: 768px) {
|
||||
.model-selection-page {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.model-selection-header {
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 2rem;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
order: 2;
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
order: 1;
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.model-selection-title {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.model-selection-subtitle {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.models-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.model-card {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.model-info {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.detail-value {
|
||||
max-width: 150px;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.no-models, .error-container {
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.model-selection-header {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.model-selection-title {
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.model-selection-subtitle {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
@ -34,6 +34,41 @@
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
.model-info-header {
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.current-model-info {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.current-model-info h3 {
|
||||
margin: 0 0 5px 0;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.model-filename {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: 12px;
|
||||
font-family: monospace;
|
||||
word-break: break-all;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.control-buttons {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
@ -45,21 +80,37 @@
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: background-color 0.2s ease;
|
||||
transition: all 0.2s ease;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: white;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.potree-button:hover {
|
||||
opacity: 0.9;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.potree-button.primary {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
background: linear-gradient(45deg, #007bff, #0056b3);
|
||||
border-color: #007bff;
|
||||
}
|
||||
|
||||
.potree-button.primary:hover {
|
||||
background: linear-gradient(45deg, #0056b3, #004085);
|
||||
box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
|
||||
}
|
||||
|
||||
.potree-button.danger {
|
||||
background-color: #dc3545;
|
||||
color: white;
|
||||
background: linear-gradient(45deg, #dc3545, #c82333);
|
||||
border-color: #dc3545;
|
||||
}
|
||||
|
||||
.potree-button.danger:hover {
|
||||
background: linear-gradient(45deg, #c82333, #a71e2a);
|
||||
box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
|
||||
}
|
||||
|
||||
.potree-loading {
|
||||
@ -113,9 +164,18 @@
|
||||
}
|
||||
|
||||
.potree-error p {
|
||||
margin: 0;
|
||||
margin: 0 0 20px 0;
|
||||
font-size: 16px;
|
||||
opacity: 0.9;
|
||||
max-width: 600px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* Стили для сайдбара */
|
||||
@ -148,7 +208,25 @@
|
||||
.potree-controls {
|
||||
top: 5px;
|
||||
right: 5px;
|
||||
gap: 5px;
|
||||
gap: 10px;
|
||||
max-width: 250px;
|
||||
}
|
||||
|
||||
.model-info-header {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.current-model-info h3 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.model-filename {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.control-buttons {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.potree-button {
|
||||
@ -170,6 +248,11 @@
|
||||
height: 35px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
/* Отдельная кнопка для управления сайдбаром */
|
||||
@ -198,45 +281,34 @@
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
padding: 0;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
visibility: visible !important;
|
||||
opacity: 1 !important;
|
||||
}
|
||||
|
||||
.potree-sidebar-toggle .potree-button:hover {
|
||||
transform: scale(1.1);
|
||||
transition: transform 0.2s ease;
|
||||
transform: translateY(-1px) scale(1.05);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
/* Скрываем ненужные элементы Potree */
|
||||
/* Скрываем встроенные кнопки управления Potree */
|
||||
#potree_menu_toggle,
|
||||
.potree_menu_toggle,
|
||||
#menu_toggle,
|
||||
.menu_toggle,
|
||||
#sidebar_toggle_button,
|
||||
.sidebar_toggle_button,
|
||||
#potree_sidebar_toggle_button,
|
||||
.potree_sidebar_toggle_button {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Скрываем встроенную кнопку-бургер */
|
||||
.potree-menu-button,
|
||||
.potree-sidebar-button {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
|
||||
/* Скрываем встроенные кнопки с определенными классами, но НЕ нашу */
|
||||
.sidebar-toggle:not(.potree-sidebar-toggle),
|
||||
.menu-button:not(.potree-sidebar-toggle) {
|
||||
.menu-toggle:not(.potree-sidebar-toggle) {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
|
||||
/* Скрываем кнопки по атрибутам, исключая наш контейнер */
|
||||
[class*="menu-toggle"]:not(.potree-sidebar-toggle),
|
||||
[class*="sidebar-toggle"]:not(.potree-sidebar-toggle),
|
||||
[id*="menu-toggle"],
|
||||
[id*="sidebar-toggle"] {
|
||||
[id*="menu-toggle"]:not(.potree-sidebar-toggle) {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
@ -56,8 +56,8 @@ export default function Login() {
|
||||
}
|
||||
|
||||
if (response.ok && data.success) {
|
||||
// Успешная авторизация, переходим на React маршрут /viewer
|
||||
navigate('/viewer');
|
||||
// Успешная авторизация, переходим на React маршрут /models для выбора модели
|
||||
navigate('/models');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
415
src/pages/ModelSelection.tsx
Normal file
415
src/pages/ModelSelection.tsx
Normal file
@ -0,0 +1,415 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import LoadingScreen from '../components/LoadingScreen';
|
||||
import '../components/ModelSelection.css';
|
||||
|
||||
interface ModelInfo {
|
||||
id: string;
|
||||
filename: string;
|
||||
alias: string;
|
||||
previewImage?: string;
|
||||
hasCustomPreview?: boolean;
|
||||
size?: number;
|
||||
lastModified?: string;
|
||||
imageTimestamp?: number;
|
||||
}
|
||||
|
||||
const ModelSelection: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const [models, setModels] = useState<ModelInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editingAlias, setEditingAlias] = useState<string | null>(null);
|
||||
const [editAliasValue, setEditAliasValue] = useState('');
|
||||
const [loadingMessage, setLoadingMessage] = useState('Загружаем модели...');
|
||||
const [showLoadingScreen, setShowLoadingScreen] = useState(true);
|
||||
const [uploadingImage, setUploadingImage] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const loadModels = async () => {
|
||||
try {
|
||||
setLoadingMessage('Ищем доступные модели...');
|
||||
const response = await fetch('/api/models');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
// Добавляем timestamp для каждой модели чтобы сбросить кэш
|
||||
const modelsWithTimestamp = data.models.map((model: ModelInfo) => ({
|
||||
...model,
|
||||
imageTimestamp: Date.now()
|
||||
}));
|
||||
setModels(modelsWithTimestamp);
|
||||
console.log('Загружены модели:', modelsWithTimestamp);
|
||||
console.log('Путь к моделям:', data.modelsPath);
|
||||
} else {
|
||||
setError(data.error || 'Не удалось загрузить модели');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка при загрузке моделей:', err);
|
||||
setError('Ошибка соединения с сервером');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setTimeout(() => {
|
||||
setShowLoadingScreen(false);
|
||||
}, 500);
|
||||
}
|
||||
};
|
||||
|
||||
loadModels();
|
||||
}, []);
|
||||
|
||||
const handleAliasEdit = (modelId: string, currentAlias: string) => {
|
||||
setEditingAlias(modelId);
|
||||
setEditAliasValue(currentAlias);
|
||||
};
|
||||
|
||||
const saveAlias = async (modelId: string) => {
|
||||
if (!editAliasValue.trim()) {
|
||||
alert('Алиас не может быть пустым');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/models/${encodeURIComponent(modelId)}/alias`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ alias: editAliasValue.trim() }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setModels(prevModels =>
|
||||
prevModels.map(model =>
|
||||
model.id === modelId
|
||||
? { ...model, alias: editAliasValue.trim() }
|
||||
: model
|
||||
)
|
||||
);
|
||||
setEditingAlias(null);
|
||||
setEditAliasValue('');
|
||||
} else {
|
||||
alert(data.error || 'Не удалось сохранить алиас');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка при сохранении алиаса:', err);
|
||||
alert('Ошибка соединения с сервером');
|
||||
}
|
||||
};
|
||||
|
||||
const cancelAliasEdit = () => {
|
||||
setEditingAlias(null);
|
||||
setEditAliasValue('');
|
||||
};
|
||||
|
||||
const uploadPreviewImage = async (modelId: string, file: File) => {
|
||||
if (!file) return;
|
||||
|
||||
// Проверяем тип файла на клиенте
|
||||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/svg+xml'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
alert('Неподдерживаемый тип файла. Разрешены: JPG, PNG, WebP, SVG');
|
||||
return;
|
||||
}
|
||||
|
||||
// Проверяем размер файла (максимум 10MB)
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
alert('Файл слишком большой. Максимальный размер: 10MB');
|
||||
return;
|
||||
}
|
||||
|
||||
setUploadingImage(modelId);
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('image', file);
|
||||
|
||||
const response = await fetch(`/api/models/${encodeURIComponent(modelId)}/upload-preview`, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
// Обновляем модель в списке
|
||||
setModels(prevModels =>
|
||||
prevModels.map(model =>
|
||||
model.id === modelId
|
||||
? {
|
||||
...model,
|
||||
previewImage: data.model.previewImage,
|
||||
hasCustomPreview: data.model.hasCustomPreview,
|
||||
imageTimestamp: Date.now()
|
||||
}
|
||||
: model
|
||||
)
|
||||
);
|
||||
|
||||
// Принудительно обновляем изображение в DOM
|
||||
const imgElement = document.querySelector(`img[data-model-id="${modelId}"]`) as HTMLImageElement;
|
||||
if (imgElement) {
|
||||
const newSrc = `/api/models/${encodeURIComponent(modelId)}/preview?t=${Date.now()}`;
|
||||
imgElement.src = newSrc;
|
||||
}
|
||||
|
||||
console.log('Изображение успешно загружено:', data.message);
|
||||
} else {
|
||||
alert(data.error || 'Не удалось загрузить изображение');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка при загрузке изображения:', err);
|
||||
alert('Ошибка соединения с сервером');
|
||||
} finally {
|
||||
setUploadingImage(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImageUpload = (modelId: string) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/jpg,image/png,image/webp,image/svg+xml';
|
||||
input.onchange = (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (file) {
|
||||
uploadPreviewImage(modelId, file);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
const selectModel = (model: ModelInfo) => {
|
||||
// Переходим к просмотру модели с передачей параметров через state
|
||||
navigate('/viewer', {
|
||||
state: {
|
||||
selectedModel: model,
|
||||
modelUrl: `/models/${encodeURIComponent(model.filename)}`
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await fetch('/api/logout', { method: 'POST' });
|
||||
navigate('/login');
|
||||
} catch (err) {
|
||||
console.error('Ошибка при выходе:', err);
|
||||
navigate('/login');
|
||||
}
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes?: number): string => {
|
||||
if (!bytes) return 'Неизвестно';
|
||||
|
||||
const units = ['Б', 'КБ', 'МБ', 'ГБ'];
|
||||
let size = bytes;
|
||||
let unitIndex = 0;
|
||||
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
return `${size.toFixed(1)} ${units[unitIndex]}`;
|
||||
};
|
||||
|
||||
const formatDate = (dateString?: string): string => {
|
||||
if (!dateString) return 'Неизвестно';
|
||||
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('ru-RU', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
if (showLoadingScreen) {
|
||||
return (
|
||||
<LoadingScreen
|
||||
isLoading={loading}
|
||||
loadingMessage={loadingMessage}
|
||||
onLoadingComplete={() => setShowLoadingScreen(false)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="model-selection-page">
|
||||
<div className="model-selection-container">
|
||||
<div className="error-container">
|
||||
<h2>⚠️ Ошибка загрузки</h2>
|
||||
<p>{error}</p>
|
||||
<div className="error-actions">
|
||||
<button onClick={() => window.location.reload()} className="model-btn model-btn-primary">
|
||||
🔄 Перезагрузить страницу
|
||||
</button>
|
||||
<button onClick={handleLogout} className="model-btn model-btn-danger">
|
||||
🚪 Выйти
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="model-selection-page">
|
||||
<div className="model-selection-container">
|
||||
<header className="model-selection-header">
|
||||
<div className="header-content">
|
||||
<h1 className="model-selection-title">Выбор модели для просмотра</h1>
|
||||
<p className="model-selection-subtitle">Выберите 3D модель облака точек для просмотра в Кварце</p>
|
||||
</div>
|
||||
<button onClick={handleLogout} className="logout-btn" title="Выйти из системы">
|
||||
🚪
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{models.length === 0 ? (
|
||||
<div className="no-models">
|
||||
<div className="no-models-icon">📦</div>
|
||||
<h3>Модели не найдены</h3>
|
||||
<p>В папке моделей пока нет доступных файлов.</p>
|
||||
<p>Поддерживаемые форматы: .laz, .las, .ply, .copc.laz</p>
|
||||
<button onClick={() => window.location.reload()} className="model-btn model-btn-primary">
|
||||
🔄 Перезагрузить страницу
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="models-grid">
|
||||
{models.map((model) => (
|
||||
<div key={model.id} className="model-card">
|
||||
<div className="model-preview">
|
||||
{model.previewImage ? (
|
||||
<img
|
||||
src={`/api/models/${encodeURIComponent(model.id)}/preview${model.imageTimestamp ? `?t=${model.imageTimestamp}` : ''}`}
|
||||
alt={model.alias}
|
||||
className="preview-image"
|
||||
data-model-id={model.id}
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
target.nextElementSibling?.classList.remove('hidden');
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<div className={`preview-placeholder ${model.previewImage ? 'hidden' : ''}`}>
|
||||
<div className="preview-icon">🎯</div>
|
||||
<span>Нет предпросмотра</span>
|
||||
</div>
|
||||
|
||||
{/* Кнопка загрузки изображения */}
|
||||
<div className="preview-controls">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleImageUpload(model.id);
|
||||
}}
|
||||
className="btn-upload-image"
|
||||
title="Загрузить свое изображение"
|
||||
disabled={uploadingImage === model.id}
|
||||
>
|
||||
{uploadingImage === model.id ? '⏳' : '📷'}
|
||||
</button>
|
||||
{model.hasCustomPreview && (
|
||||
<div className="custom-preview-badge" title="Пользовательское изображение">
|
||||
⭐
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="model-info">
|
||||
<div className="model-alias">
|
||||
{editingAlias === model.id ? (
|
||||
<div className="alias-edit">
|
||||
<input
|
||||
type="text"
|
||||
value={editAliasValue}
|
||||
onChange={(e) => setEditAliasValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
saveAlias(model.id);
|
||||
} else if (e.key === 'Escape') {
|
||||
cancelAliasEdit();
|
||||
}
|
||||
}}
|
||||
className="alias-input"
|
||||
placeholder="Введите название модели"
|
||||
autoFocus
|
||||
/>
|
||||
<div className="alias-actions">
|
||||
<button
|
||||
onClick={() => saveAlias(model.id)}
|
||||
className="btn-save"
|
||||
title="Сохранить"
|
||||
>
|
||||
✓
|
||||
</button>
|
||||
<button
|
||||
onClick={cancelAliasEdit}
|
||||
className="btn-cancel"
|
||||
title="Отменить"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="alias-display">
|
||||
<h3>{model.alias}</h3>
|
||||
<button
|
||||
onClick={() => handleAliasEdit(model.id, model.alias)}
|
||||
className="btn-edit-alias"
|
||||
title="Редактировать название"
|
||||
>
|
||||
✏️
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="model-details">
|
||||
<div className="detail-row">
|
||||
<span className="detail-label">Файл:</span>
|
||||
<span className="detail-value" title={model.filename}>
|
||||
{model.filename.length > 30
|
||||
? `${model.filename.substring(0, 27)}...`
|
||||
: model.filename
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
<div className="detail-row">
|
||||
<span className="detail-label">Размер:</span>
|
||||
<span className="detail-value">{formatFileSize(model.size)}</span>
|
||||
</div>
|
||||
<div className="detail-row">
|
||||
<span className="detail-label">Изменен:</span>
|
||||
<span className="detail-value">{formatDate(model.lastModified)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => selectModel(model)}
|
||||
className="btn-select"
|
||||
>
|
||||
⚡ Выбрать модель
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModelSelection;
|
||||
@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import PotreeSidebar from '../components/PotreeSidebar';
|
||||
import NavigationPanel from '../components/NavigationPanel';
|
||||
import LoadingScreen from '../components/LoadingScreen';
|
||||
@ -8,14 +8,32 @@ import '../components/PotreeViewer.css';
|
||||
// Простое объявление типов для избежания конфликтов
|
||||
declare const window: any;
|
||||
|
||||
interface ModelInfo {
|
||||
id: string;
|
||||
filename: string;
|
||||
alias: string;
|
||||
previewImage?: string;
|
||||
size?: number;
|
||||
lastModified?: string;
|
||||
}
|
||||
|
||||
interface LocationState {
|
||||
selectedModel?: ModelInfo;
|
||||
modelUrl?: string;
|
||||
}
|
||||
|
||||
const PotreeViewer: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const renderAreaRef = useRef<HTMLDivElement>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [loadingMessage, setLoadingMessage] = useState('Подготовка к волшебству...');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [viewer, setViewer] = useState<any>(null);
|
||||
const [showLoadingScreen, setShowLoadingScreen] = useState(true);
|
||||
|
||||
// Получаем выбранную модель из состояния навигации
|
||||
const { selectedModel, modelUrl } = (location.state as LocationState) || {};
|
||||
|
||||
// Обработчик завершения загрузки
|
||||
const handleLoadingComplete = () => {
|
||||
@ -82,11 +100,20 @@ const PotreeViewer: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
console.log('PotreeViewer useEffect started');
|
||||
console.log('Selected model:', selectedModel);
|
||||
console.log('Model URL:', modelUrl);
|
||||
|
||||
// Если нет выбранной модели, возвращаемся к выбору моделей
|
||||
if (!selectedModel || !modelUrl) {
|
||||
console.log('No model selected, redirecting to model selection');
|
||||
navigate('/models');
|
||||
return;
|
||||
}
|
||||
|
||||
const loadPotreeScripts = async () => {
|
||||
try {
|
||||
console.log('loadPotreeScripts started');
|
||||
setLoadingMessage('Подготовка к волшебству...');
|
||||
setLoadingMessage(`Подготовка модели "${selectedModel.alias}"...`);
|
||||
|
||||
// Ждем, пока компонент полностью отрендерится
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
@ -164,7 +191,7 @@ const PotreeViewer: React.FC = () => {
|
||||
throw new Error('jQuery not loaded');
|
||||
}
|
||||
|
||||
setLoadingMessage('Запускаем квантовый двигатель...');
|
||||
setLoadingMessage(`Запускаем квантовый двигатель для "${selectedModel.alias}"...`);
|
||||
|
||||
// Ждем немного перед инициализацией и еще раз проверяем render area
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
@ -178,7 +205,8 @@ const PotreeViewer: React.FC = () => {
|
||||
await initializePotree();
|
||||
} catch (err) {
|
||||
console.error('Error loading Potree:', err);
|
||||
setError(`Что-то пошло не так: ${err.message}`);
|
||||
const errorMessage = err instanceof Error ? err.message : String(err);
|
||||
setError(`Что-то пошло не так: ${errorMessage}`);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
@ -278,7 +306,7 @@ const PotreeViewer: React.FC = () => {
|
||||
}
|
||||
|
||||
console.log('Creating Potree viewer...');
|
||||
setLoadingMessage('Строим виртуальную реальность...');
|
||||
setLoadingMessage(`Строим виртуальную реальность для "${selectedModel.alias}"...`);
|
||||
|
||||
// Проверяем поддержку WebGL
|
||||
const canvas = document.createElement('canvas');
|
||||
@ -313,7 +341,7 @@ const PotreeViewer: React.FC = () => {
|
||||
window.viewer.setFOV(60);
|
||||
window.viewer.setPointBudget(1_000_000);
|
||||
window.viewer.setBackground("skybox");
|
||||
window.viewer.setDescription("DefaultRecapScene");
|
||||
window.viewer.setDescription(`${selectedModel.alias} - ${selectedModel.filename}`);
|
||||
|
||||
// Принудительно обновляем размеры
|
||||
console.log('Updating viewer size...');
|
||||
@ -339,7 +367,7 @@ const PotreeViewer: React.FC = () => {
|
||||
}
|
||||
|
||||
console.log('Viewer configured successfully');
|
||||
setLoadingMessage('Полируем кнопочки...');
|
||||
setLoadingMessage(`Полируем кнопочки для "${selectedModel.alias}"...`);
|
||||
|
||||
// Добавляем обработчик изменения размера окна
|
||||
const handleResize = () => {
|
||||
@ -364,28 +392,9 @@ const PotreeViewer: React.FC = () => {
|
||||
// Сохраняем функцию для cleanup
|
||||
(window.viewer as any).handleResize = handleResize;
|
||||
|
||||
// Добавляем тестовую геометрию для проверки рендеринга
|
||||
console.log('Adding test geometry...');
|
||||
try {
|
||||
// Three.js доступен через window.THREE или через Potree
|
||||
const THREE = window.THREE || window.Potree.THREE;
|
||||
if (THREE) {
|
||||
const geometry = new THREE.BoxGeometry(10, 10, 10);
|
||||
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true });
|
||||
const cube = new THREE.Mesh(geometry, material);
|
||||
cube.position.set(0, 0, 0);
|
||||
window.viewer.scene.scene.add(cube);
|
||||
console.log('Test cube added to scene');
|
||||
} else {
|
||||
console.warn('THREE.js not available');
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Could not add test geometry:', err);
|
||||
}
|
||||
|
||||
// Загружаем GUI
|
||||
console.log('Loading GUI...');
|
||||
setLoadingMessage('Настраиваем магию...');
|
||||
setLoadingMessage(`Настраиваем магию для "${selectedModel.alias}"...`);
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@ -455,121 +464,115 @@ const PotreeViewer: React.FC = () => {
|
||||
console.warn('GUI loading error:', err);
|
||||
}
|
||||
|
||||
// Загружаем облако точек
|
||||
console.log('Loading point cloud...');
|
||||
setLoadingMessage('Материализуем точки...');
|
||||
|
||||
const pointCloudOptions = [
|
||||
{ url: "/pointclouds/lion_takanawa.copc.laz", name: "lion_takanawa" },
|
||||
{ url: "/pointclouds/tret.las_converted/metadata.json", name: "sigeom.sa" }
|
||||
];
|
||||
// Загружаем выбранную модель
|
||||
console.log('Loading selected point cloud...');
|
||||
setLoadingMessage(`Материализуем модель "${selectedModel.alias}"...`);
|
||||
|
||||
let pointCloudLoaded = false;
|
||||
|
||||
for (const option of pointCloudOptions) {
|
||||
if (pointCloudLoaded) break;
|
||||
try {
|
||||
console.log(`Loading point cloud from: ${modelUrl}`);
|
||||
console.log('Model details:', selectedModel);
|
||||
|
||||
try {
|
||||
console.log(`Trying to load point cloud: ${option.url}`);
|
||||
setLoadingMessage('Материализуем точки...');
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error(`Point cloud loading timeout for ${option.url}`));
|
||||
}, 10000);
|
||||
// Проверим, доступен ли файл через HTTP запрос
|
||||
console.log('Checking if model file is accessible...');
|
||||
const testResponse = await fetch(modelUrl);
|
||||
console.log('Model file response status:', testResponse.status);
|
||||
|
||||
// Собираем заголовки в объект
|
||||
const responseHeaders: Record<string, string> = {};
|
||||
testResponse.headers.forEach((value, key) => {
|
||||
responseHeaders[key] = value;
|
||||
});
|
||||
console.log('Model file response headers:', responseHeaders);
|
||||
|
||||
if (!testResponse.ok) {
|
||||
throw new Error(`Model file not accessible: ${testResponse.status} ${testResponse.statusText}`);
|
||||
}
|
||||
|
||||
// Определяем тип загрузчика по расширению файла
|
||||
const fileExtension = selectedModel.filename.toLowerCase();
|
||||
let useCopcLoader = false;
|
||||
|
||||
console.log('File extension analysis:', {
|
||||
filename: selectedModel.filename,
|
||||
extension: fileExtension,
|
||||
endsWithCopc: fileExtension.endsWith('.copc.laz'),
|
||||
endsWithLaz: fileExtension.endsWith('.laz'),
|
||||
modelUrl: modelUrl
|
||||
});
|
||||
|
||||
if (fileExtension.endsWith('.copc.laz')) {
|
||||
useCopcLoader = true;
|
||||
console.log('Using COPC loader for .copc.laz file');
|
||||
} else {
|
||||
console.log('Using standard LAZ loader for .laz/.las file');
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error(`Point cloud loading timeout for ${selectedModel.filename}`));
|
||||
}, 15000); // Увеличил таймаут до 15 секунд
|
||||
|
||||
window.Potree.loadPointCloud(option.url, option.name, (e: any) => {
|
||||
clearTimeout(timeout);
|
||||
|
||||
console.log('Point cloud callback received:', e);
|
||||
|
||||
try {
|
||||
if (e.type === 'loading_failed') {
|
||||
console.error('Point cloud loading failed:', e);
|
||||
reject(new Error(`Loading failed: ${e.message || 'Unknown error'}`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.pointcloud) {
|
||||
console.log('Point cloud loaded, adding to scene...');
|
||||
console.log('Point cloud details:', {
|
||||
numPoints: e.pointcloud.numPoints,
|
||||
boundingBox: e.pointcloud.boundingBox,
|
||||
material: e.pointcloud.material
|
||||
});
|
||||
|
||||
const scene = window.viewer.scene;
|
||||
const pointcloud = e.pointcloud;
|
||||
|
||||
const material = pointcloud.material;
|
||||
material.size = 1;
|
||||
material.pointSizeType = window.Potree.PointSizeType.ADAPTIVE;
|
||||
material.shape = window.Potree.PointShape.SQUARE;
|
||||
|
||||
scene.addPointCloud(pointcloud);
|
||||
|
||||
console.log('Point cloud added to scene, fitting to screen...');
|
||||
// Подгоняем камеру к облаку точек
|
||||
window.viewer.fitToScreen();
|
||||
|
||||
console.log(`Point cloud loaded successfully: ${option.url}`);
|
||||
pointCloudLoaded = true;
|
||||
resolve();
|
||||
} else {
|
||||
console.error('No pointcloud in response:', e);
|
||||
reject(new Error('No pointcloud in response'));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error processing point cloud:', err);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
console.log('Calling Potree.loadPointCloud with:', {
|
||||
url: modelUrl,
|
||||
name: selectedModel.alias
|
||||
});
|
||||
break;
|
||||
} catch (err) {
|
||||
console.warn(`Failed to load ${option.url}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!pointCloudLoaded) {
|
||||
console.warn('No point cloud could be loaded, creating test point cloud...');
|
||||
setLoadingMessage('Рисуем из воздуха...');
|
||||
|
||||
try {
|
||||
// Создаем простое тестовое облако точек
|
||||
const THREE = window.THREE || window.Potree.THREE;
|
||||
if (THREE) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
const positions: number[] = [];
|
||||
const colors: number[] = [];
|
||||
window.Potree.loadPointCloud(modelUrl, selectedModel.alias, (e: any) => {
|
||||
clearTimeout(timeout);
|
||||
|
||||
// Создаем 1000 случайных точек
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
positions.push(
|
||||
(Math.random() - 0.5) * 100,
|
||||
(Math.random() - 0.5) * 100,
|
||||
(Math.random() - 0.5) * 100
|
||||
);
|
||||
colors.push(Math.random(), Math.random(), Math.random());
|
||||
console.log('Point cloud callback received:', e);
|
||||
|
||||
try {
|
||||
if (e.type === 'loading_failed') {
|
||||
console.error('Point cloud loading failed:', e);
|
||||
reject(new Error(`Loading failed: ${e.message || 'Unknown error'}`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.pointcloud) {
|
||||
console.log('Point cloud loaded, adding to scene...');
|
||||
console.log('Point cloud details:', {
|
||||
numPoints: e.pointcloud.numPoints,
|
||||
boundingBox: e.pointcloud.boundingBox,
|
||||
material: e.pointcloud.material
|
||||
});
|
||||
|
||||
const scene = window.viewer.scene;
|
||||
const pointcloud = e.pointcloud;
|
||||
|
||||
const material = pointcloud.material;
|
||||
material.size = 1;
|
||||
material.pointSizeType = window.Potree.PointSizeType.ADAPTIVE;
|
||||
material.shape = window.Potree.PointShape.SQUARE;
|
||||
|
||||
scene.addPointCloud(pointcloud);
|
||||
|
||||
console.log('Point cloud added to scene, fitting to screen...');
|
||||
// Подгоняем камеру к облаку точек
|
||||
window.viewer.fitToScreen();
|
||||
|
||||
console.log(`Point cloud loaded successfully: ${selectedModel.filename}`);
|
||||
pointCloudLoaded = true;
|
||||
resolve();
|
||||
} else {
|
||||
console.error('No pointcloud in response:', e);
|
||||
reject(new Error('No pointcloud in response'));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error processing point cloud:', err);
|
||||
reject(err);
|
||||
}
|
||||
|
||||
geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
|
||||
geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
|
||||
|
||||
const material = new THREE.PointsMaterial({
|
||||
size: 2,
|
||||
vertexColors: true
|
||||
});
|
||||
|
||||
const points = new THREE.Points(geometry, material);
|
||||
window.viewer.scene.scene.add(points);
|
||||
|
||||
console.log('Test point cloud created with 1000 points');
|
||||
pointCloudLoaded = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Could not create test point cloud:', err);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`Failed to load ${selectedModel.filename}:`, err);
|
||||
// Вместо создания тестового облака, показываем ошибку
|
||||
const errorMessage = err instanceof Error ? err.message : String(err);
|
||||
setError(`Не удалось загрузить модель "${selectedModel.alias}": ${errorMessage}. Возможно, файл нужно сконвертировать в формат Potree.`);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
@ -594,7 +597,8 @@ const PotreeViewer: React.FC = () => {
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error initializing Potree:', err);
|
||||
setError(`Ошибка инициализации Potree: ${err.message}`);
|
||||
const errorMessage = err instanceof Error ? err.message : String(err);
|
||||
setError(`Ошибка инициализации Potree: ${errorMessage}`);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
@ -621,9 +625,9 @@ const PotreeViewer: React.FC = () => {
|
||||
window.viewer = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
}, [selectedModel, modelUrl, navigate]);
|
||||
|
||||
const handleLogout = () => {
|
||||
const handleBackToModels = () => {
|
||||
// Очищаем viewer перед переходом
|
||||
if (window.viewer) {
|
||||
try {
|
||||
@ -633,6 +637,25 @@ const PotreeViewer: React.FC = () => {
|
||||
}
|
||||
window.viewer = null;
|
||||
}
|
||||
navigate('/models');
|
||||
};
|
||||
|
||||
const handleLogout = async () => {
|
||||
// Очищаем viewer перед переходом
|
||||
if (window.viewer) {
|
||||
try {
|
||||
window.viewer.destroy?.();
|
||||
} catch (e) {
|
||||
console.warn('Error destroying viewer:', e);
|
||||
}
|
||||
window.viewer = null;
|
||||
}
|
||||
|
||||
try {
|
||||
await fetch('/api/logout', { method: 'POST' });
|
||||
} catch (err) {
|
||||
console.error('Ошибка при выходе:', err);
|
||||
}
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
@ -641,9 +664,14 @@ const PotreeViewer: React.FC = () => {
|
||||
<div className="potree-error">
|
||||
<h2>Ошибка загрузки</h2>
|
||||
<p>{error}</p>
|
||||
<button onClick={handleLogout} className="potree-button danger">
|
||||
Вернуться к входу
|
||||
</button>
|
||||
<div className="error-actions">
|
||||
<button onClick={handleBackToModels} className="potree-button">
|
||||
Выбрать другую модель
|
||||
</button>
|
||||
<button onClick={handleLogout} className="potree-button danger">
|
||||
Вернуться к входу
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -661,12 +689,28 @@ const PotreeViewer: React.FC = () => {
|
||||
|
||||
{/* Панель управления */}
|
||||
<div className="potree-controls">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="potree-button danger"
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
<div className="model-info-header">
|
||||
{selectedModel && (
|
||||
<div className="current-model-info">
|
||||
<h3>{selectedModel.alias}</h3>
|
||||
<span className="model-filename">{selectedModel.filename}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="control-buttons">
|
||||
<button
|
||||
onClick={handleBackToModels}
|
||||
className="potree-button"
|
||||
>
|
||||
Выбрать модель
|
||||
</button>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="potree-button danger"
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Панель настроек */}
|
||||
|
||||
188
src/viteApi.ts
188
src/viteApi.ts
@ -4,14 +4,14 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Обработка тела запроса
|
||||
async function getRequestBody(req: any): Promise<string> {
|
||||
async function getRequestBody(req: any): Promise<Buffer> {
|
||||
return new Promise((resolve) => {
|
||||
let body = '';
|
||||
const chunks: Buffer[] = [];
|
||||
req.on('data', (chunk: Buffer) => {
|
||||
body += chunk.toString();
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on('end', () => {
|
||||
resolve(body);
|
||||
resolve(Buffer.concat(chunks));
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -36,26 +36,74 @@ function getMimeType(filename: string): string {
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.eot': 'application/vnd.ms-fontobject',
|
||||
'.txt': 'text/plain; charset=utf-8'
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.laz': 'application/octet-stream',
|
||||
'.las': 'application/octet-stream',
|
||||
'.ply': 'application/octet-stream'
|
||||
};
|
||||
|
||||
return mimeTypes[ext] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
// Создаем функцию для отправки статического файла
|
||||
async function serveStaticFile(filePath: string): Promise<Response | null> {
|
||||
// Создаем функцию для отправки статического файла с поддержкой Range запросов
|
||||
async function serveStaticFile(filePath: string, req?: any): Promise<Response | null> {
|
||||
try {
|
||||
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
||||
const content = await fs.promises.readFile(filePath);
|
||||
const stats = fs.statSync(filePath);
|
||||
const mimeType = getMimeType(filePath);
|
||||
|
||||
return new Response(content, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': mimeType,
|
||||
'Cache-Control': 'public, max-age=3600'
|
||||
// Проверяем, есть ли Range заголовок для partial content
|
||||
const range = req?.headers?.range;
|
||||
|
||||
if (range && range.startsWith('bytes=')) {
|
||||
// Обрабатываем Range запрос для поддержки COPC
|
||||
const parts = range.replace('bytes=', '').split('-');
|
||||
const start = parseInt(parts[0], 10);
|
||||
const end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1;
|
||||
|
||||
if (start >= stats.size || end >= stats.size) {
|
||||
return new Response('Range not satisfiable', {
|
||||
status: 416,
|
||||
headers: {
|
||||
'Content-Range': `bytes */${stats.size}`
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const chunkSize = (end - start) + 1;
|
||||
const stream = fs.createReadStream(filePath, { start, end });
|
||||
|
||||
// Читаем данные из стрима
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const content = Buffer.concat(chunks);
|
||||
|
||||
return new Response(content, {
|
||||
status: 206, // Partial Content
|
||||
headers: {
|
||||
'Content-Type': mimeType,
|
||||
'Content-Length': chunkSize.toString(),
|
||||
'Content-Range': `bytes ${start}-${end}/${stats.size}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': 'public, max-age=3600'
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Обычный запрос - возвращаем весь файл
|
||||
const content = await fs.promises.readFile(filePath);
|
||||
|
||||
return new Response(content, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': mimeType,
|
||||
'Content-Length': stats.size.toString(),
|
||||
'Accept-Ranges': 'bytes', // Указываем поддержку Range запросов
|
||||
'Cache-Control': 'public, max-age=3600'
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при чтении файла ${filePath}:`, error);
|
||||
@ -140,7 +188,7 @@ export function viteApiPlugin(): Plugin {
|
||||
const publicPath = path.join(process.cwd(), 'public', pathname);
|
||||
console.log(`Обработка запроса к: ${publicPath}`);
|
||||
|
||||
const response = await serveStaticFile(publicPath);
|
||||
const response = await serveStaticFile(publicPath, req);
|
||||
if (response) {
|
||||
res.statusCode = response.status;
|
||||
response.headers.forEach((value, key) => {
|
||||
@ -152,11 +200,106 @@ export function viteApiPlugin(): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
// Обработка запросов к /pointclouds для тестирования
|
||||
if (pathname.startsWith('/pointclouds/')) {
|
||||
const publicPath = path.join(process.cwd(), 'public', pathname);
|
||||
console.log(`Обработка запроса к pointclouds: ${publicPath}`);
|
||||
|
||||
// Проверяем авторизацию
|
||||
if (!checkAuthCookie(req)) {
|
||||
console.log('Доступ к pointclouds запрещен: отсутствует авторизация');
|
||||
res.statusCode = 403;
|
||||
res.end('Access denied');
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await serveStaticFile(publicPath, req);
|
||||
if (response) {
|
||||
res.statusCode = response.status;
|
||||
response.headers.forEach((value, key) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
const body = await response.arrayBuffer();
|
||||
res.end(Buffer.from(body));
|
||||
return;
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
res.end('File not found');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Обработка запросов к изображениям предпросмотра /image-preview/
|
||||
if (pathname.startsWith('/image-preview/')) {
|
||||
const IMAGES_DIR = process.env.IMAGES_PATH || path.join(process.cwd(), '..', 'image_model_preview');
|
||||
const imageFileName = pathname.replace('/image-preview/', '');
|
||||
const imagePath = path.join(IMAGES_DIR, imageFileName);
|
||||
|
||||
console.log(`Запрос к изображению предпросмотра: ${pathname} -> ${imagePath}`);
|
||||
|
||||
// Проверяем авторизацию
|
||||
if (!checkAuthCookie(req)) {
|
||||
console.log('Доступ запрещен: отсутствует авторизация');
|
||||
res.statusCode = 403;
|
||||
res.end('Access denied');
|
||||
return;
|
||||
}
|
||||
|
||||
// Простая раздача файла изображения
|
||||
const response = await serveStaticFile(imagePath, req);
|
||||
if (response) {
|
||||
res.statusCode = response.status;
|
||||
response.headers.forEach((value, key) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
const body = await response.arrayBuffer();
|
||||
res.end(Buffer.from(body));
|
||||
return;
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
res.end('Image not found');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Обработка запросов к моделям через статический путь /models/
|
||||
if (pathname.startsWith('/models/')) {
|
||||
const MODELS_DIR = process.env.MODELS_PATH || path.join(process.cwd(), '..', 'models');
|
||||
const modelFileName = pathname.replace('/models/', '');
|
||||
const modelPath = path.join(MODELS_DIR, modelFileName);
|
||||
|
||||
console.log(`Запрос к модели: ${pathname} -> ${modelPath}`);
|
||||
|
||||
// Проверяем авторизацию
|
||||
if (!checkAuthCookie(req)) {
|
||||
console.log('Доступ запрещен: отсутствует авторизация');
|
||||
res.statusCode = 403;
|
||||
res.end('Access denied');
|
||||
return;
|
||||
}
|
||||
|
||||
// Простая раздача файла - как для pointclouds
|
||||
const response = await serveStaticFile(modelPath, req);
|
||||
if (response) {
|
||||
res.statusCode = response.status;
|
||||
response.headers.forEach((value, key) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
const body = await response.arrayBuffer();
|
||||
res.end(Buffer.from(body));
|
||||
return;
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
res.end('Model not found');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Обрабатываем API запросы
|
||||
if (pathname.startsWith('/api/')) {
|
||||
try {
|
||||
let requestBody: string | undefined;
|
||||
if (req.method === 'POST') {
|
||||
let requestBody: Buffer | undefined;
|
||||
if (req.method === 'POST' || req.method === 'PUT') {
|
||||
requestBody = await getRequestBody(req);
|
||||
}
|
||||
|
||||
@ -179,8 +322,15 @@ export function viteApiPlugin(): Plugin {
|
||||
response.headers.forEach((value, key) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
const body = await response.text();
|
||||
res.end(body);
|
||||
|
||||
// Для изображений и файлов моделей возвращаем буфер, для JSON - текст
|
||||
if (response.headers.get('content-type')?.startsWith('application/json')) {
|
||||
const body = await response.text();
|
||||
res.end(body);
|
||||
} else {
|
||||
const body = await response.arrayBuffer();
|
||||
res.end(Buffer.from(body));
|
||||
}
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обработке запроса:', error);
|
||||
|
||||
12
test_image.svg
Normal file
12
test_image.svg
Normal file
@ -0,0 +1,12 @@
|
||||
<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:#4CAF50;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#45a049;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="100%" height="100%" fill="url(#bg)"/>
|
||||
<circle cx="150" cy="100" r="60" fill="rgba(255,255,255,0.2)"/>
|
||||
<text x="150" y="105" font-family="Arial" font-size="16" fill="white" text-anchor="middle">🦁 Lion Model</text>
|
||||
<text x="150" y="125" font-family="Arial" font-size="12" fill="rgba(255,255,255,0.8)" text-anchor="middle">Takanawa</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 679 B |
Loading…
x
Reference in New Issue
Block a user