-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQubitVisualizer.jsx
More file actions
346 lines (310 loc) · 11.9 KB
/
QubitVisualizer.jsx
File metadata and controls
346 lines (310 loc) · 11.9 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
// src/QubitVisualizer.jsx
import React, { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
/**
* QubitVisual: visual estilo 'esfera com linhas de campo' + plano grade distorcido
* - interação com mouse (OrbitControls)
* - animação automática
* - HUD com probabilidades (verde->red)
*/
export default function QubitVisualizer() {
const mountRef = useRef(null);
const rafRef = useRef(null);
const [probabilities, setProbabilities] = useState({ p0: 1, p1: 0 });
useEffect(() => {
const container = mountRef.current;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x000010, 0.06);
// Camera + renderer
const camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
0.1,
200
);
camera.position.set(4, 2.8, 5);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
container.appendChild(renderer.domElement);
// Controls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.rotateSpeed = 0.6;
controls.minDistance = 2;
controls.maxDistance = 12;
// Lights
const ambient = new THREE.AmbientLight(0xffffff, 0.35);
scene.add(ambient);
const key = new THREE.DirectionalLight(0xffffff, 0.9);
key.position.set(5, 6, 3);
scene.add(key);
const fill = new THREE.PointLight(0x66ccff, 0.25, 20);
fill.position.set(-4, 2, -6);
scene.add(fill);
// --- Plano grade distorcido (shader) ---
const planeSize = 40;
const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize, 256, 256);
const planeMat = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
color: { value: new THREE.Color(0x07122a) },
gridColor: { value: new THREE.Color(0x1fb8ff) },
amp: { value: 0.25 },
},
vertexShader: `
uniform float time;
uniform float amp;
varying vec2 vUv;
varying float vWave;
void main() {
vUv = uv;
vec3 pos = position;
// wave displacement, stronger nearer center
float r = length(position.xz) / 10.0;
pos.z += sin((position.x + time*0.8)*0.6 + r*5.0) * amp * (1.0 - r);
pos.y += cos((position.y + time*0.6)*0.5 + r*4.0) * amp * (1.0 - r);
vWave = (1.0 - r);
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
fragmentShader: `
uniform vec3 color;
uniform vec3 gridColor;
varying vec2 vUv;
varying float vWave;
void main() {
// grid lines: create two scales
vec2 gv = fract(vUv * 20.0) - 0.5;
float line1 = 1.0 - smoothstep(0.0, 0.02, length(gv));
vec2 gv2 = fract(vUv * 6.0) - 0.5;
float line2 = 1.0 - smoothstep(0.0, 0.01, length(gv2));
float grid = max(line1 * 0.9, line2 * 0.4);
// fade with distance from center to avoid clutter
float fade = smoothstep(0.9, 0.0, length(vUv - 0.5));
vec3 base = mix(vec3(0.01,0.02,0.04), color, 0.9);
vec3 gcol = gridColor * (0.6 + 0.6 * vWave);
vec3 outCol = mix(base, gcol, grid * fade);
gl_FragColor = vec4(outCol, 1.0);
}
`,
transparent: false,
side: THREE.DoubleSide,
});
const plane = new THREE.Mesh(planeGeo, planeMat);
plane.rotation.x = -Math.PI / 2;
plane.position.y = -1.2;
scene.add(plane);
// --- Núcleo emissivo (centro brilhante) ---
const coreGeo = new THREE.SphereGeometry(0.12, 32, 32);
const coreMat = new THREE.MeshBasicMaterial({ color: 0xffcf66 });
const coreMesh = new THREE.Mesh(coreGeo, coreMat);
scene.add(coreMesh);
const coreLight = new THREE.PointLight(0xffcf66, 1.6, 6, 2);
coreLight.position.set(0, 0, 0);
scene.add(coreLight);
// --- Esfera 'casca' translúcida com leve iridescência ---
const shellGeo = new THREE.SphereGeometry(1, 96, 96);
const shellMat = new THREE.MeshPhysicalMaterial({
color: 0x0b6bff,
metalness: 0.1,
roughness: 0.25,
transmission: 0.8, // glass-like
thickness: 0.6,
envMapIntensity: 0.6,
clearcoat: 0.6,
clearcoatRoughness: 0.2,
opacity: 0.95,
transparent: true,
side: THREE.DoubleSide,
});
const shell = new THREE.Mesh(shellGeo, shellMat);
scene.add(shell);
// --- Linhas de campo brilhantes (curvas ao redor da esfera) ---
const linesGroup = new THREE.Group();
const lineCount = 28;
const lineMats = [];
for (let i = 0; i < lineCount; i++) {
const theta = (i / lineCount) * Math.PI; // polar
const phiOff = (i % 7) * 0.7;
const pts = [];
const segments = 180;
for (let s = 0; s <= segments; s++) {
const t = (s / segments) * Math.PI * 2;
// parametric toroidal-ish loop around sphere; distort to look like field lines
const r = 1.02 + 0.02 * Math.sin(t * 3 + i);
const x = r * Math.sin(theta) * Math.cos(t + phiOff);
const y = r * Math.cos(theta) * Math.cos(t * 0.5 + i * 0.1);
const z = r * Math.sin(theta) * Math.sin(t + phiOff);
pts.push(new THREE.Vector3(x, y, z));
}
const geom = new THREE.BufferGeometry().setFromPoints(pts);
const mat = new THREE.LineBasicMaterial({
color: new THREE.Color().setHSL(0.08 + 0.6 * (i / lineCount), 0.9, 0.6),
transparent: true,
opacity: 0.9,
blending: THREE.AdditiveBlending,
toneMapped: false,
});
lineMats.push({ geom, mat });
const line = new THREE.Line(geom, mat);
linesGroup.add(line);
}
scene.add(linesGroup);
// small glow ring near equator (subtle)
const ringGeo = new THREE.RingGeometry(1.05, 1.08, 64);
const ringMat = new THREE.MeshBasicMaterial({ color: 0x66e6ff, transparent: true, opacity: 0.06, side: THREE.DoubleSide });
const ring = new THREE.Mesh(ringGeo, ringMat);
ring.rotation.x = Math.PI / 2;
scene.add(ring);
// --- marcador na superfície (ponta do vetor) ---
const markerGeo = new THREE.SphereGeometry(0.045, 16, 16);
const markerMat = new THREE.MeshStandardMaterial({ color: 0xffee99, emissive: 0xffaa66, emissiveIntensity: 0.9 });
const marker = new THREE.Mesh(markerGeo, markerMat);
scene.add(marker);
// Arrow: build shaft+cone for nicer appearance
const shaftGeo = new THREE.CylinderGeometry(0.02, 0.02, 0.8, 12);
const shaftMat = new THREE.MeshStandardMaterial({ color: 0xffcc66, metalness: 0.2, roughness: 0.4 });
const shaft = new THREE.Mesh(shaftGeo, shaftMat);
shaft.position.set(0, 0.4, 0);
const coneGeo = new THREE.ConeGeometry(0.05, 0.16, 12);
const coneMat = new THREE.MeshStandardMaterial({ color: 0xff8855, emissive: 0xff8855, emissiveIntensity: 0.6 });
const cone = new THREE.Mesh(coneGeo, coneMat);
cone.position.set(0, 0.88, 0);
const arrowGroup = new THREE.Group();
arrowGroup.add(shaft);
arrowGroup.add(cone);
scene.add(arrowGroup);
// helper quaternions for smooth rotation
const qTarget = new THREE.Quaternion();
const qTemp = new THREE.Quaternion();
// animation state
let time = 0;
// safe normalize
const safeVec = (x, y, z) => {
const v = new THREE.Vector3(x, y, z);
if (!isFinite(x + y + z) || v.lengthSq() < 1e-9) return new THREE.Vector3(0, 1, 0);
return v.normalize();
};
function animate() {
rafRef.current = requestAnimationFrame(animate);
time += 0.01;
// ** qubit angles generated smoothly **
const theta = THREE.MathUtils.clamp(
Math.PI / 2 + 0.45 * Math.sin(time * 0.7) + 0.18 * Math.sin(time * 1.9 + 1.2),
0.01,
Math.PI - 0.01
);
const phi = time * 0.6;
// Cartesian
const tx = Math.sin(theta) * Math.cos(phi);
const ty = Math.cos(theta);
const tz = Math.sin(theta) * Math.sin(phi);
// update HUD probabilities
const p0 = Math.pow(Math.cos(theta / 2), 2);
const p1 = 1 - p0;
setProbabilities({ p0, p1 });
// point on sphere surface for marker
marker.position.copy(new THREE.Vector3(tx, ty, tz).multiplyScalar(1.01));
// orient arrowGroup: our arrow points +Y; rotate +Y to targetVec
const targetVec = safeVec(tx, ty, tz);
qTemp.setFromUnitVectors(new THREE.Vector3(0, 1, 0), targetVec);
THREE.Quaternion.slerp(arrowGroup.quaternion, qTemp, qTarget, 0.14);
arrowGroup.quaternion.copy(qTarget);
// also position arrowGroup at origin
arrowGroup.position.set(0, 0, 0);
// rotate field lines slowly for motion
linesGroup.rotation.y = Math.sin(time * 0.2) * 0.15;
linesGroup.rotation.x = Math.cos(time * 0.13) * 0.08;
// animate plane shader uniform
planeMat.uniforms.time.value = time * 0.6;
// gentle core pulse
const pulse = 1.0 + 0.12 * Math.sin(time * 3.2);
coreMesh.scale.set(pulse, pulse, pulse);
coreLight.intensity = 1.4 + 0.6 * Math.abs(Math.sin(time * 3.2));
controls.update();
renderer.render(scene, camera);
}
animate();
// Resize
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", onResize, { passive: true });
// Cleanup and dispose
return () => {
cancelAnimationFrame(rafRef.current);
window.removeEventListener("resize", onResize);
// dispose geometries & materials
shellGeo.dispose?.();
shellMat.dispose?.();
planeGeo.dispose();
planeMat.dispose();
coreGeo.dispose?.();
coreMat.dispose?.();
shaftGeo.dispose?.();
shaftMat.dispose?.();
coneGeo.dispose?.();
coneMat.dispose?.();
markerGeo.dispose?.();
markerMat.dispose?.();
particles && particles.geometry && particles.geometry.dispose?.();
lineMats.forEach(({ geom, mat }) => {
geom.dispose();
mat.dispose();
});
controls.dispose();
renderer.dispose();
if (container.contains(renderer.domElement)) container.removeChild(renderer.domElement);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// HUD color gradient green->red
function getColor(p0) {
const r = Math.round(255 * (1 - p0));
const g = Math.round(255 * p0);
return `rgb(${r},${g},0)`;
}
return (
<div style={{ position: "relative", width: "100vw", height: "100vh", overflow: "hidden" }}>
{/* HUD */}
<div
style={{
position: "absolute",
left: 18,
top: 18,
zIndex: 20,
background: "rgba(0,0,0,0.6)",
color: "#fff",
padding: "12px",
borderRadius: 10,
fontFamily: "monospace",
fontSize: 13,
minWidth: 220,
}}
>
<div style={{ fontWeight: 700, marginBottom: 6 }}>Qubit Visualizer</div>
<div>
<span style={{ color: getColor(probabilities.p0), fontWeight: 600 }}>
|0⟩: {(probabilities.p0 * 100).toFixed(2)}%
</span>
</div>
<div>
<span style={{ color: getColor(probabilities.p1), fontWeight: 600 }}>
|1⟩: {(probabilities.p1 * 100).toFixed(2)}%
</span>
</div>
<div style={{ marginTop: 8, color: "#cfcfcf", fontSize: 12 }}>
O ponto brilhante indica o estado do qubit na superfície (esfera). As linhas representam
campos/órbitas — o vetor muda automaticamente.
</div>
</div>
<div ref={mountRef} style={{ width: "100%", height: "100%" }} />
</div>
);
}