aboutsummaryrefslogtreecommitdiff
path: root/sources/TZR_DirectResourceLoad.c
blob: 9c7153d9d2f91e8aa1d39783dc909ed2b15edac6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "TZR_resource.h"
#include "TZR_globals.h"
#include "sdl_error.h"
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_rwops.h>
#include <string.h>

int
TZR_DirectResourceLoad(TZR_Resource *res, const void *data, int size)
{
	switch (res->type) {
	case TZR_RES_RAW:
		res->raw.size = size;
		res->raw.data = malloc(size);
		if (res->raw.data == NULL) {
			perror("TZR_DirectResourceLoad");
			return -1;
		}
		memcpy(res->raw.data, data, size);
		break;
	case TZR_RES_IMAGE: {
		SDL_RWops *const rw = SDL_RWFromConstMem(data, size);
		if (rw == NULL)
			return sdl_error(-1);
		SDL_Surface *const surf = SDL_LoadBMP_RW(rw, 1);
		if (surf == NULL)
			return sdl_error(-1);
		SDL_Texture *const tex =
		    SDL_CreateTextureFromSurface(___tzr_renderer, surf);
		SDL_FreeSurface(surf);
		if (tex == NULL)
			return sdl_error(-1);
		if (SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND) < 0) {
			SDL_DestroyTexture(tex);
			return sdl_error(-1);
		}
		if (SDL_QueryTexture(tex, NULL, NULL,
		                     &res->image.width, &res->image.height)) {
			SDL_DestroyTexture(tex);
			return sdl_error(-1);
		}
		res->image.ptr = tex;
	} break;
	case TZR_RES_SOUND: {
		if (!___tzr_config.mixer) {
			SDL_Log("audio mixer disabled, skip loading");
			return -1;
		}
		SDL_RWops *const rw = SDL_RWFromConstMem(data, size);
		if (rw == NULL)
			return sdl_error(-1);
		Mix_Chunk *const chunk = Mix_LoadWAV_RW(rw, 0);
		SDL_RWclose(rw);
		if (chunk == NULL)
			return sdl_error(-1);
		res->sound.ptr = chunk;
	} break;
	default:
		fprintf(stderr, "invalid type\n");
		return -1;
	}
	return 0;
}