Sound system with metadesk, mono only for now

main
parent de9d55d62c
commit 644161ab16

@ -1,3 +1,7 @@
@sound simple_talk:
{
filepath: "simple_text_chirp.wav",
}
@image merchant:
{
filepath: "copyrighted/merchant.png",

Binary file not shown.

@ -12,4 +12,3 @@
#define BUFF_PUSH_FRONT(buff_ptr, value) { (buff_ptr)->cur_index++; BUFF_VALID(buff_ptr); for(int i = (buff_ptr)->cur_index - 1; i > 0; i--) { (buff_ptr)->data[i] = (buff_ptr)->data[i - 1]; }; (buff_ptr)->data[0] = value; }
#define BUFF_REMOVE_FRONT(buff_ptr) {if((buff_ptr)->cur_index > 0) {for(int i = 0; i < (buff_ptr)->cur_index - 1; i++) { (buff_ptr)->data[i] = (buff_ptr)->data[i+1]; }; (buff_ptr)->cur_index--;}}
#define BUFF_CLEAR(buff_ptr) {memset((buff_ptr), 0, sizeof(*(buff_ptr))); ((buff_ptr)->cur_index = 0);}

@ -252,6 +252,19 @@ int main(int argc, char **argv) {
MD_String8List level_decl_list = {0};
MD_String8List tileset_decls = {0};
for(MD_EachNode(node, parse.node->first_child)) {
if(MD_S8Match(node->first_tag->string, MD_S8Lit("sound"), 0)) {
MD_String8 variable_name = MD_S8Fmt(cg_arena, "sound_%.*s", MD_S8VArg(node->string));
log("New sound variable %.*s\n", MD_S8VArg(variable_name));
MD_String8 filepath = ChildValue(node, MD_S8Lit("filepath"));
filepath = asset_file_path(filepath);
assert_cond(filepath.str != 0, MD_S8Fmt(cg_arena, "No filepath specified for sound '%.*s'", MD_S8VArg(node->string)));
FILE *asset_file = fopen(filepath.str, "r");
assert_cond(asset_file, MD_S8Fmt(cg_arena, "Could not open filepath %.*s for asset '%.*s'", MD_S8VArg(filepath), MD_S8VArg(node->string)));
fclose(asset_file);
MD_S8ListPush(cg_arena, &declarations_list, MD_S8Fmt(cg_arena, "AudioSample %.*s = {0};\n", MD_S8VArg(variable_name)));
MD_S8ListPush(cg_arena, &load_list, MD_S8Fmt(cg_arena, "%.*s = load_wav_audio(\"%.*s\");\n", MD_S8VArg(variable_name), MD_S8VArg(filepath)));
}
if(MD_S8Match(node->first_tag->string, MD_S8Lit("image"), 0)) {
MD_String8 variable_name = MD_S8Fmt(cg_arena, "image_%.*s", MD_S8VArg(node->string));
log("New image variable %.*s\n", MD_S8VArg(variable_name));

529
main.c

@ -13,12 +13,16 @@
#include "sokol_app.h"
#include "sokol_gfx.h"
#include "sokol_time.h"
#include "sokol_audio.h"
#include "sokol_log.h"
#include "sokol_glue.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_truetype.h"
#include "HandmadeMath.h"
#define DR_WAV_IMPLEMENTATION
#include "dr_wav.h"
#pragma warning(disable : 4996) // fopen is safe. I don't care about fopen_s
@ -280,231 +284,61 @@ void make_space_and_append(Dialog *d, DialogElement elem)
BUFF_APPEND(d, elem);
}
void say_characters(Entity *npc, int num_characters)
typedef struct AudioSample
{
Sentence *sentence_to_append_to = &npc->player_dialog.data[npc->player_dialog.cur_index-1].s;
for(int i = 0; i < num_characters; i++)
{
if(!BUFF_EMPTY(&npc->player_dialog) && !BUFF_EMPTY(&npc->sentence_to_say))
{
char new_character = npc->sentence_to_say.data[0];
bool found_matching_star = false;
BUFF(char, MAX_SENTENCE_LENGTH) match_buffer = {0};
if(new_character == '*')
{
for(int ii = sentence_to_append_to->cur_index-1; ii >= 0; ii--)
{
if(sentence_to_append_to->data[ii] == '*')
{
found_matching_star = true;
break;
}
BUFF_PUSH_FRONT(&match_buffer, sentence_to_append_to->data[ii]);
}
}
if(found_matching_star)
{
#if 0 // actions
if(strcmp(match_buffer.data, "fights player") == 0 && npc->npc_kind == OLD_MAN)
{
npc->aggressive = true;
}
if(strcmp(match_buffer.data, "sells grounding boots") == 0 && npc->npc_kind == MERCHANT)
{
player->boots_modifier -= 1;
float *pcm_data; // allocated by loader, must be freed
uint64_t pcm_data_length;
} AudioSample;
}
if(strcmp(match_buffer.data, "sells swiftness boots") == 0 && npc->npc_kind == MERCHANT)
{
player->boots_modifier += 1;
}
if(strcmp(match_buffer.data, "moves") == 0 && npc->npc_kind == DEATH)
{
npc->going_to_target = true;
npc->target_goto = AddV2(npc->pos, V2(0.0, -TILE_SIZE*1.5f));
}
#endif
}
BUFF_APPEND(sentence_to_append_to, new_character);
BUFF_REMOVE_FRONT(&npc->sentence_to_say);
}
}
}
typedef struct AudioPlayer
{
AudioSample *sample; // if not 0, exists
double volume; // ZII, 1.0 + this again
double pitch; // zero initialized, the pitch used to play is 1.0 + this
double cursor_time; // in seconds, current audio sample is cursor_time * sample_rate
} AudioPlayer;
bool npc_is_knight_sprite(Entity *it)
AudioPlayer playing_audio[128] = {0};
#define SAMPLE_RATE 44100
AudioSample load_wav_audio(const char *path)
{
return it->is_npc && ( it->npc_kind == NPC_Max || it->npc_kind == NPC_Hunter || it->npc_kind == NPC_John);
unsigned int channels;
unsigned int sampleRate;
AudioSample to_return = {0};
to_return.pcm_data = drwav_open_file_and_read_pcm_frames_f32(path, &channels, &sampleRate, &to_return.pcm_data_length, 0);
assert(channels == 1);
assert(sampleRate == SAMPLE_RATE);
return to_return;
}
void add_new_npc_sentence(Entity *npc, char *sentence)
uint64_t cursor_pcm(AudioPlayer *p)
{
size_t sentence_len = strlen(sentence);
assert(sentence_len < MAX_SENTENCE_LENGTH);
Sentence new_sentence = {0};
bool inside_star = false;
for(int i = 0; i < sentence_len; i++)
{
if(sentence[i] == '"') break;
if(sentence[i] == '\n') continue;
BUFF_APPEND(&new_sentence, sentence[i]);
}
DialogElement empty_elem = { .author = NPC };
say_characters(npc, npc->sentence_to_say.cur_index);
make_space_and_append(&npc->player_dialog, empty_elem);
npc->sentence_to_say = new_sentence;
return (uint64_t)(p->cursor_time * SAMPLE_RATE);
}
void begin_text_input(); // called when player engages in dialog, must say something and fill text_input_buffer
// a callback, when 'text backend' has finished making text. End dialog
void end_text_input(char *what_player_said)
float float_rand( float min, float max )
{
player->state = CHARACTER_IDLE;
#ifdef WEB // hacky
_sapp_emsc_register_eventhandlers();
#endif
size_t player_said_len = strlen(what_player_said);
int actual_len = 0;
for(int i = 0; i < player_said_len; i++) if(what_player_said[i] != '\n') actual_len++;
if(actual_len == 0)
{
// this just means cancel the dialog
}
else
float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
return min + scale * ( max - min ); /* [min, max] */
}
void play_audio(AudioSample *sample)
{
AudioPlayer *to_use = 0;
for(int i = 0; i < ARRLEN(playing_audio); i++)
{
Sentence what_player_said_sentence = {0};
assert(player_said_len < ARRLEN(what_player_said_sentence.data));
for(int i = 0; i < player_said_len; i++)
if(playing_audio[i].sample == 0)
{
char c = what_player_said[i];
if(c == '\n') break;
BUFF_APPEND(&what_player_said_sentence, c);
to_use = &playing_audio[i];
break;
}
// order is player message, item status message in training data. So has to be same here
Dialog *to_append = &player->talking_to->player_dialog;
Entity *talking = player->talking_to;
make_space_and_append(to_append, (DialogElement){.s = what_player_said_sentence, .author = PLAYER});
if(talking->last_seen_holding != player->holding_item)
{
if(talking->last_seen_holding)
{
Sentence discard = from_str(item_discard_message_table[talking->last_seen_holding->item_kind]);
BUFF_APPEND(&discard, '\n');
make_space_and_append(to_append, (DialogElement){.author = SYSTEM, .s = discard});
assert(talking->last_seen_holding->is_item);
talking->last_seen_holding = 0;
}
if(player->holding_item)
{
assert(player->holding_item->is_item);
Sentence possess = from_str(item_possess_message_table[player->holding_item->item_kind]);
BUFF_APPEND(&possess, '\n');
make_space_and_append(to_append, (DialogElement){.author = SYSTEM, .s = possess});
}
talking->last_seen_holding = player->holding_item;
}
// the npc response will be appended here, or at least be async queued to be appended here
BUFF(char, 4000) prompt_buff = {0};
BUFF(char *, 100) to_join = {0};
assert(talking->npc_kind >= 0);
assert(talking->npc_kind < ARRLEN(prompt_table));
assert(talking->npc_kind < ARRLEN(general_prompt_table));
assert(talking->npc_kind < ARRLEN(name_table));
// general prompt
BUFF_APPEND(&to_join, general_prompt_table[talking->npc_kind]);
BUFF_APPEND(&to_join, "\n");
// item prompt
if(player->holding_item)
{
BUFF_APPEND(&to_join, item_prompt_table[player->holding_item->item_kind]);
BUFF_APPEND(&to_join, "\n");
}
// characters prompt
BUFF_APPEND(&to_join, prompt_table[talking->npc_kind]);
BUFF_APPEND(&to_join, "\n");
char *character_prompt = name_table[talking->npc_kind];
// all the dialog
int i = 0;
BUFF_ITER(DialogElement, &player->talking_to->player_dialog)
{
//bool is_player =
if(it->author == PLAYER)
{
BUFF_APPEND(&to_join, "Player: \"");
}
else if(it->author == NPC)
{
BUFF_APPEND(&to_join, character_prompt);
BUFF_APPEND(&to_join, ": \"");
}
else if(it->author == SYSTEM)
{
}
else
{
assert(false);
}
BUFF_APPEND(&to_join, it->s.data);
if(it->author == PLAYER || it->author == NPC)
BUFF_APPEND(&to_join, "\"\n");
i++;
}
BUFF_APPEND(&to_join, character_prompt);
BUFF_APPEND(&to_join, ": \"");
// concatenate into prompt_buff
BUFF_ITER(char *, &to_join)
{
size_t cur_len = strlen(*it);
for(int i = 0; i < cur_len; i++)
{
BUFF_APPEND(&prompt_buff, (*it)[i]);
}
}
const char * prompt = prompt_buff.data;
#ifdef DEVTOOLS
Log("Prompt: `%s`\n", prompt);
#endif
#ifdef WEB
// fire off generation request, save id
int req_id = EM_ASM_INT({
return make_generation_request(UTF8ToString($1), UTF8ToString($0));
}, SERVER_URL, prompt);
player->talking_to->gen_request_id = req_id;
#endif
#ifdef DESKTOP
if(player->talking_to->npc_kind == NPC_Death)
{
add_new_npc_sentence(player->talking_to, "test *moves* I am death, destroyer of games. Come join me in the afterlife, or continue onwards *moves*");
//add_new_npc_sentence(player->talking_to, "test");
}
if(player->talking_to->npc_kind == NPC_Hunter)
{
add_new_npc_sentence(player->talking_to, "I am hunter");
}
if(player->talking_to->npc_kind == NPC_Max)
{
add_new_npc_sentence(player->talking_to, "I am max");
}
if(player->talking_to->npc_kind == NPC_John)
{
add_new_npc_sentence(player->talking_to, "I am john *gives WhiteSquare*");
}
#endif
}
assert(to_use);
*to_use = (AudioPlayer){0};
to_use->sample = sample;
to_use->volume = -0.5f;
to_use->pitch = float_rand(0.9f, 1.1f);
}
// keydown needs to be referenced when begin text input,
// on web it disables event handling so the button up event isn't received
bool keydown[SAPP_KEYCODE_MENU] = {0};
@ -756,6 +590,7 @@ TileInstance get_tile(Level *l, TileCoord t)
return get_tile_layer(l, 0, t);
}
sg_image load_image(const char *path)
{
sg_image to_return = {0};
@ -791,6 +626,234 @@ sg_image load_image(const char *path)
#include "quad-sapp.glsl.h"
#include "assets.gen.c"
void say_characters(Entity *npc, int num_characters)
{
play_audio(&sound_simple_talk);
Sentence *sentence_to_append_to = &npc->player_dialog.data[npc->player_dialog.cur_index-1].s;
for(int i = 0; i < num_characters; i++)
{
if(!BUFF_EMPTY(&npc->player_dialog) && !BUFF_EMPTY(&npc->sentence_to_say))
{
char new_character = npc->sentence_to_say.data[0];
bool found_matching_star = false;
BUFF(char, MAX_SENTENCE_LENGTH) match_buffer = {0};
if(new_character == '*')
{
for(int ii = sentence_to_append_to->cur_index-1; ii >= 0; ii--)
{
if(sentence_to_append_to->data[ii] == '*')
{
found_matching_star = true;
break;
}
BUFF_PUSH_FRONT(&match_buffer, sentence_to_append_to->data[ii]);
}
}
if(found_matching_star)
{
#if 0 // actions
if(strcmp(match_buffer.data, "fights player") == 0 && npc->npc_kind == OLD_MAN)
{
npc->aggressive = true;
}
if(strcmp(match_buffer.data, "sells grounding boots") == 0 && npc->npc_kind == MERCHANT)
{
player->boots_modifier -= 1;
}
if(strcmp(match_buffer.data, "sells swiftness boots") == 0 && npc->npc_kind == MERCHANT)
{
player->boots_modifier += 1;
}
if(strcmp(match_buffer.data, "moves") == 0 && npc->npc_kind == DEATH)
{
npc->going_to_target = true;
npc->target_goto = AddV2(npc->pos, V2(0.0, -TILE_SIZE*1.5f));
}
#endif
}
BUFF_APPEND(sentence_to_append_to, new_character);
BUFF_REMOVE_FRONT(&npc->sentence_to_say);
}
}
}
bool npc_is_knight_sprite(Entity *it)
{
return it->is_npc && ( it->npc_kind == NPC_Max || it->npc_kind == NPC_Hunter || it->npc_kind == NPC_John);
}
void add_new_npc_sentence(Entity *npc, char *sentence)
{
size_t sentence_len = strlen(sentence);
assert(sentence_len < MAX_SENTENCE_LENGTH);
Sentence new_sentence = {0};
bool inside_star = false;
for(int i = 0; i < sentence_len; i++)
{
if(sentence[i] == '"') break;
if(sentence[i] == '\n') continue;
BUFF_APPEND(&new_sentence, sentence[i]);
}
DialogElement empty_elem = { .author = NPC };
say_characters(npc, npc->sentence_to_say.cur_index);
make_space_and_append(&npc->player_dialog, empty_elem);
npc->sentence_to_say = new_sentence;
}
void begin_text_input(); // called when player engages in dialog, must say something and fill text_input_buffer
// a callback, when 'text backend' has finished making text. End dialog
void end_text_input(char *what_player_said)
{
player->state = CHARACTER_IDLE;
#ifdef WEB // hacky
_sapp_emsc_register_eventhandlers();
#endif
size_t player_said_len = strlen(what_player_said);
int actual_len = 0;
for(int i = 0; i < player_said_len; i++) if(what_player_said[i] != '\n') actual_len++;
if(actual_len == 0)
{
// this just means cancel the dialog
}
else
{
Sentence what_player_said_sentence = {0};
assert(player_said_len < ARRLEN(what_player_said_sentence.data));
for(int i = 0; i < player_said_len; i++)
{
char c = what_player_said[i];
if(c == '\n') break;
BUFF_APPEND(&what_player_said_sentence, c);
}
// order is player message, item status message in training data. So has to be same here
Dialog *to_append = &player->talking_to->player_dialog;
Entity *talking = player->talking_to;
make_space_and_append(to_append, (DialogElement){.s = what_player_said_sentence, .author = PLAYER});
if(talking->last_seen_holding != player->holding_item)
{
if(talking->last_seen_holding)
{
Sentence discard = from_str(item_discard_message_table[talking->last_seen_holding->item_kind]);
BUFF_APPEND(&discard, '\n');
make_space_and_append(to_append, (DialogElement){.author = SYSTEM, .s = discard});
assert(talking->last_seen_holding->is_item);
talking->last_seen_holding = 0;
}
if(player->holding_item)
{
assert(player->holding_item->is_item);
Sentence possess = from_str(item_possess_message_table[player->holding_item->item_kind]);
BUFF_APPEND(&possess, '\n');
make_space_and_append(to_append, (DialogElement){.author = SYSTEM, .s = possess});
}
talking->last_seen_holding = player->holding_item;
}
// the npc response will be appended here, or at least be async queued to be appended here
BUFF(char, 4000) prompt_buff = {0};
BUFF(char *, 100) to_join = {0};
assert(talking->npc_kind >= 0);
assert(talking->npc_kind < ARRLEN(prompt_table));
assert(talking->npc_kind < ARRLEN(general_prompt_table));
assert(talking->npc_kind < ARRLEN(name_table));
// general prompt
BUFF_APPEND(&to_join, general_prompt_table[talking->npc_kind]);
BUFF_APPEND(&to_join, "\n");
// item prompt
if(player->holding_item)
{
BUFF_APPEND(&to_join, item_prompt_table[player->holding_item->item_kind]);
BUFF_APPEND(&to_join, "\n");
}
// characters prompt
BUFF_APPEND(&to_join, prompt_table[talking->npc_kind]);
BUFF_APPEND(&to_join, "\n");
char *character_prompt = name_table[talking->npc_kind];
// all the dialog
int i = 0;
BUFF_ITER(DialogElement, &player->talking_to->player_dialog)
{
//bool is_player =
if(it->author == PLAYER)
{
BUFF_APPEND(&to_join, "Player: \"");
}
else if(it->author == NPC)
{
BUFF_APPEND(&to_join, character_prompt);
BUFF_APPEND(&to_join, ": \"");
}
else if(it->author == SYSTEM)
{
}
else
{
assert(false);
}
BUFF_APPEND(&to_join, it->s.data);
if(it->author == PLAYER || it->author == NPC)
BUFF_APPEND(&to_join, "\"\n");
i++;
}
BUFF_APPEND(&to_join, character_prompt);
BUFF_APPEND(&to_join, ": \"");
// concatenate into prompt_buff
BUFF_ITER(char *, &to_join)
{
size_t cur_len = strlen(*it);
for(int i = 0; i < cur_len; i++)
{
BUFF_APPEND(&prompt_buff, (*it)[i]);
}
}
const char * prompt = prompt_buff.data;
#ifdef DEVTOOLS
Log("Prompt: `%s`\n", prompt);
#endif
#ifdef WEB
// fire off generation request, save id
int req_id = EM_ASM_INT({
return make_generation_request(UTF8ToString($1), UTF8ToString($0));
}, SERVER_URL, prompt);
player->talking_to->gen_request_id = req_id;
#endif
#ifdef DESKTOP
if(player->talking_to->npc_kind == NPC_Death)
{
add_new_npc_sentence(player->talking_to, "test *moves* I am death, destroyer of games. Come join me in the afterlife, or continue onwards *moves*");
//add_new_npc_sentence(player->talking_to, "test");
}
if(player->talking_to->npc_kind == NPC_Hunter)
{
add_new_npc_sentence(player->talking_to, "I am hunter");
}
if(player->talking_to->npc_kind == NPC_Max)
{
add_new_npc_sentence(player->talking_to, "I am max");
}
if(player->talking_to->npc_kind == NPC_John)
{
add_new_npc_sentence(player->talking_to, "I am john *gives WhiteSquare*");
}
#endif
}
}
AnimatedSprite knight_idle =
{
.img = &image_knight_idle,
@ -974,6 +1037,34 @@ void reset_level()
item->pos = AddV2(player->pos, V2(0.0, 30.0));
}
void audio_stream_callback(float *buffer, int num_frames, int num_channels)
{
assert(num_channels == 1);
const int num_samples = num_frames * num_channels;
double time_to_play = (double)num_frames / (double)SAMPLE_RATE;
double time_per_sample = 1.0 / (double)SAMPLE_RATE;
for(int i = 0; i < num_samples; i++)
{
float output_frame = 0.0f;
for(int audio_i = 0; audio_i < ARRLEN(playing_audio); audio_i++)
{
AudioPlayer *it = &playing_audio[audio_i];
if(it->sample != 0)
{
if(cursor_pcm(it) >= it->sample->pcm_data_length)
{
it->sample = 0;
}
else
{
output_frame += it->sample->pcm_data[cursor_pcm(it)]*(float)(it->volume + 1.0);
it->cursor_time += time_per_sample*(it->pitch + 1.0);
}
}
}
buffer[i] = output_frame;
}
}
void init(void)
{
@ -981,8 +1072,12 @@ void init(void)
Log("Size of %d entities: %zu kb\n", (int)ARRLEN(entities), sizeof(entities)/1024);
sg_setup(&(sg_desc){
.context = sapp_sgcontext(),
});
});
stm_setup();
saudio_setup(&(saudio_desc){
.stream_cb = audio_stream_callback,
.logger.func = slog_func,
});
scratch = make_arena(1024 * 10);
@ -1713,6 +1808,16 @@ AABB draw_text(TextParams t)
{
col = t.colors[i];
}
if(false) // drop shadow, don't really like it
if(t.world_space)
{
Quad shadow_quad = to_draw;
for(int i = 0; i < 4; i++)
{
shadow_quad.points[i] = AddV2(shadow_quad.points[i], V2(0.0, -1.0));
}
draw_quad((DrawParams){t.world_space, shadow_quad, image_font, font_atlas_region, (Color){0.0f,0.0f,0.0f,0.4f}, t.clip_to, .y_coord_sorting = 1.0f, .queue_for_translucent = true});
}
draw_quad((DrawParams){t.world_space, to_draw, image_font, font_atlas_region, col, t.clip_to, .y_coord_sorting = 1.0f, .queue_for_translucent = true});
}
}

8350
thirdparty/dr_wav.h vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,343 @@
#if defined(SOKOL_IMPL) && !defined(SOKOL_LOG_IMPL)
#define SOKOL_LOG_IMPL
#endif
#ifndef SOKOL_LOG_INCLUDED
/*
sokol_log.h -- common logging callback for sokol headers
Project URL: https://github.com/floooh/sokol
Example code: https://github.com/floooh/sokol-samples
Do this:
#define SOKOL_IMPL or
#define SOKOL_LOG_IMPL
before you include this file in *one* C or C++ file to create the
implementation.
Optionally provide the following defines when building the implementation:
SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
SOKOL_UNREACHABLE() - a guard macro for unreachable code (default: assert(false))
SOKOL_LOG_API_DECL - public function declaration prefix (default: extern)
SOKOL_API_DECL - same as SOKOL_GFX_API_DECL
SOKOL_API_IMPL - public function implementation prefix (default: -)
Optionally define the following for verbose output:
SOKOL_DEBUG - by default this is defined if _DEBUG is defined
OVERVIEW
========
sokol_log.h provides a default logging callback for other sokol headers.
To use the default log callback, just include sokol_log.h and provide
a function pointer to the 'slog_func' function when setting up the
sokol library:
For instance with sokol_audio.h:
#include "sokol_log.h"
...
saudio_setup(&(saudio_desc){ .logger.func = slog_func });
Logging output goes to stderr and/or a platform specific logging subsystem
(which means that in some scenarios you might see logging messages duplicated):
- Windows: stderr + OutputDebugStringA()
- macOS/iOS/Linux: stderr + syslog()
- Emscripten: console.info()/warn()/error()
- Android: __android_log_write()
On Windows with sokol_app.h also note the runtime config items to make
stdout/stderr output visible on the console for WinMain() applications
via sapp_desc.win32_console_attach or sapp_desc.win32_console_create,
however when running in a debugger on Windows, the logging output should
show up on the debug output UI panel.
In debug mode, a log message might look like this:
[sspine][error][id:12] /Users/floh/projects/sokol/util/sokol_spine.h:3472:0:
SKELETON_DESC_NO_ATLAS: no atlas object provided in sspine_skeleton_desc.atlas
The source path and line number is formatted like compiler errors, in some IDEs (like VSCode)
such error messages are clickable.
In release mode, logging is less verbose as to not bloat the executable with string data, but you still get
enough information to identify the type and location of an error:
[sspine][error][id:12][line:3472]
RULES FOR WRITING YOUR OWN LOGGING FUNCTION
===========================================
- must be re-entrant because it might be called from different threads
- must treat **all** provided string pointers as optional (can be null)
- don't store the string pointers, copy the string data instead
- must not return for log level panic
LICENSE
=======
zlib/libpng license
Copyright (c) 2023 Andre Weissflog
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#define SOKOL_LOG_INCLUDED (1)
#include <stdint.h>
#if defined(SOKOL_API_DECL) && !defined(SOKOL_LOG_API_DECL)
#define SOKOL_LOG_API_DECL SOKOL_API_DECL
#endif
#ifndef SOKOL_LOG_API_DECL
#if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_LOG_IMPL)
#define SOKOL_LOG_API_DECL __declspec(dllexport)
#elif defined(_WIN32) && defined(SOKOL_DLL)
#define SOKOL_LOG_API_DECL __declspec(dllimport)
#else
#define SOKOL_LOG_API_DECL extern
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
Plug this function into the 'logger.func' struct item when initializating any of the sokol
headers. For instance for sokol_audio.h it would loom like this:
saudio_setup(&(saudio_desc){
.logger = {
.func = slog_func
}
});
*/
SOKOL_LOG_API_DECL void slog_func(const char* tag, uint32_t log_level, uint32_t log_item, const char* message, uint32_t line_nr, const char* filename, void* user_data);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // SOKOL_LOG_INCLUDED
// ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
// ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
// ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
// ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
//
// >>implementation
#ifdef SOKOL_LOG_IMPL
#define SOKOL_LOG_IMPL_INCLUDED (1)
#ifndef SOKOL_API_IMPL
#define SOKOL_API_IMPL
#endif
#ifndef SOKOL_DEBUG
#ifndef NDEBUG
#define SOKOL_DEBUG
#endif
#endif
#ifndef SOKOL_ASSERT
#include <assert.h>
#define SOKOL_ASSERT(c) assert(c)
#endif
#ifndef _SOKOL_PRIVATE
#if defined(__GNUC__) || defined(__clang__)
#define _SOKOL_PRIVATE __attribute__((unused)) static
#else
#define _SOKOL_PRIVATE static
#endif
#endif
#ifndef _SOKOL_UNUSED
#define _SOKOL_UNUSED(x) (void)(x)
#endif
// platform detection
#if defined(__APPLE__)
#define _SLOG_APPLE (1)
#elif defined(__EMSCRIPTEN__)
#define _SLOG_EMSCRIPTEN (1)
#elif defined(_WIN32)
#define _SLOG_WINDOWS (1)
#elif defined(__ANDROID__)
#define _SLOG_ANDROID (1)
#elif defined(__linux__) || defined(__unix__)
#define _SLOG_LINUX (1)
#else
#error "sokol_log.h: unknown platform"
#endif
#include <stdlib.h> // abort
#include <stdio.h> // fputs
#include <stddef.h> // size_t
#if defined(_SLOG_EMSCRIPTEN)
#include <emscripten/emscripten.h>
#elif defined(_SLOG_WINDOWS)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#elif defined(_SLOG_ANDROID)
#include <android/log.h>
#elif defined(_SLOG_LINUX) || defined(_SLOG_APPLE)
#include <syslog.h>
#endif
// size of line buffer (on stack!) in bytes including terminating zero
#define _SLOG_LINE_LENGTH (512)
_SOKOL_PRIVATE char* _slog_append(const char* str, char* dst, char* end) {
if (str) {
char c;
while (((c = *str++) != 0) && (dst < (end - 1))) {
*dst++ = c;
}
}
*dst = 0;
return dst;
}
_SOKOL_PRIVATE char* _slog_itoa(uint32_t x, char* buf, size_t buf_size) {
const size_t max_digits_and_null = 11;
if (buf_size < max_digits_and_null) {
return 0;
}
char* p = buf + max_digits_and_null;
*--p = 0;
do {
*--p = '0' + (x % 10);
x /= 10;
} while (x != 0);
return p;
}
#if defined(_SLOG_EMSCRIPTEN)
EM_JS(void, slog_js_log, (uint32_t level, const char* c_str), {
const str = UTF8ToString(c_str);
switch (level) {
case 0: console.error(str); break;
case 1: console.error(str); break;
case 2: console.warn(str); break;
default: console.info(str); break;
}
});
#endif
SOKOL_API_IMPL void slog_func(const char* tag, uint32_t log_level, uint32_t log_item, const char* message, uint32_t line_nr, const char* filename, void* user_data) {
_SOKOL_UNUSED(user_data);
const char* log_level_str;
switch (log_level) {
case 0: log_level_str = "panic"; break;
case 1: log_level_str = "error"; break;
case 2: log_level_str = "warning"; break;
default: log_level_str = "info"; break;
}
// build log output line
char line_buf[_SLOG_LINE_LENGTH];
char* str = line_buf;
char* end = line_buf + sizeof(line_buf);
char num_buf[32];
if (tag) {
str = _slog_append("[", str, end);
str = _slog_append(tag, str, end);
str = _slog_append("]", str, end);
}
str = _slog_append("[", str, end);
str = _slog_append(log_level_str, str, end);
str = _slog_append("]", str, end);
str = _slog_append("[id:", str, end);
str = _slog_append(_slog_itoa(log_item, num_buf, sizeof(num_buf)), str, end);
str = _slog_append("]", str, end);
// if a filename is provided, build a clickable log message that's compatible with compiler error messages
if (filename) {
str = _slog_append(" ", str, end);
#if defined(_MSC_VER)
// MSVC compiler error format
str = _slog_append(filename, str, end);
str = _slog_append("(", str, end);
str = _slog_append(_slog_itoa(line_nr, num_buf, sizeof(num_buf)), str, end);
str = _slog_append("): ", str, end);
#else
// gcc/clang compiler error format
str = _slog_append(filename, str, end);
str = _slog_append(":", str, end);
str = _slog_append(_slog_itoa(line_nr, num_buf, sizeof(num_buf)), str, end);
str = _slog_append(":0: ", str, end);
#endif
}
else {
str = _slog_append("[line:", str, end);
str = _slog_append(_slog_itoa(line_nr, num_buf, sizeof(num_buf)), str, end);
str = _slog_append("] ", str, end);
}
if (message) {
str = _slog_append("\n\t", str, end);
str = _slog_append(message, str, end);
}
str = _slog_append("\n\n", str, end);
if (0 == log_level) {
str = _slog_append("ABORTING because of [panic]\n", str, end);
(void)str;
}
// print to stderr?
#if defined(_SLOG_LINUX) || defined(_SLOG_WINDOWS) || defined(_SLOG_APPLE)
fputs(line_buf, stderr);
#endif
// platform specific logging calls
#if defined(_SLOG_WINDOWS)
OutputDebugStringA(line_buf);
#elif defined(_SLOG_ANDROID)
int prio;
switch (log_level) {
case 0: prio = ANDROID_LOG_FATAL; break;
case 1: prio = ANDROID_LOG_ERROR; break;
case 2: prio = ANDROID_LOG_WARN; break;
default: prio = ANDROID_LOG_INFO; break;
}
__android_log_write(prio, "SOKOL", line_buf);
#elif defined(_SLOG_EMSCRIPTEN)
slog_js_log(log_level, line_buf);
#elif defined(_SLOG_LINUX) || defined(_SLOG_APPLE)
int prio;
switch (log_level) {
case 0: prio = LOG_CRIT; break;
case 1: prio = LOG_ERR; break;
case 2: prio = LOG_WARNING; break;
default: prio = LOG_INFO; break;
}
syslog(prio, "%s", line_buf);
#endif
if (0 == log_level) {
abort();
}
}
#endif // SOKOL_LOG_IMPL

@ -60,6 +60,8 @@
@npc "Hello, Max. Be careful with the form of your swing, you could get hurt fighting the monsters",
@player "Can I have the white square?",
@npc "*gives WhiteSquare*",
@player "Give me the white square",
@npc "I don't have it anymore bozo",
}
}
@ -81,6 +83,23 @@
},
}
@training
{
with: Hunter,
data:
{
@player "Join me and fight Death",
@npc "Nonsense! Watch your tongue, or I'll gut you like a fish.",
@player "Sorry! He doesn't seem like a good guy.",
@npc "I trust him a lot more than you, whoever you are.",
@player "Do you trust me now?",
@item_possess WhiteSquare,
@npc "Certainly a strange artifact, you're holding, but it's no death incarnate",
@player "Fine.",
@npc "Certainly.",
},
}
@training
{
with: John,
@ -108,10 +127,10 @@
@player "It's ok I got rid of it calm down",
@item_discard WhiteSquare,
@npc "Thanks",
@player "What's up with you?"<
@player "What's up with you?",
@npc "I'm going on a crusade. I do not wish to die",
@player "Too bad",
@item_possess WhiteSquare,
@npc "
@npc "Get that THING AWAY FROM ME",
},
}

Loading…
Cancel
Save