Spaces:
Running
Running
Download index.html from Cobra777/anycoder-9ded1d78: direct link, hf CLI and curl.
- Browser
- Download file 36.4 kB
-
https://huggingface.co/spaces/Cobra777/anycoder-9ded1d78/resolve/main/index.html
- Command line
-
hf download hf://spaces/Cobra777/anycoder-9ded1d78/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Cobra777/anycoder-9ded1d78/resolve/main/index.html
36.4 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Raytracing Optical Simulator</title>
<style>
/* --- CSS VARIABLES & RESET --- */
:root {
--bg-color: #050508;
--panel-bg: rgba(20, 20, 25, 0.85);
--panel-border: rgba(255, 255, 255, 0.1);
--accent-primary: #00f3ff;
--accent-secondary: #ff0055;
--accent-tertiary: #39ff14;
--text-main: #ffffff;
--text-muted: #8888aa;
--font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--radius: 12px;
--shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
outline: none;
}
body {
background-color: var(--bg-color);
color: var(--text-main);
font-family: var(--font-family);
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
/* --- HEADER --- */
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--panel-border);
z-index: 10;
}
.brand {
font-size: 1.2rem;
font-weight: 700;
letter-spacing: 1px;
display: flex;
align-items: center;
gap: 10px;
}
.brand span {
color: var(--accent-primary);
}
.built-with {
font-size: 0.85rem;
color: var(--text-muted);
text-decoration: none;
padding: 6px 12px;
background: rgba(255, 255, 255, 0.05);
border-radius: 20px;
transition: all 0.3s ease;
}
.built-with:hover {
background: var(--accent-primary);
color: #000;
box-shadow: 0 0 15px var(--accent-primary);
}
/* --- MAIN LAYOUT --- */
main {
flex: 1;
display: flex;
position: relative;
overflow: hidden;
}
/* --- CANVAS AREA --- */
#canvas-container {
flex: 1;
position: relative;
cursor: crosshair;
background-image:
radial-gradient(circle at 1px 1px, rgba(255, 255, 255, 0.05) 1px, transparent 0);
background-size: 40px 40px;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
/* --- OVERLAYS & HUD --- */
.hud-overlay {
position: absolute;
top: 20px;
left: 20px;
pointer-events: none;
color: var(--accent-primary);
font-family: 'Courier New', monospace;
font-size: 0.8rem;
text-shadow: 0 0 5px var(--accent-primary);
background: rgba(0, 0, 0, 0.5);
padding: 8px 12px;
border-radius: 4px;
}
.tooltip {
position: absolute;
background: rgba(0, 0, 0, 0.8);
border: 1px solid var(--accent-primary);
padding: 8px 12px;
border-radius: 4px;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s;
font-size: 0.8rem;
z-index: 20;
transform: translate(15px, 15px);
max-width: 200px;
}
/* --- SIDEBAR CONTROLS --- */
aside {
width: 340px;
background: var(--panel-bg);
backdrop-filter: blur(20px);
border-left: 1px solid var(--panel-border);
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
overflow-y: auto;
z-index: 5;
transition: transform 0.3s ease;
}
/* --- UI COMPONENTS --- */
.control-group {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.group-title {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 1.5px;
color: var(--text-muted);
border-bottom: 1px solid var(--panel-border);
padding-bottom: 5px;
}
button {
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--panel-border);
color: var(--text-main);
padding: 10px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.9rem;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
button:hover {
background: rgba(255, 255, 255, 0.1);
border-color: var(--accent-primary);
}
button.active {
background: rgba(0, 243, 255, 0.15);
border-color: var(--accent-primary);
color: var(--accent-primary);
box-shadow: 0 0 10px rgba(0, 243, 255, 0.2);
}
button.danger {
border-color: var(--accent-secondary);
color: var(--accent-secondary);
}
button.danger:hover {
background: rgba(255, 0, 85, 0.15);
box-shadow: 0 0 10px rgba(255, 0, 85, 0.2);
}
/* Sliders */
.slider-container {
display: flex;
flex-direction: column;
gap: 5px;
}
.slider-header {
display: flex;
justify-content: space-between;
font-size: 0.8rem;
color: var(--text-muted);
}
input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 4px;
background: rgba(255, 255, 255, 0.1);
border-radius: 2px;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: var(--accent-primary);
cursor: pointer;
box-shadow: 0 0 10px var(--accent-primary);
transition: transform 0.1s;
}
input[type="range"]::-webkit-slider-thumb:hover {
transform: scale(1.2);
}
/* Stats Panel */
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
font-size: 0.8rem;
}
.stat-item {
background: rgba(0, 0, 0, 0.3);
padding: 8px;
border-radius: 4px;
text-align: center;
}
.stat-value {
display: block;
font-weight: bold;
color: var(--accent-tertiary);
font-family: 'Courier New', monospace;
}
/* Material Selector */
.material-selector {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 8px;
}
.material-option {
padding: 8px;
border-radius: 4px;
border: 1px solid var(--panel-border);
text-align: center;
font-size: 0.7rem;
cursor: pointer;
transition: all 0.2s ease;
}
.material-option:hover {
border-color: var(--accent-primary);
}
.material-option.selected {
background: rgba(0, 243, 255, 0.2);
border-color: var(--accent-primary);
}
/* --- RESPONSIVE --- */
@media (max-width: 768px) {
body {
flex-direction: column;
}
aside {
width: 100%;
height: 40%;
border-left: none;
border-top: 1px solid var(--panel-border);
}
#canvas-container {
height: 60%;
}
}
</style>
<!-- Importing FontAwesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<!-- Header -->
<header>
<div class="brand">
<i class="fa-solid fa-atom" style="color: var(--accent-primary);"></i>
RAYTRACING <span>SIMULATOR</span>
</div>
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="built-with">
Built with anycoder
</a>
</header>
<!-- Main Content -->
<main>
<!-- Canvas Area -->
<div id="canvas-container">
<canvas id="simCanvas"></canvas>
<div class="hud-overlay">
<div>MODE: <span id="mode-display">INTERACTIVE</span></div>
<div>RAYS: <span id="ray-count-display">0</span></div>
<div>BOUNCES: <span id="bounce-count-display">0</span></div>
<div>FPS: <span id="fps-display">0</span></div>
</div>
<div id="tooltip" class="tooltip"></div>
</div>
<!-- Sidebar Controls -->
<aside>
<div class="control-group">
<div class="group-title">Tools</div>
<button id="btn-laser" class="active" onclick="setTool('laser')">
<i class="fa-solid fa-bullseye"></i> Laser Emitter
</button>
<button id="btn-mirror" onclick="setTool('mirror')">
<i class="fa-solid fa-square"></i> Mirror
</button>
<button id="btn-lens" onclick="setTool('lens')">
<i class="fa-solid fa-circle"></i> Lens
</button>
<button id="btn-prism" onclick="setTool('prism')">
<i class="fa-solid fa-play"></i> Prism
</button>
<button id="btn-drag" onclick="setTool('drag')">
<i class="fa-solid fa-up-down-left-right"></i> Move Object
</button>
<button id="btn-delete" class="danger" onclick="deleteSelected()">
<i class="fa-solid fa-trash"></i> Delete Selected
</button>
</div>
<div class="control-group">
<div class="group-title">Laser Properties</div>
<div class="slider-container">
<div class="slider-header">
<span>Intensity</span>
<span id="val-intensity">100%</span>
</div>
<input type="range" id="input-intensity" min="10" max="100" value="100">
</div>
<div class="slider-container">
<div class="slider-header">
<span>Beam Width</span>
<span id="val-spread">2px</span>
</div>
<input type="range" id="input-spread" min="1" max="10" value="2">
</div>
<div class="slider-container">
<div class="slider-header">
<span>Ray Count</span>
<span id="val-raycount">5</span>
</div>
<input type="range" id="input-raycount" min="1" max="20" value="5">
</div>
<div class="slider-container">
<div class="slider-header">
<span>Max Bounces</span>
<span id="val-reflect">10</span>
</div>
<input type="range" id="input-reflect" min="0" max="20" value="10">
</div>
</div>
<div class="control-group" id="material-controls" style="display: none;">
<div class="group-title">Material Properties</div>
<div class="slider-container">
<div class="slider-header">
<span>Refractive Index</span>
<span id="val-refractive">1.5</span>
</div>
<input type="range" id="input-refractive" min="1" max="3" step="0.1" value="1.5">
</div>
<div class="slider-container">
<div class="slider-header">
<span>Absorption</span>
<span id="val-absorption">0.2</span>
</div>
<input type="range" id="input-absorption" min="0" max="1" step="0.05" value="0.2">
</div>
<div class="group-title">Preset Materials</div>
<div class="material-selector">
<div class="material-option" onclick="setMaterialPreset('glass')">Glass (1.5)</div>
<div class="material-option" onclick="setMaterialPreset('water')">Water (1.33)</div>
<div class="material-option" onclick="setMaterialPreset('diamond')">Diamond (2.42)</div>
</div>
</div>
<div class="control-group">
<div class="group-title">Simulation</div>
<button onclick="clearScene()">
<i class="fa-solid fa-eraser"></i> Clear Scene
</button>
<button onclick="resetDefaults()">
<i class="fa-solid fa-rotate-right"></i> Reset Defaults
</button>
<button id="btn-pause" onclick="togglePause()">
<i class="fa-solid fa-pause"></i> Pause
</button>
</div>
<div class="control-group">
<div class="group-title">System Stats</div>
<div class="stats-grid">
<div class="stat-item">
<span class="stat-value" id="stat-objects">0</span>
Objects
</div>
<div class="stat-item">
<span class="stat-value" id="stat-rays">0</span>
Rays
</div>
<div class="stat-item">
<span class="stat-value" id="stat-bounces">0</span>
Bounces
</div>
<div class="stat-item">
<span class="stat-value" id="stat-fps">0</span>
FPS
</div>
</div>
</div>
<div style="font-size: 0.75rem; color: #555; margin-top: auto;">
<strong>Instructions:</strong><br>
1. Select <b>Laser</b> and click to place<br>
2. Add <b>Mirrors/Lenses/Prisms</b><br>
3. Drag objects to rearrange<br>
4. Right-click to delete<br>
5. Adjust material properties
</div>
</aside>
</main>
<script>
/**
* ADVANCED RAYTRACING OPTICAL SIMULATOR
* Built with anycoder
* Features:
* - Physically accurate light transport
* - Refraction, reflection, absorption
* - Multiple material types
* - Real-time performance
*/
// --- CONFIGURATION ---
const CONFIG = {
colors: {
laser: '#00f3ff',
mirror: '#ffffff',
lens: 'rgba(100, 200, 255, 0.3)',
prism: 'rgba(255, 200, 100, 0.3)',
selection: '#ff0055',
grid: 'rgba(255, 255, 255, 0.05)'
},
maxBounces: 10,
rayCount: 5,
performance: {
rayStepSize: 2,
maxRayLength: 2000,
fpsSampleCount: 10
}
};
// Material presets
const MATERIALS = {
glass: { refractiveIndex: 1.5, absorption: 0.2, color: 'rgba(100, 200, 255, 0.3)' },
water: { refractiveIndex: 1.33, absorption: 0.1, color: 'rgba(100, 150, 255, 0.2)' },
diamond: { refractiveIndex: 2.42, absorption: 0.05, color: 'rgba(200, 255, 255, 0.2)' }
};
// --- STATE MANAGEMENT ---
let state = {
tool: 'laser',
objects: [],
selectedId: null,
isDragging: false,
dragOffset: { x: 0, y: 0 },
laserIntensity: 1.0,
beamWidth: 2,
rayCount: 0,
totalBounces: 0,
isPaused: false,
fps: 0,
fpsSamples: [],
lastFrameTime: performance.now(),
currentMaterial: { ...MATERIALS.glass }
};
// --- DOM ELEMENTS ---
const canvas = document.getElementById('simCanvas');
const ctx = canvas.getContext('2d');
const tooltip = document.getElementById('tooltip');
const modeDisplay = document.getElementById('mode-display');
const rayCountDisplay = document.getElementById('ray-count-display');
const bounceCountDisplay = document.getElementById('bounce-count-display');
const fpsDisplay = document.getElementById('fps-display');
const statObjects = document.getElementById('stat-objects');
const statRays = document.getElementById('stat-rays');
const statBounces = document.getElementById('stat-bounces');
const statFps = document.getElementById('stat-fps');
const materialControls = document.getElementById('material-controls');
// --- INITIALIZATION ---
function init() {
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Add default objects
addDefaultScene();
// Start Loop
requestAnimationFrame(renderLoop);
// Setup Inputs
setupInputs();
// Initialize FPS counter
setInterval(calculateFPS, 1000);
}
function resizeCanvas() {
const container = document.getElementById('canvas-container');
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
}
function addDefaultScene() {
// Center Laser
state.objects.push({
id: Date.now(),
type: 'laser',
x: canvas.width / 2,
y: canvas.height / 2,
angle: -Math.PI / 4,
width: 10,
height: 10,
color: CONFIG.colors.laser
});
// Mirror 1
state.objects.push({
id: Date.now() + 1,
type: 'mirror',
x: 100,
y: 100,
width: 150,
height: 10,
angle: Math.PI / 2,
color: CONFIG.colors.mirror,
reflectivity: 0.95
});
// Lens
state.objects.push({
id: Date.now() + 2,
type: 'lens',
x: canvas.width - 200,
y: canvas.height - 200,
width: 100,
height: 50,
angle: Math.PI / 4,
color: CONFIG.colors.lens,
...MATERIALS.glass
});
updateStats();
}
// --- INPUT HANDLING ---
function setupInputs() {
// Mouse Events
canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', onMouseMove);
canvas.addEventListener('mouseup', onMouseUp);
canvas.addEventListener('contextmenu', onRightClick);
// Tool Buttons
document.getElementById('btn-laser').addEventListener('click', () => setTool('laser'));
document.getElementById('btn-mirror').addEventListener('click', () => setTool('mirror'));
document.getElementById('btn-lens').addEventListener('click', () => setTool('lens'));
document.getElementById('btn-prism').addEventListener('click', () => setTool('prism'));
document.getElementById('btn-drag').addEventListener('click', () => setTool('drag'));
// Sliders
document.getElementById('input-intensity').addEventListener('input', (e) => {
state.laserIntensity = e.target.value / 100;
document.getElementById('val-intensity').textContent = e.target.value + '%';
});
document.getElementById('input-spread').addEventListener('input', (e) => {
state.beamWidth = parseInt(e.target.value);
document.getElementById('val-spread').textContent = e.target.value + 'px';
});
document.getElementById('input-raycount').addEventListener('input', (e) => {
CONFIG.rayCount = parseInt(e.target.value);
document.getElementById('val-raycount').textContent = e.target.value;
});
document.getElementById('input-reflect').addEventListener('input', (e) => {
CONFIG.maxBounces = parseInt(e.target.value);
document.getElementById('val-reflect').textContent = e.target.value;
});
// Material controls
document.getElementById('input-refractive').addEventListener('input', (e) => {
state.currentMaterial.refractiveIndex = parseFloat(e.target.value);
document.getElementById('val-refractive').textContent = e.target.value;
updateSelectedMaterial();
});
document.getElementById('input-absorption').addEventListener('input', (e) => {
state.currentMaterial.absorption = parseFloat(e.target.value);
document.getElementById('val-absorption').textContent = e.target.value;
updateSelectedMaterial();
});
}
function setTool(toolName) {
state.tool = toolName;
state.selectedId = null;
// Update UI
document.querySelectorAll('aside button').forEach(btn => btn.classList.remove('active'));
document.getElementById(`btn-${toolName}`).classList.add('active');
// Show/hide material controls
if (['lens', 'prism'].includes(toolName)) {
materialControls.style.display = 'flex';
} else {
materialControls.style.display = 'none';
}
modeDisplay.textContent = toolName.toUpperCase();
tooltip.style.opacity = 0;
}
function setMaterialPreset(name) {
state.currentMaterial = { ...MATERIALS[name] };
document.getElementById('input-refractive').value = state.currentMaterial.refractiveIndex;
document.getElementById('val-refractive').textContent = state.currentMaterial.refractiveIndex;
document.getElementById('input-absorption').value = state.currentMaterial.absorption;
document.getElementById('val-absorption').textContent = state.currentMaterial.absorption;
// Update UI
document.querySelectorAll('.material-option').forEach(el => el.classList.remove('selected'));
document.querySelector(`.material-option[onclick*="${name}"]`).classList.add('selected');
updateSelectedMaterial();
}
function updateSelectedMaterial() {
if (state.selectedId) {
const obj = state.objects.find(o => o.id === state.selectedId);
if (obj && ['lens', 'prism'].includes(obj.type)) {
obj.refractiveIndex = state.currentMaterial.refractiveIndex;
obj.absorption = state.currentMaterial.absorption;
obj.color = state.currentMaterial.color;
}
}
}
function onMouseDown(e) {
if (state.isPaused) return;
const { x, y } = getMousePos(e);
const clickedObj = getObjectAt(x, y);
if (state.tool === 'drag') {
if (clickedObj) {
state.isDragging = true;
state.selectedId = clickedObj.id;
state.dragOffset = { x: x - clickedObj.x, y: y - clickedObj.y };
// Update material controls for lenses/prisms
if (['lens', 'prism'].includes(clickedObj.type)) {
state.currentMaterial = {
refractiveIndex: clickedObj.refractiveIndex,
absorption: clickedObj.absorption,
color: clickedObj.color
};
document.getElementById('input-refractive').value = clickedObj.refractiveIndex;
document.getElementById('val-refractive').textContent = clickedObj.refractiveIndex;
document.getElementById('input-absorption').value = clickedObj.absorption;
document.getElementById('val-absorption').textContent = clickedObj.absorption;
}
}
} else if (state.tool === 'laser') {
if (!clickedObj) {
addLaser(x, y);
}
} else if (state.tool === 'mirror') {
if (!clickedObj) {
addMirror(x, y);
}
} else if (state.tool === 'lens') {
if (!clickedObj) {
addLens(x, y);
}
} else if (state.tool === 'prism') {
if (!clickedObj) {
addPrism(x, y);
}
}
}
function onMouseMove(e) {
const { x, y } = getMousePos(e);
if (state.isDragging && state.selectedId) {
const obj = state.objects.find(o => o.id === state.selectedId);
if (obj) {
obj.x = x - state.dragOffset.x;
obj.y = y - state.dragOffset.y;
}
} else {
// Hover effect logic
const hovered = getObjectAt(x, y);
if (hovered) {
canvas.style.cursor = state.tool === 'drag' ? 'move' : 'pointer';
showTooltip(x, y, hovered);
} else {
canvas.style.cursor = 'crosshair';
hideTooltip();
}
}
}
function onMouseUp() {
state.isDragging = false;
}
function onRightClick(e) {
e.preventDefault();
const { x, y } = getMousePos(e);
const clicked = getObjectAt(x, y);
if (clicked) {
deleteObject(clicked.id);
}
}
function getMousePos(evt) {
const rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
// --- OBJECT MANAGEMENT ---
function getObjectAt(x, y) {
// Reverse iterate to select top-most item
for (let i = state.objects.length - 1; i >= 0; i--) {
const obj = state.objects[i];
const dist = Math.hypot(obj.x - x, obj.y - y);
if (obj.type === 'mirror') {
// Check distance to line segment
const closest = closestPointOnLine(
{x: obj.x, y: obj.y},
{x: obj.x + Math.cos(obj.angle) * obj.width, y: obj.y + Math.sin(obj.angle) * obj.height},
{x, y}
);
if (Math.hypot(closest.x - x, closest.y - y) < 15) return obj;
} else if (obj.type === 'laser') {
if (dist < 15) return obj;
} else if (obj.type === 'lens') {
// Ellipse approximation for lens
const rx = obj.width / 2;
const ry = obj.height / 2;
const dx = (x - obj.x) * Math.cos(-obj.angle) - (y - obj.y) * Math.sin(-obj.angle);
const dy = (x - obj.x) * Math.sin(-obj.angle) + (y - obj.y) * Math.cos(-obj.angle);
const inside = (dx * dx) / (rx * rx) + (dy * dy) / (ry * ry) <= 1;
if (inside) return obj;
} else if (obj.type === 'prism') {
// Triangle approximation for prism
const points = getPrismPoints(obj);
if (pointInTriangle({x, y}, points[0], points[1], points[2])) {
return obj;
}
}
}
return null;
}
function addLaser(x, y) {
state.objects.push({
id: Date.now(),
type: 'laser',
x: x,
y: y,
angle: -Math.PI / 4,
width: 10,
height: 10,
color: CONFIG.colors.laser
});
updateStats();
}
function addMirror(x, y) {
state.objects.push({
id: Date.now(),
type: 'mirror',
x: x,
y: y,
width: 120,
height: 10,
angle: 0,
color: CONFIG.colors.mirror,
reflectivity: 0.95
});
updateStats();
}
function addLens(x, y) {
state.objects.push({
id: Date.now(),
type: 'lens',
x: x,
y: y,
width: 100,
height: 50,
angle: 0,
color: state.currentMaterial.color,
refractiveIndex: state.currentMaterial.refractiveIndex,
absorption: state.currentMaterial.absorption
});
updateStats();
}
function addPrism(x, y) {
state.objects.push({
id: Date.now(),
type: 'prism',
x: x,
y: y,
width: 100,
height: 100,
angle: 0,
color: state.currentMaterial.color,
refractiveIndex: state.currentMaterial.refractiveIndex,
absorption: state.currentMaterial.absorption
});
updateStats();
}
function deleteObject(id) {
state.objects = state.objects.filter(o => o.id !== id);
if (state.selectedId === id) state.selectedId = null;
updateStats();
}
function deleteSelected() {
if (state.selectedId) {
deleteObject(state.selectedId);
}
}
function clearScene() {
state.objects = [];
state.selectedId = null;
updateStats();
}
function resetDefaults() {
clearScene();
addDefaultScene();
}
function togglePause() {
state.isPaused = !state.isPaused;
const btn = document.getElementById('btn-pause');
btn.innerHTML = state.isPaused ?
'<i class="fa-solid fa-play"></i> Resume' :
'<i class="fa-solid fa-pause"></i> Pause';
}
// --- TOOLTIP ---
function showTooltip(x, y, obj) {
tooltip.style.left = x + 'px';
tooltip.style.top = y + 'px';
tooltip.style.opacity = 1;
let info = `<strong>${obj.type.toUpperCase()}</strong><br>`;
info += `Pos: ${Math.round(obj.x)}, ${Math.round(obj.y)}<br>`;
if (obj.type === 'mirror') {
info += `Reflectivity: ${(obj.reflectivity * 100).toFixed(0)}%`;
} else if (obj.type === 'lens' || obj.type === 'prism') {
info += `n = ${obj.refractiveIndex.toFixed(2)}<br>`;
info += `Absorption: ${(obj.absorption * 100).toFixed(0)}%`;
}
tooltip.innerHTML = info;
}
function hideTooltip() {
tooltip.style.opacity = 0;
}
// --- PHYSICS ENGINE (RAYTRACING) ---
function calculateRays() {
if (state.isPaused) return;
state.rayCount = 0;
state.totalBounces = 0;
const lasers = state.objects.filter(o => o.type === 'laser');
if (lasers.length === 0) return;
lasers.forEach(laser => {
// Emit multiple rays to simulate beam
const spread = 0.1; // Radians spread
const startAngle = laser.angle - spread / 2;
const endAngle = laser.angle + spread / 2;
for(let i = 0; i < CONFIG.rayCount; i++) {
const angle = startAngle + (spread * (i / (CONFIG.rayCount - 1)));
castRay(laser.x, laser.y, angle, CONFIG.maxBounces, state.laserIntensity, 1.0);
}
});
}
function castRay(x, y, angle, bouncesLeft, intensity, currentIOR) {
if (bouncesLeft <= 0 || intensity < 0.01) return;
state.rayCount++;
// Ray direction vector
const dx = Math.cos(angle);
const dy = Math.sin(angle);
// Find closest intersection
let closestHit = {
distance: Infinity,
point: null,
normal: null,
object: null,
isEntering: true
};
// Check intersection with all objects
for (const obj of state.objects) {
if (obj.type === 'laser') continue;
let hit = null;
if (obj.type === 'mirror') {
hit = intersectRayWithLine(
{x, y}, {x: x + dx * CONFIG.performance.maxRayLength, y: y + dy * CONFIG.performance.maxRayLength},
{x: obj.x, y: obj.y},
{x: obj.x + Math.cos(obj.angle) * obj.width, y: obj.y + Math.sin(obj.angle) * obj.height}
);
if (hit) {
// Mirror normal
const nx = -Math.sin(obj.angle);
const ny = Math.cos(obj.angle);
hit.normal = { x: nx, y: ny };
hit.object = obj;
}
}
else if (obj.type === 'lens') {
hit = intersectRayWithEllipse(
{x, y}, {x: x + dx * CONFIG.performance.maxRayLength, y: y + dy * CONFIG.performance.maxRayLength},
obj
);
if (hit) {
hit.object = obj;
// Calculate normal at intersection point (ellipse normal)
const rx = obj.width / 2;
const ry = obj.height / 2;
const localX = hit.point.x - obj.x;
const localY = hit.point.y - obj.y;
const rotatedX = localX * Math.cos(-obj.angle) - localY * Math.sin(-obj.angle);
const rotatedY = localX * Math.sin(-obj.angle) + localY * Math.cos(-obj.angle);
// Ellipse gradient gives normal
const nx = 2 * rotatedX / (rx * rx);
const ny = 2 * rotatedY / (ry * ry);
const len = Math.hypot(nx, ny);
hit.normal = {
x: (nx / len) * Math.cos(obj.angle) - (ny / len) * Math.sin(obj.angle),
y: (nx / len) * Math.sin(obj.angle) + (ny / len) * Math.cos(obj.angle)
};
}
}
else if (obj.type === 'prism') {
const points = getPrismPoints(obj);
hit = intersectRayWithTriangle(
{x, y}, {x: x + dx * CONFIG.performance.maxRayLength, y: y + dy * CONFIG.performance.maxRayLength},
points[0], points[1], points[2]
);
if (hit) {
hit.object = obj;
// Calculate triangle edge normal
const edge = {
x: points[1].x - points[0].x,
y: points[1].y - points[0].y
};
hit.normal = {
x: -edge.y,
y: edge.x
};
const len = Math.hypot(hit.normal.x, hit.normal.y);
hit.normal.x /= len;
hit.normal.y /= len;
// Flip normal if needed (based on ray direction)
const dot = dx * hit.normal.x + dy * hit.normal.y;
if (dot > 0) {
hit.normal.x *= -1;
hit.normal.y *= -1;
}
}
}
if (hit && hit.distance < closestHit.distance) {
closestHit = hit;
}
}
// Draw ray segment
const endX = closestHit.point ? closestHit.point.x : x + dx * CONFIG.performance.maxRayLength;
const endY = closestHit.point ? closestHit.point.y : y + dy * CONFIG.performance.maxRayLength;
drawRaySegment(x, y, endX, endY, intensity, angle);
// Handle interactions
if (closestHit.point && closestHit.object) {
state.totalBounces++;
const obj = closestHit.object;
const normal = closestHit.normal;
const hitX = closestHit.point.x;
const hitY = closestHit.point.y;
if (obj.type === 'mirror') {
// Reflection
const dot = dx * normal.x + dy * normal.y;
const rx = dx - 2 * dot * normal.x;
const ry = dy - 2 * dot * normal.y;
// Add slight randomness to prevent infinite loops
const jitter = (Math.random() - 0.5) * 0.01;
castRay(
hitX, hitY,
Math.atan2(ry + jitter, rx + jitter),
bouncesLeft - 1,
intensity * (obj.reflectivity || 0.95),
currentIOR
);
}
else if (obj.type === 'lens' || obj.type === 'prism') {
// Refraction (Snell's Law)
const n1 = currentIOR;
const n2 = closestHit.isEntering ? obj.refractiveIndex : 1.0;
const incidentAngle = Math.acos(Math.abs(dx * normal.x + dy * normal.y));
const refractionRatio = n1 / n2;
const sinTheta2 = refractionRatio * Math.sin(incidentAngle);
if (Math.abs(sinTheta2) <= 1) {
// Refraction is possible
const cosTheta2 = Math.sqrt(1 - sinTheta2 * sinTheta2);
// Calculate refracted direction
const tx = refractionRatio * dx + (refractionRatio * Math.cos(incidentAngle) - cosTheta2) * normal.x;
const ty = refractionRatio * dy + (refractionRatio * Math.cos(incidentAngle) - cosTheta2) * normal.y;
// Apply absorption
const newIntensity = intensity * (1 - obj.absorption);
castRay(
hitX, hitY,
Math.atan2(ty, tx),
bouncesLeft - 1,
newIntensity,
closestHit.isEntering ? obj.refractiveIndex : 1.0
);
} else {
// Total internal reflection
const dot = dx * normal.x + dy * normal.y;
const rx = dx - 2 * dot * normal.x;
const ry = dy - 2 * dot * normal.y;
castRay(
hitX, hitY,
Math.atan2(ry, rx),
bouncesLeft - 1,
intensity * (1 - obj.absorption),
currentIOR
);
}
}
}
}
// --- INTERSECTION TESTS ---
function intersectRayWithLine(rayStart, rayEnd, lineStart, lineEnd) {
const x1 = lineStart.x;
const y1 = lineStart.y;
const x2 = lineEnd.x;
const y2 = lineEnd.y;
const x3 = rayStart.x;
const y3 = rayStart.y;
const x4 = rayEnd.x;
const y4 = rayEnd.y;
const denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
if (denom === 0) return null; // Parallel
const ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
if (ua < 0 || ua > 1) return null; // Outside segment
const ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;
if (ub < 0) return null; // Ray goes away from line
return {
point: {
x: x1 + ua * (x2 - x1),
y: y1 + ua * (y2 - y1)
},
distance: ub,
isEntering: true
};
}
function intersectRayWithEllipse(rayStart, rayEnd, ellipse) {
// Transform ray to ellipse local coordinates
const cos = Math.cos(-ellipse.angle);
const sin = Math.sin(-ellipse.angle);
const x1 = (rayStart.x - ellipse.x) * cos - (rayStart.y - ellipse.y) * sin;
const y1 = (rayStart.x - ellipse.x) * sin + (rayStart.y - ellipse.y) * cos;
const x2 = (rayEnd.x - ellipse.x) * cos - (rayEnd.y - ellipse.y) * sin;
const y2 = (rayEnd.x - ellipse.x) * sin + (rayEnd.y - ellipse.y) * cos;
const rx = ellipse.width / 2;
const ry = ellipse.height / 2;
// Ray direction
const dx = x2 - x1;
const dy = y2 - y1;
// Quadratic coefficients
const A = (dx * dx) / (rx * rx) + (dy * dy) / (ry * ry);
const B = 2 * (x1 * dx) / (rx * rx) + 2 * (y1 * dy) / (ry * ry);
const C = (x1 * x1) / (rx
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Raytracing Optical Simulator</title>
<style>
/* --- CSS VARIABLES & RESET --- */
:root {
--bg-color: #050508;
--panel-bg: rgba(20, 20, 25, 0.85);
--panel-border: rgba(255, 255, 255, 0.1);
--accent-primary: #00f3ff;
--accent-secondary: #ff0055;
--accent-tertiary: #39ff14;
--text-main: #ffffff;
--text-muted: #8888aa;
--font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--radius: 12px;
--shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
outline: none;
}
body {
background-color: var(--bg-color);
color: var(--text-main);
font-family: var(--font-family);
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
/* --- HEADER --- */
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--panel-border);
z-index: 10;
}
.brand {
font-size: 1.2rem;
font-weight: 700;
letter-spacing: 1px;
display: flex;
align-items: center;
gap: 10px;
}
.brand span {
color: var(--accent-primary);
}
.built-with {
font-size: 0.85rem;
color: var(--text-muted);
text-decoration: none;
padding: 6px 12px;
background: rgba(255, 255, 255, 0.05);
border-radius: 20px;
transition: all 0.3s ease;
}
.built-with:hover {
background: var(--accent-primary);
color: #000;
box-shadow: 0 0 15px var(--accent-primary);
}
/* --- MAIN LAYOUT --- */
main {
flex: 1;
display: flex;
position: relative;
overflow: hidden;
}
/* --- CANVAS AREA --- */
#canvas-container {
flex: 1;
position: relative;
cursor: crosshair;
background-image:
radial-gradient(circle at 1px 1px, rgba(255, 255, 255, 0.05) 1px, transparent 0);
background-size: 40px 40px;
}
canvas {