summary refs log tree commit diff stats
path: root/libs/CocosDenshion/CocosDenshion.h
blob: 638d85259709146dd97721dc212108c7d6710c21 (plain) (blame)
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
/*
 Copyright (c) 2010 Steve Oldmeadow
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 $Id$
 */



/** 
@file
@b IMPORTANT
There are 3 different ways of using CocosDenshion. Depending on which you choose you 
will need to include different files and frameworks.

@par SimpleAudioEngine
This is recommended for basic audio requirements. If you just want to play some sound fx
and some background music and have no interest in learning the lower level workings then
this is the interface to use.

Requirements:
 - Firmware: OS 2.2 or greater 
 - Files: SimpleAudioEngine.*, CocosDenshion.*
 - Frameworks: OpenAL, AudioToolbox, AVFoundation
 
@par CDAudioManager
CDAudioManager is basically a thin wrapper around an AVAudioPlayer object used for playing
background music and a CDSoundEngine object used for playing sound effects. It manages the
audio session for you deals with audio session interruption. It is fairly low level and it
is expected you have some understanding of the underlying technologies. For example, for 
many use cases regarding background music it is expected you will work directly with the
backgroundMusic AVAudioPlayer which is exposed as a property.
 
Requirements:
  - Firmware: OS 2.2 or greater 
  - Files: CDAudioManager.*, CocosDenshion.*
  - Frameworks: OpenAL, AudioToolbox, AVFoundation

@par CDSoundEngine
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch 
example. It can playback up to 32 sounds simultaneously with control over pitch, pan
and gain.  It can be set up to handle audio session interruption automatically.  You 
may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
because you require OS 2.0 compatibility.
 
Requirements:
  - Firmware: OS 2.0 or greater 
  - Files: CocosDenshion.*
  - Frameworks: OpenAL, AudioToolbox
 
*/ 

#import <OpenAL/al.h>
#import <OpenAL/alc.h>
#import <AudioToolbox/AudioToolbox.h>
#import <Foundation/Foundation.h>
#import "CDConfig.h"


#if !defined(CD_DEBUG) || CD_DEBUG == 0
#define CDLOG(...) do {} while (0)
#define CDLOGINFO(...) do {} while (0)

#elif CD_DEBUG == 1
#define CDLOG(...) NSLog(__VA_ARGS__)
#define CDLOGINFO(...) do {} while (0)

#elif CD_DEBUG > 1
#define CDLOG(...) NSLog(__VA_ARGS__)
#define CDLOGINFO(...) NSLog(__VA_ARGS__)
#endif // CD_DEBUG


#import "CDOpenALSupport.h"

//Tested source limit on 2.2.1 and 3.1.2 with up to 128 sources and appears to work. Older OS versions e.g 2.2 may support only 32
#define CD_SOURCE_LIMIT 32 //Total number of sources we will ever want, may actually get less
#define CD_NO_SOURCE 0xFEEDFAC //Return value indicating playback failed i.e. no source
#define CD_IGNORE_AUDIO_SESSION 0xBEEFBEE //Used internally to indicate audio session will not be handled
#define CD_MUTE      0xFEEDBAB //Return value indicating sound engine is muted or non functioning
#define CD_NO_SOUND = -1;

#define CD_SAMPLE_RATE_HIGH 44100
#define CD_SAMPLE_RATE_MID  22050
#define CD_SAMPLE_RATE_LOW  16000
#define CD_SAMPLE_RATE_BASIC 8000
#define CD_SAMPLE_RATE_DEFAULT 44100

extern NSString * const kCDN_BadAlContext;
extern NSString * const kCDN_AsynchLoadComplete;

extern float const kCD_PitchDefault;
extern float const kCD_PitchLowerOneOctave;
extern float const kCD_PitchHigherOneOctave;
extern float const kCD_PanDefault;
extern float const kCD_PanFullLeft;
extern float const kCD_PanFullRight;
extern float const kCD_GainDefault;

enum bufferState {
	CD_BS_EMPTY = 0,
	CD_BS_LOADED = 1,
	CD_BS_FAILED = 2
};

typedef struct _sourceGroup {
	int startIndex;
	int currentIndex;
	int totalSources;
	bool enabled;
	bool nonInterruptible;
	int *sourceStatuses;//pointer into array of source status information
} sourceGroup;

typedef struct _bufferInfo {
	ALuint bufferId;
	int bufferState;
	void* bufferData;
	ALenum format;
	ALsizei sizeInBytes;
	ALsizei frequencyInHertz;
} bufferInfo;	

typedef struct _sourceInfo {
	bool usable;
	ALuint sourceId;
	ALuint attachedBufferId;
} sourceInfo;	

#pragma mark CDAudioTransportProtocol

@protocol CDAudioTransportProtocol <NSObject>
/** Play the audio */
-(BOOL) play;
/** Pause the audio, retain resources */
-(BOOL) pause;
/** Stop the audio, release resources */
-(BOOL) stop;
/** Return playback to beginning */
-(BOOL) rewind;
@end

#pragma mark CDAudioInterruptProtocol

@protocol CDAudioInterruptProtocol <NSObject>
/** Is audio mute */
-(BOOL) mute;
/** If YES then audio is silenced but not stopped, calls to start new audio will proceed but silently */
-(void) setMute:(BOOL) muteValue;
/** Is audio enabled */
-(BOOL) enabled;
/** If NO then all audio is stopped and any calls to start new audio will be ignored */
-(void) setEnabled:(BOOL) enabledValue;
@end

#pragma mark CDUtilities
/**
 Collection of utilities required by CocosDenshion
 */
@interface CDUtilities : NSObject
{
}	

/** Fundamentally the same as the corresponding method is CCFileUtils but added to break binding to cocos2d */
+(NSString*) fullPathFromRelativePath:(NSString*) relPath;

@end


#pragma mark CDSoundEngine

/** CDSoundEngine is built upon OpenAL and works with SDK 2.0.
 CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch 
 example. It can playback up to 32 sounds simultaneously with control over pitch, pan
 and gain.  It can be set up to handle audio session interruption automatically.  You 
 may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
 because you require OS 2.0 compatibility.
 
 Requirements:
 - Firmware: OS 2.0 or greater 
 - Files: CocosDenshion.*
 - Frameworks: OpenAL, AudioToolbox
 
 @since v0.8
 */
@class CDSoundSource;
@interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> {
	
	bufferInfo		*_buffers;
	sourceInfo		*_sources;
	sourceGroup	    *_sourceGroups;
	ALCcontext		*context;
	NSUInteger		_sourceGroupTotal;
	UInt32			_audioSessionCategory;
	BOOL			_handleAudioSession;
	ALfloat			_preMuteGain;
	NSObject        *_mutexBufferLoad;
	BOOL			mute_;
	BOOL			enabled_;

	ALenum			lastErrorCode_;
	BOOL			functioning_;
	float			asynchLoadProgress_;
	BOOL			getGainWorks_;
	
	//For managing dynamic allocation of sources and buffers
	int sourceTotal_;
	int bufferTotal;
	 
}

@property (readwrite, nonatomic) ALfloat masterGain;
@property (readonly)  ALenum lastErrorCode;//Last OpenAL error code that was generated
@property (readonly)  BOOL functioning;//Is the sound engine functioning
@property (readwrite) float asynchLoadProgress;
@property (readonly)  BOOL getGainWorks;//Does getting the gain for a source work
/** Total number of sources available */
@property (readonly) int sourceTotal;
/** Total number of source groups that have been defined */
@property (readonly) NSUInteger sourceGroupTotal;

/** Sets the sample rate for the audio mixer. For best performance this should match the sample rate of your audio content */
+(void) setMixerSampleRate:(Float32) sampleRate;

/** Initializes the engine with a group definition and a total number of groups */
-(id)init;

/** Plays a sound in a channel group with a pitch, pan and gain. The sound could played looped or not */
-(ALuint) playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop;

/** Creates and returns a sound source object for the specified sound within the specified source group.
 */
-(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId;

/** Stops playing a sound */
- (void) stopSound:(ALuint) sourceId;
/** Stops playing a source group */
- (void) stopSourceGroup:(int) sourceGroupId;
/** Stops all playing sounds */
-(void) stopAllSounds;
-(void) defineSourceGroups:(NSArray*) sourceGroupDefinitions;
-(void) defineSourceGroups:(int[]) sourceGroupDefinitions total:(NSUInteger) total;
-(void) setSourceGroupNonInterruptible:(int) sourceGroupId isNonInterruptible:(BOOL) isNonInterruptible;
-(void) setSourceGroupEnabled:(int) sourceGroupId enabled:(BOOL) enabled;
-(BOOL) sourceGroupEnabled:(int) sourceGroupId;
-(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq;
-(BOOL) loadBuffer:(int) soundId filePath:(NSString*) filePath;
-(void) loadBuffersAsynchronously:(NSArray *) loadRequests;
-(BOOL) unloadBuffer:(int) soundId;
-(ALCcontext *) openALContext;

/** Returns the duration of the buffer in seconds or a negative value if the buffer id is invalid */
-(float) bufferDurationInSeconds:(int) soundId;
/** Returns the size of the buffer in bytes or a negative value if the buffer id is invalid */
-(ALsizei) bufferSizeInBytes:(int) soundId;
/** Returns the sampling frequency of the buffer in hertz or a negative value if the buffer id is invalid */
-(ALsizei) bufferFrequencyInHertz:(int) soundId;

/** Used internally, never call unless you know what you are doing */
-(void) _soundSourcePreRelease:(CDSoundSource *) soundSource;

@end

#pragma mark CDSoundSource
/** CDSoundSource is a wrapper around an OpenAL sound source.
 It allows you to manipulate properties such as pitch, gain, pan and looping while the 
 sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much
 added functionality.
 
 @since v1.0
 */
@interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInterruptProtocol> {
	ALenum lastError;
@public
	ALuint _sourceId;
	ALuint _sourceIndex;
	CDSoundEngine* _engine;
	int _soundId;
	float _preMuteGain;
	BOOL enabled_;
	BOOL mute_;
}
@property (readwrite, nonatomic) float pitch;
@property (readwrite, nonatomic) float gain;
@property (readwrite, nonatomic) float pan;
@property (readwrite, nonatomic) BOOL looping;
@property (readonly)  BOOL isPlaying;
@property (readwrite, nonatomic) int soundId;
/** Returns the duration of the attached buffer in seconds or a negative value if the buffer is invalid */
@property (readonly) float durationInSeconds;

/** Stores the last error code that occurred. Check against AL_NO_ERROR */
@property (readonly) ALenum lastError;
/** Do not init yourself, get an instance from the sourceForSound factory method on CDSoundEngine */
-(id)init:(ALuint) theSourceId sourceIndex:(int) index soundEngine:(CDSoundEngine*) engine;

@end

#pragma mark CDAudioInterruptTargetGroup

/** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled.
 Setting mute and enabled for the group propagates to all children. 
 Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings
 if that is what you want to do.*/
@interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol> {
	BOOL mute_;
	BOOL enabled_;
	NSMutableArray *children_;
}
-(void) addAudioInterruptTarget:(NSObject<CDAudioInterruptProtocol>*) interruptibleTarget;
@end

#pragma mark CDAsynchBufferLoader

/** CDAsynchBufferLoader
 TODO
 */
@interface CDAsynchBufferLoader : NSOperation {
	NSArray *_loadRequests;
	CDSoundEngine *_soundEngine;
}	

-(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine;

@end

#pragma mark CDBufferLoadRequest

/** CDBufferLoadRequest */
@interface CDBufferLoadRequest: NSObject
{
	NSString *filePath;
	int		 soundId;
	//id       loader;
}

@property (readonly) NSString *filePath;
@property (readonly) int soundId;

- (id)init:(int) theSoundId filePath:(const NSString *) theFilePath;
@end

/** Interpolation type */
typedef enum {
	kIT_Linear,			//!Straight linear interpolation fade
	kIT_SCurve,			//!S curved interpolation
	kIT_Exponential 	//!Exponential interpolation
} tCDInterpolationType;

#pragma mark CDFloatInterpolator
@interface CDFloatInterpolator: NSObject
{
	float start;
	float end;
	float lastValue;
	tCDInterpolationType interpolationType;
}
@property (readwrite, nonatomic) float start;
@property (readwrite, nonatomic) float end;
@property (readwrite, nonatomic) tCDInterpolationType interpolationType;

/** Return a value between min and max based on t which represents fractional progress where 0 is the start
 and 1 is the end */
-(float) interpolate:(float) t;
-(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal;

@end

#pragma mark CDPropertyModifier

/** Base class for classes that modify properties such as pitch, pan and gain */
@interface CDPropertyModifier: NSObject
{
	CDFloatInterpolator *interpolator;
	float startValue;
	float endValue;
	id target;
	BOOL stopTargetWhenComplete;
	
}
@property (readwrite, nonatomic) BOOL stopTargetWhenComplete;
@property (readwrite, nonatomic) float startValue;
@property (readwrite, nonatomic) float endValue;
@property (readwrite, nonatomic) tCDInterpolationType interpolationType;

-(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal;
/** Set to a fractional value between 0 and 1 where 0 equals the start and 1 equals the end*/
-(void) modify:(float) t;

-(void) _setTargetProperty:(float) newVal;
-(float) _getTargetProperty;
-(void) _stopTarget;
-(Class) _allowableType;

@end

#pragma mark CDSoundSourceFader

/** Fader for CDSoundSource objects */
@interface CDSoundSourceFader : CDPropertyModifier{}
@end

#pragma mark CDSoundSourcePanner

/** Panner for CDSoundSource objects */
@interface CDSoundSourcePanner : CDPropertyModifier{}
@end

#pragma mark CDSoundSourcePitchBender

/** Pitch bender for CDSoundSource objects */
@interface CDSoundSourcePitchBender : CDPropertyModifier{}
@end

#pragma mark CDSoundEngineFader

/** Fader for CDSoundEngine objects */
@interface CDSoundEngineFader : CDPropertyModifier{}
@end
itter Kelly Rauchenberger <fefferburbia@gmail.com> 2018-08-15 18:45:29 -0400 Started to modernize bot (this is completely broken)' href='/infinite/commit/infinite.cpp?id=0baed246b6f287e1c03519536011f34e87d19920'>0baed24 ^
d5ef658 ^

330f75e
5413c1c ^
3bc878e ^
5413c1c ^
d5c32fc ^
0baed24 ^



5413c1c ^
0baed24 ^

5413c1c ^
0baed24 ^




5413c1c ^
0baed24 ^
5413c1c ^
5413c1c ^

0baed24 ^

d5c32fc ^

3bc878e ^
0baed24 ^







5413c1c ^



3bc878e ^
d5ef658 ^
330f75e



3bc878e ^
330f75e



3bc878e ^
330f75e



d5ef658 ^
330f75e
d5ef658 ^
330f75e

















3bc878e ^
330f75e







d5ef658 ^
330f75e










d5ef658 ^



330f75e
3bc878e ^
330f75e












3bc878e ^
330f75e



3bc878e ^
330f75e

5413c1c ^
d5ef658 ^
5413c1c ^

330f75e



3bc878e ^
330f75e

3bc878e ^
5413c1c ^

330f75e
5413c1c ^
3bc878e ^
d5c32fc ^
330f75e


3bc878e ^
330f75e
3bc878e ^
330f75e



3bc878e ^
330f75e



3bc878e ^
330f75e









3bc878e ^
330f75e





3bc878e ^
330f75e































3bc878e ^
330f75e



3bc878e ^
330f75e

3bc878e ^
330f75e






3bc878e ^
330f75e


3bc878e ^
330f75e



3bc878e ^
330f75e



3bc878e ^
330f75e



3bc878e ^
330f75e


3bc878e ^
5413c1c ^
330f75e
3bc878e ^
330f75e
330f75e
3bc878e ^
5413c1c ^
d4c7cc7 ^
d0ea726 ^
d5c32fc ^
d0ea726 ^
d4c7cc7 ^
d0ea726 ^


3bc878e ^
330f75e



d5c32fc ^
3bc878e ^
d4c7cc7 ^
330f75e














3bc878e ^
330f75e

3bc878e ^
330f75e

0baed24 ^
3bc878e ^
0baed24 ^
3bc878e ^
330f75e
0baed24 ^


3bc878e ^
330f75e
3bc878e ^
d4c7cc7 ^
3944d73 ^
d4c7cc7 ^

8170d9f ^
d4c7cc7 ^
8170d9f ^
d4c7cc7 ^
3bc878e ^
5413c1c ^
330f75e
5413c1c ^

3bc878e ^
5413c1c ^



330f75e
5413c1c ^

330f75e

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








                          
                    
                    

                 



                           
 


                                                            
 
     
 







                                                                                  
 


                                                      
 





































































































                                                                                              
 

                                                                      
 







                                                                                                                              
 



                     
 










                                            
 


                    
 

                
 




                                                               
             









                                                                                                                               
 



                                                                                        
 



                                                         
 



                                                                                 
 

                               
 



                                     
 











                                                                      
 


                                                                                             
 







                                                                                              
 






                                                                                              
 



                                                                             
 








                                                                            
 



                                                                         
 







                                                                                              
 




                                                                                         
 
                                     
 

                                 
 













                                                                                                                                  
 





                                                                                          
 



                                                                                              
 

                            
 


                                                                                          
 

                            
 


                                                                                                     
 

                            
 







                                                                                    
 

                            
 


                                                                                           
 

                            
 


                                                                                        
 

                            
 


                                                                 
 



                            
 
                           
 

                      
 

                    
 


                                                              
 



                                                                                   
 





                                                                                               
 
                          
 

                    
 


                                                                                     
 

                    
 






                                                               
 
                                                                                       
 
                         
 





                                                                   
 


                    
 





                



                         
 

                                                 
 
                               




                                                                      
 







                                                                         
 
                     
   
                                                                   

                            
                                                               
     
 
                         
                     
                         





                                   
 








                          
                                            

         
     
   
 
                  
                                                               



                                                           
   

                                                       
 




                                                   
     
                              
     

   

                    

                                                             
 







                               



                                                   
 
                                  



                                                                             
 



                                                                                                     
 



                                                                                                                     
                                           
       
                                                                                                                      

















                                                                                                     
 







                                                                                                                      
                                               










                                                        



                                                                   
       
 












                                                                                                            
 



                                                                               
 

                                                                     
 
                                     

                           



                           
 

                                                                       
 

                           
     
                                                              
 
                                                    


                                                                                                          
                                                         
                                         
 



                                                      
 



                                    
 









                                                                                                   
 





                             
 































                                                                                                 
 



                           
 

                                                                                
 






                                                                                                 
 


                                          
 



                                   
 



                                   
 



                                   
 


                                                               
 
                                                               
                                                        
 
                  
     
 
                                     
                                   
                                                    
                                                                     
     
                                                                                                      


                                
 



                                                                                 
                                              
 
                                                                       














                                                       
 

                        
 

                                                       
                                                                
 
                        
 
                           


                              
 
                                                                               
 
                          
                                                                                                                                      

                                   
                                                                                                         
            
                                                                              
     
 
       
     

                                                                                                           
 



                                                                                  
     

                                                       

   
#include "fractal.h"
#include <Magick++.h>
#include <ctime>
#include <cstdio>
#include <iostream>
#include <verbly.h>
#include <fstream>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include <twitter.h>
#include <algorithm>
#include <chrono>
#include <thread>

class fill_blanks {
  private:
    verbly::data& database;

  public:
    fill_blanks(verbly::data& database) : database(database)
    {

    }

    verbly::filter<verbly::noun> parse_selrestrs(verbly::frame::selrestr selrestr)
    {
      switch (selrestr.get_type())
      {
        case verbly::frame::selrestr::type::empty:
        {
          return verbly::filter<verbly::noun>{};
        }

        case verbly::frame::selrestr::type::singleton:
        {
          verbly::noun n;

          if (selrestr.get_restriction() == "concrete")
          {
            n = database.nouns().with_singular_form("physical entity").limit(1).run().front();
          } else if (selrestr.get_restriction() == "time")
          {
            n = database.nouns().with_singular_form("time").limit(1).run().front();
          } else if (selrestr.get_restriction() == "state")
          {
            n = database.nouns().with_singular_form("state").limit(1).run().front();
          } else if (selrestr.get_restriction() == "abstract")
          {
            n = database.nouns().with_singular_form("abstract entity").limit(1).run().front();
          } else if (selrestr.get_restriction() == "time")
          {
            n = database.nouns().with_singular_form("time").limit(1).run().front();
          } else if (selrestr.get_restriction() == "scalar")
          {
            n = database.nouns().with_singular_form("number").limit(1).run().front();
          } else if (selrestr.get_restriction() == "currency")
          {
            auto nn2 = database.nouns().with_singular_form("currency").limit(2).run();
            std::vector<verbly::noun> nn(std::begin(nn2), std::end(nn2));
            n = nn[1];
          } else if (selrestr.get_restriction() == "location")
          {
            n = database.nouns().with_singular_form("location").limit(1).run().front();
          } else if (selrestr.get_restriction() == "organization")
          {
            n = database.nouns().with_singular_form("organization").limit(1).run().front();
          } else if (selrestr.get_restriction() == "int_control")
          {
            n = database.nouns().with_singular_form("causal agent").limit(1).run().front();
          } else if (selrestr.get_restriction() == "natural")
          {
            n = database.nouns().with_singular_form("natural object").limit(1).run().front();
          } else if (selrestr.get_restriction() == "phys_obj")
          {
            n = database.nouns().with_singular_form("physical object").limit(1).run().front();
          } else if (selrestr.get_restriction() == "solid")
          {
            n = database.nouns().with_singular_form("solid").limit(1).run().front();
          } else if (selrestr.get_restriction() == "shape")
          {
            n = database.nouns().with_singular_form("shape").limit(1).run().front();
          } else if (selrestr.get_restriction() == "substance")
          {
            n = database.nouns().with_singular_form("substance").limit(1).run().front();
          } else if (selrestr.get_restriction() == "idea")
          {
            n = database.nouns().with_singular_form("idea").limit(1).run().front();
          } else if (selrestr.get_restriction() == "sound")
          {
            auto nn2 = database.nouns().with_singular_form("sound").limit(4).run();
            std::vector<verbly::noun> nn(std::begin(nn2), std::end(nn2));
            n = nn[3];
          } else if (selrestr.get_restriction() == "communication")
          {
            n = database.nouns().with_singular_form("communication").limit(1).run().front();
          } else if (selrestr.get_restriction() == "region")
          {
            n = database.nouns().with_singular_form("region").limit(1).run().front();
          } else if (selrestr.get_restriction() == "place")
          {
            n = database.nouns().with_singular_form("place").limit(1).run().front();
          } else if (selrestr.get_restriction() == "machine")
          {
            n = database.nouns().with_singular_form("machine").limit(1).run().front();
          } else if (selrestr.get_restriction() == "animate")
          {
            n = database.nouns().with_singular_form("animate being").limit(1).run().front();
          } else if (selrestr.get_restriction() == "plant")
          {
            auto nn2 = database.nouns().with_singular_form("plant").limit(2).run();
            std::vector<verbly::noun> nn(std::begin(nn2), std::end(nn2));
            n = nn[1];
          } else if (selrestr.get_restriction() == "comestible")
          {
            n = database.nouns().with_singular_form("food").limit(1).run().front();
          } else if (selrestr.get_restriction() == "artifact")
          {
            n = database.nouns().with_singular_form("artifact").limit(1).run().front();
          } else if (selrestr.get_restriction() == "vehicle")
          {
            n = database.nouns().with_singular_form("vehicle").limit(1).run().front();
          } else if (selrestr.get_restriction() == "human")
          {
            n = database.nouns().with_singular_form("person").limit(1).run().front();
          } else if (selrestr.get_restriction() == "animal")
          {
            n = database.nouns().with_singular_form("animal").limit(1).run().front();
          } else if (selrestr.get_restriction() == "body_part")
          {
            n = database.nouns().with_singular_form("body part").limit(1).run().front();
          } else if (selrestr.get_restriction() == "garment")
          {
            n = database.nouns().with_singular_form("clothing").limit(1).run().front();
          } else if (selrestr.get_restriction() == "tool")
          {
            n = database.nouns().with_singular_form("tool").limit(1).run().front();
          } else {
            return verbly::filter<verbly::noun>{};
          }

          return verbly::filter<verbly::noun>{n, !selrestr.get_pos()};
        }

        case verbly::frame::selrestr::type::group:
        {
          verbly::filter<verbly::noun> ret;
          ret.set_orlogic(selrestr.get_orlogic());

          std::transform(std::begin(selrestr), std::end(selrestr), std::back_inserter(ret), [&] (verbly::frame::selrestr sr) {
            return parse_selrestrs(sr);
          });

          return ret;
        }
      }
    }

    void visit(verbly::token& it)
    {
      switch (it.get_type())
      {
        case verbly::token::type::utterance:
        {
          for (auto& tkn : it)
          {
            if (!tkn.is_complete())
            {
              visit(tkn);

              break;
            }
          }

          break;
        }

        case verbly::token::type::fillin:
        {
          switch (it.get_fillin_type())
          {
            case verbly::token::fillin_type::participle_phrase:
            {
              for (;;)
              {
                verbly::verb v = database.verbs().has_frames().random().limit(1).run().front();
                auto frames = v.frames().run();
                std::vector<verbly::frame> filtered;
                std::remove_copy_if(std::begin(frames), std::end(frames), std::back_inserter(filtered), [] (verbly::frame& f) {
                  if (f.parts().size() < 2)
                  {
                    return true;
                  }

                  if (f.parts()[0].get_type() != verbly::frame::part::type::noun_phrase)
                  {
                    return true;
                  }

                  if (f.parts()[0].get_role() != "Agent")
                  {
                    return true;
                  }

                  if (f.parts()[1].get_type() != verbly::frame::part::type::verb)
                  {
                    return true;
                  }

                  return false;
                });

                if (filtered.empty())
                {
                  continue;
                }

                verbly::frame fr = filtered[rand() % filtered.size()];
                verbly::token utter;
                for (auto part : fr.parts())
                {
                  switch (part.get_type())
                  {
                    case verbly::frame::part::type::noun_phrase:
                    {
                      if (part.get_role() == "Agent")
                      {
                        continue;
                      }

                      if (part.get_synrestrs().count("adjp") == 1)
                      {
                        utter << verbly::token{verbly::token::fillin_type::adjective_phrase};

                        continue;
                      } else if ((part.get_synrestrs().count("be_sc_ing") == 1)
                        || (part.get_synrestrs().count("ac_ing") == 1)
                        || (part.get_synrestrs().count("sc_ing") == 1)
                        || (part.get_synrestrs().count("np_omit_ing") == 1)
                        || (part.get_synrestrs().count("oc_ing") == 1))
                      {
                        utter << verbly::token{verbly::token::fillin_type::participle_phrase};

                        continue;
                      } else if ((part.get_synrestrs().count("poss_ing") == 1)
                        || (part.get_synrestrs().count("possing") == 1)
                        || (part.get_synrestrs().count("pos_ing") == 1))
                      {
                        utter << verbly::token{"their"};
                        utter << verbly::token{verbly::token::fillin_type::participle_phrase};

                        continue;
                      } else if (part.get_synrestrs().count("genitive") == 1)
                      {
                        utter << verbly::token{"their"};

                        continue;
                      } else if (part.get_synrestrs().count("adv_loc") == 1)
                      {
                        if (rand() % 2 == 0)
                        {
                          utter << verbly::token{"here"};
                        } else {
                          utter << verbly::token{"there"};
                        }

                        continue;
                      } else if (part.get_synrestrs().count("refl") == 1)
                      {
                        utter << verbly::token{"themselves"};

                        continue;
                      } else if ((part.get_synrestrs().count("sc_to_inf") == 1)
                        || (part.get_synrestrs().count("ac_to_inf") == 1)
                        || (part.get_synrestrs().count("vc_to_inf") == 1)
                        || (part.get_synrestrs().count("rs_to_inf") == 1)
                        || (part.get_synrestrs().count("oc_to_inf") == 1))
                      {
                        utter << verbly::token{verbly::token::fillin_type::infinitive_phrase};

                        continue;
                      } else if (part.get_synrestrs().count("oc_bare_inf") == 1)
                      {
                        verbly::token tkn{verbly::token::fillin_type::infinitive_phrase};
                        tkn.set_extra(1);

                        utter << tkn;

                        continue;
                      }

                      auto selrestrs = fr.roles()[part.get_role()];
                      auto query = database.nouns().limit(1).random().is_not_proper().full_hyponym_of(parse_selrestrs(selrestrs));
                      verbly::noun n = query.run().front();
                      if ((rand() % 2 == 0) && (part.get_synrestrs().count("definite") == 0))
                      {
                        utter << verbly::token{"the"};
                      } else {
                        if (n.starts_with_vowel_sound())
                        {
                          utter << verbly::token{"an"};
                        } else {
                          utter << verbly::token{"a"};
                        }
                      }

                      if (part.get_synrestrs().count("plural") == 1)
                      {
                        utter << verbly::token{n, verbly::token::noun_inflection::plural};
                      } else {
                        utter << verbly::token{n};
                      }

                      if (part.get_synrestrs().count("acc_ing") == 1)
                      {
                        utter << verbly::token{verbly::token::fillin_type::participle_phrase};
                      }

                      break;
                    }

                    case verbly::frame::part::type::verb:
                    {
                      utter << verbly::token{v, verbly::token::verb_inflection::ing_form};

                      break;
                    }

                    case verbly::frame::part::type::literal_preposition:
                    {
                      utter << verbly::token{part.get_choices()[rand() % part.get_choices().size()]};

                      break;
                    }

                    case verbly::frame::part::type::selection_preposition:
                    {
                      auto query = database.prepositions();
                      for (auto preprestr : part.get_preprestrs())
                      {
                        query.in_group(preprestr);
                      }
                      utter << verbly::token{query.random().limit(1).run().front()};

                      break;
                    }

                    case verbly::frame::part::type::adjective:
                    {
                      utter << verbly::token{verbly::token::fillin_type::adjective_phrase};

                      break;
                    }

                    case verbly::frame::part::type::adverb:
                    {
                      utter << verbly::token{verbly::token::fillin_type::adverb_phrase};

                      break;
                    }

                    case verbly::frame::part::type::literal:
                    {
                      utter << verbly::token{part.get_literal()};

                      break;
                    }
                  }
                }

                it = utter;

                break;
              }

              break;
            }

            case verbly::token::fillin_type::adjective_phrase:
            {
              verbly::token phrase;

              if (rand() % 4 == 0)
              {
                phrase << verbly::token{verbly::token::fillin_type::adverb_phrase};
              }

              if (rand() % 2 == 0)
              {
                phrase << verbly::token{verbly::token::fillin_type::participle_phrase};
              } else {
                phrase << verbly::token{database.adjectives().random().limit(1).run().front()};
              }

              it = phrase;

              break;
            }

            case verbly::token::fillin_type::adverb_phrase:
            {
              it = verbly::token{database.adverbs().random().limit(1).run().front()};

              break;
            }

            case verbly::token::fillin_type::infinitive_phrase:
            {
              verbly::token utter;
              if (it.get_extra() != 1)
              {
                utter << verbly::token{"to"};
              }

              utter << verbly::token{database.verbs().random().limit(1).run().front()};

              it = utter;

              break;
            }

            default:
            {
              it = verbly::token{"*the reality of the situation*"};

              break;
            }
          }

          break;
        }
      }
    }
};

infinite::infinite(
  std::string configFile,
  std::mt19937& rng) :
    rng_(rng)
{
  // Load the config file.
  YAML::Node config = YAML::LoadFile(configFile);

  // Set up the Twitter client.
  twitter::auth auth;
  auth.setConsumerKey(config["consumer_key"].as<std::string>());
  auth.setConsumerSecret(config["consumer_secret"].as<std::string>());
  auth.setAccessKey(config["access_key"].as<std::string>());
  auth.setAccessSecret(config["access_secret"].as<std::string>());

  client_ = std::unique_ptr<twitter::client>(new twitter::client(auth));

  // Set up the verbly database.
  database_ = std::unique_ptr<verbly::database>(
    new verbly::database(config["verbly_datafile"].as<std::string>()));

  // Set up the sentence generator.
  generator_ = std::unique_ptr<sentence>(new sentence(*database_, rng_));

  // Parse forms file
  {
    std::ifstream datafile(config["forms_file"].as<std::string>());
    if (!datafile.is_open())
    {
      throw std::invalid_argument("Could not find forms file");
    }

    bool newgroup = true;
    std::string line;
    std::string curgroup;
    while (getline(datafile, line))
    {
      if (line.back() == '\r')
      {
        line.pop_back();
      }

      if (newgroup)
      {
        curgroup = line;
        newgroup = false;
      } else {
        if (line.empty())
        {
          newgroup = true;
        } else {
          groups_[curgroup].push_back(line);
        }
      }
    }
  }

  // Read in fonts
  std::string fontsdirname = config["fonts"].as<std::string>();
  DIR* fontdir;
  struct dirent* ent;
  
  if ((fontdir = opendir(fontsdirname.c_str())) == nullptr)
  {
    throw std::invalid_argument("Couldn't find fonts");
  }

  while ((ent = readdir(fontdir)) != nullptr)
  {
    std::string dname(ent->d_name);
    if ((dname.find(".otf") != std::string::npos)
      || (dname.find(".ttf") != std::string::npos))
    {
      fonts_.push_back(dname);
    }
  }

  closedir(fontdir);

  std::string colorsfile(config["colors"].as<std::string>());



}

int main(int argc, char** argv)
{


  
  for (;;)
  {
    // Generate the text
    std::cout << "Generating text..." << std::endl;

    std::string action = "{FORM}";
    int tknloc;
    while ((tknloc = action.find("{")) != std::string::npos)
    {
      std::string token = action.substr(tknloc+1, action.find("}")-tknloc-1);

      std::string canontkn;
      std::transform(std::begin(token), std::end(token), std::back_inserter(canontkn), [] (char ch) {
        return std::toupper(ch);
      });

      std::string result;
      if (canontkn == "NOUN")
      {
        result = database.nouns().is_not_proper().random().limit(1).with_complexity(1).run().front().singular_form();
      } else if (canontkn == "SUPERLATIVE")
      {
        result = database.adjectives().requires_superlative_form().random().limit(1).run().front().superlative_form();
      } else if (canontkn == "VERB")
      {
        result = database.verbs().random().limit(1).run().front().infinitive_form();
      } else if (canontkn == "VERBED")
      {
        result = database.verbs().random().limit(1).run().front().past_tense_form();
      } else if (canontkn == "VERBS")
      {
        result = database.verbs().random().limit(1).run().front().s_form();
      } else if (canontkn == "VERBING")
      {
        result = database.verbs().random().limit(1).run().front().ing_form();
      } else if (canontkn == "LOCATION")
      {
        auto hem1 = database.nouns().with_singular_form("eastern hemisphere").limit(1).run().front();
        auto hem2 = database.nouns().with_singular_form("western hemisphere").limit(1).run().front();
        verbly::filter<verbly::noun> region{hem1, hem2};
        region.set_orlogic(true);

        result = database.nouns().full_part_holonym_of(region).random().limit(1).run().front().singular_form();
      } else if (canontkn == "LANGUAGE")
      {
        auto natlan = database.nouns().with_singular_form("natural language").limit(1).run().front();
        result = database.nouns().full_hyponym_of(natlan).is_proper().random().limit(1).run().front().singular_form();
      } else if (canontkn == "ADVERB")
      {
        result = database.adverbs().with_complexity(1).random().limit(1).run().front().base_form();
      } else if (canontkn == "VERBLY_SENTENCE")
      {
        fill_blanks yeah {database};
        verbly::token action{
          {"I am"},
          {verbly::token::fillin_type::adjective_phrase}
        };
        while (!action.is_complete())
        {
          yeah.visit(action);
        }
        result = action.compile();
      } else {
		    auto group = groups[canontkn];
        result = group[rand() % group.size()];
        std::cout << canontkn << ": " << group.size() << std::endl;
      }

      std::string finalresult;
      if (islower(token[0]))
      {
        std::transform(std::begin(result), std::end(result), std::back_inserter(finalresult), [] (char ch) {
          return std::tolower(ch);
        });
      } else if (isupper(token[0]) && !isupper(token[1]))
      {
        auto words = verbly::split<std::list<std::string>>(result, " ");
        for (auto& word : words)
        {
          word[0] = std::toupper(word[0]);
        }

        finalresult = verbly::implode(std::begin(words), std::end(words), " ");
      } else {
        finalresult = result;
      }

      action.replace(tknloc, action.find("}")-tknloc+1, finalresult);
    }

    std::cout << action << std::endl;

    // Generate the fractal
    double zoom = 2.0;
    double target_w = 1280;
    double target_h = 800;
    double sample_rate = 3;

    Magick::Image image(Magick::Geometry(target_w, target_h), "black");
    image.type(Magick::TrueColorMatteType);

    double coverage = 0.0;
    while (coverage < 0.05)
    {
      std::cout << "Generating flame fractal..." << std::endl;

      Fractal fractal = Fractal::random(colorsfile);
      std::vector<Color> irradiance(target_w*target_h*sample_rate*sample_rate, Color(0.0, 0.0, 0.0, 0.0));

      double x = (double)rand()/(double)RAND_MAX*2.0-1.0;
      double y = (double)rand()/(double)RAND_MAX*2.0-1.0;
      double c = (double)rand()/RAND_MAX;

      double widthmul = fractal.width/target_w*zoom;
      double heightmul = fractal.height/target_w*zoom;
      double widthmul2 = widthmul * 2.0;
      double heightmul2 = heightmul * 2.0;

      int maxrad = 0;
      for (int i=0; i<50000000; i++)
      {
        fractal.sample(x, y, c);

        int fx = (x+widthmul)/widthmul2*target_w*sample_rate;
        int fy = (y+heightmul)/heightmul2*target_h*sample_rate;

        if (fx >= 0 && fx < target_w*sample_rate && fy >= 0 && fy < target_h*sample_rate && i > 20)
        {
          auto& irr = irradiance[fx+fy*target_w*sample_rate];
          irr += fractal.get_color(c);
          double alph = irr.a;
          irr *= 0.5;
          irr.a = alph;

          if (irr.a > maxrad)
          {
            maxrad = irr.a;
          }
        }
      }

      image.modifyImage();
      Magick::Pixels view(image);
      Magick::PixelPacket* pixels = view.get(0, 0, target_w, target_h);

      double white = 200.0;
      double quality = sample_rate*sample_rate;
      double vibrancy = 1.0;
      double contrast = 1.0;
      double brightadjust = 2.3;
      double k1 = contrast * (268.0 * brightadjust) * 100.0 / fractal.brightness / (256.0*256.0);
      double k2 = 1.0 / (contrast * white * quality);
      int covered = 0;
      for (int j=0; j<target_h; j++)
      {
        for (int i=0; i<target_w; i++)
        {
          double freq_avg = 0.0;
          double freq_max = 0.0;
          Color color_avg(0.0,0.0,0.0,0.0);
          for (int sy = 0; sy<sample_rate; sy++)
          {
            for (int sx = 0; sx<sample_rate; sx++)
            {
              auto& fc = irradiance[i*sample_rate+sx+(j*sample_rate+sy)*target_w*sample_rate];
              freq_avg += fc.a;
              color_avg += fc;
              if (fc.a > freq_max)
              {
                freq_max = fc.a;
              }
            }
          }

          if (freq_max > 0)
          {
            covered++;
          }

          freq_avg *= (white * fractal.filterlevel)/(sample_rate * sample_rate);
          color_avg *= (fractal.filterlevel/(sample_rate*sample_rate));

          double alph = k1 * std::log(1+white*freq_avg*k2)/(std::log(10*white*freq_max));
          double alphg = pow(alph, 1.0/fractal.gamma);
          if (alph <= fractal.gammathresh)
          {
            double frac = alph / fractal.gammathresh;
            alphg = (1-frac)*alph*pow(fractal.gammathresh, 1.0/fractal.gamma - 1.0) + frac*alphg;
          }

          double ls = vibrancy*alphg/alph;
          Color finc = color_avg * ls;
          finc.a = 1.0;

          if (finc.r > 1.0)
          {
            finc *= (1.0 / finc.r);
          }

          if (finc.g > 1.0)
          {
            finc *= (1.0 / finc.g);
          }

          if (finc.b > 1.0)
          {
            finc *= (1.0 / finc.b);
          }

          *pixels++ = Magick::ColorRGB(finc.r, finc.g, finc.b);
        }
      }

      coverage = ((double)covered/(double)(target_w*target_h));
      std::cout << coverage << " coverage" << std::endl;

      view.sync();
    }

    // Put text on top of the fractal
    std::string subaction = action;
    std::string font = fonts[rand() % fonts.size()];
    if (font.find("Le_Super_Type_SemiBold.ttf") != std::string::npos)
    {
      std::transform(std::begin(subaction), std::end(subaction), std::begin(subaction), [] (char ch) {
        return std::toupper(ch);
      });
    }

    Magick::Image textimage(Magick::Geometry(target_w, target_h), "transparent");
    textimage.type(Magick::TrueColorMatteType);
    textimage.fillColor(Magick::Color("white"));
    textimage.fontPointsize(72.0);
    textimage.font(fontsdirname + "/" + font);

    auto words = verbly::split<std::list<std::string>>(subaction, " ");
    std::string towrite = "";
    std::string curline = "";
    Magick::TypeMetric metric;
    while (!words.empty())
    {
      std::string temp = curline + " " + words.front();
      textimage.fontTypeMetrics(temp, &metric);
      if (metric.textWidth() > ((target_w/10)*9))
      {
        towrite += "\n" + words.front();
        curline = words.front();
      } else {
        towrite += " " + words.front();
        curline = temp;
      }

      words.pop_front();
    }

    textimage.annotate(towrite, Magick::CenterGravity);
    textimage.opacity(((double)MaxRGB) * 0.8);
    //image.composite(textimage, 0, 0, Magick::OverCompositeOp);

    image.magick("png");

    Magick::Blob outputimg;
    //image.write(&outputimg);
    image.write("output.png");
    return 1;

    std::cout << "Generated image!" << std::endl << "Tweeting..." << std::endl;

    std::string tweetText;
    size_t tweetLim = 140 - client.getConfiguration().getCharactersReservedPerMedia() - client.getUser().getScreenName().length() - 6;
    if (action.length() > tweetLim)
    {
      tweetText = "\"" + action.substr(0, tweetLim - 1) + "…\" --@" + client.getUser().getScreenName();
    } else {
      tweetText = "\"" + action + "\" --@" + client.getUser().getScreenName();
    }

    try
    {
      long media_id = client.uploadMedia("image/jpeg", (const char*) outputimg.data(), outputimg.length());
      client.updateStatus(tweetText, {media_id});

      std::cout << "Done!" << std::endl << "Waiting..." << std::endl << std::endl;
    } catch (const twitter::twitter_error& e)
    {
      std::cout << "Twitter error: " << e.what() << std::endl;
    }

    std::this_thread::sleep_for(std::chrono::hours(1));
  }
}