File size: 10,544 Bytes
4e95a36
22c5fe9
197e07d
22c5fe9
f4a7c39
929729e
 
 
 
22c5fe9
2027e8d
e5d4f4b
2027e8d
faf5ff0
 
2027e8d
 
7bf55c6
2027e8d
 
 
 
 
 
7fe6445
2027e8d
e5d4f4b
 
2027e8d
e5d4f4b
 
 
 
 
2027e8d
 
7bf55c6
2027e8d
 
929729e
 
101fb89
929729e
 
 
 
 
 
 
 
 
 
 
 
 
2027e8d
929729e
 
 
 
2027e8d
929729e
e5d4f4b
 
 
 
faf5ff0
101fb89
929729e
101fb89
faf5ff0
7bf55c6
e5d4f4b
101fb89
e5d4f4b
7bf55c6
 
faf5ff0
929729e
 
e5d4f4b
929729e
faf5ff0
7bf55c6
 
e5d4f4b
 
101fb89
 
 
7bf55c6
101fb89
929729e
 
2027e8d
929729e
 
2027e8d
7bf55c6
929729e
 
 
 
1438dc1
e5d4f4b
 
 
 
 
 
 
 
 
 
 
317d7bf
929729e
e5d4f4b
 
 
317d7bf
e5d4f4b
 
 
2027e8d
101fb89
e5d4f4b
929729e
 
 
 
 
 
101fb89
e5d4f4b
101fb89
e5d4f4b
929729e
101fb89
 
 
e5d4f4b
 
 
 
 
 
 
 
929729e
7bf55c6
e5d4f4b
 
7bf55c6
929729e
e5d4f4b
7bf55c6
 
929729e
e5d4f4b
7bf55c6
e5d4f4b
 
 
101fb89
e5d4f4b
 
 
7bf55c6
e5d4f4b
 
 
101fb89
e5d4f4b
 
 
929729e
e5d4f4b
 
 
 
 
929729e
7bf55c6
 
101fb89
7bf55c6
e5d4f4b
 
7bf55c6
 
e5d4f4b
 
101fb89
7bf55c6
 
e5d4f4b
 
 
 
 
 
929729e
7bf55c6
929729e
 
 
 
 
 
 
 
 
 
e5d4f4b
7bf55c6
e5d4f4b
929729e
faf5ff0
2027e8d
7bf55c6
2027e8d
7760b04
929729e
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf55c6
317d7bf
101fb89
e5d4f4b
 
7fe6445
7bf55c6
317d7bf
1438dc1
2027e8d
101fb89
 
e5d4f4b
 
 
317d7bf
101fb89
e5d4f4b
2027e8d
1438dc1
929729e
 
1438dc1
 
7760b04
1438dc1
 
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
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import comb
import time
import threading
from queue import Queue
import io
from PIL import Image

# ============================================================
# FUNÇÕES MATEMÁTICAS (idênticas ao original)
# ============================================================

def bernstein_poly(i, n, t):
    return comb(n, i) * (t**i) * ((1-t)**(n-i))

def bezier_curve(points, n_times=20):
    points = np.array(points)
    t = np.linspace(0, 1, n_times)
    n = len(points) - 1
    curve = np.zeros((n_times, 3))
    for i, p in enumerate(points):
        curve += np.outer(bernstein_poly(i, n, t), p)
    return curve.T

def quantize(value, multiple=4):
    return multiple * round(value / multiple)

def learn_from_echo(echo_points):
    if len(echo_points) < 2:
        return np.array([0, 0, 0])
    p1, p2 = np.array(echo_points[0]), np.array(echo_points[-1])
    return p2 - p1

# ============================================================
# SIMULAÇÃO COM RASTRO IDÊNTICO AO ORIGINAL + ESFERA TRANSPARENTE
# ============================================================

class CometSimulation:
    def __init__(self):
        self.queue = Queue(maxsize=2)
        self.running = False
        self.thread = None
        
    def start(self, camera_angle, auto_rotate):
        if not self.running:
            self.running = True
            self.thread = threading.Thread(
                target=self._run_simulation,
                args=(camera_angle, auto_rotate),
                daemon=True
            )
            self.thread.start()
        return self.queue
    
    def stop(self):
        self.running = False
        if self.thread:
            self.thread.join(timeout=1.0)
    
    def _run_simulation(self, camera_angle, auto_rotate):
        # Estado inicial (quantizado como no original)
        pos = np.array([quantize(0.), quantize(0.), quantize(0.)])
        inertia = np.array([quantize(10.), quantize(10.), quantize(10.)])
        history = [pos.tolist()]
        
        # Configuração da figura
        dpi = 100
        fig = plt.figure(figsize=(12, 8), dpi=dpi)
        
        # Layout: 3D à esquerda (2/3), painéis à direita (1/3)
        gs = fig.add_gridspec(2, 3, hspace=0.3, wspace=0.3)
        
        ax_3d = fig.add_subplot(gs[:, 0:2], projection='3d')
        ax_info = fig.add_subplot(gs[0, 2])   # estatísticas de inércia
        ax_stats = fig.add_subplot(gs[1, 2])  # posição atual
        
        bg_color = '#0a0a0a'
        fig.patch.set_facecolor(bg_color)
        for ax in [ax_3d, ax_info, ax_stats]:
            ax.set_facecolor(bg_color)
        
        # ========== ESFERA TRANSPARENTE (MELHORIA VISUAL) ==========
        # Malha da esfera – referência espacial sem poluir
        u = np.linspace(0, 2*np.pi, 20)
        v = np.linspace(0, np.pi, 15)
        sphere_x = 28 * np.outer(np.cos(u), np.sin(v))
        sphere_y = 28 * np.outer(np.sin(u), np.sin(v))
        sphere_z = 28 * np.outer(np.ones_like(u), np.cos(v))
        # ============================================================
        
        cycle = 0
        frame_global = 0
        
        while self.running:
            cycle += 1
            
            # Ângulo da câmera (com rotação automática opcional)
            if auto_rotate:
                current_angle = (camera_angle + frame_global * 0.8) % 360
            else:
                current_angle = camera_angle
            
            # Ponto atual é o último do histórico
            current_point = np.array(history[-1])
            
            # Gera novo alvo aleatório quantizado (igual ao original)
            random_target = np.random.rand(3) * 50 - 25
            target = np.array([quantize(v) for v in random_target])
            
            # Calcula trajetória Bézier
            control = current_point + inertia
            curve = bezier_curve([current_point, control, target], n_times=20)
            x_cycle, y_cycle, z_cycle = curve[0], curve[1], curve[2]
            
            # Atualiza histórico
            new_points = list(zip(x_cycle, y_cycle, z_cycle))
            history.extend([list(p) for p in new_points])
            history = history[-150:]  # max_trail_length = 150
            
            # Aprende inércia do eco (últimos 10 pontos)
            echo_points = history[-10:]
            inertia = learn_from_echo(echo_points)
            
            # Anima a curva
            for frame_idx in range(len(x_cycle)):
                if not self.running:
                    break
                    
                frame_global += 1
                
                ax_3d.clear()
                ax_info.clear()
                ax_stats.clear()
                
                # ===== CONFIGURAÇÃO 3D (igual ao original) =====
                ax_3d.set_facecolor(bg_color)
                ax_3d.xaxis.pane.fill = False
                ax_3d.yaxis.pane.fill = False
                ax_3d.zaxis.pane.fill = False
                ax_3d.grid(color='#222222', linestyle='--')
                ax_3d.view_init(elev=30., azim=current_angle)
                ax_3d.set_xlim(-30, 30)
                ax_3d.set_ylim(-30, 30)
                ax_3d.set_zlim(-30, 30)
                ax_3d.set_xticklabels([])
                ax_3d.set_yticklabels([])
                ax_3d.set_zticklabels([])
                
                # ========== DESENHA A ESFERA TRANSPARENTE ==========
                ax_3d.plot_wireframe(sphere_x, sphere_y, sphere_z, 
                                    color='#4488ff', alpha=0.1, linewidth=0.5)
                # ===================================================
                
                # ===== ELEMENTOS ESTÁTICOS (igual ao original) =====
                ax_3d.scatter(*current_point, s=150, c='lime', alpha=0.7)  # ponto inicial do ciclo
                ax_3d.scatter(*target, s=150, c='red', marker='X', alpha=0.9)  # alvo
                
                # ===== RASTRO IDÊNTICO AO ORIGINAL =====
                # Índices: últimos 12 pontos antes do frame atual
                trail_end = len(history) - len(x_cycle) + frame_idx
                trail_start = max(0, trail_end - 12)
                trail_segment = history[trail_start:trail_end+1]
                
                if len(trail_segment) > 1:
                    for i in range(len(trail_segment) - 1):
                        p1, p2 = trail_segment[i], trail_segment[i+1]
                        # Alpha = 0.8 * (i/12) – exatamente como no original
                        alpha = 0.8 * (i / 12)
                        ax_3d.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], 
                                  color='#ff4500', linewidth=4, alpha=alpha)
                
                # ===== AGENTE (laranja, igual ao original) =====
                ax_3d.plot([x_cycle[frame_idx]], [y_cycle[frame_idx]], [z_cycle[frame_idx]], 
                          'o', color='#ff4500', markersize=10, markeredgecolor='white')
                
                # ===== TEXTO INFO (igual ao original) =====
                info_text = f"Ciclo: {cycle}\nAlvo: {np.round(target)}"
                ax_3d.text2D(0.05, 0.95, info_text, transform=ax_3d.transAxes, 
                            color='white', fontsize=10,
                            bbox=dict(boxstyle='round', facecolor='#222222', alpha=0.7))
                
                # ===== PAINEL INFO (MELHORIA) =====
                ax_info.set_title('📊 INÉRCIA', color='white', fontsize=11)
                ax_info.axis('off')
                inertia_text = f"""Vetor:
({inertia[0]:.1f}, {inertia[1]:.1f}, {inertia[2]:.1f})

Histórico: {len(history)} pontos
Eco: {len(echo_points)} pontos"""
                ax_info.text(0.1, 0.8, inertia_text, transform=ax_info.transAxes,
                            color='#ffaa00', fontsize=9, verticalalignment='top')
                
                # ===== PAINEL STATS (MELHORIA) =====
                ax_stats.set_title('📍 POSIÇÃO', color='white', fontsize=11)
                ax_stats.axis('off')
                pos_text = f"""X: {x_cycle[frame_idx]:.1f}
Y: {y_cycle[frame_idx]:.1f}
Z: {z_cycle[frame_idx]:.1f}"""
                ax_stats.text(0.1, 0.6, pos_text, transform=ax_stats.transAxes,
                             color='#88ccff', fontsize=12, fontweight='bold')
                
                # Renderiza e envia
                fig.canvas.draw()
                buf = io.BytesIO()
                fig.savefig(buf, format='png', dpi=dpi, 
                           facecolor=bg_color, bbox_inches='tight',
                           pad_inches=0.1)
                buf.seek(0)
                
                if self.queue.qsize() < 2:
                    self.queue.put(buf)
                
                time.sleep(0.01)  # igual ao original
            
            # Prepara próximo ciclo
            pos = target

# ============================================================
# INTERFACE GRADIO (COM ROTAÇÃO E PAINÉIS)
# ============================================================

simulation = CometSimulation()

def get_frame(camera_angle, auto_rotate):
    queue = simulation.start(camera_angle, auto_rotate)
    try:
        while True:
            buf = queue.get(timeout=1.0)
            img = Image.open(buf)
            yield np.array(img)
    except Exception as e:
        print(f"Error: {e}")
    finally:
        simulation.stop()

with gr.Blocks(theme=gr.themes.Base(primary_hue="purple", secondary_hue="orange")) as demo:
    gr.HTML("""
    <div style="text-align: center; margin-bottom: 15px;">
        <h1 style="color: #ff4500; font-size: 2.2rem; margin: 0;">
            ✨ CAUSAL CONVERGENCE SIMULATOR ✨
        </h1>
        <p style="color: #cccccc;">rastro original • esfera transparente • estatísticas</p>
    </div>
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            camera = gr.Slider(-180, 180, value=25, label="🎥 Camera Angle (Azimuth)")
            auto_rotate = gr.Checkbox(label="🌀 Auto-rotate", value=True)
            btn = gr.Button("🚀 START SIMULATION", variant="primary", size="lg")
        
        with gr.Column(scale=3):
            output = gr.Image(label="Real-Time Visualization", height=600)
    
    btn.click(
        fn=get_frame,
        inputs=[camera, auto_rotate],
        outputs=output
    )

if __name__ == "__main__":
    demo.launch()