-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttfx.c
1848 lines (1755 loc) · 62.3 KB
/
ttfx.c
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "dirent.h"
#include "errno.h"
#include "signal.h"
#include "string.h"
#include "sys/stat.h"
#include "SDL.h"
#if defined( ALSA_MIDI )
#include "alsa/asoundlib.h"
#endif
#include "worker.h"
#if defined( ASM_STATEMENT )
#include "ttasm.h"
#endif
#define MAX_STACK 1048576
/*
SDL graphics and sound extension for Towntalk (c)2024 Martin Cameron.
Statements:
display w, h, "caption"; Open a display window.
rect x, y, w, h, 0xrrggbb; Draw an opaque rectangle.
show; Update the display. May wait for the next vertical blank.
surface num, width, height, pixels; Set the specified surface to specified size and RGBA pixel array.
blit num, sx, sy, sw, sh, x, y; Draw the specified region of the specified surface.
sleep millis; Wait for the specified time period.
timer millis; Generate timer events at the specified interval (0 to disable).
audio period; Enable the audio system (period in samples per tick at 24000hz).
sample num, "str", loop, looplength; Set the specified sample to the specified signed 8-bit string and loop points.
play channel, "sequence"; Play the specified sequence on the specified channel offset.
queue channel, "sequence"; Queue the specified sequence on the specified channel offset.
midi "device"; Open the named MIDI input device for recieving events.
Expressions:
$millis Value incremented every millisecond.
$pollevent Return an event or 0 if none avaliable.
$waitevent Wait for an event and return it.
$xmouse The horizontal mouse coordinate from the latest mouse event.
$ymouse The vertical mouse coordinate from the latest mouse event.
$mousekey The state of the mouse buttons from the latest mouse event.
$mousewheel The state of the mouse wheel from the latest mouse event.
$keyboard The key associated with the latest keyboard event.
$keyshift The currently pressed modifier keys (least significant 2 bits are shift keys).
$seqtick Return an integer incremented every sequencer period.
$seqmix(output) Copy 16-bit stereo sample pairs for the current tick and return the count (max 8192).
$seqmsg The channel and parameter of the latest sequencer event (0xccpppppp).
$seqrate(key) The sampling rate corresponding to the specified sequencer key.
$dir("path") An element tree of the names and sizes of all files in the specified dir.
$path("file") The full path of the specified file.
$midimsg The message associated with the latest MIDI event.
$winmsg The value of the latest window event.
$keyheld Whether the latest keyboard event was from a held-down key.
$datfile A string containing the datfile the current program was run from, or 0.
$extract(datfile index) Extract the specified string from the specified datfile.
$stream(arr offset count) Stream 16-bit stereo sample pairs to the audio system and return count written.
Event Constants (for $pollevent and $waitevent):
WINDOW_EVENT Window event.
KEY_PRESSED_EVENT Key pressed event.
KEY_RELEASED_EVENT Key released event.
MOUSE_MOTION_EVENT Mouse moved event.
MOUSE_PRESSED_EVENT Mouse button pressed event.
MOUSE_RELEASED_EVENT Mouse button released event.
MOUSE_WHEEL_EVENT Mouse wheel event.
TIMER_EVENT Timer event.
SEQUENCER_EVENT Sequencer event.
MIDI_EVENT MIDI event.
Window Event Constants (for $winmsg):
WINDOW_EXPOSED_MSG Window exposed.
Key Constants (for $keyboard):
KEY_BACKSPACE Backspace.
KEY_TAB Tab.
KEY_RETURN Return.
KEY_ESCAPE Escape.
KEY_SPACE Space.
KEY_0 Zero (other number keys can be calculated by adding to this value).
KEY_A A (other alphabetical keys can be calculated by adding to this value).
KEY_PAD_0 Key pad zero.
KEY_PAD_1 Key pad one (keys up to 9 can be calculated by adding to this value).
KEY_PAD_PERIOD Key pad period.
KEY_PAD_DIVIDE Key pad divide.
KEY_PAD_MULTIPLY Key pad multiply.
KEY_PAD_MINUS Key pad minus.
KEY_PAD_PLUS Key pad plus.
KEY_PAD_ENTER Key pad enter.
KEY_PAD_EQUALS Key pad equals.
KEY_UP Cursor up.
KEY_DOWN Cursor down.
KEY_LEFT Cursor left.
KEY_RIGHT Cursor right.
KEY_INSERT Insert.
KEY_DELETE Delete.
KEY_HOME Home.
KEY_END End.
KEY_PAGE_UP Page Up.
KEY_PAGE_DOWN Page Down.
KEY_F1 F1 (other function keys can be calculated by adding to this value).
Audio Sequencer Commands (2 and 4-bytes each packed into big-endian string for play and queue statements):
0x00xx do nothing (used to pad 2-byte commands to 4).
0x08xxxxxx fire an event containing the specified 24-bit parameter.
0x1kkkiicc set key k, instrument i and sample offset 0 on channel c.
Instrument 0 / key 0 ignored.
If instrument >= 0x40, set volume / panning instead.
Keys specified in 96ths of an octave (480 = 16744hz).
0x2kkkiicc set key k and instrument i on channel c.
The sample offset is not reset.
0x3ssssscc set sample offset s on channel c.
0xvvcc set volume (0x40-0x80) on channel c.
0xppcc set panning (0x81-0xBF) on channel c.
0xCxxx set sequence gain (default 0x40).
0xDxxx set sequence transpose (default 0x800).
0xEttt set period (tempo) in samples per tick (at 24000hz).
0xFwww wait w ticks.
Datfiles:
A datfile is a simple indexed file format which can be used to combine programs and data.
The first 4 bytes is the ASCII string "TTFX", followed by 4-byte big-endian offsets into the file.
The length of an item can be calculated by subtracting one offset from the next.
The last item is typically identified by having zero length.
An executable datfile has the program at the first offset.
*/
#if defined( __MINGW32__ )
#define realpath( path, resolved_path ) _fullpath( NULL, ( path ), 0 )
#endif
#define NUM_SAMPLES 64
#define NUM_CHANNELS 32
#define NUM_SURFACES 256
#define MIN_TICK_LEN 512
#define MAX_TICK_LEN 8192
#define DEFAULT_PERIOD 480
#define MAX_SAMPLE_LEN 524200
#define SAMPLE_RATE 48000
static const int FREQ_TABLE[] = {
16744, 16865, 16988, 17111, 17235, 17360, 17485, 17612,
17740, 17868, 17998, 18128, 18260, 18392, 18525, 18659,
18795, 18931, 19068, 19206, 19345, 19485, 19627, 19769,
19912, 20056, 20202, 20348, 20496, 20644, 20794, 20944,
21096, 21249, 21403, 21558, 21714, 21872, 22030, 22190,
22351, 22513, 22676, 22840, 23006, 23172, 23340, 23509,
23680, 23851, 24024, 24198, 24374, 24550, 24728, 24907,
25088, 25270, 25453, 25637, 25823, 26010, 26198, 26388,
26580, 26772, 26966, 27162, 27358, 27557, 27756, 27957,
28160, 28364, 28570, 28777, 28985, 29195, 29407, 29620,
29834, 30051, 30268, 30488, 30709, 30931, 31155, 31381,
31609, 31838, 32068, 32301, 32535, 32770, 33008, 33247
};
struct fxsample {
int loop_start, loop_length;
struct variable sample_data;
};
struct fxchannel {
struct fxsample *sample;
int sample_idx, sample_fra;
int frequency, volume, panning, gain, transpose;
int sequence_offset, sequence_wait;
struct variable sequence, next_sequence;
};
struct fxenvironment {
struct environment env;
struct variable datfile;
#if SDL_MAJOR_VERSION > 1
SDL_Keycode key;
struct SDL_Window *window;
struct SDL_Renderer *renderer;
struct SDL_Texture *target, *surfaces[ NUM_SURFACES ];
#else
SDLKey key;
struct SDL_Surface *surfaces[ NUM_SURFACES ];
#endif
SDL_TimerID timer;
int win_event, key_held, wheel;
struct fxsample samples[ NUM_SAMPLES ];
struct fxchannel channels[ NUM_CHANNELS ];
unsigned int timer_event_type, seq_event_type, midi_event_type;
int tick, tick_len, audio_idx, audio_end, stream_idx, seq_msg, midi_msg;
int audio[ ( MAX_TICK_LEN + 33 ) * 4 ], stream[ MAX_TICK_LEN * 2 ], ramp_buf[ 64 ];
#if defined( ALSA_MIDI )
int midi_buf, midi_idx;
snd_rawmidi_t *midi_in;
#endif
};
static struct fxenvironment fxenv;
static void ( *interrupt_handler )( int signum );
#if defined( MULTI_THREAD )
int worker_thread( void *data ) {
struct variables vars = { 0 };
struct function_expression expr = { 0 };
struct worker *work = ( struct worker * ) data;
vars.exception = &work->exception;
vars.func = work->env.entry_point;
initialize_entry_point( &expr, vars.func );
expr.expr.parameters = work->parameters;
work->ret = expr.expr.evaluate( &expr.expr, &vars, &work->result );
return 0;
}
/* Add thread-safe custom statements and operators to the specified worker.
Returns 0 and assigns message on failure. */
int initialize_worker( struct worker *work, char *message ) {
#if defined( ASM_STATEMENT )
return add_statements( asm_keyword, &work->env, message );
#else
return 1;
#endif
}
/* Begin execution of the specified worker. Returns 0 on failure. */
int start_worker( struct worker *work ) {
int success = 0;
work->mutex = SDL_CreateMutex();
if( work->mutex ) {
work->thread = SDL_CreateThread( worker_thread, work->custom.str.string, work );
if( work->thread ) {
success = 1;
} else {
SDL_DestroyMutex( ( SDL_mutex * ) work->mutex );
work->mutex = NULL;
}
}
return success;
}
/* Lock the specified worker mutex. Returns 0 on failure. */
int lock_worker( struct worker *work ) {
return work->mutex == NULL || SDL_LockMutex( ( SDL_mutex * ) work->mutex ) == 0;
}
/* Unlock the specified worker mutex. Returns 0 on failure. */
int unlock_worker( struct worker *work ) {
return work->mutex == NULL || SDL_UnlockMutex( ( SDL_mutex * ) work->mutex ) == 0;
}
/* Wait for the completion of the specified worker.
If cancel is non-zero, the worker should be interrupted. */
void await_worker( struct worker *work, int cancel ) {
if( work->thread ) {
if( cancel ) {
work->env.interrupted = 1;
}
SDL_WaitThread( ( SDL_Thread * ) work->thread, NULL );
SDL_DestroyMutex( ( SDL_mutex * ) work->mutex );
work->thread = work->mutex = NULL;
}
}
#endif
static void signal_handler( int signum ) {
signal( signum, signal_handler );
fxenv.env.interrupted = 1;
if( fxenv.env.worker ) {
/* Terminate current worker. */
( ( struct worker * ) fxenv.env.worker )->env.interrupted = 1;
}
if( signum == SIGINT && interrupt_handler ) {
interrupt_handler( SIGINT );
}
}
static Uint32 timer_callback( Uint32 interval, void *param ) {
SDL_Event event = { 0 };
event.type = ( ( struct fxenvironment * ) param )->timer_event_type;
SDL_PushEvent( &event );
return interval;
}
static int datfile_extract( char *datfile, int datfile_length, int bank, char *buffer ) {
int offset, end, length = -1;
if( datfile_length < 4 || strncmp( datfile, "TTFX", 4 ) ) {
/* Not a datfile. */
return -2;
}
if( bank >= 0 && ( bank + 3 ) * 4 <= datfile_length ) {
offset = unpack( datfile, bank + 1 );
end = unpack( datfile, bank + 2 );
if( offset > 0 && end >= offset && end <= datfile_length ) {
length = end - offset;
if( buffer ) {
memcpy( buffer, &datfile[ offset ], sizeof( char ) * length );
}
}
}
return length;
}
static void volume_ramp( int *mix_buf, int *ramp_buf, int tick_len ) {
int idx, a1, a2;
for( idx = 0, a1 = 0; a1 < 32; idx += 2, a1++ ) {
a2 = 32 - a1;
mix_buf[ idx ] = ( mix_buf[ idx ] * a1 + ramp_buf[ idx ] * a2 ) >> 5;
mix_buf[ idx + 1 ] = ( mix_buf[ idx + 1 ] * a1 + ramp_buf[ idx + 1 ] * a2 ) >> 5;
}
memcpy( ramp_buf, &mix_buf[ tick_len * 2 ], 64 * sizeof( int ) );
}
/* 2:1 downsampling with simple but effective anti-aliasing.
Buf must contain count * 2 + 1 stereo samples. */
static void downsample( int *buf, int count ) {
int idx, out_idx, out_len = count * 2;
for( idx = 0, out_idx = 0; out_idx < out_len; idx += 4, out_idx += 2 ) {
buf[ out_idx ] = ( buf[ idx ] >> 2 ) + ( buf[ idx + 2 ] >> 1 ) + ( buf[ idx + 4 ] >> 2 );
buf[ out_idx + 1 ] = ( buf[ idx + 1 ] >> 2 ) + ( buf[ idx + 3 ] >> 1 ) + ( buf[ idx + 5 ] >> 2 );
}
}
static int key_to_freq( int key ) {
return ( FREQ_TABLE[ key % 96 ] << 4 ) >> ( 9 - key / 96 );
}
static void mix_channel( struct fxchannel *channel, int *output, int count ) {
int idx, end, loop, llen, lend, sidx, sfra, lamp, ramp, step, sam;
signed char *data;
if( channel->volume > 0 && channel->sample
&& channel->sample->sample_data.string_value ) {
loop = channel->sample->loop_start;
llen = channel->sample->loop_length;
lend = loop + llen;
sidx = channel->sample_idx;
sfra = channel->sample_fra;
if( sidx < lend || llen > 1 ) {
lamp = channel->volume * ( 32 - channel->panning );
ramp = channel->volume * ( 32 + channel->panning );
step = ( channel->frequency << 12 ) / ( SAMPLE_RATE >> 2 );
data = ( signed char * ) channel->sample->sample_data.string_value->string;
idx = 0;
end = count << 1;
while( idx < end ) {
if( sidx >= lend ) {
if( llen > 1 ) {
sidx = loop + ( ( sidx - loop ) % llen );
} else {
sidx = lend;
break;
}
}
sam = data[ sidx ];
output[ idx++ ] += ( sam * lamp ) >> 11;
output[ idx++ ] += ( sam * ramp ) >> 11;
sfra += step;
sidx += sfra >> 15;
sfra &= 0x7FFF;
}
}
}
}
static void update_channel( struct fxchannel *channel, int *output, int count ) {
int step;
struct fxsample *sample = channel->sample;
if( sample && sample->sample_data.string_value ) {
step = ( channel->frequency << 12 ) / ( SAMPLE_RATE >> 2 );
channel->sample_fra += step * count;
channel->sample_idx += channel->sample_fra >> 15;
if( channel->sample_idx > sample->loop_start ) {
if( sample->loop_length > 1 ) {
channel->sample_idx = sample->loop_start
+ ( channel->sample_idx - sample->loop_start ) % sample->loop_length;
} else {
channel->sample_idx = sample->loop_start;
}
}
channel->sample_fra &= 0x7FFF;
}
}
static void process_sequence( struct fxenvironment *fxenv, int channel_idx ) {
int off, len, cmd, oper, tick, chan, key, ins, vol, gain;
struct fxchannel *channel, *cmdchan;
SDL_Event event = { 0 };
char *seq;
channel = &fxenv->channels[ channel_idx ];
if( channel->sequence.string_value ) {
off = channel->sequence_offset;
len = channel->sequence.string_value->length;
seq = channel->sequence.string_value->string;
while( channel->sequence_wait < 1 && off < len ) {
cmd = seq[ off ] & 0xFF;
oper = cmd >> 4;
if( ( cmd == 0 || oper >= 0x4 ) && ( off + 1 < len ) ) {
cmd = ( cmd << 8 ) | ( seq[ off + 1 ] & 0xFF );
off += 2;
} else if( off + 3 < len ) {
cmd = ( cmd << 24 )
| ( ( seq[ off + 1 ] & 0xFF ) << 16 )
| ( ( seq[ off + 2 ] & 0xFF ) << 8 )
| ( seq[ off + 3 ] & 0xFF );
off += 4;
} else {
oper = cmd = 0;
off = len;
}
if( oper == 0xF ) {
/* 0xFwww wait w ticks. */
channel->sequence_wait = cmd & 0xFFF;
} else if( oper == 0xE ) {
/* 0xEttt set tempo. */
tick = ( cmd & 0xFFF ) * SAMPLE_RATE / 24000;
if( tick >= MIN_TICK_LEN && tick <= MAX_TICK_LEN ) {
fxenv->tick_len = tick;
}
} else if( oper == 0xC ) {
/* 0xCxxx set gain. */
gain = cmd & 0x7F;
fxenv->channels[ channel_idx ].gain = gain * gain;
} else if( oper == 0xD ) {
/* 0xDxxx set transpose. */
fxenv->channels[ channel_idx ].transpose = ( cmd & 0xFFF ) - 0x800;
} else if( oper < 0xC ) {
chan = cmd & 0xFF;
if( chan + channel_idx < NUM_CHANNELS ) {
cmdchan = &fxenv->channels[ chan + channel_idx ];
if( oper >= 0x4 ) {
if( cmd >= 0x8100 ) {
/* 0xppcc set panning. */
cmdchan->panning = ( ( cmd >> 8 ) - 0x80 ) - 32;
} else if( cmd >= 0x4000 ) {
/* 0xvvcc set volume */
vol = ( cmd >> 8 ) - 0x40;
gain = fxenv->channels[ channel_idx ].gain;
cmdchan->volume = ( gain * vol * vol ) >> 12;
}
} else if( oper == 0x3 ) {
/* 0x3ssssscc sample offset + channel */
cmdchan->sample_idx = ( ( cmd & 0xFFFFF00 ) >> 8 );
cmdchan->sample_fra = 0;
} else if( oper > 0 ) {
/* 0x1kkkiicc / 0x2kkkiicc key + instrument + channel */
key = ( cmd >> 16 ) & 0xFFF;
key = key + fxenv->channels[ channel_idx ].transpose;
if( key > 0 && key < 957 ) {
cmdchan->frequency = key_to_freq( key );
}
ins = ( cmd >> 8 ) & 0xFF;
if( ins > 0 && ins < 0xC0 ) {
if( ins >= 0x81 ) {
cmdchan->panning = ( ins - 0x80 ) - 32;
} else if( ins >= 0x40 ) {
vol = ins - 0x40;
gain = fxenv->channels[ channel_idx ].gain;
cmdchan->volume = ( gain * vol * vol ) >> 12;
} else {
cmdchan->sample = &fxenv->samples[ ins - 1 ];
}
}
if( oper == 1 ) {
cmdchan->sample_idx = cmdchan->sample_fra = 0;
}
} else if( ( cmd & 0xF000000 ) == 0x8000000 ) {
/* 0x08xxxxxx sequencer event. */
event.type = fxenv->seq_event_type;
event.user.code = ( channel_idx << 24 ) | ( cmd & 0xFFFFFF );
SDL_PushEvent( &event );
}
}
}
}
channel->sequence_offset = off;
}
}
static void audio_callback( void *userdata, Uint8 *stream, int len ) {
struct fxenvironment *fxenv = ( struct fxenvironment * ) userdata;
Sint16 *output = ( Sint16 * ) stream;
struct fxchannel *channel;
int samples = len >> 2;
int *fxaudio = fxenv->audio, *fxstream = fxenv->stream;
int out_idx, out_end, aud_idx, aud_end, ampl;
int chan_idx, count, offset = 0;
#if defined( ALSA_MIDI )
SDL_Event event = { 0 };
unsigned char chr;
if( fxenv->midi_in ) {
while( snd_rawmidi_read( fxenv->midi_in, &chr, 1 ) > 0 ) {
/*printf( "%x\n", (int)chr );*/
if( chr & 0x80 ) {
fxenv->midi_buf = chr << 16;
if( ( fxenv->midi_buf & 0xF00000 ) == 0xF00000 ) {
/* 1-byte 0xFx message. */
fxenv->midi_idx = 3;
} else {
fxenv->midi_idx = 1;
}
} else if( fxenv->midi_idx == 1 ) {
fxenv->midi_buf |= chr << 8;
if( ( fxenv->midi_buf & 0xE00000 ) == 0xC00000 ) {
/* 2-byte message. */
fxenv->midi_idx = 3;
} else {
fxenv->midi_idx = 2;
}
} else if( fxenv->midi_idx == 2 ) {
/* 3-byte message. */
fxenv->midi_buf |= chr;
fxenv->midi_idx = 3;
}
if( fxenv->midi_idx == 3 ) {
/* Push message.*/
event.type = fxenv->midi_event_type;
event.user.code = fxenv->midi_buf;
SDL_PushEvent( &event );
fxenv->midi_idx = 0;
}
}
}
#endif
while( offset < samples ) {
count = samples - offset;
if( fxenv->audio_idx + count > fxenv->audio_end ) {
count = fxenv->audio_end - fxenv->audio_idx;
}
if( output ) {
out_idx = offset << 1;
out_end = ( offset + count ) << 1;
aud_idx = fxenv->audio_idx << 1;
while( out_idx < out_end ) {
ampl = fxaudio[ aud_idx++ ];
if( ampl > 32767 ) {
ampl = 32767;
}
if( ampl < -32768 ) {
ampl = -32768;
}
output[ out_idx++ ] = ampl;
}
}
offset += count;
fxenv->audio_idx += count;
if( fxenv->audio_idx >= fxenv->audio_end ) {
chan_idx = 0;
while( chan_idx < NUM_CHANNELS ) {
channel = &fxenv->channels[ chan_idx ];
if( channel->sequence.string_value ) {
channel->sequence_wait--;
if( channel->sequence_wait < 1 ) {
channel->sequence_wait = 0;
process_sequence( fxenv, chan_idx );
while( channel->sequence.string_value && channel->sequence_wait == 0 ) {
assign_variable( &channel->next_sequence, &channel->sequence );
dispose_variable( &channel->next_sequence );
channel->next_sequence.string_value = NULL;
channel->sequence_offset = 0;
process_sequence( fxenv, chan_idx );
}
}
}
chan_idx++;
}
fxenv->audio_idx = 0;
fxenv->audio_end = fxenv->tick_len;
memset( fxenv->audio, 0, sizeof( int ) * ( fxenv->tick_len + 33 ) * 4 );
chan_idx = 0;
while( chan_idx < NUM_CHANNELS ) {
channel = &fxenv->channels[ chan_idx++ ];
mix_channel( channel, fxenv->audio, ( fxenv->tick_len + 33 ) * 2 );
update_channel( channel, fxenv->audio, fxenv->tick_len * 2 );
}
downsample( fxenv->audio, fxenv->tick_len + 32 );
volume_ramp( fxenv->audio, fxenv->ramp_buf, fxenv->tick_len );
aud_idx = 0;
aud_end = fxenv->stream_idx << 1;
while( aud_idx < aud_end ) {
fxaudio[ aud_idx ] += fxstream[ aud_idx ];
aud_idx++;
}
fxenv->stream_idx = 0;
fxenv->tick++;
}
}
}
static enum result execute_display_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
int width, height;
struct variable caption = { 0, NULL };
struct expression *expr = this->source;
#if SDL_MAJOR_VERSION > 1
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
#endif
enum result ret = evaluate_integer( expr, vars, &width );
if( ret ) {
expr = expr->next;
ret = evaluate_integer( expr, vars, &height );
if( ret ) {
expr = expr->next;
ret = expr->evaluate( expr, vars, &caption );
if( ret ) {
#if SDL_MAJOR_VERSION > 1
if( !fxenv->window ) {
fxenv->window = SDL_CreateWindow(
caption.string_value ? caption.string_value->string : "",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, 0 );
if( fxenv->window ) {
fxenv->renderer = SDL_CreateRenderer(
fxenv->window, -1, SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_PRESENTVSYNC );
if( fxenv->renderer ) {
fxenv->target = SDL_CreateTexture( fxenv->renderer,
SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height );
if( fxenv->target ) {
SDL_SetRenderDrawColor( fxenv->renderer, 0, 0, 0, 255 );
SDL_RenderClear( fxenv->renderer );
SDL_SetRenderTarget( fxenv->renderer, fxenv->target );
SDL_RenderClear( fxenv->renderer );
SDL_RenderPresent( fxenv->renderer );
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
SDL_DestroyRenderer( fxenv->renderer );
fxenv->renderer = NULL;
SDL_DestroyWindow( fxenv->window );
fxenv->window = NULL;
}
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
SDL_DestroyWindow( fxenv->window );
fxenv->window = NULL;
}
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
} else {
ret = throw( vars, this->source, 0, "Window already open." );
}
#else
if( caption.string_value ) {
SDL_WM_SetCaption( caption.string_value->string, "" );
}
if( SDL_SetVideoMode( width, height, 32, SDL_HWSURFACE ) == NULL ) {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#endif
dispose_variable( &caption );
}
}
}
return ret;
}
static enum result execute_surface_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
struct variable var = { 0, NULL };
int surf, width, height, idx, len;
struct array *arr;
number *values;
Uint32 *pixels;
#if SDL_MAJOR_VERSION > 1
struct SDL_Texture *texture = NULL;
#else
struct SDL_Surface *surface = NULL;
#endif
struct expression *expr = this->source;
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
enum result ret = evaluate_integer( expr, vars, &surf );
if( ret ) {
expr = expr->next;
ret = evaluate_integer( expr, vars, &width );
}
if( ret ) {
expr = expr->next;
ret = evaluate_integer( expr, vars, &height );
}
if( ret ) {
expr = expr->next;
ret = expr->evaluate( expr, vars, &var );
}
if( ret ) {
if( surf >= 0 && surf < NUM_SURFACES ) {
if( width > 0 && height > 0 ) {
#if SDL_MAJOR_VERSION > 1
texture = SDL_CreateTexture( fxenv->renderer,
SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, width, height );
if( texture ) {
if( var.string_value ) {
if( var.string_value->type == ARRAY ) {
arr = ( struct array * ) var.string_value;
values = arr->number_values;
pixels = malloc( arr->length * sizeof( Uint32 ) );
if( pixels ) {
idx = 0;
len = arr->length;
if( len >= width * height ) {
len = width * height;
while( idx < len ) {
pixels[ idx ] = ( long_int ) values[ idx ];
idx++;
}
if( SDL_UpdateTexture( texture, NULL, pixels, width * sizeof( Uint32 ) ) ) {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
SDL_SetTextureBlendMode( texture, SDL_BLENDMODE_BLEND );
} else {
ret = throw( vars, this->source, len, "Array index out of bounds." );
}
free( pixels );
} else {
ret = throw_out_of_memory( vars, this->source );
}
} else {
ret = throw( vars, this->source, 0, "Not an array." );
}
}
if( ret ) {
if( fxenv->surfaces[ surf ] ) {
SDL_DestroyTexture( fxenv->surfaces[ surf ] );
}
fxenv->surfaces[ surf ] = texture;
} else {
SDL_DestroyTexture( texture );
}
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#else
surface = SDL_CreateRGBSurface( SDL_HWSURFACE, width, height,
32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF );
if( surface ) {
if( var.string_value ) {
if( var.string_value->type == ARRAY ) {
arr = ( struct array * ) var.string_value;
values = arr->number_values;
if( SDL_LockSurface( surface ) == 0 ) {
idx = 0;
len = arr->length;
if( len >= width * height ) {
len = width * height;
pixels = ( Uint32 * ) surface->pixels;
while( idx < len ) {
pixels[ idx ] = ( long_int ) values[ idx ];
idx++;
}
} else {
ret = throw( vars, this->source, len, "Array index out of bounds." );
}
SDL_UnlockSurface( surface );
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
} else {
ret = throw( vars, this->source, 0, "Not an array." );
}
}
if( ret ) {
if( fxenv->surfaces[ surf ] ) {
SDL_FreeSurface( fxenv->surfaces[ surf ] );
}
fxenv->surfaces[ surf ] = surface;
} else {
SDL_FreeSurface( surface );
}
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#endif
} else {
ret = throw( vars, this->source, 0, "Invalid surface dimensions." );
}
} else {
ret = throw( vars, this->source, surf, "Surface index out of bounds." );
}
dispose_temporary( &var );
}
return ret;
}
static enum result execute_blit_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
int idx = 0, params[ 7 ];
enum result ret = OKAY;
#if SDL_MAJOR_VERSION > 1
struct SDL_Rect clip, dest;
#else
struct SDL_Rect src, dest;
#endif
struct expression *expr = this->source;
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
while( ret && idx < 7 ) {
ret = evaluate_integer( expr, vars, ¶ms[ idx++ ] );
expr = expr->next;
}
if( ret ) {
idx = params[ 0 ];
if( idx >= 0 && idx < NUM_SURFACES ) {
#if SDL_MAJOR_VERSION > 1
clip.x = params[ 5 ];
clip.y = params[ 6 ];
clip.w = params[ 3 ];
clip.h = params[ 4 ];
dest.x = clip.x - params[ 1 ];
dest.y = clip.y - params[ 2 ];
SDL_QueryTexture( fxenv->surfaces[ idx ], NULL, NULL, &dest.w, &dest.h );
SDL_RenderSetClipRect( fxenv->renderer, &clip );
if( SDL_RenderCopy( fxenv->renderer, fxenv->surfaces[ idx ], NULL, &dest ) ) {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#else
src.x = params[ 1 ];
src.y = params[ 2 ];
src.w = params[ 3 ];
src.h = params[ 4 ];
dest.x = params[ 5 ];
dest.y = params[ 6 ];
if( SDL_BlitSurface( fxenv->surfaces[ idx ], &src, SDL_GetVideoSurface(), &dest ) ) {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#endif
} else {
ret = throw( vars, this->source, idx, "Surface index out of bounds." );
}
}
return ret;
}
static enum result execute_rect_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
enum result ret = OKAY;
int idx = 0, params[ 5 ];
struct SDL_Rect rect;
struct expression *expr = this->source;
#if SDL_MAJOR_VERSION > 1
int colour;
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
#endif
while( ret && idx < 5 ) {
ret = evaluate_integer( expr, vars, ¶ms[ idx++ ] );
expr = expr->next;
}
if( ret ) {
rect.x = params[ 0 ];
rect.y = params[ 1 ];
rect.w = params[ 2 ];
rect.h = params[ 3 ];
#if SDL_MAJOR_VERSION > 1
colour = params[ 4 ];
SDL_RenderSetClipRect( fxenv->renderer, NULL );
SDL_SetRenderDrawColor( fxenv->renderer,
( colour >> 16 ) & 0xFF, ( colour >> 8 ) & 0xFF, colour & 0xFF, 0xFF );
if( SDL_RenderFillRect( fxenv->renderer, &rect ) ) {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#else
if( SDL_FillRect( SDL_GetVideoSurface(), &rect, params[ 4 ] ) ) {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
#endif
}
return ret;
}
static enum result execute_show_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
#if SDL_MAJOR_VERSION > 1
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
SDL_SetRenderTarget( fxenv->renderer, NULL );
SDL_RenderCopy( fxenv->renderer, fxenv->target, NULL, NULL );
SDL_RenderPresent( fxenv->renderer );
SDL_SetRenderTarget( fxenv->renderer, fxenv->target );
#else
SDL_UpdateRect( SDL_GetVideoSurface(), 0, 0, 0, 0 );
#endif
return OKAY;
}
static enum result execute_sleep_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
int millis;
enum result ret = evaluate_integer( this->source, vars, &millis );
if( ret && millis > 0 ) {
SDL_Delay( millis );
}
return ret;
}
static enum result execute_timer_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
int millis;
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
enum result ret = evaluate_integer( this->source, vars, &millis );
if( ret ) {
if( millis > 0 ) {
fxenv->timer = SDL_AddTimer( millis, timer_callback, fxenv );
if( !fxenv->timer ) {
ret = throw( vars, this->source, millis, "Unable to start timer." );
}
} else {
if( SDL_RemoveTimer( fxenv->timer ) == 0 ) {
ret = throw( vars, this->source, millis, "Unable to stop timer." );
}
}
}
return ret;
}
static enum result execute_audio_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
SDL_AudioSpec audiospec = { 0 };
int ticklen;
enum result ret = evaluate_integer( this->source, vars, &ticklen );
if( ret ) {
/* audio period; (Samples per tick at 24khz, 480 = 50hz) */
if( ticklen > 0 ) {
ticklen = ticklen * SAMPLE_RATE / 24000;
if( ticklen >= MIN_TICK_LEN && ticklen <= MAX_TICK_LEN ) {
SDL_LockAudio();
fxenv->tick_len = ticklen;
SDL_UnlockAudio();
if( SDL_GetAudioStatus() == SDL_AUDIO_STOPPED ) {
audiospec.freq = SAMPLE_RATE;
audiospec.format = AUDIO_S16SYS;
audiospec.channels = 2;
audiospec.samples = MIN_TICK_LEN;
audiospec.callback = audio_callback;
audiospec.userdata = fxenv;
if( SDL_OpenAudio( &audiospec, NULL ) >= 0 ) {
SDL_PauseAudio( 0 );
} else {
ret = throw( vars, this->source, 0, SDL_GetError() );
}
}
} else {
ret = throw( vars, this->source, ticklen, "Invalid tick length." );
}
} else {
SDL_CloseAudio();
fxenv->tick = fxenv->tick_len = fxenv->audio_idx = fxenv->audio_end = fxenv->stream_idx = 0;
memset( fxenv->audio, 0, sizeof( fxenv->audio ) );
memset( fxenv->stream, 0, sizeof( fxenv->stream ) );
memset( fxenv->ramp_buf, 0, sizeof( fxenv->ramp_buf ) );
}
}
return ret;
}
static enum result execute_sample_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
/* sample index "data" loopstart looplen; */
int loop, llen, lend, idx, len;
struct variable data = { 0 };
struct expression *expr = this->source;
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
enum result ret = evaluate_integer( expr, vars, &idx );
if( ret ) {
expr = expr->next;
ret = evaluate_string( expr, vars, &data );
}
if( ret ) {
expr = expr->next;
ret = evaluate_integer( expr, vars, &loop );
}
if( ret ) {
expr = expr->next;
ret = evaluate_integer( expr, vars, &llen );
}
if( ret ) {
if( idx > 0 && idx <= NUM_SAMPLES ) {
len = data.string_value->length;
if( len < MAX_SAMPLE_LEN ) {
lend = loop + llen;
if( loop >= 0 && lend >= loop && lend <= len ) {
SDL_LockAudio();
fxenv->samples[ idx - 1 ].loop_start = loop;
fxenv->samples[ idx - 1 ].loop_length = llen;
assign_variable( &data, &fxenv->samples[ idx - 1 ].sample_data );
SDL_UnlockAudio();
} else {
ret = throw( vars, this->source, lend, "Loop out of bounds." );
}
} else {
ret = throw( vars, this->source, len, "Sample data too long." );
}
} else {
ret = throw( vars, this->source, idx, "Invalid sample index." );
}
}
dispose_variable( &data );
return ret;
}
static enum result execute_play_statement( struct statement *this,
struct variables *vars, struct variable *result ) {
int channel;
struct expression *expr = this->source;
struct variable sequence = { 0, NULL };
struct fxenvironment *fxenv = ( struct fxenvironment * ) vars->func->env;
enum result ret = evaluate_integer( expr, vars, &channel );
if( ret ) {