Что это:
import * as THREE from 'three';
import {
OrbitControls
} from 'three/addons/controls/OrbitControls.js';
import {
EffectComposer
} from 'three/addons/postprocessing/EffectComposer.js';
import {
RenderPass
} from 'three/addons/postprocessing/RenderPass.js';
import {
UnrealBloomPass
} from 'three/addons/postprocessing/UnrealBloomPass.js';
import {
SMAAPass
} from 'three/addons/postprocessing/SMAAPass.js';
// Initialize loading manager
const loadingManager = new THREE.LoadingManager();
const textureLoader = new THREE.TextureLoader(loadingManager);
let assetsLoaded = false;
let playerRubles = 1000; // Initialize player's starting rubles
const parentDiv = document.getElementById('renderDiv');
let canvas = document.getElementById('threeRenderCanvas');
if (!canvas) {
canvas = document.createElement('canvas');
canvas.id = 'threeRenderCanvas';
parentDiv.appendChild(canvas);
}
// Initialize and play background music
backgroundMusic = new Audio('https://play.rosebud.ai/assets/rosebud_official_theme_02.mp3?hJzg');
backgroundMusic.loop = true;
backgroundMusic.volume = 0.04; // Adjust volume as needed (0.0 to 1.0)
backgroundMusic.play().catch((error) => {
console.warn('Autoplay was prevented. User interaction is required to play the background music.');
});
};
// Initialize the scene
const scene = new THREE.Scene();
// Clock for animation
const clock = new THREE.Clock();
// Initialize the camera
const camera = new THREE.PerspectiveCamera(
75,
canvas.offsetWidth / canvas.offsetHeight,
0.1,
1000
);
camera.position.set(0, 50, 100);
camera.lookAt(0, 0, 0);
Assistant
Данный код представляет собой приложение, созданное с использованием библиотеки Three.js, которая позволяет создавать 3D графику в веб-приложениях. В данном случае, код задает сцену 3D-графики с элементами управления, постобработкой и механиками для интерактивной игры о выращивании овощей (в данном случае, моркови).
// Define sky colors for environmental lighting
const skyColor = new THREE.Color(0x87ceeb); // Bright sky blue
const groundColor = new THREE.Color(0xffffff); // White ground reflection
// Create new bed at center of view
const newPosition = new THREE.Vector3(0, 0, 0);
const newBed = new VegetableBed(newPosition);
scene.add(newBed.getMesh());
vegetableBeds.push(newBed);
// Immediately enter move mode for the new bed
vegetableBeds.forEach(bed => bed.deselect()); // Deselect all other beds
newBed.isMoving = true; // Enter move mode
canvas.style.cursor = 'move';
} else {
alert('Not enough rubles!');
}
// Add plant button listener
document.getElementById('plantBtn').onclick = () => {
if (!bed.isPlanted) {
showPlantingMenu(bed);
} else {
alert('This bed is already planted!');
}
};
// Add harvest button listener if bed is ready to harvest
if (bed.isReadyToHarvest) {
document.getElementById('harvestBtn').onclick = () => {
playerRubles += 20; // Add 20 rubles for harvesting
updateCurrencyDisplay();
// Reset the bed
bed.isPlanted = false;
bed.isReadyToHarvest = false;
bed.plantType = null;
bed.plantedTime = null;
if (bed.growthTimer) {
clearInterval(bed.growthTimer);
bed.growthTimer = null;
}
// Remove carrot models if they exist
if (bed.carrotModels) {
bed.mesh.remove(bed.carrotModels);
// Clean up each carrot instance
bed.carrotModels.children.forEach(carrot => {
carrot.traverse(child => {
if (child instanceof THREE.Mesh) {
if (child.geometry) {
child.geometry.dispose();
}
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(mat => mat.dispose());
} else {
child.material.dispose();
}
}
}
});
});
bed.carrotModels = null;
}
if (bed.carrotModel) {
bed.carrotModel = null;
}
// Refresh the context menu
showContextMenu(bed);
};
}
// Update time remaining if plant is growing
if (bed.isPlanted && !bed.isReadyToHarvest) {
const timeRemainingElement = document.getElementById('timeRemaining');
const updateTimeRemaining = () => {
const now = Date.now();
const timeElapsed = now - bed.plantedTime;
const totalGrowthTime = 60000; // 1 minute in milliseconds
const timeRemaining = Math.max(totalGrowthTime - timeElapsed, 0);
const growthPercentage = ((totalGrowthTime - timeRemaining) / totalGrowthTime) * 100;
// Update carrot model based on growth stage
updateCarrotGrowth(bed, growthPercentage);
if (timeRemaining > 0) {
const seconds = Math.ceil(timeRemaining / 1000);
timeRemainingElement.textContent = `${seconds}s`;
} else {
bed.isReadyToHarvest = true;
// Only update if this is the currently selected bed
if (bed.selected && contextMenu.style.display !== 'none') {
showContextMenu(bed);
}
}
};
updateTimeRemaining(); // Initial update
// Clear any existing interval
if (bed.growthTimer) {
clearInterval(bed.growthTimer);
}
// Set new interval
bed.growthTimer = setInterval(updateTimeRemaining, 1000);
}
}
// Hide context menu
function hideContextMenu() {
contextMenu.style.display = 'none';
if (plantingMenu) {
plantingMenu.style.display = 'none';
}
}
// Create planting menu
let plantingMenu = document.createElement('div');
plantingMenu.style.cssText = position: fixed; background: rgba(0, 0, 0, 0.8); color: white; padding: 10px; border-radius: 5px; display: none; z-index: 1002; font-family: Arial, sans-serif;;
document.body.appendChild(plantingMenu);
function showPlantingMenu(bed) {
const rect = contextMenu.getBoundingClientRect();
plantingMenu.style.left = ${rect.right + 10}px;
plantingMenu.style.top = ${rect.top}px;
code
plantingMenu.innerHTML = `
<div style="margin-bottom: 8px;">Select Crop:</div>
<button id="carrotsBtn" style="padding: 5px; width: 100%;">Carrots (₽5)</button>
`;
plantingMenu.style.display = 'block';
document.getElementById('carrotsBtn').onclick = () => {
if (playerRubles >= 5) {
playerRubles -= 5;
updateCurrencyDisplay();
bed.plantType = 'Carrots';
bed.isPlanted = true;
bed.isReadyToHarvest = false;
bed.plantedTime = Date.now();
bed.growthStage = 0;
// Create carrot model
createCarrotModel(bed);
// Set up growth timer
if (bed.growthTimer) {
clearInterval(bed.growthTimer);
}
hideContextMenu(); // Hide both menus
showContextMenu(bed); // Refresh the main context menu to show planted status
} else {
alert('Not enough rubles to plant carrots!');
hideContextMenu();
}
};
}
// Add mouse interaction
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Add a flag to track if we just finished moving
let justFinishedMoving = false;
canvas.addEventListener('click', (event) => {
// If we just finished moving, ignore this click
if (justFinishedMoving) {
justFinishedMoving = false;
return;
}
// Calculate mouse position in normalized device coordinates (-1 to +1)
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
// Check for intersections with vegetable beds
const intersects = [];
vegetableBeds.forEach(bed => {
const result = raycaster.intersectObject(bed.getMesh(), true);
if (result.length > 0) {
intersects.push({
bed,
distance: result[0].distance
});
}
});
// Sort by distance and select the closest one
if (intersects.length > 0) {
// Deselect all beds first
vegetableBeds.forEach(bed => bed.deselect());
// Select the closest bed
intersects.sort((a, b) => a.distance - b.distance);
intersects[0].bed.select();
} else {
// Clicked empty space, deselect all
vegetableBeds.forEach(bed => bed.deselect());
}
});
// Add mouse move and up handlers for moving beds
let movePlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
let moveIntersection = new THREE.Vector3();
canvas.addEventListener('mousemove', (event) => {
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
// Find the currently moving bed
const movingBed = vegetableBeds.find(bed => bed.isMoving);
if (movingBed) {
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(movePlane, moveIntersection);
// Round the position to the nearest grid position
const gridSize = 6; // Same as spacing in createVegetableBeds
const x = Math.round(moveIntersection.x / gridSize) * gridSize;
const z = Math.round(moveIntersection.z / gridSize) * gridSize;
// Update bed position
movingBed.mesh.position.set(x, movingBed.mesh.position.y, z);
// Check for collisions
let collision = false;
code
// Check collisions for all beds
vegetableBeds.forEach(otherBed => {
if (otherBed === movingBed) return;
const otherPos = otherBed.mesh.position;
const distance = movingBed.mesh.position.distanceTo(otherPos);
if (distance < 5) { // Minimum distance between beds
collision = true;
// Update colors for both the moving bed and the colliding bed
otherBed.isColliding = true;
otherBed.mesh.children.forEach(child => {
if (child.isMesh) {
child.material.color.setHex(0xff0000);
}
});
otherBed.mesh.material.color.setHex(0xff0000);
}
});
// Update material color based on collision for moving bed
if (collision !== movingBed.isColliding) {
movingBed.isColliding = collision;
movingBed.mesh.children.forEach(child => {
if (child.isMesh) {
child.material.color.setHex(collision ? 0xff0000 : 0x228B22);
}
});
movingBed.mesh.material.color.setHex(collision ? 0xff0000 : 0xb5783c);
}
// Reset colors for beds that are no longer colliding
vegetableBeds.forEach(otherBed => {
if (otherBed === movingBed) return;
const distance = movingBed.mesh.position.distanceTo(otherBed.mesh.position);
if (distance >= 5 && otherBed.isColliding) {
otherBed.isColliding = false;
otherBed.mesh.children.forEach(child => {
if (child.isMesh) {
child.material.color.setHex(0x228B22);
}
});
otherBed.mesh.material.color.setHex(0xb5783c);
}
});
}
// Check collisions with all other beds
vegetableBeds.forEach(otherBed => {
if (otherBed === movingBed) return;
const otherPos = otherBed.mesh.position;
const distance = currentPos.distanceTo(otherPos);
if (distance < 5) { // Minimum distance between beds
collision = true;
// Update colors for both beds
otherBed.mesh.children.forEach(child => {
if (child.isMesh) {
child.material.color.setHex(0xff0000);
}
});
otherBed.mesh.material.color.setHex(0xff0000);
otherBed.isColliding = true;
}
});
if (collision) {
// Return bed to previous valid position or starting position
movingBed.mesh.position.set(
movingBed.lastValidPosition?.x || 0,
movingBed.mesh.position.y,
movingBed.lastValidPosition?.z || 0
);
} else {
// Store the valid position
movingBed.lastValidPosition = {
x: movingBed.mesh.position.x,
z: movingBed.mesh.position.z
};
}
// Reset all beds' colors
vegetableBeds.forEach(bed => {
bed.isColliding = false;
bed.mesh.children.forEach(child => {
if (child.isMesh) {
child.material.color.setHex(0x228B22);
}
});
bed.mesh.material.color.setHex(0xb5783c);
});
movingBed.isMoving = false;
canvas.style.cursor = 'default';
// Set the flag to prevent immediate selection
justFinishedMoving = true;
// Use setTimeout to reset the flag after a short delay
setTimeout(() => {
justFinishedMoving = false;
}, 100);
// Prevent the click event from triggering bed selection
event.stopPropagation();
}
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
if (assetsLoaded) {
applyControls(); // Apply camera controls
controls.update();
// Update context menu position if a bed is selected
const selectedBed = vegetableBeds.find(bed => bed.selected);
if (selectedBed && contextMenu.style.display !== 'none') {
const vector = new THREE.Vector3();
selectedBed.mesh.getWorldPosition(vector);
vector.project(camera);
const x = (vector.x * 0.5 + 0.5) * canvas.clientWidth;
const y = (-vector.y * 0.5 + 0.5) * canvas.clientHeight;
contextMenu.style.left = ${x}px;
contextMenu.style.top = ${y}px;
}
}
composer.render();
}
// =========================
// Mobile Controls Integration
// =========================
// Create a container for the D-pad
const dpadContainer = document.createElement('div');
dpadContainer.id = 'dpadContainer';
document.body.appendChild(dpadContainer);
// Append the styles to the head
const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);
// Add event listeners for keyboard controls
window.addEventListener('keydown', (event) => {
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
keysPressed.up = true;
break;
case 'ArrowDown':
case 'KeyS':
keysPressed.down = true;
break;
case 'ArrowLeft':
case 'KeyA':
keysPressed.left = true;
break;
case 'ArrowRight':
case 'KeyD':
keysPressed.right = true;
break;
case 'Space':
keysPressed.jump = true;
break;
default:
break;
}
});
window.addEventListener('keyup', (event) => {
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
keysPressed.up = false;
break;
case 'ArrowDown':
case 'KeyS':
keysPressed.down = false;
break;
case 'ArrowLeft':
case 'KeyA':
keysPressed.left = false;
break;
case 'ArrowRight':
case 'KeyD':
keysPressed.right = false;
break;
case 'Space':
keysPressed.jump = false;
break;
default:
break;
}
});
// =========================
// End of Mobile and Keyboard Controls Integration
// =========================
// Function to apply controls based on keysPressed
function applyControls() {
const moveSpeed = 1.0; // Adjust as needed
const verticalSpeed = 1.0; // Speed for moving up/down
code
if (keysPressed.up) {
camera.position.z -= moveSpeed;
}
if (keysPressed.down) {
camera.position.z += moveSpeed;
}
if (keysPressed.left) {
camera.position.x -= moveSpeed;
}
if (keysPressed.right) {
camera.position.x += moveSpeed;
}
if (keysPressed.jump) {
camera.position.y += verticalSpeed;
}
}
// Function to create a carrot model
function createCarrotModel(bed) {
// Remove existing carrot model if it exists
if (bed.carrotModel) {
bed.mesh.remove(bed.carrotModels);
// Properly dispose of all geometries and materials
bed.carrotModels.children.forEach(carrot => {
carrot.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) child.material.dispose();
});
});
bed.carrotModels = null;
}
}
// Function to update carrot growth
function updateCarrotGrowth(bed, growthPercentage) {
let scale;
code
if (growthPercentage < 33) {
// Remove any existing model (0-32%)
if (bed.carrotModels) {
bed.mesh.remove(bed.carrotModels);
bed.carrotModels.children.forEach(carrot => {
carrot.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) child.material.dispose();
});
});
bed.carrotModels = null;
}
return;
}
// Create or update carrot model
if (!bed.carrotModel) {
// Create carrot body (cone)
const carrotGeometry = new THREE.ConeGeometry(0.2, 1, 8);
const carrotMaterial = new THREE.MeshStandardMaterial({
color: 0xff6b1a
}); // Orange color
bed.carrotModel = new THREE.Group();
const carrotBody = new THREE.Mesh(carrotGeometry, carrotMaterial);
// Create a group for the carrot body
const carrotBodyGroup = new THREE.Group();
carrotBodyGroup.add(carrotBody);
carrotBodyGroup.rotation.x = Math.PI; // Rotate the body to point downward
bed.carrotModel.add(carrotBodyGroup);
// Create carrot leaves
const leavesGroup = new THREE.Group();
// Create a single leaf shape
const leafShape = new THREE.Shape();
leafShape.moveTo(0, 0);
leafShape.bezierCurveTo(0.1, 0.3, 0.2, 0.6, 0.1, 1.0); // Right curve, made longer
leafShape.bezierCurveTo(0, 1.2, -0.2, 0.6, -0.1, 1.0); // Left curve, made longer
leafShape.bezierCurveTo(-0.2, 0.6, -0.1, 0.3, 0, 0); // Bottom curve, adjusted for longer shape
const leafGeometry = new THREE.ShapeGeometry(leafShape);
const leafMaterial = new THREE.MeshStandardMaterial({
color: 0x228B22,
side: THREE.DoubleSide,
roughness: 0.7,
metalness: 0.1
});
// Create two leaves
for (let i = 0; i < 2; i++) {
const leaf = new THREE.Mesh(leafGeometry, leafMaterial);
leaf.position.y = 0.5;
leaf.scale.set(0.2, 0.8, 0.2); // Thinner and longer leaves
// Position leaves on opposite sides
leaf.rotation.z = (i === 0 ? -0.2 : 0.2); // Slight angle outward
leaf.rotation.x = Math.PI / 8; // Less tilt for more upright position
// Add subtle random variation
leaf.rotation.z += (Math.random() - 0.5) * 0.1;
leaf.rotation.x += (Math.random() - 0.5) * 0.1;
leavesGroup.add(leaf);
}
bed.carrotModel.add(leavesGroup);
// Create a group for all 9 carrot models
const carrotsGroup = new THREE.Group();
// Create 3x3 grid of carrots
for (let row = -1; row <= 1; row++) {
for (let col = -1; col <= 1; col++) {
const carrotInstance = bed.carrotModel.clone();
// Position each carrot in the grid
carrotInstance.position.set(
col * 1.0, // Spread on X axis
0.25, // Height above bed
row * 1.0 // Spread on Z axis
);
// Add slight random rotation variation for natural look
carrotInstance.rotation.y = (Math.random() - 0.5) * 0.2;
carrotsGroup.add(carrotInstance);
}
}
bed.carrotModels = carrotsGroup; // Store the group of carrots
bed.mesh.add(carrotsGroup);
}
// Scale based on growth percentage
if (growthPercentage >= 33 && growthPercentage < 66) {
scale = 0.3; // Small model
} else if (growthPercentage >= 66 && growthPercentage < 100) {
scale = 0.6; // Medium model
} else {
scale = 1.0; // Large model (100%)
}
if (bed.carrotModels) {
bed.carrotModels.children.forEach(carrot => {
carrot.scale.set(scale, scale, scale);
});
}
}
Основные компоненты кода:
Инициализация:
Код загружает модули Three.js, создает загружающий экран и инициализирует переменные, такие как музыкальный фон и стартовые деньги игрока.
Сцена и камера:
Создается сцена, камера и рендерер. Камера позволяет пользователю смотреть на 3D-объекты из различных углов.
Постобработка:
Используются эффекты постобработки для улучшения визуального качества, такие как размытие, антиалиасинг и другие.
Окружающая среда:
Создается небесная сфера с кастомными шейдерами для улучшения визуальной составляющей, а также добавляются источники света (направленный и полусферический свет).
Создание "земляных" участков:
Класс VegetableBed создаёт и управляет участками земли, куда можно высаживать семена (в данный момент — морковь).
Интерактивность:
Интегрированы слушатели событий для взаимодействия с землей, включая покупку новых участков и высадку семян. Меню с контекстными действиями позволяет игроку взаимодействовать с объектами в сцене.
Визуализация роста растений:
В зависимости от времени роста моркови, меняется их масштаб для отображения разных стадий роста.
Управление с помощью мобильных и клавиатурных контроллеров:
Интеграция управления через кнопки на экране и клавиши клавиатуры (WASD и стрелки) для движений камеры.
Как это работает:
При загрузке страницы отображается экран загрузки, который обновляется по мере загрузки ресурсов (текстур, моделей и музыки).
После полной загрузки, приложение демонстрирует 3D-сцену с возможностью взаимодействия: игрок может сажать семена, собирать урожай и управлять участками земли.
Используются различные механики для управления состоянием растительности (время роста, смена стадий и так далее).
Заключение:
Код предоставляет функционал для создания простого симулятора/игры, основанной на системе "выращивания" с элементами 3D визуализации и постобработки, используя мощные инструменты Three.js.