~vladh/peony

peony/src/files.cpp -rw-r--r-- 2.0 KiB
7fc9922bVlad-Stefan Harbuz changes shaders namespace into class a month ago
                                                                                
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
  Peony Game Engine
  Copyright (C) 2020 Vlad-Stefan Harbuz <vlad@vladh.net>
  All rights reserved.
*/

#include "logs.hpp"
#include "memory.hpp"
#include "stb.hpp"
#include "files.hpp"


unsigned char* files::load_image(
  const char *path, int32 *width, int32 *height, int32 *n_channels, bool should_flip
) {
  stbi_set_flip_vertically_on_load(should_flip);
  unsigned char *image_data = stbi_load(
    path, width, height, n_channels, 0
  );
  if (!image_data) {
    logs::fatal("Could not open file %s.", path);
  }
  return image_data;
}


unsigned char* files::load_image(
  const char *path, int32 *width, int32 *height, int32 *n_channels
) {
  return load_image(path, width, height, n_channels, true);
}


void files::free_image(unsigned char *image_data) {
  stbi_image_free(image_data);
}


uint32 files::get_file_size(const char *path) {
  FILE *f = fopen(path, "rb");
  if (!f) {
    logs::error("Could not open file %s.", path);
    return 0;
  }
  fseek(f, 0, SEEK_END);
  uint32 size = ftell(f);
  fclose(f);
  return size;
}


const char* files::load_file(MemoryPool *memory_pool, const char *path) {
  FILE *f = fopen(path, "rb");
  if (!f) {
    logs::error("Could not open file %s.", path);
    return nullptr;
  }
  fseek(f, 0, SEEK_END);
  uint32 file_size = ftell(f);
  fseek(f, 0, SEEK_SET);

  char *string = (char*)memory::push(memory_pool, file_size + 1, path);
  size_t result = fread(string, file_size, 1, f);
  fclose(f);
  if (result != 1) {
    logs::error("Could not read from file %s.", path);
    return nullptr;
  }

  string[file_size] = 0;
  return string;
}


const char* files::load_file(char *string, const char *path) {
  FILE *f = fopen(path, "rb");
  if (!f) {
    logs::error("Could not open file %s.", path);
    return nullptr;
  }
  fseek(f, 0, SEEK_END);
  uint32 file_size = ftell(f);
  fseek(f, 0, SEEK_SET);

  size_t result = fread(string, file_size, 1, f);
  fclose(f);
  if (result != 1) {
    logs::error("Could not read from file %s.", path);
    return nullptr;
  }

  string[file_size] = 0;
  return string;
}