1#include "texture.h"
2
3#include "globals.h"
4
5#define STB_IMAGE_IMPLEMENTATION
6#include "stb_image.h"
7
8Texture load_texture(const char *filename) {
9 int width, height, channels;
10 unsigned char *data = stbi_load(filename, &width, &height, &channels, 4);
11
12 if (!data) {
13 fprintf(stderr, "Failed to load image: %s\n", filename);
14 return textures[0]; // can see this being annoying to debug, change
15 }
16
17 Texture tex;
18 tex.width = width;
19 tex.height = height;
20 tex.pixels = (u32 *)malloc(sizeof(u32) * width * height);
21 for (int y = 0; y < height; ++y) {
22 for (int x = 0; x < width; ++x) {
23 int pixel_idx = y * width + x;
24 int flipped_y = height - 1 - y;
25 u8 r = data[flipped_y * width * 4 + x * 4 + 0];
26 u8 g = data[flipped_y * width * 4 + x * 4 + 1];
27 u8 b = data[flipped_y * width * 4 + x * 4 + 2];
28 u8 a = data[flipped_y * width * 4 + x * 4 + 3];
29 tex.pixels[pixel_idx] = (r << 24) | (g << 16) | (b << 8) | a;
30 }
31 }
32 stbi_image_free(data);
33 return tex;
34}
35
36u32 sample_texture(int texture_index, vec2f uv) {
37 const Texture &tex = textures[texture_index];
38 int x = (int)(uv.x * tex.width);
39 int y = (int)(uv.y * tex.height);
40 return tex.pixels[y * tex.width + x];
41}