✔ Copied

C:\PythonPrograms\neon_butterfly\neon_butterfly_v3_3.py

  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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import turtle
import math
import colorsys
import random
import webbrowser
import threading
from pathlib import Path
from datetime import datetime
import traceback
import sys
import wave
import tempfile
import subprocess
import atexit

# Neon Butterfly Curve - Version 3.3
PROJECT_URL = "https://mindstorm.gr/category/python/"
APP_VERSION = "3.3"


def show_project_info():
    print("=" * 72)
    print(f" NEON BUTTERFLY | Version {APP_VERSION}")
    print(" Python Mathematical Art & Animation")
    print("=" * 72)
    print("Project: An animated parametric butterfly curve with neon trails.")
    print("Libraries: turtle, math, colorsys, random, webbrowser (standard library)")
    print("Mathematical model:")
    print("  r = exp(cos(t)) - 2*cos(4*t) - sin(t/12)**5")
    print("  x = r*sin(t), y = r*cos(t), 0 <= t <= 12*pi")
    print(f"Drawing: {POINTS:,} segments | Scale: {SCALE} | Batch: {BATCH}")
    print(f"Timer delay: {DELAY} ms | Trail interval: {TRAIL_EVERY} segments")
    print("Features: rainbow colours, glow, particles and radial light trails.")
    print("Controls: R = replay | SPACE = pause/resume | ESC = exit")
    print("          W = open Mindstorm Python resources in your browser")
    print(f"Export: automatic GIF + MP4 | {EXPORT_SIZE} x {EXPORT_SIZE} | {DRAW_SECONDS + HOLD_SECONDS} seconds")
    print("          E = export again (when current export finishes)")
    print("Export updates in V3.3:")
    print(f"  - MP4: {EXPORT_FPS} FPS | GIF: {GIF_FPS} FPS")
    print("  - butterfly placed slightly lower in exported GIF/MP4")
    print("  - butterfly outline exported without visible point markers")
    print("Music: original ambient soundtrack in MP4; GIF remains silent")
    print("          M = toggle live music (Windows)")
    print("Learn more about Python:")
    print(f"  {PROJECT_URL}")
    print("=" * 72, flush=True)


def open_resources():
    print(f"[INFO] Opening {PROJECT_URL}", flush=True)
    if not webbrowser.open(PROJECT_URL):
        print("[WARNING] Could not open browser. Use the URL above.", flush=True)


POINTS = 2400
SCALE = 85
BATCH = 8
DELAY = 10  # milliseconds
TRAIL_EVERY = 18
EXPORT_SIZE = 720
EXPORT_FPS = 60  # MP4 frames per second
GIF_FPS = 50     # GIF frames per second (20 ms per frame)
DRAW_SECONDS = 10
HOLD_SECONDS = 2
EXPORT_DIR = Path(__file__).resolve().parent / "exports"

# Export tuning so rendered GIF/MP4 matches the Turtle window more closely.
EXPORT_BUTTERFLY_SCALE = 1.07
EXPORT_BUTTERFLY_CENTER_X = 360
EXPORT_BUTTERFLY_CENTER_Y = 405  # lower than before
EXPORT_PROGRESS_Y = 653
EXPORT_TITLE_Y = 45
EXPORT_SUBTITLE_Y = 86
EXPORT_BRAND_Y = 680
EXPORT_URL_Y = 706

MUSIC_ENABLED = True
MUSIC_VOLUME = 0.7

def make_music(path):
    """Original synthesized ambient arpeggio; no external music assets."""
    import numpy as np
    rate = 44100
    duration = DRAW_SECONDS + HOLD_SECONDS
    t = np.arange(round(rate*duration))/rate
    audio = np.zeros_like(t)
    chords = [(48,55,60,64),(45,52,57,60),(41,48,53,57),(43,50,55,59)]
    for j, start in enumerate(np.arange(0,duration,.375)):
        chord = chords[int(start/3)%len(chords)]
        note = chord[j%4]+12
        n = min(int(rate*1.1), len(t)-round(start*rate))
        u = np.arange(n)/rate
        freq = 440*2**((note-69)/12)
        env = np.minimum(u/.025,1)*np.exp(-u*4)*np.minimum((n/rate-u)/.08,1)
        audio[round(start*rate):round(start*rate)+n] += .13*env*(np.sin(2*np.pi*freq*u)+.22*np.sin(4*np.pi*freq*u))
    for start in np.arange(0,duration,3):
        chord = chords[int(start/3)%len(chords)]
        n=min(int(rate*3),len(t)-round(start*rate)); u=np.arange(n)/rate
        env=np.sin(np.pi*u/3)**2
        for note in chord:
            audio[round(start*rate):round(start*rate)+n] += .035*env*np.sin(2*np.pi*440*2**((note-69)/12)*u)
    audio *= np.minimum(t/.25,1)*np.clip((duration-t)/.65,0,1)
    with wave.open(str(path),'wb') as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate)
        w.writeframes((np.clip(audio*MUSIC_VOLUME,-1,1)*32767).astype('<i2').tobytes())

_music_dir = None
music_path = None

def prepare_music():
    global _music_dir, music_path
    if sys.platform != 'win32':
        return
    try:
        _music_dir = tempfile.TemporaryDirectory(prefix='neon_butterfly_')
        music_path = Path(_music_dir.name) / 'soundtrack.wav'
        make_music(music_path)
    except Exception as exc:
        print(f'[MUSIC WARNING] {exc}', flush=True)

def stop_music():
    if sys.platform == 'win32':
        import winsound
        try:
            winsound.PlaySound(None, 0)
        except RuntimeError as exc:
            print(f'[MUSIC WARNING] {exc}', flush=True)

def play_music():
    if sys.platform == 'win32' and MUSIC_ENABLED and music_path and music_path.exists():
        import winsound
        try:
            winsound.PlaySound(str(music_path), winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_LOOP | winsound.SND_NODEFAULT)
        except RuntimeError as exc:
            print(f'[MUSIC WARNING] {exc}', flush=True)

def cleanup_music():
    stop_music()
    if _music_dir is not None:
        _music_dir.cleanup()

atexit.register(cleanup_music)

def toggle_music():
    global MUSIC_ENABLED
    MUSIC_ENABLED = not MUSIC_ENABLED
    if MUSIC_ENABLED and not paused:
        play_music()
    else:
        stop_music()
    print(f'[MUSIC] Live playback: {"ON" if MUSIC_ENABLED else "OFF"}', flush=True)

show_project_info()
prepare_music()
print("[INFO] Opening animation window...", flush=True)
screen = turtle.Screen()
screen.setup(1000, 850)
screen.title(f'Python | Neon Butterfly Curve V{APP_VERSION}')
screen.bgcolor('#050509')
screen.colormode(1.0)
screen.tracer(0)


def pen():
    p = turtle.Turtle(visible=False)
    p.speed(0)
    p.penup()
    return p


stars, heading, trails, glow, outline, particles, counter = [pen() for _ in range(7)]
rng = random.Random(42)
for _ in range(100):
    stars.goto(rng.randint(-480, 480), rng.randint(-390, 390))
    v = rng.uniform(.10, .35)
    stars.dot(rng.choice([1, 2]), (v, v, v))

heading.color('#aaff22')
heading.goto(0, 335)
heading.write('PYTHON', align='center', font=('Arial', 38, 'bold'))
heading.color('white')
heading.goto(0, 300)
heading.write('Butterfly Curve with Neon Trails', align='center', font=('Arial', 17, 'bold'))
heading.goto(0, -370)
heading.color('#9999aa')
heading.write('R: replay   |   SPACE: pause / resume   |   ESC: exit   |   W: resources   |   E: export   |   M: music', align='center', font=('Arial', 11, 'normal'))

heading.goto(0, -397)
heading.color('#aaff22')
heading.write(PROJECT_URL, align='center', font=('Arial', 11, 'normal'))

coords = []
for i in range(POINTS + 1):
    t = i / POINTS * 12 * math.pi
    r = math.exp(math.cos(t)) - 2 * math.cos(4*t) - math.sin(t/12)**5
    coords.append((SCALE*r*math.sin(t), SCALE*r*math.cos(t)-40))


# Export independently of the desktop window, using the same mathematical points.
export_thread = None


def export_animation():
    try:
        import numpy as np
        import imageio.v2 as imageio
        from PIL import Image, ImageDraw, ImageFont

        EXPORT_DIR.mkdir(parents=True, exist_ok=True)
        stamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
        base = EXPORT_DIR / f'neon_butterfly_{stamp}'
        gif_path = base.with_suffix('.gif')
        mp4_path = base.with_suffix('.mp4')
        gif_tmp = base.with_suffix('.part.gif')
        mp4_tmp = base.with_suffix('.part.mp4')
        size = EXPORT_SIZE
        k = size / 720
        bg = (5, 5, 9)

        def font(n, bold=False):
            for name in (['arialbd.ttf', 'DejaVuSans-Bold.ttf'] if bold else ['arial.ttf', 'DejaVuSans.ttf']):
                try:
                    return ImageFont.truetype(name, round(n*k))
                except OSError:
                    pass
            return ImageFont.load_default()

        def text(draw, xy, label, n, color, bold=False):
            draw.text(tuple(round(v*k) for v in xy), label, font=font(n, bold), fill=color, anchor='mm')

        def xy(point):
            return (
                round((EXPORT_BUTTERFLY_CENTER_X + EXPORT_BUTTERFLY_SCALE * point[0]) * k),
                round((EXPORT_BUTTERFLY_CENTER_Y - EXPORT_BUTTERFLY_SCALE * point[1]) * k),
            )

        def rgb(h, saturation=0.9, value=1):
            return tuple(round(c*255) for c in colorsys.hsv_to_rgb(h, saturation, value))

        def width(n):
            return max(1, round(n*k))

        def dot(draw, point, radius, color):
            x, y = point
            r = width(radius)
            draw.ellipse((x-r, y-r, x+r, y+r), fill=color)

        canvas = Image.new('RGB', (size, size), bg)
        d = ImageDraw.Draw(canvas)
        rng = random.Random(42)
        for _ in range(100):
            x, y = rng.randrange(size), rng.randrange(size)
            v = rng.randint(25, 80)
            d.point((x, y), fill=(v, v, v))

        text(d, (360, EXPORT_TITLE_Y), 'PYTHON', 44, '#aaff22', True)
        text(d, (360, EXPORT_SUBTITLE_Y), 'Butterfly Curve with Neon Trails', 23, 'white', True)
        text(d, (360, EXPORT_BRAND_Y), 'MINDSTORM.GR', 23, '#aaff22', True)
        text(d, (360, EXPORT_URL_Y), PROJECT_URL, 17, '#ccccdd')

        # Separate layers prevent later trails from obscuring the bright outline.
        layers = [Image.new('RGBA', (size, size)) for _ in range(3)]
        trail, glow_draw, line = [ImageDraw.Draw(im) for im in layers]
        center = xy((0, -40))
        if not 1 <= GIF_FPS <= min(EXPORT_FPS, 50):
            raise ValueError("GIF_FPS must be between 1 and min(EXPORT_FPS, 50).")
        frames = []
        draw_frames = DRAW_SECONDS * EXPORT_FPS
        total_frames = (DRAW_SECONDS + HOLD_SECONDS) * EXPORT_FPS
        previous = 0

        print(f'[EXPORT] MP4: {EXPORT_FPS} FPS | GIF: {GIF_FPS} FPS', flush=True)
        print(f'[EXPORT] Rendering {total_frames} video frames to {EXPORT_DIR}', flush=True)
        try:
            with imageio.get_writer(
                str(mp4_tmp),
                fps=EXPORT_FPS,
                codec='libx264',
                pixelformat='yuv420p',
                quality=8,
                macro_block_size=2,
            ) as writer:
                for f in range(total_frames):
                    target = min(POINTS, round((f + 1) * POINTS / draw_frames))
                    for i in range(previous, target):
                        h = (0.02 + 2 * i / POINTS) % 1
                        a, b = xy(coords[i]), xy(coords[i + 1])
                        if i % TRAIL_EVERY == 0:
                            trail.line([center, b], fill=rgb(h, value=.22), width=width(1))
                        glow_draw.line([a, b], fill=rgb(h, value=.22), width=width(6))
                        line.line([a, b], fill=rgb(h), width=width(2))
                    previous = target

                    frame = canvas.convert('RGBA')
                    for layer in layers:
                        frame = Image.alpha_composite(frame, layer)

                    if target == POINTS:
                        draw_frame = ImageDraw.Draw(frame)
                        # Small final centre glow only; no point markers along the butterfly.
                        for r, c in [(6, '#666600'), (4, '#ffcc22'), (2, '#ffffcc')]:
                            dot(draw_frame, center, r, c)
                    text(ImageDraw.Draw(frame), (360, EXPORT_PROGRESS_Y), f'{target:,} / {POINTS:,}', 15, '#b0b0c0')
                    frame = frame.convert('RGB')
                    writer.append_data(np.asarray(frame))
                    # Sample GIF frames independently at the requested rate.
                    if ((f + 1) * GIF_FPS) // EXPORT_FPS > (f * GIF_FPS) // EXPORT_FPS:
                        frames.append(frame.quantize(colors=256, method=Image.Quantize.MEDIANCUT))
                    if (f + 1) % EXPORT_FPS == 0:
                        print(f'[EXPORT] {f + 1}/{total_frames} frames', flush=True)

            durations = [10 * (round((j + 1) * 100 / GIF_FPS) - round(j * 100 / GIF_FPS)) for j in range(len(frames))]
            frames[0].save(gif_tmp, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=False, disposal=2)
            # Add soundtrack without re-encoding the 60 FPS video.
            import imageio_ffmpeg
            audio_tmp = base.with_suffix('.part.wav')
            mux_tmp = base.with_suffix('.audio.mp4')
            try:
                print('[EXPORT] Adding original ambient soundtrack to MP4...', flush=True)
                make_music(audio_tmp)
                subprocess.run([imageio_ffmpeg.get_ffmpeg_exe(), '-y', '-loglevel', 'error',
                    '-i', str(mp4_tmp), '-i', str(audio_tmp), '-map', '0:v:0', '-map', '1:a:0',
                    '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest',
                    '-movflags', '+faststart', str(mux_tmp)], check=True)
                mux_tmp.replace(mp4_path)
            except Exception as exc:
                print(f'[EXPORT WARNING] Music encoding failed; saving silent MP4: {exc}', flush=True)
                mp4_tmp.replace(mp4_path)
            finally:
                audio_tmp.unlink(missing_ok=True)
                mux_tmp.unlink(missing_ok=True)
            gif_tmp.replace(gif_path)
            print(f'[EXPORT COMPLETE] MP4: {mp4_path} ({mp4_path.stat().st_size / 1048576:.2f} MB)', flush=True)
            print(f'[EXPORT COMPLETE] GIF: {gif_path} ({gif_path.stat().st_size / 1048576:.2f} MB)', flush=True)
        finally:
            for temp in (gif_tmp, mp4_tmp):
                temp.unlink(missing_ok=True)
    except ImportError:
        print('[EXPORT ERROR] Install dependencies: py -3.11 -m pip install pillow numpy imageio imageio-ffmpeg', flush=True)
    except Exception:
        print('[EXPORT ERROR] Export failed; desktop animation remains independent.', flush=True)
        traceback.print_exc()



def start_export():
    global export_thread
    if export_thread is not None and export_thread.is_alive():
        print('[EXPORT] Already running.', flush=True)
        return
    export_thread = threading.Thread(target=export_animation, daemon=False)
    export_thread.start()



def segment(p, start, end, color, width):
    p.penup()
    p.goto(start)
    p.pencolor(color)
    p.pensize(width)
    p.pendown()
    p.goto(end)
    p.penup()


index = 0
paused = False
version = 0


def animate(run):
    global index
    if run != version:
        return
    if not paused:
        for _ in range(BATCH):
            if index >= POINTS:
                break
            i = index
            hue = (0.02 + 2.0 * i / POINTS) % 1.0
            rgb = colorsys.hsv_to_rgb(hue, .9, 1)
            a, b = coords[i], coords[i+1]
            if i % TRAIL_EVERY == 0:
                segment(trails, (0, -40), b, tuple(c*.22 for c in rgb), 1)
            segment(glow, a, b, tuple(c*.22 for c in rgb), 6)
            segment(outline, a, b, rgb, 2)
            if i % 24 == 0:
                particles.goto(b)
                particles.dot(4, colorsys.hsv_to_rgb(hue, .4, 1))
            index += 1
        counter.clear()
        counter.goto(465, -345)
        counter.color('#b0b0c0')
        counter.write(f'{index:,} / {POINTS:,}', align='right', font=('Consolas', 12, 'normal'))
        screen.update()
    if index < POINTS:
        screen.ontimer(lambda: animate(run), DELAY)
    else:
        print(f"[COMPLETE] {POINTS:,} segments drawn. Press R to replay.", flush=True)
        particles.goto(0, -40)
        particles.dot(18, '#666600')
        particles.dot(10, '#ffcc22')
        particles.dot(5, '#ffffcc')
        screen.update()



def replay():
    global index, paused, version
    print("[INFO] Starting butterfly animation...", flush=True)
    version += 1
    index = 0
    paused = False
    for p in (trails, glow, outline, particles, counter):
        p.clear()
    stop_music()
    play_music()
    animate(version)



def toggle_pause():
    global paused
    paused = not paused
    if paused:
        stop_music()
    else:
        play_music()
    print("[INFO] Animation paused." if paused else "[INFO] Animation resumed.", flush=True)


screen.listen()
screen.onkey(toggle_music, "m")
screen.onkey(toggle_music, "M")
screen.onkey(replay, 'r')
screen.onkey(replay, 'R')
screen.onkey(toggle_pause, 'space')
screen.onkey(screen.bye, 'Escape')
screen.onkey(open_resources, 'w')
screen.onkey(open_resources, 'W')
screen.onkey(start_export, 'e')
screen.onkey(start_export, 'E')
start_export()
replay()
try:
    screen.mainloop()
finally:
    stop_music()
print("[INFO] Neon Butterfly window closed.", flush=True)
if export_thread is not None and export_thread.is_alive():
    print("[EXPORT] Finishing files before exit...", flush=True)
    export_thread.join()