Merge branch 'master' of harrygodden.com:/home/fishladder into master
authorhgn <hgodden00@gmail.com>
Mon, 13 Dec 2021 08:00:44 +0000 (08:00 +0000)
committerhgn <hgodden00@gmail.com>
Mon, 13 Dec 2021 08:00:44 +0000 (08:00 +0000)
52 files changed:
build.sh
fishladder.c
fishladder_resources.h
maps/cmp_and.map [new file with mode: 0644]
maps/cmp_b01.map [new file with mode: 0644]
maps/cmp_b02.map [new file with mode: 0644]
maps/cmp_b03.map [new file with mode: 0644]
maps/cmp_b04.map [new file with mode: 0644]
maps/cmp_b05.map [new file with mode: 0644]
maps/cmp_b06.map [new file with mode: 0644]
maps/cmp_b07.map [new file with mode: 0644]
maps/cmp_b08.map [new file with mode: 0644]
maps/cmp_b09.map [new file with mode: 0644]
maps/cmp_b10.map [new file with mode: 0644]
maps/cmp_b11.map [new file with mode: 0644]
maps/cmp_grad.map [new file with mode: 0644]
maps/cmp_i01.map [new file with mode: 0644]
maps/cmp_i02.map [new file with mode: 0644]
maps/cmp_not.map [new file with mode: 0644]
maps/cmp_routing.map [new file with mode: 0644]
maps/cmp_secret.map [new file with mode: 0644]
maps/cmp_t01.map [new file with mode: 0644]
maps/cmp_t02.map [new file with mode: 0644]
maps/cmp_t03.map [new file with mode: 0644]
maps/cmp_t04.map [new file with mode: 0644]
maps/cmp_xor.map [new file with mode: 0644]
maps/level0.map [deleted file]
maps/level1.map [deleted file]
maps/level2.map [deleted file]
maps/level3.map [deleted file]
maps/level4.map [deleted file]
maps/sort.map [deleted file]
maps/spam.map [new file with mode: 0644]
maps/thirds.map [deleted file]
sound/click_a.ogg [new file with mode: 0644]
sound/click_b.ogg [new file with mode: 0644]
sound/click_c.ogg [new file with mode: 0644]
sound/rolling_01.ogg
sound/splitter_01.ogg
textures/ascii.png [new file with mode: 0644]
textures/bnoise.png [new file with mode: 0644]
textures/buttons.png [new file with mode: 0644]
textures/unkown.png [new file with mode: 0644]
vg/config.h
vg/vg.h
vg/vg_audio.h
vg/vg_console.h
vg/vg_input.h
vg/vg_m.h
vg/vg_platform.h
vg/vg_steamworks.h [new file with mode: 0644]
vg/vg_ui.h

index 485a8c170626e76b7bb2902d1c0a3c4413d9dd0d..63891f6238109708a1f33facbefb4dec890da946 100755 (executable)
--- a/build.sh
+++ b/build.sh
@@ -3,7 +3,7 @@
 src="fishladder.c"
 target="fishladder"
 lib="-I. -L./lib -L./"
-libs="-lGL -lglfw -lX11 -lXxf86vm -lXrandr -lm -lpthread -lXi -ldl" # -l:steam/libsteam_api.so"
+libs="-lGL -lglfw -lX11 -lXxf86vm -lXrandr -lm -lpthread -lXi -ldl -l:steam/libsteam_api.so"
 flags="-fsanitize=address -ggdb3 -Wno-unused-function -DNO_STEAM"
 build_dir="build.linux"
 
@@ -24,7 +24,7 @@ compile_models=false
 while (( "$#" )); do
        case $1 in
                -r|--release) 
-                       flags="-O3 -Wno-unused-function -DNO_STEAM"
+                       flags="-O3 -Wno-unused-function"
                        echo "Release mode" 
                ;;
                -p|--play)
index 26a94eb404d0abf76f19a0a5e9a33ce64342165c..d7b887d2f602bc62b0a7a2f03cb9af134a8e0cd6 100644 (file)
 // Copyright (C) 2021 Harry Godden (hgn) - All Rights Reserved
 
-//#define VG_STEAM
+#define VG_STEAM
+#define VG_STEAM_APPID 1218140U
 #include "vg/vg.h"
 #include "fishladder_resources.h"
 
-const char *level_pack_1[] = { 
-       "level0", 
-       "level1", 
-       "level2", 
-       "level3", 
-       "level4",
-       "level5",
-       "level6",
-       "level7_combine",
-       "xor_small",
-       "sort",
-       "thirds"
-};
+// CONSTANTS
+// ===========================================================================================================
 
-#pragma pack(push,1)
-struct career_state
+enum cell_type
 {
-       u32 version;
-
-       struct career_level
-       {
-               u32 score;
-               u32 time;
-               u32 completed;
-       }
-       levels[ vg_list_size( level_pack_1 ) ]; 
-}
-career = { .version = 1 };
-#pragma pack(pop)
+       k_cell_type_stub = 0,
+       k_cell_type_ramp_right = 3,
+       k_cell_type_ramp_left = 6,
+       k_cell_type_split = 7,
+       k_cell_type_merge = 13,
+       k_cell_type_con_r = 1,
+       k_cell_type_con_u = 2,
+       k_cell_type_con_l = 4,
+       k_cell_type_con_d = 8
+};
 
-static void career_serialize(void)
+enum e_fish_state
 {
-       vg_asset_write( "sav/game.sav", &career, sizeof( struct career_state ) );
-}
+       k_fish_state_soon_dead = -1,
+       k_fish_state_dead = 0,
+       k_fish_state_alive,
+       k_fish_state_bg,
+       k_fish_state_soon_alive
+};
 
-static void career_load(void)
+enum e_world_button
 {
-       i64 sz;
-       struct career_state *cr = vg_asset_read_s( "sav/game.sav", &sz );
-       
-       memset( (void*)career.levels, 0, vg_list_size(level_pack_1) * sizeof(struct career_level) );
-       
-       if( cr )
-       {
-               if( sz > sizeof( struct career_state ) )
-                       vg_warn( "This save file is too big! Some levels will be lost\n" );
-               
-               if( sz <= offsetof( struct career_state, levels ) )
-               {
-                       vg_error( "This save file is too small to have a header\n" );
-                       free( cr );
-                       return;
-               }
-               
-               u32 const size_header = offsetof(struct career_state, levels);
-               u32 const size_levels = sizeof(struct career_state)-size_header;
-               u32 const size_levels_input = sz - size_header;
-               
-               memcpy( (void*)career.levels, (void*)cr->levels, size_levels_input );
-               
-               if( sz < sizeof( struct career_state ) )
-               {
-                       memset( ((void*)career.levels) + size_levels_input, 0, size_levels-size_levels_input );
-               }
-               
-               free( cr );
-               vg_success( "Loaded save file... Info:\n" );
-               
-               for( int i = 0; i < vg_list_size( career.levels ); i ++ )
-               {
-                       struct career_level *lvl = &career.levels[i];
-                       vg_info( "Score: %u, Time: %u, Completed: %u\n", lvl->score, lvl->time, lvl->completed );
-               }
-       }
-       else
-       {
-               vg_info( "No save file... Using blank one\n" );
-       }
-}
-
-m3x3f m_projection;
-m3x3f m_view;
-m3x3f m_mdl;
+       k_world_button_none = -1,
+       k_world_button_sim = 0,
+       k_world_button_pause = 1,
+       k_world_button_wire_mode = 2
+};
 
 #define FLAG_CANAL             0x1
 #define FLAG_IS_TRIGGER 0x2
 #define FLAG_RESERVED0         0x4
 #define FLAG_RESERVED1         0x8
 
-#define FLAG_INPUT 0x10
-#define FLAG_OUTPUT 0x20
-#define FLAG_WALL 0x40
+#define FLAG_INPUT             0x10
+#define FLAG_OUTPUT            0x20
+#define FLAG_WALL              0x40
 
-#define FLAG_FLIP_FLOP 0x100
-#define FLAG_TRIGGERED 0x200
+#define FLAG_FLIP_FLOP         0x100
+#define FLAG_TRIGGERED         0x200
 #define FLAG_FLIP_ROTATING 0x400
-#define FLAG_TARGETED 0x800
+#define FLAG_TARGETED  0x800
 
 /*
        0000 0   | 0001 1   | 0010 2   | 0011 3
@@ -121,83 +71,62 @@ m3x3f m_mdl;
                |          |    |     |    |     |    |
 */
 
-enum cell_type
-{
-       k_cell_type_ramp_right = 3,
-       k_cell_type_ramp_left = 6,
-       k_cell_type_split = 7,
-       k_cell_type_merge = 13,
-       k_cell_type_con_r = 1,
-       k_cell_type_con_u = 2,
-       k_cell_type_con_l = 4,
-       k_cell_type_con_d = 8
-};
-
-v3f colour_sets[] =
-{ { 0.9f, 0.6f, 0.20f },
-  { 0.2f, 0.9f, 0.14f },
-  { 0.4f, 0.8f, 1.00f } };
-
-static void colour_code_v3( char cc, v3f target )
+static struct cell_description
 {
-       if( cc >= 'a' && cc <= 'z' )
-       {
-               int id = cc - 'a';
-               
-               if( id < vg_list_size( colour_sets ) )
-               {
-                       v3_copy( colour_sets[ id ], target );
-                       return;
-               }
-       }
+       v2i start;
+       v2i end;
        
-       v3_copy( (v3f){0.0f,0.0f,0.0f}, target );
+       int is_special;
+       int is_linear;
+       
+       v2f trigger_pos;
 }
-
-struct mesh
+cell_descriptions[] =
 {
-       GLuint vao, vbo;
-       u32 elements;
+       // 0-3
+       {},
+       { .start = {  1,  0 }, .end = { -1,  0 }, .trigger_pos = { 0.5f, 0.25f } },
+       { .start = {  0,  1 }, .end = {  0, -1 }, .trigger_pos = { 0.25f, 0.5f } },
+       { .start = {  0,  1 }, .end = {  1,  0 }, .trigger_pos = { 0.25f, 0.25f } },
+       // 4-7
+       { .start = { -1,  0 }, .end = {  1,  0 }, .trigger_pos = { 0.5f, 0.25f } },
+       { .start = { -1,  0 }, .end = {  1,  0 }, .trigger_pos = { 0.5f, 0.25f }, .is_linear = 1 },
+       { .start = {  0,  1 }, .end = { -1,  0 }, .trigger_pos = { 0.5f, 0.25f } },
+       { .start = {  0,  1 }, .is_special = 1 },
+       // 8-11
+       { .start = {  0, -1 }, .end = {  0,  1 }, .trigger_pos = { 0.25f, 0.5f } },
+       { .start = {  1,  0 }, .end = {  0, -1 }, .trigger_pos = { 0.25f, 0.75f } },
+       { .start = {  0,  1 }, .end = {  0, -1 }, .trigger_pos = { 0.25f, 0.5f }, .is_linear = 1 },
+       { },
+       // 12-15
+       { .start = { -1,  0 }, .end = {  0, -1 }, .trigger_pos = { 0.75f, 0.75f } },
+       { .end = { 0, -1 }, .is_special = 1, .trigger_pos = { 0.5f, 0.75f } },
+       { },
+       { }
 };
 
-static void init_mesh( struct mesh *m, float const *tris, u32 length )
-{
-       m->elements = length/3;
-       glGenVertexArrays( 1, &m->vao );
-       glGenBuffers( 1, &m->vbo );
-       
-       glBindVertexArray( m->vao );
-       glBindBuffer( GL_ARRAY_BUFFER, m->vbo );
-       glBufferData( GL_ARRAY_BUFFER, length*sizeof(float), tris, GL_STATIC_DRAW );
-       
-       glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0 );
-       glEnableVertexAttribArray( 0 );
-       
-       VG_CHECK_GL();
-}
+v2f const curve_3[] = {{0.5f,1.0f},{0.5f,0.625f},{0.625f,0.5f},{1.0f,0.5f}};
+v2f const curve_6[] = {{0.5f,1.0f},{0.5f,0.625f},{0.375f,0.5f},{0.0f,0.5f}};
+v2f const curve_9[] = {{1.0f,0.5f},{0.625f,0.5f},{0.5f,0.375f},{0.5f,0.0f}};
+v2f const curve_12[]= {{0.0f,0.5f},{0.375f,0.5f},{0.5f,0.375f},{0.5f,0.0f}};
 
-static void free_mesh( struct mesh *m )
-{
-       glDeleteVertexArrays( 1, &m->vao );
-       glDeleteBuffers( 1, &m->vbo );
-}
+v2f const curve_1[] = {{1.0f,0.5f},{0.8f,0.5f},{0.3f,0.5f},{0.2f,0.5f}};
+v2f const curve_4[] = {{0.0f,0.5f},{0.3f,0.5f},{0.5f,0.5f},{0.8f,0.5f}};
+v2f const curve_2[] = {{0.5f,1.0f},{0.5f,0.8f},{0.5f,0.3f},{0.5f,0.2f}};
+v2f const curve_8[] = {{0.5f,0.0f},{0.5f,0.3f},{0.5f,0.5f},{0.5f,0.8f}};
 
-static void draw_mesh( int const start, int const count )
-{
-       glDrawArrays( GL_TRIANGLES, start*3, count*3 );
-}
+v2f const curve_7[] = {{0.5f,0.8438f},{0.875f,0.8438f},{0.625f,0.5f},{1.0f,0.5f}};
+v2f const curve_7_1[] = {{0.5f,0.8438f},{1.0f-0.875f,0.8438f},{1.0-0.625f,0.5f},{0.0f,0.5f}};
 
-static void use_mesh( struct mesh *m )
-{
-       glBindVertexArray( m->vao );
-}
+float const curve_7_linear_section = 0.1562f;
 
-enum e_fish_state
+// Types
+// ===========================================================================================================
+
+struct mesh
 {
-       k_fish_state_soon_dead = -1,
-       k_fish_state_dead = 0,
-       k_fish_state_alive,
-       k_fish_state_bg
+       GLuint vao, vbo;
+       u32 elements;
 };
 
 struct world
@@ -213,22 +142,22 @@ struct world
        *data;
 #pragma pack(pop)
        
-       int frame;
        
        int initialzed;
        
-       int sim_frame;
-       float sim_start;
-       int simulating;
        int sim_run, max_runs;
-       
-       float frame_lerp;
+
+       int sim_frame, sim_target;
+       float sim_internal_time,                // current tick-time 
+               sim_internal_delta,                     // time delta
+               sim_internal_ref,                               // Reference point of internal time
+               sim_delta_ref,                          // Reference point of vg_time when we started at current sim_speed
+               sim_delta_speed,                                // Rate to apply time delta
+               frame_lerp,                                             // Fractional part of sim_internal_time
+               pause_offset_target;                    // 
        
        struct cell_terminal
        {
-               //char *conditions;
-               //char recv[12];
-               
                struct terminal_run
                {
                        char conditions[8];
@@ -239,14 +168,21 @@ struct world
                runs[8];
                
                int run_count;
-               
-               int id;
+               v2i pos;
+               //int id;
        }
        *io;
        
+       struct cell_button
+       {
+               float light_target, light;
+               int pressed;
+       }
+       buttons[4];
+       
        int w, h;
        
-       struct mesh tile, circle, numbers;
+       struct mesh shapes, numbers;
        struct mesh_wire
        {
                GLuint vao, vbo, ebo;
@@ -266,6 +202,7 @@ struct world
                v2i dir;
                enum e_fish_state state;
                char payload;
+               int flow_reversed;
                float death_time;
                v2f physics_v;
                v2f physics_co;
@@ -274,14 +211,151 @@ struct world
        
        int num_fishes;
        
-       char map_name[128];
-       struct career_level *ptr_career_level;
+       char map_name[64];
+       //struct career_level *ptr_career_level;
+       struct cmp_level *pCmpLevel;
        
        u32 score;
        u32 completed;
        u32 time;
        
-} world = {};
+       u16 id_drag_from;
+       v2f drag_from_co;
+       v2f drag_to_co;
+};
+
+// Forward declerations
+// --------------------
+
+static int console_credits( int argc, char const *argv[] );
+static int console_save_map( int argc, char const *argv[] );
+static int console_load_map( int argc, char const *argv[] );
+static int console_changelevel( int argc, char const *argv[] );
+
+// GLOBALS
+// ===========================================================================================================
+
+m3x3f m_projection;
+m3x3f m_view;
+m3x3f m_mdl;
+
+struct world world;
+
+// UTILITY
+// ===========================================================================================================
+
+static void colour_code_v3( char const cc, v3f target )
+{
+       static v3f colour_sets[] =
+       { { 1.0f, 0.9f, 0.3f },
+         { 0.2f, 0.9f, 0.14f },
+         { 0.4f, 0.8f, 1.00f },
+         { 0.882f, 0.204f, 0.922f }
+       };
+
+       if( cc >= 'a' && cc <= 'z' )
+       {
+               int id = cc - 'a';
+               
+               if( id < vg_list_size( colour_sets ) )
+               {
+                       v3_copy( colour_sets[ id ], target );
+                       return;
+               }
+       }
+       
+       v3_copy( (v3f){0.0f,0.0f,0.0f}, target );
+}
+
+static int hash21i( v2i p, u32 umod )
+{
+       static const int random_noise[] = 
+       {
+       0x46,0xD5,0xB8,0xD3,0xF2,0xE5,0xCC,0x07,0xD0,0xB3,0x7A,0xA2,0xC3,0xDA,0xDC,0x7F,0xE0,0xB7,0x42,0xA0,0xBF,0x41,0x92,0x32,0x6F,0x0D,0x45,0xC7,0x54,0xDB,0x30,0xC2,
+       0xD5,0xDA,0x55,0x09,0xDE,0x74,0x48,0x20,0xE1,0x24,0x5C,0x4D,0x6F,0x36,0xD8,0xE9,0x8D,0x8F,0x54,0x99,0x98,0x51,0xFE,0xDB,0x26,0x04,0x65,0x57,0x56,0xF3,0x53,0x30,
+       0x3D,0x16,0xC0,0xB6,0xF2,0x47,0xCF,0x62,0xB0,0x6C,0x8F,0x4F,0x8C,0x4C,0x17,0xF0,0x19,0x7E,0x2D,0x81,0x8D,0xFB,0x10,0xD3,0x49,0x50,0x60,0xFD,0x38,0x15,0x3B,0xEE,
+       0x05,0xC1,0xCF,0x62,0x97,0x75,0xDF,0x4E,0x4D,0x89,0x5E,0x88,0x5C,0x30,0x8C,0x54,0x1D,0x39,0x41,0xEA,0xA2,0x63,0x12,0x1B,0x8E,0x35,0x22,0x9B,0x98,0xA3,0x7F,0x80,
+       0xD6,0x27,0x94,0x66,0xB5,0x1D,0x7E,0xDF,0x96,0x28,0x38,0x3A,0xA0,0xE8,0x71,0x09,0x62,0x5E,0x9D,0x53,0x58,0x1B,0x7D,0x0D,0x2D,0x99,0x77,0x83,0xC3,0x89,0xC2,0xA2,
+       0xA7,0x1D,0x78,0x80,0x37,0xC1,0x87,0xFF,0x65,0xBF,0x2C,0xF1,0xE5,0xB3,0x09,0xE0,0x25,0x92,0x83,0x0F,0x8A,0x57,0x3C,0x0B,0xC6,0xBC,0x44,0x16,0xE3,0xCE,0xC3,0x0D,
+       0x69,0xD3,0xC6,0x99,0xB8,0x46,0x44,0xC4,0xF3,0x1E,0xBF,0xF5,0xB4,0xDB,0xFB,0x93,0xA1,0x7B,0xC9,0x08,0x77,0x22,0xE5,0x02,0xEF,0x9E,0x90,0x94,0x8A,0xA6,0x3D,0x7E,
+       0xA2,0xA0,0x10,0x82,0x47,0x5C,0xAA,0xF8,0x2F,0x0D,0x9F,0x76,0xDA,0x99,0x0F,0xCB,0xE2,0x02,0x0C,0x75,0xCA,0x35,0x29,0xA6,0x49,0x83,0x6D,0x91,0xB4,0xEC,0x31,0x69,
+       0xBA,0x13,0xF3,0xC7,0x21,0x06,0xC8,0x79,0xEF,0xB1,0x9C,0x6A,0xEE,0x64,0x9A,0xDC,0x1E,0xC6,0x18,0x93,0xA9,0x7E,0x89,0x7D,0x96,0xE5,0x44,0xB8,0x00,0x15,0xAF,0x8C,
+       0x78,0x8F,0xA8,0x05,0xA7,0x07,0x25,0x9A,0xC8,0x5D,0x90,0x1A,0x41,0x53,0x30,0xD3,0x24,0x33,0x71,0xB4,0x50,0x6E,0xE4,0xEA,0x0D,0x2B,0x6D,0xF5,0x17,0x08,0x74,0x49,
+       0x71,0xC2,0xAC,0xF7,0xDC,0xB2,0x7E,0xCC,0xB6,0x1B,0xB8,0xA9,0x52,0xCF,0x6B,0x51,0xD2,0x4E,0xC9,0x43,0xEE,0x2E,0x92,0x24,0xBB,0x47,0x4D,0x0C,0x3E,0x21,0x53,0x19,
+       0xD4,0x82,0xE2,0xC6,0x93,0x85,0x0A,0xF8,0xFA,0x04,0x07,0xD3,0x1D,0xEC,0x03,0x66,0xFD,0xB1,0xFB,0x8F,0xC5,0xDE,0xE8,0x29,0xDF,0x23,0x09,0x9D,0x7C,0x43,0x3D,0x4D,
+       0x89,0xB9,0x6F,0xB4,0x6B,0x4A,0x51,0xC3,0x94,0xF4,0x7C,0x5E,0x19,0x87,0x79,0xC1,0x80,0x0C,0x45,0x12,0xEC,0x95,0xF3,0x31,0x68,0x42,0xE1,0x06,0x57,0x0E,0xA7,0xFB,
+       0x78,0x96,0x87,0x23,0xA5,0x20,0x7A,0x09,0x3A,0x45,0xE6,0xD9,0x5E,0x6A,0xD6,0xAA,0x29,0x50,0x92,0x4E,0xD0,0xB5,0x91,0xC2,0x9A,0xCF,0x07,0xFE,0xB2,0x15,0xEB,0xE4,
+       0x84,0x40,0x14,0x47,0xFA,0x93,0xB9,0x06,0x69,0xDB,0xBD,0x4E,0xEA,0x52,0x9B,0xDE,0x5B,0x50,0x36,0xAB,0xB3,0x1F,0xD2,0xCD,0x9C,0x13,0x07,0x7E,0x8B,0xED,0x72,0x62,
+       0x74,0x77,0x3B,0x88,0xAC,0x5B,0x6A,0xBC,0xDA,0x99,0xE8,0x24,0x90,0x5A,0xCA,0x8D,0x5C,0x2B,0xF8,0xF1,0xE1,0x1D,0x94,0x11,0xEA,0xCC,0x02,0x09,0x1E,0xA2,0x48,0x67,
+       0x87,0x5A,0x7E,0xC6,0xCC,0xA3,0xFB,0xC5,0x36,0xEB,0x5C,0xE1,0xAF,0x1E,0xBE,0xE7,0xD8,0x8F,0x70,0xAE,0x42,0x05,0xF5,0xCD,0x2D,0xA2,0xB0,0xFD,0xEF,0x65,0x2C,0x22,
+       0xCB,0x8C,0x8B,0xAA,0x3D,0x86,0xE2,0xCD,0xBE,0xC3,0x42,0x38,0xE3,0x9C,0x08,0xB5,0xAE,0xBD,0x54,0x73,0x83,0x70,0x24,0x47,0xCA,0x4C,0x04,0xC4,0xE0,0x1D,0x40,0xED,
+       0xF4,0x2B,0x50,0x8E,0x97,0xB3,0xF0,0xA6,0x76,0xDB,0x49,0x30,0xE5,0xD9,0x71,0x07,0xB2,0xF1,0x0F,0xD6,0x77,0xAA,0x72,0xC0,0xAF,0x66,0xD8,0x40,0xC6,0x08,0x19,0x8C,
+       0xD9,0x8F,0x5A,0x75,0xAC,0xBE,0xC2,0x40,0x5B,0xBD,0x0D,0x1D,0x00,0xAF,0x26,0x5E,0x78,0x43,0xAA,0xC6,0x4F,0xF3,0xD8,0xE2,0x7F,0x0C,0x1E,0x77,0x4D,0x35,0x96,0x23,
+       0x32,0x44,0x03,0x8D,0x92,0xE7,0xFD,0x48,0x07,0xD0,0x58,0xFC,0x6D,0xC9,0x91,0x33,0xF0,0x23,0x45,0xA4,0x29,0xB9,0xF5,0xB0,0x68,0x8F,0x7B,0x59,0x15,0x8E,0xA6,0x66,
+       0x15,0xA0,0x76,0x9B,0x69,0xCB,0x38,0xA5,0xF4,0xB4,0x6B,0xDC,0x1F,0xAB,0xAE,0x12,0x77,0xC0,0x8C,0x4A,0x03,0xB9,0x73,0xD3,0x6D,0x52,0xC5,0xF5,0x6E,0x4E,0x4B,0xA3,
+       0x24,0x02,0x58,0xEE,0x5F,0xF9,0xD6,0xD0,0x1D,0xBC,0xF4,0xB8,0x4F,0xFD,0x4B,0x2D,0x34,0x77,0x46,0xE5,0xD4,0x33,0x7B,0x9C,0x35,0xCD,0xB0,0x5D,0x06,0x39,0x99,0xEB,
+       0x0C,0xD0,0x0F,0xF7,0x92,0xB5,0x58,0x5B,0x5E,0x79,0x12,0xF4,0x05,0xF6,0x21,0x07,0x0B,0x49,0x1A,0xFB,0xD4,0x98,0xC4,0xEF,0x7A,0xD6,0xCA,0xA1,0xDA,0xB3,0x51,0x00,
+       0x76,0xEC,0x08,0x48,0x40,0x35,0xD7,0x94,0xBE,0xF5,0x7B,0xA4,0x20,0x81,0x5F,0x82,0xF3,0x6F,0x96,0x24,0x98,0xB6,0x49,0x18,0xC8,0xC5,0x8C,0xD2,0x38,0x7F,0xC4,0xF6,
+       0xAA,0x87,0xDC,0x73,0x5B,0xA1,0xAF,0xE5,0x3D,0x37,0x6B,0x85,0xED,0x38,0x62,0x7D,0x57,0xBD,0xCF,0xB5,0x1B,0xA8,0xBB,0x32,0x33,0xD3,0x34,0x5A,0xC1,0x5D,0xFB,0x28,
+       0x6E,0xE1,0x67,0x51,0xBB,0x31,0x92,0x83,0xAC,0xAA,0x72,0x52,0xFD,0x13,0x4F,0x73,0xD3,0xF0,0x5E,0xFC,0xBA,0xB1,0x3C,0x7B,0x08,0x76,0x03,0x38,0x1E,0xD1,0xCC,0x33,
+       0xA3,0x1E,0xFC,0xE0,0x82,0x30,0x27,0x93,0x71,0x35,0x75,0x77,0xBA,0x78,0x10,0x33,0xCD,0xAB,0xCF,0x8E,0xAD,0xF9,0x32,0xC9,0x15,0x9F,0xD6,0x6D,0xA8,0xAE,0xB1,0x3F,
+       0x90,0xEB,0xD4,0xF9,0x31,0x81,0xA3,0x53,0x99,0x4B,0x3C,0x93,0x3B,0xFE,0x55,0xFF,0x25,0x9F,0xCC,0x07,0xC5,0x2C,0x14,0xA7,0xA4,0x1E,0x6C,0xB6,0x91,0x2A,0xE0,0x3E,
+       0x7F,0x39,0x0A,0xD9,0x24,0x3C,0x01,0xA0,0x30,0x99,0x8E,0xB8,0x1D,0xF9,0xA7,0x78,0x86,0x95,0x35,0x0E,0x21,0xDA,0x7A,0x7B,0xAD,0x9F,0x4E,0xF6,0x63,0x5B,0x96,0xBB,
+       0x87,0x36,0x3F,0xA7,0x1A,0x66,0x91,0xCD,0xB0,0x3B,0xC0,0x4F,0x54,0xD2,0x5F,0xBB,0x38,0x89,0x1C,0x79,0x7E,0xA2,0x02,0xE4,0x80,0x84,0x1E,0x33,0xAB,0x74,0xFA,0xBE,
+       0x31,0x46,0x2E,0xC5,0x15,0xB9,0x12,0xE9,0xD3,0x73,0x43,0xEA,0x74,0x11,0xA7,0xC0,0xD5,0xD8,0x39,0x08,0x9F,0x4F,0xC7,0x71,0x25,0x09,0x51,0x65,0xD6,0xA8,0x02,0x1F
+       };
+
+       return random_noise[ (random_noise[p[1] & 1023] + p[0]) & 1023 ] & umod;
+}
+
+// MESH
+// ===========================================================================================================
+
+static void init_mesh( struct mesh *m, float const *tris, u32 length )
+{
+       m->elements = length/3;
+       glGenVertexArrays( 1, &m->vao );
+       glGenBuffers( 1, &m->vbo );
+       
+       glBindVertexArray( m->vao );
+       glBindBuffer( GL_ARRAY_BUFFER, m->vbo );
+       glBufferData( GL_ARRAY_BUFFER, length*sizeof(float), tris, GL_STATIC_DRAW );
+       
+       glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0 );
+       glEnableVertexAttribArray( 0 );
+       
+       VG_CHECK_GL();
+}
+
+static void free_mesh( struct mesh *m )
+{
+       glDeleteVertexArrays( 1, &m->vao );
+       glDeleteBuffers( 1, &m->vbo );
+}
+
+static void draw_mesh( int const start, int const count )
+{
+       glDrawArrays( GL_TRIANGLES, start*3, count*3 );
+}
+
+static void use_mesh( struct mesh *m )
+{
+       glBindVertexArray( m->vao );
+}
+
+
+
+
+
+static struct cell_button *get_wbutton( enum e_world_button btn )
+{
+       return &world.buttons[ btn ];
+}
+
+void leaderboard_set_score( struct cmp_level *cmp_level, u32 score );
+
+// WORLD/MAP
+// ===========================================================================================================
 
 static void map_free(void)
 {      
@@ -310,43 +384,138 @@ static void io_reset(void)
        }
 }
 
-static void map_reclassify( v2i start, v2i end, int update_texbuffer );
-static int map_load( const char *str, const char *name )
+static struct cell *pcell( v2i pos )
 {
-       //TODO: It may be worthwhile, at this point, to switch to binary encoding for save data
-       
-       map_free();
+       return &world.data[ pos[1]*world.w + pos[0] ];
+}
 
-       char const *c = str;
+static void map_reclassify( v2i start, v2i end, int update_texbuffer )
+{
+       v2i full_start = { 1,1 };
+       v2i full_end = { world.w-1, world.h-1 };
        
-       // Scan for width
-       for(;; world.w ++)
+       if( !start || !end )
        {
-               if( str[world.w] == ';' )
-                       break;
-               else if( !str[world.w] )
-               {
-                       vg_error( "Unexpected EOF when parsing level\n" );
-                       return 0;
-               }
+               start = full_start;
+               end = full_end;
        }
        
-       struct cell *row = arraddnptr( world.data, world.w );
-       int cx = 0;
-       int reg_start = 0, reg_end = 0;
-       
-       u32 *links_to_make = NULL;
-       int links_satisfied = 0;
-       
-       char link_id_buffer[32];
-       int link_id_n = 0;
-       
-       for(;;)
-       {
-               if( !*c )
-                       break;
+       // Texture data
+       u8 info_buffer[64*64*4];
+       u32 pixel_id = 0;
        
-               if( *c == '\r' ) { c ++; continue; } // fuck off windows
+       int px0 = vg_max( start[0], full_start[0] ),
+                px1 = vg_min( end[0], full_end[0] ),
+                py0 = vg_max( start[1], full_start[1] ),
+                py1 = vg_min( end[1], full_end[1] );
+
+       for( int y = py0; y < py1; y ++ )
+       {
+               for( int x = px0; x < px1; x ++ )
+               {
+                       struct cell *cell = pcell((v2i){x,y});
+
+                       v2i dirs[] = {{1,0},{0,1},{-1,0},{0,-1}};
+                       
+                       u8 height = 0;
+                       u8 config = 0x00;
+                       
+                       if( cell->state & (FLAG_CANAL|FLAG_INPUT|FLAG_OUTPUT) )
+                       {
+                               for( int i = 0; i < vg_list_size( dirs ); i ++ )
+                               {
+                                       struct cell *neighbour = pcell((v2i){x+dirs[i][0], y+dirs[i][1]});
+                                       if( neighbour->state & (FLAG_CANAL|FLAG_INPUT|FLAG_OUTPUT) )
+                                               config |= 0x1 << i;
+                               }
+                               
+                               height = 128;
+                       } 
+                       else 
+                       {
+                               if( cell->state & FLAG_WALL )
+                                       height = 0xFF-0x3F + hash21i( (v2i){x,y}, 0x3F );
+                               
+                               config = 0xF;
+                       }
+                       
+                       pcell((v2i){x,y})->config = config;
+                       
+                       u8 *info_px = &info_buffer[ (pixel_id ++)*4 ];
+                       info_px[0] = height;
+                       info_px[1] = cell->state & FLAG_WALL? 0: 255;
+                       info_px[2] = 0;
+                       info_px[3] = 0;
+                       
+                       if( 
+                               (
+                                       ((cell->state & FLAG_IS_TRIGGER) && (cell->config == 0xF || cell->config == k_cell_type_split)) || 
+                                       ((cell->state & FLAG_TARGETED) && (cell->config != k_cell_type_split)) 
+                               ) && update_texbuffer
+                       ){
+                               cell->state &= ~(FLAG_TARGETED|FLAG_IS_TRIGGER);
+                               for( u32 i = 0; i < 2; i ++ )
+                               {
+                                       if( cell->links[i] )
+                                       {
+                                               struct cell *other_ptr = &world.data[ cell->links[i] ];
+                                               other_ptr->links[ i ] = 0;
+                                               other_ptr->state &= ~FLAG_IS_TRIGGER;
+                                               
+                                               if( other_ptr->links[ i ^ 0x1 ] == 0 )
+                                                       other_ptr->state &= ~FLAG_TARGETED;
+                                       }
+                               }
+                               
+                               cell->links[0] = 0;
+                               cell->links[1] = 0;
+                       }
+               }
+       }
+       
+       if( update_texbuffer )
+       {
+               glBindTexture( GL_TEXTURE_2D, world.background_data );
+               glTexSubImage2D( GL_TEXTURE_2D, 0, px0 + 16, py0 + 16, px1-px0, py1-py0, GL_RGBA, GL_UNSIGNED_BYTE, info_buffer );
+       }
+}
+
+static int map_load( const char *str, const char *name )
+{
+       //TODO: It may be worthwhile, at this point, to switch to binary encoding for save data
+       
+       map_free();
+
+       char const *c = str;
+       
+       // Scan for width
+       for(;; world.w ++)
+       {
+               if( c[world.w] == ';' )
+                       break;
+               else if( !c[world.w] )
+               {
+                       vg_error( "Unexpected EOF when parsing level\n" );
+                       return 0;
+               }
+       }
+       
+       struct cell *row = arraddnptr( world.data, world.w );
+       int cx = 0;
+       int reg_start = 0, reg_end = 0;
+       
+       u32 *links_to_make = NULL;
+       int links_satisfied = 0;
+       
+       char link_id_buffer[32];
+       int link_id_n = 0;
+
+       for(;;)
+       {
+               if( !*c )
+                       break;
+       
+               if( *c == '\r' ) { c ++; continue; } // fuck off windows
        
                if( *c == ';' )
                {
@@ -366,7 +535,7 @@ static int map_load( const char *str, const char *name )
                                                struct cell_terminal *terminal = &world.io[ reg_start ];
                                                struct terminal_run *run = &terminal->runs[ terminal->run_count-1 ];
 
-                                               if( *c >= 'a' && *c <= 'z' )
+                                               if( (*c >= 'a' && *c <= 'z') || *c == ' ' )
                                                {                                                       
                                                        run->conditions[ run->condition_count ++ ] = *c;
                                                }
@@ -480,7 +649,9 @@ static int map_load( const char *str, const char *name )
                        if( *c == '+' || *c == '-' )
                        {
                                struct cell_terminal *term = arraddnptr( world.io, 1 );
-                               term->id = cx + world.h*world.w;
+                               term->pos[0] = cx;
+                               term->pos[1] = world.h;
+                               
                                term->run_count = 1;
                                term->runs[0].condition_count = 0;
 
@@ -516,13 +687,66 @@ static int map_load( const char *str, const char *name )
        // Update data texture to fill out the background
        {
                u8 info_buffer[64*64*4];
-               for( int i = 0; i < 64*64; i ++ )
+               for( int x = 0; x < 64; x ++ )
+               {
+                       for( int y = 0; y < 64; y ++ )
+                       {
+                               u8 *px = &info_buffer[((x*64)+y)*4];
+                               
+                               px[0] = 0xFF-0x3F + hash21i( (v2i){x,y}, 0x3F );
+                               px[1] = 0;
+                               px[2] = 0;
+                               px[3] = 0;
+                       }
+               }
+
+               // Random walks.. kinda
+               for( int i = 0; i < arrlen(world.io); i ++ )
                {
-                       u8 *px = &info_buffer[i*4];
-                       px[0] = 255;
-                       px[1] = 0;
-                       px[2] = 0;
-                       px[3] = 0;
+                       struct cell_terminal *term = &world.io[ i ];
+                       
+                       v2i turtle;
+                       v2i turtle_dir;
+                       int original_y;
+                       
+                       turtle[0] = 16+term->pos[0];
+                       turtle[1] = 16+term->pos[1];
+                       
+                       turtle_dir[0] = 0;
+                       turtle_dir[1] = pcell(term->pos)->state & FLAG_INPUT? 1: -1;
+                       original_y = turtle_dir[1];
+                       
+                       info_buffer[((turtle[1]*64)+turtle[0])*4] = 0;  
+                       v2i_add( turtle_dir, turtle, turtle );
+                       
+                       for( int i = 0; i < 100; i ++ )
+                       {
+                               info_buffer[((turtle[1]*64)+turtle[0])*4] = 0;
+                               
+                               v2i_add( turtle_dir, turtle, turtle );
+                               
+                               if( turtle[0] == 0 ) break;
+                               if( turtle[0] == 63 ) break;
+                               if( turtle[1] == 0 ) break;
+                               if( turtle[1] == 63 ) break;
+                               
+                               int random_value = hash21i( turtle, 0xFF );
+                               if( random_value > 255-40 && !turtle_dir[0] )
+                               {
+                                       turtle_dir[0] = -1;
+                                       turtle_dir[1] = 0;
+                               }
+                               else if( random_value > 255-80 && !turtle_dir[0] )
+                               {
+                                       turtle_dir[0] = 1;
+                                       turtle_dir[1] = 0;
+                               }
+                               else if( random_value > 255-100 )
+                               {
+                                       turtle_dir[0] = 0;
+                                       turtle_dir[1] = original_y;
+                               }
+                       }
                }
                
                glBindTexture( GL_TEXTURE_2D, world.background_data );
@@ -585,11 +809,6 @@ IL_REG_ERROR:
        return 0;
 }
 
-static struct cell *pcell( v2i pos )
-{
-       return &world.data[ pos[1]*world.w + pos[0] ];
-}
-
 static void map_serialize( FILE *stream )
 {
        for( int y = 0; y < world.h; y ++ )
@@ -617,7 +836,7 @@ static void map_serialize( FILE *stream )
                        for( int i = 0; i < arrlen( world.io ); i ++ )
                        {
                                struct cell_terminal *term = &world.io[i];
-                               if( term->id == y*world.w+x )
+                               if( v2i_eq( term->pos, (v2i){x,y} ) )
                                {
                                        if( terminal_write_count )
                                                fputc( ',', stream );
@@ -654,322 +873,210 @@ static void map_serialize( FILE *stream )
        }
 }
 
-int main( int argc, char *argv[] )
-{
-       vg_init( argc, argv, "Marble Computing | SPACE: Test | LeftClick: Toggle tile | RightClick: Drag wire" );
-}
+// CAREER STATE
+// ===========================================================================================================
 
-static int console_credits( int argc, char const *argv[] )
+#pragma pack(push,1)
+struct dcareer_state
 {
-       vg_info( "Aknowledgements:\n" );
-       vg_info( "  GLFW         zlib/libpng  glfw.org\n" );
-       vg_info( "  miniaudio    MIT0         miniaud.io\n" );
-       vg_info( "  QOI          MIT          phoboslab.org\n" );
-       vg_info( "  STB library  MIT          nothings.org\n" );
-       vg_info( "  Weiholmir font            justfredrik.itch.io\n" );
-       return 0;
-}
+       u32 version;
+       i32 in_map;
+       
+       u32 reserved[14];
 
-static int console_save_map( int argc, char const *argv[] )
-{
-       if( !world.initialzed )
+       struct dlevel_state
        {
-               vg_error( "Tried to save uninitialized map!\n" );
-               return 0;
+               i32 score;
+               i32 unlocked;
+               i32 reserved[2];
        }
+       levels[ NUM_CAMPAIGN_LEVELS ];  
+};
+#pragma pack(pop)
 
-       char map_path[ 256 ];
+static int career_load_success = 0;
 
-       strcpy( map_path, "sav/" );
-       strcat( map_path, world.map_name );
-       strcat( map_path, ".map" );
+static void career_serialize(void)
+{
+       if( !career_load_success )
+               return;
 
-       FILE *test_writer = fopen( map_path, "wb" );
-       if( test_writer )
+       struct dcareer_state encoded;
+       encoded.version = 2;
+       encoded.in_map = world.pCmpLevel? world.pCmpLevel->serial_id: -1;
+       
+       memset( encoded.reserved, 0, sizeof( encoded.reserved ) );
+
+       for( int i = 0; i < vg_list_size( career_serializable ); i ++ )
        {
-               vg_info( "Saving map to '%s'\n", map_path );
-               map_serialize( test_writer );
+               struct serializable_set *set = &career_serializable[i];
                
-               fclose( test_writer );
-               return 1;
+               for( int j = 0; j < set->count; j ++ )
+               {
+                       struct cmp_level *lvl = &set->pack[j];
+                       struct dlevel_state *dest = &encoded.levels[lvl->serial_id];
+                       
+                       dest->score = lvl->completed_score;
+                       dest->unlocked = lvl->unlocked;
+                       dest->reserved[0] = 0;
+                       dest->reserved[1] = 0;
+               }
        }
-       else
+
+       vg_asset_write( "sav/game.sv2", &encoded, sizeof( struct dcareer_state ) );
+}
+
+static void career_unlock_level( struct cmp_level *lvl );
+static void career_unlock_level( struct cmp_level *lvl )
+{
+       lvl->unlocked = 1;
+       
+       if( lvl->linked )
+               career_unlock_level( lvl->linked );
+}
+
+static void career_pass_level( struct cmp_level *lvl, int score, int upload )
+{
+       if( score > 0 )
        {
-               vg_error( "Unable to open stream for writing\n" );
-               return 0;
+               if( score < lvl->completed_score || lvl->completed_score == 0 )
+               {
+                       if( !lvl->is_tutorial && upload )
+                               leaderboard_set_score( lvl, score );
+                       
+                       lvl->completed_score = score;
+               }
+               
+               if( lvl->unlock ) career_unlock_level( lvl->unlock );
        }
 }
 
-static int console_load_map( int argc, char const *argv[] )
+static void career_reset_level( struct cmp_level *lvl )
 {
-       char map_path[ 256 ];
+       lvl->unlocked = 0;
+       lvl->completed_score = 0;
+}
 
-       if( argc >= 1 )
-       {
-               // try from saves
-               strcpy( map_path, "sav/" );
-               strcat( map_path, argv[0] );
-               strcat( map_path, ".map" );
+static void career_load(void)
+{
+       i64 sz;
+       struct dcareer_state encoded;
+
+       // Blank save state
+       memset( (void*)&encoded, 0, sizeof( struct dcareer_state ) );   
+       encoded.in_map = -1;
+       encoded.levels[0].unlocked = 1;
        
-               char *text_source = vg_textasset_read( map_path );
+       // Load and copy data into encoded
+       void *cr = vg_asset_read_s( "sav/game.sv2", &sz );
+       
+       if( cr )
+       {
+               if( sz > sizeof( struct dcareer_state ) )
+                       vg_warn( "This save file is too big! Some levels will be lost\n" );
                
-               if( !text_source )
+               if( sz <= offsetof( struct dcareer_state, levels ) )
                {
-                       strcpy( map_path, "maps/" );
-                       strcat( map_path, argv[0] );
-                       strcat( map_path, ".map" );
-                       
-                       text_source = vg_textasset_read( map_path );
+                       vg_warn( "This save file is too small to have a header. Creating a blank one\n" );
+                       free( cr );
                }
                
-               if( text_source )
+               memcpy( (void*)&encoded, cr, VG_MIN( sizeof( struct dcareer_state ), sz ) );
+               free( cr );
+       }
+       else
+               vg_info( "No save file... Using blank one\n" );
+       
+       // Reset memory
+       for( int i = 0; i < vg_list_size( career_serializable ); i ++ )
+       {
+               struct serializable_set *set = &career_serializable[i];
+               
+               for( int j = 0; j < set->count; j ++ )
+                       career_reset_level( &set->pack[j] );
+       }
+       
+       // Header information
+       // =================================
+       
+       // Decode everything from dstate
+       for( int i = 0; i < vg_list_size( career_serializable ); i ++ )
+       {
+               struct serializable_set *set = &career_serializable[i];
+               
+               for( int j = 0; j < set->count; j ++ )
                {
-                       vg_info( "Loading map: '%s'\n", map_path );
-                       world.ptr_career_level = NULL;
-                       
-                       if( !map_load( text_source, argv[0] ) )
-                       {
-                               free( text_source );
-                               return 0;
-                       }
+                       struct cmp_level *lvl = &set->pack[j];
+                       struct dlevel_state *src = &encoded.levels[lvl->serial_id];
                        
-                       free( text_source );
+                       if( src->unlocked ) career_unlock_level( lvl );
+                       if( src->score ) lvl->completed_score = src->score;
                        
-                       for( int i = 0; i < vg_list_size( level_pack_1 ); i ++ )
+                       // ...
+                       if( lvl->serial_id == encoded.in_map )
                        {
-                               if( !strcmp( level_pack_1[i], argv[0] ) )
-                               {
-                                       world.ptr_career_level = career.levels + i;
-                                       break;
-                               }
+                               if( console_changelevel( 1, &lvl->map_name ) )
+                                       world.pCmpLevel = lvl;
                        }
-                       
-                       return 1;
-               }
-               else
-               {
-                       vg_error( "Missing maps '%s'\n", argv[0] );
-                       return 0;
                }
        }
-       else
-       {
-               vg_error( "Missing argument <map_path>\n" );
-               return 0;
-       }
+       
+       career_load_success = 1;
+}
+
+// MAIN GAMEPLAY
+// ===========================================================================================================
+static int is_simulation_running(void)
+{
+       return world.buttons[ k_world_button_sim ].pressed;
+}
+
+static void clear_animation_flags(void)
+{
+       for( int i = 0; i < world.w*world.h; i ++ )
+               world.data[ i ].state &= ~(FLAG_FLIP_FLOP|FLAG_FLIP_ROTATING);
 }
 
 static void simulation_stop(void)
 {
-       world.simulating = 0;
+       world.buttons[ k_world_button_sim ].pressed = 0;
+       world.buttons[ k_world_button_pause ].pressed = 0;
+       
        world.num_fishes = 0;
        world.sim_frame = 0;
        world.sim_run = 0;
+       world.frame_lerp = 0.0f;
        
        io_reset();
        
        sfx_system_fadeout( &audio_system_balls_rolling, 44100 );
        
-       vg_info( "Stopping simulation!\n" );
-}
-
-static int console_changelevel( int argc, char const *argv[] )
-{
-       if( argc >= 1 )
-       {
-               // Save current level
-               console_save_map( 0, NULL );
-               if( console_load_map( argc, argv ) )
-               {                               
-                       simulation_stop();
-                       return 1;
-               }
-       }
-       else
-       {
-               vg_error( "Missing argument <map_path>\n" );
-       }
+       clear_animation_flags();
        
-       return 0;
+       vg_info( "Stopping simulation!\n" );
 }
 
-void vg_start(void)
+static void simulation_start(void)
 {
-       vg_function_push( (struct vg_cmd){
-               .name = "_map_write",
-               .function = console_save_map
-       });
-       
-       vg_function_push( (struct vg_cmd){
-               .name = "_map_load",
-               .function = console_load_map
-       });
-       
-       vg_function_push( (struct vg_cmd){
-               .name = "map",
-               .function = console_changelevel
-       });
-       
-       vg_function_push( (struct vg_cmd){
-               .name = "credits",
-               .function = console_credits
-       });
-
-       // Quad mesh
-       {
-               float quad_mesh[] =
-               {
-                       0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-                       0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f,
-                       
-                       0.0f, 0.0f, 0.0f, 1.0f, 4.0f, 1.0f,
-                       0.0f, 0.0f, 4.0f, 1.0f, 4.0f, 0.0f
-               };
-               
-               init_mesh( &world.tile, quad_mesh, vg_list_size(quad_mesh) );
-       }
-       
-       // Circle mesh
-       {
-               float circle_mesh[32*6*3];
-               int res = vg_list_size( circle_mesh ) / (6*3);
-
-               for( int i = 0; i < res; i ++ )
-               {
-                       v2f v0 = { sinf( ((float)i/(float)res)*VG_TAUf ), cosf( ((float)i/(float)res)*VG_TAUf ) };
-                       v2f v1 = { sinf( ((float)(i+1)/(float)res)*VG_TAUf ), cosf( ((float)(i+1)/(float)res)*VG_TAUf ) };
-               
-                       circle_mesh[ i*6+0 ] = 0.0f;
-                       circle_mesh[ i*6+1 ] = 0.0f;
-                       
-                       v2_copy( v0, circle_mesh + 32*6 + i*12 );
-                       v2_muls( v0, 0.8f, circle_mesh + 32*6 + i*12+2 );
-                       v2_copy( v1, circle_mesh + 32*6 + i*12+4 );
-                       
-                       v2_copy( v1, circle_mesh + 32*6 + i*12+6 );
-                       v2_muls( v1, 0.8f, circle_mesh + 32*6 + i*12+8 );
-                       v2_muls( v0, 0.8f, circle_mesh + 32*6 + i*12+10 );
-                       
-                       v2_copy( v0, circle_mesh + i*6+4 );
-                       v2_copy( v1, circle_mesh + i*6+2 );
-                       v2_copy( v0, circle_mesh+i*6+4 );
-                       v2_copy( v1, circle_mesh+i*6+2 );
-               }
-               
-               init_mesh( &world.circle, circle_mesh, vg_list_size( circle_mesh ) );
-       }
-       
-       // Numbers mesh
-       {
-               init_mesh( &world.numbers,
-                       MESH_NUMBERS_BUFFER,
-                       vg_list_size( MESH_NUMBERS_BUFFER )
-               );
-               
-               for( int i = 0; i < 10; i ++ )
-               {
-                       vg_info( "offset: %u, length: %u\n", MESH_NUMBERS_OFFSETS[i][0], MESH_NUMBERS_OFFSETS[i][1] );
-               }
-       }
-       
-       // Create wire mesh
-       {
-               int const num_segments = 64;
-       
-               struct mesh_wire *mw = &world.wire;
-       
-               v2f wire_points[ num_segments * 2 ];
-               u16 wire_indices[ 6*(num_segments-1) ];
-               
-               for( int i = 0; i < num_segments; i ++ )
-               {
-                       float l = (float)i / (float)(num_segments-1);
-                       
-                       v2_copy( (v2f){ l, -0.5f }, wire_points[i*2+0] );
-                       v2_copy( (v2f){ l,  0.5f }, wire_points[i*2+1] );
-                       
-                       if( i < num_segments-1 )
-                       {
-                               wire_indices[ i*6+0 ] = i*2 + 0;
-                               wire_indices[ i*6+1 ] = i*2 + 1;
-                               wire_indices[ i*6+2 ] = i*2 + 3;
-                               wire_indices[ i*6+3 ] = i*2 + 0;
-                               wire_indices[ i*6+4 ] = i*2 + 3;
-                               wire_indices[ i*6+5 ] = i*2 + 2;
-                       }
-               }
-               
-               glGenVertexArrays( 1, &mw->vao );
-               glGenBuffers( 1, &mw->vbo );
-               glGenBuffers( 1, &mw->ebo );
-               glBindVertexArray( mw->vao );
-               
-               glBindBuffer( GL_ARRAY_BUFFER, mw->vbo );
-               
-               glBufferData( GL_ARRAY_BUFFER, sizeof( wire_points ), wire_points, GL_STATIC_DRAW );
-               glBindVertexArray( mw->vao );
-               
-               glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mw->ebo );
-               glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( wire_indices ), wire_indices, GL_STATIC_DRAW );
-               
-               // XY
-               glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0 );
-               glEnableVertexAttribArray( 0 );
-               
-               VG_CHECK_GL();
-               
-               mw->em = vg_list_size( wire_indices );
-       }
+       vg_success( "Starting simulation!\n" );
+                               
+       sfx_set_playrnd( &audio_rolls, &audio_system_balls_rolling, 0, 1 );
        
-       // Create info data texture
-       {
-               glGenTextures( 1, &world.background_data );
-               glBindTexture( GL_TEXTURE_2D, world.background_data );
-               glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
-               vg_tex2d_nearest();
-       }
+       world.num_fishes = 0;
+       world.sim_frame = 0;
+       world.sim_run = 0;
        
-       // Create random smaples texture
-       {
-               u8 *data = malloc(512*512*2);
-               for( int i = 0; i < 512*512*2; i ++ )
-                       data[ i ] = rand()/(RAND_MAX/255);
-               
-               glGenTextures( 1, &world.random_samples );
-               glBindTexture( GL_TEXTURE_2D, world.random_samples );
-               glTexImage2D( GL_TEXTURE_2D, 0, GL_RG, 512, 512, 0, GL_RG, GL_UNSIGNED_BYTE, data );
-               vg_tex2d_linear();
-               vg_tex2d_repeat();
-               
-               free( data );
-       }
+       world.sim_delta_speed = 2.5f;
+       world.sim_delta_ref = vg_time;
+       world.sim_internal_ref = 0.0f;
+       world.sim_internal_time = 0.0f;
+       world.pause_offset_target = 0.0f;
        
-       resource_load_main();
+       world.sim_target = 0;
        
-       // Restore gamestate
-       career_load();
-       console_load_map( 1, level_pack_1 );
-}
-
-void vg_free(void)
-{
-       console_save_map( 0, NULL );
-       career_serialize();
-
-       resource_free_main();
-
-       glDeleteTextures( 1, &world.background_data );
-       glDeleteTextures( 1, &world.random_samples );
-
-       glDeleteVertexArrays( 1, &world.wire.vao );
-       glDeleteBuffers( 1, &world.wire.vbo );
-       glDeleteBuffers( 1, &world.wire.ebo );
-
-       free_mesh( &world.tile );
-       free_mesh( &world.circle );
-       free_mesh( &world.numbers );
+       clear_animation_flags();
        
-       map_free();
+       io_reset();
 }
 
 static int world_check_pos_ok( v2i co )
@@ -1062,174 +1169,64 @@ static int cell_interactive( v2i co )
        return 1;
 }
 
-static void map_reclassify( v2i start, v2i end, int update_texbuffer )
+void vg_update(void)
 {
-       v2i full_start = { 1,1 };
-       v2i full_end = { world.w-1, world.h-1 };
+       // Camera
+       // ========================================================================================================
        
-       if( !start || !end )
-       {
-               start = full_start;
-               end = full_end;
-       }
+       float r1 = (float)vg_window_y / (float)vg_window_x,
+                       r2 = (float)world.h / (float)world.w,
+                       size;
        
-       // Texture data
-       u8 info_buffer[64*64*4];
-       u32 pixel_id = 0;
+       size = ( r2 < r1? (float)world.w * 0.5f: ((float)world.h * 0.5f) / r1 ) + 2.5f; 
+       m3x3_projection( m_projection, -size, size, -size*r1, size*r1 );
        
-       int px0 = vg_max( start[0], full_start[0] ),
-                px1 = vg_min( end[0], full_end[0] ),
-                py0 = vg_max( start[1], full_start[1] ),
-                py1 = vg_min( end[1], full_end[1] );
+       v3f origin;
+       origin[0] = floorf( -0.5f * world.w );
+       origin[1] = floorf( -0.5f * world.h );
+       origin[2] = 0.0f;
+       
+       m3x3_identity( m_view );
+       m3x3_translate( m_view, origin );
+       m3x3_mul( m_projection, m_view, vg_pv );
+       vg_projection_update();
+       
+       // Mouse input
+       // ========================================================================================================
+       v2_copy( vg_mouse_ws, world.tile_pos );
+       
+       world.tile_x = floorf( world.tile_pos[0] );
+       world.tile_y = floorf( world.tile_pos[1] );
 
-       for( int y = py0; y < py1; y ++ )
+       // Tilemap
+       // ========================================================================================================
+       if( !is_simulation_running() && !gui_want_mouse() )
        {
-               for( int x = px0; x < px1; x ++ )
+               v2_copy( vg_mouse_ws, world.drag_to_co );
+               
+               if( cell_interactive( (v2i){ world.tile_x, world.tile_y } ))
                {
-                       struct cell *cell = pcell((v2i){x,y});
-
-                       v2i dirs[] = {{1,0},{0,1},{-1,0},{0,-1}};
+                       world.selected = world.tile_y * world.w + world.tile_x;
                        
-                       u8 height = 0;
-                       u8 config = 0x00;
+                       static u32 modify_state = 0;
                        
-                       if( cell->state & (FLAG_CANAL|FLAG_INPUT|FLAG_OUTPUT) )
+                       struct cell *cell_ptr = &world.data[world.selected];
+                       
+                       if( vg_get_button_down("primary") )
+                               modify_state = (cell_ptr->state & FLAG_CANAL) ^ FLAG_CANAL;
+                       
+                       if( vg_get_button("primary") && ((cell_ptr->state & FLAG_CANAL) != modify_state) )
                        {
-                               for( int i = 0; i < vg_list_size( dirs ); i ++ )
+                               cell_ptr->state &= ~FLAG_CANAL;
+                               cell_ptr->state |= modify_state;
+                               
+                               if( cell_ptr->state & FLAG_CANAL )
                                {
-                                       struct cell *neighbour = pcell((v2i){x+dirs[i][0], y+dirs[i][1]});
-                                       if( neighbour->state & (FLAG_CANAL|FLAG_INPUT|FLAG_OUTPUT) )
-                                               config |= 0x1 << i;
-                               }
-                               
-                               height = 128;
-                       } 
-                       else 
-                       {
-                               if( cell->state & FLAG_WALL )
-                                       height = 255;
-                               
-                               config = 0xF;
-                       }
-                       
-                       pcell((v2i){x,y})->config = config;
-                       
-                       u8 *info_px = &info_buffer[ (pixel_id ++)*4 ];
-                       info_px[0] = height;
-                       info_px[1] = cell->state & FLAG_WALL? 0: 255;
-                       info_px[2] = 0;
-                       info_px[3] = 0;
-                       
-                       if( 
-                               (
-                                       ((cell->state & FLAG_IS_TRIGGER) && (cell->config == 0xF || cell->config == k_cell_type_split)) || 
-                                       ((cell->state & FLAG_TARGETED) && (cell->config != k_cell_type_split)) 
-                               ) && update_texbuffer
-                       ){
-                               cell->state &= ~(FLAG_TARGETED|FLAG_IS_TRIGGER);
-                               for( u32 i = 0; i < 2; i ++ )
-                               {
-                                       if( cell->links[i] )
-                                       {
-                                               struct cell *other_ptr = &world.data[ cell->links[i] ];
-                                               other_ptr->links[ i ] = 0;
-                                               other_ptr->state &= ~FLAG_IS_TRIGGER;
-                                               
-                                               if( other_ptr->links[ i ^ 0x1 ] == 0 )
-                                                       other_ptr->state &= ~FLAG_TARGETED;
-                                       }
-                               }
-                               
-                               cell->links[0] = 0;
-                               cell->links[1] = 0;
-                       }
-               }
-       }
-       
-       if( update_texbuffer )
-       {
-               glBindTexture( GL_TEXTURE_2D, world.background_data );
-               glTexSubImage2D( GL_TEXTURE_2D, 0, px0 + 16, py0 + 16, px1-px0, py1-py0, GL_RGBA, GL_UNSIGNED_BYTE, info_buffer );
-       }
-}
-
-
-v2f const curve_3[] = {{0.5f,1.0f},{0.5f,0.625f},{0.625f,0.5f},{1.0f,0.5f}};
-v2f const curve_6[] = {{0.5f,1.0f},{0.5f,0.625f},{0.375f,0.5f},{0.0f,0.5f}};
-v2f const curve_9[] = {{1.0f,0.5f},{0.625f,0.5f},{0.5f,0.375f},{0.5f,0.0f}};
-v2f const curve_12[]= {{0.0f,0.5f},{0.375f,0.5f},{0.5f,0.375f},{0.5f,0.0f}};
-
-v2f const curve_1[] = {{1.0f,0.5f},{0.8f,0.5f},{0.3f,0.5f},{0.2f,0.5f}};
-v2f const curve_4[] = {{0.0f,0.5f},{0.3f,0.5f},{0.5f,0.5f},{0.8f,0.5f}};
-v2f const curve_2[] = {{0.5f,1.0f},{0.5f,0.8f},{0.5f,0.3f},{0.5f,0.2f}};
-v2f const curve_8[] = {{0.5f,0.8f},{0.5f,0.5f},{0.5f,0.3f},{0.5f,0.0f}};
-
-v2f const curve_7[] = {{0.5f,0.8438f},{0.875f,0.8438f},{0.625f,0.5f},{1.0f,0.5f}};
-v2f const curve_7_1[] = {{0.5f,0.8438f},{1.0f-0.875f,0.8438f},{1.0-0.625f,0.5f},{0.0f,0.5f}};
-
-float const curve_7_linear_section = 0.1562f;
-
-u16 id_drag_from = 0;
-v2f drag_from_co;
-v2f drag_to_co;
-
-void vg_update(void)
-{
-       // Fit within screen
-
-       float r1 = (float)vg_window_y / (float)vg_window_x,
-                       r2 = (float)world.h / (float)world.w,
-                       size;
-       
-       size = ( r2 < r1? (float)world.w * 0.5f: ((float)world.h * 0.5f) / r1 ) + 2.5f; 
-       m3x3_projection( m_projection, -size, size, -size*r1, size*r1 );
-       
-       v3f origin;
-       origin[0] = floorf( -0.5f * world.w );
-       origin[1] = floorf( -0.5f * world.h );
-       origin[2] = 0.0f;
-       
-       m3x3_identity( m_view );
-       m3x3_translate( m_view, origin );
-       m3x3_mul( m_projection, m_view, vg_pv );
-       vg_projection_update();
-       
-       // Input stuff
-       v2_copy( vg_mouse_ws, world.tile_pos );
-       
-       world.tile_x = floorf( world.tile_pos[0] );
-       world.tile_y = floorf( world.tile_pos[1] );
-
-       // Tilemap editing
-       if( !world.simulating )
-       {
-               v2_copy( vg_mouse_ws, drag_to_co );
-       
-               if( cell_interactive( (v2i){ world.tile_x, world.tile_y } ))
-               {
-                       world.selected = world.tile_y * world.w + world.tile_x;
-                       
-                       static u32 modify_state = 0;
-                       
-                       struct cell *cell_ptr = &world.data[world.selected];
-                       
-                       if( vg_get_button_down("primary") )
-                       {
-                               modify_state = (cell_ptr->state & FLAG_CANAL) ^ FLAG_CANAL;
-                       }
-                       
-                       if( vg_get_button("primary") && ((cell_ptr->state & FLAG_CANAL) != modify_state) )
-                       {
-                               cell_ptr->state &= ~FLAG_CANAL;
-                               cell_ptr->state |= modify_state;
-                               
-                               if( cell_ptr->state & FLAG_CANAL )
-                               {
-                                       cell_ptr->links[0] = 0;
-                                       cell_ptr->links[1] = 0;
-                                       
-                                       sfx_set_playrnd( &audio_tile_mod, &audio_system_sfx, 3, 6 );
-                                       world.score ++;
+                                       cell_ptr->links[0] = 0;
+                                       cell_ptr->links[1] = 0;
+                                       
+                                       sfx_set_playrnd( &audio_tile_mod, &audio_system_sfx, 3, 6 );
+                                       world.score ++;
                                }
                                else
                                {                                       
@@ -1241,22 +1238,44 @@ void vg_update(void)
                                                                                (v2i){ world.tile_x +2, world.tile_y +2 }, 1 );
                        }
                        
-                       if( vg_get_button_down("secondary") && !(cell_ptr->config == k_cell_type_split) )
+                       if( vg_get_button_down("secondary") && (cell_ptr->state & FLAG_CANAL) && !(cell_ptr->config == k_cell_type_split) )
+                       {
+                               world.id_drag_from = world.selected;
+                       
+                               struct cell_description *desc = &cell_descriptions[ world.data[world.id_drag_from].config ];
+                               v2_add( desc->trigger_pos, (v2f){ world.tile_x, world.tile_y }, world.drag_from_co );
+                       }
+                       
+                       float local_x = vg_mouse_ws[0] - (float)world.tile_x;
+                       
+                       if( vg_get_button_up("secondary") && world.id_drag_from == world.selected )
                        {
-                               id_drag_from = world.selected;
-                               drag_from_co[0] = world.tile_x + 0.5f;
-                               drag_from_co[1] = world.tile_y + 0.5f;
+                               u32 link_id = local_x > 0.5f? 1: 0;
+                               
+                               // break existing connection off
+                               if( cell_ptr->links[ link_id ] )
+                               {
+                                       struct cell *current_connection = &world.data[ cell_ptr->links[ link_id ]];
+                                       
+                                       if( !current_connection->links[ link_id ^ 0x1 ] )
+                                               current_connection->state &= ~FLAG_TARGETED;
+                                       
+                                       current_connection->links[ link_id ] = 0;
+                                       cell_ptr->links[ link_id ] = 0;
+                               }
+                               
+                               cell_ptr->state &= ~FLAG_IS_TRIGGER;
+                               world.id_drag_from = 0;
                        }
                        
-                       if( id_drag_from && (cell_ptr->config == k_cell_type_split) )
+                       if( world.id_drag_from && (cell_ptr->state & FLAG_CANAL) && (cell_ptr->config == k_cell_type_split) )
                        {
-                               float local_x = vg_mouse_ws[0] - (float)world.tile_x;
-                               drag_to_co[0] = (float)world.tile_x + (local_x > 0.5f? 0.75f: 0.25f);
-                               drag_to_co[1] = (float)world.tile_y + 0.25f;
+                               world.drag_to_co[0] = (float)world.tile_x + (local_x > 0.5f? 0.75f: 0.25f);
+                               world.drag_to_co[1] = (float)world.tile_y + 0.25f;
 
                                if( vg_get_button_up("secondary") )
                                {
-                                       struct cell *drag_ptr = &world.data[id_drag_from];
+                                       struct cell *drag_ptr = &world.data[world.id_drag_from];
                                        u32 link_id = local_x > 0.5f? 1: 0;
                                        
                                        // Cleanup existing connections
@@ -1282,62 +1301,48 @@ void vg_update(void)
                                        }
                                        
                                        // Create the new connection
-                                       vg_success( "Creating connection on link %u (%hu)\n", link_id, id_drag_from );
+                                       vg_success( "Creating connection on link %u (%hu)\n", link_id, world.id_drag_from );
                                                
-                                       cell_ptr->links[ link_id ] = id_drag_from;
+                                       cell_ptr->links[ link_id ] = world.id_drag_from;
                                        drag_ptr->links[ link_id ] = world.selected;
                                        
                                        cell_ptr->state |= FLAG_TARGETED;
                                        drag_ptr->state |= FLAG_IS_TRIGGER;
-                                       id_drag_from = 0;
+                                       world.id_drag_from = 0;
                                }
                        }
                }
                else
+               {
                        world.selected = -1;
+               }
                        
-               if( !(vg_get_button("secondary") && id_drag_from) )
-                       id_drag_from = 0;
+               if( !(vg_get_button("secondary") && world.id_drag_from) )
+                       world.id_drag_from = 0;
        }
        else
        {
                world.selected = -1;
-               id_drag_from = 0;
+               world.id_drag_from = 0;
        }
        
-       // Simulation stop/start
-       if( vg_get_button_down("go") )
-       {
-               if( world.simulating )
-               {
-                       simulation_stop();
-               }
-               else
-               {
-                       vg_success( "Starting simulation!\n" );
-                       
-                       sfx_set_playrnd( &audio_rolls, &audio_system_balls_rolling, 0, 1 );
-                       
-                       world.simulating = 1;
-                       world.num_fishes = 0;
-                       world.sim_frame = 0;
-                       world.sim_start = vg_time;
-                       world.sim_run = 0;
-                       
-                       for( int i = 0; i < world.w*world.h; i ++ )
-                               world.data[ i ].state &= ~FLAG_FLIP_FLOP;
-                       
-                       io_reset();
-               }
-       }
-
-       // Fish ticks
-       if( world.simulating )
+       // Marble state updates
+       // ========================================================================================================
+       if( is_simulation_running() )
        {       
-               while( world.sim_frame < (int)((vg_time-world.sim_start)*2.0f) )
+               float old_time = world.sim_internal_time;
+       
+               if( !world.buttons[ k_world_button_pause ].pressed )
+                       world.sim_internal_time = world.sim_internal_ref + (vg_time-world.sim_delta_ref) * world.sim_delta_speed;
+               else
+                       world.sim_internal_time = vg_lerpf( world.sim_internal_time, world.sim_internal_ref + world.pause_offset_target, vg_time_delta*15.0f );
+               world.sim_internal_delta = world.sim_internal_time-old_time;
+               
+               world.sim_target = (int)floorf(world.sim_internal_time);
+               
+               while( world.sim_frame < world.sim_target )
                {
-                       //vg_info( "frame: %u\n", world.sim_frame );
-                       sfx_set_playrnd( &audio_random, &audio_system_balls_switching, 0, 9 );
+                       sfx_set_playrnd( &audio_random, &audio_system_balls_switching, 0, 8 );
 
                        // Update splitter deltas
                        for( int i = 0; i < world.h*world.w; i ++ )
@@ -1361,6 +1366,9 @@ void vg_update(void)
                                if( fish->state == k_fish_state_soon_dead )
                                        fish->state = k_fish_state_dead;
                                
+                               if( fish->state == k_fish_state_soon_alive )
+                                       fish->state = k_fish_state_alive;
+                               
                                if( fish->state < k_fish_state_alive )
                                        continue;
                                
@@ -1375,7 +1383,7 @@ void vg_update(void)
                                                {
                                                        struct cell_terminal *term = &world.io[j];
                                                        
-                                                       if( term->id == fish->pos[1]*world.w + fish->pos[0] )
+                                                       if( v2i_eq( term->pos, fish->pos ) )
                                                        {
                                                                struct terminal_run *run = &term->runs[ world.sim_run ];
                                                                if( run->recv_count < vg_list_size( run->recieved ) )
@@ -1386,93 +1394,101 @@ void vg_update(void)
                                                }
                                                
                                                fish->state = k_fish_state_dead;
+                                               fish->death_time = -1000.0f;
                                                continue;
                                        }
                                        
-                                       if( cell_current->config == k_cell_type_split )
-                                       {
-                                               // Flip flop L/R
-                                               fish->dir[0] = cell_current->state&FLAG_FLIP_FLOP?1:-1;
-                                               fish->dir[1] = 0;
-                                               
-                                               if( !(cell_current->state & FLAG_TARGETED) )
-                                                       cell_current->state ^= FLAG_FLIP_FLOP;
-                                       }
-                                       else if( cell_current->config == k_cell_type_merge )
+
+                                       if( cell_current->config == k_cell_type_merge )
                                        {
                                                // Can only move up
                                                fish->dir[0] = 0;
                                                fish->dir[1] = -1;
+                                               fish->flow_reversed = 0;
                                        }
                                        else
                                        {
-                                               struct cell *cell_next = pcell( (v2i){ fish->pos[0]+fish->dir[0], fish->pos[1]+fish->dir[1] } );
-                                               if( !(cell_next->state & (FLAG_CANAL|FLAG_OUTPUT)) )
+                                               if( cell_current->config == k_cell_type_split )
                                                {
-                                                       // Try other directions for valid, so down, left, right..
-                                                       v2i dirs[] = {{1,0},{-1,0},{0,-1}};
-                                                       //vg_info( "Trying some other directions...\n" );
+                                                       // Flip flop L/R
+                                                       fish->dir[0] = cell_current->state&FLAG_FLIP_FLOP?1:-1;
+                                                       fish->dir[1] = 0;
                                                        
-                                                       for( int j = 0; j < vg_list_size(dirs); j ++ )
-                                                       {
-                                                               if( (dirs[j][0] == -fish->dir[0]) && (dirs[j][1] == -fish->dir[1]) )
-                                                                       continue;
+                                                       if( !(cell_current->state & FLAG_TARGETED) )
+                                                               cell_current->state ^= FLAG_FLIP_FLOP;
+                                               }
+                                               else
+                                               {
+                                                       // Apply cell out-flow
+                                                       struct cell_description *desc = &cell_descriptions[ cell_current->config ];
+                                                       
+                                                       v2i_copy( fish->flow_reversed? desc->start: desc->end, fish->dir );
+                                               }
+                                               
+                                               v2i pos_next;
+                                               v2i_add( fish->pos, fish->dir, pos_next );
+                                               
+                                               struct cell *cell_next = pcell( pos_next );
+                                               
+                                               if( cell_next->state & (FLAG_CANAL|FLAG_OUTPUT) )
+                                               {
+                                                       struct cell_description *desc = &cell_descriptions[ cell_next->config ];
                                                        
-                                                               if( pcell( (v2i){ fish->pos[0]+dirs[j][0], fish->pos[1]+dirs[j][1] } )->state & (FLAG_CANAL|FLAG_OUTPUT) )
+                                                       if( cell_next->config == k_cell_type_merge )
+                                                       {
+                                                               if( fish->dir[0] == 0 )
+                                                               {
+                                                                       fish->state = k_fish_state_dead;
+                                                                       fish->death_time = world.sim_internal_time;
+                                                               }
+                                                               else
+                                                                       fish->flow_reversed = 0;
+                                                       }
+                                                       else
+                                                       {
+                                                               if( cell_next->config == k_cell_type_split )
                                                                {
-                                                                       fish->dir[0] = dirs[j][0];
-                                                                       fish->dir[1] = dirs[j][1];
+                                                                       if( fish->dir[0] == 0 )
+                                                                       {
+                                                                               sfx_set_playrnd( &audio_splitter, &audio_system_balls_important, 0, 1 );
+                                                                               cell_next->state |= FLAG_FLIP_ROTATING;
+                                                                               
+                                                                               fish->flow_reversed = 0;
+                                                                       }
+                                                                       else
+                                                                       {
+                                                                               fish->state = k_fish_state_dead;
+                                                                               fish->death_time = world.sim_internal_time;
+                                                                       }
                                                                }
+                                                               else
+                                                                       fish->flow_reversed = ( fish->dir[0] != -desc->start[0] || 
+                                                                                                                                       fish->dir[1] != -desc->start[1] )? 1: 0;
                                                        }
                                                }
-                                       }
-                                       
-                                       fish->pos[0] += fish->dir[0];
-                                       fish->pos[1] += fish->dir[1];
-                                       
-                                       struct cell *cell_entry = pcell( fish->pos );
-                                       
-                                       if( !(cell_entry->state & (FLAG_INPUT|FLAG_CANAL|FLAG_OUTPUT) ))
-                                       {
-                                               if( world_check_pos_ok( fish->pos ) )
-                                                       fish->state = k_fish_state_bg;
                                                else
-                                                       fish->state = k_fish_state_dead;
-                                       }
-                                       else
-                                       {
-                                               if( fish->dir[0] )
                                                {
-                                                       if( cell_entry->config == k_cell_type_split ||
-                                                                cell_entry->config == k_cell_type_ramp_right ||
-                                                                cell_entry->config == k_cell_type_ramp_left )
+                                                       if( world_check_pos_ok( fish->pos ) )
+                                                               fish->state = k_fish_state_bg;
+                                                       else
                                                        {
-                                                               // Special death (FALL)
-                                                               /*
-                                                               v2_sub( fish->physics_co, fish->physics_v, fish->physics_v );
-                                                               v2_divs( fish->physics_v, vg_time_delta, fish->physics_v );
-                                                               */
-                                                               
                                                                fish->state = k_fish_state_dead;
-                                                               vg_error( "REMOVE THIS CONDITION\n" );
-                                                               continue;
+                                                               fish->death_time = world.sim_internal_time;     
                                                        }
                                                }
-                                       
-                                               if( cell_entry->config == k_cell_type_split )
-                                               {
-                                                       sfx_set_playrnd( &audio_splitter, &audio_system_balls_important, 0, 1 );
-                                                       cell_entry->state |= FLAG_FLIP_ROTATING;
-                                               }
                                        }
+                                       
+                                       //v2i_add( fish->pos, fish->dir, fish->pos );
                                }
                                else if( fish->state == k_fish_state_bg )
                                {
-                                       fish->pos[0] += fish->dir[0];
-                                       fish->pos[1] += fish->dir[1];
+                                       v2i_add( fish->pos, fish->dir, fish->pos );
                                        
                                        if( !world_check_pos_ok( fish->pos ) )
+                                       {
                                                fish->state = k_fish_state_dead;
+                                               fish->death_time = -1000.0f;
+                                       }
                                        else
                                        {
                                                struct cell *cell_entry = pcell( fish->pos );
@@ -1482,10 +1498,13 @@ void vg_update(void)
                                                        if( cell_entry->config == k_cell_type_con_r || cell_entry->config == k_cell_type_con_u 
                                                                || cell_entry->config == k_cell_type_con_l || cell_entry->config == k_cell_type_con_d )
                                                        {
-                                                               fish->state = k_fish_state_alive;
+                                                               sw_set_achievement( "CAN_DO_THAT" );
+                                                       
+                                                               fish->state = k_fish_state_soon_alive;
                                                                
                                                                fish->dir[0] = 0;
                                                                fish->dir[1] = 0;
+                                                               fish->flow_reversed = 1;
                                                                
                                                                switch( cell_entry->config )
                                                                {
@@ -1511,16 +1530,12 @@ void vg_update(void)
                                
                                if( fish->state == k_fish_state_alive )
                                {
+                                       v2i_add( fish->pos, fish->dir, fish->pos );
                                        struct cell *cell_current = pcell( fish->pos );
 
                                        if( cell_current->state & FLAG_IS_TRIGGER )
                                        {
                                                int trigger_id = cell_current->links[0]?0:1;
-                                               int connection_id = cell_current->links[trigger_id];
-                                               int target_px = connection_id % world.w;
-                                               int target_py = (connection_id - target_px)/world.w;
-                                               
-                                               vg_line2( (v2f){ fish->pos[0], fish->pos[1] }, (v2f){ target_px, target_py }, 0xffffffff, 0xffffffff );
                                                
                                                struct cell *target_peice = &world.data[ cell_current->links[trigger_id] ];
                                                
@@ -1535,23 +1550,58 @@ void vg_update(void)
                        }
                        
                        // Third pass (collisions)
+                       struct fish *fi, *fj;
+                       
                        for( int i = 0; i < world.num_fishes; i ++ )
                        {
-                               if( world.fishes[i].state == k_fish_state_alive )
+                               fi = &world.fishes[i];
+                               
+                               if( fi->state == k_fish_state_alive )
                                {
+                                       int continue_again = 0;
+                               
                                        for( int j = i+1; j < world.num_fishes; j ++ )
                                        {
-                                               if( (world.fishes[j].state == k_fish_state_alive) && 
-                                                        (world.fishes[i].pos[0] == world.fishes[j].pos[0]) &&
-                                                        (world.fishes[i].pos[1] == world.fishes[j].pos[1]) )
+                                               fj = &world.fishes[j];
+                                               
+                                               if( (fj->state == k_fish_state_alive) )
                                                {
-                                                       // Shatter death (+0.5s)
-                                                       world.fishes[i].state = k_fish_state_soon_dead;
-                                                       world.fishes[j].state = k_fish_state_soon_dead;
-                                                       world.fishes[i].death_time = 0.5f;
-                                                       world.fishes[j].death_time = 0.5f;
+                                                       v2i fi_prev;
+                                                       v2i fj_prev;
+                                                       
+                                                       v2i_sub( fi->pos, fi->dir, fi_prev );
+                                                       v2i_sub( fj->pos, fj->dir, fj_prev );
+                                               
+                                                       int 
+                                                       collide_next_frame = ( 
+                                                                (fi->pos[0] == fj->pos[0]) &&
+                                                                (fi->pos[1] == fj->pos[1]))? 1: 0,
+                                                       collide_this_frame = (
+                                                                (fi_prev[0] == fj->pos[0]) &&
+                                                                (fi_prev[1] == fj->pos[1]) &&
+                                                                (fj_prev[0] == fi->pos[0]) &&
+                                                                (fj_prev[1] == fi->pos[1])
+                                                               )? 1: 0;
+                                                       
+                                                       if( collide_next_frame || collide_this_frame )
+                                                       {
+                                                               sw_set_achievement( "BANG" );
+                                                       
+                                                               // Shatter death (+0.5s)
+                                                               float death_time = world.sim_internal_time + ( collide_this_frame? 0.0f: 0.5f );
+                                                               
+                                                               fi->state = k_fish_state_soon_dead;
+                                                               fj->state = k_fish_state_soon_dead;
+                                                               fi->death_time = death_time;
+                                                               fj->death_time = death_time;
+                                                               
+                                                               continue_again = 1;
+                                                               break;
+                                                       }
                                                }
                                        }
+                                       if( continue_again )
+                                               continue;
                                }
                        }
                        
@@ -1559,36 +1609,34 @@ void vg_update(void)
                        for( int i = 0; i < arrlen( world.io ); i ++ )
                        {
                                struct cell_terminal *term = &world.io[ i ];
-                               int posx = term->id % world.w;
-                               int posy = (term->id - posx)/world.w;
-                               int is_input = world.data[ term->id ].state & FLAG_INPUT;
+                               int is_input = pcell(term->pos)->state & FLAG_INPUT;
                                
                                if( is_input )
                                {
                                        if( world.sim_frame < term->runs[ world.sim_run ].condition_count )
                                        {
-                                               struct fish *fish = &world.fishes[world.num_fishes++];
-                                               fish->pos[0] = posx;
-                                               fish->pos[1] = posy;
-                                               fish->state = k_fish_state_alive;
-                                               fish->payload = term->runs[ world.sim_run ].conditions[ world.sim_frame ];
+                                               char emit = term->runs[ world.sim_run ].conditions[ world.sim_frame ];
+                                               if( emit == ' ' )
+                                                       continue;
+                                       
+                                               struct fish *fish = &world.fishes[ world.num_fishes ];
+                                               v2i_copy( term->pos, fish->pos );
                                                
-                                               int can_spawn = 0;
+                                               fish->state = k_fish_state_alive;
+                                               fish->payload = emit;
                                                
-                                               v2i dirs[] = {{1,0},{-1,0},{0,-1}};
-                                               for( int j = 0; j < vg_list_size(dirs); j ++ )
-                                                       if( pcell( (v2i){ posx+dirs[j][0], posy+dirs[j][1] } )->state & FLAG_CANAL )
-                                                       {
-                                                               fish->dir[0] = dirs[j][0];
-                                                               fish->dir[1] = dirs[j][1];
-                                                               can_spawn = 1;
-                                                               break;
-                                                       }
+                                               struct cell *cell_ptr = pcell( fish->pos );
                                                
-                                               if( !can_spawn )
-                                                       world.num_fishes--;
-                                               else
+                                               if( cell_ptr->config != k_cell_type_stub )
+                                               {
+                                                       struct cell_description *desc = &cell_descriptions[ cell_ptr->config ];
+                                                       
+                                                       v2i_copy( desc->start, fish->dir );
+                                                       fish->flow_reversed = 1;
+                                                       
+                                                       world.num_fishes ++;
                                                        alive_count ++;
+                                               }
                                        }
                                }
                        }
@@ -1600,7 +1648,7 @@ void vg_update(void)
                                for( int i = 0; i < arrlen( world.io ); i ++ )
                                {
                                        struct cell_terminal *term = &world.io[ i ];
-                                       int is_input = world.data[ term->id ].state & FLAG_INPUT;
+                                       int is_input = pcell(term->pos)->state & FLAG_INPUT;
                                        
                                        if( !is_input )
                                        {
@@ -1632,8 +1680,23 @@ void vg_update(void)
                                                vg_success( "Run passed, starting next\n" );
                                                world.sim_run ++;
                                                world.sim_frame = 0;
-                                               world.sim_start = vg_time;
+                                               world.sim_target = 0;
                                                world.num_fishes = 0;
+                                               
+                                               // Reset timing reference points
+                                               world.sim_delta_ref = vg_time;
+                                               world.sim_internal_ref = 0.0f;
+                                               
+                                               if( world.buttons[ k_world_button_pause ].pressed )
+                                                       world.pause_offset_target = 0.5f;
+                                               else
+                                                       world.pause_offset_target = 0.0f;
+                                               
+                                               world.sim_internal_time = 0.0f;
+                                               
+                                               for( int i = 0; i < world.w*world.h; i ++ )
+                                                       world.data[ i ].state &= ~FLAG_FLIP_FLOP;
+                                               
                                                continue;
                                        }
                                        else
@@ -1647,33 +1710,34 @@ void vg_update(void)
                                                
                                                world.score = score;
                                                world.time = world.sim_frame;
+                                               
+                                               // Copy into career data
+                                               if( world.pCmpLevel )
+                                               {
+                                                       career_pass_level( world.pCmpLevel, world.score, 1 );
+                                               }
                                        }
                                }
                                else
                                {
+                                       if( world.sim_run > 0 )
+                                               sw_set_achievement( "GOOD_ENOUGH" );
+                                       
                                        vg_error( "Level failed :(\n" );
                                }
                                
-                               // Copy into career data
-                               if( world.ptr_career_level )
-                               {
-                                       world.ptr_career_level->score = world.score;
-                                       world.ptr_career_level->time = world.time;
-                                       world.ptr_career_level->completed = world.completed;
-                               }
-                               
-                               simulation_stop(); // TODO: Async?
+                               simulation_stop();
                                break;
                        }
                        
                        world.sim_frame ++;
                }
                
-               float scaled_time = 0.0f;
-               scaled_time = (vg_time-world.sim_start)*2.0f;
-               world.frame_lerp = scaled_time - (float)world.sim_frame;
+               // Position update
+               // =====================================================================================================
+               
+               world.frame_lerp = world.sim_internal_time - floorf( world.sim_internal_time );
                
-               // Update positions
                for( int i = 0; i < world.num_fishes; i ++ )
                {
                        struct fish *fish = &world.fishes[i];
@@ -1681,37 +1745,32 @@ void vg_update(void)
                        if( fish->state == k_fish_state_dead )
                                continue;
                        
-                       if( fish->state == k_fish_state_soon_dead && (world.frame_lerp > fish->death_time) )
+                       if( fish->state == k_fish_state_soon_dead && (world.sim_internal_time > fish->death_time) )
                                continue; // Todo: particle thing?
                                
                        struct cell *cell = pcell(fish->pos);
+                       struct cell_description *desc = &cell_descriptions[ cell->config ];
+                       
                        v2f const *curve;
                        
                        float t = world.frame_lerp;
-                       float ti = 1.0f-t;
-                       
+                       if( fish->flow_reversed && !desc->is_linear )
+                               t = 1.0f-t;
+
                        v2_copy( fish->physics_co, fish->physics_v );
                        
                        switch( cell->config )
                        {
-                               case 13:
+                               case k_cell_type_merge:
                                        if( fish->dir[0] == 1 )
                                                curve = curve_12;
                                        else
                                                curve = curve_9;
                                break;
-                               case k_cell_type_con_r: curve = curve_1; 
-                                       if( fish->dir[0] == 1 ) t = ti;
-                               break;
-                               case k_cell_type_con_l: curve = curve_4; 
-                                       if( fish->dir[0] == -1 ) t = ti;
-                               break;
-                               case k_cell_type_con_u: curve = curve_2; 
-                                       if( fish->dir[1] == 1 ) t = ti;
-                               break;
-                               case k_cell_type_con_d: curve = curve_8; 
-                                       if( fish->dir[1] == 1 ) t = ti;
-                               break;
+                               case k_cell_type_con_r: curve = curve_1; break;
+                               case k_cell_type_con_l: curve = curve_4; break;
+                               case k_cell_type_con_u: curve = curve_2; break;
+                               case k_cell_type_con_d: curve = curve_8; break;
                                case 3: curve = curve_3; break;
                                case 6: curve = curve_6; break;
                                case 9: curve = curve_9; break;
@@ -1752,10 +1811,16 @@ void vg_update(void)
                                fish->physics_co[0] = origin[0] + (float)fish->dir[0]*t;
                                fish->physics_co[1] = origin[1] + (float)fish->dir[1]*t;
                        }
+                       
+                       v2_sub( fish->physics_co, fish->physics_v, fish->physics_v );
+                       v2_divs( fish->physics_v, world.sim_internal_delta, fish->physics_v );
                }
        }
 }
 
+void leaderboard_found( LeaderboardFindResult_t *pCallback );
+void leaderboard_downloaded( LeaderboardScoresDownloaded_t *pCallback );
+
 static void render_tiles( v2i start, v2i end, v4f const regular_colour, v4f const selected_colour )
 {
        v2i full_start = { 0,0 };
@@ -1805,6 +1870,7 @@ static void render_tiles( v2i start, v2i end, v4f const regular_colour, v4f cons
        }
 }
 
+/*
 static void draw_numbers( v3f coord, int number )
 {
        v3f pos;
@@ -1823,41 +1889,143 @@ static void draw_numbers( v3f coord, int number )
                draw_mesh( MESH_NUMBERS_OFFSETS[digits[i-j-1]][0], MESH_NUMBERS_OFFSETS[digits[i-j-1]][1] );
                pos[0] += pos[2] * 0.75f;
        }
-}
+}*/
 
-void vg_render(void)
+static void wbutton_run( enum e_world_button btn_name )
 {
-       glViewport( 0,0, vg_window_x, vg_window_y );
-
-       glDisable( GL_DEPTH_TEST );
-       glClearColor( 0.369768f, 0.3654f, 0.42f, 1.0f );
-       glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
-       
-       v4f const colour_default = {1.0f, 1.0f, 1.0f, 1.0f};
-       v4f const colour_selected = {0.90f, 0.92f, 1.0f, 1.0f};
-
-       // TILE SET RENDERING 
-       //      todo: just slam everything into a mesh...
-       //          when user modifies a tile the neighbours can be easily uploaded to gpu mem
-       //          in ~3 subBuffers
-       //          Currently we're uploading a fair amount of data every frame anyway.
-       //          NOTE: this is for final optimisations ONLY!
-       // ======================================================================
+       static v3f button_colours[] = {
+               {0.204f, 0.345f, 0.553f},
+               {0.204f, 0.345f, 0.553f},
+               {0.741f, 0.513f, 0.078f},
+               {1.0f, 0.0f, 0.0f}
+       };
 
-       use_mesh( &world.tile );
-       
-       // Draw background
+       struct cell_button *btn = &world.buttons[btn_name];
        
-       if(1){
+       // Interaction
        
-       SHADER_USE( shader_background );
-       glUniformMatrix3fv( SHADER_UNIFORM( shader_background, "uPv" ), 1, GL_FALSE, (float *)vg_pv );
-       
-       glActiveTexture( GL_TEXTURE0 );
-       glBindTexture( GL_TEXTURE_2D, world.background_data );
-       glUniform1i( SHADER_UNIFORM( shader_background, "uTexMain" ), 0 );
-       
-       glUniform3f( SHADER_UNIFORM( shader_background, "uOffset" ), -16, -16, 64 );
+       int is_hovering = (world.tile_x == world.w-1 && world.tile_y == world.h-btn_name-2)?1:0;        
+       if( vg_get_button_up( "primary" ) && is_hovering )
+       {
+               // Click event
+               if( btn_name == k_world_button_sim )
+               {
+                       if( world.buttons[ k_world_button_pause ].pressed )
+                       {
+                               if( !btn->pressed )
+                               {
+                                       btn->pressed = 1;
+                                       simulation_start();
+                                       
+                                       world.pause_offset_target = 0.5f;
+                               }
+                               else
+                                       world.pause_offset_target += 1.0f;
+                       }
+                       else
+                       {
+                               btn->pressed ^= 0x1;
+                               
+                               if( btn->pressed )
+                                       simulation_start();
+                               else
+                                       simulation_stop();
+                       }
+               }
+               else if( btn_name == k_world_button_pause )
+               {
+                       btn->pressed ^= 0x1;
+               
+                       world.sim_internal_ref = world.sim_internal_time;
+                       world.sim_delta_ref = vg_time;
+                       
+                       if( btn->pressed )
+                       {
+                               float time_frac = world.sim_internal_time-floorf(world.sim_internal_time);
+                               world.pause_offset_target = 0.5f - time_frac;
+                       }
+                       else
+                               world.pause_offset_target = 0.0f;
+               }
+               else
+               {
+                       btn->pressed ^= 0x1;
+               }
+               
+               sfx_set_play( &audio_clicks, &audio_system_ui, btn->pressed?1:0 );
+       }
+       
+       // Drawing
+       if( btn->pressed ) 
+       {
+               if( is_hovering )
+               {
+                       btn->light_target = 0.9f;
+               }
+               else
+               {
+                       if( btn_name == k_world_button_sim && world.buttons[ k_world_button_pause ].pressed )
+                               btn->light_target = fabsf(sinf( vg_time * 2.0f )) * 0.3f + 0.3f;
+                       else
+                               btn->light_target = 0.8f;
+               }
+       }
+       else 
+       {
+               btn->light_target = is_hovering? 0.2f: 0.0f;
+       }
+
+       if( vg_get_button( "primary" ) && is_hovering )
+               btn->light_target = 1.0f;
+       
+       btn->light = vg_lerpf( btn->light, btn->light_target, vg_time_delta*26.0f );
+       
+       // Draw
+       
+       v4f final_colour;
+       v3_copy( button_colours[ btn_name ], final_colour );
+       final_colour[3] = btn->light;
+       
+       glUniform4f( SHADER_UNIFORM( shader_buttons, "uOffset" ), 
+               world.w-1, 
+               world.h-btn_name-2, 
+               (float)btn_name, 
+               3.0f 
+       );
+       glUniform4fv( SHADER_UNIFORM( shader_buttons, "uColour" ), 1, final_colour );
+       
+       draw_mesh( 0, 2 );
+}
+
+void vg_render(void)
+{
+       glViewport( 0,0, vg_window_x, vg_window_y );
+
+       glDisable( GL_DEPTH_TEST );
+       glClearColor( 0.369768f, 0.3654f, 0.42f, 1.0f );
+       glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
+       
+       v4f const colour_default = {1.0f, 1.0f, 1.0f, 1.0f};
+       v4f const colour_selected = {0.90f, 0.92f, 1.0f, 1.0f};
+
+       int const circle_base = 6;
+       int const filled_start = circle_base+0;
+       int const filled_count = circle_base+32;
+       int const empty_start = circle_base+32;
+       int const empty_count = circle_base+32*2;
+       
+       // BACKGROUND
+       // ========================================================================================================
+       use_mesh( &world.shapes );
+       
+       SHADER_USE( shader_background );
+       glUniformMatrix3fv( SHADER_UNIFORM( shader_background, "uPv" ), 1, GL_FALSE, (float *)vg_pv );
+       
+       glActiveTexture( GL_TEXTURE0 );
+       glBindTexture( GL_TEXTURE_2D, world.background_data );
+       glUniform1i( SHADER_UNIFORM( shader_background, "uTexMain" ), 0 );
+       
+       glUniform3f( SHADER_UNIFORM( shader_background, "uOffset" ), -16, -16, 64 );
        glUniform1f( SHADER_UNIFORM( shader_background, "uVariance" ), 0.02f );
        
        glActiveTexture( GL_TEXTURE1 );
@@ -1865,10 +2033,10 @@ void vg_render(void)
        glUniform1i( SHADER_UNIFORM( shader_background, "uSamplerNoise" ), 1 );
        
        draw_mesh( 0, 2 );
-
-       }
-       
        
+       // TILESET BACKGROUND LAYER
+       // ========================================================================================================
+       use_mesh( &world.shapes );
        SHADER_USE( shader_tile_main );
 
        m2x2f subtransform;
@@ -1891,36 +2059,54 @@ void vg_render(void)
        
        render_tiles( NULL, NULL, colour_default, colour_default );
        
-
-       
+       // MARBLES
+       // ========================================================================================================
        SHADER_USE( shader_ball );
        glUniformMatrix3fv( SHADER_UNIFORM( shader_ball, "uPv" ), 1, GL_FALSE, (float *)vg_pv );
        
-       vg_tex2d_bind( &tex_ball, 0 );
+       vg_tex2d_bind( &tex_ball_noise, 0 );
        glUniform1i( SHADER_UNIFORM( shader_ball, "uTexMain" ), 0 );
        
-       // Draw 'fish'
-       if( world.simulating )
+       if( get_wbutton( k_world_button_sim )->pressed )
        {
                for( int i = 0; i < world.num_fishes; i ++ )
                {
                        struct fish *fish = &world.fishes[i];
+                       v3f render_pos;
+                       render_pos[2] = 1.0f;
                        
-                       if( fish->state == k_fish_state_dead || fish->state == k_fish_state_bg )
+                       if( fish->state == k_fish_state_dead || fish->state == k_fish_state_soon_dead )
+                       {
+                               float death_anim_time = world.sim_internal_time - fish->death_time;
+                               
+                               // Death animation
+                               if( death_anim_time > 0.0f && death_anim_time < 1.0f )
+                               {
+                                       float amt = 1.0f-death_anim_time*death_anim_time;
+                               
+                                       v2_muladds( fish->physics_co, fish->physics_v, -1.0f * world.sim_internal_delta * amt, fish->physics_co );
+                                       render_pos[2] = amt;
+                               }
+                               else if( world.sim_internal_time > fish->death_time )
+                                       continue;
+                       }
+                       else if( fish->state == k_fish_state_bg )
                                continue;
                        
-                       if( fish->state == k_fish_state_soon_dead && (world.frame_lerp > fish->death_time) )
-                               continue;
+                       v2_copy( fish->physics_co, render_pos );
                        
                        v4f dot_colour = { 0.0f, 0.0f, 0.0f, 1.0f };
                        colour_code_v3( fish->payload, dot_colour );
                        
                        glUniform3fv( SHADER_UNIFORM( shader_ball, "uColour" ), 1, dot_colour );
-                       glUniform2fv( SHADER_UNIFORM( shader_ball, "uOffset" ), 1, fish->physics_co );
-                       draw_mesh( 0, 32 );
+                       glUniform3fv( SHADER_UNIFORM( shader_ball, "uOffset" ), 1, render_pos );
+                       glUniform2f( SHADER_UNIFORM( shader_ball, "uTexOffset" ), (float)i * 1.2334, (float)i * -0.3579f );
+                       draw_mesh( 0, 2 );
                }
        }
        
+       // TILESET FOREGROUND LAYER
+       // ========================================================================================================
        SHADER_USE( shader_tile_main );
 
        // Bind textures
@@ -1967,15 +2153,21 @@ void vg_render(void)
                                        m2x2_create_rotation( subtransform, rotation );
 
                                        glUniformMatrix2fv( SHADER_UNIFORM( shader_tile_main, "uSubTransform" ), 1, GL_FALSE, (float *)subtransform );  
-                                       glUniform4f( SHADER_UNIFORM( shader_tile_main, "uOffset" ), (float)x, (float)y + 0.125f, cell->state & FLAG_TARGETED? 3.0f: 0.0f, 0.0f );
+                                       glUniform4f( SHADER_UNIFORM( shader_tile_main, "uOffset" ), 
+                                               (float)x, 
+                                               (float)y + 0.125f, 
+                                               cell->state & FLAG_TARGETED? 3.0f: 0.0f, 
+                                               0.0f 
+                                       );
                                        draw_mesh( 0, 2 );
                                }
                        }
                }
        }
        
-       // Edit overlay
-       if( world.selected != -1 && !(world.data[ world.selected ].state & FLAG_CANAL) && !id_drag_from )
+       // EDIT OVERLAY
+       // ========================================================================================================
+       if( world.selected != -1 && !(world.data[ world.selected ].state & FLAG_CANAL) && !world.id_drag_from )
        {
                v2i new_begin = { world.tile_x - 2, world.tile_y - 2 };
                v2i new_end = { world.tile_x + 2, world.tile_y + 2 };
@@ -1994,27 +2186,47 @@ void vg_render(void)
                map_reclassify( new_begin, new_end, 0 );
        }
        
-       //glDisable(GL_BLEND);
+       // BUTTONS
+       // ========================================================================================================
+       SHADER_USE( shader_buttons );
+       glUniformMatrix3fv( SHADER_UNIFORM( shader_buttons, "uPv" ), 1, GL_FALSE, (float *)vg_pv );
        
-       // Draw connecting wires
-       glDisable(GL_BLEND);
+       vg_tex2d_bind( &tex_buttons, 0 );
+       glUniform1i( SHADER_UNIFORM( shader_buttons, "uTexMain" ), 0 );
+       
+       wbutton_run( k_world_button_sim );
+       wbutton_run( k_world_button_pause );
+       //wbutton_run( k_world_button_wire_mode );
+       
+       // WIRES
+       // ========================================================================================================
+       //glDisable(GL_BLEND);
 
        SHADER_USE( shader_wire );
        glBindVertexArray( world.wire.vao );
 
        glUniformMatrix3fv( SHADER_UNIFORM( shader_wire, "uPv" ), 1, GL_FALSE, (float *)vg_pv );
-       glUniform4f( SHADER_UNIFORM( shader_wire, "uColour" ), 0.2f, 0.2f, 0.2f, 1.0f );
        
-       if( id_drag_from )
+       v4f const wire_left_colour = { 0.5f, 0.5f, 0.5f, 1.0f };
+       v4f const wire_right_colour = { 0.2f, 0.2f, 0.2f, 1.0f };
+       v4f const wire_drag_colour = { 0.2f, 0.2f, 0.2f, 0.6f };
+       
+       glUniform1f( SHADER_UNIFORM( shader_wire, "uTime" ), world.frame_lerp );
+       glUniform1f( SHADER_UNIFORM( shader_wire, "uGlow" ), 0.0f );
+       
+       if( world.id_drag_from )
        {
+               glUniform4fv( SHADER_UNIFORM( shader_wire, "uColour" ), 1, wire_drag_colour );
                glUniform1f( SHADER_UNIFORM( shader_wire, "uCurve" ), 0.4f );
-               glUniform3f( SHADER_UNIFORM( shader_wire, "uStart" ), drag_from_co[0], drag_from_co[1], 0.06f );
-               glUniform3f( SHADER_UNIFORM( shader_wire, "uEnd" ), drag_to_co[0], drag_to_co[1], 0.06f );
+               glUniform3f( SHADER_UNIFORM( shader_wire, "uStart" ), world.drag_from_co[0], world.drag_from_co[1], 0.20f );
+               glUniform3f( SHADER_UNIFORM( shader_wire, "uEnd" ), world.drag_to_co[0], world.drag_to_co[1], 0.20f );
                glDrawElements( GL_TRIANGLES, world.wire.em, GL_UNSIGNED_SHORT, (void*)(0) );
        }
        
+       // Pulling animation
        float rp_x1 = world.frame_lerp*9.0f;
-       float rp_x2 = 1.0f-rp_x1*expf(1.0f-rp_x1)* 0.36f;
+       float rp_xa = rp_x1*expf(1.0f-rp_x1)* 0.36f;
+       float rp_x2 = 1.0f-rp_xa;
        
        for( int y = 2; y < world.h-2; y ++ )
        {
@@ -2026,6 +2238,8 @@ void vg_render(void)
                        {
                                if( cell->state & FLAG_IS_TRIGGER )
                                {
+                                       struct cell_description *desc = &cell_descriptions[ cell->config ];
+                               
                                        int trigger_id = cell->links[0]?0:1;
                                        
                                        int x2 = cell->links[trigger_id] % world.w;
@@ -2037,59 +2251,171 @@ void vg_render(void)
                                        startpoint[0] = (float)x2 + (trigger_id? 0.75f: 0.25f);
                                        startpoint[1] = (float)y2 + 0.25f;
                                        
-                                       endpoint[0] = x+0.5f;
-                                       endpoint[1] = y+0.5f;
+                                       endpoint[0] = x;
+                                       endpoint[1] = y;
                                        
+                                       v2_add( desc->trigger_pos, endpoint, endpoint );
+                                       
+                                       glUniform4fv( SHADER_UNIFORM( shader_wire, "uColour" ), 1, trigger_id? wire_right_colour: wire_left_colour );
                                        glUniform1f( SHADER_UNIFORM( shader_wire, "uCurve" ), cell->state & FLAG_TRIGGERED? rp_x2 * 0.4f: 0.4f );
-                                       glUniform3f( SHADER_UNIFORM( shader_wire, "uStart" ), startpoint[0], startpoint[1], 0.04f );
-                                       glUniform3f( SHADER_UNIFORM( shader_wire, "uEnd" ), endpoint[0], endpoint[1], 0.04f );
+                                       glUniform1f( SHADER_UNIFORM( shader_wire, "uGlow" ), cell->state & FLAG_TRIGGERED? rp_xa: 0.0f );
+                                       glUniform3f( SHADER_UNIFORM( shader_wire, "uStart" ), startpoint[0], startpoint[1], 0.18f );
+                                       glUniform3f( SHADER_UNIFORM( shader_wire, "uEnd" ), endpoint[0], endpoint[1], 0.18f );
                                        glDrawElements( GL_TRIANGLES, world.wire.em, GL_UNSIGNED_SHORT, (void*)(0) );
                                }
                        }
                }
        }
-
+       
+       // WIRE ENDPOINTS
+       // ========================================================================================================
+       
        SHADER_USE( shader_tile_colour );
        glUniformMatrix3fv( SHADER_UNIFORM( shader_tile_colour, "uPv" ), 1, GL_FALSE, (float *)vg_pv );
-       use_mesh( &world.circle );
+       use_mesh( &world.shapes );
+       
+       for( int y = 2; y < world.h-2; y ++ )
+       {
+               for( int x = 2; x < world.w-2; x ++ )
+               {
+                       struct cell *cell = pcell((v2i){x,y});
+
+                       if( cell->state & FLAG_CANAL )
+                       {
+                               if( cell->state & FLAG_IS_TRIGGER )
+                               {
+                                       struct cell_description *desc = &cell_descriptions[ cell->config ];
+                               
+                                       int trigger_id = cell->links[0]?0:1;
+                                       
+                                       int x2 = cell->links[trigger_id] % world.w;
+                                       int y2 = (cell->links[trigger_id] - x2) / world.w;
+                                       
+                                       v2f pts[2];
+                                       
+                                       pts[0][0] = (float)x2 + (trigger_id? 0.75f: 0.25f);
+                                       pts[0][1] = (float)y2 + 0.25f;
+                                       
+                                       pts[1][0] = x;
+                                       pts[1][1] = y;
+                                       
+                                       v2_add( desc->trigger_pos, pts[1], pts[1] );
+                                       
+                                       glUniform4fv( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 
+                                                       1, trigger_id? wire_right_colour: wire_left_colour );
+                                       
+                                       for( int i = 0; i < 2; i ++ )
+                                       {
+                                               glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), 
+                                                       pts[i][0],
+                                                       pts[i][1], 
+                                                       0.08f 
+                                               );
+                                               draw_mesh( filled_start, filled_count );        
+                                       }
+                               }
+                       }
+               }
+       }
+       
+       // SUB SPLITTER DIRECTION
+       // ========================================================================================================
+       
+       glUniform4f( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 0.9f, 0.35f, 0.1f, 0.75f );
+       
+       for( int y = 2; y < world.h-2; y ++ )
+       {
+               for( int x = 2; x < world.w-2; x ++ )
+               {
+                       struct cell *cell = pcell((v2i){x,y});
 
-       int const filled_start = 0;
-       int const filled_count = 32;
-       int const empty_start = 32;
-       int const empty_count = 32*2;
+                       if( cell->state & FLAG_CANAL && cell->state & FLAG_TARGETED && cell->config == k_cell_type_split )
+                       {
+                               glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), x, y, 1.0f );
+                               draw_mesh( cell->state & FLAG_FLIP_FLOP? 5: 4, 1 );
+                       }
+               }
+       }
+       
+       // I/O ARRAYS
+       // ========================================================================================================
+       
+       //glEnable(GL_BLEND);
        
-       // Draw i/o arrays
        for( int i = 0; i < arrlen( world.io ); i ++ )
        {
                struct cell_terminal *term = &world.io[ i ];
-               int posx = term->id % world.w;
-               int posy = (term->id - posx)/world.w;
-               int is_input = world.data[ term->id ].state & FLAG_INPUT;
+               int is_input = pcell(term->pos)->state & FLAG_INPUT;
 
                v4f dot_colour = { 0.0f, 0.0f, 0.0f, 1.0f };
                
                for( int k = 0; k < term->run_count; k ++ )
                {
-                       for( int j = 0; j < term->runs[k].condition_count; j ++ )
+                       float arr_base   = is_input? 1.2f: -0.2f, 
+                                       run_offset = (is_input? 0.2f: -0.2f) * (float)k, 
+                                       y_position = is_input? 
+                                               (arr_base + (float)term->pos[1] + (float)(term->run_count-1)*0.2f) - run_offset:
+                                               (float)term->pos[1] + arr_base + run_offset;
+                       
+                       v4f bar_colour;
+                       int bar_draw = 0;
+                       
+                       if( is_simulation_running() )
                        {
-                               float y_offset = is_input? 1.2f: -0.2f;
-                               y_offset += (is_input? 0.2f: -0.2f) * (float)k;
-                               
-                               glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), (float)posx + 0.2f + 0.2f * (float)j, (float)posy + y_offset, 0.1f );
+                               if( k == world.sim_run )
+                               {
+                                       float a = fabsf(sinf( vg_time * 2.0f )) * 0.075f + 0.075f;
+                                       
+                                       v4_copy( (v4f){ 1.0f, 1.0f, 1.0f, a }, bar_colour );
+                               }
+                               else
+                                       v4_copy( (v4f){ 0.0f, 0.0f, 0.0f, 0.13f }, bar_colour );
                                
+                               bar_draw = 1;
+                       }
+                       else if( 1 || k & 0x1 )
+                       {
+                               if( k & 0x1 )
+                                       v4_copy( (v4f){ 1.0f, 1.0f, 1.0f, 0.07f }, bar_colour );
+                               else
+                                       v4_copy( (v4f){ 0.0f, 0.0f, 0.0f, 0.13f }, bar_colour );                        
+                                                       
+                               bar_draw = 1;
+                       }
+                       
+                       if( bar_draw )
+                       {
+                               glUniform4fv( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 1, bar_colour );
+                               glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), (float)term->pos[0], y_position - 0.1f, 1.0f );
+                               draw_mesh( 2, 2 );
+                       }
+                       
+                       for( int j = 0; j < term->runs[k].condition_count; j ++ )
+                       {
+                               glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), 
+                                       (float)term->pos[0] + 0.2f + 0.2f * (float)j, 
+                                       y_position, 
+                                       0.1f 
+                               );
+                       
                                if( is_input )
                                {
-                                       colour_code_v3( term->runs[k].conditions[j], dot_colour );
-                                       glUniform4fv( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 1, dot_colour );
-                               
-                                       // Draw filled if tick not passed, draw empty if empty
-                                       if( (world.sim_frame > j && world.sim_run >= k) || world.sim_run > k )
-                                               draw_mesh( empty_start, empty_count );
-                                       else
-                                               draw_mesh( filled_start, filled_count );
+                                       char cc = term->runs[k].conditions[j];
+                                       if( cc != ' ' )
+                                       {                                       
+                                               colour_code_v3( cc, dot_colour );
+                                               glUniform4fv( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 1, dot_colour );
+                                       
+                                               // Draw filled if tick not passed, draw empty if empty
+                                               if( (world.sim_frame > j && world.sim_run >= k) || world.sim_run > k )
+                                                       draw_mesh( empty_start, empty_count );
+                                               else
+                                                       draw_mesh( filled_start, filled_count );
+                                       }
                                }
                                else
                                {
+                               
                                        if( term->runs[k].recv_count > j )
                                        {
                                                colour_code_v3( term->runs[k].recieved[j], dot_colour );
@@ -2108,118 +2434,795 @@ void vg_render(void)
                }
        }
        
-       if( world.simulating )
-       {
-               glUniform4f( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 0.0f, 0.0f, 0.0f, 1.0f );
-               glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), -0.5f + cosf( vg_time * 4.0f ) * 0.2f, sinf( vg_time * 4.0f ) * 0.2f + (float)world.h * 0.5f, 0.05f );
-               draw_mesh( filled_start, filled_count );
-       }
+       glDisable(GL_BLEND);
        
        // Draw score
+       /*
        float const score_bright = 1.25f;
        glUniform4f( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 
                0.4f*score_bright, 0.39f*score_bright, 0.45f*score_bright, 1.0f );
                
        use_mesh( &world.numbers );
        draw_numbers( (v3f){ 2.0f, (float)world.h-1.875f, 0.3333f }, world.score );
+       */
+}
+
+static ui_colourset flcol_list_a = {
+       .main = 0xff877979,
+       .hover = 0xffa09393,
+       .active = 0xffbfb1b0
+};
+static ui_colourset flcol_list_b = {
+       .main = 0xff7c6e6e,
+       .hover = 0xffa09393,
+       .active = 0xffbfb1b0
+};
+
+static ui_colourset flcol_list_complete_a = {
+       .main = 0xff62a064,
+       .hover = 0xff8dc18f,
+       .active = 0xffb2ddb3
+};
+
+static ui_colourset flcol_list_complete_b = {
+       .main = 0xff79b37b,
+       .hover = 0xff8dc18f,
+       .active = 0xffb2ddb3
+};
+
+static ui_colourset flcol_list_locked = {
+       .main = 0xff655959,
+       .hover = 0xff655959,
+       .active = 0xff655959
+};
+
+static struct
+{
+       SteamLeaderboard_t steam_leaderboard;
+       int leaderboard_show;
+       
+       struct leaderboard_player
+       {
+               // Internal
+               u64_steamid id;
+               i32 score;
+               int is_local_player;
+               
+               // To be displayed
+               char score_text[ 16 ];
+               char player_name[ 48 ];
+               GLuint texture;                 // Not dynamic
+       }
+       leaderboard_players[10];
+       int leaderboard_count;
+       
+       struct
+       {
+               struct cmp_level *level;
                
-       // Level selection UI
-       use_mesh( &world.circle );
-       float ratio = ((float)vg_window_x/(float)vg_window_y);
+               i32 score;
+               int is_waiting;
+       }
+       upload_request;
        
-       m3x3f ui_view = M3X3_IDENTITY;
-       m3x3_scale( ui_view, (v3f){ 1.0f, ratio, 1.0f } );
-       glUniformMatrix3fv( SHADER_UNIFORM( shader_tile_colour, "uPv" ), 1, GL_FALSE, (float *)ui_view );
+       struct cmp_level *level_selected;
+} 
+ui_data;
 
-       // Calculate mouse in UIsp
-       v3f mouse_ui_space = { ((float)vg_mouse[0] / (float)(vg_window_x)) * 2.0f - 1.0f,
-                                                                 (((float)vg_mouse[1] / (float)(vg_window_y)) * 2.0f - 1.0f)*(-1.0f/ratio), 0.0125f };
+void vg_ui(void)
+{
+       // UI memory
+       static int pack_selection = 0;
+       static struct pack_info
+       {
+               struct cmp_level *levels;
+               u32 level_count;
+               const char *name;
+       }
+       pack_infos[] = 
+       {
+               {
+                       .levels = cmp_levels_tutorials,
+                       .level_count = vg_list_size(cmp_levels_tutorials),
+                       .name = "Training"
+               },
+               {
+                       .levels = cmp_levels_basic,
+                       .level_count = vg_list_size(cmp_levels_basic),
+                       .name = "Main"
+               },
+               {
+                       .levels = cmp_levels_grad,
+                       .level_count = vg_list_size(cmp_levels_tutorials),
+                       .name = "Expert"
+               }
+       };
+       
+       // UI Code
+       ui_global_ctx.cursor[0] = 0;
+       ui_global_ctx.cursor[1] = 0;
+       ui_global_ctx.cursor[2] = 256;
 
-       // Get selected level
-       const float selection_scale = 0.05f;
-       int const level_count = vg_list_size( level_pack_1 );
-       int level_select = -1;
+       gui_fill_y();
+       
+       ui_global_ctx.id_base = 4 << 16;
        
-       if( mouse_ui_space[0] <= -0.8f )
+       gui_new_node();
        {
-               float levels_range = (float)level_count*selection_scale*0.6f;
-               float level_offset = ((-mouse_ui_space[1] + levels_range) / levels_range) * 0.5f * (float)level_count;
-               level_select = ceilf( level_offset );
-
-               // Draw selector
-               if( level_select >= 0 && level_select < vg_list_size( level_pack_1 ) )
+               gui_capture_mouse( 9999 );
+               gui_fill_rect( ui_global_ctx.cursor, 0xff5a4e4d );
+               
+               gui_text( "ASSIGNMENTS", 8, 0 );
+               
+               ui_global_ctx.cursor[1] += 30;
+               ui_global_ctx.cursor[3] = 25;
+               
+               gui_new_node();
                {
-                       glUniform4f( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 0.369768f, 0.3654f, 0.42f, 1.0f );
+                       ui_rect_pad( ui_global_ctx.cursor, 2 );
+                       ui_global_ctx.cursor[2] = 84;
                        
-                       use_mesh( &world.tile );
-                       glUniform3f( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), 
-                               -1.0f, 
-                               ((float)level_count - (float)level_select * 2.0f ) * selection_scale * 0.6f,
-                               selection_scale
-                       );
-                       draw_mesh( 2, 2 );
+                       for( int i = 0; i < 3; i ++ )
+                       {
+                               int pack_is_unlocked = pack_infos[i].levels[0].unlocked;
                        
-                       use_mesh( &world.circle );
+                               if( i == pack_selection || !pack_is_unlocked )
+                                       gui_override_colours( &flcol_list_locked );
+                               
+                               if( gui_button( 2000 + i ) == k_button_click && pack_is_unlocked )
+                                       pack_selection = i;
+                               
+                               ui_global_ctx.cursor[1] += 2;
+                               gui_text( pack_is_unlocked? pack_infos[i].name: "???", 4, 0 );
+                               gui_end_right();
+                               
+                               gui_reset_colours();
+                       } 
+               }
+               gui_end_down();
+               
+               ui_global_ctx.cursor[3] = 500;
+               
+               // DRAW LEVEL SELECTION LIST
+               {
+                       struct cmp_level *levels = pack_infos[ pack_selection ].levels;
+                       int count = pack_infos[ pack_selection ].level_count;
+
+                       static struct ui_scrollbar sb = {
+                               .bar_height = 400
+                       };
                        
-                       if( vg_get_button_down( "primary" ) )
+                       ui_px view_height = ui_global_ctx.cursor[3];
+                       ui_px level_height = 50;
+
+                       // Level scroll view
+                       gui_new_node();
                        {
-                               console_changelevel( 1, level_pack_1 + level_select );
+                               gui_fill_rect( ui_global_ctx.cursor, 0xff5a4e4d );
+                               gui_set_clip( ui_global_ctx.cursor );
+                               
+                               ui_global_ctx.cursor[2] = 14;
+                               gui_align_right();
+                               
+                               ui_px content_height = count*level_height;
+                               if( content_height > view_height )
+                               {
+                                       ui_scrollbar( &ui_global_ctx, &sb, 1 );
+                                       ui_global_ctx.cursor[1] -= ui_calculate_content_scroll( &sb, content_height );
+                               }
+                               else
+                               {
+                                       gui_fill_rect( ui_global_ctx.cursor, 0xff807373 );
+                               }
+                               
+                               ui_global_ctx.cursor[2] = 240;
+                               ui_global_ctx.cursor[3] = level_height;
+                               gui_align_left();
+                               
+                               for( int i = 0; i < count; i ++ )
+                               {
+                                       struct cmp_level *lvl_info = &levels[i];
+                               
+                                       if( lvl_info->unlocked )
+                                       {
+                                               if( lvl_info->completed_score != 0 )
+                                                       gui_override_colours( i&0x1? &flcol_list_complete_a: &flcol_list_complete_b );
+                                               else
+                                                       gui_override_colours( i&0x1? &flcol_list_a: &flcol_list_b );
+                                       }
+                                       else
+                                               gui_override_colours( &flcol_list_locked );
+                                       
+                                       if( lvl_info->unlocked )
+                                       {
+                                               if( gui_button( 2 + i ) == k_button_click )
+                                               {
+                                                       ui_data.level_selected = &levels[i];
+                                                       ui_data.leaderboard_show = 0;
+                                                       
+                                                       if( pack_selection >= 1 )
+                                                               sw_find_leaderboard( ui_data.level_selected->map_name );
+                                               }
+                                               
+                                               ui_global_ctx.override_colour = 0xffffffff;
+                                               gui_text( lvl_info->title, 6, 0 );
+                                               ui_global_ctx.cursor[1] += 18;
+                                               gui_text( lvl_info->completed_score>0? "passed": "incomplete", 4, 0 );
+                                       }
+                                       else
+                                       {
+                                               gui_button( 2 + i );
+                                               
+                                               ui_global_ctx.override_colour = 0xff786f6f;
+                                               gui_text( "???", 6, 0 );
+                                               ui_global_ctx.cursor[1] += 18;
+                                               gui_text( "locked", 4, 0 );
+                                       }
+                                       
+                                       gui_end_down();
+                               }
+                               
+                               gui_reset_colours();            
+                               gui_release_clip();
                        }
+                       gui_end_down();
                }
        }
-       else mouse_ui_space[1] = INFINITY;
-
-       glUniform4f( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 0.4f, 0.39f, 0.45f, 1.0f );
-
-       // Draw levels
-       for( int i = 0; i < level_count; i ++ )
-       {
-               struct career_level *clevel = &career.levels[i];
-       
-               v3f level_ui_space = { 
-                       -0.97f, 
-                       ((float)level_count - (float)i * 2.0f ) * selection_scale * 0.6f + selection_scale * 0.5f,
-                       selection_scale * 0.5f
-               };
-               
-               float scale = vg_clampf( 1.0f - fabsf(level_ui_space[1] - mouse_ui_space[1]) * 2.0f, 0.9f, 1.0f );
-               level_ui_space[2] *= scale;
-               
-               glUniform3fv( SHADER_UNIFORM( shader_tile_colour, "uOffset" ), 1, level_ui_space );
-               
-               if( clevel->completed )
-                       draw_mesh( filled_start, filled_count );
-               else
-                       draw_mesh( empty_start, empty_count );
-       }
+       gui_end_right();
        
-       // Level scores
-       glUniform4f( SHADER_UNIFORM( shader_tile_colour, "uColour" ), 0.4f*1.25f, 0.39f*1.25f, 0.45f*1.25f, 1.0f );
+       // Selected level UI
+       // ============================================================
        
-       use_mesh( &world.numbers );
-       for( int i = 0; i < level_count; i ++ )
+       if( ui_data.level_selected )
        {
-               struct career_level *clevel = &career.levels[i];
+               ui_global_ctx.cursor[0] += 16;
+               ui_global_ctx.cursor[1] += 16;
+               ui_global_ctx.cursor[2] = 512-40;
+               ui_global_ctx.cursor[3] = 560-16;
+               
+               gui_new_node();
+               {
+                       gui_capture_mouse( 9999 );
+                       
+                       gui_fill_rect( ui_global_ctx.cursor, 0xff5a4e4d );
+                       ui_global_ctx.cursor[1] += 4;
+                       gui_text( ui_data.level_selected->title, 6, 0 );
+                       
+                       ui_global_ctx.cursor[1] += 30;
+                       ui_rect_pad( ui_global_ctx.cursor, 8 );
+                       ui_global_ctx.cursor[3] = 300;
+                       
+                       gui_new_node();
+                       {
+                               gui_fill_rect( ui_global_ctx.cursor, 0xff655959 );
+                       }
+                       gui_end_down();
+                       
+                       ui_text_use_paragraph( &ui_global_ctx );
+                       ui_global_ctx.cursor[1] += 2;
+                       
+                       gui_text( ui_data.level_selected->description, 5, 0 );
+                       ui_text_use_title( &ui_global_ctx );
+                       
+                       // Buttons at the bottom
+                       ui_global_ctx.cursor[3] = 25;
+                       ui_global_ctx.cursor[2] = 80;
+                       
+                       gui_align_bottom();
+                       ui_global_ctx.cursor[1] -= 8;
+                       
+                       if( gui_button( 3000 ) == k_button_click )
+                       {
+                               ui_data.level_selected = NULL;
+                       }
+                       gui_text( "BACK", 6, k_text_alignment_center );
+                       gui_end();
+                       
+                       gui_align_right();
+                       ui_global_ctx.cursor[2] = 170;
+                       ui_global_ctx.cursor[0] -= 8 + 170 + 2;
+                       
+                       {
+                               gui_override_colours( &flcol_list_locked );
+                               if( gui_button( 3001 ) == k_button_click )
+                                       vg_error( "UNIMPLEMENTED\n" );
+                               
+                               ui_global_ctx.override_colour = 0xff888888;
+                               
+                               gui_text( "RESTORE SOLUTION", 6, k_text_alignment_center );
+                               gui_end_right();
+                               ui_global_ctx.override_colour = 0xffffffff;
+                       }
+                       
+                       ui_global_ctx.cursor[0] += 2;
+                       ui_global_ctx.cursor[2] = 80;
+                       
+                       {
+                               gui_override_colours( &flcol_list_complete_a );
+                               if( gui_button( 3002 ) == k_button_click )
+                               {
+                                       if( console_changelevel( 1, &ui_data.level_selected->map_name ) )
+                                       {
+                                               world.pCmpLevel = ui_data.level_selected;
+
+                                               ui_data.level_selected = NULL;
+                                               ui_data.leaderboard_show = 0;
+                                       }
+                               }
+                               gui_text( "PLAY", 6, k_text_alignment_center );
+                               gui_end();
+                       }
+                       
+                       gui_reset_colours();
+               }
+               gui_end_right();
+               
+               if( ui_data.leaderboard_show )
+               {
+                       ui_global_ctx.cursor[0] += 16;
+                       ui_global_ctx.cursor[2] = 350;
+                       ui_global_ctx.cursor[3] = 25;
+                       
+                       // If has results
+                       gui_new_node();
+                       {
+                               gui_fill_rect( ui_global_ctx.cursor, 0xff5a4e4d );
+                               gui_text( "FRIEND LEADERBOARD", 6, 0 );
+                       }
+                       gui_end_down();
+                       
+                       ui_global_ctx.cursor[1] += 2;
+                               
+                       gui_new_node();
+                       {
+                               ui_global_ctx.cursor[3] = 32+8;
+                               
+                               for( int i = 0; i < ui_data.leaderboard_count; i ++ )
+                               {
+                                       gui_new_node();
+                                       {
+                                               gui_fill_rect( ui_global_ctx.cursor, i&0x1? flcol_list_a.main: flcol_list_b.main );
+
+                                               ui_global_ctx.cursor[0] += 4;
+                                               ui_global_ctx.cursor[1] += 4;                                                   
+                                               
+                                               // 1,2,3 ...
+                                               static const char *places[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
+                                               gui_text( places[i], 7, 0 );
+                                               ui_global_ctx.cursor[0] += 32;
+                                               
+                                               struct leaderboard_player *player = &ui_data.leaderboard_players[i];
+                                               
+                                               // Players image
+                                               ui_global_ctx.cursor[2] = 32;
+                                               ui_global_ctx.cursor[3] = 32;
+                                               
+                                               gui_new_node();
+                                               {
+                                                       gui_push_image( ui_global_ctx.cursor, player->texture );
+                                               }
+                                               gui_end_right();
+                                               
+                                               // Players name
+                                               gui_text( player->player_name, 7, 0 );
+                                               
+                                               ui_global_ctx.cursor[2] = 50;
+                                               gui_align_right();
+                                               
+                                               gui_text( player->score_text, 7, k_text_alignment_right );
+                                       }
+                                       gui_end_down();
+                                       
+                                       ui_global_ctx.cursor[1] += 2;
+                               }
+                       }
+                       gui_end();
+               }
+       }
+}
+
+void leaderboard_dispatch_score(void)
+{
+       sw_upload_leaderboard_score( 
+               ui_data.upload_request.level->steam_leaderboard, 
+               k_ELeaderboardUploadScoreMethodKeepBest,
+               ui_data.upload_request.score,
+               NULL,
+               0
+       );
+       
+       ui_data.upload_request.is_waiting = 0;
+       
+       vg_success( "Dispatched leaderboard score\n" );
+}
+
+void leaderboard_found( LeaderboardFindResult_t *pCallback )
+{
+       if( !pCallback->m_bLeaderboardFound )
+       {
+               vg_error( "Leaderboard could not be found\n" );
+               ui_data.steam_leaderboard = 0;
+       }
+       else
+       {
+               const char *recieved_name = sw_get_leaderboard_name( pCallback->m_hSteamLeaderboard );
+               
+               // Update UI state and request entries if this callback found the current UI level
+               if( ui_data.level_selected )
+               {
+                       if( !strcmp( recieved_name, ui_data.level_selected->map_name ) )
+                       {
+                               sw_download_leaderboard_entries( pCallback->m_hSteamLeaderboard, k_ELeaderboardDataRequestFriends, 0, 8 );
+                               ui_data.level_selected->steam_leaderboard = pCallback->m_hSteamLeaderboard;
+                       }
+               }
+               
+               // Dispatch the waiting request if there was one
+               if( ui_data.upload_request.is_waiting )
+               {
+                       if( !strcmp( recieved_name, ui_data.upload_request.level->map_name ) )
+                       {
+                               ui_data.upload_request.level->steam_leaderboard = pCallback->m_hSteamLeaderboard;
+                               leaderboard_dispatch_score();
+                       }
+               }
+       }
+}
+
+void leaderboard_downloaded( LeaderboardScoresDownloaded_t *pCallback )
+{
+       // Update UI if this leaderboard matches what we currently have in view
+       if( ui_data.level_selected->steam_leaderboard == pCallback->m_hSteamLeaderboard )
+       {
+               vg_info( "Recieved %d entries\n", pCallback->m_cEntryCount );
+               ui_data.leaderboard_count = VG_MIN( pCallback->m_cEntryCount, 8 );
+               
+               u64_steamid local_player = sw_get_steamid();
+               
+               for( int i = 0; i < ui_data.leaderboard_count; i ++ )
+               {
+                       LeaderboardEntry_t entry;
+                       sw_get_downloaded_entry( pCallback->m_hSteamLeaderboardEntries, i, &entry, NULL, 0 );
+                       
+                       struct leaderboard_player *player = &ui_data.leaderboard_players[i];
+
+                       player->id = entry.m_steamIDUser.m_unAll64Bits;
+                       strncpy( player->player_name, sw_get_friend_persona_name( player->id ), vg_list_size( player->player_name )-1 );
+                       player->score = entry.m_nScore;
+                       
+                       snprintf( player->score_text, vg_list_size(player->score_text), "%d", player->score );
+                       player->texture = sw_get_player_image( player->id );
+                       
+                       if( player->texture == 0 )
+                               player->texture = tex_unkown.name;
+                               
+                       player->is_local_player = local_player == player->id? 1: 0;
+               }
+               
+               if( ui_data.leaderboard_count )
+                       ui_data.leaderboard_show = 1;
+               else
+                       ui_data.leaderboard_show = 0;
+       }
+       else vg_warn( "Downloaded leaderboard does not match requested!\n" );
+}
+
+void leaderboard_set_score( struct cmp_level *cmp_level, u32 score )
+{
+       if( ui_data.upload_request.is_waiting )
+               vg_warn( "You are uploading leaderboard entries too quickly!\n" );
+               
+       ui_data.upload_request.level = cmp_level;
+       ui_data.upload_request.score = score;
+       ui_data.upload_request.is_waiting = 1;
+       
+       // If leaderboard ID has been downloaded already then just immediately dispatch this
+       if( cmp_level->steam_leaderboard )
+               leaderboard_dispatch_score();
+       else
+               sw_find_leaderboard( cmp_level->map_name );
+}
+
+// CONSOLE COMMANDS
+// ===========================================================================================================
+
+static int console_credits( int argc, char const *argv[] )
+{
+       vg_info( "Aknowledgements:\n" );
+       vg_info( "  GLFW         zlib/libpng  glfw.org\n" );
+       vg_info( "  miniaudio    MIT0         miniaud.io\n" );
+       vg_info( "  QOI          MIT          phoboslab.org\n" );
+       vg_info( "  STB library  MIT          nothings.org\n" );
+       return 0;
+}
+
+static int console_save_map( int argc, char const *argv[] )
+{
+       if( !world.initialzed )
+       {
+               vg_error( "Tried to save uninitialized map!\n" );
+               return 0;
+       }
+
+       char map_path[ 256 ];
+
+       strcpy( map_path, "sav/" );
+       strcat( map_path, world.map_name );
+       strcat( map_path, ".map" );
+
+       FILE *test_writer = fopen( map_path, "wb" );
+       if( test_writer )
+       {
+               vg_info( "Saving map to '%s'\n", map_path );
+               map_serialize( test_writer );
+               
+               fclose( test_writer );
+               return 1;
+       }
+       else
+       {
+               vg_error( "Unable to open stream for writing\n" );
+               return 0;
+       }
+}
+
+static int console_load_map( int argc, char const *argv[] )
+{
+       char map_path[ 256 ];
+
+       if( argc >= 1 )
+       {
+               // try from saves
+               strcpy( map_path, "sav/" );
+               strcat( map_path, argv[0] );
+               strcat( map_path, ".map" );
        
-               v3f level_ui_space = { 
-                       -0.94f, 
-                       ((float)level_count - (float)i * 2.0f ) * selection_scale * 0.6f + selection_scale * 0.5f,
-                       0.02f
+               char *text_source = vg_textasset_read( map_path );
+               
+               if( !text_source )
+               {
+                       strcpy( map_path, "maps/" );
+                       strcat( map_path, argv[0] );
+                       strcat( map_path, ".map" );
+                       
+                       text_source = vg_textasset_read( map_path );
+               }
+               
+               if( text_source )
+               {
+                       vg_info( "Loading map: '%s'\n", map_path );
+                       world.pCmpLevel = NULL;
+                       
+                       if( !map_load( text_source, argv[0] ) )
+                       {
+                               free( text_source );
+                               return 0;
+                       }
+                       
+                       free( text_source );    
+                       return 1;
+               }
+               else
+               {
+                       vg_error( "Missing maps '%s'\n", argv[0] );
+                       return 0;
+               }
+       }
+       else
+       {
+               vg_error( "Missing argument <map_path>\n" );
+               return 0;
+       }
+}
+
+static int console_changelevel( int argc, char const *argv[] )
+{
+       if( argc >= 1 )
+       {
+               // Save current level
+               console_save_map( 0, NULL );
+               if( console_load_map( argc, argv ) )
+               {                               
+                       simulation_stop();
+                       return 1;
+               }
+       }
+       else
+       {
+               vg_error( "Missing argument <map_path>\n" );
+       }
+       
+       return 0;
+}
+
+// START UP / SHUTDOWN
+// ===========================================================================================================
+
+#define TRANSFORM_TRI_2D( S, OX, OY, X1, Y1, X2, Y2, X3, Y3 ) \
+       X1*S+OX, Y1*S+OY, X2*S+OX, Y2*S+OY, X3*S+OX, Y3*S+OY 
+
+void vg_start(void)
+{
+       // Steamworks callbacks
+       sw_leaderboard_found = &leaderboard_found;
+       sw_leaderboard_downloaded = &leaderboard_downloaded;
+
+       vg_function_push( (struct vg_cmd){
+               .name = "_map_write",
+               .function = console_save_map
+       });
+       
+       vg_function_push( (struct vg_cmd){
+               .name = "_map_load",
+               .function = console_load_map
+       });
+       
+       vg_function_push( (struct vg_cmd){
+               .name = "map",
+               .function = console_changelevel
+       });
+       
+       vg_function_push( (struct vg_cmd){
+               .name = "credits",
+               .function = console_credits
+       });
+
+       // Combined quad, long quad / empty circle / filled circle mesh
+       {
+               float combined_mesh[6*6 + 32*6*3] = {
+                       0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
+                       0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f,
+                       
+                       0.0f, 0.0f, 0.0f, 0.2f, 1.0f, 0.2f,
+                       0.0f, 0.0f, 1.0f, 0.2f, 1.0f, 0.0f,
+                       
+                       TRANSFORM_TRI_2D( 0.15f,0.05f,0.4f, 0.0f, 1.0f, 1.0f, 2.0f, 1.0f, 0.0f ),
+                       TRANSFORM_TRI_2D( 0.15f,0.80f,0.4f, 0.0f, 0.0f, 0.0f, 2.0f, 1.0f, 1.0f )
                };
                
-               if( clevel->completed )
-                       draw_numbers( level_ui_space, clevel->score );
+               float *circle_mesh = combined_mesh + 6*6;
+               int const res = 32;
+
+               for( int i = 0; i < res; i ++ )
+               {
+                       v2f v0 = { sinf( ((float)i/(float)res)*VG_TAUf ), cosf( ((float)i/(float)res)*VG_TAUf ) };
+                       v2f v1 = { sinf( ((float)(i+1)/(float)res)*VG_TAUf ), cosf( ((float)(i+1)/(float)res)*VG_TAUf ) };
+               
+                       circle_mesh[ i*6+0 ] = 0.0f;
+                       circle_mesh[ i*6+1 ] = 0.0f;
+                       
+                       v2_copy( v0, circle_mesh + 32*6 + i*12 );
+                       v2_muls( v0, 0.8f, circle_mesh + 32*6 + i*12+2 );
+                       v2_copy( v1, circle_mesh + 32*6 + i*12+4 );
+                       
+                       v2_copy( v1, circle_mesh + 32*6 + i*12+6 );
+                       v2_muls( v1, 0.8f, circle_mesh + 32*6 + i*12+8 );
+                       v2_muls( v0, 0.8f, circle_mesh + 32*6 + i*12+10 );
                        
-               level_ui_space[0] = -0.975f;
-               level_ui_space[1] -= 0.01f;
-               draw_numbers( level_ui_space, i );
+                       v2_copy( v0, circle_mesh + i*6+4 );
+                       v2_copy( v1, circle_mesh + i*6+2 );
+                       v2_copy( v0, circle_mesh+i*6+4 );
+                       v2_copy( v1, circle_mesh+i*6+2 );
+               }
+               
+               init_mesh( &world.shapes, combined_mesh, vg_list_size( combined_mesh ) );
        }
        
-       //use_mesh( &world.numbers );
-       //draw_numbers( (v3f){ 0.0f, -0.5f, 0.1f }, 128765 );
+       // Numbers mesh
+       {
+               init_mesh( &world.numbers,
+                       MESH_NUMBERS_BUFFER,
+                       vg_list_size( MESH_NUMBERS_BUFFER )
+               );
+               
+               for( int i = 0; i < 10; i ++ )
+               {
+                       vg_info( "offset: %u, length: %u\n", MESH_NUMBERS_OFFSETS[i][0], MESH_NUMBERS_OFFSETS[i][1] );
+               }
+       }
+       
+       // Create wire mesh
+       {
+               int const num_segments = 64;
+       
+               struct mesh_wire *mw = &world.wire;
+       
+               v2f wire_points[ num_segments * 2 ];
+               u16 wire_indices[ 6*(num_segments-1) ];
+               
+               for( int i = 0; i < num_segments; i ++ )
+               {
+                       float l = (float)i / (float)(num_segments-1);
+                       
+                       v2_copy( (v2f){ l, -0.5f }, wire_points[i*2+0] );
+                       v2_copy( (v2f){ l,  0.5f }, wire_points[i*2+1] );
+                       
+                       if( i < num_segments-1 )
+                       {
+                               wire_indices[ i*6+0 ] = i*2 + 0;
+                               wire_indices[ i*6+1 ] = i*2 + 1;
+                               wire_indices[ i*6+2 ] = i*2 + 3;
+                               wire_indices[ i*6+3 ] = i*2 + 0;
+                               wire_indices[ i*6+4 ] = i*2 + 3;
+                               wire_indices[ i*6+5 ] = i*2 + 2;
+                       }
+               }
+               
+               glGenVertexArrays( 1, &mw->vao );
+               glGenBuffers( 1, &mw->vbo );
+               glGenBuffers( 1, &mw->ebo );
+               glBindVertexArray( mw->vao );
+               
+               glBindBuffer( GL_ARRAY_BUFFER, mw->vbo );
+               
+               glBufferData( GL_ARRAY_BUFFER, sizeof( wire_points ), wire_points, GL_STATIC_DRAW );
+               glBindVertexArray( mw->vao );
+               
+               glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mw->ebo );
+               glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( wire_indices ), wire_indices, GL_STATIC_DRAW );
+               
+               // XY
+               glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0 );
+               glEnableVertexAttribArray( 0 );
+               
+               VG_CHECK_GL();
+               
+               mw->em = vg_list_size( wire_indices );
+       }
+       
+       // Create info data texture
+       {
+               glGenTextures( 1, &world.background_data );
+               glBindTexture( GL_TEXTURE_2D, world.background_data );
+               glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
+               vg_tex2d_nearest();
+       }
+       
+       // Create random smaples texture
+       {
+               u8 *data = malloc(512*512*2);
+               for( int i = 0; i < 512*512*2; i ++ )
+                       data[ i ] = rand()/(RAND_MAX/255);
+               
+               glGenTextures( 1, &world.random_samples );
+               glBindTexture( GL_TEXTURE_2D, world.random_samples );
+               glTexImage2D( GL_TEXTURE_2D, 0, GL_RG, 512, 512, 0, GL_RG, GL_UNSIGNED_BYTE, data );
+               vg_tex2d_linear();
+               vg_tex2d_repeat();
+               
+               free( data );
+       }
+       
+       resource_load_main();
+       
+       // Restore gamestate
+       career_local_data_init();
+       career_load();
 }
 
-void vg_ui(void)
+void vg_free(void)
 {
-       ui_test();
+       sw_free_opengl();
+       console_save_map( 0, NULL );
+       career_serialize();
+
+       resource_free_main();
+
+       glDeleteTextures( 1, &world.background_data );
+       glDeleteTextures( 1, &world.random_samples );
+
+       glDeleteVertexArrays( 1, &world.wire.vao );
+       glDeleteBuffers( 1, &world.wire.vbo );
+       glDeleteBuffers( 1, &world.wire.ebo );
+
+       free_mesh( &world.shapes );
+       free_mesh( &world.numbers );
+       
+       map_free();
+}
+
+int main( int argc, char *argv[] )
+{
+       vg_init( argc, argv, "Marble Computing" );
+       return 0;
 }
index 2bd1442d125e379b53eb589b77fc3f0b81ba8390..30b4dc9609e3af70754233636234e8556ee19afa 100644 (file)
@@ -4,10 +4,13 @@
 vg_tex2d tex_tile_data =       { .path = "textures/tileset.qoi" };
 vg_tex2d tex_tile_detail = { .path = "textures/tile_overlays.qoi" };
 vg_tex2d tex_wood =                    { .path = "textures/wood.qoi" };
-vg_tex2d tex_ball =                    { .path = "textures/ball.qoi", .flags = VG_TEXTURE_CLAMP };
 vg_tex2d tex_background =      { .path = "textures/background.qoi" };
+vg_tex2d tex_ball_noise =  { .path = "textures/bnoise.qoi" };
+vg_tex2d tex_monofur   =  { .path = "textures/ascii.qoi", .flags = VG_TEXTURE_NO_MIP };
+vg_tex2d tex_unkown            =  { .path = "textures/unkown.qoi" };
+vg_tex2d tex_buttons           =  { .path = "textures/buttons.qoi" };
 
-vg_tex2d *texture_list[] = { &tex_tile_detail, &tex_tile_data, &tex_wood, &tex_ball, &tex_background };
+vg_tex2d *texture_list[] = { &tex_tile_detail, &tex_tile_data, &tex_wood, &tex_background, &tex_ball_noise, &tex_monofur, &tex_unkown, &tex_buttons };
 
 // AUDIO
 // ===========================================================================================================
@@ -61,6 +64,14 @@ sound/random_07.ogg\0\
 sound/random_08.ogg\0"
 };
 
+sfx_set audio_clicks =
+{
+ .sources = "\
+sound/click_a.ogg\0\
+sound/click_b.ogg\0\
+sound/click_c.ogg\0"
+};
+
 // One two or three layers of rolling noise
 sfx_system audio_system_balls_rolling =
 {
@@ -89,16 +100,40 @@ sfx_system audio_system_balls_extra =
        .name = "Balls Extra"
 };
 
+sfx_system audio_system_ui = 
+{
+       .vol = 1.f, .ch = 1, .vol_src = &audio_volume_sfx,
+       .name = "UI"
+};
+
+ui_colourset ui_fl_colours = {
+       .main = 0xff807373,
+       .hover = 0xff918484,
+       .active = 0xffad9f9e
+};
+
+ui_colourset ui_fl_colours_inactive = {
+       .main = 0xff655958,
+       .hover = 0xff655958,
+       .active = 0xff655958
+};
+
 static void resource_load_main(void)
 {
        // Textures
        vg_tex2d_init( texture_list, vg_list_size( texture_list ) );
        
+       ui_override_font( tex_monofur.name, 7 );
+
+       ui_global_ctx.colours_main = &ui_fl_colours;
+       gui_reset_colours();
+       
        // Audio
        sfx_set_init( &audio_tile_mod, NULL );
        sfx_set_init( &audio_splitter, NULL );
        sfx_set_init( &audio_rolls, NULL );
        sfx_set_init( &audio_random, NULL );
+       sfx_set_init( &audio_clicks, NULL );
 }
 
 static void resource_free_main(void)
@@ -109,6 +144,7 @@ static void resource_free_main(void)
        sfx_set_free( &audio_splitter );
        sfx_set_free( &audio_rolls );
        sfx_set_free( &audio_random );
+       sfx_set_free( &audio_clicks );
 }
 
 // SHADERS
@@ -141,19 +177,19 @@ SHADER_DEFINE( shader_tile_colour,
 SHADER_DEFINE( shader_ball,
        // VERTEX
        "layout (location=0) in vec2 a_co;"
-       "uniform vec2 uOffset;"
+       "uniform vec3 uOffset;"
        "uniform mat3 uPv;"
        ""
-       "out vec2 aTexCoords;"
+       "out vec4 aTexCoords;"
        ""
        "void main()"
        "{"
-               // Create texture coords
-               "aTexCoords = a_co;"
-               
                // Vertex transform
-               "vec3 worldpos = vec3( a_co * 0.5 - 0.25 + uOffset, 1.0 );"
+               "vec3 worldpos = vec3( (a_co * 0.5 - 0.25) * uOffset.z + uOffset.xy, 1.0 );"
                "gl_Position = vec4( uPv * worldpos, 1.0 );"
+
+               // Create texture coords
+               "aTexCoords = vec4( a_co, worldpos.xy );"
        "}",
        
        // FRAGMENT
@@ -161,16 +197,33 @@ SHADER_DEFINE( shader_ball,
        ""
        "uniform sampler2D uTexMain;"
        "uniform vec3 uColour;"
+       "uniform vec2 uTexOffset;"
        ""
-       "in vec2 aTexCoords;"
+       "in vec4 aTexCoords;"
        ""
        "void main()"
        "{"
-               "vec4 glyph = texture( uTexMain, aTexCoords );"
-               "FragColor = vec4( uColour + glyph.rgb * 0.2, glyph.a );"
+               "vec2 center_coords = aTexCoords.xy - 0.5;"
+               "vec2 center_coords_sqr = center_coords*center_coords;"
+               "float circle_factor = smoothstep( 0.07, 0.0625, center_coords_sqr.x+center_coords_sqr.y );"
+               
+               "float bulge_amt = center_coords_sqr.x+center_coords_sqr.y;"
+               "vec2 warped_coords = aTexCoords.zw+uTexOffset - center_coords;"
+               "vec4 noise_sample = texture( uTexMain, warped_coords );"
+               
+               "float rim_light = (center_coords_sqr.x+center_coords_sqr.y)*15.0;"
+               
+               "vec2 shadow_coords = center_coords + vec2(0.02,0.07);"
+               "vec2 shadow_coords_sqr = shadow_coords*shadow_coords;"
+               "float shadow = exp(-((shadow_coords_sqr.x+shadow_coords_sqr.y)-0.0125)*15.0);"
+               
+               "vec3 marble_comp = uColour*0.9 + (noise_sample.x*0.7+pow(rim_light,3.0)*2.0) * 0.1;"
+               "vec4 colour_comp = mix( vec4(0.74,0.53,0.34,shadow), vec4(marble_comp,1.0), circle_factor );"
+               
+               "FragColor = colour_comp;"
        "}"
        ,
-       UNIFORMS({ "uTexMain", "uColour", "uOffset", "uPv" })
+       UNIFORMS({ "uTexMain", "uColour", "uOffset", "uPv", "uTexOffset" })
 )
 
 SHADER_DEFINE( shader_tile_main,
@@ -219,7 +272,7 @@ SHADER_DEFINE( shader_tile_main,
        ""
        "void main()"
        "{"
-               "vec3 shadowing_colour = vec3( 0.93, 0.88536, 0.8184 );"
+               "vec3 shadowing_colour = vec3( 0.93, 0.88536, 0.8184 ) * 0.97;"
                "vec4 glyph = texture( uTexGlyphs, aTexCoords.xy );"
                "vec4 wood = texture( uTexWood, aTexCoords.zw );"
                "vec4 wood_secondary = texture( uTexWood, aTexCoords.zw + 0.25 );"
@@ -277,7 +330,7 @@ SHADER_DEFINE( shader_background,
                
                "ao_accum -= data_this_tile.r;"
                
-               "vec3 colour_main = vec3( 0.369768, 0.3654, 0.42 );"
+               "vec3 colour_main = mix( vec3( 0.369768, 0.3654, 0.42 ),vec3( 0.275, 0.388, 0.553 ), data_this_tile.g );"
                
                "vec2 square_coords = fract( aTexCoords * 64.0 );"
                "vec2 grid_coords = abs( square_coords - 0.5 );"
@@ -332,15 +385,63 @@ SHADER_DEFINE( shader_wire,
        ""
        "uniform sampler2D uTexMain;"
        "uniform vec4 uColour;"
+       "uniform float uTime;"
+       "uniform float uGlow;"
        ""
        "in vec2 aTexCoords;"
        ""
        "void main()"
        "{"
-               "FragColor = uColour;"
+               // Compute shadowing
+               "float shadow = 1.0 - abs(aTexCoords.y - 0.5) * 2.0;"
+               "float masking = smoothstep( 0.5, 0.8, shadow );"
+               
+               "vec3 colour_comp = mix( vec3(0.0,0.0,0.0), uColour.rgb, masking );"
+               
+               "float flow_thing = fract( aTexCoords.x + uTime );"
+               "vec3 final_comp = colour_comp + flow_thing * uGlow;"
+               
+               "FragColor = vec4( final_comp, max( shadow* 0.2, masking ) * uColour.a );"
+       "}"
+       ,
+       UNIFORMS({ "uPv", "uColour", "uTexMain", "uStart", "uEnd", "uCurve", "uTime", "uGlow" })
+)
+
+SHADER_DEFINE( shader_buttons,
+       // VERTEX
+       "layout (location=0) in vec2 a_co;"
+       "uniform vec4 uOffset;" // Tile x/y, uv x/y
+       "uniform mat3 uPv;"
+       ""
+       "out vec2 aTexCoords;"
+       ""
+       "void main()"
+       "{"
+               // Vertex transform
+               "vec3 worldpos = vec3( a_co + uOffset.xy, 1.0 );"
+               "gl_Position = vec4( uPv * worldpos, 1.0 );"
+
+               // Create texture coords
+               "vec2 edge_safe_coords = a_co * 0.98 + 0.01;"
+               "aTexCoords = (edge_safe_coords + uOffset.zw) * 0.25;"  
+       "}",
+       
+       // FRAGMENT
+       "out vec4 FragColor;"
+       ""
+       "uniform sampler2D uTexMain;"
+       "uniform vec4 uColour;" // rgb, light amount
+       ""
+       "in vec2 aTexCoords;"
+       ""
+       "void main()"
+       "{"
+               "vec4 glyph = texture( uTexMain, aTexCoords.xy );"
+               
+               "FragColor = vec4( uColour.rgb * (mix(glyph.r, glyph.g, uColour.a)+0.02)*2.6 + glyph.b * 0.4, glyph.a );"
        "}"
        ,
-       UNIFORMS({ "uPv", "uColour", "uTexMain", "uStart", "uEnd", "uCurve" })
+       UNIFORMS({ "uPv", "uOffset", "uTexMain", "uColour" })
 )
 
 
@@ -351,6 +452,7 @@ void vg_register(void)
        SHADER_INIT( shader_ball );
        SHADER_INIT( shader_background );
        SHADER_INIT( shader_wire );
+       SHADER_INIT( shader_buttons );
 }
 
 /*
@@ -523,3 +625,348 @@ u32 const MESH_NUMBERS_OFFSETS[][2] =
                vg_list_size( MESH_NUMBER_9 ) / MESH_NUMBER_DIVISOR
        }
 };
+
+struct cmp_level
+{
+       const char *map_name;
+       const char *title;
+       const char *description;
+       
+       int unlocked;
+       int completed_score;
+       
+       int _unlock, _linked;   // When completed, unlock this level
+       struct cmp_level *unlock, *linked;
+       
+       int serial_id;
+       int is_tutorial;
+       
+       SteamLeaderboard_t steam_leaderboard;
+};
+
+static struct cmp_level cmp_levels_tutorials[] = 
+{
+       // r1
+       {
+               .serial_id = 0,
+               .title = "PRINCIPLE 1",
+               .map_name = "cmp_t01",
+               .description = 
+                       "Utilize basic transport methods",
+               
+               ._unlock = 1,
+               .is_tutorial = 1
+       },
+       // r1
+       {
+               .serial_id = 1,
+               .title = "PRINCIPLE 2",
+               .map_name = "cmp_t02",
+               .description = 
+                       "Utilize the twisty turny(TM) piece to split the marble\n"
+                       "stream into two",
+               
+               ._unlock = 2,
+               .is_tutorial = 1,
+       },
+       // r1
+       {
+               .serial_id = 2,
+               .title = "PRINCIPLE 3",
+               .map_name = "cmp_t03",
+               .description = 
+                       "Merge transport into one",
+               
+               ._unlock = 12,
+               .is_tutorial = 1
+       },
+       // r1
+       {
+               .serial_id = 12,
+               .title = "PRINCIPLE 4",
+               .map_name = "cmp_t04",
+               .description = 
+                       "Some stages require multiple runs to succeed in order to\n" 
+                       "pass",
+               
+               ._unlock = 3,
+               .is_tutorial = 1
+       }
+};
+
+static struct cmp_level cmp_levels_basic[] =
+{
+       // r2 GM
+       {
+               .serial_id = 6,
+               .title = "PATCH",
+               .map_name = "cmp_b04",
+               .description = 
+                       "For some reason, the division module our intern built\n"
+                       "for us is sending twice as many yellows as needed. Send\n"
+                       "the excess to be recycled!",
+               
+               ._unlock = 7,
+               ._linked = 3
+       },
+       // r1 GM
+       {
+               .serial_id = 3,
+               .title = "SUBDIVISION 1",
+               .map_name = "cmp_b01",
+               .description = 
+                       "Sometimes getting the desired amount takes dividing up\n"
+                       "the input and recombining it.",
+               
+               ._linked = 4,
+               ._unlock = 5
+       },
+       // r1 GM
+       {
+               .serial_id = 4,
+               .title = "SUBDIVISION 2",
+               .map_name = "cmp_b02",
+               .description = 
+                       "",
+               
+               ._unlock = 7
+       },
+       // r1 GM
+       {
+               .serial_id = 5,
+               .title = "RESTRUCTURE",
+               .map_name = "cmp_b03",
+               .description = 
+                       "It is possible to swap these values using simple\n"
+                       "division and addition.",
+               
+               ._unlock = 8
+       },
+       // r2 GM
+       {
+               .serial_id = 7,
+               .title = "PATTERNS 1",
+               .map_name = "cmp_b05",
+               .description = 
+                       "Replicate",
+               
+               ._linked = 8
+       },
+       // r2 GM
+       {
+               .serial_id = 8,
+               .title = "PATTERNS 2",
+               .map_name = "cmp_b06",
+               .description = 
+                       "Replicate MORE",
+               
+               ._unlock = 15
+       },
+       // r2 GM
+       {
+               .serial_id = 15,
+               .title = "PRINCIPLE 5",
+               .map_name = "cmp_b10",
+               .description = 
+                       "The eager engineers among you may have already spotted\n" 
+                       "and utilized these parts of the system\n"
+                       "\n"
+                       "We forgot to include the relevant principle tasks as\n"
+                       "of your training package, you will now be tasked to\n"
+                       "complete them",
+
+               ._unlock = 16,
+               .is_tutorial = 1
+       },
+       // r2 GM
+       {
+               .serial_id = 16,
+               .title = "ROUTING PROBLEM",
+               .map_name = "cmp_routing",
+               .description = 
+                       "Things can get a little chaotic on tight boards, do your\n"
+                       "best to utilize principle 5 to get the job done\n",
+               
+               ._linked = 9
+       },
+       // r2 GM
+       {
+               .serial_id = 9,
+               .title = "MIGHTY CONSUMER",
+               .map_name = "cmp_b07",
+               .description = 
+                       "Build a greedy system",
+               
+               ._linked = 10,
+               ._unlock = 11
+       },
+       {
+               .serial_id = 10,
+               .title = "SHIFT",
+               .map_name = "cmp_b08",
+               .description = 
+                       "",
+
+               ._unlock = 17
+       },
+       // r2 GM
+       {
+               .serial_id = 11,
+               .title = "REVERSE",
+               .map_name = "cmp_b09",
+               .description = 
+                       "Reverse the incoming order. Always length 4",
+               
+               ._unlock = 17
+       },
+       // r2 GM
+       {
+               .serial_id = 17,
+               .title = "PRINCIPLE 6",
+               .map_name = "cmp_b11",
+               .description =
+                       "Usually the splitter piece will flip flop between left\n"
+                       "and right, however it can be forced to only rotate in\n"
+                       "one direction if trigger wires are attached.\n"
+                       "\n"
+                       "Right click and drag from a regular block, and attach it\n"
+                       "to a splitter. This creates a trigger.\n"
+                       "The default state is left, and once a marble hits the\n"
+                       "trigger it will switch to rotating that direction.",
+
+               ._unlock = 18,
+               .is_tutorial = 1
+       },
+       // r2 GM
+       {
+               .serial_id = 18,
+               .title = "NOT GATE",
+               .map_name = "cmp_not",
+               .description = 
+                       "Test your knowledge of triggers, build an 'NOT GATE'\n"
+                       "emulated by marble logic.",
+               
+               ._linked = 19,
+               ._unlock = 20
+       },
+       // r2 GM
+       {
+               .serial_id = 19,
+               .title = "AND GATE",
+               .map_name = "cmp_and",
+               .description = 
+                       "A slightly more complicated gate, but shouldn't be\n"
+                       "too difficult for your skillset.",
+               
+               ._unlock = 20
+       },
+       // r2 GM
+       {
+               .serial_id = 20,
+               .title = "QUALIFICATION PROJECT",
+               .map_name = "cmp_xor",
+               .description =  
+                       "Significantly more complicated than an AND or NOT gate,\n"
+                       "but possible.",
+
+               ._unlock = 13
+       }
+};
+
+static struct cmp_level cmp_levels_grad[] =
+{
+       // r2
+       {
+               .serial_id = 13,
+               .title = "SORT",
+               .map_name = "cmp_i01",
+               .description = 
+                       "Device a scheme to filter and sort the inputs. If you\n"
+                       "believe you lack the tools required to solve this one,\n"
+                       "take a harder look at the inputs.",
+               ._linked = 14
+               
+       },
+       // r2
+       {
+               .serial_id = 14,
+               .title = "THIRDS",
+               .map_name = "cmp_i02",
+               .description = 
+                       "Split the inputs up into a third of their values\n"
+                       "\n"
+                       "Is this possible? -HG",
+               ._linked = 21
+               
+       },
+       // r2 GM
+       {
+               .serial_id = 21,
+               .title = "SIMPLE ADDITION",
+               .map_name = "cmp_grad",
+               .description = 
+                       "Take the amount of yellows coming in, and add them\n"
+                       "together. Send your result using the stream of blues.",
+
+               ._linked = 22
+       },
+       // r2 GM
+       {
+               .serial_id = 22,
+               .title = "SECRET CODE",
+               .map_name = "cmp_secret",
+               .description = 
+                       ""
+       }
+};
+
+#define NUM_CAMPAIGN_LEVELS (vg_list_size( cmp_levels_tutorials ) + vg_list_size( cmp_levels_basic ) + vg_list_size( cmp_levels_grad ))
+
+static struct serializable_set 
+{
+       struct cmp_level *pack;
+       int count;
+} 
+career_serializable[] =
+{
+       {
+               .pack = cmp_levels_tutorials,
+               .count = vg_list_size( cmp_levels_tutorials )
+       },
+       {
+               .pack = cmp_levels_basic,
+               .count = vg_list_size( cmp_levels_basic )
+       },
+       {
+               .pack = cmp_levels_grad,
+               .count = vg_list_size( cmp_levels_grad )
+       }
+};
+
+// Setup pointers and that
+static void career_local_data_init(void)
+{
+       struct cmp_level *level_ptrs[ NUM_CAMPAIGN_LEVELS ];
+       
+       // COllect pointers
+       for( int i = 0; i < vg_list_size( career_serializable ); i ++ )
+       {
+               struct serializable_set *set = &career_serializable[i];
+               
+               for( int j = 0; j < set->count; j ++ )
+                       level_ptrs[ set->pack[j].serial_id ] = &set->pack[j];
+       }
+       
+       // Apply
+       for( int i = 0; i < vg_list_size( career_serializable ); i ++ )
+       {
+               struct serializable_set *set = &career_serializable[i];
+               
+               for( int j = 0; j < set->count; j ++ )
+               {
+                       struct cmp_level *lvl = &set->pack[j];
+                       lvl->unlock = lvl->_unlock? level_ptrs[ lvl->_unlock ]: NULL;
+                       lvl->linked = lvl->_linked? level_ptrs[ lvl->_linked ]: NULL;
+               }
+       }
+}
diff --git a/maps/cmp_and.map b/maps/cmp_and.map
new file mode 100644 (file)
index 0000000..cd48389
--- /dev/null
@@ -0,0 +1,10 @@
+#############;
+######-######;::c
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+###+##+##+###;a::a,:a:a,c:c:c
+#############;
diff --git a/maps/cmp_b01.map b/maps/cmp_b01.map
new file mode 100644 (file)
index 0000000..9c548b3
--- /dev/null
@@ -0,0 +1,10 @@
+#############;
+###-#####-###;a,aaa
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+######+######;aaaa
+#############;
diff --git a/maps/cmp_b02.map b/maps/cmp_b02.map
new file mode 100644 (file)
index 0000000..013f900
--- /dev/null
@@ -0,0 +1,13 @@
+###############;
+####-##-##-####;aaaaaa,a,a
+##           ##;
+##           ##;
+##           ##;
+#### ##### ####;
+###         ###;
+###         ###;
+###         ###;
+###         ###;
+###         ###;
+#######+#######;aaaaaaaa
+###############;
diff --git a/maps/cmp_b03.map b/maps/cmp_b03.map
new file mode 100644 (file)
index 0000000..3fa19dc
--- /dev/null
@@ -0,0 +1,10 @@
+#############;
+###-#####-###;aaa,aa
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+###+#####+###;aa,aaa
+#############;
diff --git a/maps/cmp_b04.map b/maps/cmp_b04.map
new file mode 100644 (file)
index 0000000..0f3ec63
--- /dev/null
@@ -0,0 +1,12 @@
+#############;
+######-######;aac
+##         ##;
+###       ###;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+###       ###;
+##         ##;
+######+######;aacc
+#############;
diff --git a/maps/cmp_b05.map b/maps/cmp_b05.map
new file mode 100644 (file)
index 0000000..c3022e2
--- /dev/null
@@ -0,0 +1,12 @@
+#############;
+######-######;abab
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+###+#####+###;aa,bb
+#############;
diff --git a/maps/cmp_b06.map b/maps/cmp_b06.map
new file mode 100644 (file)
index 0000000..df94449
--- /dev/null
@@ -0,0 +1,14 @@
+#################;
+#######-#########;abccba
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+####+###+###+####;aa,bb,cc
+#################;
diff --git a/maps/cmp_b07.map b/maps/cmp_b07.map
new file mode 100644 (file)
index 0000000..915a949
--- /dev/null
@@ -0,0 +1,14 @@
+#################;
+##-##-##-##-##-##;aaa,a,aaaaa,aa,aaa
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##     ###     ##;
+##     ###     ##;
+##             ##;
+##             ##;
+##             ##;
+##             ##;
+##+##+#+#+#+##+##;aa,aaaa,aa,a,aaaa,a
+#################;
diff --git a/maps/cmp_b08.map b/maps/cmp_b08.map
new file mode 100644 (file)
index 0000000..b08e0bd
--- /dev/null
@@ -0,0 +1,13 @@
+###############;
+#####-#########;cdab:acaa:bcbc
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+#########+#####;abcd:aaac:bcbc
+###############;
diff --git a/maps/cmp_b09.map b/maps/cmp_b09.map
new file mode 100644 (file)
index 0000000..7e2c727
--- /dev/null
@@ -0,0 +1,13 @@
+###############;
+####-##########;abcb:ccaa
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##########+####;bcba:aacc
+###############;
diff --git a/maps/cmp_b10.map b/maps/cmp_b10.map
new file mode 100644 (file)
index 0000000..dcdf667
--- /dev/null
@@ -0,0 +1,7 @@
+###########;
+##-########;ab
+##   #   ##;
+##   #   ##;
+##   #   ##;
+########+##;ab
+###########;
diff --git a/maps/cmp_b11.map b/maps/cmp_b11.map
new file mode 100644 (file)
index 0000000..5154c5e
--- /dev/null
@@ -0,0 +1,5 @@
+###########;
+##-#####-##;a,aa
+##       ##;
+#####+#####;aaa
+###########;
diff --git a/maps/cmp_grad.map b/maps/cmp_grad.map
new file mode 100644 (file)
index 0000000..dbd51c0
--- /dev/null
@@ -0,0 +1,18 @@
+#####################;
+##########-##########;cccc:cccc:ccc:cc
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+####+##+########+####;a:aa:aa:a,aaa:aa:a:a,cccc:cccc:cccc:cccc
+#####################;
diff --git a/maps/cmp_i01.map b/maps/cmp_i01.map
new file mode 100644 (file)
index 0000000..07ab324
--- /dev/null
@@ -0,0 +1,16 @@
+################;
+####-######-####;aa:a:a:aa,bbb:bbb:bb:bbbb
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+##            ##;
+###+#######+####;aa:bbb:bb:aa,bbb:a:a:bbbb
+################;
diff --git a/maps/cmp_i02.map b/maps/cmp_i02.map
new file mode 100644 (file)
index 0000000..9794f43
--- /dev/null
@@ -0,0 +1,19 @@
+#####################;
+#######-##-##-#######;a:aa:aaa,a:aa:aaa,a:aa:aaa
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##########+##########;aaa:aaaaaa:aaaaaaaaa
+#####################;
diff --git a/maps/cmp_not.map b/maps/cmp_not.map
new file mode 100644 (file)
index 0000000..4bb2855
--- /dev/null
@@ -0,0 +1,8 @@
+#############;
+######-######;:c:
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+####+###+####;a::a,c:c:c
+#############;
diff --git a/maps/cmp_routing.map b/maps/cmp_routing.map
new file mode 100644 (file)
index 0000000..ead3b05
--- /dev/null
@@ -0,0 +1,16 @@
+###################;
+####-#########-####;bbbb,aaaa
+## #  #######    ##;
+##    #######  # ##;
+## #  ##   ##  # ##;
+## ####     #### ##;
+## #  ####  #  ####;
+####  ##-#+##  #-##;dddd,dddd,cccc
+##    #  ####    ##;
+##    #     #    ##;
+##+#####   ########;cccc
+####   #####   # ##;
+##             # ##;
+## #           # ##;
+#####+#######+#####;aaaa,bbbb
+###################;
diff --git a/maps/cmp_secret.map b/maps/cmp_secret.map
new file mode 100644 (file)
index 0000000..c2801e0
--- /dev/null
@@ -0,0 +1,18 @@
+#####################;
+##########-##########;:c::
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+##                 ##;
+####+###########+####;aa a:a aa:a a :aaaa,c:c:c:c
+#####################;
diff --git a/maps/cmp_t01.map b/maps/cmp_t01.map
new file mode 100644 (file)
index 0000000..76b32b8
--- /dev/null
@@ -0,0 +1,8 @@
+#########;
+###-#####;aa
+##     ##;
+##     ##;
+##     ##;
+##     ##;
+#####+###;aa
+#########;
diff --git a/maps/cmp_t02.map b/maps/cmp_t02.map
new file mode 100644 (file)
index 0000000..5d06111
--- /dev/null
@@ -0,0 +1,9 @@
+#########;
+##-###-##;b,b
+##     ##;
+##     ##;
+##     ##;
+##     ##;
+##     ##;
+####+####;bb
+#########;
diff --git a/maps/cmp_t03.map b/maps/cmp_t03.map
new file mode 100644 (file)
index 0000000..46cc4e7
--- /dev/null
@@ -0,0 +1,8 @@
+###########;
+#####-#####;bbbbb
+##       ##;
+##      ###;
+##  #    ##;
+##       ##;
+###+##+####;bbb,bb
+###########;
diff --git a/maps/cmp_t04.map b/maps/cmp_t04.map
new file mode 100644 (file)
index 0000000..48bcc5b
--- /dev/null
@@ -0,0 +1,10 @@
+#############;
+###-#####-###;a:aa,b:bb
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+######+######;ab:abab
+#############;
diff --git a/maps/cmp_xor.map b/maps/cmp_xor.map
new file mode 100644 (file)
index 0000000..1cf622c
--- /dev/null
@@ -0,0 +1,12 @@
+#############;
+######-######;:c:c:
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+##         ##;
+###+##+###+##;::a:a,:a::a,c:c:c:c
+#############;
diff --git a/maps/level0.map b/maps/level0.map
deleted file mode 100644 (file)
index e5dc410..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-#########;
-###-#####;acac
-##     ##;
-##     ##;
-##     ##;
-##     ##;
-#####+###;acac
-#########;
diff --git a/maps/level1.map b/maps/level1.map
deleted file mode 100644 (file)
index 5d06111..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-#########;
-##-###-##;b,b
-##     ##;
-##     ##;
-##     ##;
-##     ##;
-##     ##;
-####+####;bb
-#########;
diff --git a/maps/level2.map b/maps/level2.map
deleted file mode 100644 (file)
index 46cc4e7..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-###########;
-#####-#####;bbbbb
-##       ##;
-##      ###;
-##  #    ##;
-##       ##;
-###+##+####;bbb,bb
-###########;
diff --git a/maps/level3.map b/maps/level3.map
deleted file mode 100644 (file)
index 9c548b3..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-#############;
-###-#####-###;a,aaa
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-######+######;aaaa
-#############;
diff --git a/maps/level4.map b/maps/level4.map
deleted file mode 100644 (file)
index 3fa19dc..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-#############;
-###-#####-###;aaa,aa
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-###+#####+###;aa,aaa
-#############;
diff --git a/maps/sort.map b/maps/sort.map
deleted file mode 100644 (file)
index 07ab324..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-################;
-####-######-####;aa:a:a:aa,bbb:bbb:bb:bbbb
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-##            ##;
-###+#######+####;aa:bbb:bb:aa,bbb:a:a:bbbb
-################;
diff --git a/maps/spam.map b/maps/spam.map
new file mode 100644 (file)
index 0000000..1ce9c7c
--- /dev/null
@@ -0,0 +1,13 @@
+###############;
+#####-#########;abab
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+##           ##;
+###+#+#+#+#+###;abab,cccc,ccaa,aabb,bbbb
+###############;
diff --git a/maps/thirds.map b/maps/thirds.map
deleted file mode 100644 (file)
index ab14e51..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-#############;
-###-##-##-###;a:aa:aaa,a:aa:aaa,a:aa:aaa
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-##         ##;
-######+######;aaa:aaaaaa:aaaaaaaaa
-#############;
diff --git a/sound/click_a.ogg b/sound/click_a.ogg
new file mode 100644 (file)
index 0000000..9ed767a
Binary files /dev/null and b/sound/click_a.ogg differ
diff --git a/sound/click_b.ogg b/sound/click_b.ogg
new file mode 100644 (file)
index 0000000..174be87
Binary files /dev/null and b/sound/click_b.ogg differ
diff --git a/sound/click_c.ogg b/sound/click_c.ogg
new file mode 100644 (file)
index 0000000..4c8d73e
Binary files /dev/null and b/sound/click_c.ogg differ
index 6a79597a91613f1cf170335440daeca69e6fda67..7243b8bf7ffb01859fd4e1cacb72c8bd6f706a1c 100644 (file)
Binary files a/sound/rolling_01.ogg and b/sound/rolling_01.ogg differ
index a145fbd109907a77e5648823f9fd6e48377f1ed6..934a353c1b472bea0799d66bff0767d64408ed8e 100644 (file)
Binary files a/sound/splitter_01.ogg and b/sound/splitter_01.ogg differ
diff --git a/textures/ascii.png b/textures/ascii.png
new file mode 100644 (file)
index 0000000..78884ae
Binary files /dev/null and b/textures/ascii.png differ
diff --git a/textures/bnoise.png b/textures/bnoise.png
new file mode 100644 (file)
index 0000000..23b4a8f
Binary files /dev/null and b/textures/bnoise.png differ
diff --git a/textures/buttons.png b/textures/buttons.png
new file mode 100644 (file)
index 0000000..52e9001
Binary files /dev/null and b/textures/buttons.png differ
diff --git a/textures/unkown.png b/textures/unkown.png
new file mode 100644 (file)
index 0000000..b26c041
Binary files /dev/null and b/textures/unkown.png differ
index ac8df5531e9a084d97b35d3d9018dc906b7f6211..b9aef412206d479e92cbf18d464ba1e94c484121 100644 (file)
@@ -17,3 +17,15 @@ static struct axis_binding vg_axis_binds[] =
        { .name = "horizontal", .positive = GLFW_KEY_D,                                         .negative = GLFW_KEY_A },
        { .name = "vertical",   .positive = GLFW_KEY_W,                                         .negative = GLFW_KEY_S }
 };
+
+static struct vg_achievement vg_achievements[] =
+{
+       { .name = "CAN_DO_THAT" },
+       { .name = "TUTORIALS" },
+       { .name = "GRADUATE" },
+       { .name = "BANG" },
+       { .name = "GOOD_ENOUGH" },
+       { .name = "MIGHTY_CONSUMER" },
+       { .name = "SQUEEZE" },
+       { .name = "MASTER_ENGINEER" }
+};
diff --git a/vg/vg.h b/vg/vg.h
index 22cd0a7e3e80bb3fd1a2f41b97c46f97d2bb905c..13f3d63f00a8b8364db9f03441eb719ce3710151 100644 (file)
--- a/vg/vg.h
+++ b/vg/vg.h
@@ -35,8 +35,12 @@ m3x3f vg_pv;
 
 // Engine globals
 GLFWwindow* vg_window;
-int vg_window_x = 1280;
-int vg_window_y = 720;
+
+// 1366, 768
+// 1920, 1080
+
+int vg_window_x = 1366;
+int vg_window_y = 768;
 
 v2f vg_mouse;
 v3f vg_mouse_ws;
@@ -55,7 +59,7 @@ float vg_time_delta;
 #include "vg/vg_console.h"
 #include "vg/vg_debug.h"
 
-#include "steam/steamworks_thin.h"
+#include "vg/vg_steamworks.h"
 
 // Engine main
 // ===========================================================================================================
@@ -139,14 +143,8 @@ static void vg_init( int argc, char *argv[], const char *window_name )
 {
 #ifdef VG_STEAM
        // Initialize steamworks
-       if( !sw_init( 1218140U ) )
-       {
-               vg_exiterr( "Steamworks failed to initialize" );
-       }
-       else
-       {
-               vg_register_exit( &sw_SteamAPI_Shutdown, "SteamAPI" );
-       }
+       if( !sw_init() )
+               return;
 #endif
        
        // Context creation
@@ -156,6 +154,7 @@ static void vg_init( int argc, char *argv[], const char *window_name )
        glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
        glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
        glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE );
+       glfwWindowHint( GLFW_RESIZABLE, GLFW_TRUE );
        
        glfwWindowHint( GLFW_SAMPLES, 4 );
        
@@ -239,7 +238,7 @@ static void vg_init( int argc, char *argv[], const char *window_name )
                        glfwPollEvents();
                        
                        #ifdef VG_STEAM
-                       sw_RunSteamEventLoop();
+                       sw_event_loop();
                        #endif
                        
                        vg_time_last = vg_time;
@@ -254,24 +253,14 @@ static void vg_init( int argc, char *argv[], const char *window_name )
                        
                        {
                                ui_begin( &ui_global_ctx, vg_window_x, vg_window_y );
-               
-                               // TODO: Find a more elegent form for this
-                               int mouse_state = 0;
-                               if( vg_get_button( "primary" ) ) mouse_state = 2;
-                               if( vg_get_button_down( "primary" ) ) mouse_state = 1;
-                               if( vg_get_button_up( "primary" ) ) mouse_state = 3;
-                                       
-                               ui_set_mouse( &ui_global_ctx, vg_mouse[0], vg_mouse[1], mouse_state );
+                               ui_set_mouse( &ui_global_ctx, vg_mouse[0], vg_mouse[1], vg_get_button_state( "primary" ) );
                                
                                vg_ui();
                                vg_console_draw();
                                vg_debugtools_draw();
                                
                                ui_resolve( &ui_global_ctx );
-                               m3x3f view = M3X3_IDENTITY;
-                               m3x3_translate( view, (v3f){ -1.0f, 1.0f, 0.0f } );
-                               m3x3_scale( view, (v3f){ 1.0f/((float)vg_window_x*0.5f), -1.0f/((float)vg_window_y*0.5f), 1.0f } );     
-                               ui_draw( &ui_global_ctx );
+                               ui_draw( &ui_global_ctx, NULL );
                        }
                        
                        glfwSwapBuffers( vg_window );
index 0c9a666691e64f62f4926041d41f4fc0679e33cf..aefc0fc81cd0693688a125304877a15ae354be39 100644 (file)
@@ -625,20 +625,14 @@ static void sfx_set_init( sfx_set *dest, char *sources )
                sfx_set_strings( dest, sources, dest->flags, 0 );
 }
 
-// Pick a random sound from the buffer and play it into system
-static void sfx_set_playrnd( sfx_set *source, sfx_system *sys, int min_id, int max_id )
+static void sfx_set_play( sfx_set *source, sfx_system *sys, int id )
 {
-       if( !source->numsegments )
-               return;
-
-       int pick = (rand() % (max_id-min_id)) + min_id;
-
        if( sfx_begin_edit( sys ) )
        {
                sys->fadeout = 0;
                sys->source = source->main;
-               sys->cur        = source->segments[ pick*2 + 0 ];
-               sys->end        = source->segments[ pick*2 + 1 ];
+               sys->cur        = source->segments[ id*2 + 0 ];
+               sys->end        = source->segments[ id*2 + 1 ];
                sys->ch                 = source->ch;
                
                // Diagnostics
@@ -650,6 +644,23 @@ static void sfx_set_playrnd( sfx_set *source, sfx_system *sys, int min_id, int m
        }
 }
 
+// Pick a random sound from the buffer and play it into system
+static void sfx_set_playrnd( sfx_set *source, sfx_system *sys, int min_id, int max_id )
+{
+       if( !source->numsegments )
+               return;
+
+       if( max_id > source->numsegments )
+       {
+               vg_error( "Max ID out of range for playrnd\n" );
+               return; 
+       }
+
+       int pick = (rand() % (max_id-min_id)) + min_id;
+       
+       sfx_set_play( source, sys, pick );
+}
+
 static void sfx_system_fadeout( sfx_system *sys, u32 length_samples )
 {
        if( sfx_begin_edit( sys ) )
index 0e974f83b0223e2d87f257a0cd41b7357aa81467..c10abd653fb1cb3fc23f611ddaef545c459895fd 100644 (file)
@@ -42,7 +42,7 @@ struct vg_console
        int enabled;
        int scale;
 }
-vg_console = { .scale = 1 };
+vg_console = { .scale = 2 };
 
 static int vg_console_enabled(void) { return vg_console.enabled; }
 
@@ -80,7 +80,7 @@ static void vg_console_draw( void )
                
                for( int i = 0; i < vg_console.len; i ++ )
                {
-                       ui_text( &ui_global_ctx, vg_console.lines[ptr], vg_console.scale, 0 );
+                       ui_text( &ui_global_ctx, vg_console.lines[ptr], vg_console.scale*2, 0 );
                        ui_global_ctx.cursor[1] -= 8*vg_console.scale;
                
                        ptr --;
@@ -97,13 +97,13 @@ static void vg_console_draw( void )
        {
                ui_fill_rect( &ui_global_ctx, ui_global_ctx.cursor, 0x77333333 );
                
-               ui_text( &ui_global_ctx, vg_console.input, vg_console.scale, 0 );
+               ui_text( &ui_global_ctx, vg_console.input, vg_console.scale*2, 0 );
                
                int start = VG_MIN( vg_console.cursor_pos, vg_console.cursor_user ),
                         end   = VG_MAX( vg_console.cursor_pos, vg_console.cursor_user );
                
-               ui_global_ctx.cursor[0] = start * 6 * vg_console.scale;
-               ui_global_ctx.cursor[2] = (start == end? 1: (end-start)) * 6 * vg_console.scale;
+               ui_global_ctx.cursor[0] = (start * ui_glyph_spacing_x * vg_console.scale)/2 + 2;
+               ui_global_ctx.cursor[2] = (start == end? 0.2f: (float)(end-start)) * (float)ui_glyph_spacing_x * (float)vg_console.scale * 0.5f;
                
                ui_fill_rect( &ui_global_ctx, ui_global_ctx.cursor, 0x66ffffff );
        }
@@ -177,6 +177,9 @@ static void execute_console_input( const char *cmd )
                        {
                                temp[i] = '\0';
                                in_token = 0;
+                               
+                               if( arg_count == vg_list_size( args ) )
+                                       break;
                        }
                        else
                        {
index 62dd4b15b39f381737d9a4f03f42da746541fd0f..6bae274d99cff79a25e39c220a6742463578eb60 100644 (file)
@@ -89,6 +89,14 @@ static inline int vg_get_button_up( const char *button )
        return bind->prev & (bind->value ^ bind->prev) && !vg_console_enabled();
 }
 
+static inline int vg_get_button_state( const char *button )
+{
+       if( vg_get_button_down( button ) ) return 1;
+       if( vg_get_button_up( button ) ) return 3;
+       if( vg_get_button( button ) ) return 2;
+       return 0;
+}
+
 static inline int key_is_keyboard( int const id )
 {
        vg_static_assert( GLFW_MOUSE_BUTTON_LAST < GLFW_KEY_SPACE, "GLFW: Mouse has too many buttons" );
index 9e70c9290ca48d859df9f9c054065c506040df23..6276edb814bdb23bb0b83e036698ebf4b9d9513a 100644 (file)
--- a/vg/vg_m.h
+++ b/vg/vg_m.h
@@ -50,6 +50,26 @@ static inline void v2_copy( v2f a, v2f b )
        b[0] = a[0]; b[1] = a[1];
 }
 
+static inline void v2i_copy( v2i a, v2i b )
+{
+       b[0] = a[0]; b[1] = a[1];
+}
+
+static inline int v2i_eq( v2i a, v2i b )
+{
+       return ((a[0] == b[0]) && (a[1] == b[1]));
+}
+
+static inline void v2i_add( v2i a, v2i b, v2i d )
+{
+       d[0] = a[0]+b[0]; d[1] = a[1]+b[1];
+}
+
+static inline void v2i_sub( v2i a, v2i b, v2i d )
+{
+       d[0] = a[0]-b[0]; d[1] = a[1]-b[1];
+}
+
 static inline void v2_minv( v2f a, v2f b, v2f dest ) 
 {
        dest[0] = vg_minf(a[0], b[0]);
@@ -212,7 +232,7 @@ static inline void v3_normalize( v3f a )
        v3_muls( a, 1.f / v3_length( a ), a );
 }
 
-static inline float csr_lerpf( float a, float b, float t )
+static inline float vg_lerpf( float a, float b, float t )
 {
        return a + t*(b-a);
 }
index 24882841f007746d2d1642538fa904936f6bbda8..b1986b96d088e26732166a5020c6d6c2602e9d60 100644 (file)
@@ -25,6 +25,12 @@ typedef v3f                  boxf[2];
 // Resource types
 typedef struct vg_tex2d vg_tex2d;
 
+struct vg_achievement
+{
+       int is_set;
+       const char *name;
+};
+
 #define vg_static_assert _Static_assert
 
 #define vg_list_size( A ) (sizeof(A)/sizeof(A[0]))
diff --git a/vg/vg_steamworks.h b/vg/vg_steamworks.h
new file mode 100644 (file)
index 0000000..c0baba5
--- /dev/null
@@ -0,0 +1,870 @@
+#if defined(__linux__) || defined(__APPLE__) 
+// The 32-bit version of gcc has the alignment requirement for u64 and double set to
+// 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned.
+// The 64-bit version of gcc has the alignment requirement for these types set to
+// 8 meaning that unless we use #pragma pack(4) our structures will get bigger.
+// The 64-bit structure packing has to match the 32-bit structure packing for each platform.
+ #define VALVE_CALLBACK_PACK_SMALL
+#else
+ #define VALVE_CALLBACK_PACK_LARGE
+#endif
+
+#if defined( VALVE_CALLBACK_PACK_SMALL )
+ #pragma pack( push, 4 )
+#elif defined( VALVE_CALLBACK_PACK_LARGE )
+ #pragma pack( push, 8 )
+#else
+ #error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx
+#endif 
+
+// Types
+typedef void ISteamFriends;
+typedef void ISteamUserStats;
+typedef void ISteamUtils;
+typedef void ISteamUser;
+typedef void ISteamNetworking;
+
+typedef i32    HSteamPipe;
+typedef i32    HSteamUser;
+
+typedef int E_iCallBack_t;
+
+typedef u32 SNetSocket_t;                      // CreateP2PConnectionSocket()
+typedef u32 SNetListenSocket_t;        // CreateListenSocket()
+
+typedef u64    u64_steamid;
+typedef u64 SteamAPICall_t;
+
+enum { k_iSteamUserCallbacks = 100 };
+enum { k_iSteamGameServerCallbacks = 200 };
+enum { k_iSteamFriendsCallbacks = 300 };
+enum { k_iSteamBillingCallbacks = 400 };
+enum { k_iSteamMatchmakingCallbacks = 500 };
+enum { k_iSteamContentServerCallbacks = 600 };
+enum { k_iSteamUtilsCallbacks = 700 };
+enum { k_iClientFriendsCallbacks = 800 };
+enum { k_iClientUserCallbacks = 900 };
+enum { k_iSteamAppsCallbacks = 1000 };
+enum { k_iSteamUserStatsCallbacks = 1100 };
+enum { k_iSteamNetworkingCallbacks = 1200 };
+enum { k_iSteamNetworkingSocketsCallbacks = 1220 };
+enum { k_iSteamNetworkingMessagesCallbacks = 1250 };
+enum { k_iSteamNetworkingUtilsCallbacks = 1280 };
+enum { k_iClientRemoteStorageCallbacks = 1300 };
+enum { k_iClientDepotBuilderCallbacks = 1400 };
+enum { k_iSteamGameServerItemsCallbacks = 1500 };
+enum { k_iClientUtilsCallbacks = 1600 };
+enum { k_iSteamGameCoordinatorCallbacks = 1700 };
+enum { k_iSteamGameServerStatsCallbacks = 1800 };
+enum { k_iSteam2AsyncCallbacks = 1900 };
+enum { k_iSteamGameStatsCallbacks = 2000 };
+enum { k_iClientHTTPCallbacks = 2100 };
+enum { k_iClientScreenshotsCallbacks = 2200 };
+enum { k_iSteamScreenshotsCallbacks = 2300 };
+enum { k_iClientAudioCallbacks = 2400 };
+enum { k_iClientUnifiedMessagesCallbacks = 2500 };
+enum { k_iSteamStreamLauncherCallbacks = 2600 };
+enum { k_iClientControllerCallbacks = 2700 };
+enum { k_iSteamControllerCallbacks = 2800 };
+enum { k_iClientParentalSettingsCallbacks = 2900 };
+enum { k_iClientDeviceAuthCallbacks = 3000 };
+enum { k_iClientNetworkDeviceManagerCallbacks = 3100 };
+enum { k_iClientMusicCallbacks = 3200 };
+enum { k_iClientRemoteClientManagerCallbacks = 3300 };
+enum { k_iClientUGCCallbacks = 3400 };
+enum { k_iSteamStreamClientCallbacks = 3500 };
+enum { k_IClientProductBuilderCallbacks = 3600 };
+enum { k_iClientShortcutsCallbacks = 3700 };
+enum { k_iClientRemoteControlManagerCallbacks = 3800 };
+enum { k_iSteamAppListCallbacks = 3900 };
+enum { k_iSteamMusicCallbacks = 4000 };
+enum { k_iSteamMusicRemoteCallbacks = 4100 };
+enum { k_iClientVRCallbacks = 4200 };
+enum { k_iClientGameNotificationCallbacks = 4300 }; 
+enum { k_iSteamGameNotificationCallbacks = 4400 }; 
+enum { k_iSteamHTMLSurfaceCallbacks = 4500 };
+enum { k_iClientVideoCallbacks = 4600 };
+enum { k_iClientInventoryCallbacks = 4700 };
+enum { k_iClientBluetoothManagerCallbacks = 4800 };
+enum { k_iClientSharedConnectionCallbacks = 4900 };
+enum { k_ISteamParentalSettingsCallbacks = 5000 };
+enum { k_iClientShaderCallbacks = 5100 };
+enum { k_iSteamGameSearchCallbacks = 5200 };
+enum { k_iSteamPartiesCallbacks = 5300 };
+enum { k_iClientPartiesCallbacks = 5400 };
+enum { k_iSteamSTARCallbacks = 5500 };
+enum { k_iClientSTARCallbacks = 5600 };
+enum { k_iSteamRemotePlayCallbacks = 5700 };
+enum { k_iClientCompatCallbacks = 5800 };
+enum { k_iSteamChatCallbacks = 5900 };
+
+// General result codes
+typedef enum EResult
+{
+       k_EResultNone = 0,                                                      // no result
+       k_EResultOK     = 1,                                                    // success
+       k_EResultFail = 2,                                                      // generic failure 
+       k_EResultNoConnection = 3,                                      // no/failed network connection
+//     k_EResultNoConnectionRetry = 4,                         // OBSOLETE - removed
+       k_EResultInvalidPassword = 5,                           // password/ticket is invalid
+       k_EResultLoggedInElsewhere = 6,                         // same user logged in elsewhere
+       k_EResultInvalidProtocolVer = 7,                        // protocol version is incorrect
+       k_EResultInvalidParam = 8,                                      // a parameter is incorrect
+       k_EResultFileNotFound = 9,                                      // file was not found
+       k_EResultBusy = 10,                                                     // called method busy - action not taken
+       k_EResultInvalidState = 11,                                     // called object was in an invalid state
+       k_EResultInvalidName = 12,                                      // name is invalid
+       k_EResultInvalidEmail = 13,                                     // email is invalid
+       k_EResultDuplicateName = 14,                            // name is not unique
+       k_EResultAccessDenied = 15,                                     // access is denied
+       k_EResultTimeout = 16,                                          // operation timed out
+       k_EResultBanned = 17,                                           // VAC2 banned
+       k_EResultAccountNotFound = 18,                          // account not found
+       k_EResultInvalidSteamID = 19,                           // steamID is invalid
+       k_EResultServiceUnavailable = 20,                       // The requested service is currently unavailable
+       k_EResultNotLoggedOn = 21,                                      // The user is not logged on
+       k_EResultPending = 22,                                          // Request is pending (may be in process, or waiting on third party)
+       k_EResultEncryptionFailure = 23,                        // Encryption or Decryption failed
+       k_EResultInsufficientPrivilege = 24,            // Insufficient privilege
+       k_EResultLimitExceeded = 25,                            // Too much of a good thing
+       k_EResultRevoked = 26,                                          // Access has been revoked (used for revoked guest passes)
+       k_EResultExpired = 27,                                          // License/Guest pass the user is trying to access is expired
+       k_EResultAlreadyRedeemed = 28,                          // Guest pass has already been redeemed by account, cannot be acked again
+       k_EResultDuplicateRequest = 29,                         // The request is a duplicate and the action has already occurred in the past, ignored this time
+       k_EResultAlreadyOwned = 30,                                     // All the games in this guest pass redemption request are already owned by the user
+       k_EResultIPNotFound = 31,                                       // IP address not found
+       k_EResultPersistFailed = 32,                            // failed to write change to the data store
+       k_EResultLockingFailed = 33,                            // failed to acquire access lock for this operation
+       k_EResultLogonSessionReplaced = 34,
+       k_EResultConnectFailed = 35,
+       k_EResultHandshakeFailed = 36,
+       k_EResultIOFailure = 37,
+       k_EResultRemoteDisconnect = 38,
+       k_EResultShoppingCartNotFound = 39,                     // failed to find the shopping cart requested
+       k_EResultBlocked = 40,                                          // a user didn't allow it
+       k_EResultIgnored = 41,                                          // target is ignoring sender
+       k_EResultNoMatch = 42,                                          // nothing matching the request found
+       k_EResultAccountDisabled = 43,
+       k_EResultServiceReadOnly = 44,                          // this service is not accepting content changes right now
+       k_EResultAccountNotFeatured = 45,                       // account doesn't have value, so this feature isn't available
+       k_EResultAdministratorOK = 46,                          // allowed to take this action, but only because requester is admin
+       k_EResultContentVersion = 47,                           // A Version mismatch in content transmitted within the Steam protocol.
+       k_EResultTryAnotherCM = 48,                                     // The current CM can't service the user making a request, user should try another.
+       k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed.
+       k_EResultAlreadyLoggedInElsewhere = 50,         // You are already logged in elsewhere, you must wait
+       k_EResultSuspended = 51,                                        // Long running operation (content download) suspended/paused
+       k_EResultCancelled = 52,                                        // Operation canceled (typically by user: content download)
+       k_EResultDataCorruption = 53,                           // Operation canceled because data is ill formed or unrecoverable
+       k_EResultDiskFull = 54,                                         // Operation canceled - not enough disk space.
+       k_EResultRemoteCallFailed = 55,                         // an remote call or IPC call failed
+       k_EResultPasswordUnset = 56,                            // Password could not be verified as it's unset server side
+       k_EResultExternalAccountUnlinked = 57,          // External account (PSN, Facebook...) is not linked to a Steam account
+       k_EResultPSNTicketInvalid = 58,                         // PSN ticket was invalid
+       k_EResultExternalAccountAlreadyLinked = 59,     // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first
+       k_EResultRemoteFileConflict = 60,                       // The sync cannot resume due to a conflict between the local and remote files
+       k_EResultIllegalPassword = 61,                          // The requested new password is not legal
+       k_EResultSameAsPreviousValue = 62,                      // new value is the same as the old one ( secret question and answer )
+       k_EResultAccountLogonDenied = 63,                       // account login denied due to 2nd factor authentication failure
+       k_EResultCannotUseOldPassword = 64,                     // The requested new password is not legal
+       k_EResultInvalidLoginAuthCode = 65,                     // account login denied due to auth code invalid
+       k_EResultAccountLogonDeniedNoMail = 66,         // account login denied due to 2nd factor auth failure - and no mail has been sent
+       k_EResultHardwareNotCapableOfIPT = 67,          // 
+       k_EResultIPTInitError = 68,                                     // 
+       k_EResultParentalControlRestricted = 69,        // operation failed due to parental control restrictions for current user
+       k_EResultFacebookQueryError = 70,                       // Facebook query returned an error
+       k_EResultExpiredLoginAuthCode = 71,                     // account login denied due to auth code expired
+       k_EResultIPLoginRestrictionFailed = 72,
+       k_EResultAccountLockedDown = 73,
+       k_EResultAccountLogonDeniedVerifiedEmailRequired = 74,
+       k_EResultNoMatchingURL = 75,
+       k_EResultBadResponse = 76,                                      // parse failure, missing field, etc.
+       k_EResultRequirePasswordReEntry = 77,           // The user cannot complete the action until they re-enter their password
+       k_EResultValueOutOfRange = 78,                          // the value entered is outside the acceptable range
+       k_EResultUnexpectedError = 79,                          // something happened that we didn't expect to ever happen
+       k_EResultDisabled = 80,                                         // The requested service has been configured to be unavailable
+       k_EResultInvalidCEGSubmission = 81,                     // The set of files submitted to the CEG server are not valid !
+       k_EResultRestrictedDevice = 82,                         // The device being used is not allowed to perform this action
+       k_EResultRegionLocked = 83,                                     // The action could not be complete because it is region restricted
+       k_EResultRateLimitExceeded = 84,                        // Temporary rate limit exceeded, try again later, different from k_EResultLimitExceeded which may be permanent
+       k_EResultAccountLoginDeniedNeedTwoFactor = 85,  // Need two-factor code to login
+       k_EResultItemDeleted = 86,                                      // The thing we're trying to access has been deleted
+       k_EResultAccountLoginDeniedThrottle = 87,       // login attempt failed, try to throttle response to possible attacker
+       k_EResultTwoFactorCodeMismatch = 88,            // two factor code mismatch
+       k_EResultTwoFactorActivationCodeMismatch = 89,  // activation code for two-factor didn't match
+       k_EResultAccountAssociatedToMultiplePartners = 90,      // account has been associated with multiple partners
+       k_EResultNotModified = 91,                                      // data not modified
+       k_EResultNoMobileDevice = 92,                           // the account does not have a mobile device associated with it
+       k_EResultTimeNotSynced = 93,                            // the time presented is out of range or tolerance
+       k_EResultSmsCodeFailed = 94,                            // SMS code failure (no match, none pending, etc.)
+       k_EResultAccountLimitExceeded = 95,                     // Too many accounts access this resource
+       k_EResultAccountActivityLimitExceeded = 96,     // Too many changes to this account
+       k_EResultPhoneActivityLimitExceeded = 97,       // Too many changes to this phone
+       k_EResultRefundToWallet = 98,                           // Cannot refund to payment method, must use wallet
+       k_EResultEmailSendFailure = 99,                         // Cannot send an email
+       k_EResultNotSettled = 100,                                      // Can't perform operation till payment has settled
+       k_EResultNeedCaptcha = 101,                                     // Needs to provide a valid captcha
+       k_EResultGSLTDenied = 102,                                      // a game server login token owned by this token's owner has been banned
+       k_EResultGSOwnerDenied = 103,                           // game server owner is denied for other reason (account lock, community ban, vac ban, missing phone)
+       k_EResultInvalidItemType = 104,                         // the type of thing we were requested to act on is invalid
+       k_EResultIPBanned = 105,                                        // the ip address has been banned from taking this action
+       k_EResultGSLTExpired = 106,                                     // this token has expired from disuse; can be reset for use
+       k_EResultInsufficientFunds = 107,                       // user doesn't have enough wallet funds to complete the action
+       k_EResultTooManyPending = 108,                          // There are too many of this thing pending already
+       k_EResultNoSiteLicensesFound = 109,                     // No site licenses found
+       k_EResultWGNetworkSendExceeded = 110,           // the WG couldn't send a response because we exceeded max network send size
+       k_EResultAccountNotFriends = 111,                       // the user is not mutually friends
+       k_EResultLimitedUserAccount = 112,                      // the user is limited
+       k_EResultCantRemoveItem = 113,                          // item can't be removed
+       k_EResultAccountDeleted = 114,                          // account has been deleted
+       k_EResultExistingUserCancelledLicense = 115,    // A license for this already exists, but cancelled
+       k_EResultCommunityCooldown = 116,                       // access is denied because of a community cooldown (probably from support profile data resets)
+       k_EResultNoLauncherSpecified = 117,                     // No launcher was specified, but a launcher was needed to choose correct realm for operation.
+       k_EResultMustAgreeToSSA = 118,                          // User must agree to china SSA or global SSA before login
+       k_EResultLauncherMigrated = 119,                        // The specified launcher type is no longer supported; the user should be directed elsewhere
+       k_EResultSteamRealmMismatch = 120,                      // The user's realm does not match the realm of the requested resource
+       k_EResultInvalidSignature = 121,                        // signature check did not match
+       k_EResultParseFailure = 122,                            // Failed to parse input
+       k_EResultNoVerifiedPhone = 123,                         // account does not have a verified phone number
+} EResult;
+
+// Structures
+typedef struct {  
+        u32 m_u32;
+    u64 m_u64;
+    u16 m_u16;
+    double m_d;
+} ValvePackingSentinel_t;
+
+typedef struct {
+
+       HSteamUser m_hSteamUser;        // Specific user to whom this callback applies.
+       int m_iCallback;                                // Callback identifier.  (Corresponds to the k_iCallback enum in the callback structure.)
+       u8 *m_pubParam;                 // Points to the callback structure
+       int m_cubParam;                                 // Size of the data pointed to by m_pubParam
+       
+} CallbackMsg_t;
+
+typedef struct {
+
+       SteamAPICall_t m_hAsyncCall;
+       int m_iCallback;
+       u32 m_cubParam;
+       
+} SteamAPICallCompleted_t;
+
+// Steam universes.  Each universe is a self-contained Steam instance.
+typedef enum {
+       k_EUniverseInvalid = 0,
+       k_EUniversePublic = 1,
+       k_EUniverseBeta = 2,
+       k_EUniverseInternal = 3,
+       k_EUniverseDev = 4,
+       // k_EUniverseRC = 5,                           // no such universe anymore
+       k_EUniverseMax
+} EUniverse_t;
+
+typedef struct 
+{
+       // 64 bits total
+       union {
+               struct SteamIDComponent_t
+               {
+#ifdef VALVE_BIG_ENDIAN
+                       EUniverse_t                     m_EUniverse : 8;        // universe this account belongs to
+                       unsigned int            m_EAccountType : 4;                     // type of account - can't show as EAccountType, due to signed / unsigned difference
+                       unsigned int            m_unAccountInstance : 20;       // dynamic instance ID
+                       u32                                     m_unAccountID : 32;                     // unique account identifier
+#else
+                       u32                                     m_unAccountID : 32;                     // unique account identifier
+                       unsigned int            m_unAccountInstance : 20;       // dynamic instance ID
+                       unsigned int            m_EAccountType : 4;                     // type of account - can't show as EAccountType, due to signed / unsigned difference
+                       EUniverse_t                     m_EUniverse : 8;        // universe this account belongs to
+#endif
+               } m_comp;
+
+               u64 m_unAll64Bits;
+       };
+} CSteamID;
+
+typedef struct GameID_t
+{
+#ifdef VALVE_BIG_ENDIAN
+       unsigned int m_nModID : 32;
+       unsigned int m_nType : 8;
+       unsigned int m_nAppID : 24;
+#else
+       unsigned int m_nAppID : 24;
+       unsigned int m_nType : 8;
+       unsigned int m_nModID : 32;
+#endif
+} CGameID;
+
+#define SW_CBID_SteamAPICallCompleted (k_iSteamUtilsCallbacks + 3)
+
+typedef enum ESteamAPICallFailure
+{
+       k_ESteamAPICallFailureNone = -1,                        // no failure
+       k_ESteamAPICallFailureSteamGone = 0,            // the local Steam process has gone away
+       k_ESteamAPICallFailureNetworkFailure = 1,       // the network connection to Steam has been broken, or was already broken
+       // SteamServersDisconnected_t callback will be sent around the same time
+       // SteamServersConnected_t will be sent when the client is able to talk to the Steam servers again
+       k_ESteamAPICallFailureInvalidHandle = 2,        // the SteamAPICall_t handle passed in no longer exists
+       k_ESteamAPICallFailureMismatchedCallback = 3,// GetAPICallResult() was called with the wrong callback type for this API call
+} ESteamAPICallFailure;
+
+typedef u64 UGCHandle_t;
+typedef u64 PublishedFileUpdateHandle_t;
+typedef u64 PublishedFileId_t;
+const PublishedFileId_t k_PublishedFileIdInvalid = 0;
+const UGCHandle_t k_UGCHandleInvalid = 0xffffffffffffffffull;
+const PublishedFileUpdateHandle_t k_PublishedFileUpdateHandleInvalid = 0xffffffffffffffffull;
+
+// Handle for writing to Steam Cloud
+typedef u64 UGCFileWriteStreamHandle_t;
+
+// size limit on stat or achievement name (UTF-8 encoded)
+enum { k_cchStatNameMax = 128 };
+
+// maximum number of bytes for a leaderboard name (UTF-8 encoded)
+enum { k_cchLeaderboardNameMax = 128 };
+
+// maximum number of details i32's storable for a single leaderboard entry
+enum { k_cLeaderboardDetailsMax = 64 };
+
+// handle to a single leaderboard
+typedef u64 SteamLeaderboard_t;
+
+// handle to a set of downloaded entries in a leaderboard
+typedef u64 SteamLeaderboardEntries_t;
+
+// type of data request, when downloading leaderboard entries
+typedef enum ELeaderboardDataRequest
+{
+       k_ELeaderboardDataRequestGlobal = 0,
+       k_ELeaderboardDataRequestGlobalAroundUser = 1,
+       k_ELeaderboardDataRequestFriends = 2,
+       k_ELeaderboardDataRequestUsers = 3
+} ELeaderboardDataRequest;
+
+// the sort order of a leaderboard
+typedef enum ELeaderboardSortMethod
+{
+       k_ELeaderboardSortMethodNone = 0,
+       k_ELeaderboardSortMethodAscending = 1,  // top-score is lowest number
+       k_ELeaderboardSortMethodDescending = 2, // top-score is highest number
+} ELeaderboardSortMethod;
+
+// the display type (used by the Steam Community web site) for a leaderboard
+typedef enum ELeaderboardDisplayType
+{
+       k_ELeaderboardDisplayTypeNone = 0, 
+       k_ELeaderboardDisplayTypeNumeric = 1,                   // simple numerical score
+       k_ELeaderboardDisplayTypeTimeSeconds = 2,               // the score represents a time, in seconds
+       k_ELeaderboardDisplayTypeTimeMilliSeconds = 3,  // the score represents a time, in milliseconds
+} ELeaderboardDisplayType;
+
+typedef enum ELeaderboardUploadScoreMethod
+{
+       k_ELeaderboardUploadScoreMethodNone = 0,
+       k_ELeaderboardUploadScoreMethodKeepBest = 1,    // Leaderboard will keep user's best score
+       k_ELeaderboardUploadScoreMethodForceUpdate = 2, // Leaderboard will always replace score with specified
+} ELeaderboardUploadScoreMethod;
+
+// a single entry in a leaderboard, as returned by GetDownloadedLeaderboardEntry()
+typedef struct LeaderboardEntry_t
+{
+       CSteamID m_steamIDUser; // user with the entry - use SteamFriends()->GetFriendPersonaName() & SteamFriends()->GetFriendAvatar() to get more info
+       i32 m_nGlobalRank;      // [1..N], where N is the number of users with an entry in the leaderboard
+       i32 m_nScore;                   // score as set in the leaderboard
+       i32 m_cDetails;         // number of i32 details available for this entry
+       UGCHandle_t m_hUGC;             // handle for UGC attached to the entry
+} LeaderboardEntry_t;
+
+//-----------------------------------------------------------------------------
+// Purpose: called when the latests stats and achievements have been received
+//                     from the server
+//-----------------------------------------------------------------------------
+typedef struct UserStatsReceived_t
+{
+       u64             m_nGameID;              // Game these stats are for
+       EResult         m_eResult;              // Success / error fetching the stats
+       CSteamID        m_steamIDUser;  // The user for whom the stats are retrieved for
+} UserStatsReceived_t;
+#define SW_CBID_UserStatsReceived (k_iSteamUserStatsCallbacks + 1)
+
+//-----------------------------------------------------------------------------
+// Purpose: result of a request to store the user stats for a game
+//-----------------------------------------------------------------------------
+typedef struct UserStatsStored_t
+{
+       u64             m_nGameID;              // Game these stats are for
+       EResult         m_eResult;              // success / error
+} UserStatsStored_t;
+#define SW_CBID_UserStatsStored (k_iSteamUserStatsCallbacks + 2)
+
+//-----------------------------------------------------------------------------
+// Purpose: result of a request to store the achievements for a game, or an 
+//                     "indicate progress" call. If both m_nCurProgress and m_nMaxProgress
+//                     are zero, that means the achievement has been fully unlocked.
+//-----------------------------------------------------------------------------
+typedef struct UserAchievementStored_t
+{
+       u64             m_nGameID;                              // Game this is for
+       int             m_bGroupAchievement;    // if this is a "group" achievement
+       char            m_rgchAchievementName[k_cchStatNameMax];                // name of the achievement
+       u32             m_nCurProgress;                 // current progress towards the achievement
+       u32             m_nMaxProgress;                 // "out of" this many
+} UserAchievementStored_t;
+#define SW_CBID_UserAchievementStored (k_iSteamUserStatsCallbacks + 3)
+
+//-----------------------------------------------------------------------------
+// Purpose: call result for finding a leaderboard, returned as a result of FindOrCreateLeaderboard() or FindLeaderboard()
+//                     use CCallResult<> to map this async result to a member function
+//-----------------------------------------------------------------------------
+typedef struct LeaderboardFindResult_t
+{
+       SteamLeaderboard_t m_hSteamLeaderboard; // handle to the leaderboard serarched for, 0 if no leaderboard found
+       u8 m_bLeaderboardFound;                         // 0 if no leaderboard found
+} LeaderboardFindResult_t;
+#define SW_CBID_LeaderboardFindResult (k_iSteamUserStatsCallbacks + 4)
+
+//-----------------------------------------------------------------------------
+// Purpose: call result indicating scores for a leaderboard have been downloaded and are ready to be retrieved, returned as a result of DownloadLeaderboardEntries()
+//                     use CCallResult<> to map this async result to a member function
+//-----------------------------------------------------------------------------
+typedef struct LeaderboardScoresDownloaded_t
+{
+       SteamLeaderboard_t m_hSteamLeaderboard;
+       SteamLeaderboardEntries_t m_hSteamLeaderboardEntries;   // the handle to pass into GetDownloadedLeaderboardEntries()
+       int m_cEntryCount; // the number of entries downloaded
+} LeaderboardScoresDownloaded_t;
+#define SW_CBID_LeaderboardScoresDownloaded (k_iSteamUserStatsCallbacks + 5)
+
+//-----------------------------------------------------------------------------
+// Purpose: call result indicating scores has been uploaded, returned as a result of UploadLeaderboardScore()
+//                     use CCallResult<> to map this async result to a member function
+//-----------------------------------------------------------------------------
+typedef struct LeaderboardScoreUploaded_t
+{
+       u8 m_bSuccess;                  // 1 if the call was successful
+       SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was
+       i32 m_nScore;                           // the score that was attempted to set
+       u8 m_bScoreChanged;             // true if the score in the leaderboard change, false if the existing score was better
+       int m_nGlobalRankNew;           // the new global rank of the user in this leaderboard
+       int m_nGlobalRankPrevious;      // the previous global rank of the user in this leaderboard; 0 if the user had no existing entry in the leaderboard
+} LeaderboardScoreUploaded_t;
+#define SW_CBID_LeaderboardScoreUploaded (k_iSteamUserStatsCallbacks + 6)
+
+typedef struct NumberOfCurrentPlayers_t
+{
+       u8 m_bSuccess;                  // 1 if the call was successful
+       i32 m_cPlayers;                 // Number of players currently playing
+} NumberOfCurrentPlayers_t;
+#define SW_CBID_NumberOfCurrentPlayers (k_iSteamUserStatsCallbacks + 7)
+
+
+//-----------------------------------------------------------------------------
+// Purpose: Callback indicating that a user's stats have been unloaded.
+//  Call RequestUserStats again to access stats for this user
+//-----------------------------------------------------------------------------
+typedef struct UserStatsUnloaded_t
+{
+       CSteamID        m_steamIDUser;  // User whose stats have been unloaded
+} UserStatsUnloaded_t;
+#define SW_CBID_UserStatsUnloaded (k_iSteamUserStatsCallbacks + 8)
+
+
+//-----------------------------------------------------------------------------
+// Purpose: Callback indicating that an achievement icon has been fetched
+//-----------------------------------------------------------------------------
+typedef struct UserAchievementIconFetched_t
+{
+       CGameID         m_nGameID;                              // Game this is for
+       char            m_rgchAchievementName[k_cchStatNameMax];                // name of the achievement
+       int             m_bAchieved;            // Is the icon for the achieved or not achieved version?
+       int                     m_nIconHandle;          // Handle to the image, which can be used in SteamUtils()->GetImageRGBA(), 0 means no image is set for the achievement
+} UserAchievementIconFetched_t;
+#define SW_CBID_UserAchievementIconFetched (k_iSteamUserStatsCallbacks + 9)
+
+//-----------------------------------------------------------------------------
+// Purpose: Callback indicating that global achievement percentages are fetched
+//-----------------------------------------------------------------------------
+typedef struct GlobalAchievementPercentagesReady_t
+{
+       u64             m_nGameID;                              // Game this is for
+       EResult         m_eResult;                              // Result of the operation
+} GlobalAchievementPercentagesReady_t;
+#define SW_CBID_GlobalAchievementPercentagesReady (k_iSteamUserStatsCallbacks + 10)
+
+//-----------------------------------------------------------------------------
+// Purpose: call result indicating UGC has been uploaded, returned as a result of SetLeaderboardUGC()
+//-----------------------------------------------------------------------------
+typedef struct LeaderboardUGCSet_t
+{
+       EResult m_eResult;                              // The result of the operation
+       SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was
+} LeaderboardUGCSet_t;
+#define SW_CBID_LeaderboardUGCSet (k_iSteamUserStatsCallbacks + 11)
+
+//-----------------------------------------------------------------------------
+// Purpose: callback indicating that PS3 trophies have been installed
+//-----------------------------------------------------------------------------
+typedef struct PS3TrophiesInstalled_t
+{
+       u64     m_nGameID;                              // Game these stats are for
+       EResult m_eResult;                              // The result of the operation
+       u64 m_ulRequiredDiskSpace;      // If m_eResult is k_EResultDiskFull, will contain the amount of space needed to install trophies
+
+} PS3TrophiesInstalled_t;
+#define SW_CBID_TrophiesInstalled (k_iSteamUserStatsCallbacks + 12)
+
+//-----------------------------------------------------------------------------
+// Purpose: callback indicating global stats have been received.
+//     Returned as a result of RequestGlobalStats()
+//-----------------------------------------------------------------------------
+typedef struct GlobalStatsReceived_t
+{
+       u64     m_nGameID;                              // Game global stats were requested for
+       EResult m_eResult;                              // The result of the request
+} GlobalStatsReceived_t;
+#define SW_CBID_GlobalStatsReceived (k_iSteamUserStatsCallbacks + 12)
+
+#pragma pack( pop )
+
+// API
+void           SteamAPI_Shutdown();
+int            SteamAPI_Init();
+int            SteamAPI_RestartAppIfNecessary( u32 unOwnAppID );
+
+void           SteamAPI_ManualDispatch_Init();
+void           SteamAPI_ManualDispatch_RunFrame( HSteamPipe hSteamPipe );
+int            SteamAPI_ManualDispatch_GetNextCallback( HSteamPipe hSteamPipe, CallbackMsg_t *pCallbackMsg );
+void           SteamAPI_ManualDispatch_FreeLastCallback( HSteamPipe hSteamPipe );
+int            SteamAPI_ManualDispatch_GetAPICallResult( HSteamPipe hSteamPipe, SteamAPICall_t hSteamAPICall, void *pCallback, int cubCallback, int iCallbackExpected, int *pbFailed );
+void           SteamAPI_ReleaseCurrentThreadMemory();
+
+int            SteamAPI_ISteamUserStats_SetAchievement( ISteamUserStats *self, const char *pchName );
+
+ESteamAPICallFailure SteamAPI_ISteamUtils_GetAPICallFailureReason( ISteamUtils* self, SteamAPICall_t hSteamAPICall );
+
+// Friends
+char                                   *SteamAPI_ISteamFriends_GetPersonaName( ISteamFriends *self );
+const char                     *SteamAPI_ISteamFriends_GetFriendPersonaName( ISteamFriends *self, u64_steamid steamIDFriend );
+u64_steamid             SteamAPI_ISteamUser_GetSteamID( ISteamUser *self );
+int                                     SteamAPI_ISteamFriends_GetSmallFriendAvatar( ISteamFriends *self, u64_steamid steamIDFriend ); // 32x32
+int    SteamAPI_ISteamUtils_GetImageSize( ISteamUtils *self, int iImage, u32 *pnWidth, u32 *pnHeight );
+int    SteamAPI_ISteamUtils_GetImageRGBA( ISteamUtils *self, int iImage, u8 *pubDest, int nDestBufferSize );
+
+// Leaderboards
+SteamAPICall_t SteamAPI_ISteamUserStats_FindOrCreateLeaderboard( ISteamUserStats* self, const char * pchLeaderboardName, ELeaderboardSortMethod eLeaderboardSortMethod, ELeaderboardDisplayType eLeaderboardDisplayType );
+SteamAPICall_t SteamAPI_ISteamUserStats_FindLeaderboard( ISteamUserStats* self, const char * pchLeaderboardName );
+const char * SteamAPI_ISteamUserStats_GetLeaderboardName( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard );
+int SteamAPI_ISteamUserStats_GetLeaderboardEntryCount( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard );
+ELeaderboardSortMethod SteamAPI_ISteamUserStats_GetLeaderboardSortMethod( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard );
+ELeaderboardDisplayType SteamAPI_ISteamUserStats_GetLeaderboardDisplayType( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard );
+SteamAPICall_t SteamAPI_ISteamUserStats_DownloadLeaderboardEntries( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard, ELeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd );
+SteamAPICall_t SteamAPI_ISteamUserStats_DownloadLeaderboardEntriesForUsers( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard, CSteamID * prgUsers, int cUsers );
+int SteamAPI_ISteamUserStats_GetDownloadedLeaderboardEntry( ISteamUserStats* self, SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, LeaderboardEntry_t * pLeaderboardEntry, i32 * pDetails, int cDetailsMax );
+SteamAPICall_t SteamAPI_ISteamUserStats_UploadLeaderboardScore( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard, ELeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, i32 nScore, const i32 * pScoreDetails, int cScoreDetailsCount );
+SteamAPICall_t SteamAPI_ISteamUserStats_AttachLeaderboardUGC( ISteamUserStats* self, SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC );
+
+#define sw_get_image_size(...) SteamAPI_ISteamUtils_GetImageSize( steam_api_classes.utils, __VA_ARGS__ )
+#define sw_get_image_rgba(...) SteamAPI_ISteamUtils_GetImageRGBA( steam_api_classes.utils, __VA_ARGS__ )
+#define sw_get_small_friend_avatar(...) SteamAPI_ISteamFriends_GetSmallFriendAvatar( steam_api_classes.friends, __VA_ARGS__ )
+#define sw_get_steamid() SteamAPI_ISteamUser_GetSteamID( steam_api_classes.friends )
+#define sw_get_friend_persona_name(...) SteamAPI_ISteamFriends_GetFriendPersonaName( steam_api_classes.friends, __VA_ARGS__ )
+#define sw_get_persona_name() SteamAPI_ISteamFriends_GetPersonaName( steam_api_classes.friends )
+#define sw_find_leaderboard(...) SteamAPI_ISteamUserStats_FindLeaderboard( steam_api_classes.stats, __VA_ARGS__ );
+#define sw_get_leaderboard_name(...) SteamAPI_ISteamUserStats_GetLeaderboardName( steam_api_classes.stats, __VA_ARGS__ )
+#define sw_download_leaderboard_entries(...) SteamAPI_ISteamUserStats_DownloadLeaderboardEntries( steam_api_classes.stats, __VA_ARGS__ )
+#define sw_get_downloaded_entry(...) SteamAPI_ISteamUserStats_GetDownloadedLeaderboardEntry( steam_api_classes.stats, __VA_ARGS__ )
+#define sw_upload_leaderboard_score(...) SteamAPI_ISteamUserStats_UploadLeaderboardScore( steam_api_classes.stats, __VA_ARGS__ )
+
+HSteamPipe SteamAPI_GetHSteamPipe();
+HSteamUser SteamAPI_GetHSteamUser();
+
+struct
+{
+       ISteamFriends           *friends;
+       ISteamUser                      *user;
+       ISteamUserStats         *stats;
+       ISteamNetworking        *net;
+       ISteamUtils                     *utils;
+       
+       HSteamPipe                      pipe;
+       
+       struct cached_player
+       {
+               u64_steamid id;
+               GLuint          avatar_texture;         // tex_unkown.name
+               
+               struct cached_player *l, *r;
+       }
+       cached_players[20];
+       
+       struct cached_player *cache_head, *cache_tail;
+       
+       u32 cache_count;
+       
+} steam_api_classes;
+
+static void _sw_cache_push( struct cached_player *player )
+{
+       player->l = NULL;
+       player->r = steam_api_classes.cache_head;
+       if( steam_api_classes.cache_head ) steam_api_classes.cache_head->l = player;
+       if( !steam_api_classes.cache_tail ) steam_api_classes.cache_tail = player;
+       steam_api_classes.cache_head = player;
+       steam_api_classes.cache_count ++;
+}
+
+static void _sw_cache_evict( struct cached_player *player )
+{
+       if( player == steam_api_classes.cache_tail ) steam_api_classes.cache_tail = player->l;
+       if( player == steam_api_classes.cache_head ) steam_api_classes.cache_head = player->r;
+       if( player->l ) player->l->r = player->r;
+       if( player->r ) player->r->l = player->l;
+       steam_api_classes.cache_count --;
+}
+
+static void _sw_access_cache( struct cached_player *player )
+{
+       _sw_cache_evict( player );
+       _sw_cache_push( player );
+}
+
+static GLuint sw_get_player_image( u64_steamid usr )
+{
+       // Look for player in cache
+       for( int i = 0; i < steam_api_classes.cache_count; i ++ )
+       {
+               struct cached_player *player = &steam_api_classes.cached_players[i];
+               
+               if( player->id == usr )
+               {
+                       _sw_access_cache( player );
+                       return player->avatar_texture;
+               }
+       }
+       
+       struct cached_player *dest;
+       
+       if( steam_api_classes.cache_count == vg_list_size( steam_api_classes.cached_players ) )
+       {
+               dest = steam_api_classes.cache_tail;
+               _sw_access_cache( dest );
+               
+               // Delete previous before creating a new one
+               glDeleteTextures( 1, &dest->avatar_texture );
+       }
+       else
+       {
+               dest = &steam_api_classes.cached_players[ steam_api_classes.cache_count ];
+               _sw_cache_push( dest );
+       }
+       
+       dest->id = usr;
+       dest->avatar_texture = 0;
+       
+       // Upload new image
+       u32 x = 32, y = 32;
+       int steam_image;
+       
+       steam_image = sw_get_small_friend_avatar( usr );
+       if( !steam_image )
+               return 0;
+               
+       if( !sw_get_image_size( steam_image, &x, &y ) )
+               return 0;
+               
+       u8 * img_buf = (u8 *)malloc( x * y * 4 );
+       
+       if( !sw_get_image_rgba(steam_image, img_buf, x * y * 4) )
+       {
+               free( img_buf );
+               return 0;
+       }
+       
+       glGenTextures( 1, &dest->avatar_texture );
+       glBindTexture( GL_TEXTURE_2D, dest->avatar_texture );
+       
+       glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_buf );
+       glGenerateMipmap( GL_TEXTURE_2D );
+       
+       glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
+       glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+       
+       glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+       glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
+       
+       free( img_buf );
+       
+       return dest->avatar_texture;
+}
+
+ISteamFriends          *SteamAPI_SteamFriends_v017();
+ISteamUser                     *SteamAPI_SteamUser_v021();
+ISteamUserStats        *SteamAPI_SteamUserStats_v012();
+ISteamNetworking       *SteamAPI_SteamNetworking_v006();
+ISteamUtils                    *SteamAPI_SteamUtils_v010();
+
+static void sw_exit(void)
+{
+       SteamAPI_Shutdown();
+}
+
+// Needs to be manually called by client unfortunately
+static void sw_free_opengl(void)
+{
+       for( int i = 0; i < steam_api_classes.cache_count; i ++ )
+               if( steam_api_classes.cached_players[i].avatar_texture )
+                       glDeleteTextures( 1, &steam_api_classes.cached_players[i].avatar_texture );
+}
+
+static int sw_init(void)
+{
+       #if defined(VALVE_CALLBACK_PACK_SMALL)
+       if( sizeof(ValvePackingSentinel_t) != 24 ){
+               printf( "Struct packing error: ValvePackingSentinel_t expected 24 got %i\nThe application is built incorrectly\n", (int)sizeof(ValvePackingSentinel_t));
+               return 0;
+       }
+       #else
+               if( sizeof(ValvePackingSentinel_t) != 32 ){
+                       printf( "Struct packing error: ValvePackingSentinel_t expected 32 got %i\nThe application is built incorrectly\n", (int)sizeof(ValvePackingSentinel_t));
+                       return 0;
+               }
+       #endif
+       
+       vg_info( "Intializing steamworks\n" );
+       
+       if( SteamAPI_RestartAppIfNecessary( VG_STEAM_APPID ) == 1 )
+       {
+               vg_info( "Restarting app via steam\n" );
+               return 0;
+       }
+       
+       if( !SteamAPI_Init() )
+       {
+               vg_error( "Steamworks connection failed\n" );
+               return 0;
+       }
+       
+       SteamAPI_ManualDispatch_Init();
+       
+       steam_api_classes.friends = SteamAPI_SteamFriends_v017();
+       steam_api_classes.user = SteamAPI_SteamUser_v021();
+       steam_api_classes.stats = SteamAPI_SteamUserStats_v012();
+       steam_api_classes.net = SteamAPI_SteamNetworking_v006();
+       steam_api_classes.utils = SteamAPI_SteamUtils_v010();
+       
+       if( !steam_api_classes.friends || !steam_api_classes.user || !steam_api_classes.stats || !steam_api_classes.net || !steam_api_classes.utils )
+       {
+               vg_error( "Steamworks interface pointers failed. Steamworks DLL may be old\n" );
+               SteamAPI_Shutdown();
+               return 0;
+       }
+       
+       steam_api_classes.pipe = SteamAPI_GetHSteamPipe();
+       vg_success( "Steamworks API running\n" );
+       
+       vg_register_exit( &sw_exit, "SteamAPI" );
+       return 1;
+}
+
+
+void (*sw_leaderboard_found)( LeaderboardFindResult_t *pCallback );
+void (*sw_leaderboard_downloaded)( LeaderboardScoresDownloaded_t *pCallback );
+
+static void sw_event_loop(void)
+{
+       SteamAPI_ManualDispatch_RunFrame( steam_api_classes.pipe );
+       CallbackMsg_t callback;
+       
+       while( SteamAPI_ManualDispatch_GetNextCallback( steam_api_classes.pipe, &callback ) )
+       {
+               vg_info( "steamworks_event::callback( %i )\n", callback.m_iCallback );
+       
+               // Check for dispatching API call results
+               if( callback.m_iCallback == SW_CBID_SteamAPICallCompleted ){
+               
+                       SteamAPICallCompleted_t *pCallCompleted = (SteamAPICallCompleted_t *)callback.m_pubParam;
+                       void *pTmpCallResult = malloc( pCallCompleted->m_cubParam );
+                       int bFailed;
+                       
+                       if( SteamAPI_ManualDispatch_GetAPICallResult( 
+                               steam_api_classes.pipe, 
+                               pCallCompleted->m_hAsyncCall, 
+                               pTmpCallResult,
+                               pCallCompleted->m_cubParam, 
+                               pCallCompleted->m_iCallback, 
+                               &bFailed ) 
+                       )
+                       {
+                               // Dispatch the call result to the registered handler(s) for the
+                               // call identified by pCallCompleted->m_hAsyncCall
+                               
+                               vg_info( "steamworks_event::api_call_completed( %lu )\n", pCallCompleted->m_hAsyncCall );
+                               
+                               switch( pCallCompleted->m_iCallback )
+                               {
+                                       case SW_CBID_LeaderboardFindResult:
+                                               if( sw_leaderboard_found ) sw_leaderboard_found( (LeaderboardFindResult_t*)pTmpCallResult );
+                                       break;
+                                       case SW_CBID_LeaderboardScoresDownloaded:
+                                               if( sw_leaderboard_downloaded ) sw_leaderboard_downloaded( (LeaderboardScoresDownloaded_t*)pTmpCallResult );
+                                       break;
+                                       default:break;
+                               }
+                       } 
+                       else 
+                       { 
+                               typedef enum ESteamAPICallFailure
+                               {
+                                       k_ESteamAPICallFailureNone = -1,                        // no failure
+                                       k_ESteamAPICallFailureSteamGone = 0,            // the local Steam process has gone away
+                                       k_ESteamAPICallFailureNetworkFailure = 1,       // the network connection to Steam has been broken, or was already broken
+                                       // SteamServersDisconnected_t callback will be sent around the same time
+                                       // SteamServersConnected_t will be sent when the client is able to talk to the Steam servers again
+                                       k_ESteamAPICallFailureInvalidHandle = 2,        // the SteamAPICall_t handle passed in no longer exists
+                                       k_ESteamAPICallFailureMismatchedCallback = 3,// GetAPICallResult() was called with the wrong callback type for this API call
+                               } ESteamAPICallFailure;
+                       
+                               ESteamAPICallFailure fail_why = 
+                               SteamAPI_ISteamUtils_GetAPICallFailureReason( steam_api_classes.utils, pCallCompleted->m_hAsyncCall );
+                       
+                               vg_error( "steamworks_event: error getting call result on %lu (code %d)\n", pCallCompleted->m_hAsyncCall, fail_why );
+                       }
+                       
+                       free( pTmpCallResult );
+               } 
+               else 
+               {
+                       // Look at callback.m_iCallback to see what kind of callback it is,
+                       // and dispatch to appropriate handler(s)
+                       //void *data = callback.m_pubParam;
+                       
+                       switch( callback.m_iCallback )
+                       {
+                               default: break;
+                       }
+               }
+               
+               SteamAPI_ManualDispatch_FreeLastCallback( steam_api_classes.pipe );
+       }
+}
+
+static void sw_set_achievement( const char *vg_ach_name )
+{
+       struct vg_achievement *ach = NULL;
+       
+       for( int i = 0; i < vg_list_size( vg_achievements ); i ++ )
+               if( !strcmp( vg_ach_name, vg_achievements[i].name ) )
+                       ach = &vg_achievements[i];
+       
+       if( !ach->is_set )
+       {
+               SteamAPI_ISteamUserStats_SetAchievement( steam_api_classes.stats, vg_ach_name );
+               ach->is_set = 1;
+               vg_success( "Achievement set: '%s'\n", vg_ach_name );
+       }
+}
index bf9adc85549d761ecbd833c5df438aa1ad1c3b31..11728509ae0d9ac7fa03feae4fd5a83c39332cd3 100644 (file)
@@ -6,16 +6,22 @@ SHADER_DEFINE( shader_ui,
        "layout (location=0) in vec2 a_co;"                     // i16, i16, .. ?
        "layout (location=1) in vec2 a_uv;"                     // i8, i8
        "layout (location=2) in vec4 a_colour;" // u32
+       "layout (location=3) in vec4 a_clip;"           // i16, i16, i16, i16
        "uniform mat3 uPv;"
        ""
        "out vec2 aTexCoords;"
        "out vec4 aColour;"
+       "out vec2 aWsp;"
+       "out vec4 aClip;"
        ""
        "void main()"
        "{"
                "gl_Position = vec4( uPv * vec3( a_co, 1.0 ), 1.0 );"
-               "aTexCoords = a_uv * 0.01388888888;"
+               "aTexCoords = a_uv * 0.0078125;"
                "aColour = a_colour;"
+               
+               "aWsp = a_co;"
+               "aClip = a_clip;"
        "}",
        
        // FRAGMENT
@@ -25,10 +31,15 @@ SHADER_DEFINE( shader_ui,
        "in vec2 aTexCoords;"
        "in vec4 aColour;"
        ""
+       "in vec2 aWsp;"
+       "in vec4 aClip;"
+       ""
        "void main()"
        "{"
+               "float clip_blend = step( aWsp.x, aClip.z ) * step( aWsp.y, aClip.w ) * step( aClip.x, aWsp.x ) * step( aClip.y, aWsp.y );"
+       
                "vec4 glyph = texture( uTexGlyphs, aTexCoords );"
-               "FragColor = aColour * vec4( 1.0, 1.0, 1.0, glyph.r );"
+               "FragColor = vec4( aColour.rgb * glyph.rgb, aColour.a*glyph.a*clip_blend );"
        "}"
        ,
        UNIFORMS({ "uPv", "uTexGlyphs" })
@@ -44,6 +55,26 @@ typedef i16                          ui_px;
 typedef u32                            ui_colour;
 typedef ui_px                          ui_rect[4];
 typedef struct ui_ctx  ui_ctx;
+typedef struct ui_colourset ui_colourset;
+
+struct ui_colourset
+{
+       union
+       {
+               struct
+               {
+                       ui_colour main;
+                       ui_colour hover;
+                       ui_colour active;
+               };
+               struct
+               {
+                       ui_colour background;
+                       ui_colour bar;
+                       ui_colour bar_hover;
+               };
+       };
+};
 
 struct ui_ctx
 {
@@ -61,49 +92,142 @@ struct ui_ctx
        #pragma pack(push,1)
        struct ui_vert
        {
-               ui_px co[2];
-               u8 uv[2];
-               u32 colour;
+               ui_px co[2];    //32 4
+               u8 uv[2];               //16 2
+               u32 colour;             //32 4
+               ui_rect clip;   //64 8
        }
        *verts;
        #pragma pack(pop)
        
+       u32 override_colour;
+       
        u32 num_verts;
        u16 *indices;
        u32 num_indices;
        
+       ui_rect clipping;
        ui_rect cursor;
        u32 stack_count;
        u32 capture_mouse_id;
        int capture_lock;
        u32 id_base;
+       int glyph_base;
        
        // User input
        ui_px mouse[2];
        int click_state;        // 0: released, 1: on down, 2: pressed, 3: on release
+       
+       ui_colourset *colours_main;
+       ui_colourset *colours_current;
+       
+       GLuint vao;
+       GLuint vbo;
+       GLuint ebo;
+       
+       struct ui_image
+       {
+               ui_rect rc;
+               GLuint image;
+       }
+       images[16];
+       int image_count;
 };
 
 // Globals
 // ===========================================================================================================
 
 // Opengl
-GLuint ui_glyph_texture;
-GLuint ui_vao;
-GLuint ui_vbo;
-GLuint ui_ebo;
-
-#define UI_BUFFER_SIZE 30000
-#define UI_INDEX_SIZE 20000
-
-ui_ctx ui_global_ctx = { .padding = 8 };
+int ui_glyph_override = 0;
+ui_px ui_glyph_spacing_x = 6;
+GLuint ui_glyph_texture = 0;
+
+ui_colourset ui_default_colours = {
+       .main = 0xff00ff00,
+       .hover = 0xffff00ff,
+       .active = 0xffff0000
+};
+ui_ctx ui_global_ctx = { 
+       .padding = 8, 
+       .colours_main = &ui_default_colours
+};
 
 
 // Initialization
 // ===========================================================================================================
 
+static void ui_reset_colours( ui_ctx *ctx );
+static void ui_init_context( ui_ctx *ctx, int index_buffer_size )
+{
+       ui_reset_colours( ctx );
+       
+       u32 vertex_buffer_size = (index_buffer_size+(index_buffer_size/2));
+       
+       // Generate the buffer we are gonna be drawing to
+       {
+               glGenVertexArrays(1, &ctx->vao);
+               glGenBuffers( 1, &ctx->vbo );
+               glGenBuffers( 1, &ctx->ebo );
+               glBindVertexArray( ctx->vao );
+               
+               glBindBuffer( GL_ARRAY_BUFFER, ctx->vbo );
+               
+               glBufferData( GL_ARRAY_BUFFER, vertex_buffer_size * sizeof( struct ui_vert ), NULL, GL_DYNAMIC_DRAW );
+               glBindVertexArray( ctx->vao );
+               
+               glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ctx->ebo );
+               glBufferData( GL_ELEMENT_ARRAY_BUFFER, index_buffer_size * sizeof( u16 ), NULL, GL_DYNAMIC_DRAW );
+               
+               u32 const stride = sizeof( struct ui_vert );
+               
+               // XY
+               glVertexAttribPointer( 0, 2, GL_SHORT, GL_FALSE, stride, (void *)offsetof( struct ui_vert, co ) );
+               glEnableVertexAttribArray( 0 );
+               
+               // UV
+               glVertexAttribPointer( 1, 2, GL_UNSIGNED_BYTE, GL_FALSE, stride, (void *)offsetof( struct ui_vert, uv ) );
+               glEnableVertexAttribArray( 1 );
+               
+               // COLOUR
+               glVertexAttribPointer( 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void *)offsetof( struct ui_vert, colour ) );
+               glEnableVertexAttribArray( 2 );
+               
+               // CLIPPING
+               glVertexAttribPointer( 3, 4, GL_SHORT, GL_FALSE, stride, (void *)offsetof( struct ui_vert, clip ) );
+               glEnableVertexAttribArray( 3 );
+       }
+       
+       // Initialize default context
+       {
+               ctx->verts = (struct ui_vert *)malloc( vertex_buffer_size * sizeof(struct ui_vert) );
+               ctx->indices = (u16*)malloc( index_buffer_size * sizeof(u16) );
+       }
+}
+
+static void ui_context_free( ui_ctx *ctx )
+{
+       glDeleteVertexArrays( 1, &ctx->vao );
+       glDeleteBuffers( 1, &ctx->vbo );
+       glDeleteBuffers( 1, &ctx->ebo );
+       
+       free( ctx->verts );
+       free( ctx->indices );
+}
+
+static void ui_override_font( GLuint new_tex, ui_px space_x )
+{
+       if( ui_glyph_texture )
+               glDeleteTextures( 1, &ui_glyph_texture );
+       
+       ui_glyph_texture = new_tex;
+       ui_glyph_override = 1;
+       ui_glyph_spacing_x = space_x;
+}
+
 static void ui_default_init(void)
 {
-       // Load font
+       // Load default font
+       if( !ui_glyph_override )
        {
                u32 compressed[] = {
                        #include "fonts/weiholmir.h"
@@ -139,65 +263,33 @@ static void ui_default_init(void)
        }
        
        // Setup OpenGL memory
-       {
-               SHADER_INIT( shader_ui );
-               
-               // Generate the buffer we are gonna be drawing to
-               glGenVertexArrays(1, &ui_vao);
-               glGenBuffers( 1, &ui_vbo );
-               glGenBuffers( 1, &ui_ebo );
-               glBindVertexArray( ui_vao );
-               
-               glBindBuffer( GL_ARRAY_BUFFER, ui_vbo );
-               
-               glBufferData( GL_ARRAY_BUFFER, UI_BUFFER_SIZE * sizeof( struct ui_vert ), NULL, GL_DYNAMIC_DRAW );
-               glBindVertexArray( ui_vao );
-               
-               glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ui_ebo );
-               glBufferData( GL_ELEMENT_ARRAY_BUFFER, UI_INDEX_SIZE * sizeof( u16 ), NULL, GL_DYNAMIC_DRAW );
-               
-               u32 const stride = sizeof( struct ui_vert );
-               
-               // XY
-               glVertexAttribPointer( 0, 2, GL_UNSIGNED_SHORT, GL_FALSE, stride, (void *)offsetof( struct ui_vert, co ) );
-               glEnableVertexAttribArray( 0 );
-               
-               // UV
-               glVertexAttribPointer( 1, 2, GL_UNSIGNED_BYTE, GL_FALSE, stride, (void *)offsetof( struct ui_vert, uv ) );
-               glEnableVertexAttribArray( 1 );
-               
-               // COLOUR
-               glVertexAttribPointer( 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void *)offsetof( struct ui_vert, colour ) );
-               glEnableVertexAttribArray( 2 );
-       }
-       
-       // Initialize default context
-       {
-               ui_global_ctx.verts = (struct ui_vert *)malloc( UI_BUFFER_SIZE * sizeof(struct ui_vert) );
-               ui_global_ctx.indices = (u16*)malloc( UI_INDEX_SIZE * sizeof(u16) );
-       }
+       SHADER_INIT( shader_ui );
+       ui_init_context( &ui_global_ctx, 20000 );
 }
 
 static void ui_default_free(void)
 {
-       glDeleteTextures( 1, &ui_glyph_texture );
+       if( !ui_glyph_override )        
+               glDeleteTextures( 1, &ui_glyph_texture );
        
-       glDeleteVertexArrays( 1, &ui_vao );
-       glDeleteBuffers( 1, &ui_vbo );
-       glDeleteBuffers( 1, &ui_ebo );
-       
-       free( ui_global_ctx.verts );
-       free( ui_global_ctx.indices );
+       ui_context_free( &ui_global_ctx );
 }
 
-static void ui_draw( ui_ctx *ctx )
+static struct ui_vert *ui_fill_rect_uv( ui_ctx *ctx, ui_rect rect, u32 colour, ui_px uv[4] );
+static void ui_draw( ui_ctx *ctx, m3x3f view_override )
 {
-       glBindVertexArray( ui_vao );
+       u32 num_indices_normal = ctx->num_indices;
+       
+       // Append images to back of buffer
+       for( int i = 0; i < ctx->image_count; i ++ )
+               ui_fill_rect_uv( ctx, ctx->images[i].rc, 0xffffffff, (ui_px[4]){0,0,128,128} );
+
+       glBindVertexArray( ctx->vao );
        
-       glBindBuffer( GL_ARRAY_BUFFER, ui_vbo );
+       glBindBuffer( GL_ARRAY_BUFFER, ctx->vbo );
        glBufferSubData( GL_ARRAY_BUFFER, 0, ctx->num_verts * sizeof( struct ui_vert ), ctx->verts );
        
-       glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ui_ebo );
+       glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ctx->ebo );
        glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, 0, ctx->num_indices * sizeof( u16 ), ctx->indices );
        
        glEnable(GL_BLEND);
@@ -207,17 +299,31 @@ static void ui_draw( ui_ctx *ctx )
        SHADER_USE( shader_ui );
        
        m3x3f view = M3X3_IDENTITY;
-       m3x3_translate( view, (v3f){ -1.0f, 1.0f, 0.0f } );
-       m3x3_scale( view, (v3f){ 1.0f/((float)vg_window_x*0.5f), -1.0f/((float)vg_window_y*0.5f), 1.0f } );
-       glUniformMatrix3fv( SHADER_UNIFORM( shader_ui, "uPv" ), 1, GL_FALSE, (float *)view );
+       
+       if( !view_override )
+       {
+               view_override = view;
+       
+               m3x3_translate( view, (v3f){ -1.0f, 1.0f, 0.0f } );
+               m3x3_scale( view, (v3f){ 1.0f/((float)vg_window_x*0.5f), -1.0f/((float)vg_window_y*0.5f), 1.0f } );
+       }
+       
+       glUniformMatrix3fv( SHADER_UNIFORM( shader_ui, "uPv" ), 1, GL_FALSE, (float *)view_override );
        
        glActiveTexture( GL_TEXTURE0 );
        glBindTexture( GL_TEXTURE_2D, ui_glyph_texture );
        glUniform1i( SHADER_UNIFORM( shader_ui, "uTexGlyphs" ), 0 );
        
-       glDrawElements( GL_TRIANGLES, ctx->num_indices, GL_UNSIGNED_SHORT, (void*)(0) );
+       glDrawElements( GL_TRIANGLES, num_indices_normal, GL_UNSIGNED_SHORT, (void*)(0) );
        
-       //vg_info( "Verts: %u, Indices: %u\n", ctx->num_verts, ctx->num_indices );
+       // Draw image elements
+       for( int i = 0; i < ctx->image_count; i ++ )
+       {
+               struct ui_image *img = &ctx->images[i];
+               
+               glBindTexture( GL_TEXTURE_2D, img->image );
+               glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)( (num_indices_normal + 6*i)*sizeof(u16) ) );
+       }
        
        glDisable(GL_BLEND);
 }
@@ -278,8 +384,8 @@ static void ui_new_node( ui_ctx *ctx )
        
        if( parent->mouse_over )
        {
-               if( ctx->mouse[0] >= node->rect[0] && ctx->mouse[0] <= node->rect[0]+node->rect[2] &&
-                        ctx->mouse[1] >= node->rect[1] && ctx->mouse[1] <= node->rect[1]+node->rect[3] )
+               if( ctx->mouse[0] >= node->rect[0] && ctx->mouse[0] < node->rect[0]+node->rect[2] &&
+                        ctx->mouse[1] >= node->rect[1] && ctx->mouse[1] < node->rect[1]+node->rect[3] )
                        node->mouse_over = 1;
                else
                        node->mouse_over = 0;
@@ -380,6 +486,27 @@ static void ui_capture_mouse( ui_ctx *ctx, u32 id )
        }
 }
 
+static int ui_want_mouse( ui_ctx *ctx )
+{
+       return ctx->capture_mouse_id == 0? 0: 1;
+}
+
+static void ui_set_clip( ui_ctx *ctx, ui_rect clip )
+{
+       ctx->clipping[0] = clip[0];
+       ctx->clipping[1] = clip[1];
+       ctx->clipping[2] = clip[0] + clip[2];
+       ctx->clipping[3] = clip[1] + clip[3];
+}
+
+static void ui_release_clip( ui_ctx *ctx )
+{
+       ctx->clipping[0] = -32000;
+       ctx->clipping[1] = -32000;
+       ctx->clipping[2] =  32000;
+       ctx->clipping[3] =  32000;
+}
+
 // Drawing
 // ===========================================================================================================
 
@@ -409,6 +536,11 @@ static struct ui_vert *ui_fill_rect_uv( ui_ctx *ctx, ui_rect rect, u32 colour, u
        u16 ind_start = ctx->num_verts;
        u16 *indices = &ctx->indices[ ctx->num_indices ];
        
+       ui_rect_copy( ctx->clipping, vertices[0].clip );
+       ui_rect_copy( ctx->clipping, vertices[1].clip );
+       ui_rect_copy( ctx->clipping, vertices[2].clip );
+       ui_rect_copy( ctx->clipping, vertices[3].clip );
+       
        indices[0] = ind_start+0;
        indices[1] = ind_start+2;
        indices[2] = ind_start+1;
@@ -425,19 +557,54 @@ static struct ui_vert *ui_fill_rect_uv( ui_ctx *ctx, ui_rect rect, u32 colour, u
 
 static struct ui_vert *ui_fill_rect( ui_ctx *ctx, ui_rect rect, u32 colour )
 {
-       return ui_fill_rect_uv( ctx, rect, colour, (ui_px[4]){ 66, 66, 66, 66 } );
+       return ui_fill_rect_uv( ctx, rect, colour, (ui_px[4]){ 4,124,4,124 } );
 }
 
-static void ui_text( ui_ctx *ctx, const char *str, ui_px scale, int alignment )
+static void ui_text_use_title( ui_ctx *ctx )
+{
+       ctx->glyph_base = 0;
+}
+
+static void ui_text_use_paragraph( ui_ctx *ctx )
+{
+       ctx->glyph_base = 6;
+}
+
+enum text_alignment
+{
+       k_text_alignment_left = 0,
+       k_text_alignment_center,
+       k_text_alignment_right
+};
+
+static ui_px ui_text( ui_ctx *ctx, const char *str, ui_px scale, enum text_alignment alignment )
 {
        ui_rect text_cursor;
 
        text_cursor[0] = ctx->cursor[0];
        text_cursor[1] = ctx->cursor[1];
-       text_cursor[2] = 7*scale;
-       text_cursor[3] = 7*scale;
+       text_cursor[2] = (scale*8)/2;
+       text_cursor[3] = (scale*8)/2;
+
+       u32 current_colour = ctx->override_colour;
 
-       u32 current_colour = 0xffffffff;
+       ui_px offset = 0;
+       if( alignment != k_text_alignment_left )
+       {
+               const char *pch = str;
+               for(;;)
+               {
+                       offset += (ui_glyph_spacing_x*scale)/4;
+                       if( !(*pch) || *pch == '\n' )
+                               break;
+                       pch ++;
+               }
+               
+               if( alignment == k_text_alignment_right )
+                       text_cursor[0] = ctx->cursor[0]+ctx->cursor[2]-offset;
+               else
+                       text_cursor[0] = (ctx->cursor[0]+(ctx->cursor[2]/2))-(offset/2);
+       }
 
        const char *_c = str;
        char c;
@@ -445,7 +612,7 @@ static void ui_text( ui_ctx *ctx, const char *str, ui_px scale, int alignment )
        {
                if( c == '\n' )
                {
-                       text_cursor[1] += 10*scale;
+                       text_cursor[1] += (7*scale)/2;
                        text_cursor[0] = ctx->cursor[0];
                        continue;
                }
@@ -453,13 +620,19 @@ static void ui_text( ui_ctx *ctx, const char *str, ui_px scale, int alignment )
                {
                        u8 glyph_base[2];
                        u8 glyph_index = c - 32;
-                       glyph_base[0] = glyph_index%10;
-                       glyph_base[1] = (glyph_index-glyph_base[0])/10;
-                       
-                       glyph_base[0] *= 7;
-                       glyph_base[1] *= 7;
+                       glyph_base[0] = (glyph_index&0xf);
+                       glyph_base[1] = ctx->glyph_base + ((glyph_index-glyph_base[0])>>4);
+
+                       glyph_base[0] *= 8;
+                       glyph_base[1] *= 8;
                        
-                       ui_fill_rect_uv( ctx, text_cursor, current_colour, (ui_px[4]){glyph_base[0],glyph_base[1],glyph_base[0]+7,glyph_base[1]+7} );
+                       ui_fill_rect_uv( ctx, text_cursor, current_colour, 
+                               (ui_px[4]){
+                                       glyph_base[0],
+                                       128-glyph_base[1],
+                                       glyph_base[0]+8,
+                                       128-(glyph_base[1]+8)
+                               });
                }
                else if( c == '\x1B' )
                {
@@ -496,10 +669,13 @@ static void ui_text( ui_ctx *ctx, const char *str, ui_px scale, int alignment )
                                        break;
                                }
                        }
+                       continue;
                }
                
-               text_cursor[0] += 6*scale;
+               text_cursor[0] += (ui_glyph_spacing_x*scale)/4;
        }
+       
+       return text_cursor[0];
 }
 
 // API control
@@ -519,6 +695,13 @@ static void ui_begin( ui_ctx *ctx, ui_px res_x, ui_px res_y )
        
        ctx->num_verts = 0;
        ctx->num_indices = 0;
+       
+       ui_release_clip( ctx );
+       
+       if( ctx->click_state == 0 )
+               ctx->capture_mouse_id = 0;
+       
+       ctx->image_count = 0;
 }
 
 static void ui_resolve( ui_ctx *ctx )
@@ -555,6 +738,14 @@ struct ui_window
        ui_px drag_offset[2];
 };
 
+enum button_state
+{
+       k_button_released = 0,
+       k_button_start_click,
+       k_button_click,
+       k_button_hold
+};
+
 static int ui_button( ui_ctx *ctx, u32 id )
 {
        ui_new_node( ctx );
@@ -563,20 +754,23 @@ static int ui_button( ui_ctx *ctx, u32 id )
                
                if( ui_hasmouse(ctx) )
                {
-                       ui_fill_rect( ctx, ctx->cursor, 0xffcccccc );
-               
+                       ui_fill_rect( ctx, ctx->cursor, ctx->colours_current->hover );
+                       
                        if( ctx->click_state == 1 )
-                               ctx->capture_lock = 1;
-                       else if( ctx->capture_lock && ctx->click_state == 3 )
                        {
-                               return 1;
+                               ctx->capture_lock = 1;
+                               return k_button_start_click;
                        }
+                       else if( ctx->capture_lock && ctx->click_state == 3 )
+                               return k_button_click;
+                       else if( ctx->capture_lock && ctx->click_state == 2 )
+                               return k_button_hold;
                }
                else
-                       ui_fill_rect( ctx, ctx->cursor, 0xff999999 );
+                       ui_fill_rect( ctx, ctx->cursor, ctx->colours_current->main );
        }
        
-       return 0;
+       return k_button_released;
 }
 
 static int ui_window( ui_ctx *ctx, struct ui_window *window, u32 control_group )
@@ -602,8 +796,6 @@ static int ui_window( ui_ctx *ctx, struct ui_window *window, u32 control_group )
        {
                ui_capture_mouse( ctx, __COUNTER__ );
                
-               //ui_fill_rect( ctx, ctx->cursor, 0xff333333 );
-               
                // Drag bar
                ctx->cursor[3] = 25;            
                ui_new_node( ctx );
@@ -654,99 +846,118 @@ static int ui_window( ui_ctx *ctx, struct ui_window *window, u32 control_group )
        return 1;
 }
 
-static void ui_test(void)
-{
-       /*
-               +------------------------------------------------------+
-               | Central Market                                    [x]|
-               +------+--------------+-+------------------------------+
-               | Buy  | Balance      |#| [filters] [favorites]        |
-               | <>_  | () 2,356     |#|----------------------------+-+
-               |------|--------------|#| [] potion of madness     4 |#| 
-               | Sell | \ Main sword |#|----------------------------|#|
-               | _*^  |--------------|#| [] Balance of time      23 | |
-               |------| * Side arm   |#|----------------------------| |
-               | 235  |--------------| | [] Strength          5,300 | |
-               |      | () Sheild    | |----------------------------| |
-               |      |--------------| | [] Bewilder          2,126 | |
-               |      [ & Spells     ] |----------------------------| |
-               |      |--------------| | [] Eternal flames        6 | |
-               +------+--------------+-+----------------------------+-+
-       */
-
-       ui_begin( &ui_global_ctx, vg_window_x, vg_window_y );
-       
-       // TODO: Find a more elegent form for this
-       int mouse_state = 0;
-       if( vg_get_button( "primary" ) ) mouse_state = 2;
-       if( vg_get_button_down( "primary" ) ) mouse_state = 1;
-       if( vg_get_button_up( "primary" ) ) mouse_state = 3;
-               
-       ui_set_mouse( &ui_global_ctx, vg_mouse[0], vg_mouse[1], mouse_state );
+struct ui_scrollbar
+{
+       int     drag;
+       ui_px drag_offset;
        
-       /*
-       static struct ui_window window =
+       ui_px py;
+       ui_px bar_height;
+       ui_px view_height;
+};
+
+static void ui_scrollbar( ui_ctx *ctx, struct ui_scrollbar *scrollbar, u32 id )
+{
+       scrollbar->view_height = ctx->cursor[3];
+
+       if( scrollbar->drag )
        {
-               .transform = { 20, 20, 500, 350 },
-               .title = "Central Market"
-       };
+               scrollbar->py = ctx->mouse[1]+scrollbar->drag_offset;
+               scrollbar->py = VG_MAX( scrollbar->py, 0 );
+               scrollbar->py = VG_MIN( scrollbar->py, ctx->cursor[3] - scrollbar->bar_height );
+               
+               if( ctx->click_state == 0 || ctx->click_state == 3 )
+                       scrollbar->drag = 0;
+       }
        
-       if( ui_window( &ui_global_ctx, &window, __COUNTER__ ) )
+       ui_new_node( ctx );
        {
-               // Contents
-               //ui_text( &ui_global_ctx, "A slice of heaven. O for awesome, this chocka \nfull cuzzie is as rip-off as a cracker.\nMeanwhile, in behind the bicycle shed, Hercules Morse,\nas big as a horse and Mrs Falani were up to no \ngood with a bunch of crook pikelets. Meanwhile, \nat the black singlet woolshed party, not even au,\nsort your drinking out.", 1, 0 );
-               ui_global_ctx.cursor[2] = 75;
-               ui_fill_y( &ui_global_ctx );
+               ui_fill_rect( ctx, ctx->cursor, ctx->colours_current->background );
+               ui_capture_mouse( ctx, id );
+               
+               ctx->cursor[1] += scrollbar->py;
+               ctx->cursor[3] = scrollbar->bar_height;
                
-               ui_new_node( &ui_global_ctx );
+               ui_new_node( ctx );
                {
-                       ui_global_ctx.cursor[3] = 75;
-                       
-                       if( ui_button( &ui_global_ctx, __COUNTER__ ) )
-                               vg_info( "Buy\n" );
+                       ui_capture_mouse( ctx, __COUNTER__ );
+                       struct ui_vert *drag_bar = ui_fill_rect( ctx, ctx->cursor, ctx->colours_current->bar );
+
+                       if( ui_hasmouse( ctx ) || scrollbar->drag )
                        {
-                               ui_rect_pad( ui_global_ctx.cursor, 4 );
-                               ui_text( &ui_global_ctx, "Buy", 2, 0 );
-                       }
-                       ui_end_down( &ui_global_ctx );
+                               drag_bar[0].colour = ctx->colours_current->bar_hover;
+                               drag_bar[1].colour = ctx->colours_current->bar_hover;
+                               drag_bar[2].colour = ctx->colours_current->bar_hover;
+                               drag_bar[3].colour = ctx->colours_current->bar_hover;
                        
-                       if( ui_button( &ui_global_ctx, __COUNTER__ ) )
-                               vg_info( "Sell\n" );
-                       {
-                               ui_rect_pad( ui_global_ctx.cursor, 4 );
-                               ui_text( &ui_global_ctx, "Sell", 2, 0 );
+                               // start drag
+                               if( ctx->click_state == 1 )
+                               {
+                                       scrollbar->drag = 1;
+                                       scrollbar->drag_offset = scrollbar->py - ctx->mouse[1];
+                               }
                        }
-                       ui_end_down( &ui_global_ctx );
-               }
-               ui_end_right( &ui_global_ctx );
-               
-               ui_global_ctx.cursor[2] = 200;
-               ui_new_node( &ui_global_ctx );
-               {
-               
                }
-               ui_end_right( &ui_global_ctx );
+               ui_end_down( ctx );
        }
-       ui_end( &ui_global_ctx );
-       */
-       
-       ui_rect rbf;
-       ui_rect_copy( ui_global_ctx.cursor, rbf );
-       
-       ui_global_ctx.cursor[0] = 6;
-       ui_global_ctx.cursor[3] = 21;
-       ui_fill_x( &ui_global_ctx );
-       ui_align_bottom( &ui_global_ctx );
-       ui_text( &ui_global_ctx, "Marble computer build 2 -- development version -- (C) Harry Godden 2021\nAknowledgements: 'credits' in console (`)", 1, 0 );
-       
-       ui_resolve( &ui_global_ctx );
-       
-       m3x3f view = M3X3_IDENTITY;
-       m3x3_translate( view, (v3f){ -1.0f, 1.0f, 0.0f } );
-       m3x3_scale( view, (v3f){ 1.0f/((float)vg_window_x*0.5f), -1.0f/((float)vg_window_y*0.5f), 1.0f } );
-       //vg_lines_drawall( (float*)view );
-       
-       ui_draw( &ui_global_ctx );
+       ui_end( ctx );
+}
+
+static ui_px ui_calculate_content_scroll( struct ui_scrollbar *scrollbar, ui_px content )
+{
+       float overlap = vg_maxf( 0.0f, (float)(content - scrollbar->view_height) );
        
-       ui_rect_copy( rbf, ui_global_ctx.cursor );
+       float range = scrollbar->view_height - scrollbar->bar_height;
+       return ((float)scrollbar->py / range) * overlap;
+}
+
+static void ui_override_colours( ui_ctx *ctx, ui_colourset *set )
+{
+       ctx->colours_current = set;
 }
+
+static void ui_reset_colours( ui_ctx *ctx )
+{
+       ctx->colours_current = ctx->colours_main;
+       ctx->override_colour = 0xffffffff;
+}
+
+static void ui_push_image( ui_ctx *ctx, ui_rect rc, GLuint image )
+{
+       struct ui_image *img = &ctx->images[ ctx->image_count ++ ];
+       ui_rect_copy( rc, img->rc );
+       img->image = image;
+}
+
+// Shortnames
+#define gui_draw(...) ui_draw( &ui_global_ctx, __VA_ARGS__)
+#define gui_current(...) ui_current( &ui_global_ctx, __VA_ARGS__)
+#define gui_new_node() ui_new_node( &ui_global_ctx )
+#define gui_hasmouse(...) ui_hasmouse( &ui_global_ctx, __VA_ARGS__)
+#define gui_end() ui_end( &ui_global_ctx )
+#define gui_end_down() ui_end_down( &ui_global_ctx )
+#define gui_end_right() ui_end_right( &ui_global_ctx )
+#define gui_fill_y() ui_fill_y( &ui_global_ctx)
+#define gui_fill_x() ui_fill_x( &ui_global_ctx)
+#define gui_align_bottom() ui_align_bottom( &ui_global_ctx )
+#define gui_align_right() ui_align_right( &ui_global_ctx )
+#define gui_align_top() ui_align_top( &ui_global_ctx )
+#define gui_align_left() ui_align_left( &ui_global_ctx )
+#define gui_clamp_rect(...) ui_clamp_rect( &ui_global_ctx, __VA_ARGS__)
+#define gui_group_id(...) ui_group_id( &ui_global_ctx, __VA_ARGS__)
+#define gui_capture_mouse(...) ui_capture_mouse( &ui_global_ctx, __VA_ARGS__)
+#define gui_set_clip(...) ui_set_clip( &ui_global_ctx, __VA_ARGS__)
+#define gui_release_clip() ui_release_clip( &ui_global_ctx )
+#define gui_fill_rect_uv(...) ui_fill_rect_uv( &ui_global_ctx, __VA_ARGS__)
+#define gui_fill_rect(...) ui_fill_rect( &ui_global_ctx, __VA_ARGS__)
+#define gui_text(...) ui_text( &ui_global_ctx, __VA_ARGS__)
+#define gui_begin(...) ui_begin( &ui_global_ctx, __VA_ARGS__)
+#define gui_resolve(...) ui_resolve( &ui_global_ctx, __VA_ARGS__)
+#define gui_set_mouse(...) ui_set_mouse( &ui_global_ctx, __VA_ARGS__)
+#define gui_button(...) ui_button( &ui_global_ctx, __VA_ARGS__)
+#define gui_window(...) ui_window( &ui_global_ctx, __VA_ARGS__)
+#define gui_want_mouse() ui_want_mouse( &ui_global_ctx )
+#define gui_push_image(...) ui_push_image( &ui_global_ctx, __VA_ARGS__ )
+#define gui_scrollbar(...) ui_scrollbar( &ui_global_ctx, __VA_ARGS__)
+#define gui_override_colours(...) ui_override_colours( &ui_global_ctx, __VA_ARGS__)
+#define gui_reset_colours(...) ui_reset_colours( &ui_global_ctx )