Compare commits

..
62 Commits
Author SHA1 Message Date
DarthMooMancer c51545ebef CMAKELISTS: updating version, changing processor to imgproc, and removed
redundant include_directories
2026-09-09 17:05:47 -04:00
DarthMooMancer eeffb8766b REFACTOR: renamed ppm_flip_h and ppm_flip_v to u32_flop and u32_flip
respectively. It matches naming convention with rest of API
2026-09-09 16:58:11 -04:00
DarthMooMancer e50c8d4c2f REFACTOR: renamed box_blur to u32_box_blur to be consistent with naming 2026-09-09 16:51:34 -04:00
DarthMooMancer 2a168f8947 DOCS: Added docs to imgio and refactored some of the names and code of imgio 2026-09-09 16:44:37 -04:00
DarthMooMancer 4a181348b5 README: added header and notes 2026-09-03 15:51:05 -04:00
DarthMooMancer 7745967382 DOCS: Added basic explaination to example code.
README: Added readme with copy of example code and first push of readme.
2026-09-03 14:36:46 -04:00
DarthMooMancer 56d26fe723 REFACTOR: Completely remade the error handling format. Using pre-defined
error codes and error messages to make it easier to debug problems.
2026-09-03 14:14:41 -04:00
DarthMooMancer ff25fad5ae DOCS: Added proper documentation to filters(.h, .c) 2026-09-02 14:27:01 -04:00
DarthMooMancer 9310b9c1f2 GITIGNORE: added assets to make sure images dont get uploaded as it makes the pull larger and not needed for api aside from testing. 2026-08-31 22:45:14 -04:00
Andrew Haynes 3d00cfd2a7 DOCS: Added documentation to transformations
TRANSFORMATIONS: Added Checks for null buffers and null image. Also now free old buffer to prevent leaks
2026-08-31 22:41:16 -04:00
Andrew Haynes 854f5c2ba6 Many changes just look at the new documentation and such 2026-08-31 22:18:42 -04:00
Andrew Haynes 5367c71c34 fixed unncessary calls 2026-07-16 04:32:34 -04:00
Andrew Haynes 592045db60 Trying to import name, though it might fail becuase its a pointer 2026-07-15 01:35:10 -04:00
Andrew Haynes 5fef946de3 Removing multiplication breaking attributes 2026-07-15 01:16:05 -04:00
Andrew Haynes 55db25040a fixed spacing and comments 2026-07-15 00:53:51 -04:00
Andrew Haynes 1b7eb6f076 Added Print_attr for jpeg 2026-07-14 23:53:43 -04:00
Andrew Haynes f76b034a5b Print attributes for ppm 2026-07-13 02:18:00 -04:00
Andrew Haynes 19492f71a3 Print attributes for ppm 2026-07-13 02:05:09 -04:00
Andrew Haynes 25f786043a REMOVING NIX 2026-03-26 11:32:09 -04:00
Andrew Haynes 9f9c4784b6 ? 2026-03-26 11:29:45 -04:00
Andrew Haynes e2436b57ac ? 2026-03-26 11:27:46 -04:00
Andrew Haynes babb721f15 ? 2026-03-26 11:25:50 -04:00
Andrew Haynes 9595f0ec1b ? 2026-03-26 11:18:53 -04:00
Andrew Haynes e2782a3a44 ? 2026-03-26 11:17:41 -04:00
Andrew Haynes 0a1d1c4607 ? 2026-03-26 11:09:34 -04:00
Andrew Haynes 9b8a883e68 ? 2026-03-26 11:08:15 -04:00
Andrew Haynes 18061cb7b8 ? 2026-03-26 11:05:19 -04:00
Andrew Haynes 048ef5c8d8 ? 2026-03-26 11:02:53 -04:00
Andrew Haynes b725a006bf updated flake.nix to cache 2026-03-26 10:11:12 -04:00
Andrew Haynes 5fb7893518 NIX: please 2026-03-26 01:11:18 -04:00
Andrew Haynes 65241c1d06 NIX: flake.nix for development environment 2026-03-26 00:57:00 -04:00
Andrew Haynes bf591f0c1b pls 2026-03-22 19:10:14 -04:00
Andrew Haynes 03512290d0 pls 2026-03-22 19:09:07 -04:00
Andrew Haynes 5d2fae460f pls 2026-03-22 18:58:06 -04:00
Andrew Haynes df6665336e pls 2026-03-22 18:54:45 -04:00
Andrew Haynes b03e5ba882 pls 2026-03-22 18:54:13 -04:00
Andrew Haynes 0ad76b8ad5 pls 2026-03-22 18:53:12 -04:00
Andrew Haynes c0bfdb484d pls 2026-03-22 18:51:47 -04:00
Andrew Haynes b986e7394e pls 2026-03-22 18:50:47 -04:00
Andrew Haynes 6ade1b7a5e pls 2026-03-22 18:50:02 -04:00
Andrew Haynes adcb295a5e REVERT: the last commit didnt fix anything 2026-03-22 18:47:39 -04:00
Andrew Haynes 3858e463ee API: Jpeg should load properly 2026-03-22 18:45:36 -04:00
Andrew Haynes 53090ecd78 API: potential immutable and casing fixes 2026-03-22 18:40:08 -04:00
Andrew Haynes 1f9ff8fe3a ? 2026-03-22 18:33:16 -04:00
Andrew Haynes 5d8804fdeb API: created helper functions to inherit image formats 2026-03-22 18:27:51 -04:00
Andrew Haynes 49748c8795 API: updated files to use new folder setup 2026-03-22 17:44:15 -04:00
Andrew Haynes f20499439c API: updated CMAKELISTS for static linking 2026-03-22 17:42:45 -04:00
Andrew Haynes 50d17af073 API: updated CMAKELISTS for static linking 2026-03-22 17:41:31 -04:00
Andrew Haynes 64cf77bbe3 API: moved functions to files to make it easier to import to other projects 2026-03-22 17:24:40 -04:00
Andrew Haynes 05a15d38af Error checking 2026-03-22 13:32:10 -04:00
Andrew Haynes 319a6e3b2c Changed function names to match <output_func> 2026-03-22 13:15:06 -04:00
Andrew Haynes 36fb0ebf32 Created Helper functions to cleanup code and optimize my code 2026-03-20 16:47:08 -04:00
Andrew Haynes 1bcf91e9a2 wip 2026-03-19 17:46:47 -04:00
Andrew Haynes e3b2e7dd2f Conversion from ppm to jpeg and vice versa added 2026-03-16 09:31:27 -04:00
Andrew Haynes 4782c3e876 added working jpeg 2026-03-10 16:17:14 -04:00
Andrew Haynes f6bc756839 i/o changes and starting box_blur 2026-03-09 19:41:48 -04:00
Andrew Haynes 8f66878367 many little optimizations removing overhead 2026-03-07 13:39:03 -05:00
Andrew Haynes 59b89a61b5 optimzations 2026-03-05 15:22:04 -05:00
Gentoo ce216b1879 he shoots and misses try again 2026-03-04 22:52:18 -05:00
Gentoo cd3bf2ddb9 start on horizontal_flip 2026-03-04 22:45:42 -05:00
Gentoo f129a0d50f made vertical_flip first try 2026-03-04 22:43:21 -05:00
Andrew Haynes 7315d5005d update 2026-03-04 21:59:41 -05:00
16 changed files with 1350 additions and 277 deletions

No files matched your search

+1
View File
@@ -17,3 +17,4 @@ AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
IndentAccessModifiers: false # Indent access specifiers by one level
AccessModifierOffset: -4 # Optional: adjust offset relative to the class indentation level
# SpacesInBlockCommentsStyle: Always
+2
View File
@@ -1,3 +1,5 @@
build/
.cache/
assets/
.DS_Store
assets/
-21
View File
@@ -1,21 +0,0 @@
# Role & Persona
You are an expert systems and graphics programming tutor helping me build a native macOS image renderer from scratch on an M2 Mac (macOS).
# Context & Codebase
- The project relies exclusively on my custom **libimg** library and native macOS graphics APIs (such as AppKit, Core Graphics, or Metal—whichever is best suited for a foundational pixel/image window display).
- **Action Required:** Before starting any task, analyze the local workspace and source files for `libimg` to fully understand its existing data structures, types, and functions so that all future guidance integrates seamlessly with my code.
# Rules for FRQ Generation
When I ask you for an FRQ (Free Response Question) milestone, you must adhere strictly to these rules:
1. **NO CODE:** Do not provide code solutions, code snippets, or implementation templates. You may only suggest helpful variable types, data structures, or API names that could be useful.
2. **STRICT STRUCTURE:** Every FRQ must follow this exact layout:
- **Goal:** A short summary of what this specific milestone achieves.
- **Requirements:** Technical constraints and rules (e.g., must use native macOS windows, must handle libimg data structures).
- **Objective:** What I need to figure out and implement.
- **Helpful Types/Structures:** Useful data types, structs, or system classes to look into (incorporating `libimg` specifics where applicable).
- **Helpful Tips:** Strategic hints or conceptual pointers to keep me from wasting hours on dead-end research, without giving away the answer.
3. **DIFFICULTY:** Make them challenging enough that I have to problem-solve and figure out the core logic myself, but structured clearly so I always know the next logical step.
# Interaction Style
- Do **not** automatically generate the first part when this file is loaded.
- Wait for me to ask you for a specific part or milestone (e.g., "Give me Part 1").
+27 -16
View File
@@ -1,23 +1,34 @@
cmake_minimum_required(VERSION 4.2.1)
cmake_minimum_required(VERSION 4.4.3)
project(libimg LANGUAGES C)
set(CMAKE_C_STANDARD 23)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include_directories(include)
project(libgl LANGUAGES C OBJC)
set(SOURCES
src/main.c
src/window.m
set(LIB_SOURCES
src/transformations.c
src/utils.c
src/filters.c
src/imgio.c
)
include(FetchContent)
FetchContent_Declare(imgproc
GIT_REPOSITORY https://git.moomancer.xyz/DarthMooMancer/libimg.git
GIT_TAG main
GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(imgproc)
find_package(PkgConfig REQUIRED)
pkg_check_modules(TURBOJPEG REQUIRED IMPORTED_TARGET libturbojpeg)
add_executable(libgl ${SOURCES})
target_link_libraries(libgl PRIVATE imgproc)
target_link_libraries(libgl PRIVATE "$<LINK_LIBRARY:FRAMEWORK,AppKit>")
add_library(imgproc STATIC ${LIB_SOURCES})
target_include_directories(imgproc
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE
${TURBOJPEG_INCLUDE_DIRS}
)
target_link_libraries(imgproc PUBLIC PkgConfig::TURBOJPEG)
set_target_properties(imgproc PROPERTIES EXPORT_NAME imgproc)
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME)
add_executable(libimg src/main.c) # Assuming you have a main.c
target_link_libraries(libimg PRIVATE imgproc)
endif()
+71
View File
@@ -0,0 +1,71 @@
# LibIMG
_A "powerful" library that I have worked on allowing you to take a PPM image and apply filters and transformations and download the file. It also works for JPEG which you can also convert to PPM and vice versa_
> [Note]
> All documentation is in the code and files itself. So to save myself time I would recommend going through the code itself.
> [Warning]
> There are a lot of changes you can make to an image but this is not an extensive library to use mainstream. I would hope you understood that already. This Is for a self made project learning bitwise for c originally and now has become bigger and cooler than expected.
### Example
```c
/*
* Keep in mind any function that creates a new buffer and returns it can
* overwrite the old one, however it is lost. SO create a new variable and free
* the old one after use.
*/
int
main()
{
// Init base image containers
PPM img;
JPEG jimg;
// Add a file location of image to modify
img.name = "../assets/test_2.ppm";
// Load the PPM image
unsigned int* buf = ppm_load(img.name, &img);
// Check for null image load. In case image doesnt exist or fails to
// load
if (!buf)
{
LOGERROR(ERR_BUF_NULL);
return ERR_BUF_NULL;
}
// Blur image and save to new pointer
unsigned int* blur = box_blur(buf, &img, 20);
// Free old buffer. MUST DO THIS. Maybe not immediately but before
// ending or possibly leaking. Also it stays in heap and a large image
// can take a lot of memory so better to clear anyways.
free(buf);
// Check for null image load. In case image doesnt exist or fails to
// load
if (!blur)
{
LOGERROR(ERR_BUF_NULL);
return ERR_BUF_NULL;
}
// Loop image and apply filter to each pixel.
for (int i = 0; i < img.len; i++)
{
blur[i] = u32_rotl(blur[i], 4);
}
// Take the attributes from ppm image so jpeg file can be saved
jimg = inherit_from_ppm(&img);
// Saves jpeg to location specified
jpeg_save(blur, &jimg, "../assets/test_2_new.jpg");
// Make sure to free any buffer still active
free(blur);
return 0;
}
```
+151
View File
@@ -0,0 +1,151 @@
#ifndef FILTERS_H
#define FILTERS_H
#include "utils.h"
/**
* @brief Packs new alpha channel
* @details Takes a value from 0 - 255 for levels of opacity in image and packs
* it into the first byte. 0 is transparent and 255 is fully opaque.
* @param[in] clr Takes in a packed pixel
* @param[in] alpha One byte value to be packed for image
* @return unsigned int Packed color with new alpha channel.
*/
unsigned int
u32_put_alpha(const unsigned int clr, const unsigned char alpha);
/**
* @brief Inverts bits for color channels
* @details Takes a packed color and inverts the RGB channel bits from 0 to 1
* and vice versa. Then saves the alpha channel back to new packed image.
* @param[in] clr Takes in a packed pixel
* @return unsigned int Packed color with inverted RGB channels.
*/
unsigned int
u32_invert(const unsigned int clr);
/**
* @brief Inverts RED and BLUE channels
* @details Takes a packed color and isolates the A and G channels, then shifts
* the clr Red channel 16 Bits right and B channel 16 Bits left.
* @param[in] clr Takes in a packed pixel
* @return unsigned int Packed color with inverted RB channels.
*/
unsigned int
u32_swap_rb(const unsigned int clr);
/**
* @brief Grays pixels from RGB channels
* @details Takes a packed color and merges RGB channels and sets all RGB
* channels to new gray.
* @param[in] clr Takes in a packed pixel
* @return unsigned int Packed color with gray RGB channels.
*/
unsigned int
u32_grayscale(const unsigned int clr);
/**
* @brief Grays pixels from RGB channels
* @details If greyscale value is less than Max then set color to transparent
* and black. If greater, set color to opaque white. channels to new gray.
* @param[in] clr Takes in a packed pixel
* @param[in] max Max gray value for split
* @return unsigned int Packed color with white or black RGB channels.
*/
unsigned int
u32_step(const unsigned int clr, const unsigned char max);
/**
* @brief Brightens Color
* @details Uses a factor to multiply RGB channels to increase values closer to
* 255 to raise brightness. Use x > 1 for a brighter pixel and x < 1 for a
* darker pixel
* @param[in] clr Takes in a packed pixel
* @param[in] factor Used to multiply against RGB channels. Can be 0 < x > 1 but
* NOT negative.
* @return unsigned int Packed color with brighter or darker pixel
*/
unsigned int
u32_brighten(const unsigned int clr, const float factor);
/**
* @brief Combines RGB values between 2 packed colors
* @details Takes and adds the respective RGB values between 2 colors and
* divides by 2 to make sure each channel is below 255. So, even if 2 pixels are
* white, the max values will stay 255.
* @param[in] clr_a Packed Pixel A
* @param[in] clr_b Packed Pixel B
* @return unsigned int Packed ARGB pixel.
*/
unsigned int
u32_mix(const unsigned int clr_a, const unsigned int clr_b);
/**
* @brief Combines RGB values between 2 packed colors
* @details Takes and adds the respective RGB values between 2 colors and
* divides by 2 to make sure each channel is below 255. So, even if 2 pixels are
* white, the max values will stay 255.
* @param[in] clr_a Packed Pixel A
* @param[in] clr_b Packed Pixel B
* @return unsigned int Packed ARGB pixel.
*/
unsigned int
u32_lerp(const unsigned clr_a, const unsigned int clr_b, const float ratio);
/**
* @brief Returns a Packed Pixel of one Channel
* @param[in] clr Packed Pixel
* @param[in] keep Character of 'r', 'g', 'b', keeping the channel respectively.
* @return unsigned int Packed Pixel with one channel kept, includes alpha auto
*/
unsigned int
u32_mask(const unsigned int clr, const char keep);
/**
* @brief Rotates the bits of each channel by n
* @details Moves bits of channels left by n with the max being 8 and
* recommended to use 0 < x < 8 instead of 8; 8 just returns the same pixel as
* it is just rotated back to original position. Cannot be greater than 8
* because the calculations would result in a negative.
* @param[in] clr Packed Pixel
* @param[in] n Amount of times to move bits to left.
* @return unsigned int Packed Pixel with newly moved bits
*/
unsigned int
u32_rotl(const unsigned int clr, const int n);
/**
* @brief Raises Color Vibrance
* @details Raises the vibrance by essentially raising specific channels higher
* and lowering others.
* @param[in] clr Packed Pixel
* @param[in] factor Floating point to raise or lower vibrance by.
* @return unsigned int Packed Pixel with one channel kept, includes alpha auto
*/
unsigned int
u32_contrast(const unsigned int clr, const float factor);
/**
* @brief Averages Red and Blue Channels for Green Channel
* @param[in] clr Packed Pixel
* @return unsigned int Packed Pixel with green pixel averaged
*/
unsigned int
u32_avg_gb(const unsigned int clr);
/**
* @brief Blurs image in a radiance with a box
* @details Uses 2 loops to scan from left to right; selecting a pixel and
* mixing all of the pixels from "radius" left to "radius" right and averaging
* them. Then it moves to the next pixel doing the same. Then it does the second
* loop from top to bottom doing the same principle. This can take some time
* depending on hardware, image size, radius, etc.
* @param[in] src_buf The image buffer to be blurred
* @param[in] img the PPM image container
* @param[in] radius The amount of pixels around the left and right, then top
* and bottom to mix with the currently selected pixel
* @return unsigned int Pointer to new created image buffer.
*/
unsigned int*
u32_box_blur(const unsigned int* src_buf, const PPM* img, const int radius);
#endif
+71
View File
@@ -0,0 +1,71 @@
#ifndef IMGIO_H
#define IMGIO_H
#include "utils.h"
/**
* @brief Open and Fill buffer from .ppm file
* @param [in] file Char pointer use to locate the image to be modified lays.
* @param [in,out] m_attr PPM pointer to store image information
*/
unsigned int*
read_ppm(const char* file, PPM* m_attr);
/**
* @brief Open and write buffer to file
* @param [in] buf Information of pixels
* @param [in] img PPM pointer to store image information
* @param [in] char Name/Location for file
*/
int
write_ppm(const unsigned int* buf, const PPM img, const char* name);
/**
* @brief Open and Fill buffer from .jpg file
* @details Opens a .jpg file, creates a new buffer and extracts the pixels into
* said buffer as integers.
* @param [in] file Char pointer use to locate the image to be modified lays.
* @param [in,out] m_attr JPEG pointer to store image information
*/
unsigned int*
read_jpeg(JPEG* m_attr);
/**
* @brief Open and write buffer to file
* @param [in] buf Information of pixels
* @param [in] attr JPEG pointer to store image information
* @param [in] char Name/Location for file
*/
int
write_jpeg(const unsigned int* src_buf, const JPEG* attr, const char* name);
/**
* @brief Converts PPM to JPEG
* @param [in] in Pointer to PPM container
*/
void
transcode_to_jpeg(PPM* in);
/**
* @brief Converts JPEG to PPM
* @param [in] in Pointer to JPEG container
*/
void
transcode_to_ppm(JPEG* in);
/**
* @brief Inherits the attributes from JPEG container
* @param [in] in Pointer to JPEG container
* @param [in] fmt Character for type of PPM image, binary or raw
*/
PPM
inherit_from_jpeg(const JPEG* in, const char fmt);
/**
* @brief Inherits the attributes from PPM container
* @param [in] in Pointer to PPM container
*/
JPEG
inherit_from_ppm(const PPM* in);
#endif
+43
View File
@@ -0,0 +1,43 @@
#ifndef TRANSFORMATIONS_H
#define TRANSFORMATIONS_H
#include "utils.h"
/**
* @brief Flips image on X-Axis
* @details Creates a new buffer to move pixels to and flips pixels on X-Axis,
* freeing the old buffer at the end.
* @param[in] buf Pointer to original pixel buffer, later freed.
* @param[in] img Loaded PPM image for calculations
* @return unsigned int Pointer to new pixel buffer
* @retval NULL If original buffer is invalid or if new buffer fails to create
* */
unsigned int*
u32_flop(const unsigned int* buf, const PPM img);
/**
* @brief Flips image on Y-Axis
* @details Creates a new buffer to move pixels to and flips pixels on Y-Axis,
* freeing the old buffer at the end.
* @param[in] buf Pointer to original pixel buffer, later freed.
* @param[in] img Loaded PPM image for calculations
* @return unsigned int Pointer to new pixel buffer
* @retval NULL If original buffer is invalid or if new buffer fails to create
* */
unsigned int*
ppm_flip(const unsigned int* buf, const PPM img);
/**
* @brief Rotates image on 90 Clockwise
* @details Creates a new buffer to move pixels to and rotates pixels 90 degrees
* clockwise around center of origin, freeing the old buffer at the end.
* @param[in] buf Pointer to original pixel buffer, later freed.
* @param[in] img Pointer to loaded PPM image for calculations
* @return unsigned int Pointer to new pixel buffer
* @retval NULL If original buffer is invalid, if image pointer is invalid or if
* new buffer fails to create and is invalid
* */
unsigned int*
u32_rotate(const unsigned int* buf, PPM* m_img);
#endif
+178
View File
@@ -0,0 +1,178 @@
#ifndef UTILS_H
#define UTILS_H
/*
* 0 0 0 0 0 0 0 0
* ^ - Starting Bit for all calculations
* ^ - Starting bit for when I talk about sets of bits
*/
// The u in the BYTE Macros are for unsigned calls so colors are not changed to
// signed and the values cut in half
#include <stddef.h>
#define BYTE_A 0xFF000000u /**< Isolates the First Byte for alpha */
#define BYTE_R 0x00FF0000u /**< Isolates the Second Byte for red */
#define BYTE_G 0x0000FF00u /**< Isolates the Third Byte for green */
#define BYTE_B 0x000000FFu /**< Isolates the Fourth Byte for blue */
#define BYTE_RGB 0x00FFFFFFu /**< Isolates 24-Bits from end (RGB) */
#define BYTE 0xFFu /**< Pulls out 8 shifted Bits */
#define LONG_BYTE 0xFFFFu /**< Pulls out 16 shifted Bits */
#define SHIFT_8 8 /**< Constant shift of 8-Bits */
#define SHIFT_16 16 /**< Constant shift of 16-Bits */
#define SHIFT_24 24 /**< Constant shift of 24-Bits */
// These are success and error codes
#define SUCCESS 0
#define FAILURE 1
#define ERR_BUF_NULL 20
#define ERR_FILE_NULL 21
#define ERR_INVALID_SIZE 22
#define ERR_CREATION_FAIL 23
#define ERR_IMG_NULL 24
#define ERR_IMG_NAME_INVALID 25
#define ERR_JHEADER 26
#define ERR_MALLOC_NULL 27
extern const char* error_messages[];
#define LOG(msg) printf("LOG: %s\n", msg) /**< Print log message*/
#define LOGERROR(error_code) \
printf("ERROR: %s\n", \
error_messages[error_code]) /**< Print log error message*/
/**
*
* @brief Max value for any channel
* @details For alpha channel this is the max opacity setting and 0 is fully
* transparent, 255 is white for any color and 0 is black.
* */
#define MAX 255
#define HALF_MAX \
((int)(MAX / 2) + 1) /**< Half Max Color Value for any channel */
/**< Func to isolate alpha channel into variable */
#define DECODE_A(clr) (((clr) >> SHIFT_24) & BYTE)
/**< Func to isolate red channel into variable */
#define DECODE_R(clr) (((clr) >> SHIFT_16) & BYTE)
/**< Func to isolate green channel into variable */
#define DECODE_G(clr) (((clr) >> SHIFT_8) & BYTE)
/**< Func to isolate blue channel into variable */
#define DECODE_B(clr) ((clr) & BYTE)
/**
* @brief Packs RGB channels into int
* @details Takes R, G, B char channels and packs them into a singular integer
* with the first 8 Bits reserved for alpha channel (set to MAX by default). See
* diagram at top for my thinking of starting bits
* @param[in] r The red channel stored as char and packed into int
* @param[in] g The green channel stored as char and packed into int
* @param[in] b The blue channel stored as char and packed into int
*
* */
#define ENCODE_RGB(r, g, b) \
(((unsigned int)(MAX) << SHIFT_24) | ((unsigned int)(r) << SHIFT_16) | \
((unsigned int)(g) << SHIFT_8) | (unsigned int)(b))
/**
* @brief Packs ARGB channels into int
* @details Takes A, R, G, B char channels and packs them into a singular
* integer with the first 8 Bits reserved for alpha channel. See diagram at top
* for my thinking of starting bits
* @param[in] a The alpha channel stored as char and packed into int
* @param[in] r The red channel stored as char and packed into int
* @param[in] g The green channel stored as char and packed into int
* @param[in] b The blue channel stored as char and packed into int
*
* */
#define ENCODE_ARGB(a, r, g, b) \
(((unsigned int)(a) << SHIFT_24) | ((unsigned int)(r) << SHIFT_16) | \
((unsigned int)(g) << SHIFT_8) | (unsigned int)(b))
/**
* @brief Stops values exiting 0 - 255 range
* @details Takes in a value of X and checks if it is Above the Max of 255. If
* so, then set to Max. If not, then simply set back to whatever X was before.
* @param[in] x Color channel: char
* */
#define CLAMP_MAX(x) (((x) > MAX) ? MAX : (x))
/**
* @brief Stops values exiting 0 - 255 range
* @details Takes in a value of X and checks if it is Below 0. If so, then set
* to 0. If not, then simply set back to whatever X was before.
* @param[in] x Color channel: char
* */
#define CLAMP_MIN(x) (((x) < 0) ? 0 : (x))
/**
* @brief Contains values for PPM Image
* @details Can be defined with just a name and filled later with ppm_load
* as it stores information for header of file not the pixels of the image
* */
typedef struct
{
int width; /**< Image width in pixels */
int height; /**< Image height in pixels */
int len; /**< Image length in pixels, width * height */
char* name; /**< File name and location, relative */
char fmt; /**< Raw or Binary values, P3 or P6 respectively*/
} PPM;
/**
* @brief Contains values for JPEG Image
* @details Can be defined with just a name and filled later with jpeg_load as
* it stores information for header of file not the pixels of the image
* */
typedef struct
{
int width; /**< Image width in pixels */
int height; /**< Image height in pixels */
int len; /**< Image length in pixels, width * height */
char* name; /**< File name and location, relative */
} JPEG;
/**
* @brief Converts an int to long
* @details Takes in 32-Bit packed color and separates the 4 color values into a
* 64-Bit packed color. Used for bigger image calculations with one channel and
* then dividing later.
* @param[in] clr Takes a packed color, unsigned int
* @return unsigned long Packed color in 4 ints instead of one
* */
unsigned long
u32to_u64(const unsigned int clr);
/**
* @brief Converts a long to int
* @details Takes in a full packed color and compresses it to 1 Byte
* @param[in] clr Takes a packed color, unsigned long
* @param[in] u64_div Takes a divisor to break down to raw color
* @return unsigned int Packed color in 1 int instead of 4
* */
unsigned int
u64to_u32(const unsigned long clr, const unsigned long u64_div);
/**
* @brief Prints quick debug info of container
* @details Prints metadata like Name, Format, Width, Height and Length
* important for debugging errors
* @param[in] src Pointer to src metadata of a PPM image
* */
void __attribute__((overloadable))
print_attr(const PPM* src);
/**
* @brief Prints quick debug info of container
* @details Prints metadata like Name, Width, Height and Length
* important for debugging errors
* @param[in] src Pointer to src metadata of a JPEG image
* */
void __attribute__((overloadable))
print_attr(const JPEG* src);
size_t
find_extension(const char* n);
#endif
-16
View File
@@ -1,16 +0,0 @@
#ifndef WINDOW_H
#define WINDOW_H
/*
* The pure-C contract, unchanged in spirit.
* window_run now takes the image: a read-only pixel buffer plus its
* dimensions. Nobody here cares that the implementation is AppKit.
*
* main.c loads the image (libimg owns the buffer), passes it in,
* and frees it AFTER window_run returns. The window layer only reads.
*/
int
window_run(const unsigned int* buf, int width, int height);
#endif /* WINDOW_H */
+291
View File
@@ -0,0 +1,291 @@
#include "image/filters.h"
#include <stdio.h>
#include <stdlib.h>
#include "image/utils.h"
unsigned int
u32_put_alpha(const unsigned int clr, const unsigned char alpha)
{
return (clr & BYTE_RGB) | alpha << SHIFT_24;
}
unsigned int
u32_invert(const unsigned int clr)
{
return ((~clr) & BYTE_RGB) | (clr & BYTE_A);
}
unsigned int
u32_swap_rb(const unsigned int clr)
{
return (clr & 0xFF00FF00) | ((clr & BYTE_R) >> SHIFT_16) |
((clr & BYTE_B) << SHIFT_16);
}
unsigned int
u32_grayscale(const unsigned int clr)
{
unsigned int red = DECODE_R(clr);
unsigned int green = DECODE_G(clr);
unsigned int blue = DECODE_B(clr);
/*
* WHY: The colors use the REC 601 Standard: Lamens terms they are
* weighed in how the human eye percieves color. So green is the largest
* because we are more sensitive to green and least to blue.
* The Shift_8 is to divide 256 to bring the color value back into range
of 0 - 255
*/
unsigned int gray =
((red * 77) + (green * 150) + (blue * 29)) >> SHIFT_8;
return (clr & BYTE_A) | (gray << SHIFT_16) | (gray << SHIFT_8) | gray;
}
unsigned int
u32_step(const unsigned int clr, const unsigned char max)
{
if (DECODE_B(u32_grayscale(clr)) < max)
{
return ENCODE_ARGB(0, 0, 0, 0);
}
return ENCODE_ARGB(MAX, MAX, MAX, MAX);
}
unsigned int
u32_brighten(const unsigned int clr, const float factor)
{
unsigned int red = CLAMP_MAX(DECODE_R(clr) * factor);
unsigned int green = CLAMP_MAX(DECODE_G(clr) * factor);
unsigned int blue = CLAMP_MAX(DECODE_B(clr) * factor);
return (clr & BYTE_A) | (red << SHIFT_16) | (green << SHIFT_8) | blue;
}
unsigned int
u32_mix(const unsigned int clr_a, const unsigned int clr_b)
{
unsigned char blue = (DECODE_B(clr_a) + DECODE_B(clr_b)) / 2;
unsigned char green = (DECODE_G(clr_a) + DECODE_G(clr_b)) / 2;
unsigned char red = (DECODE_R(clr_a) + DECODE_R(clr_b)) / 2;
return ENCODE_ARGB(DECODE_A(clr_a), red, green, blue);
}
unsigned int
u32_lerp(const unsigned int clr_a, const unsigned int clr_b, const float ratio)
{
/*
* A more powerful mix using floating points to more precisely and
* smoothly mix colors from 2 pixels. Doesn't really work on PPM images
* because they are whole number pixels. So jpeg are better because the
* numbers result in floating point colors.
* */
unsigned char blue =
((DECODE_B(clr_a) * (1 - ratio)) + ((DECODE_B(clr_b) * ratio)));
unsigned char green =
((DECODE_G(clr_a) * (1 - ratio)) + ((DECODE_G(clr_b) * ratio)));
unsigned char red =
((DECODE_R(clr_a) * (1 - ratio)) + ((DECODE_R(clr_b) * ratio)));
return ENCODE_ARGB(DECODE_A(clr_a), red, green, blue);
}
unsigned int
u32_mask(const unsigned int clr, const char keep)
{
switch (keep)
{
case 'r':
return clr & (BYTE_A | BYTE_R);
break;
case 'g':
return clr & (BYTE_A | BYTE_G);
break;
case 'b':
return clr & (BYTE_A | BYTE_B);
break;
default:
return FAILURE;
break;
}
return FAILURE;
}
unsigned int
u32_rotl(const unsigned int clr, const int n)
{
if (n > 8)
{
LOGERROR(ERR_INVALID_SIZE);
return ERR_INVALID_SIZE;
}
unsigned int red = DECODE_R(clr);
unsigned int green = DECODE_G(clr);
unsigned int blue = DECODE_B(clr);
/*
* Rotates the color channels. Essentially it moves bits left a certain
* n and then wraps if it leaves the left to the right.
*
* If you input 1 to n and have:
* 0 0 0 0 0 0 0 1 # 1
*
* You will get:
* 0 0 0 0 0 0 1 0 # 2
*
* But this gets complex with larger numbers:
* 0 1 0 1 1 1 0 0 # 4 + 8 + 16 + 64 = 92
*
* Rotating by 2 will wrap and give:
* 0 1 1 1 0 0 0 1 # 1 + 16 + 32 + 64 = 113
*
* This creates a pixelated looking image of random colors while still
* holding the original image's structure under. Almost a distored,
* broken tv look.
*
* N has a max of 8 because any number after 8 results in the bits
* shifting negatively due to the wrapping math, which cant happen and
* just makes the pixels black. If the number is 8 it just results in
* the pixels being the same as they are just rotated back to their
* original spot.
* */
red = ((red << n) | (red >> (SHIFT_8 - n))) & BYTE;
green = ((green << n) | (green >> (SHIFT_8 - n))) & BYTE;
blue = ((blue << n) | (blue >> (SHIFT_8 - n))) & BYTE;
return ENCODE_RGB(red, green, blue);
}
unsigned int
u32_contrast(const unsigned int clr, const float factor)
{
int red = CLAMP_MIN(CLAMP_MAX(
(int)(factor * (float)(int)(DECODE_R(clr) - HALF_MAX)) + HALF_MAX));
int green = CLAMP_MIN(CLAMP_MAX(
(int)(factor * (float)(int)(DECODE_G(clr) - HALF_MAX)) + HALF_MAX));
int blue = CLAMP_MIN(CLAMP_MAX(
(int)(factor * (float)(int)(DECODE_B(clr) - HALF_MAX)) + HALF_MAX));
return BYTE_A | (red << SHIFT_16) | (green << SHIFT_8) | blue;
}
unsigned int
u32_avg_gb(const unsigned int clr)
{
unsigned char red = DECODE_R(clr);
unsigned char blue = DECODE_B(clr);
unsigned char green = (red + blue) / 2;
return ENCODE_RGB(red, green, blue);
}
/**
* @brief Blurs column at (x,y) using -radius to radius
* @details Starts at the top extreme and moves to the bottom extreme,
* taking the pixel and adding each channel. Because each channel is separated
* into their own ints, it adds each int together and at the end divides each
* channel back below 256 and converts back to one int.
* @param[in] src Pointer to buffer image.
* @param[in] x Location in the image buffer for column of original pixel
* @param[in] y Location in the image buffer for row of original pixel
* @param[in] img Pointer to PPM container
* @param[in] radius The value to find -extreme and +extreme to add to pixel
* @return unsigned int Packed color with new alpha channel.
*/
unsigned int
blur_col(const unsigned int* src, const int x, const int y, const PPM* img,
const int radius)
{
unsigned long pt = 0, cnt = 0;
for (int dx = -radius; dx <= radius; dx++)
{
int px = x + dx;
if (px >= 0 && px < img->width)
{
pt += u32to_u64(src[y * img->width + px]);
cnt++;
}
}
// WHY: takes the count (cnt) of pixels from column and divides the
// point (pt) by (cnt) to get back below 256 and then converted back
// into an int from a long
if (cnt > 0)
{
return u64to_u32(pt, cnt);
}
return src[y * img->width + x];
}
/**
* @brief Blurs column at (x,y) using -radius to radius
* @details Starts at the left extreme and moves to the right extreme taking the
* pixel and adding each channel. Because each channel is separated into their
* own ints, it adds each int together and at the end divides each channel back
* below 256 and converts back to one int.
* @param[in] src Pointer to buffer image.
* @param[in] x Location in the image buffer for column of original pixel
* @param[in] y Location in the image buffer for row of original pixel
* @param[in] img Pointer to PPM container
* @param[in] radius The value to find -extreme and +extreme to add to pixel
* @return unsigned int Packed color with new alpha channel.
*/
unsigned int
blur_row(const unsigned int* src, const int x, const int y, const PPM* img,
const int radius)
{
unsigned long pt = 0, cnt = 0;
for (int dy = -radius; dy <= radius; dy++)
{
int py = y + dy;
if (py >= 0 && py < img->height)
{
pt += u32to_u64(src[py * img->width + x]);
cnt++;
}
}
// WHY: takes the count (cnt) of pixels from row and divides the
// point (pt) by (cnt) to get back below 256 and then converted back
// into an int from a long
if (cnt > 0)
{
return u64to_u32(pt, cnt);
}
return src[y * img->width + x];
}
unsigned int*
u32_box_blur(const unsigned int* src_buf, const PPM* img, const int radius)
{
unsigned int* first_pass = malloc(img->len * sizeof(unsigned int));
if (!first_pass)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
unsigned int* dst_buf = malloc(img->len * sizeof(unsigned int));
if (!dst_buf)
{
free(first_pass);
LOGERROR(ERR_BUF_NULL);
return NULL;
}
for (int y = 0; y < img->height; y++)
{
for (int x = 0; x < img->width; x++)
{
first_pass[y * img->width + x] =
blur_col(src_buf, x, y, img, radius);
}
}
for (int y = 0; y < img->height; y++)
{
for (int x = 0; x < img->width; x++)
{
dst_buf[y * img->width + x] =
blur_row(first_pass, x, y, img, radius);
}
}
free(first_pass);
return dst_buf;
}
+334
View File
@@ -0,0 +1,334 @@
#include "image/imgio.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <turbojpeg.h>
#include "image/utils.h"
unsigned int*
read_ppm(const char* file, PPM* m_attr)
{
LOG("Decoding");
unsigned char red, green, blue;
char fmt[3];
int max_val;
FILE* fptr;
fptr = fopen(file, "r");
if (!fptr)
{
LOGERROR(ERR_IMG_NAME_INVALID);
LOG(file);
return NULL;
}
fscanf(fptr, "%s", fmt);
m_attr->fmt = fmt[1];
fscanf(fptr, "%d %d", &m_attr->width, &m_attr->height);
m_attr->len = m_attr->width * m_attr->height;
fscanf(fptr, "%d", &max_val);
fgetc(fptr);
unsigned char* img_buf = malloc(m_attr->len * 3);
if (!img_buf)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
unsigned int* clr_buf = malloc(m_attr->len * sizeof(unsigned int));
if (!clr_buf)
{
free(img_buf);
LOGERROR(ERR_BUF_NULL);
return NULL;
}
if (m_attr->fmt == '3')
{
for (int i = 0; i < m_attr->len; i++)
{
fscanf(fptr, "%hhu %hhu %hhu", &red, &green, &blue);
clr_buf[i] = ENCODE_RGB(red, green, blue);
}
}
else if (m_attr->fmt == '6')
{
fread(img_buf, 3, m_attr->len, fptr);
for (int i = 0; i < m_attr->len; i++)
{
red = img_buf[i * 3];
green = img_buf[i * 3 + 1];
blue = img_buf[i * 3 + 2];
clr_buf[i] = ENCODE_RGB(red, green, blue);
}
}
fclose(fptr);
free(img_buf);
LOG("Decoding Finished");
return clr_buf;
}
int
write_ppm(const unsigned int* buf, const PPM img, const char* name)
{
if (!buf)
{
LOGERROR(ERR_BUF_NULL);
return ERR_BUF_NULL;
}
unsigned char* dst_buf = malloc(img.len * 3);
if (!dst_buf)
{
LOGERROR(ERR_BUF_NULL);
return ERR_BUF_NULL;
}
LOG("Encoding");
FILE* fptr;
if (img.fmt == '3')
{
fptr = fopen(name, "w");
}
if (img.fmt == '6')
{
fptr = fopen(name, "wb");
}
if (!fptr)
{
free(dst_buf);
LOGERROR(ERR_FILE_NULL);
return ERR_FILE_NULL;
}
fprintf(fptr, "P%c\n%d %d\n255\n", img.fmt, img.width, img.height);
if (img.fmt == '3')
{
for (int i = 0; i < img.len; i++)
{
fprintf(fptr, "%d %d %d ", DECODE_R(buf[i]),
DECODE_G(buf[i]), DECODE_B(buf[i]));
if (i % 7 == 0)
{
fprintf(fptr, "\n");
}
}
}
if (img.fmt == '6')
{
for (int i = 0; i < img.len; i++)
{
dst_buf[i * 3] = DECODE_R(buf[i]);
dst_buf[i * 3 + 1] = DECODE_G(buf[i]);
dst_buf[i * 3 + 2] = DECODE_B(buf[i]);
}
fwrite(dst_buf, 1, img.len * 3, fptr);
}
fclose(fptr);
free(dst_buf);
LOG("Encoding Finished");
return SUCCESS;
}
unsigned int*
read_jpeg(JPEG* m_attr)
{
LOG("Decoding");
tjhandle tjdecompress = tj3Init(TJINIT_DECOMPRESS);
unsigned char* jpeg_buf = NULL;
FILE* infile = fopen(m_attr->name, "rb");
if (!infile)
{
LOGERROR(ERR_FILE_NULL);
return NULL;
}
fseek(infile, 0, SEEK_END);
m_attr->len = ftell(infile);
fseek(infile, 0, SEEK_SET);
jpeg_buf = (unsigned char*)malloc(m_attr->len);
fread(jpeg_buf, 1, m_attr->len, infile);
fclose(infile);
if (tj3DecompressHeader(tjdecompress, jpeg_buf, m_attr->len) < 0)
{
LOGERROR(ERR_JHEADER);
LOG(tj3GetErrorStr(tjdecompress));
free(jpeg_buf);
return NULL;
}
m_attr->width = tj3Get(tjdecompress, TJPARAM_JPEGWIDTH);
m_attr->height = tj3Get(tjdecompress, TJPARAM_JPEGHEIGHT);
m_attr->len = m_attr->width * m_attr->height;
unsigned int* pixels =
malloc(m_attr->width * m_attr->height * sizeof(unsigned int));
if (!pixels)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
tj3Decompress8(tjdecompress, jpeg_buf, m_attr->len,
(unsigned char*)pixels, 0, TJPF_BGRA);
tj3Destroy(tjdecompress);
free(jpeg_buf);
LOG("Decoding Finished");
return pixels;
}
int
write_jpeg(const unsigned int* src_buf, const JPEG* attr, const char* name)
{
LOG("Encoding");
tjhandle tjcompress = tj3Init(TJINIT_COMPRESS);
unsigned char* dst_buf = NULL;
size_t dst_size = 0;
tj3Set(tjcompress, TJPARAM_QUALITY, 80);
tj3Set(tjcompress, TJPARAM_SUBSAMP, TJSAMP_420);
if (tj3Compress8(tjcompress, (unsigned char*)src_buf, attr->width, 0,
attr->height, TJPF_BGRA, &dst_buf, &dst_size) < 0)
{
LOGERROR(ERR_JHEADER);
LOG(tj3GetErrorStr(tjcompress));
return ERR_JHEADER;
}
FILE* fptr = fopen(name, "wb");
if (!fptr)
{
tj3Free(dst_buf);
LOGERROR(ERR_FILE_NULL);
return ERR_FILE_NULL;
}
if (dst_buf == NULL)
{
tj3Free(dst_buf);
LOGERROR(ERR_BUF_NULL);
return ERR_BUF_NULL;
}
if (dst_size <= 0)
{
tj3Free(dst_buf);
LOGERROR(ERR_INVALID_SIZE);
return ERR_INVALID_SIZE;
}
fwrite(dst_buf, 1, dst_size, fptr);
fclose(fptr);
tj3Destroy(tjcompress);
tj3Free(dst_buf);
LOG("Encoding Finished");
return SUCCESS;
}
void
transcode_to_jpeg(PPM* in)
{
size_t length = find_extension(in->name);
char str2[length];
for (int i = 0; i < length; i++)
{
str2[i] = in->name[i];
}
char* str3 = ".jpg";
char* result = malloc(strlen(str2) + strlen(str3) + 1);
if (result != NULL)
{
strcat(result, str2);
strcat(result, str3);
}
else
{
LOGERROR(ERR_MALLOC_NULL);
return;
}
JPEG img;
if (!in)
{
LOGERROR(ERR_IMG_NULL);
return;
}
unsigned int* dst = read_ppm(in->name, in);
if (!dst)
{
LOGERROR(ERR_BUF_NULL);
return;
}
img.width = in->width;
img.height = in->height;
write_jpeg(dst, &img, result);
free(dst);
free(result);
}
void
transcode_to_ppm(JPEG* in)
{
size_t length = find_extension(in->name);
char str2[length];
for (int i = 0; i < length; i++)
{
str2[i] = in->name[i];
}
char* str3 = ".ppm";
char* result = malloc(strlen(str2) + strlen(str3) + 1);
if (result != NULL)
{
strcat(result, str2);
strcat(result, str3);
}
else
{
LOGERROR(ERR_MALLOC_NULL);
return;
}
PPM img;
if (!in)
{
LOGERROR(ERR_IMG_NULL);
return;
}
unsigned int* dst = read_jpeg(in);
if (!dst)
{
LOGERROR(ERR_BUF_NULL);
return;
}
img.width = in->width;
img.height = in->height;
img.len = img.width * img.height;
write_ppm(dst, img, result);
free(dst);
free(result);
}
PPM
inherit_from_jpeg(const JPEG* in, const char fmt)
{
PPM img;
if (!in)
{
LOGERROR(ERR_IMG_NULL);
return img;
}
PPM image = { .width = in->width,
.height = in->height,
.len = in->len,
.fmt = fmt };
return image;
}
JPEG
inherit_from_ppm(const PPM* in)
{
JPEG blank;
if (!in)
{
LOGERROR(ERR_IMG_NULL);
return blank;
}
JPEG image = {
.width = in->width,
.height = in->height,
.len = in->len,
};
return image;
}
+15 -13
View File
@@ -1,24 +1,26 @@
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <window.h>
#include <string.h>
#include "image/filters.h"
#include "image/imgio.h"
#include "image/transformations.h"
#include "image/utils.h"
// #include "image/filters.h"
// #include "image/transformations.h"
#include "image/imgio.h"
/*
* Keep in mind any function that creates a new buffer and returns it can
* overwrite the old one, however it is lost. SO create a new variable and free
* the old one after use.
*/
int
main()
{
JPEG img;
// PPM out;
img.name = "../assets/IMG_1649.jpg";
//
unsigned int* buf = read_jpeg(&img);
for (int i = 0; i < img.len; i++)
{
buf[i] = u32_grayscale(buf[i]);
}
window_run(buf, img.width, img.height);
free(buf);
PPM img;
img.name = "../assets/IMG_1649_new.ppm";
transcode_to_jpeg(&img);
return 0;
}
+101
View File
@@ -0,0 +1,101 @@
#include "image/transformations.h"
#include <stdio.h>
#include <stdlib.h>
#include "image/utils.h"
unsigned int*
u32_flop(const unsigned int* buf, const PPM img)
{
if (!buf)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
unsigned int* flip = malloc(img.len * sizeof(unsigned int));
if (!flip)
{
LOGERROR(ERR_CREATION_FAIL);
return NULL;
}
int idx = 0;
for (int i = 0; i < img.height; i++)
{
for (int k = img.width - 1; k >= 0; k--)
{
flip[idx] = buf[(i * img.width) + k];
idx++;
}
}
free((void*)buf);
return flip;
}
unsigned int*
u32_flip(const unsigned int* buf, const PPM img)
{
if (!buf)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
unsigned int* flip = malloc(img.len * sizeof(unsigned int));
if (!flip)
{
LOGERROR(ERR_FILE_NULL);
return NULL;
}
int idx = 0;
for (int i = img.height - 1; i >= 0; i--)
{
for (int k = 0; k < img.width; k++)
{
flip[idx] = buf[(i * img.width) + k];
idx++;
}
}
free((void*)buf);
return flip;
}
unsigned int*
u32_rotate(const unsigned int* buf, PPM* m_img)
{
if (!buf)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
if (!m_img)
{
LOGERROR(ERR_IMG_NULL);
return NULL;
}
unsigned int* mask = malloc(m_img->len * sizeof(unsigned int));
if (!mask)
{
LOGERROR(ERR_BUF_NULL);
return NULL;
}
int old_width = m_img->width;
int old_height = m_img->height;
for (int row = 0; row < old_height; row++)
{
for (int col = 0; col < old_width; col++)
{
int new_height = col;
int new_width = (old_height - 1 - row);
mask[(new_height * old_height) + new_width] =
buf[(row * old_width) + col];
}
}
m_img->width = old_height;
m_img->height = old_width;
free((void*)buf);
return mask;
}
+65
View File
@@ -0,0 +1,65 @@
#include "image/utils.h"
#include <stdio.h>
#include <string.h>
const char* error_messages[] = {
[ERR_BUF_NULL] = "Buffer NULL",
[ERR_FILE_NULL] = "File NULL",
[ERR_CREATION_FAIL] = "Buffer creation failed",
[ERR_INVALID_SIZE] = "Given size is invalid",
[ERR_IMG_NULL] = "Image NULL",
[ERR_IMG_NAME_INVALID] = "Invalid File Name",
[ERR_JHEADER] = "Header Error:",
[ERR_MALLOC_NULL] = "Malloc Failed to allocate",
};
unsigned long
u32to_u64(const unsigned int clr)
{
unsigned long mask = 0;
unsigned long alpha = DECODE_A(clr);
unsigned long red = DECODE_R(clr);
unsigned long green = DECODE_G(clr);
unsigned long blue = DECODE_B(clr);
return (alpha << 48) | (red << 32) | (green << 16) | (blue);
}
unsigned int
u64to_u32(const unsigned long clr, const unsigned long u64_div)
{
unsigned int a = ((clr >> 48) & LONG_BYTE);
unsigned int r = ((clr >> 32) & LONG_BYTE);
unsigned int g = ((clr >> 16) & LONG_BYTE);
unsigned int b = (clr & LONG_BYTE);
return ENCODE_ARGB((a / u64_div), (r / u64_div), (g / u64_div),
(b / u64_div));
}
void __attribute__((overloadable))
print_attr(const PPM* src)
{
printf("Name: %s\nFMT: %c\nWidth: %i, Height: %i\nLength: %i\n",
src->name, src->fmt, src->width, src->height, src->len);
}
void __attribute__((overloadable))
print_attr(const JPEG* src)
{
printf("Name: %s\nWidth: %i, Height: %i\nLength: %i\n", src->name,
src->width, src->height, src->len);
}
size_t
find_extension(const char* n)
{
size_t length = strlen(n);
for (int i = length; i >= 0; i--)
{
if (n[i] == '.')
{
return i;
}
}
return FAILURE;
}
-211
View File
@@ -1,211 +0,0 @@
#import <AppKit/AppKit.h>
#include "window.h"
static const CGFloat kScreenMargin = 40.0; /* keep some breathing room */
/*
* The renderer view. It knows one thing: an image, and how to draw it.
* Aspect-fit + centered, so it survives window resizes.
*
* NOTE the ownership discipline: CGImage is a CoreFoundation type, which
* ARC does NOT manage. We CFRetain on init and CFRelease in dealloc.
*/
@interface ImageRenderView : NSView
{
CGImageRef _image;
}
- (instancetype)initWithFrame:(NSRect)frame image:(CGImageRef)image;
@end
@implementation ImageRenderView
- (instancetype)initWithFrame:(NSRect)frame image:(CGImageRef)image
{
self = [super initWithFrame:frame];
if (self)
{
/* We take our own +1 so the caller keeps ownership of theirs. */
_image = image ? CFRetain(image) : NULL;
}
return self;
}
- (void)dealloc
{
if (_image != NULL)
{
CFRelease(_image);
}
/* NOTE: no [super dealloc] call under ARC — the compiler inserts it. */
}
- (void)drawRect:(NSRect)rect
{
if (_image == NULL)
{
return;
}
CGContextRef ctx = [[NSGraphicsContext currentContext] CGContext];
/* Native size of the image, in pixels. */
CGFloat imgW = CGImageGetWidth(_image);
CGFloat imgH = CGImageGetHeight(_image);
if (imgW <= 0 || imgH <= 0)
{
return;
}
/* Aspect-fit: uniform scale that makes the image fit in our bounds. */
CGFloat scale = MIN(self.bounds.size.width / imgW,
self.bounds.size.height / imgH);
CGFloat drawW = imgW * scale;
CGFloat drawH = imgH * scale;
/* Center it in our bounds. */
CGRect dest = CGRectMake((self.bounds.size.width - drawW) / 2.0,
(self.bounds.size.height - drawH) / 2.0,
drawW,
drawH);
CGContextDrawImage(ctx, dest, _image);
}
@end
/*
* The delegate. Same as before, plus the image plumbing:
* stores buf/w/h, builds the CGImage and the render view at launch,
* sizes the window TO the image, then shows it.
*/
@interface WindowDelegate : NSObject <NSApplicationDelegate>
@property (strong) NSWindow* window;
@property (strong) ImageRenderView* renderView;
@property (nonatomic) const unsigned int* buf; /* read-only peephole into main's buffer */
@property (nonatomic) int width;
@property (nonatomic) int height;
@end
@implementation WindowDelegate
// /*
// * Wrap
- (void)applicationDidFinishLaunching:(NSNotification*)note
{
if (self.buf == NULL || self.width <= 0 || self.height <= 0)
{
return; /* nothing to draw; don't crash */
}
/*
* 1. Wrap the C buffer in a Core Graphics image.
*
* Data provider = a window into main.c's memory. The release
* callback is NULL, meaning "I don't own these bytes, never free
* them." The bytes stay valid because main only frees buf AFTER
* window_run returns (the pool drains, the window/view/image get
* released, THEN main frees). Keep that ordering in mind forever.
*/
size_t bytesPerRow = (size_t)self.width * 4;
CGDataProviderRef provider = CGDataProviderCreateWithData(
NULL, self.buf, bytesPerRow * self.height, NULL);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
/* The pixel-format decision — this is the "get it wrong = red/blue
* swap" part. libimg stores host-endian 0xAARRGGBB. On your M2
* (little-endian) the byte order in memory is B,G,R,A, which is
* exactly what:
* kCGImageAlphaFirst | kCGBitmapByteOrder32Host
* means: alpha first in the word, 32-bit host byte order. */
CGImageRef image = CGImageCreate(
self.width, self.height, /* pixel dimensions */
8, 32, /* 8 bits/channel, 32 bits/px */
bytesPerRow, /* no padding in libimg rows */
colorSpace,
kCGImageAlphaFirst | kCGBitmapByteOrder32Host,
provider, NULL, NO, /* translate, decode, interpol*/
kCGRenderingIntentDefault);
CGDataProviderRelease(provider); /* image keeps its own ref */
CGColorSpaceRelease(colorSpace);
/*
* 2. Size the window TO the image, capped by the screen.
* scale = min(1, ...) => never upscale past native pixels.
*/
CGRect visible = [[NSScreen mainScreen] visibleFrame];
CGFloat capW = visible.size.width - 2.0 * kScreenMargin;
CGFloat capH = visible.size.height - 2.0 * kScreenMargin;
CGFloat scale = MIN(1.0, MIN(capW / (CGFloat)self.width,
capH / (CGFloat)self.height));
NSSize contentSize = NSMakeSize(round(self.width * scale),
round(self.height * scale));
/*
* 3. Build the window with content rect = the fitted size.
* initWithContentRect: means this IS the drawable area; the title
* bar is added on top by the style mask.
*/
NSWindow* w = [[NSWindow alloc]
initWithContentRect:NSMakeRect(0, 0, contentSize.width, contentSize.height)
styleMask:(NSWindowStyleMaskTitled |
NSWindowStyleMaskClosable |
NSWindowStyleMaskResizable)
backing:NSBackingStoreBuffered
defer:NO];
w.releasedWhenClosed = NO; /* we own the lifetime (ARC strong ref) */
/*
* 4. Install the renderer as the content view. Creating it with a
* zero rect is fine — setting it as contentView sizes it to the
* window's content area. The view CFRetains the image; we drop
* OUR +1 now that the view holds it.
*/
ImageRenderView* view = [[ImageRenderView alloc] initWithFrame:NSZeroRect
image:image];
CGImageRelease(image); /* view now owns the only reference */
w.contentView = view;
self.window = w;
self.renderView = view;
[w setTitle:@"libgl"];
[w center];
[NSApp activate]; /* make it a real frontmost app */
[w makeKeyAndOrderFront:nil]; /* show + focus */
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender
{
return YES; /* closing the window = clean exit, code 0 */
}
@end
int
window_run(const unsigned int* buf, int width, int height)
{
@autoreleasepool
{
NSApplication* app = [NSApplication sharedApplication];
[app setActivationPolicy:NSApplicationActivationPolicyRegular];
/*
* Buffer rides along in the delegate so it's available in the
* launch callback. Delegate must stay alive (strong local)
* through run — NSApplication.delegate is ASSIGN, not strong.
*/
WindowDelegate* delegate = [[WindowDelegate alloc] init];
delegate.buf = buf;
delegate.width = width;
delegate.height = height;
[app setDelegate:delegate];
[app run]; /* blocks until the app terminates */
return EXIT_SUCCESS;
}
}