File size: 8,849 Bytes
7700c61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
__version__ = "1.5.5"

import math
from typing import Dict, List, Tuple

import plotly.graph_objects as go

# Colour mapping by chord quality (triads/7ths/sus/etc.)
QUALITY_COLOR = {
    "maj": "#2563eb",
    "min": "#16a34a",
    "dim": "#dc2626",
    "aug": "#a855f7",
    "sus2": "#0ea5e9",
    "sus4": "#0ea5e9",
    "6": "#f59e0b",
    "m6": "#f59e0b",
    "maj7": "#1d4ed8",
    "7": "#ea580c",
    "m7": "#15803d",
    "m(maj7)": "#7c3aed",
    "ø7": "#b91c1c",
    "dim7": "#991b1b",
    "aug7": "#9333ea",
}

def pc_angle(pc: int) -> float:
    return (pc % 12) * (2 * math.pi / 12)



def _chord_colour(chord: Dict) -> str:
    return QUALITY_COLOR.get(chord.get("quality",""), "#334155")

def chord_helix_figure(chord: Dict, show_labels: bool = True, show_connections: bool = True) -> go.Figure:
    # Spiral guide configuration (must be defined before use)
    oct_min, oct_max = 3, 7
    steps_per_oct = 12
    y_step = 0.10  # vertical rise per semitone

    pcs: List[int] = chord["pitch_classes"]
    notes: List[str] = chord["notes"]
    midi: List[int] = chord["midi"]

    colour = _chord_colour(chord)

    # Helix geometry:
    # - Circular placement by pitch class (theta)
    # - Height is mapped to Y axis (pitch goes UP)
    r = 1.0
    # Pitch-spiral mapping helper (single source of truth)
    def pitch_to_xyz(pc: int, octave: int) -> tuple[float,float,float]:
        s = (octave - oct_min) * 12 + (pc % 12)
        turns = s / 12.0
        theta = pc_angle(pc) + (2 * math.pi) * turns
        x = r * math.cos(theta)
        z = r * math.sin(theta)
        y = (oct_min - 3) + s * y_step
        return x, y, z

    xs, ys, zs, labels = [], [], [], []    # Chord nodes: plot chord tones ON the rising pitch spiral (same mapping as the guide)
    for pc, note, m in zip(pcs, notes, midi[:len(pcs)]):
        octave = (m // 12) - 1
        x, y, z = pitch_to_xyz(pc, octave)
        xs.append(x); ys.append(y); zs.append(z)
        labels.append(note)
    fig = go.Figure()

    fig.add_trace(go.Scatter3d(
        x=xs, y=ys, z=zs,
        mode="markers+text" if show_labels else "markers",
        text=labels if show_labels else None,
        textposition="top center",
        marker=dict(size=8, color=colour),
        name="Chord tones",
        hovertemplate="Note: %{text}<br>x=%{x:.2f}, y=%{y:.2f}, z=%{z:.2f}<extra></extra>",
    ))

    # Connection lines (coloured)
    if show_connections and len(xs) >= 2:
        xline = xs + [xs[0]]
        yline = ys + [ys[0]]
        zline = zs + [zs[0]]
        fig.add_trace(go.Scatter3d(
            x=xline, y=yline, z=zline,
            mode="lines",
            line=dict(color=colour, width=6),
            name="Chord shape",
            hoverinfo="skip",
            opacity=0.9
        ))

        # Fill the area between chord nodes (semi-transparent) and project onto a reference plane
        if len(xs) >= 3:
            # 3D fill (fan triangulation)
            i = [0] * (len(xs) - 2)
            j = list(range(1, len(xs) - 1))
            k = list(range(2, len(xs)))
            fig.add_trace(go.Mesh3d(
                x=xs, y=ys, z=zs,
                i=i, j=j, k=k,
                color=colour,
                opacity=0.20,
                name="Chord fill",
                hoverinfo="skip",
            ))

        # Projection plane is y = min(ys) - small padding
        y0 = min(ys) - 0.35
        fig.add_trace(go.Mesh3d(
            x=xs,
            y=[y0 for _ in ys],
            z=zs,
            color=colour,
            opacity=0.18,
            name="Projection",
            hoverinfo="skip",
        ))

    # Reference helix: TRUE upward pitch spiral (continuous rise)
    spiral_x, spiral_y, spiral_z = [], [], []
    total_steps = (oct_max - oct_min) * steps_per_oct

    # Make the spiral visually curved by sampling between semitone steps
    substeps = 10  # higher = smoother curve (more points)
    for si in range(total_steps * substeps + 1):
        s = si / substeps  # fractional semitone steps
        turns = s / 12.0
        # Anchor phase to C=0 so the curve is smooth
        theta = pc_angle(0) + (2 * math.pi) * turns + (2 * math.pi) * ((s % 12) / 12.0)
        x = r * math.cos(theta)
        z = r * math.sin(theta)
        y = (oct_min - 3) + s * y_step
        spiral_x.append(x); spiral_y.append(y); spiral_z.append(z)
    fig.add_trace(go.Scatter3d(
        x=spiral_x, y=spiral_y, z=spiral_z,
        mode="lines",
        line=dict(color="#ffffff", width=4, dash="dot"),
        name="Pitch spiral",
        hoverinfo="skip",
        opacity=0.65
    ))

    # Labels: place one chromatic turn of labels on the spiral for readability
    prefer_sharps = bool(chord.get('prefer_sharps', True)) if isinstance(chord, dict) else True
    label_names = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"] if prefer_sharps else ["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"]

    lab_x, lab_y, lab_z, lab_t = [], [], [], []
    base_s = int(steps_per_oct * 1.5)  # mid-turn
    for pc in range(12):
        s = base_s + pc
        octave = oct_min + (s // 12)
        x, y, z = pitch_to_xyz(pc, octave)
        lab_x.append(x); lab_y.append(y); lab_z.append(z)
        lab_t.append(label_names[pc])

    fig.add_trace(go.Scatter3d(
        x=lab_x, y=lab_y, z=lab_z,
        mode="text",
        text=lab_t,
        textposition="middle center",
        textfont=dict(size=12, color="#ffffff"),
        name="Note labels",
        hoverinfo="skip",
        opacity=0.85
    ))

# Camera: slight elevation and centred; allow orbit (user can spin easily)
    fig.update_layout(
        margin=dict(l=0, r=0, t=10, b=0),
        scene=dict(
            bgcolor="rgba(0,0,0,0)",
            xaxis=dict(visible=False),
            yaxis=dict(title="Helix axis (upward)", showgrid=False),
            zaxis=dict(visible=False),
            
            aspectmode="data",
            camera=dict(
                eye=dict(x=2.2, y=1.6, z=1.2),
                up=dict(x=0, y=1, z=0),  # x-axis as "up" feel for rotation
            ),
        ),
        dragmode="orbit",
        height=540,
        legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),
    )
    return fig

def chord_helix_figure_overlays(chords: list[dict], active_idx: int | None = None, pulse: float = 1.0):
    """Render multiple chords over the same pitch spiral."""
    if not chords:
        return chord_helix_figure({"pitch_classes": [], "midi": [], "name": "No chord", "prefer_sharps": True})

    base = chord_helix_figure(chords[0])

    for i, ch in enumerate(chords):
        fig_i = chord_helix_figure(ch)
        for tr in fig_i.data:
            name = getattr(tr, "name", "") or ""
            if name in ("Pitch spiral", "Note labels"):
                continue

            is_active = (active_idx is not None and i == active_idx)

            # Marker highlight
            if getattr(tr, "mode", "") and "markers" in tr.mode and hasattr(tr, "marker"):
                tr.marker.size = (11 * pulse) if is_active else 7
                tr.marker.opacity = 1.0 if is_active else 0.55
                if hasattr(tr.marker, "line"):
                    tr.marker.line.width = 2 if is_active else 0

            # Glow ring around active chord
            if is_active and hasattr(tr, 'x') and tr.x is not None and len(tr.x) >= 3:
                try:
                    xs = [float(v) for v in tr.x]
                    ys = [float(v) for v in tr.y]
                    zs = [float(v) for v in tr.z]
                    cx = sum(xs) / len(xs)
                    cy = sum(ys) / len(ys)
                    cz = sum(zs) / len(zs)
                    r0 = max(( (x-cx)**2 + (z-cz)**2 )**0.5 for x,z in zip(xs,zs))
                    r1 = max(0.15, r0 * 1.6)
                    ring_n = 64
                    ring_x = [cx + r1 * math.cos(2*math.pi*k/ring_n) for k in range(ring_n+1)]
                    ring_z = [cz + r1 * math.sin(2*math.pi*k/ring_n) for k in range(ring_n+1)]
                    ring_y = [cy for _ in range(ring_n+1)]
                    base.add_trace(go.Scatter3d(
                        x=ring_x, y=ring_y, z=ring_z,
                        mode='lines',
                        line=dict(width=6, color='rgba(255,255,255,0.45)'),
                        name=f'Active ring {i+1}',
                        hoverinfo='skip',
                        opacity=0.55
                    ))
                except Exception:
                    pass

            # Surface/area highlight
            if hasattr(tr, "opacity"):
                tr.opacity = 0.35 if is_active else min(float(getattr(tr, "opacity", 0.25)), 0.18)

            tr.name = f"Chord {i+1}: {ch.get('name','')}".strip()
            base.add_trace(tr)

    return base