Files
przekroj/components/templates/generator.js

446 lines
13 KiB
JavaScript

import { useState, useEffect } from "react";
import { useRouter } from "next/router";
import { Card, CardHeader, CardContent, CardTitle, CardDescription, Button, Input, Textarea, Alert } from "../ui/components";
import { ChartBarIcon, ArrowDownTrayIcon as DownloadIcon, EyeIcon } from '@heroicons/react/24/outline';
import axios from "axios";
export default function Generator() {
const [profil, setProfil] = useState();
const [args, setArgs] = useState({
scale: 200,
elementOne: 0,
elementTwo: 0,
});
const [isLoading, setIsLoading] = useState(false);
const [previewVisible, setPreviewVisible] = useState(false);
const { query } = useRouter();
const ElementOneOptions = [
{ label: "Nic", value: "0" },
{ label: "Słup", value: "1" },
{ label: "Dom", value: "2" },
];
const ElementTwoOptions = [
{ label: "Nic", value: "0" },
{ label: "Słup", value: "1" },
{ label: "Dom", value: "2" },
];
useEffect(() => {
if (query.external == "tru") {
axios
.post("/api/readtext", {
id: query.id,
})
.then(function (response) {
setProfil(response.data.data);
document.getElementById("textarea-1").value = response.data.data;
console.log(response.data.data);
});
}
}, []);
const getPath = (e, path) => {
let newLines = [];
const lines = path.split("\n");
// Parse the data more accurately
for (let line of lines) {
line = line.trim();
// Skip header lines, segment lines, and empty lines
if (line.startsWith("Próbkowanie") ||
line.startsWith("Segment") ||
line.startsWith("X:") ||
line === "") {
continue;
}
newLines.push(line);
}
if (newLines.length === 0) {
console.log("No valid coordinate data found");
return;
}
let points = [];
// Parse coordinates more reliably
for (let line of newLines) {
const coords = line.split(/[,\t]+/).map(s => s.trim());
if (coords.length >= 3) {
const x = parseFloat(coords[0]);
const y = parseFloat(coords[1]);
const z = parseFloat(coords[2]);
if (!isNaN(x) && !isNaN(y) && !isNaN(z)) {
points.push({ x, y, z });
}
}
}
if (points.length === 0) {
console.log("No valid points parsed");
return;
}
console.log(`Parsed ${points.length} points`);
const canvas = document.getElementById("canvas");
console.log("Canvas element:", canvas);
if (!canvas || !canvas.getContext) {
console.log("canvas not found or no context available");
console.log("canvas exists:", !!canvas);
console.log("getContext available:", canvas ? !!canvas.getContext : false);
return;
}
const ctx = canvas.getContext("2d");
const canvasWidth = 800; // Match the canvas width
const canvasHeight = 400; // Match the canvas height
const padding = 50;
// Clear canvas
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Calculate bounds
const xCoords = points.map(p => p.x);
const yCoords = points.map(p => p.y);
const zCoords = points.map(p => p.z);
const minX = Math.min(...xCoords);
const maxX = Math.max(...xCoords);
const minY = Math.min(...yCoords);
const maxY = Math.max(...yCoords);
const minZ = Math.min(...zCoords);
const maxZ = Math.max(...zCoords);
// Calculate distances along the path
let distances = [0];
let totalDistance = 0;
for (let i = 1; i < points.length; i++) {
const dx = points[i].x - points[i-1].x;
const dy = points[i].y - points[i-1].y;
const distance = Math.sqrt(dx * dx + dy * dy);
totalDistance += distance;
distances.push(totalDistance);
}
console.log(`Total distance: ${totalDistance.toFixed(2)}m, Height range: ${minZ.toFixed(2)}m - ${maxZ.toFixed(2)}m`);
// Set up drawing area
const drawWidth = canvasWidth - 2 * padding;
const drawHeight = canvasHeight - 2 * padding;
// Draw coordinate system
ctx.strokeStyle = "#E5E7EB";
ctx.lineWidth = 1;
// Draw grid
const gridLines = 10;
for (let i = 0; i <= gridLines; i++) {
const x = padding + (i / gridLines) * drawWidth;
const y = padding + (i / gridLines) * drawHeight;
// Vertical grid lines
ctx.beginPath();
ctx.moveTo(x, padding);
ctx.lineTo(x, canvasHeight - padding);
ctx.stroke();
// Horizontal grid lines
ctx.beginPath();
ctx.moveTo(padding, y);
ctx.lineTo(canvasWidth - padding, y);
ctx.stroke();
}
// Draw axes
ctx.strokeStyle = "#6B7280";
ctx.lineWidth = 2;
// X-axis (bottom)
ctx.beginPath();
ctx.moveTo(padding, canvasHeight - padding);
ctx.lineTo(canvasWidth - padding, canvasHeight - padding);
ctx.stroke();
// Y-axis (left)
ctx.beginPath();
ctx.moveTo(padding, padding);
ctx.lineTo(padding, canvasHeight - padding);
ctx.stroke();
// Draw labels
ctx.fillStyle = "#374151";
ctx.font = "12px sans-serif";
ctx.textAlign = "center";
// Distance labels (bottom)
for (let i = 0; i <= 5; i++) {
const distance = (totalDistance * i) / 5;
const x = padding + (i / 5) * drawWidth;
ctx.fillText(`${distance.toFixed(0)}m`, x, canvasHeight - padding + 20);
}
// Height labels (left)
ctx.textAlign = "right";
for (let i = 0; i <= 5; i++) {
const height = minZ + ((maxZ - minZ) * i) / 5;
const y = canvasHeight - padding - (i / 5) * drawHeight;
ctx.fillText(`${height.toFixed(1)}m`, padding - 10, y + 4);
}
// Draw profile line
ctx.strokeStyle = "#3B82F6";
ctx.lineWidth = 3;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
for (let i = 0; i < points.length; i++) {
const x = padding + (distances[i] / totalDistance) * drawWidth;
const y = canvasHeight - padding - ((points[i].z - minZ) / (maxZ - minZ)) * drawHeight;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
// Draw elevation points
ctx.fillStyle = "#3B82F6";
for (let i = 0; i < points.length; i++) {
const x = padding + (distances[i] / totalDistance) * drawWidth;
const y = canvasHeight - padding - ((points[i].z - minZ) / (maxZ - minZ)) * drawHeight;
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2 * Math.PI);
ctx.fill();
}
// Add title
ctx.fillStyle = "#1F2937";
ctx.font = "16px sans-serif";
ctx.textAlign = "center";
ctx.fillText("Profil terenu", canvasWidth / 2, 30);
setPreviewVisible(true);
};
const py = (e, profil, args) => {
e.preventDefault();
setIsLoading(true);
axios
.post("/api/spawn", {
profil: profil,
arguments: args,
})
.then(function (response) {
setIsLoading(false);
console.log(response);
if (response.data.toString().startsWith("Py Error")) {
alert("Błąd: " + response.data);
return;
}
document.getElementById("down").download = response.data.filename.toString() + ".dxf";
document.getElementById("down").click();
})
.catch(function (error) {
setIsLoading(false);
console.log(error);
});
};
return (
<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
{/* Input Section */}
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center space-x-2">
<ChartBarIcon className="w-5 h-5 text-blue-600" />
<span>Dane wejściowe</span>
</CardTitle>
<CardDescription>
Wklej dane z Geoportalu lub wprowadź własne współrzędne
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Textarea
id="textarea-1"
label="Dane z Geoportalu"
placeholder="Próbkowanie: 1 ..."
rows={8}
onChange={(e) => {
setProfil(e.target.value);
}}
className="font-mono text-sm"
/>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Input
label="Skala"
placeholder="200"
type="number"
value={args.scale}
onChange={(e) => setArgs({ ...args, scale: e.target.value })}
/>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Element lewy
</label>
<select
className="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
value={args.elementOne}
onChange={(e) => setArgs({ ...args, elementOne: e.target.value })}
>
{ElementOneOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Element prawy
</label>
<select
className="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
value={args.elementTwo}
onChange={(e) => setArgs({ ...args, elementTwo: e.target.value })}
>
{ElementTwoOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</div>
</div>
<div className="flex space-x-3">
<Button
onClick={() => {
const textareaValue = document.getElementById("textarea-1").value;
if (textareaValue && textareaValue.startsWith("Próbkowanie")) {
// First set preview visible, then draw after a small delay
setPreviewVisible(true);
setTimeout(() => {
getPath(null, textareaValue);
}, 50);
} else {
alert("Wprowadź poprawne dane z Geoportalu");
}
}}
variant="outline"
className="flex-1"
>
<EyeIcon className="w-5 h-5 mr-2" />
Podgląd
</Button>
<Button
onClick={(e) => {
const textareaValue = document.getElementById("textarea-1").value;
if (textareaValue === "") {
alert("Pole danych nie może być puste");
} else if (!textareaValue.startsWith("Próbkowanie")) {
alert("Błędne dane");
} else {
py(e, profil, args);
}
}}
disabled={isLoading}
loading={isLoading}
className="flex-1"
>
<DownloadIcon className="w-5 h-5 mr-2" />
{isLoading ? 'Generowanie...' : 'Generuj profil'}
</Button>
</div>
</CardContent>
</Card>
</div>
{/* Preview Section */}
<div>
<Card>
<CardHeader>
<CardTitle className="flex items-center space-x-2">
<EyeIcon className="w-5 h-5 text-green-600" />
<span>Podgląd profilu</span>
</CardTitle>
<CardDescription>
Wizualizacja profilu terenu na podstawie wprowadzonych danych
</CardDescription>
</CardHeader>
<CardContent>
<div className="bg-gray-50 rounded-lg p-4">
<canvas
id="canvas"
height="400"
width="800"
className="border border-gray-200 rounded bg-white w-full max-w-full"
style={{ display: previewVisible ? 'block' : 'none' }}
/>
{!previewVisible && (
<div className="bg-gray-50 rounded-lg p-8 text-center">
<div className="mx-auto w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center mb-4">
<ChartBarIcon className="w-8 h-8 text-gray-400" />
</div>
<p className="text-gray-500">Wprowadź dane i kliknij "Podgląd" aby zobaczyć profil</p>
</div>
)}
</div>
</CardContent>
</Card>
{/* Instructions */}
<Card className="mt-6">
<CardHeader>
<CardTitle>Instrukcje</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3 text-sm">
<div className="flex items-start space-x-3">
<div className="flex-shrink-0 w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-xs font-semibold text-blue-600">1</span>
</div>
<p className="text-gray-600">Skopiuj dane z Geoportalu w formacie "Próbkowanie: 1"</p>
</div>
<div className="flex items-start space-x-3">
<div className="flex-shrink-0 w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-xs font-semibold text-blue-600">2</span>
</div>
<p className="text-gray-600">Ustaw skalę i wybierz elementy dodatkowe</p>
</div>
<div className="flex items-start space-x-3">
<div className="flex-shrink-0 w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-xs font-semibold text-blue-600">3</span>
</div>
<p className="text-gray-600">Kliknij "Podgląd" aby zobaczyć wizualizację profilu</p>
</div>
<div className="flex items-start space-x-3">
<div className="flex-shrink-0 w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-xs font-semibold text-blue-600">4</span>
</div>
<p className="text-gray-600">Kliknij "Generuj profil" aby pobrać plik DXF</p>
</div>
</div>
</CardContent>
</Card>
</div>
<a href="test.dxf" download="test.dxf" id="down" className="hidden" />
</div>
);
}