code:
#ifndef __player_h__
#define __player_h__

#include "build.h"

#define MAXNUMORBS   8
#define MAXTREASURES 18
#define MAXWEAPONS   10
#define MAXPOTIONS   5
#define PLAYERHEIGHT 48

struct Player
{
    int32_t x, y, z;
    int ang;
    int horiz;
    int zoom;
    int height;
    int hvel;
    short sector, oldsector;
    short screensize;
    short spritenum;
    uint8_t dimension;
    uint32_t flags;
    int weapon[MAXWEAPONS];
    int ammo[MAXWEAPONS];
    int orbammo[MAXNUMORBS];
    int treasure[MAXTREASURES];
    int orbactive[MAXNUMORBS];
    int orb[MAXNUMORBS];
    int potion[MAXPOTIONS];
    int lvl;
    int score;
    int health;
    int svgahealth;
    int maxhealth;
    int armor;
    int armortype;
    uint8_t onsomething;
    int fallz;

    int8_t currentpotion;
    int8_t currweapon;
    int8_t selectedgun;
    int8_t currentorb;
    int8_t currweaponfired;
    int8_t currweaponanim;
    int8_t currweaponattackstyle;
    int8_t shieldpoints;
    int8_t poisoned;
    bool currweaponflip;
    bool spiked;
    bool playerdie;
    int invincibletime;

    bool hasshot;
    bool orbshot;

    int16_t helmettime;
    int16_t shadowtime;
    int16_t nightglowtime;
    int16_t strongtime;
    int16_t manatime;
    int16_t vampiretime;
    int16_t shockme;
    int16_t poisontime;
    int16_t invisibletime;

    fix16_t q16angle, q16oangle;
    fix16_t q16horiz, q16ohoriz;
    vec3_t opos;
};

extern Player player[MAXPLAYERS];

extern int pyrn;
extern int autohoriz;

void addarmoramount(int nArmor);
void addscoreamount(int nScore);
void drawweapons(Player *plr);
void drawarmor();
void drawpotionpic();
void drawscore();
void draworbpic();
void spikeheart(Player *plr);
void updatepics();
void sethealth(int hp);
void healthpic();
void setpotion(int nPotion);
//void score(int score);
void keyspic();
//void armorpic(int arm);
void autoweaponchange(int dagun);
void levelpic();
void shootgun(Player *plr, short daang, char guntype);
void potiontext();
int checkweapondist(short i, int x, int y, int z, char guntype);
void castaorb(Player *plr);
//void orbpic(int currentorb);
void goesupalevel(Player *plr);
void loadnewlevel(int mapon);
void displayspelltext();
void captureflagpic();
void fragspic();
void initplayersprite();
void plrfireweapon(Player *plr);
int lvlspellcheck(Player* plr);
void activatedaorb(Player* plr);
void usapotion(Player* plr);
void plruse(Player* plr);
void playerdead(Player* plr);
void autothehoriz(Player* plr);
void singleshot(short bstatus);
void weaponchange();
void checkcheat();
void victory();

#endif

repo_name: orochi/nblood

license: mit


code:
//
//    SNDMOD HEADER AND DEF'S
//

#ifndef __sndmod_h__
#define __sndmod_h__

// #define SND_CALLER

#define     S_THUNDER1              0
#define     S_THUNDER2              1
#define     S_THUNDER3              2
#define     S_THUNDER4              3
#define     S_WINDLOOP1             4
#define     S_WAVELOOP1             5
#define     S_LAVALOOP1             6
#define     S_FIRELOOP1             7
#define     S_STONELOOP1            8
#define     S_BATSLOOP              9
#define     S_PLRWEAPON0            10
#define     S_PLRWEAPON1            11
#define     S_PLRWEAPON2            12
#define     S_PLRWEAPON3            13
#define     S_PLRWEAPON4            14
#define     S_GOBLIN1               15
#define     S_GOBLIN2               16
#define     S_GOBLIN3               17
#define     S_GOBPAIN1              18
#define     S_GOBPAIN2              19
#define     S_GOBDIE1               20
#define     S_GOBDIE2               21
#define     S_GOBDIE3               22
#define     S_KSNARL1               23
#define     S_KSNARL2               24
#define     S_KSNARL3               25
#define     S_KSNARL4               26
#define     S_KPAIN1                27
#define     S_KPAIN2                28
#define     S_KDIE1                 29
#define     S_KDIE2                 30
#define     S_DEMON1                31
#define     S_DEMON2                32
#define     S_DEMON3                33
#define     S_DEMON4                34
#define     S_DEMON5                35
#define     S_DEMONDIE1             36
#define     S_DEMONDIE2             37
#define     S_MSNARL1               38
#define     S_MSNARL2               39
#define     S_MSNARL3               40
#define     S_MSNARL4               41
#define     S_MPAIN1                42
#define     S_MDEATH1               43
#define     S_DRAGON1               44
#define     S_DRAGON2               45
#define     S_DRAGON3               46
#define     S_RIP1              	47
#define     S_RIP2              	48
#define     S_RIP3              	49
#define     S_SKELHIT1          	50
#define     S_SKELHIT2          	51
#define     S_SKELETONDIE           52
#define     S_GUARDIAN1         	53
#define     S_GUARDIAN2         	54
#define     S_GUARDIANPAIN1     	55
#define     S_GUARDIANPAIN2     	56
#define     S_GUARDIANDIE           57
#define     S_WISP              	58
#define     S_WISP2             	59
#define     S_SPLASH1               60
#define     S_SPLASH2               61
#define     S_SPLASH3               62
#define     S_SPLASH4               63
#define     S_SPLASH5               64
#define     S_SPLASH6               65
#define     S_WILLOWDIE         	66
#define     S_FATWITCHDIE           67
#define     S_JUDY1             	68
#define     S_JUDY2             	69
#define     S_JUDY3             	70
#define     S_JUDY4             	71
#define     S_JUDYDIE               72
#define     S_SKULLWITCH1           73
#define     S_SKULLWITCH2           74
#define     S_SKULLWITCH3           75
#define     S_SKULLWITCHDIE     	76
#define     S_GRONDEATHA        	77
#define     S_GRONDEATHB        	78
#define     S_GRONDEATHC        	79
#define     S_CHAIN1                80
#define     S_FLAME1                81
#define     S_GRONPAINA        	    82
#define     S_GRONPAINB        	    83
#define     S_GRONPAINC        	    84
#define     S_CLUNK                 85
#define     S_DEMONTHROW            86
#define     S_WITCHTHROW            87
#define     S_DOOR1                 88
#define     S_DOOR2                 89
#define     S_DOOR3                 90
#define     S_CREAKDOOR1            91
#define     S_CREAKDOOR2            92
#define     S_CREAKDOOR3            93
#define     S_STING1                94
#define     S_STING2                95
#define     S_POTION1               96
#define     S_GENTHROW              97
#define     S_GENSWING              98
#define     S_ARROWHIT          	99
#define     S_WALLHIT1          	100
#define     S_GONG                  101
#define     S_SPELL1                102
#define     S_FREEZE                103
#define     S_FREEZEDIE             104
#define     S_TRAP1                 105
#define     S_TRAP2                 106
#define     S_RATS1                 107
#define     S_RATS2                 108
#define     S_WINDLOOP2         	109
#define     S_BREATH1               110
#define     S_BREATH2               111
#define     S_PUSH1             	112
#define     S_PUSH2             	113
#define     S_PLRPAIN1			    114
#define     S_PLRPAIN2              115
#define     S_GORE1                 116
#define     S_GORE2                 117
#define     S_GORE1A                118
#define     S_GORE1B                119
#define     S_DEADSTEP          	120
#define     S_HEARTBEAT         	121
#define     S_SOFTCHAINWALK     	122
#define     S_SOFTCREAKWALK     	123
#define     S_LOUDCHAINWALK     	124
#define     S_GRATEWALK         	125
#define     S_SCARYDUDE             126
#define     S_WATERY                127
#define     S_GLASSBREAK1           128
#define     S_GLASSBREAK2           129
#define     S_GLASSBREAK3           130
#define     S_TREASURE1         	131
#define     S_SWORD1                132
#define     S_SWORD2                133
#define     S_SWORDCLINK1           134
#define     S_SWORDCLINK2           135
#define     S_SWORDCLINK3           136
#define     S_SWORDCLINK4           137
#define     S_SOCK1                 138
#define     S_SOCK2                 139
#define     S_SOCK3                 140
#define     S_SOCK4                 141
#define     S_KOBOLDHIT         	142
#define     S_SPIDERBITE            143
#define     S_FIREBALL              144
#define     S_WOOD1             	145
#define     S_CHAINDOOR1            146
#define     S_PULLCHAIN1            147
#define     S_PICKUPAXE         	148
#define     S_EXPLODE               149
#define     S_SKELSEE               150
#define     S_BARRELBREAK           151
#define     S_WARP              	152
#define     S_SPELL2                153
#define     S_THROWPIKE         	154
#define     S_PICKUPFLAG        	155
#define     S_DROPFLAG          	156
#define     S_LAUGH             	157
#define     S_DRINK                 158
#define     S_PAGE                  159
#define     S_BOTTLES               160
#define     S_CRACKING              161
#define     S_PLRDIE1               162
#define     S_FATLAUGH			    163

#define  _OFF              0
#define  _ON               1
#define  _STANDARD_MUSIC   1
#define  _DIG_MIDI_MUSIC   2
#define  _LOOP_MUSIC       3

#define  MAX_AUX_TIMERS       4
#define  MAX_ACTIVE_SAMPLES   10
#define  MAX_ACTIVE_SONGS     4
//num of array elements in ambsoundarray[]
#define MAX_AMB_SOUNDS       6
#define  MAX_ACTIVE_FXLOOPS   4

#define  MAX_SND_LOOPS        8

#define  DIG_MIDI 2
#define  MIDI     1
#define  DIGI     0

#define  MENUSONG   0
#define  DEATHSONG  1

#define BASE_SONG   0
#define EMB_SONG    1
#define SPICE_SONG  2

#define  WINDSNDBIT        1
#define  WAVESNDBIT        2
#define  WATERSNDBIT       4
#define  LAVASNDBIT        8
#define  GRATESNDBIT       16
#define  CARTSNDBIT        32
#define  FIRE1SNDBIT       64
#define  FIRE2SNDBIT       128

/*
struct SampleType
{
	int      playing;
	uint32_t SOSHandle;
	uint32_t number;
	int32_t  priority;
	int32_t  x, y;
};
*/

struct ambsounds {
	int soundnum;       //the actual sound number S_x
	int hsound;     //the handle returned by hmi
};

#ifdef SND_CALLER

void _far _loadds timerevent(void);

//Callback functions
void _far cdecl sosDIGISampleCallback(  int16_t, int16_t, int16_t  );
void _far sosMIDISongCallback( int16_t );
void _far cdecl _loadds sosMIDITriggerCallback(  int16_t, BYTE, BYTE );

	//
	//defs for hmi Setup
	//
	// profile structure
	typedef  struct   _tagINIInstance
			{

				int16_t  wFlags;           // misc. flags
				BYTE  szName[ 128 ];    // name of .ini file

				PSTR  pData;            // pointer to .ini file in memory
				int16_t  wSize;            // size, in bytes, of file
				int16_t  wMaxSize;         // maximum size in bytes of the .ini

				PSTR  pCurrent;         // current location in file
				int16_t  wCurrent;         // current location in file

				PSTR  pSection;         // pointer to section start

				PSTR  pItemPtr;         // pointer to the start of line w/item
				PSTR  pItem;            // pointer to last item
				PSTR  pList;            // pointer to last item location, for list
												// management.
				PSTR  pListPtr;         // pointer for raw string list

			} _INI_INSTANCE;

	// equates
	#define  _INI_SECTION_START   '['
	#define  _INI_SECTION_END     ']'
	#define  _INI_EQUATE          '='
	#define  _INI_SPACE           ' '
	#define  _INI_TAB             0x9
	#define  _INI_STRING_START    '"'
	#define  _INI_STRING_END      '"'
	#define  _INI_EOL             0x0d
	#define  _INI_CR              0x0d
	#define  _INI_LF              0x0a
	#define  _INI_HEX_INDICATOR   'x'
	#define  _INI_LIST_SEPERATOR  ','

	// amount of bytes to allocate in addition to file size so that the
	// .ini file may be modified by the application.
	#define  _INI_EXTRA_MEMORY    1024

	// various flags for .ini structure
	#define  _INI_MODIFIED        0x8000

	// function prototypes
	BOOL  cdecl hmiINIOpen              ( _INI_INSTANCE * sInstance, PSTR szName );
	BOOL  cdecl hmiINIClose             ( _INI_INSTANCE * sInstance );
	BOOL  cdecl hmiINILocateSection     ( _INI_INSTANCE * sInstance, PSTR szName );
	BOOL  cdecl hmiINILocateItem        ( _INI_INSTANCE * sInstance, PSTR szItem );
	BOOL  cdecl hmiINIGetDecimal        ( _INI_INSTANCE * sInstance, int16_t * wValue );
	BOOL  cdecl hmiINIGetItemDecimal    ( _INI_INSTANCE * sInstance, PSTR szItem, int16_t * wValue );

	BOOL  cdecl sosEZGetConfig( PSTR );

	int16_t  wMIDIDeviceID,wDIGIDeviceID;

	//
	//          DIGI SPECIFIC
	//
	#define  _SOS_DMA_BUFFERSIZE     0x2000
	#define  _SOS_SAMPLE_RATE        11025
	//#define  _SOS_FILL_TIMER_RATE    40
	#define  _SOS_FILL_TIMER_RATE    100

	#define  _SAMPLE0                 0x1000
	#define  _SAMPLE1                 0x1001
	#define  _SAMPLE2                 0x1002
	#define  _SAMPLE3                 0x1003
	#define  _SAMPLE4                 0x1004
	#define  _SAMPLE5                 0x1005
	#define  _SAMPLE6                 0x1006
	#define  _SAMPLE7                 0x1007
	#define  _SAMPLE8                 0x1008
	#define  _SAMPLE9                 0x1009
	#define  _SAMPLE10                0x100a
	#define  _SAMPLE11                0x100b
	#define _LSAMPLE1                   0x100c
	#define _LSAMPLE2                   0x100d

	UINT  PanArray[] = {
		//REAR to HARD LEFT (angle = 0->512)
	0x8000,0x7000,0x6000,0x5000,0x4000,0x3000,0x2000,0x1000,0x0000,
		//HARD LEFT to CENTER (angle = 513-1024)
	0x1000,0x20f0,0x2000,0x3000,0x4000,0x5000,0x6000,0x7000,0x8000,
		//CENTER to HARD RIGHT (angle = 1025-1536)
	0x70f0,0x8000,0x9000,0xa000,0xb000,0xc000,0xd000,0xe000,0xf000,
		//HARD RIGHT to REAR (angle = 1537-2047)
	0xffff,0xf000,0xe000,0xd000,0xc000,0xb000,0xa000,0x9000,0x8000
	};

	volatile    SampleType  SampleRay[MAX_ACTIVE_SAMPLES];
	BYTE        ActiveSampleBits = 0x00;

	volatile    SampleType  FXLoopRay[MAX_ACTIVE_FXLOOPS];

	_SOS_CAPABILITIES sSOSDeviceCaps;
	_SOS_HARDWARE     sDIGIHardware;
	_SOS_INIT_DRIVER  sSOSInitDriver = {
		_SOS_DMA_BUFFERSIZE,
		_NULL,
		_TRUE,
		_SOS_SAMPLE_RATE,
		19,
		0L,
		_NULL,
		_NULL,
		_NULL,
		_SOS_NORMAL_TIMER
		};

	_SOS_INIT_DRIVER  sSOSInitDriver1 = {
		_SOS_DMA_BUFFERSIZE,
		_NULL,
		_TRUE,
		_SOS_SAMPLE_RATE,
		19,
		0L,
		_NULL,
		_NULL,
		_NULL,
		_SOS_NORMAL_TIMER
		};

	_SOS_START_SAMPLE sSOSSampleData[12] = {

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE0, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE1, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE2, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE3, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE4, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE5, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE6, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE7, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE8, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE9, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE10, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

		{  _NULL, 0L, 0, _CENTER_CHANNEL, 0x7fff,
			_SAMPLE11, sosDIGISampleCallback, 0, _VOLUME | _PANNING | _LOOPING,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L },

	};

//array for loop and pending loop MUSIC
	_SOS_START_SAMPLE LoopSampleData[2] =
		{
			{_NULL, 0L, -1, _CENTER_CHANNEL, 0x7fff,
			_LSAMPLE1, sosDIGISampleCallback, 0, _LOOPING | _VOLUME,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L},

			{_NULL, 0L, -1, _CENTER_CHANNEL, 0x7fff,
			_LSAMPLE2, sosDIGISampleCallback, 0, _LOOPING | _VOLUME,
			0L, 0L, 0L, 0L, 0, 0, 0, 0x8000, 0, 0, 0, 0,
			0L, 0, 0, 0L, 0L, 0L},
		};

	int16_t     LoopHandles[2];
	int16_t     LoopPending=0,LoopIndex=0,looptoggle=0,loopmusepauseflag=0;
	int16_t     Metronome;

	Dint16_t    *DigiList;
	Dint16_t    *LoopList;
	Dint16_t    *SongList;
	Dint16_t    SeekIndex;

	//
	//    MIDI SPECIFIC
	//
	_SOS_MIDI_HARDWARE         sMIDIHardware;
	_SOS_MIDI_INIT_DRIVER      sSOSMIDIInitDriver;
	_SOS_MIDI_DIGI_INIT_DRIVER sSOSMIDIDIGIInitDriver;

//midimusic vars
	int16_t        Metronome;
	int16_t        SongPending,BranchPending;

	int16_t     hSOSSongHandles[MAX_ACTIVE_SONGS];
	BYTE     ActiveSongBits = 0x00;

	BYTE     *m_bnkptr,*d_bnkptr,*digi_bnkptr;
	BYTE _huge *lpMIDISong;

	_SOS_MIDI_INIT_SONG        sSOSInitSongs[MAX_ACTIVE_SONGS];

	_SOS_MIDI_TRACK_DEVICE   sSOSTrackMap[MAX_ACTIVE_SONGS] = {
		{
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK
		},
		{
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK
		},
		{
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK
		},
		{
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK,
		_MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK, _MIDI_MAP_TRACK
		}
	};

	//
	//    MISC/COMMON STUFF
	//
	int16_t     hSOSDriverHandles[3];
	int16_t     hSOSDriverHandles1;

	int16_t     SD_Started=0;
	BOOL     Midi_Loaded,Digi_Loaded,DigMidi_Loaded;
	int16_t     wError,wIndex;

	int16_t     hSoundFile  =  -1;       // Handle for Sound F/X file
	int16_t     hLoopFile   =  -1;       // Handle for Loop file
	int16_t     hSongFile   =  -1;
	int16_t     hMiscHandle =  -1;

	//
	//    TIMER STUFF
	//
	int16_t     hTimerT_ClockHandle;    // Handle for the game timer (TotalClock)
	int16_t     hTimerDig_FillHandle;   // Handle for the sSOSInitDriver.lpFillHandler
	int16_t     hTimerRec_FillHandle;   // Handle for the sSOSInitDriver.lpFillHandler

	int16_t     AuxTimerList[MAX_AUX_TIMERS];
	BYTE     ActiveTimerBits = 0x00;

	int16_t     LoopSndsPlaying=0;

	//
	//          GLOBAL VARIABLES
	//

	//
	//          EXTERN STUFF
	//
	extern keytimerstuff();
	extern volatile long totalclock;
	extern long posx[],posy[];

	//JSA temp int to show vol and pan
	int gVol,gPan;

#else

extern int  Metronome,SongPending,BranchPending;
extern int  hSOSSongHandles[];

extern int  SoundMode,wDIGIVol,MusicMode,wMIDIVol,use_dig_midi,
				LoopPending,LoopIndex,looptoggle,LoopSndsPlaying,
				gPan,gVol;

//extern SampleType SampleRay[],FXLoopRay[];

extern struct ambsounds ambsoundarray[];
extern int lavasnd,batsnd,cartsnd;

#endif

#endif


code:
#include "witchaven.h"
#include "sound.h"
#include "compat.h"
#include "baselayer.h"
#include "renderlayer.h" // for win_gethwnd()
#include "build.h"
#include "cache1d.h"
#include "music.h"
#include "fx_man.h"
#include "hmpplay.h"
#include "keyboard.h"
#include "control.h"
#include "config.h"
#include "player.h"

void SND_MIDIFlush(void);
char* SND_LoadMIDISong(int nSong);
int SND_PrepareMIDISong(int SongIndex);
int SND_StartMIDISong(int wSongHandle);

int lavasnd = -1;
int batsnd = -1;
int cartsnd = -1;

int SoundMode, wDIGIVol;
int MusicMode, wMIDIVol;
int use_rec_driver, voicecom_enabled;
int SD_Started;
int wMIDIDeviceID;
int SongPending;

#define  _MIDI_MPU_401              0xa001
#define  _MIDI_FM                   0xa002
#define  _MIDI_OPL2                 0xa002
#define  _MIDI_OPL3                 0xa009
char *BaseSongPtr;
char *EmbSongPtr;
char *SpiceSongPtr;

char *m_bnkptr, *d_bnkptr;

#define MAX_ACTIVE_SONGS 4

int hSOSSongHandles[MAX_ACTIVE_SONGS];
InitSong sSOSInitSongs[MAX_ACTIVE_SONGS];
TrackDevice sSOSTrackMap[MAX_ACTIVE_SONGS] = {
    {
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff
    },
    {
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff
    },
    {
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff
    },
    {
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff,
        0xff, 0xff, 0xff, 0xff
    },
};

static uint16_t songelements = 3;
static uint16_t arrangements = 3;
static uint16_t songsperlevel;
static uint16_t totallevels = 6;    // really there use two to test menusong

uint32_t DigiList[4096];
uint32_t LoopList[4096];
uint32_t SongList[4096];

uint32_t PanArray[] = {
    // REAR to HARD LEFT (angle = 0->512)
    0x8000,0x7000,0x6000,0x5000,0x4000,0x3000,0x2000,0x1000,0x0000,
    // HARD LEFT to CENTER (angle = 513-1024)
    0x1000,0x20F0,0x2000,0x3000,0x4000,0x5000,0x6000,0x7000,0x8000,
    // CENTER to HARD RIGHT (angle = 1025-1536)
    0x70F0,0x8000,0x9000,0xA000,0xB000,0xC000,0xD000,0xE000,0xF000,
    // HARD RIGHT to REAR (angle = 1537-2047)
    0xFFFF,0xF000,0xE000,0xD000,0xC000,0xB000,0xA000,0x9000,0x8000
};

struct SampleType
{
//  int     playing;
    int32_t nFXHandle;
    int32_t number;
    int32_t priority;
    int32_t loopcount;
    int32_t x, y;

    int nSize;
    char* pData;
};

SampleType SampleRay[MAX_ACTIVE_SAMPLES];

ambsounds ambsoundarray[] =
{
    0,0,
    S_WINDLOOP1,-1,
    S_WINDLOOP2,-1,
    S_WAVELOOP1,-1,
    S_LAVALOOP1,-1,
    S_WATERY,-1,
    S_STONELOOP1,-1,
    S_BATSLOOP,-1
};

buildvfs_kfd hSoundFile = buildvfs_kfd_invalid;
buildvfs_kfd hLoopsFile = buildvfs_kfd_invalid;
buildvfs_kfd hSongsFile = buildvfs_kfd_invalid;

void SND_SetupTables()
{
    if (SoundMode)
    {
        hSoundFile = kopen4loadfrommod("joesnd", 0);
        if (hSoundFile == buildvfs_kfd_invalid) {
            crash("Couldn't open joesnd");
        }

        int nSize = kfilelength(hSoundFile);
        if (nSize < 4096) {
            crash("Invalid size for joesdn");
        }

        klseek(hSoundFile, nSize - 4096, SEEK_SET);

        if (kread(hSoundFile, DigiList, 4096) != 4096) {
            crash("Couldn't read from joesnd");
        }
    }

    if (MusicMode == _LOOP_MUSIC)
    {
        hLoopsFile = kopen4loadfrommod("loops", 0);
        if (hLoopsFile == buildvfs_kfd_invalid) {
            crash("Couldn't open loops");
        }

        int nSize = kfilelength(hLoopsFile);
        if (nSize < 4096) {
            crash("Invalid size for loops");
        }

        klseek(hLoopsFile, nSize - 4096, SEEK_SET);

        if (kread(hLoopsFile, LoopList, 4096) != 4096) {
            crash("Couldn't read from loops");
        }
    }
    else if (MusicMode)
    {
        hSongsFile = kopen4loadfrommod("songs", 0);
        if (hSongsFile == buildvfs_kfd_invalid) {
            crash("Couldn't open songs");
        }

        int nSize = kfilelength(hSongsFile);
        if (nSize < 4096) {
            crash("Invalid size for songs");
        }

        klseek(hSongsFile, nSize - 4096, SEEK_SET);

        if (kread(hSongsFile, SongList, 4096) != 4096) {
            crash("Couldn't read from songs");
        }
    }

    return;
}

void SND_LoadMidiIns(void)
{
    static int wLength;

    //JSA_DEMO check port address to verify FM device
    buildvfs_kfd handle = kopen4loadfrommod("melodic.bnk", 0);
    if (handle == buildvfs_kfd_invalid)
        crash("MELODIC BANK FILE FAILED!");
    m_bnkptr = (char*)malloc(0x152c);
    kread(handle, m_bnkptr, 0x152c);
    kclose(handle);
    if (FMSetBank(m_bnkptr))
        crash("BAD SetInsData MEL!");

    handle = kopen4loadfrommod("drum.bnk", 0);
    if (handle == buildvfs_kfd_invalid)
        crash("PERCUSSIVE BANK FILE FAILED!");
    d_bnkptr = (char*)malloc(0x152c);
    kread(handle, d_bnkptr, 0x152c);
    kclose(handle);
    if (FMSetBank(d_bnkptr))
        printf("BAD SetInsData DRUM!");
}

void ASSCallback(intptr_t pSample)
{
    SampleType *sample = (SampleType*)pSample;
    sample->loopcount = 0;
    sample->nSize = 0;
    sample->nFXHandle = 0;
    sample->priority = 0;
    sample->number = -1;
}

extern int MV_MixRate;
extern int musiclevel;

void SND_Startup()
{
    #ifdef MIXERTYPEWIN
    void* initdata = (void*)win_gethwnd(); // used for DirectSound
    #else
    void* initdata = NULL;
    #endif

    //  if (bNoSound)
    //      return;

    if (FX_Init(NumVoices, NumChannels, MixRate, initdata) != FX_Ok)
    {
        //        crash("Error initializing sound card!\n");
        initprintf("Error initializing sound card!\n");
        //        DebugOut("ERROR: %s\n", FX_ErrorString(FX_Error));
        return;
    }

    FX_SetCallBack(ASSCallback);

    memset(SampleRay, 0, sizeof(SampleRay));
    for (int i = 0; i < MAX_ACTIVE_SAMPLES; i++)
    {
        SampleRay[i].number = -1;
 //       SampleRay[i].loopcount = -1;
    }

    // init buffer space
    for (int i = 0; i < MAX_ACTIVE_SAMPLES; i++) {
        SampleRay[i].pData = new char[55000]; // just alloc a big block, like the original code
    }

    // Init music
    #if 1
            // if they chose None lets return
    #if 0
    if (!MusicToggle)
    {
        gs.MusicOn = FALSE;
        return;
    }
    #endif

    wMIDIVol = (musiclevel<<3);
    wMIDIDeviceID = _MIDI_FM;
    HMIInit(MV_MixRate);

    SND_LoadMidiIns();
    for (int i = 0; i < MAX_ACTIVE_SONGS; i++)
        hSOSSongHandles[i] = 0x7fff;

    songsperlevel = songelements * arrangements;

    HMISetMasterVolume(wMIDIVol);
        /*
    auto const fil = kopen4load("swtimbr.tmb", 0);

    if (fil != buildvfs_kfd_invalid)
    {
        int l = kfilelength(fil);
        auto tmb = (uint8_t*)Xmalloc(l);
        kread(fil, tmb, l);
        AL_RegisterTimbreBank(tmb);
        Xfree(tmb);
        kclose(fil);
    }
    */
    #endif

    // read in offset page lists
    SND_SetupTables();

    SD_Started = 1;
}

void SND_Shutdown()
{
    FX_Shutdown();

    for (int i = 0; i < MAX_ACTIVE_SAMPLES; i++)
    {
        if (SampleRay[i].pData) {
            delete[] SampleRay[i].pData;
        }
    }

    SND_MIDIFlush();
    HMIUnInit();
    if (m_bnkptr != NULL)
        free(m_bnkptr);
    if (d_bnkptr != NULL)
        free(d_bnkptr);

    if (hSoundFile != buildvfs_kfd_invalid) {
        kclose(hSoundFile);
    }

    if (hLoopsFile != buildvfs_kfd_invalid) {
        kclose(hLoopsFile);
    }

    if (hSongsFile != buildvfs_kfd_invalid) {
        kclose(hSongsFile);
    }

    SD_Started = 0;
}

int SND_Sound(int nSound)
{
    if (!SoundMode)
        return -1;

    return(SND_PlaySound(nSound, 0, 0, 0, 0));
}

int SND_PlaySound(int nSound, int32_t x, int32_t y, int16_t Pan, int16_t loopcount)
{
    //return 0; // TODO

    short wVol, flag = 0;
    int32_t sqrdist;
    int32_t prioritize;
    int i;

    if (!SoundMode)
        return 0;

    prioritize = DigiList[(nSound * 3) + 2];

    if (((x == 0) && (y == 0)) || ((player[pyrn].x == x) && (player[pyrn].y == y)))
    {
        wVol = 0x7fff;
        Pan = 0;
    }
    else
    {
        sqrdist = labs(player[pyrn].x - x) + labs(player[pyrn].y - y);
        if (sqrdist < 1500)
            wVol = 0x7fff;
        else if (sqrdist > 8500)
            wVol = 0x1f00;
        else
            wVol = 39000 - (sqrdist << 2);
    }

    if (nSound == S_STONELOOP1)
    {
        for (i = 0, flag = 0; i < MAX_ACTIVE_SAMPLES; i++)
        {
            if (nSound == SampleRay[i].number)
                return 0;
        }
    }

    for (i = 0, flag = 0; i < MAX_ACTIVE_SAMPLES; i++)
    {
        if (SampleRay[i].nFXHandle <= 0)
        {
            flag = 1;
            break;
        }
    }

    if (!flag && prioritize < 9)           // none available low priority
        return 0;
    else if (!flag)                        // none available but high priority
    {
        for (i = 0; i < MAX_ACTIVE_SAMPLES; i++)
        {
            if (SampleRay[i].priority < 9 && SampleRay[i].loopcount != -1)//sSOSSampleData[i].wLoopCount != -1)
            {
                //if (!sosDIGISampleDone(hSOSDriverHandles[DIGI], SampleRay[i].SOSHandle) && (sSOSSampleData[i].dwSampleSize != 0))
                if (SampleRay[i].nFXHandle > 0)
                {
                    FX_StopSound(SampleRay[i].nFXHandle);
                    SampleRay[i].loopcount = 0;
                    SampleRay[i].nSize = 0;
                    SampleRay[i].nFXHandle = 0;
//                    SampleRay[i].playing = 0;
                    SampleRay[i].priority = 0;
                    SampleRay[i].number = -1;
                    break;
                }
            }
        }
    }

    if (i >= MAX_ACTIVE_SAMPLES)
    {
        return 0; // FIXME - this shouldn't trigger?
    }

    assert(i >= 0 && i < 10);

    if (Pan) {
        Pan = ((getangle(player[pyrn].x - x, player[pyrn].y - y) + (2047 - player[pyrn].ang)) % kAngleMask) >> 6;
    }

    int SeekIndex = (DigiList[(nSound * 3) + 0] * 4096);

    if (klseek(hSoundFile, SeekIndex, SEEK_SET) < 0)
    {
        assert(1 == 2);
    }

    SampleRay[i].nSize = (uint16_t)DigiList[(nSound * 3) + 1];

//    assert(hSoundFileSize - SeekIndex >= SampleRay[i].nSize);

    int nRead = kread(hSoundFile, SampleRay[i].pData, SampleRay[i].nSize);
    if (nRead != SampleRay[i].nSize)
    {
        assert(1 == 2);
    }

    SampleRay[i].nFXHandle = FX_PlayRaw(SampleRay[i].pData, SampleRay[i].nSize, 11025, 0, 32, 32, 32, 0, fix16_one, (intptr_t)&SampleRay[i]);
    assert(SampleRay[i].nFXHandle > 0);

    #if 0 // TODO
    if (loopcount)
        sSOSSampleData[i].wLoopCount = loopcount;

    if (Pan)
        Pan = ((getangle(player[pyrn].x - x, player[pyrn].y - y) + (2047 - player[pyrn].ang)) % 2047) >> 6;

    sSOSSampleData[wIndex].wSamplePanLocation = PanArray[Pan];
    sSOSSampleData[wIndex].wVolume = wVol;
    SampleRay[wIndex].SOSHandle = sosDIGIStartSample(hSOSDriverHandles[DIGI], &sSOSSampleData[wIndex]);
    #endif

    SampleRay[i].x = x;
    SampleRay[i].y = y;
//    SampleRay[i].playing = 1;
    SampleRay[i].number = nSound;
    SampleRay[i].priority = prioritize;
    // TODO	ActiveSampleBits |= (0x01 << wIndex);

    return SampleRay[i].nFXHandle;
}

void playsound_loc(int nSound, int32_t xplc, int32_t yplc)
{
    SND_PlaySound(nSound, xplc, yplc, 1, 0);
}

void SND_UpdateSoundLoc(int which, int Volume, int Pan)
{
    #if 0
    gVol = Volume;
    gPan = sosDIGISetPanLocation(hSOSDriverHandles[DIGI], SampleRay[which].SOSHandle, PanArray[Pan]);
    sosDIGISetSampleVolume(hSOSDriverHandles[DIGI], SampleRay[which].SOSHandle, Volume);
    #endif
}

void updatesound_loc()
{
    #if 0
    unsigned wVol, wPan;
    long sqrdist;

    if (!SoundMode)
        return;

    for (int i = 0; i < MAX_ACTIVE_SAMPLES; i++)
    {
        if (SampleRay[i].playing && SampleRay[i].x && SampleRay[i].y)
        {
            if (sSOSSampleData[wIndex].dwSampleSize != 0)
            {
                sqrdist = labs(player[pyrn].x - SampleRay[wIndex].x) +
                    labs(player[pyrn].y - SampleRay[wIndex].y);

                if (sqrdist < 1500)
                    wVol = 0x7fff;
                else if (sqrdist > 8500)
                    wVol = 0x1f00;
                else
                    wVol = 39000 - (sqrdist << 2);

                wPan = ((getangle(player[pyrn].x - SampleRay[wIndex].x, player[pyrn].y - SampleRay[wIndex].y) + (2047 - player[pyrn].ang)) % kAngleMask) >> 6;
                SND_UpdateSoundLoc(wIndex, wVol, wPan);
                //sprintf(displaybuf,"%dVol %x Pan %x Dist %ld",SampleRay[wIndex].number,wVol,wPan,sqrdist);
                //displaytime=100;
            }
        }
    }
    #endif
}

void SND_CheckLoops()
{
}

void SND_StopLoop(int16_t nSound)
{
}

void SND_LoadSongs(uint16_t which)
{
    static int index;

    index = songsperlevel * which;                  //vanilla

    //if digi_midi used skip to those songs
    // if (wMIDIDeviceID == _MIDI_AWE32)
    //     index += songelements;                            //skip past vanilla

    //if soundcanvas skip to those songs
    if (wMIDIDeviceID == _MIDI_MPU_401/* || wMIDIDeviceID == _MIDI_GUS*/)
        index += songelements * 2;

    BaseSongPtr = SND_LoadMIDISong(index + BASE_SONG);
    EmbSongPtr = SND_LoadMIDISong(index + EMB_SONG);
    SpiceSongPtr = SND_LoadMIDISong(index + SPICE_SONG);
}

void SND_StartMusic(int16_t level)
{
    if ((!MusicMode) || !SD_Started)
        return;

    if (level > 5)
        level = rand() % 6;

    SND_SongFlush();
    SND_LoadSongs(level);
    SongPending = SND_PrepareMIDISong(BASE_SONG);
    SND_StartMIDISong(SongPending);
    SongPending = 0;
}

void SND_Mixer(int16_t wSource, int16_t wVolume)
{
    if (wSource == MIDI) {
        wMIDIVol = (wVolume << 3);
        HMISetMasterVolume(wMIDIVol);
    }
}

void SND_Sting(int16_t nSound)
{
}

void SND_FadeMusic()
{
}

// temp
int nMusicSize = 0;

char* SND_LoadMIDISong(int nSong)
{
    uint32_t nLength = SongList[(nSong * 3) + 1];
    uint32_t SeekIndex = (SongList[(nSong * 3) + 0] * 4096);
    char* pData = (char*)malloc(nLength);

    klseek(hSongsFile, SeekIndex, SEEK_SET);
    kread(hSongsFile, pData, nLength);

    nMusicSize = nLength;

    return pData;
}

void SND_MenuMusic(int nSong)
{
    if (!MusicMode || !SD_Started)
        return;

    if ((nSong == DEATHSONG) && (wMIDIDeviceID == _MIDI_FM))
        return;
    SND_SongFlush();

    if (nSong == MENUSONG)
    {
        if (wMIDIDeviceID == _MIDI_MPU_401/* || wMIDIDeviceID == _MIDI_AWE32 || wMIDIDeviceID == _MIDI_GUS*/)
        {
            BaseSongPtr = SND_LoadMIDISong((totallevels * songsperlevel) + BASE_SONG + 2);
        }
        else
        {
            BaseSongPtr = SND_LoadMIDISong((totallevels * songsperlevel) + BASE_SONG);
        }
    }
    else if (wMIDIDeviceID == _MIDI_MPU_401/* || wMIDIDeviceID == _MIDI_AWE32 || wMIDIDeviceID == _MIDI_GUS*/)
    {
        BaseSongPtr = SND_LoadMIDISong((totallevels * songsperlevel) + 3 + BASE_SONG + 2);
    }

    SongPending = SND_PrepareMIDISong(BASE_SONG);
    SND_StartMIDISong(SongPending);
    SongPending = 0;
}

void sosMIDISongCallback(uint32_t hSong)
{
    int i;
    for (i = 0; i < MAX_ACTIVE_SONGS; i++)
        if (hSong == hSOSSongHandles[i])
            break;

    HMIUnInitSong(hSOSSongHandles[i]);
    hSOSSongHandles[i] = 0x7fff;
}

int SND_PrepareMIDISong(int SongIndex)
{
    int status;
    if (!MusicMode)
        return(0x7fff);

    if (hSOSSongHandles[SongIndex] != 0x7fff)
        return(0x7fff);

    if (SongIndex == BASE_SONG)
        sSOSInitSongs[SongIndex].songptr = (uint8_t*)BaseSongPtr;
    if (SongIndex == EMB_SONG)
        sSOSInitSongs[SongIndex].songptr = (uint8_t*)EmbSongPtr;
    if (SongIndex == SPICE_SONG)
        sSOSInitSongs[SongIndex].songptr = (uint8_t*)SpiceSongPtr;

    sSOSInitSongs[SongIndex].callback = sosMIDISongCallback;
    if ((status = HMIInitSong(&sSOSInitSongs[SongIndex], &sSOSTrackMap[SongIndex], (uint32_t*)&hSOSSongHandles[SongIndex])))
    {
        crash("Init Song Failed!");
    }

    return((int)hSOSSongHandles[SongIndex]);
}
int SND_StartMIDISong(int wSongHandle)
{
    HMISetMasterVolume(wMIDIVol);
    return(HMIStartSong(wSongHandle));
}

void SND_StopMIDISong(int wSongHandle)
{
    int i;
    for (i = 0; i < MAX_ACTIVE_SONGS; i++)
        if (hSOSSongHandles[i] == wSongHandle)
            break;

    if (i >= MAX_ACTIVE_SONGS)
        return;

    if (!HMISongDone(hSOSSongHandles[i]))
    {
        HMIStopSong(hSOSSongHandles[i]);
        HMIUnInitSong(hSOSSongHandles[i]);
        hSOSSongHandles[i] = 0x7fff;
        free(sSOSInitSongs[i].songptr);
    }
}

void SND_SongFlush()
{
    if (!MusicMode)
        return;

    if (hSOSSongHandles[BASE_SONG] != 0x7fff)
        SND_StopMIDISong(hSOSSongHandles[BASE_SONG]);
    if (hSOSSongHandles[EMB_SONG] != 0x7fff)
        SND_StopMIDISong(hSOSSongHandles[EMB_SONG]);
    if (hSOSSongHandles[SPICE_SONG] != 0x7fff)
        SND_StopMIDISong(hSOSSongHandles[SPICE_SONG]);
}

void SND_MIDIFlush(void)
{
    int i;
    for (i = 0; i < MAX_ACTIVE_SONGS; i++) {
        if (!HMISongDone(hSOSSongHandles[i]))
            HMIStopSong(hSOSSongHandles[i]);
        if (hSOSSongHandles[i] != 0x7fff)
            HMIUnInitSong(hSOSSongHandles[i]);
        hSOSSongHandles[i] = 0x7fff;
    }

    free(BaseSongPtr);
    free(EmbSongPtr);
    free(SpiceSongPtr);
}


code:
#ifndef __sound_h__
#define __sound_h__

#include <stdint.h>
#include "sndmod.h"

extern int SoundMode;
extern int MusicMode;

void SND_Startup();
void SND_Shutdown();

int SND_Sound(int nSound);
int SND_PlaySound(int nSound, int32_t x, int32_t y, int16_t Pan, int16_t loopcount);
void playsound_loc(int nSound, int32_t xplc, int32_t yplc);
void SND_CheckLoops();
void SND_StopLoop(int16_t nSound);
void SND_SongFlush();
void SND_StartMusic(int16_t level);
void SND_Mixer(int16_t wSource, int16_t wVolume);
void SND_Sting(int16_t nSound);
void SND_FadeMusic();
void SND_MenuMusic(int nSong);

#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010 EDuke32 developers and contributors

This file is part of EDuke32.

EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#include "build.h"
#include "common.h"
#include "compat.h"
#include "keyboard.h"
#include "control.h"
#include "config.h"
#include "witchaven.h"
#include "dynamicgtk.h"
#include "grpscan.h"
#include "gtkpixdata.h"

enum
{
    NONE,
    ALL,
    POPULATE_VIDEO,
    POPULATE_CONFIG,
    POPULATE_GAME,
};

enum
{
    TAB_CONFIG,
    TAB_GAME,
    TAB_MESSAGES,
};

enum
{
    INPUT_KB,
    INPUT_MOUSE,
    INPUT_JOYSTICK,
    INPUT_ALL,
};

static struct
{
    GtkWidget *startwin;
    GtkWidget *hlayout;
    GtkWidget *banner;
    GtkWidget *vlayout;
    GtkWidget *tabs;
    GtkWidget *configtlayout;
    GtkWidget *displayvlayout;
    GtkWidget *vmode3dlabel;
    GtkWidget *vmode3dcombo;
    GtkWidget *fullscreencheck;
#ifdef POLYMER
    GtkWidget *polymercheck;
#endif
    GtkWidget *inputdevlabel;
    GtkWidget *inputdevcombo;
    GtkWidget *custommodlabel;
    GtkWidget *custommodcombo;
    GtkWidget *emptyhlayout;
    GtkWidget *autoloadcheck;
    GtkWidget *alwaysshowcheck;
    GtkWidget *configtab;
    GtkWidget *gamevlayout;
    GtkWidget *gamelabel;
    GtkWidget *gamescroll;
    GtkWidget *gamelist;
    GtkWidget *gametab;
    GtkWidget *messagesscroll;
    GtkWidget *messagestext;
    GtkWidget *messagestab;
    GtkWidget *buttons;
    GtkWidget *cancelbutton;
    GtkWidget *cancelbuttonalign;
    GtkWidget *cancelbuttonlayout;
    GtkWidget *cancelbuttonicon;
    GtkWidget *cancelbuttonlabel;
    GtkWidget *startbutton;
    GtkWidget *startbuttonalign;
    GtkWidget *startbuttonlayout;
    GtkWidget *startbuttonicon;
    GtkWidget *startbuttonlabel;
} stwidgets;

static struct
{
    grpfile_t const * grp;
    char *gamedir;
    ud_setup_t shared;
#ifdef POLYMER
    int polymer;
#endif
} settings;

static int32_t retval = -1, mode = TAB_MESSAGES;
extern int32_t gtkenabled;
static void PopulateForm(unsigned char pgs);

// -- EVENT CALLBACKS AND CREATION STUFF --------------------------------------

static void on_vmode3dcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    GtkTreeModel *data;
    GtkTreeIter iter;
    int32_t val;
    UNREFERENCED_PARAMETER(user_data);

    if (!gtk_combo_box_get_active_iter(combobox, &iter)) return;
    if (!(data = gtk_combo_box_get_model(combobox))) return;
    gtk_tree_model_get(data, &iter, 1, &val, -1);
    settings.shared.xdim = validmode[val].xdim;
    settings.shared.ydim = validmode[val].ydim;
    settings.shared.bpp = validmode[val].bpp;
}

static void on_fullscreencheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.shared.fullscreen = gtk_toggle_button_get_active(togglebutton);
    PopulateForm(POPULATE_VIDEO);
}

#ifdef POLYMER
static void on_polymercheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    if (gtk_toggle_button_get_active(togglebutton))
    {
        glrendmode = REND_POLYMER;
        settings.polymer = TRUE;
        if (settings.shared.bpp == 8)
        {
            settings.shared.bpp = 32;
            PopulateForm(POPULATE_VIDEO);
        }
    }
    else
    {
        glrendmode = REND_POLYMOST;
        settings.polymer = FALSE;
    }
}
#endif

static void on_inputdevcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    switch (gtk_combo_box_get_active(combobox))
    {
    case 0: settings.shared.usemouse = 0; settings.shared.usejoystick = 0; break;
    case 1:	settings.shared.usemouse = 1; settings.shared.usejoystick = 0; break;
    case 2:	settings.shared.usemouse = 0; settings.shared.usejoystick = 1; break;
    case 3:	settings.shared.usemouse = 1; settings.shared.usejoystick = 1; break;
    }
}

static void on_custommodcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;
    GtkTreePath *path;
    char *value;
    UNREFERENCED_PARAMETER(user_data);

    if (gtk_combo_box_get_active_iter(combobox, &iter))
    {
        model = gtk_combo_box_get_model(combobox);
        gtk_tree_model_get(model, &iter, 0,&value, -1);
        path = gtk_tree_model_get_path(model, &iter);

        if (*gtk_tree_path_get_indices(path) == NONE)
            settings.gamedir = NULL;
        else settings.gamedir = value;
    }
}

static void on_autoloadcheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.shared.noautoload = !gtk_toggle_button_get_active(togglebutton);
}

static void on_alwaysshowcheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.shared.forcesetup = gtk_toggle_button_get_active(togglebutton);
}

static void on_cancelbutton_clicked(GtkButton *button, gpointer user_data)
{
    UNREFERENCED_PARAMETER(button);
    UNREFERENCED_PARAMETER(user_data);
    if (mode == TAB_CONFIG) { retval = 0; gtk_main_quit(); }
    else quitevent++;
}

static void on_startbutton_clicked(GtkButton *button, gpointer user_data)
{
    UNREFERENCED_PARAMETER(button);
    UNREFERENCED_PARAMETER(user_data);
    retval = 1;
    gtk_main_quit();
}

static void on_gamelist_selection_changed(GtkTreeSelection *selection, gpointer user_data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;
    UNREFERENCED_PARAMETER(user_data);

    if (gtk_tree_selection_get_selected(selection, &model, &iter))
    {
        grpfile_t const *fg;
        gtk_tree_model_get(model, &iter, 2, (gpointer)&fg, -1);
        settings.grp = fg;
    }
}

static gboolean on_startwin_delete_event(GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
    UNREFERENCED_PARAMETER(widget);
    UNREFERENCED_PARAMETER(event);
    UNREFERENCED_PARAMETER(user_data);
    if (mode == TAB_CONFIG) { retval = 0; gtk_main_quit(); }
    else quitevent++;
    return TRUE;	// FALSE would let the event go through. we want the game to decide when to close
}

// -- SUPPORT FUNCTIONS -------------------------------------------------------

static GdkPixbuf *load_banner(void)
{
    return gdk_pixbuf_from_pixdata((GdkPixdata const *)&startbanner_pixdata, FALSE, NULL);
}

static void SetPage(int32_t n)
{
    if (!gtkenabled || !stwidgets.startwin) return;
    mode = n;
    gtk_notebook_set_current_page(GTK_NOTEBOOK(stwidgets.tabs), n);

    // each control in the config page vertical layout plus the start button should be made (in)sensitive
    if (n == TAB_CONFIG) n = TRUE; else n = FALSE;
    gtk_widget_set_sensitive(stwidgets.startbutton, n);
    gtk_container_foreach(GTK_CONTAINER(stwidgets.configtlayout),
                          (GtkCallback)gtk_widget_set_sensitive,
                          (gpointer)&n);
}

static unsigned char GetModsDirNames(GtkListStore *list)
{
    char *homedir;
    char pdir[BMAX_PATH];
    unsigned char iternumb = 0;
    BUILDVFS_FIND_REC *dirs = NULL;
    GtkTreeIter iter;

    pathsearchmode = 1;

    if ((homedir = Bgethomedir()))
    {
        Bsnprintf(pdir, sizeof(pdir), "%s/" ".eduke32", homedir);
        dirs = klistpath(pdir, "*", BUILDVFS_FIND_DIR);
        for (; dirs != NULL; dirs=dirs->next)
        {
            if ((Bstrcmp(dirs->name, "autoload") == 0) ||
                    (Bstrcmp(dirs->name, "..") == 0) ||
                    (Bstrcmp(dirs->name, ".") == 0))
                continue;
            else
            {
                gtk_list_store_append(list, &iter);
                gtk_list_store_set(list, &iter, 0,dirs->name, -1);
                iternumb++;
            }
        }
    }

    klistfree(dirs);
    dirs = NULL;

    return iternumb;
}

static void PopulateForm(unsigned char pgs)
{
    if ((pgs == ALL) || (pgs == POPULATE_VIDEO))
    {
        int32_t mode3d, i;
        GtkListStore *modes3d;
        GtkTreeIter iter;
        char buf[64];

        mode3d = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, settings.shared.bpp, settings.shared.fullscreen, 1);
        if (mode3d < 0)
        {
            int32_t i, cd[] = { 32, 24, 16, 15, 8, 0 };

            for (i=0; cd[i];) { if (cd[i] >= settings.shared.bpp) i++; else break; }
            for (; cd[i]; i++)
            {
                mode3d = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, cd[i], settings.shared.fullscreen, 1);
                if (mode3d < 0) continue;
                settings.shared.bpp = cd[i];
                break;
            }
        }

        modes3d = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(stwidgets.vmode3dcombo)));
        gtk_list_store_clear(modes3d);

        for (i=0; i<validmodecnt; i++)
        {
            if (validmode[i].fs != settings.shared.fullscreen) continue;

            // all modes get added to the 3D mode list
            Bsprintf(buf, "%dx%d %s", validmode[i].xdim, validmode[i].ydim, validmode[i].bpp == 8 ? "software" : "OpenGL");
            gtk_list_store_append(modes3d, &iter);
            gtk_list_store_set(modes3d, &iter, 0,buf, 1,i, -1);
            if (i == mode3d)
            {
                g_signal_handlers_block_by_func(stwidgets.vmode3dcombo, (gpointer)on_vmode3dcombo_changed, NULL);
                gtk_combo_box_set_active_iter(GTK_COMBO_BOX(stwidgets.vmode3dcombo), &iter);
                g_signal_handlers_unblock_by_func(stwidgets.vmode3dcombo, (gpointer)on_vmode3dcombo_changed, NULL);
            }
        }
    }

    if ((pgs == ALL) || (pgs == POPULATE_CONFIG))
    {
        GtkListStore *devlist, *modsdir;
        GtkTreeIter iter;
        GtkTreePath *path;
        char *value;
        unsigned char i, r = 0;
        const char *availabledev[] =
        {
            "Keyboard only",
            "Keyboard and mouse",
            "Keyboard and joystick",
            "All supported devices"
        };

        // populate input devices combo
        devlist = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(stwidgets.inputdevcombo)));
        gtk_list_store_clear(devlist);

        for (i=0; i<(int32_t)G_N_ELEMENTS(availabledev); i++)
        {
            gtk_list_store_append(devlist, &iter);
            gtk_list_store_set(devlist, &iter, 0,availabledev[i], -1);
        }
        switch (settings.shared.usemouse)
        {
        case 0: if (settings.shared.usejoystick)
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_JOYSTICK);
            else
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_KB);
            break;
        case 1:	if (settings.shared.usejoystick)
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_ALL);
            else
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_MOUSE);
            break;
        }

        // populate custom mod combo
        modsdir = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(stwidgets.custommodcombo)));
        gtk_list_store_clear(modsdir);

        gtk_list_store_append(modsdir, &iter);
        gtk_list_store_set(modsdir, &iter, 0,"None", -1);
        r = GetModsDirNames(modsdir);

        for (i=0; i<=r; i++)
        {
            path = gtk_tree_path_new_from_indices(i, -1);
            gtk_tree_model_get_iter(GTK_TREE_MODEL(modsdir), &iter, path);
            gtk_tree_model_get(GTK_TREE_MODEL(modsdir), &iter, 0,&value, -1);

            if (Bstrcmp(settings.gamedir, "/") == 0)
            {
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.custommodcombo), NONE);
                settings.gamedir = NULL;

                break;
            }
            if (Bstrcmp(settings.gamedir, value) == 0)
            {
                gtk_combo_box_set_active_iter(GTK_COMBO_BOX(stwidgets.custommodcombo),
                                              &iter);

                break;
            }
        }

        // populate check buttons
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.fullscreencheck), settings.shared.fullscreen);
#ifdef POLYMER
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.polymercheck), settings.polymer);
#endif
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.autoloadcheck), !settings.shared.noautoload);
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.alwaysshowcheck), settings.shared.forcesetup);
    }

    if ((pgs == ALL) || (pgs == POPULATE_GAME))
    {
        GtkListStore *list;
        GtkTreeIter iter;
        GtkTreeView *gamelist;

        gamelist = GTK_TREE_VIEW(stwidgets.gamelist);
        list = GTK_LIST_STORE(gtk_tree_view_get_model(gamelist));
        gtk_list_store_clear(list);

        for (grpfile_t const * fg = foundgrps; fg; fg=fg->next)
        {
            gtk_list_store_append(list, &iter);
            gtk_list_store_set(list, &iter, 0, fg->type->name, 1, fg->filename, 2, (void const *)fg, -1);
            if (settings.grp == fg)
            {
                GtkTreeSelection *sel = gtk_tree_view_get_selection(gamelist);
                g_signal_handlers_block_by_func(sel, (gpointer)on_gamelist_selection_changed, NULL);
                gtk_tree_selection_select_iter(sel, &iter);
                g_signal_handlers_unblock_by_func(sel, (gpointer)on_gamelist_selection_changed, NULL);
            }
        }
    }
}

static gint name_sorter(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer user_data)
{
    gchar *as, *bs;
    gint r;
    UNREFERENCED_PARAMETER(user_data);
    gtk_tree_model_get(model, a, 0, &as, -1);
    gtk_tree_model_get(model, b, 0, &bs, -1);

    r = g_utf8_collate(as,bs);

    g_free(as);
    g_free(bs);

    return r;
}

static GtkWidget *create_window(void)
{
    // Basic window
    stwidgets.startwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(stwidgets.startwin), apptitle);	// NOTE: use global app title
    gtk_window_set_position(GTK_WINDOW(stwidgets.startwin), GTK_WIN_POS_CENTER);
    gtk_window_set_resizable(GTK_WINDOW(stwidgets.startwin), FALSE);
    gtk_window_set_type_hint(GTK_WINDOW(stwidgets.startwin), GDK_WINDOW_TYPE_HINT_DIALOG);

    // Horizontal layout of banner and controls
    stwidgets.hlayout = gtk_hbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.startwin), stwidgets.hlayout);

    // banner
    {
        GdkPixbuf *pixbuf = load_banner();
        stwidgets.banner = gtk_image_new_from_pixbuf(pixbuf);
        g_object_unref((gpointer)pixbuf);
    }
    gtk_box_pack_start(GTK_BOX(stwidgets.hlayout), stwidgets.banner, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(stwidgets.banner), 0.5, 0);

    // Vertical layout of tab control and start+cancel buttons
    stwidgets.vlayout = gtk_vbox_new(FALSE, 0);
    gtk_box_pack_start(GTK_BOX(stwidgets.hlayout), stwidgets.vlayout, TRUE, TRUE, 0);

    // Tab control
    stwidgets.tabs = gtk_notebook_new();
    gtk_box_pack_start(GTK_BOX(stwidgets.vlayout), stwidgets.tabs, TRUE, TRUE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.tabs), 4);

    // layout table of config page
    stwidgets.configtlayout = gtk_table_new(6, 3, FALSE);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.configtlayout);

    // 3D video mode LabelText
    stwidgets.vmode3dlabel = gtk_label_new_with_mnemonic("_Video mode:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.vmode3dlabel), 0.3, 0);
#ifdef POLYMER
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dlabel, 0,1, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 0);
#else
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dlabel, 0,1, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 7);
#endif

    // 3D video mode combo
    {
        GtkListStore *list = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT);
        GtkCellRenderer *cell;

        stwidgets.vmode3dcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.vmode3dcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.vmode3dcombo), cell, "text", 0, NULL);
    }

#ifdef POLYMER
   gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dcombo, 1,2, 0,1,
       (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 0);
#else
   gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dcombo, 1,2, 0,1, (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 7);
#endif

    // Fullscreen checkbox
    stwidgets.displayvlayout = gtk_vbox_new(TRUE, 0);
#ifdef POLYMER
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.displayvlayout, 2,3, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 0);
#else
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.displayvlayout, 2,3, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 7);
#endif

    stwidgets.fullscreencheck = gtk_check_button_new_with_mnemonic("_Fullscreen");
    gtk_box_pack_start(GTK_BOX(stwidgets.displayvlayout), stwidgets.fullscreencheck, FALSE, FALSE, 0);

#ifdef POLYMER
    // Polymer checkbox
    stwidgets.polymercheck = gtk_check_button_new_with_mnemonic("_Polymer");
    gtk_box_pack_start(GTK_BOX(stwidgets.displayvlayout), stwidgets.polymercheck, FALSE, FALSE, 0);
#endif

    // Input devices LabelText
    stwidgets.inputdevlabel = gtk_label_new_with_mnemonic("_Input devices:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.inputdevlabel), 0.3, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.inputdevlabel, 0,1, 1,2, GTK_FILL, (GtkAttachOptions)0, 4, 0);

    // Input devices combo
    {
        GtkListStore *list = gtk_list_store_new(1, G_TYPE_STRING);
        GtkCellRenderer *cell;

        stwidgets.inputdevcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.inputdevcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.inputdevcombo), cell, "text", 0, NULL);
    }
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.inputdevcombo, 1,2, 1,2,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 0);

    // Custom mod LabelText
    stwidgets.custommodlabel = gtk_label_new_with_mnemonic("Custom _game:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.custommodlabel), 0.3, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.custommodlabel, 0,1, 2,3, GTK_FILL, (GtkAttachOptions)0, 4, 7);

    // Custom mod combo
    {
        GtkListStore *list = gtk_list_store_new(1, G_TYPE_STRING);
        GtkCellRenderer *cell;

        stwidgets.custommodcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.custommodcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.custommodcombo), cell, "text", 0, NULL);
    }
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.custommodcombo, 1,2, 2,3,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 7);

    // Empty horizontal layout
    stwidgets.emptyhlayout = gtk_hbox_new(TRUE, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.emptyhlayout, 0,3, 3,4, (GtkAttachOptions)0,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 4, 0);

    // Autoload checkbox
    stwidgets.autoloadcheck = gtk_check_button_new_with_mnemonic("_Enable \"autoload\" folder");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.autoloadcheck, 0,3, 4,5, GTK_FILL, (GtkAttachOptions)0, 2, 2);

    // Always show config checkbox
    stwidgets.alwaysshowcheck = gtk_check_button_new_with_mnemonic("_Always show this window at startup");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.alwaysshowcheck, 0,3, 5,6, GTK_FILL, (GtkAttachOptions)0, 2, 2);

    // Configuration tab
    stwidgets.configtab = gtk_label_new("Configuration");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 0), stwidgets.configtab);

    // Game data layout
    stwidgets.gamevlayout = gtk_vbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.gamevlayout);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.gamevlayout), 4);

    // Game data field LabelText
    stwidgets.gamelabel = gtk_label_new_with_mnemonic("_Game:");
    gtk_box_pack_start(GTK_BOX(stwidgets.gamevlayout), stwidgets.gamelabel, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(stwidgets.gamelabel), 0, 0.5);

    // Game data scrollable area
    stwidgets.gamescroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_box_pack_start(GTK_BOX(stwidgets.gamevlayout), stwidgets.gamescroll, TRUE, TRUE, 0);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(stwidgets.gamescroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
    gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(stwidgets.gamescroll), GTK_SHADOW_IN);

    // Game data list
    {
        GtkListStore *list = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);
        GtkCellRenderer *cell;
        GtkTreeViewColumn *col;

        gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(list), 0, name_sorter, NULL, NULL);
        gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(list), 0, GTK_SORT_ASCENDING);

        stwidgets.gamelist = gtk_tree_view_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        col = gtk_tree_view_column_new_with_attributes("Game", cell, "text", 0, NULL);
        gtk_tree_view_column_set_expand(col, TRUE);
        gtk_tree_view_append_column(GTK_TREE_VIEW(stwidgets.gamelist), col);
        col = gtk_tree_view_column_new_with_attributes("GRP file", cell, "text", 1, NULL);
        gtk_tree_view_column_set_min_width(col, 64);
        gtk_tree_view_append_column(GTK_TREE_VIEW(stwidgets.gamelist), col);
    }
    gtk_container_add(GTK_CONTAINER(stwidgets.gamescroll), stwidgets.gamelist);

    gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(stwidgets.gamelist), FALSE);
    gtk_tree_view_set_enable_search(GTK_TREE_VIEW(stwidgets.gamelist), FALSE);

    // Game tab
    stwidgets.gametab = gtk_label_new("Game");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 1), stwidgets.gametab);

    // Messages scrollable area
    stwidgets.messagesscroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.messagesscroll);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(stwidgets.messagesscroll), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);

    // Messages text area
    stwidgets.messagestext = gtk_text_view_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.messagesscroll), stwidgets.messagestext);
    gtk_text_view_set_editable(GTK_TEXT_VIEW(stwidgets.messagestext), FALSE);
    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(stwidgets.messagestext), GTK_WRAP_WORD);
    gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(stwidgets.messagestext), FALSE);
    gtk_text_view_set_left_margin(GTK_TEXT_VIEW(stwidgets.messagestext), 2);
    gtk_text_view_set_right_margin(GTK_TEXT_VIEW(stwidgets.messagestext), 2);

    // Messages tab
    stwidgets.messagestab = gtk_label_new("Messages");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 2), stwidgets.messagestab);

    // Dialogue box buttons layout
    stwidgets.buttons = gtk_hbutton_box_new();
    gtk_box_pack_start(GTK_BOX(stwidgets.vlayout), stwidgets.buttons, FALSE, TRUE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.buttons), 3);
    gtk_button_box_set_layout(GTK_BUTTON_BOX(stwidgets.buttons), GTK_BUTTONBOX_END);

    // Cancel button
    stwidgets.cancelbutton = gtk_button_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.buttons), stwidgets.cancelbutton);
    GTK_WIDGET_SET_FLAGS(stwidgets.cancelbutton, GTK_CAN_DEFAULT);

    stwidgets.cancelbuttonalign = gtk_alignment_new(0.5, 0.5, 0, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.cancelbutton), stwidgets.cancelbuttonalign);

    stwidgets.cancelbuttonlayout = gtk_hbox_new(FALSE, 2);
    gtk_container_add(GTK_CONTAINER(stwidgets.cancelbuttonalign), stwidgets.cancelbuttonlayout);

    stwidgets.cancelbuttonicon = gtk_image_new_from_stock("gtk-cancel", GTK_ICON_SIZE_BUTTON);
    gtk_box_pack_start(GTK_BOX(stwidgets.cancelbuttonlayout), stwidgets.cancelbuttonicon, FALSE, FALSE, 0);

    stwidgets.cancelbuttonlabel = gtk_label_new_with_mnemonic("_Cancel");
    gtk_box_pack_start(GTK_BOX(stwidgets.cancelbuttonlayout), stwidgets.cancelbuttonlabel, FALSE, FALSE, 0);

    // Start button
    stwidgets.startbutton = gtk_button_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.buttons), stwidgets.startbutton);
    GTK_WIDGET_SET_FLAGS(stwidgets.startbutton, GTK_CAN_DEFAULT);

    gtk_window_set_default(GTK_WINDOW(stwidgets.startwin), stwidgets.startbutton);

    stwidgets.startbuttonalign = gtk_alignment_new(0.5, 0.5, 0, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.startbutton), stwidgets.startbuttonalign);

    stwidgets.startbuttonlayout = gtk_hbox_new(FALSE, 2);
    gtk_container_add(GTK_CONTAINER(stwidgets.startbuttonalign), stwidgets.startbuttonlayout);

    stwidgets.startbuttonicon = gtk_image_new_from_stock("gtk-execute", GTK_ICON_SIZE_BUTTON);
    gtk_box_pack_start(GTK_BOX(stwidgets.startbuttonlayout), stwidgets.startbuttonicon, FALSE, FALSE, 0);

    stwidgets.startbuttonlabel = gtk_label_new_with_mnemonic("_Start");
    gtk_box_pack_start(GTK_BOX(stwidgets.startbuttonlayout), stwidgets.startbuttonlabel, FALSE, FALSE, 0);

    // Wire up the signals
    g_signal_connect((gpointer) stwidgets.startwin, "delete_event",
                     G_CALLBACK(on_startwin_delete_event),
                     NULL);
    g_signal_connect((gpointer) stwidgets.vmode3dcombo, "changed",
                     G_CALLBACK(on_vmode3dcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.fullscreencheck, "toggled",
                     G_CALLBACK(on_fullscreencheck_toggled),
                     NULL);
#ifdef POLYMER
    g_signal_connect((gpointer) stwidgets.polymercheck, "toggled",
                     G_CALLBACK(on_polymercheck_toggled),
                     NULL);
#endif
    g_signal_connect((gpointer) stwidgets.inputdevcombo, "changed",
                     G_CALLBACK(on_inputdevcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.custommodcombo, "changed",
                     G_CALLBACK(on_custommodcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.autoloadcheck, "toggled",
                     G_CALLBACK(on_autoloadcheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.alwaysshowcheck, "toggled",
                     G_CALLBACK(on_alwaysshowcheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.cancelbutton, "clicked",
                     G_CALLBACK(on_cancelbutton_clicked),
                     NULL);
    g_signal_connect((gpointer) stwidgets.startbutton, "clicked",
                     G_CALLBACK(on_startbutton_clicked),
                     NULL);
    {
        GtkTreeSelection *sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(stwidgets.gamelist));
        gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
        g_signal_connect((gpointer) sel, "changed",
                         G_CALLBACK(on_gamelist_selection_changed),
                         NULL);
    }

    // Associate labels with their controls
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.vmode3dlabel), stwidgets.vmode3dcombo);
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.inputdevlabel), stwidgets.inputdevcombo);
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.custommodlabel), stwidgets.custommodcombo);
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.gamelabel), stwidgets.gamelist);

    return stwidgets.startwin;
}

// -- BUILD ENTRY POINTS ------------------------------------------------------

int32_t startwin_open(void)
{
    if (!gtkenabled) return 0;
    if (stwidgets.startwin) return 1;

    stwidgets.startwin = create_window();
    if (stwidgets.startwin)
    {
        SetPage(TAB_MESSAGES);
        gtk_widget_show_all(stwidgets.startwin);
        gtk_main_iteration_do(FALSE);
        return 0;
    }
    return -1;
}

int32_t startwin_close(void)
{
    if (!gtkenabled) return 0;
    if (!stwidgets.startwin) return 1;
    gtk_widget_destroy(stwidgets.startwin);
    stwidgets.startwin = NULL;
    return 0;
}

int32_t startwin_puts(const char *str)
{
    GtkWidget *textview;
    GtkTextBuffer *textbuffer;
    GtkTextIter enditer;
    GtkTextMark *mark;
    const char *aptr, *bptr;

    if (!gtkenabled || !str) return 0;
    if (!stwidgets.startwin) return 1;
    if (!(textview = stwidgets.messagestext)) return -1;
    textbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));

    gtk_text_buffer_get_end_iter(textbuffer, &enditer);
    for (aptr = bptr = str; *aptr != 0;)
    {
        switch (*bptr)
        {
        case '\b':
            if (bptr > aptr)
                gtk_text_buffer_insert(textbuffer, &enditer, (const gchar *)aptr, (gint)(bptr-aptr)-1);
#if GTK_CHECK_VERSION(2,6,0)
            gtk_text_buffer_backspace(textbuffer, &enditer, FALSE, TRUE);
#else
            {
                GtkTextIter iter2 = enditer;
                gtk_text_iter_backward_cursor_position(&iter2);
                //FIXME: this seems be deleting one too many chars somewhere!
                if (!gtk_text_iter_equal(&iter2, &enditer))
                    gtk_text_buffer_delete_interactive(textbuffer, &iter2, &enditer, TRUE);
            }
#endif
            aptr = ++bptr;
            break;
        case 0:
            if (bptr > aptr)
                gtk_text_buffer_insert(textbuffer, &enditer, (const gchar *)aptr, (gint)(bptr-aptr));
            aptr = bptr;
            break;
        case '\r':	// FIXME
        default:
            bptr++;
            break;
        }
    }

    mark = gtk_text_buffer_create_mark(textbuffer, NULL, &enditer, 1);
    gtk_text_view_scroll_to_mark(GTK_TEXT_VIEW(textview), mark, 0.0, FALSE, 0.0, 1.0);
    gtk_text_buffer_delete_mark(textbuffer, mark);

    return 0;
}

int32_t startwin_settitle(const char *title)
{
    if (!gtkenabled) return 0;
    if (!stwidgets.startwin) return 1;
    gtk_window_set_title(GTK_WINDOW(stwidgets.startwin), title);
    return 0;
}

int32_t startwin_idle(void *s)
{
    UNREFERENCED_PARAMETER(s);
    if (!gtkenabled) return 0;
    //if (!stwidgets.startwin) return 1;
    gtk_main_iteration_do(FALSE);
    return 0;
}

int32_t startwin_run(void)
{
    if (!gtkenabled) return 1;
    if (!stwidgets.startwin) return 1;

    SetPage(TAB_CONFIG);

    settings.shared = gSetup;
    settings.gamedir = g_modDir;
    settings.grp = g_selectedGrp;
#ifdef POLYMER
    settings.polymer = (glrendmode == REND_POLYMER) & (settings.shared.bpp != 8);
#endif
    PopulateForm(ALL);

    gtk_main();

    SetPage(TAB_MESSAGES);
    if (retval) // launch the game with these parameters
    {
        gSetup = settings.shared;
#ifdef POLYMER
        glrendmode = (settings.polymer) ? REND_POLYMER : REND_POLYMOST;
#endif
        g_selectedGrp = settings.grp;

        Bstrcpy(g_modDir, (g_noSetup == 0 && settings.gamedir != NULL) ? settings.gamedir : "/");
    }

    return retval;
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010 EDuke32 developers and contributors

This file is part of EDuke32.

EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#ifndef _WIN32
#error Only for Windows
#endif

#include "renderlayer.h"

#ifdef STARTUP_SETUP_WINDOW

#define NEED_WINDOWSX_H
#define NEED_COMMCTRL_H
#define ONLY_USERDEFS

#include "_control.h"
#include "build.h"
#include "cache1d.h"
#include "compat.h"
#include "keyboard.h"
#include "control.h"
#include "witchaven.h"
#include "config.h"
#include "grpscan.h"
#include "startwin.game.h"
#include "windows_inc.h"

#define TAB_CONFIG 0
#define TAB_MESSAGES 1

static struct
{
    struct grpfile_t const * grp;
    char *gamedir;
    ud_setup_t shared;
    int polymer;
}
settings;

static HWND startupdlg;
static HWND pages[3];
static int done = -1;
static int mode = TAB_CONFIG;

static BUILDVFS_FIND_REC *finddirs;

static inline void clearfilenames(void)
{
    klistfree(finddirs);
    finddirs = NULL;
}

static inline void getfilenames(char const *path)
{
    clearfilenames();
    finddirs = klistpath(path,"*",BUILDVFS_FIND_DIR);
}

#define POPULATE_VIDEO 1
#define POPULATE_CONFIG 2
#define POPULATE_GAME 4
#define POPULATE_GAMEDIRS 8

#ifdef INPUT_MOUSE
#undef INPUT_MOUSE
#endif

#define INPUT_KB 0
#define INPUT_MOUSE 1
#define INPUT_JOYSTICK 2
#define INPUT_ALL 3

const char *controlstrings[] = { "Keyboard only", "Keyboard and mouse", "Keyboard and joystick", "All supported devices" };

static void PopulateForm(int32_t pgs)
{
    char buf[512];

    if (pgs & POPULATE_GAMEDIRS)
    {
        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCGAMEDIR);

        getfilenames("/");
        (void)ComboBox_ResetContent(hwnd);
        int const r = ComboBox_AddString(hwnd, "None");
        (void)ComboBox_SetItemData(hwnd, r, 0);
        (void)ComboBox_SetCurSel(hwnd, r);
        auto dirs = finddirs;
        for (int i=1, j=1; dirs != NULL; dirs=dirs->next)
        {
            if (Bstrcasecmp(dirs->name, "autoload") == 0)
            {
                j++;
                continue;
            }

            (void)ComboBox_AddString(hwnd, dirs->name);
            (void)ComboBox_SetItemData(hwnd, i, j);
            if (Bstrcasecmp(dirs->name, settings.gamedir) == 0)
                (void)ComboBox_SetCurSel(hwnd, i);

            i++;
            j++;
        }
    }

    if (pgs & POPULATE_VIDEO)
    {
        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCVMODE);
        int mode = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, settings.shared.bpp, settings.shared.fullscreen, 1);

        if (mode < 0 || (settings.shared.bpp < 15 && (settings.polymer)))
        {
            int CONSTEXPR cd[] = { 32, 24, 16, 15, 8, 0 };
            int i;

            for (i=0; cd[i];)
            {
                if (cd[i] >= settings.shared.bpp) i++;
                else break;
            }
            for (; cd[i]; i++)
            {
                mode = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, cd[i], settings.shared.fullscreen, 1);
                if (mode < 0) continue;
                settings.shared.bpp = cd[i];
                break;
            }
        }

        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCFULLSCREEN), ((settings.shared.fullscreen) ? BST_CHECKED : BST_UNCHECKED));
        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCPOLYMER), ((settings.polymer) ? BST_CHECKED : BST_UNCHECKED));

        (void)ComboBox_ResetContent(hwnd);

        for (int i=0; i<validmodecnt; i++)
        {
            if (validmode[i].fs != (settings.shared.fullscreen)) continue;
            if ((validmode[i].bpp < 15) && (settings.polymer)) continue;

            // all modes get added to the 3D mode list
            Bsprintf(buf, "%dx%d %s", validmode[i].xdim, validmode[i].ydim, validmode[i].bpp == 8 ? "software" : "OpenGL");
            int const j = ComboBox_AddString(hwnd, buf);
            (void)ComboBox_SetItemData(hwnd, j, i);
            if (i == mode)(void)ComboBox_SetCurSel(hwnd, j);
        }
    }

    if (pgs & POPULATE_CONFIG)
    {
        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCALWAYSSHOW), (settings.shared.forcesetup ? BST_CHECKED : BST_UNCHECKED));
        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCAUTOLOAD), (!(settings.shared.noautoload) ? BST_CHECKED : BST_UNCHECKED));

        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCINPUT);

        (void)ComboBox_ResetContent(hwnd);
        (void)ComboBox_SetCurSel(hwnd, 0);

        int j = 4;

#ifdef RENDERTYPEWIN
        if (di_disabled) j = 2;
#endif

        for (int i=0; i<j; i++)
        {
            (void)ComboBox_InsertString(hwnd, i, controlstrings[i]);
            (void)ComboBox_SetItemData(hwnd, i, i);

            switch (i)
            {
            case INPUT_MOUSE:
                if (settings.shared.usemouse && !settings.shared.usejoystick)(void)ComboBox_SetCurSel(hwnd, i);
                break;
            case INPUT_JOYSTICK:
                if (!settings.shared.usemouse && settings.shared.usejoystick)(void)ComboBox_SetCurSel(hwnd, i);
                break;
            case INPUT_ALL:
                if (settings.shared.usemouse && settings.shared.usejoystick)(void)ComboBox_SetCurSel(hwnd, i);
                break;
            }
        }
    }

    if (pgs & POPULATE_GAME)
    {
        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCDATA);

        for (auto fg = foundgrps; fg; fg=fg->next)
        {
            Bsprintf(buf, "%s\t%s", fg->type->name, fg->filename);
            int const j = ListBox_AddString(hwnd, buf);
            (void)ListBox_SetItemData(hwnd, j, (LPARAM)fg);
            if (settings.grp == fg)
                (void)ListBox_SetCurSel(hwnd, j);
        }
    }
}

static INT_PTR CALLBACK ConfigPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDCFULLSCREEN:
            settings.shared.fullscreen = !settings.shared.fullscreen;
            PopulateForm(POPULATE_VIDEO);
            return TRUE;
        case IDCPOLYMER:
            settings.polymer = !settings.polymer;
            if (settings.shared.bpp == 8) settings.shared.bpp = 32;
            PopulateForm(POPULATE_VIDEO);
            return TRUE;
        case IDCVMODE:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    settings.shared.xdim = validmode[i].xdim;
                    settings.shared.ydim = validmode[i].ydim;
                    settings.shared.bpp  = validmode[i].bpp;
                }
            }
            return TRUE;
        case IDCALWAYSSHOW:
            settings.shared.forcesetup = IsDlgButtonChecked(hwndDlg, IDCALWAYSSHOW) == BST_CHECKED;
            return TRUE;
        case IDCAUTOLOAD:
            settings.shared.noautoload = (IsDlgButtonChecked(hwndDlg, IDCAUTOLOAD) != BST_CHECKED);
            return TRUE;
        case IDCINPUT:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    switch (i)
                    {
                    case INPUT_KB:
                        settings.shared.usemouse = settings.shared.usejoystick = 0;
                        break;
                    case INPUT_MOUSE:
                        settings.shared.usemouse = 1;
                        settings.shared.usejoystick = 0;
                        break;
                    case INPUT_JOYSTICK:
                        settings.shared.usemouse = 0;
                        settings.shared.usejoystick = 1;
                        break;
                    case INPUT_ALL:
                        settings.shared.usemouse = settings.shared.usejoystick = 1;
                        break;
                    }
                }
            }
            return TRUE;

        case IDCGAMEDIR:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    if (i==0)
                        settings.gamedir = NULL;
                    else
                    {
                        BUILDVFS_FIND_REC *dir = finddirs;
                        for (int j = 1; dir != NULL; dir = dir->next, j++)
                        {
                            if (j == i)
                            {
                                settings.gamedir = dir->name;
                                break;
                            }
                        }
                    }
                }
            }
            return TRUE;
        case IDCDATA:
        {
            if (HIWORD(wParam) != LBN_SELCHANGE) break;
            intptr_t i = ListBox_GetCurSel((HWND)lParam);
            if (i != CB_ERR) i = ListBox_GetItemData((HWND)lParam, i);
            if (i != CB_ERR)
            {
                settings.grp = (grpfile_t const *)i;
            }
            return TRUE;
        }
        default:
            break;
        }
        break;
    default:
        break;
    }
    return FALSE;
}

static void SetPage(int pageNum)
{
    HWND tab = GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL);
    auto const cur = SendMessage(tab, TCM_GETCURSEL, 0, 0);
    ShowWindow(pages[cur], SW_HIDE);
    SendMessage(tab, TCM_SETCURSEL, pageNum, 0);
    ShowWindow(pages[pageNum], SW_SHOW);
    mode = pageNum;

    SetFocus(GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL));
}

static void EnableConfig(bool n)
{
    //EnableWindow(GetDlgItem(startupdlg, WIN_STARTWIN_CANCEL), n);
    EnableWindow(GetDlgItem(startupdlg, WIN_STARTWIN_START), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCDATA), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCFULLSCREEN), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCGAMEDIR), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCINPUT), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCPOLYMER), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCVMODE), n);
}

static INT_PTR CALLBACK startup_dlgproc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    static HBITMAP hbmp = NULL;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        // Fetch the positions (in screen coordinates) of all the windows we need to tweak
        RECT chrome = {};
        AdjustWindowRect(&chrome, GetWindowLong(hwndDlg, GWL_STYLE), FALSE);
        RECT rdlg;
        GetWindowRect(hwndDlg, &rdlg);

        // Knock off the non-client area of the main dialogue to give just the client area
        rdlg.left -= chrome.left;
        rdlg.top -= chrome.top;
        rdlg.right -= chrome.right;
        rdlg.bottom -= chrome.bottom;

        RECT rtab;
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL), &rtab);

        // Translate them to client-relative coordinates wrt the main dialogue window
        rtab.right -= rtab.left - 1;
        rtab.bottom -= rtab.top - 1;
        rtab.left  -= rdlg.left;
        rtab.top -= rdlg.top;

        RECT rcancel;
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_CANCEL), &rcancel);

        rcancel.right -= rcancel.left - 1;
        rcancel.bottom -= rcancel.top - 1;
        rcancel.left -= rdlg.left;
        rcancel.top -= rdlg.top;

        RECT rstart;
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_START), &rstart);

        rstart.right -= rstart.left - 1;
        rstart.bottom -= rstart.top - 1;
        rstart.left -= rdlg.left;
        rstart.top -= rdlg.top;

        // And then convert the main dialogue coordinates to just width/length
        rdlg.right -= rdlg.left - 1;
        rdlg.bottom -= rdlg.top - 1;
        rdlg.left = 0;
        rdlg.top = 0;

        // Load the bitmap into the bitmap control and fetch its dimensions
        hbmp = LoadBitmap((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(RSRC_BMP));

        HWND hwnd = GetDlgItem(hwndDlg, WIN_STARTWIN_BITMAP);
        SendMessage(hwnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hbmp);

        RECT r;
        GetClientRect(hwnd, &r);

        int const xoffset = r.right;
        int const yoffset = r.bottom - rdlg.bottom;

        // Shift and resize the controls that require it
        rtab.left += xoffset;
        rtab.bottom += yoffset;
        rcancel.left += xoffset;
        rcancel.top += yoffset;
        rstart.left += xoffset;
        rstart.top += yoffset;
        rdlg.right += xoffset;
        rdlg.bottom += yoffset;

        // Move the controls to their new positions
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL), rtab.left, rtab.top, rtab.right, rtab.bottom, FALSE);
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_CANCEL), rcancel.left, rcancel.top, rcancel.right, rcancel.bottom, FALSE);
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_START), rstart.left, rstart.top, rstart.right, rstart.bottom, FALSE);

        // Move the main dialogue to the centre of the screen
        HDC hdc = GetDC(NULL);
        rdlg.left = (GetDeviceCaps(hdc, HORZRES) - rdlg.right) / 2;
        rdlg.top = (GetDeviceCaps(hdc, VERTRES) - rdlg.bottom) / 2;
        ReleaseDC(NULL, hdc);
        MoveWindow(hwndDlg, rdlg.left + chrome.left, rdlg.top + chrome.left,
                   rdlg.right + (-chrome.left+chrome.right), rdlg.bottom + (-chrome.top+chrome.bottom), TRUE);

        // Add tabs to the tab control
        {
            static char textSetup[] = TEXT("Setup");
            static char textMessageLog[] = TEXT("Message Log");

            hwnd = GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL);

            TCITEM tab = {};
            tab.mask = TCIF_TEXT;
            tab.pszText = textSetup;
            SendMessage(hwnd, TCM_INSERTITEM, (WPARAM)TAB_CONFIG, (LPARAM)&tab);
            tab.mask = TCIF_TEXT;
            tab.pszText = textMessageLog;
            SendMessage(hwnd, TCM_INSERTITEM, (WPARAM)TAB_MESSAGES, (LPARAM)&tab);

            // Work out the position and size of the area inside the tab control for the pages
            ZeroMemory(&r, sizeof(r));
            GetClientRect(hwnd, &r);
            SendMessage(hwnd, TCM_ADJUSTRECT, FALSE, (LPARAM)&r);
            r.right -= r.left-1;
            r.bottom -= r.top-1;
            r.top += rtab.top;
            r.left += rtab.left;

            // Create the pages and position them in the tab control, but hide them
            pages[TAB_CONFIG] = CreateDialog((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(WIN_STARTWINPAGE_CONFIG), hwndDlg, ConfigPageProc);
            SetWindowPos(pages[TAB_CONFIG], hwnd, r.left, r.top, r.right, r.bottom, SWP_HIDEWINDOW);

            pages[TAB_MESSAGES] = GetDlgItem(hwndDlg, WIN_STARTWIN_MESSAGES);
            SetWindowPos(pages[TAB_MESSAGES], hwnd, r.left, r.top, r.right, r.bottom, SWP_HIDEWINDOW);

            // Tell the editfield acting as the console to exclude the width of the scrollbar
            GetClientRect(pages[TAB_MESSAGES], &r);
            r.right -= GetSystemMetrics(SM_CXVSCROLL)+4;
            r.left = r.top = 0;
            SendMessage(pages[TAB_MESSAGES], EM_SETRECTNP,0,(LPARAM)&r);

            // Set a tab stop in the game data listbox
            {
                DWORD tabs[1] = { 150 };
                (void)ListBox_SetTabStops(GetDlgItem(pages[TAB_CONFIG], IDCDATA), 1, tabs);
            }

            SetFocus(GetDlgItem(hwndDlg, WIN_STARTWIN_START));
            SetWindowText(hwndDlg, apptitle);
        }
        return FALSE;
    }

    case WM_NOTIFY:
    {
        auto nmhdr = (LPNMHDR)lParam;
        if (nmhdr->idFrom != WIN_STARTWIN_TABCTL) break;
        int const cur = SendMessage(nmhdr->hwndFrom, TCM_GETCURSEL,0,0);
        switch (nmhdr->code)
        {
            case TCN_SELCHANGING:
            case TCN_SELCHANGE:
                if (cur < 0 || !pages[cur])
                    break;
                ShowWindow(pages[cur], nmhdr->code == TCN_SELCHANGING ? SW_HIDE : SW_SHOW);
                return TRUE;
        }
        break;
    }

    case WM_CLOSE:
        if (mode == TAB_CONFIG) done = 0;
        else quitevent++;
        return TRUE;

    case WM_DESTROY:
        if (hbmp)
        {
            DeleteObject(hbmp);
            hbmp = NULL;
        }

        if (pages[TAB_CONFIG])
        {
            DestroyWindow(pages[TAB_CONFIG]);
            pages[TAB_CONFIG] = NULL;
        }

        startupdlg = NULL;
        return TRUE;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case WIN_STARTWIN_CANCEL:
            if (mode == TAB_CONFIG) done = 0;
            else quitevent++;
            return TRUE;
        case WIN_STARTWIN_START:
            done = 1;
            return TRUE;
        }
        return FALSE;

    case WM_CTLCOLORSTATIC:
        if ((HWND)lParam == pages[TAB_MESSAGES])
            return (BOOL)(intptr_t)GetSysColorBrush(COLOR_WINDOW);
        break;

    default:
        break;
    }

    return FALSE;
}

bool startwin_isopen(void)
{
    return !!startupdlg;
}

int32_t startwin_open(void)
{
    if (startupdlg) return 1;
    INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_TAB_CLASSES };
    InitCommonControlsEx(&icc);
    startupdlg = CreateDialog((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(WIN_STARTWIN), NULL, startup_dlgproc);
    if (startupdlg)
    {
        SetPage(TAB_MESSAGES);
        EnableConfig(0);
        return 0;
    }
    return -1;
}

int32_t startwin_close(void)
{
    if (!startupdlg) return 1;
    DestroyWindow(startupdlg);
    startupdlg = NULL;
    return 0;
}

int32_t startwin_puts(const char *buf)
{
    if (!startupdlg) return 1;

    const HWND edctl = pages[TAB_MESSAGES];

    if (!edctl) return -1;

    static HWND dactrl = NULL;
    if (!dactrl) dactrl = GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL);

    int const vis = ((int)SendMessage(dactrl, TCM_GETCURSEL,0,0) == TAB_MESSAGES);

    if (vis)
        SendMessage(edctl, WM_SETREDRAW, FALSE, 0);

    int const curlen = SendMessage(edctl, WM_GETTEXTLENGTH, 0,0);
    SendMessage(edctl, EM_SETSEL, (WPARAM)curlen, (LPARAM)curlen);

    int const   numlines = SendMessage(edctl, EM_GETLINECOUNT, 0, 0);
    static bool newline  = false;
    const char *p        = buf;

    while (*p)
    {
        if (newline)
        {
            SendMessage(edctl, EM_REPLACESEL, 0, (LPARAM)"\r\n");
            newline = false;
        }
        const char *q = p;
        while (*q && *q != '\n') q++;
        static char workbuf[1024];
        Bmemcpy(workbuf, p, q-p);
        if (*q == '\n')
        {
            if (!q[1])
            {
                newline = true;
                workbuf[q-p] = 0;
            }
            else
            {
                workbuf[q-p] = '\r';
                workbuf[q-p+1] = '\n';
                workbuf[q-p+2] = 0;
            }
            p = q+1;
        }
        else
        {
            workbuf[q-p] = 0;
            p = q;
        }
        SendMessage(edctl, EM_REPLACESEL, 0, (LPARAM)workbuf);
    }

    int const newnumlines = SendMessage(edctl, EM_GETLINECOUNT, 0, 0);
    SendMessage(edctl, EM_LINESCROLL, 0, newnumlines - numlines);

    if (vis)
        SendMessage(edctl, WM_SETREDRAW, TRUE, 0);

    return 0;
}

int32_t startwin_settitle(const char *str)
{
    if (!startupdlg) return 1;
    SetWindowText(startupdlg, str);
    return 0;
}

int32_t startwin_idle(void *v)
{
    if (!startupdlg || !IsWindow(startupdlg)) return 0;
    if (IsDialogMessage(startupdlg, (MSG *)v)) return 1;
    return 0;
}

int32_t startwin_run(void)
{
    if (!startupdlg) return 1;

    done = -1;

    SetPage(TAB_CONFIG);
    EnableConfig(1);

#ifdef POLYMER
    settings.polymer = (glrendmode == REND_POLYMER);
#else
    settings.polymer = 0;
#endif

    settings.shared = gSetup;
    settings.grp = g_selectedGrp;
    settings.gamedir = g_modDir;

    PopulateForm(-1);

    do
    {
        MSG msg;

        switch (GetMessage(&msg, NULL, 0,0))
        {
        case 0:
            done = 1;
            break;
        case -1:
            return -1;
        default:
            if (IsWindow(startupdlg) && IsDialogMessage(startupdlg, &msg))
                break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            break;
        }
    }
    while (done < 0);

    SetPage(TAB_MESSAGES);
    EnableConfig(0);

    if (done)
    {
        gSetup = settings.shared;
#ifdef USE_OPENGL
        glrendmode = (settings.polymer) ? REND_POLYMER : REND_POLYMOST;
#endif
        g_selectedGrp = settings.grp;
        if (g_modDir != settings.gamedir)
            Bstrcpy(g_modDir, (g_noSetup == 0 && settings.gamedir != NULL) ? settings.gamedir : "/");
    }

    return done;
}

#endif // STARTUP_SETUP_WINDOW


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010 EDuke32 developers and contributors

This file is part of EDuke32.

EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

// resource ids
#define WIN_STARTWIN		1000
#define WIN_STARTWINPAGE_CONFIG 2000
#define WIN_STARTWIN_BITMAP	100	// banner bitmap
#define WIN_STARTWIN_TABCTL	101
#define WIN_STARTWIN_CANCEL	IDCANCEL
#define WIN_STARTWIN_START	IDOK

#define WIN_STARTWIN_MESSAGES	104	// output list box

#define RSRC_ICON		100
#define RSRC_BMP		200

// config page
#define IDCFULLSCREEN	100
#define IDCVMODE	    101
#define IDCSOUNDDRV	    102
#define IDCMIDIDEV	    103
#define IDCCDADEV	    104
#define IDCALWAYSSHOW	105
#define IDCDATA         106
#define IDCGAMEDIR      107
#define IDCPOLYMER      108
#define IDCAUTOLOAD     109
#define IDCINPUT	    110