-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
423 lines (349 loc) · 18.1 KB
/
script.js
File metadata and controls
423 lines (349 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Global variables
let scene, camera, renderer, terrain, audioContext, analyser, dataArray;
let audioSource, audioElement, microphone, microphoneStream;
let isPlaying = false, isMicrophoneActive = false;
let frameCount = 0, lastTime = Date.now();
let terrainGeometry, terrainMaterial;
let cameraAngle = 0;
const terrainSize = 100;
const terrainSegments = 64;
// Initialize Three.js scene
function initThreeJS() {
const container = document.getElementById('container');
// Scene setup
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x000033, 50, 200);
// Camera setup
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 30, 50);
camera.lookAt(0, 0, 0);
// Renderer setup
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000022, 0.8);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
// Create terrain
createTerrain();
// Add lighting
addLighting();
// Add particles
addParticleSystem();
// Start render loop
animate();
}
function createTerrain() {
terrainGeometry = new THREE.PlaneGeometry(terrainSize, terrainSize, terrainSegments, terrainSegments);
terrainGeometry.rotateX(-Math.PI / 2);
// Create custom shader material
terrainMaterial = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
audioData: { value: new THREE.DataTexture(new Uint8Array(256), 256, 1, THREE.RedFormat) },
colorIntensity: { value: 0.75 }
},
vertexShader: `
uniform float time;
uniform sampler2D audioData;
varying vec3 vPosition;
varying vec3 vNormal;
varying float vAudioInfluence;
void main() {
vPosition = position;
// Sample audio data based on position
float audioSample = texture2D(audioData, vec2((position.x + 50.0) / 100.0, 0.5)).r;
vAudioInfluence = audioSample;
// Create base wave motion
float wave1 = sin(position.x * 0.1 + time) * 2.0;
float wave2 = cos(position.z * 0.1 + time * 0.7) * 1.5;
// Apply audio influence
float audioHeight = audioSample * 20.0;
vec3 newPosition = position;
newPosition.y += wave1 + wave2 + audioHeight;
vNormal = normalize(normalMatrix * normal);
gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
}
`,
fragmentShader: `
uniform float time;
uniform float colorIntensity;
varying vec3 vPosition;
varying vec3 vNormal;
varying float vAudioInfluence;
void main() {
// Create dynamic colors based on audio and position
float r = sin(vPosition.x * 0.1 + time + vAudioInfluence * 10.0) * 0.5 + 0.5;
float g = cos(vPosition.z * 0.1 + time * 0.7 + vAudioInfluence * 8.0) * 0.5 + 0.5;
float b = sin(time + vAudioInfluence * 6.0) * 0.5 + 0.5;
// Apply audio influence to brightness
float brightness = 0.3 + vAudioInfluence * colorIntensity;
vec3 color = vec3(r, g, b) * brightness;
// Add fresnel-like effect
float fresnel = pow(1.0 - dot(vNormal, vec3(0.0, 1.0, 0.0)), 2.0);
color += fresnel * vec3(0.0, 0.5, 1.0) * vAudioInfluence;
gl_FragColor = vec4(color, 1.0);
}
`,
wireframe: false,
side: THREE.DoubleSide
});
terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrain.receiveShadow = true;
scene.add(terrain);
}
function addLighting() {
// Ambient light
const ambientLight = new THREE.AmbientLight(0x404040, 0.4);
scene.add(ambientLight);
// Directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(50, 100, 50);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
scene.add(directionalLight);
// Point lights that react to audio
for (let i = 0; i < 3; i++) {
const light = new THREE.PointLight(0xff00ff, 1, 100);
light.position.set(
(Math.random() - 0.5) * 100,
20,
(Math.random() - 0.5) * 100
);
light.userData = { originalIntensity: 1, phase: i * Math.PI * 0.67 };
scene.add(light);
}
}
function addParticleSystem() {
const particleCount = 1000;
const particles = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
const colors = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount; i++) {
positions[i * 3] = (Math.random() - 0.5) * 200;
positions[i * 3 + 1] = Math.random() * 100;
positions[i * 3 + 2] = (Math.random() - 0.5) * 200;
colors[i * 3] = Math.random();
colors[i * 3 + 1] = Math.random();
colors[i * 3 + 2] = Math.random();
}
particles.setAttribute('position', new THREE.BufferAttribute(positions, 3));
particles.setAttribute('color', new THREE.BufferAttribute(colors, 3));
const particleMaterial = new THREE.PointsMaterial({
size: 2,
vertexColors: true,
transparent: true,
opacity: 0.6
});
const particleSystem = new THREE.Points(particles, particleMaterial);
particleSystem.userData = { originalPositions: positions.slice() };
scene.add(particleSystem);
}
// Audio setup
function initAudio() {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
dataArray = new Uint8Array(analyser.frequencyBinCount);
// Create spectrum visualizer bars
const spectrum = document.getElementById('spectrum');
for (let i = 0; i < analyser.frequencyBinCount; i++) {
const bar = document.createElement('div');
bar.className = 'spectrum-bar';
spectrum.appendChild(bar);
}
}
// Generate procedural demo audio
function generateDemoAudio() {
if (!audioContext) initAudio();
const duration = 30; // 30 seconds
const sampleRate = audioContext.sampleRate;
const buffer = audioContext.createBuffer(1, duration * sampleRate, sampleRate);
const data = buffer.getChannelData(0);
// Generate complex harmonic content
for (let i = 0; i < data.length; i++) {
const t = i / sampleRate;
let sample = 0;
// Base frequencies with evolving patterns
sample += Math.sin(2 * Math.PI * 220 * t) * Math.sin(t * 0.5) * 0.3;
sample += Math.sin(2 * Math.PI * 330 * t) * Math.cos(t * 0.3) * 0.2;
sample += Math.sin(2 * Math.PI * 440 * t) * Math.sin(t * 0.7) * 0.25;
// Add some rhythm
sample *= (Math.sin(t * 8) > 0) ? 1 : 0.3;
// Add evolving harmonics
for (let h = 2; h <= 5; h++) {
sample += Math.sin(2 * Math.PI * 220 * h * t) * Math.sin(t * h * 0.1) * (0.1 / h);
}
data[i] = sample * 0.3;
}
startAudioBuffer(buffer);
document.getElementById('trackInfo').textContent = 'Procedural Demo';
}
function startAudioBuffer(buffer) {
if (audioSource) {
audioSource.stop();
}
audioSource = audioContext.createBufferSource();
audioSource.buffer = buffer;
audioSource.loop = true;
audioSource.connect(analyser);
analyser.connect(audioContext.destination);
audioSource.start();
isPlaying = true;
}
// File audio handling
document.getElementById('audioFile').addEventListener('change', handleAudioFile);
function handleAudioFile(event) {
const file = event.target.files[0];
if (!file) return;
if (!audioContext) initAudio();
const reader = new FileReader();
reader.onload = function(e) {
audioContext.decodeAudioData(e.target.result)
.then(buffer => {
startAudioBuffer(buffer);
document.getElementById('trackInfo').textContent = file.name;
})
.catch(err => console.error('Error decoding audio:', err));
};
reader.readAsArrayBuffer(file);
}
// Microphone handling
function toggleMicrophone() {
if (!isMicrophoneActive) {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
if (!audioContext) initAudio();
microphoneStream = stream;
microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(analyser);
isMicrophoneActive = true;
isPlaying = true;
document.getElementById('trackInfo').textContent = 'Microphone Input';
})
.catch(err => console.error('Microphone access denied:', err));
} else {
if (microphoneStream) {
microphoneStream.getTracks().forEach(track => track.stop());
}
if (microphone) {
microphone.disconnect();
}
isMicrophoneActive = false;
isPlaying = false;
document.getElementById('trackInfo').textContent = 'No audio';
}
}
// Control handlers
document.getElementById('sensitivity').addEventListener('input', (e) => {
document.getElementById('sensitivityVal').textContent = e.target.value;
});
document.getElementById('colorIntensity').addEventListener('input', (e) => {
const value = e.target.value / 100;
document.getElementById('colorIntensityVal').textContent = e.target.value;
if (terrainMaterial) {
terrainMaterial.uniforms.colorIntensity.value = value;
}
});
document.getElementById('cameraSpeed').addEventListener('input', (e) => {
document.getElementById('cameraSpeedVal').textContent = e.target.value;
});
function toggleWaveform() {
const waveform = document.getElementById('waveformContainer');
waveform.style.display = waveform.style.display === 'none' ? 'block' : 'none';
}
function resetCamera() {
camera.position.set(0, 30, 50);
camera.lookAt(0, 0, 0);
cameraAngle = 0;
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
const currentTime = Date.now();
if (frameCount % 60 === 0) {
const fps = Math.round(1000 / (currentTime - lastTime) * 60);
document.getElementById('fps').textContent = fps;
lastTime = currentTime;
}
frameCount++;
if (isPlaying && analyser) {
analyser.getByteFrequencyData(dataArray);
updateVisualization();
}
// Update camera movement
const cameraSpeed = parseFloat(document.getElementById('cameraSpeed').value);
cameraAngle += 0.005 * cameraSpeed;
camera.position.x = Math.sin(cameraAngle) * 60;
camera.position.z = Math.cos(cameraAngle) * 60;
camera.lookAt(0, 0, 0);
// Update shader time
if (terrainMaterial) {
terrainMaterial.uniforms.time.value = currentTime * 0.001;
}
renderer.render(scene, camera);
}
function updateVisualization() {
const sensitivity = parseFloat(document.getElementById('sensitivity').value) / 50;
// Update terrain with audio data
if (terrainMaterial && dataArray) {
const audioTexture = new THREE.DataTexture(dataArray, dataArray.length, 1, THREE.RedFormat);
audioTexture.needsUpdate = true;
terrainMaterial.uniforms.audioData.value = audioTexture;
}
// Update spectrum bars
const spectrumBars = document.querySelectorAll('.spectrum-bar');
let totalVolume = 0;
let dominantFreq = 0;
let maxAmplitude = 0;
for (let i = 0; i < Math.min(dataArray.length, spectrumBars.length); i++) {
const amplitude = dataArray[i] / 255;
spectrumBars[i].style.height = (amplitude * 60) + 'px';
spectrumBars[i].style.opacity = amplitude;
totalVolume += amplitude;
if (amplitude > maxAmplitude) {
maxAmplitude = amplitude;
dominantFreq = (i / dataArray.length) * (audioContext.sampleRate / 2);
}
}
// Update info display
document.getElementById('volume').textContent = Math.round((totalVolume / dataArray.length) * 100) + '%';
document.getElementById('frequency').textContent = Math.round(dominantFreq) + ' Hz';
// Update point lights
scene.children.forEach(child => {
if (child instanceof THREE.PointLight && child.userData.originalIntensity !== undefined) {
const audioInfluence = (totalVolume / dataArray.length) * sensitivity;
child.intensity = child.userData.originalIntensity + audioInfluence * 3;
// Color cycling based on audio
const hue = (Date.now() * 0.001 + child.userData.phase + audioInfluence * 10) % 1;
child.color.setHSL(hue, 1, 0.5);
}
});
// Update particles
const particles = scene.children.find(child => child instanceof THREE.Points);
if (particles) {
const positions = particles.geometry.attributes.position;
const originalPositions = particles.userData.originalPositions;
for (let i = 0; i < positions.count; i++) {
const audioIndex = Math.floor((i / positions.count) * dataArray.length);
const audioValue = dataArray[audioIndex] / 255 * sensitivity;
positions.setY(i, originalPositions[i * 3 + 1] + audioValue * 20);
}
positions.needsUpdate = true;
}
}
// Window resize handler
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Initialize everything
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
document.getElementById('loading').style.display = 'none';
initThreeJS();
initAudio();
}, 1000);
});