rename engine to src
This commit is contained in:
80
src/image.cpp
Normal file
80
src/image.cpp
Normal file
@@ -0,0 +1,80 @@
|
||||
#include "pch.h"
|
||||
#include "log.h"
|
||||
#include "image.h"
|
||||
#include "asset.h"
|
||||
|
||||
#include <stb/stb_image.h>
|
||||
|
||||
using namespace ui;
|
||||
|
||||
bool Image::load(std::string filename)
|
||||
{
|
||||
stbi_set_flip_vertically_on_load(false);
|
||||
Asset file;
|
||||
if (!(file.open(filename.c_str()) && file.read_all()))
|
||||
{
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
uint8_t* buffer = stbi_load_from_memory(file.m_data, file.m_len, &width, &height, nullptr, 4);
|
||||
file.close();
|
||||
comp = 4;
|
||||
m_data = std::unique_ptr<uint8_t[]>(buffer);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Image::load_file(std::string filename)
|
||||
{
|
||||
stbi_set_flip_vertically_on_load(false);
|
||||
uint8_t* buffer = stbi_load(filename.c_str(), &width, &height, nullptr, 4);
|
||||
comp = 4;
|
||||
m_data = std::unique_ptr<uint8_t[]>(buffer);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Image::flip()
|
||||
{
|
||||
auto flipped = std::make_unique<uint8_t[]>(width*height*4);
|
||||
int line_size = width * 4;
|
||||
const uint8_t* src = m_data.get();
|
||||
uint8_t* dst = flipped.get() + line_size * (height - 1);
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
std::copy(src, src+line_size, dst);
|
||||
src += line_size;
|
||||
dst -= line_size;
|
||||
}
|
||||
std::swap(m_data, flipped);
|
||||
}
|
||||
|
||||
ui::Image ui::Image::resize(int w, int h)
|
||||
{
|
||||
Image ret;
|
||||
ret.create(w, h);
|
||||
auto temp = (glm::u8vec4*)ret.data();
|
||||
auto pixels = (glm::u8vec4*)data();
|
||||
float x_ratio = ((float)(width - 1)) / w;
|
||||
float y_ratio = ((float)(height - 1)) / h;
|
||||
int offset = 0;
|
||||
for (int i = 0; i < h; i++) {
|
||||
for (int j = 0; j < w; j++) {
|
||||
int x = (int)(x_ratio * j);
|
||||
int y = (int)(y_ratio * i);
|
||||
float x_diff = (x_ratio * j) - x;
|
||||
float y_diff = (y_ratio * i) - y;
|
||||
int index = y * width + x;
|
||||
|
||||
// range is 0 to 255 thus bitwise AND with 0xff
|
||||
glm::vec4 A = pixels[index];
|
||||
glm::vec4 B = pixels[index + 1];
|
||||
glm::vec4 C = pixels[index + width];
|
||||
glm::vec4 D = pixels[index + width + 1];
|
||||
|
||||
// Y = A(1-w)(1-h) + B(w)(1-h) + C(h)(1-w) + Dwh
|
||||
glm::vec4 gray = A*(1 - x_diff)*(1 - y_diff) + B * (x_diff)*(1 - y_diff) +
|
||||
C * (y_diff)*(1 - x_diff) + D * (x_diff*y_diff);
|
||||
temp[offset++] = glm::clamp(gray, glm::vec4(0), glm::vec4(255));
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
Reference in New Issue
Block a user