Happy-Valley-Game / index.html
awacke1's picture
Update index.html
d046ba4 verified
raw
history blame
11.6 kB
<!DOCTYPE html>
<html>
<head>
<title>Three.js Pick and Place</title>
<style>
body { margin: 0; overflow: hidden; } /* Hide scrollbars */
canvas { display: block; }
</style>
</head>
<body>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
let scene, camera, renderer, groundMesh;
let raycaster, mouse;
const placedObjects = []; // Keep track of placed objects
// --- Access State from Streamlit (set in global scope via injection) ---
// Default value if injection fails for some reason
const selectedObjectType = window.SELECTED_OBJECT_TYPE || "None";
function init() {
// --- Basic Setup ---
scene = new THREE.Scene();
scene.background = new THREE.Color(0xabcdef); // Light blue sky
// --- Camera (Orthographic adjusted for better view) ---
const aspect = window.innerWidth / window.innerHeight;
const viewSize = 30; // Increase view size
camera = new THREE.OrthographicCamera(
-viewSize * aspect / 2, viewSize * aspect / 2,
viewSize / 2, -viewSize / 2,
0.1, 100 // Adjust near/far planes
);
// Position camera higher and angled slightly for better 3D view
camera.position.set(10, 20, 10);
camera.lookAt(scene.position); // Look at the center
camera.zoom = 1.2; // Zoom in a bit
camera.updateProjectionMatrix();
scene.add(camera);
// --- Lighting (Improved) ---
// Ambient light for overall illumination
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // Soft white light
scene.add(ambientLight);
// Directional light for sunlight and shadows
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
directionalLight.position.set(15, 30, 20); // Adjust position for angle
directionalLight.castShadow = true;
// Configure shadow properties (important!)
directionalLight.shadow.mapSize.width = 2048; // Higher res shadows
directionalLight.shadow.mapSize.height = 2048;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 100;
// Adjust shadow camera frustum to cover the playable area
directionalLight.shadow.camera.left = -30;
directionalLight.shadow.camera.right = 30;
directionalLight.shadow.camera.top = 30;
directionalLight.shadow.camera.bottom = -30;
directionalLight.shadow.bias = -0.001; // Helps prevent shadow acne
scene.add(directionalLight);
// Optional: Visualize the shadow camera
// const shadowHelper = new THREE.CameraHelper(directionalLight.shadow.camera);
// scene.add(shadowHelper);
// --- Ground ---
const groundGeometry = new THREE.PlaneGeometry(50, 50); // Larger ground
// Use MeshStandardMaterial for lighting/shadows
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x55aa55, // Grassy green
roughness: 0.9,
metalness: 0.1
});
groundMesh = new THREE.Mesh(groundGeometry, groundMaterial);
groundMesh.rotation.x = -Math.PI / 2; // Rotate flat
groundMesh.position.y = -0.05; // Position slightly below origin
groundMesh.receiveShadow = true; // Allow ground to receive shadows
scene.add(groundMesh);
// --- Raycaster and Mouse Vector ---
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
// --- Renderer (Shadows Enabled) ---
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true; // Enable shadow map rendering
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Softer shadows
document.body.appendChild(renderer.domElement);
// --- Event Listeners ---
document.addEventListener('mousemove', onMouseMove, false);
document.addEventListener('click', onDocumentClick, false);
window.addEventListener('resize', onWindowResize, false);
// --- Start Animation ---
animate();
}
// --- Object Creation Functions (Using Primitives) ---
function createSimpleHouse() {
const group = new THREE.Group();
const mainMaterial = new THREE.MeshStandardMaterial({ color: 0xffccaa, roughness: 0.8 });
const roofMaterial = new THREE.MeshStandardMaterial({ color: 0xaa5533, roughness: 0.7 });
// Base (BoxGeometry)
const base = new THREE.Mesh(new THREE.BoxGeometry(2, 1.5, 2.5), mainMaterial);
base.position.y = 1.5 / 2; // Sit on ground
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
// Roof (ConeGeometry or angled planes) - using Cone here
const roof = new THREE.Mesh(new THREE.ConeGeometry(1.8, 1, 4), roofMaterial); // Radius, Height, Segments (4 for pyramid)
roof.position.y = 1.5 + 1 / 2; // Place on top of base
roof.rotation.y = Math.PI / 4; // Align edges
roof.castShadow = true;
roof.receiveShadow = true;
group.add(roof);
return group;
}
function createTree() {
const group = new THREE.Group();
const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.9 }); // Brown
const leavesMaterial = new THREE.MeshStandardMaterial({ color: 0x228B22, roughness: 0.8 }); // Forest Green
// Trunk (CylinderGeometry)
const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.4, 2, 8), trunkMaterial); // RadiusTop, RadiusBottom, Height, Segments
trunk.position.y = 2 / 2;
trunk.castShadow = true;
trunk.receiveShadow = true;
group.add(trunk);
// Leaves (SphereGeometry or Icosahedron)
const leaves = new THREE.Mesh(new THREE.IcosahedronGeometry(1.2, 0), leavesMaterial); // Radius, Detail (0=less poly)
leaves.position.y = 2 + 0.8; // Place above trunk
leaves.castShadow = true;
leaves.receiveShadow = true;
group.add(leaves);
return group;
}
function createRock() {
// Use Icosahedron for irregular shape, or Sphere with displacement later
const rockMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8, metalness: 0.1 });
const rock = new THREE.Mesh(new THREE.IcosahedronGeometry(0.7, 0), rockMaterial); // Radius, Detail
rock.position.y = 0.7 / 2; // Sit on ground (approx)
rock.rotation.x = Math.random() * Math.PI;
rock.rotation.y = Math.random() * Math.PI;
rock.castShadow = true;
rock.receiveShadow = true;
return rock; // Simple mesh, no group needed
}
function createFencePost() {
const postMaterial = new THREE.MeshStandardMaterial({ color: 0xdeb887, roughness: 0.9 }); // BurlyWood
// Use BoxGeometry for a simple square post
const post = new THREE.Mesh(new THREE.BoxGeometry(0.2, 1.5, 0.2), postMaterial);
post.position.y = 1.5 / 2;
post.castShadow = true;
post.receiveShadow = true;
return post;
}
// --- Event Handlers ---
function onMouseMove(event) {
// Calculate mouse position in normalized device coordinates (-1 to +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
function onDocumentClick(event) {
console.log("Click! Selected type:", selectedObjectType); // Debug
if (selectedObjectType === "None") {
console.log("No object type selected for placement.");
return; // Don't place anything if "None" is selected
}
// Update the picking ray with the camera and mouse position
raycaster.setFromCamera(mouse, camera);
// Calculate objects intersecting the picking ray - only check the ground
const intersects = raycaster.intersectObject(groundMesh);
if (intersects.length > 0) {
const intersectPoint = intersects[0].point;
console.log("Intersection at:", intersectPoint); // Debug
let newObject = null;
// Call the correct creation function based on the selected type
switch (selectedObjectType) {
case "Simple House":
newObject = createSimpleHouse();
break;
case "Tree":
newObject = createTree();
break;
case "Rock":
newObject = createRock();
break;
case "Fence Post":
newObject = createFencePost();
break;
default:
console.warn("Unknown object type:", selectedObjectType);
return; // Don't place unknown types
}
if (newObject) {
// Position the new object at the click point on the ground
// The Y position is handled within the create functions to sit on origin
newObject.position.x = intersectPoint.x;
newObject.position.z = intersectPoint.z;
// Y position might need slight adjustment depending on object origin
// For objects created with base at y=0, intersectPoint.y is close enough
scene.add(newObject);
placedObjects.push(newObject); // Track the object
console.log(`Placed ${selectedObjectType} at`, newObject.position);
}
} else {
console.log("Click did not intersect ground.");
}
}
function onWindowResize() {
const aspect = window.innerWidth / window.innerHeight;
const viewSize = 30;
camera.left = -viewSize * aspect / 2;
camera.right = viewSize * aspect / 2;
camera.top = viewSize / 2;
camera.bottom = -viewSize / 2;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
// Add any animations here later if needed
renderer.render(scene, camera);
}
// --- Start the app ---
init();
</script>
</body>
</html>