Reformat code

This commit is contained in:
2023-09-24 21:15:57 +02:00
parent 456b873de0
commit 584b0cffc5
23 changed files with 5711 additions and 6018 deletions

View File

@@ -2,32 +2,30 @@
Language: Cpp Language: Cpp
# BasedOnStyle: LLVM # BasedOnStyle: LLVM
AccessModifierOffset: -2 AccessModifierOffset: -2
AlignAfterOpenBracket: true AlignAfterOpenBracket: AlwaysBreak
AlignEscapedNewlinesLeft: false
AlignOperands: true AlignOperands: true
AlignTrailingComments: true AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: All
AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakTemplateDeclarations: false AlwaysBreakTemplateDeclarations: No
AlwaysBreakBeforeMultilineStrings: false AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false BreakConstructorInitializersBeforeComma: false
BinPackParameters: true BinPackParameters: true
BinPackArguments: true BinPackArguments: false
ColumnLimit: 80 ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4 ConstructorInitializerIndentWidth: 4
DerivePointerAlignment: false DerivePointerAlignment: false
ExperimentalAutoDetectBinPacking: false ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false IndentCaseLabels: false
IndentWrappedFunctionNames: false IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
MaxEmptyLinesToKeep: 1 MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: true KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: None NamespaceIndentation: None
@@ -43,10 +41,10 @@ PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right PointerAlignment: Right
SpacesBeforeTrailingComments: 1 SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true Cpp11BracedListStyle: true
Standard: Cpp11 Standard: c++11
IndentWidth: 4 IndentWidth: 4
TabWidth: 4 TabWidth: 4
UseTab: true UseTab: AlignWithSpaces
BreakBeforeBraces: Attach BreakBeforeBraces: Attach
SpacesInParentheses: false SpacesInParentheses: false
SpacesInSquareBrackets: false SpacesInSquareBrackets: false
@@ -57,9 +55,9 @@ SpaceAfterCStyleCast: false
SpacesInContainerLiterals: true SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4 ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:'
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements SpaceBeforeParens: ControlStatements
DisableFormat: false DisableFormat: false
AlignConsecutiveAssignments: Consecutive
... ...

View File

@@ -2,32 +2,30 @@
Language: Cpp Language: Cpp
# BasedOnStyle: LLVM # BasedOnStyle: LLVM
AccessModifierOffset: -2 AccessModifierOffset: -2
AlignAfterOpenBracket: true AlignAfterOpenBracket: AlwaysBreak
AlignEscapedNewlinesLeft: false
AlignOperands: true AlignOperands: true
AlignTrailingComments: true AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: All
AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakTemplateDeclarations: false AlwaysBreakTemplateDeclarations: No
AlwaysBreakBeforeMultilineStrings: false AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false BreakConstructorInitializersBeforeComma: false
BinPackParameters: true BinPackParameters: true
BinPackArguments: true BinPackArguments: false
ColumnLimit: 80 ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4 ConstructorInitializerIndentWidth: 4
DerivePointerAlignment: false DerivePointerAlignment: false
ExperimentalAutoDetectBinPacking: false ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false IndentCaseLabels: false
IndentWrappedFunctionNames: false IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
MaxEmptyLinesToKeep: 1 MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: true KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: None NamespaceIndentation: None
@@ -43,10 +41,10 @@ PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right PointerAlignment: Right
SpacesBeforeTrailingComments: 1 SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true Cpp11BracedListStyle: true
Standard: Cpp11 Standard: c++11
IndentWidth: 4 IndentWidth: 4
TabWidth: 4 TabWidth: 4
UseTab: true UseTab: AlignWithSpaces
BreakBeforeBraces: Attach BreakBeforeBraces: Attach
SpacesInParentheses: false SpacesInParentheses: false
SpacesInSquareBrackets: false SpacesInSquareBrackets: false
@@ -57,9 +55,9 @@ SpaceAfterCStyleCast: false
SpacesInContainerLiterals: true SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4 ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:'
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements SpaceBeforeParens: ControlStatements
DisableFormat: false DisableFormat: false
AlignConsecutiveAssignments: Consecutive
... ...

View File

@@ -48,8 +48,7 @@ void Player_Proc(Entity e, int ft) {
Entity_SetScale(e, entityScale); Entity_SetScale(e, entityScale);
if (e->A > 0) { if (e->A > 0) {
if (Input_GetKey(InputKey_Jump) == InputKey_Pressed || if (Input_GetKey(InputKey_Jump) == InputKey_Pressed || Input_GetKey(InputKey_Up) == InputKey_Pressed) {
Input_GetKey(InputKey_Up) == InputKey_Pressed) {
// Apply jump // Apply jump
if (e->vel[1] > (-jumpVel)) { if (e->vel[1] > (-jumpVel)) {
@@ -91,8 +90,7 @@ void Player_Proc(Entity e, int ft) {
Entity_AddVelLimit(e, right, maxVel * airMovementFactor); Entity_AddVelLimit(e, right, maxVel * airMovementFactor);
} }
} }
if (Input_GetKey(InputKey_Action1) == InputKey_Pressed || if (Input_GetKey(InputKey_Action1) == InputKey_Pressed || Input_GetKey(InputKey_Action2) == InputKey_Pressed) {
Input_GetKey(InputKey_Action2) == InputKey_Pressed) {
Entity_SetScale(e, (float[2]){1.0f, 1.0f}); Entity_SetScale(e, (float[2]){1.0f, 1.0f});
} }
@@ -114,14 +112,12 @@ int Player_Collision(Entity ent, Entity ent2, float t, vec2 n) {
if (fabs(n[0]) > fabs(n[1])) { if (fabs(n[0]) > fabs(n[1])) {
float intensity = (fabs(ent->vel[0]) - 10.0f) / 40.0f; float intensity = (fabs(ent->vel[0]) - 10.0f) / 40.0f;
if (intensity > 0) { if (intensity > 0) {
Entity_SetScale(ent, (float[2]){1.0f - (0.3f * intensity), Entity_SetScale(ent, (float[2]){1.0f - (0.3f * intensity), 1.0f + (0.3f * intensity)});
1.0f + (0.3f * intensity)});
} }
} else { } else {
float intensity = (fabs(ent->vel[1]) - 10.0f) / 40.0f; float intensity = (fabs(ent->vel[1]) - 10.0f) / 40.0f;
if (intensity > 0) { if (intensity > 0) {
Entity_SetScale(ent, (float[2]){1.0f + (0.3f * intensity), Entity_SetScale(ent, (float[2]){1.0f + (0.3f * intensity), 1.0f - (0.3f * intensity)});
1.0f - (0.3f * intensity)});
} }
} }
return -1; return -1;

View File

@@ -59,8 +59,7 @@ int main(int argc, char *argv[]) {
// Run the world. // Run the world.
// //
GameLib_CleanParallaxBackgrounds(); GameLib_CleanParallaxBackgrounds();
GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512}, GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512}, (int[2]){0, 0}, (float[2]){0.5f, 0.0f});
(int[2]){0, 0}, (float[2]){0.5f, 0.0f});
GameLib_Loop(ProcGame, PostProcGame, PreDrawGame, DrawGame); GameLib_Loop(ProcGame, PostProcGame, PreDrawGame, DrawGame);
return (0); return (0);

View File

@@ -5,8 +5,8 @@
Feel free to customize this file to suit your needs Feel free to customize this file to suit your needs
*/ */
#include <SDL.h>
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include <SDL.h>
@interface SDLMain : NSObject @interface SDLMain : NSObject
@end @end
@@ -17,7 +17,7 @@
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4, /* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare but the method still is there and works. To avoid warnings, we declare
it ourselves here. */ it ourselves here. */
@interface NSApplication(SDL_Missing_Methods) @interface NSApplication (SDL_Missing_Methods)
- (void)setAppleMenu:(NSMenu *)menu; - (void)setAppleMenu:(NSMenu *)menu;
@end @end
@@ -28,15 +28,15 @@
#define SDL_USE_CPS 1 #define SDL_USE_CPS 1
#ifdef SDL_USE_CPS #ifdef SDL_USE_CPS
/* Portions of CPS.h */ /* Portions of CPS.h */
typedef struct CPSProcessSerNum typedef struct CPSProcessSerNum {
{
UInt32 lo; UInt32 lo;
UInt32 hi; UInt32 hi;
} CPSProcessSerNum; } CPSProcessSerNum;
extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); extern OSErr CPSGetCurrentProcess(CPSProcessSerNum *psn);
extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); extern OSErr
extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); CPSEnableForegroundOperation(CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess(CPSProcessSerNum *psn);
#endif /* SDL_USE_CPS */ #endif /* SDL_USE_CPS */
@@ -45,15 +45,14 @@ static char **gArgv;
static BOOL gFinderLaunch; static BOOL gFinderLaunch;
static BOOL gCalledAppMainline = FALSE; static BOOL gCalledAppMainline = FALSE;
static NSString *getApplicationName(void) static NSString *getApplicationName(void) {
{
const NSDictionary *dict; const NSDictionary *dict;
NSString *appName = 0; NSString *appName = 0;
/* Determine the application name */ /* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict) if (dict)
appName = [dict objectForKey: @"CFBundleName"]; appName = [dict objectForKey:@"CFBundleName"];
if (![appName length]) if (![appName length])
appName = [[NSProcessInfo processInfo] processName]; appName = [[NSProcessInfo processInfo] processName];
@@ -73,8 +72,7 @@ static NSString *getApplicationName(void)
@implementation NSApplication (SDLApplication) @implementation NSApplication (SDLApplication)
/* Invoked from the Quit menu item */ /* Invoked from the Quit menu item */
- (void)terminate:(id)sender - (void)terminate:(id)sender {
{
/* Post a SDL_QUIT event */ /* Post a SDL_QUIT event */
SDL_Event event; SDL_Event event;
event.type = SDL_QUIT; event.type = SDL_QUIT;
@@ -86,10 +84,8 @@ static NSString *getApplicationName(void)
@implementation SDLMain @implementation SDLMain
/* Set the working directory to the .app's parent directory */ /* Set the working directory to the .app's parent directory */
- (void) setupWorkingDirectory:(BOOL)shouldChdir - (void)setupWorkingDirectory:(BOOL)shouldChdir {
{ if (shouldChdir) {
if (shouldChdir)
{
char parentdir[MAXPATHLEN]; char parentdir[MAXPATHLEN];
CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
@@ -104,22 +100,20 @@ static NSString *getApplicationName(void)
#if SDL_USE_NIB_FILE #if SDL_USE_NIB_FILE
/* Fix menu to contain the real app name instead of "SDL App" */ /* Fix menu to contain the real app name instead of "SDL App" */
- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName {
{
NSRange aRange; NSRange aRange;
NSEnumerator *enumerator; NSEnumerator *enumerator;
NSMenuItem *menuItem; NSMenuItem *menuItem;
aRange = [[aMenu title] rangeOfString:@"SDL App"]; aRange = [[aMenu title] rangeOfString:@"SDL App"];
if (aRange.length != 0) if (aRange.length != 0)
[aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; [aMenu setTitle:[[aMenu title] stringByReplacingRange:aRange with:appName]];
enumerator = [[aMenu itemArray] objectEnumerator]; enumerator = [[aMenu itemArray] objectEnumerator];
while ((menuItem = [enumerator nextObject])) while ((menuItem = [enumerator nextObject])) {
{
aRange = [[menuItem title] rangeOfString:@"SDL App"]; aRange = [[menuItem title] rangeOfString:@"SDL App"];
if (aRange.length != 0) if (aRange.length != 0)
[menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; [menuItem setTitle:[[menuItem title] stringByReplacingRange:aRange with:appName]];
if ([menuItem hasSubmenu]) if ([menuItem hasSubmenu])
[self fixMenu:[menuItem submenu] withAppName:appName]; [self fixMenu:[menuItem submenu] withAppName:appName];
} }
@@ -127,8 +121,7 @@ static NSString *getApplicationName(void)
#else #else
static void setApplicationMenu(void) static void setApplicationMenu(void) {
{
/* warning: this code is very odd */ /* warning: this code is very odd */
NSMenu *appleMenu; NSMenu *appleMenu;
NSMenuItem *menuItem; NSMenuItem *menuItem;
@@ -147,8 +140,10 @@ static void setApplicationMenu(void)
title = [@"Hide " stringByAppendingString:appName]; title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others"
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; action:@selector(hideOtherApplications:)
keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
@@ -157,7 +152,6 @@ static void setApplicationMenu(void)
title = [@"Quit " stringByAppendingString:appName]; title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */ /* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu]; [menuItem setSubmenu:appleMenu];
@@ -172,8 +166,7 @@ static void setApplicationMenu(void)
} }
/* Create a window menu */ /* Create a window menu */
static void setupWindowMenu(void) static void setupWindowMenu(void) {
{
NSMenu *windowMenu; NSMenu *windowMenu;
NSMenuItem *windowMenuItem; NSMenuItem *windowMenuItem;
NSMenuItem *menuItem; NSMenuItem *menuItem;
@@ -199,8 +192,7 @@ static void setupWindowMenu(void)
} }
/* Replacement for NSApplicationMain */ /* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv) static void CustomApplicationMain(int argc, char **argv) {
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
SDLMain *sdlMain; SDLMain *sdlMain;
@@ -212,7 +204,7 @@ static void CustomApplicationMain (int argc, char **argv)
CPSProcessSerNum PSN; CPSProcessSerNum PSN;
/* Tell the dock about us */ /* Tell the dock about us */
if (!CPSGetCurrentProcess(&PSN)) if (!CPSGetCurrentProcess(&PSN))
if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) if (!CPSEnableForegroundOperation(&PSN, 0x03, 0x3C, 0x2C, 0x1103))
if (!CPSSetFrontProcess(&PSN)) if (!CPSSetFrontProcess(&PSN))
[NSApplication sharedApplication]; [NSApplication sharedApplication];
} }
@@ -236,7 +228,6 @@ static void CustomApplicationMain (int argc, char **argv)
#endif #endif
/* /*
* Catch document open requests...this lets us notice files when the app * Catch document open requests...this lets us notice files when the app
* was launched by double-clicking a document, or when a document was * was launched by double-clicking a document, or when a document was
@@ -252,8 +243,7 @@ static void CustomApplicationMain (int argc, char **argv)
* *
* This message is ignored once the app's mainline has been called. * This message is ignored once the app's mainline has been called.
*/ */
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename {
{
const char *temparg; const char *temparg;
size_t arglen; size_t arglen;
char *arg; char *arg;
@@ -267,13 +257,12 @@ static void CustomApplicationMain (int argc, char **argv)
temparg = [filename UTF8String]; temparg = [filename UTF8String];
arglen = SDL_strlen(temparg) + 1; arglen = SDL_strlen(temparg) + 1;
arg = (char *) SDL_malloc(arglen); arg = (char *)SDL_malloc(arglen);
if (arg == NULL) if (arg == NULL)
return FALSE; return FALSE;
newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); newargv = (char **)realloc(gArgv, sizeof(char *) * (gArgc + 2));
if (newargv == NULL) if (newargv == NULL) {
{
SDL_free(arg); SDL_free(arg);
return FALSE; return FALSE;
} }
@@ -285,10 +274,8 @@ static void CustomApplicationMain (int argc, char **argv)
return TRUE; return TRUE;
} }
/* Called when the internal event loop has just started running */ /* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note - (void)applicationDidFinishLaunching:(NSNotification *)note {
{
int status; int status;
/* Set the working directory to the .app's parent directory */ /* Set the working directory to the .app's parent directory */
@@ -301,18 +288,16 @@ static void CustomApplicationMain (int argc, char **argv)
/* Hand off to main application code */ /* Hand off to main application code */
gCalledAppMainline = TRUE; gCalledAppMainline = TRUE;
status = SDL_main (gArgc, gArgv); status = SDL_main(gArgc, gArgv);
/* We're done, thank you for playing */ /* We're done, thank you for playing */
exit(status); exit(status);
} }
@end @end
@implementation NSString (ReplaceSubString) @implementation NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString {
{
unsigned int bufferSize; unsigned int bufferSize;
unsigned int selfLen = [self length]; unsigned int selfLen = [self length];
unsigned int aStringLen = [aString length]; unsigned int aStringLen = [aString length];
@@ -321,7 +306,7 @@ static void CustomApplicationMain (int argc, char **argv)
NSString *result; NSString *result;
bufferSize = selfLen + aStringLen - aRange.length; bufferSize = selfLen + aStringLen - aRange.length;
buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar)); buffer = (unichar *)NSAllocateMemoryPages(bufferSize * sizeof(unichar));
/* Get first part into buffer */ /* Get first part into buffer */
localRange.location = 0; localRange.location = 0;
@@ -331,12 +316,12 @@ static void CustomApplicationMain (int argc, char **argv)
/* Get middle part into buffer */ /* Get middle part into buffer */
localRange.location = 0; localRange.location = 0;
localRange.length = aStringLen; localRange.length = aStringLen;
[aString getCharacters:(buffer+aRange.location) range:localRange]; [aString getCharacters:(buffer + aRange.location) range:localRange];
/* Get last part into buffer */ /* Get last part into buffer */
localRange.location = aRange.location + aRange.length; localRange.location = aRange.location + aRange.length;
localRange.length = selfLen - localRange.location; localRange.length = selfLen - localRange.location;
[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; [self getCharacters:(buffer + aRange.location + aStringLen) range:localRange];
/* Build output string */ /* Build output string */
result = [NSString stringWithCharacters:buffer length:bufferSize]; result = [NSString stringWithCharacters:buffer length:bufferSize];
@@ -348,20 +333,16 @@ static void CustomApplicationMain (int argc, char **argv)
@end @end
#ifdef main #ifdef main
# undef main #undef main
#endif #endif
/* Main entry point to executable - should *not* be SDL_main! */ /* Main entry point to executable - should *not* be SDL_main! */
int main (int argc, char **argv) int main(int argc, char **argv) {
{
/* Copy the arguments into a global variable */ /* Copy the arguments into a global variable */
/* This is passed if we are launched by double-clicking */ /* This is passed if we are launched by double-clicking */
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { if (argc >= 2 && strncmp(argv[1], "-psn", 4) == 0) {
gArgv = (char **) SDL_malloc(sizeof (char *) * 2); gArgv = (char **)SDL_malloc(sizeof(char *) * 2);
gArgv[0] = argv[0]; gArgv[0] = argv[0];
gArgv[1] = NULL; gArgv[1] = NULL;
gArgc = 1; gArgc = 1;
@@ -369,16 +350,16 @@ int main (int argc, char **argv)
} else { } else {
int i; int i;
gArgc = argc; gArgc = argc;
gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); gArgv = (char **)SDL_malloc(sizeof(char *) * (argc + 1));
for (i = 0; i <= argc; i++) for (i = 0; i <= argc; i++)
gArgv[i] = argv[i]; gArgv[i] = argv[i];
gFinderLaunch = NO; gFinderLaunch = NO;
} }
#if SDL_USE_NIB_FILE #if SDL_USE_NIB_FILE
NSApplicationMain (argc, argv); NSApplicationMain(argc, argv);
#else #else
CustomApplicationMain (argc, argv); CustomApplicationMain(argc, argv);
#endif #endif
return 0; return 0;
} }

View File

@@ -159,8 +159,7 @@ void AnimPlay_SetAnim(AnimPlay *ap, Anim ani) {
ap->imgPart = NULL; ap->imgPart = NULL;
} }
void AnimPlay_SetImgPart(AnimPlay *ap, DrawImg img, int w, int h, int i, void AnimPlay_SetImgPart(AnimPlay *ap, DrawImg img, int w, int h, int i, int j) {
int j) {
ap->anim = NULL; ap->anim = NULL;
ap->time_ms = 0; ap->time_ms = 0;
@@ -187,8 +186,7 @@ void AnimPlay_Draw(AnimPlay *ani, int x, int y, float scale[2]) {
return; return;
} }
if (ani->imgPart) { if (ani->imgPart) {
Draw_DrawImgPart(ani->imgPart, x, y, ani->w, ani->h, ani->i, ani->j, Draw_DrawImgPart(ani->imgPart, x, y, ani->w, ani->h, ani->i, ani->j, scale);
scale);
return; return;
} }
} }

View File

@@ -174,8 +174,7 @@ static void Audio_MixerCallback(void *ud, Uint8 *stream, int l) {
// Next sample // Next sample
ptr_out += 2; ptr_out += 2;
if (ptr_wave >= if (ptr_wave >= (((signed short *)wave->buffer) + (wave->len - 1))) {
(((signed short *)wave->buffer) + (wave->len - 1))) {
ptr_wave = ((signed short *)wave->buffer); ptr_wave = ((signed short *)wave->buffer);
} else { } else {
ptr_wave++; ptr_wave++;
@@ -260,9 +259,12 @@ AudioSnd Audio_LoadSound(char *filename) {
// Assert sound format // Assert sound format
if (sampleRate != 44100 || channels != 1 || bitsPerSample != 2) { if (sampleRate != 44100 || channels != 1 || bitsPerSample != 2) {
Print("Audio_LoadSound: Format not supported: " Print(
"Audio_LoadSound: Format not supported: "
"sampleRate:%d; channels:%d; BPB:%d\n", "sampleRate:%d; channels:%d; BPB:%d\n",
sampleRate, channels, bitsPerSample); sampleRate,
channels,
bitsPerSample);
fclose(f); fclose(f);
return (NULL); return (NULL);
} }
@@ -313,8 +315,7 @@ AudioSnd Audio_LoadSound(char *filename) {
// Audio_PlaySound // Audio_PlaySound
// //
// Loads a sound, giving a reference. // Loads a sound, giving a reference.
AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol, AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol, int loop) {
int loop) {
AudioChan chan; AudioChan chan;
AudioWave wave; AudioWave wave;
if (!snd) { if (!snd) {

View File

@@ -275,12 +275,12 @@ int Draw_Init(int width, int height, char *title, int pfps, int fps) {
glBindBuffer(GL_ARRAY_BUFFER, vertexObject); glBindBuffer(GL_ARRAY_BUFFER, vertexObject);
glVertexAttribPointer(vertPosLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), glVertexAttribPointer(
(void *)(0 * sizeof(float))); vertPosLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), (void *)(0 * sizeof(float)));
glVertexAttribPointer(vertTexLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), glVertexAttribPointer(
(void *)(2 * sizeof(float))); vertTexLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), (void *)(2 * sizeof(float)));
glVertexAttribPointer(vertColorLoc, 4, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), glVertexAttribPointer(
(void *)(4 * sizeof(float))); vertColorLoc, 4, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), (void *)(4 * sizeof(float)));
glEnableVertexAttribArray(vertPosLoc); glEnableVertexAttribArray(vertPosLoc);
glEnableVertexAttribArray(vertTexLoc); glEnableVertexAttribArray(vertTexLoc);
@@ -342,8 +342,23 @@ void Draw_ShowInfo() {
// Sets the render matrix // Sets the render matrix
void Draw_SetMatrix(float matrix[16]) { void Draw_SetMatrix(float matrix[16]) {
#if USE_OpenGL #if USE_OpenGL
float tempMatrix[16] = {matrix[0], matrix[4], matrix[8], matrix[12], matrix[1], matrix[5], matrix[9], matrix[13], float tempMatrix[16] = {
matrix[2], matrix[6], matrix[10], matrix[14], matrix[3], matrix[7], matrix[11], matrix[15]}; matrix[0],
matrix[4],
matrix[8],
matrix[12],
matrix[1],
matrix[5],
matrix[9],
matrix[13],
matrix[2],
matrix[6],
matrix[10],
matrix[14],
matrix[3],
matrix[7],
matrix[11],
matrix[15]};
glLoadMatrixf(tempMatrix); glLoadMatrixf(tempMatrix);
#endif #endif
#if USE_OpenGLES #if USE_OpenGLES
@@ -879,8 +894,8 @@ void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, float scale[
// Draw_ImgParallax // Draw_ImgParallax
// //
// //
void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], void Draw_ImgParallax(
int gameSize[2]) { DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], int gameSize[2]) {
int paralaxPos[2]; int paralaxPos[2];
int mult[2]; int mult[2];
int x, y; int x, y;

View File

@@ -19,8 +19,7 @@ void Draw_Clean(unsigned char r, unsigned char g, unsigned char b);
// Draw_Loop // Draw_Loop
// //
// Loops updating the game window. // Loops updating the game window.
void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), void *data);
void *data);
///////////////////////////// /////////////////////////////
// Draw_BreakLoop // Draw_BreakLoop
@@ -95,22 +94,20 @@ void Draw_DrawImgResized(DrawImg img, int x, int y, float w, float h);
// Draw_DrawImgPart // Draw_DrawImgPart
// //
// Draws an image part. // Draws an image part.
void Draw_DrawImgPart(DrawImg img, int x, int y, int w, int h, int i, int j, void Draw_DrawImgPart(DrawImg img, int x, int y, int w, int h, int i, int j, float scale[2]);
float scale[2]);
///////////////////////////// /////////////////////////////
// Draw_DrawImgPartHoriz // Draw_DrawImgPartHoriz
// //
// Draws an image part horizontally. // Draws an image part horizontally.
void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, float scale[2]);
float scale[2]);
///////////////////////////// /////////////////////////////
// Draw_ImgParallax // Draw_ImgParallax
// //
// //
void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], void Draw_ImgParallax(
float parallaxFactor[2], int gamePos[2], int gameSize[2]); DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], int gameSize[2]);
///////////////////////////// /////////////////////////////
// Draw_SetColor // Draw_SetColor
@@ -128,8 +125,7 @@ typedef void *DrawFnt;
// Draw_DefaultFont // Draw_DefaultFont
// //
// Creates the default font. // Creates the default font.
DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
unsigned char a);
///////////////////////////// /////////////////////////////
// Draw_LoadFont // Draw_LoadFont
@@ -152,15 +148,13 @@ void Draw_DrawText(DrawFnt f, char *text, int x, int y);
// Draw_SaveRGBAToBMP // Draw_SaveRGBAToBMP
// //
// //
void Draw_SaveRGBAToBMP(char *filename, unsigned char *data, int width, void Draw_SaveRGBAToBMP(char *filename, unsigned char *data, int width, int height);
int height);
///////////////////////////// /////////////////////////////
// Draw_SaveRGBAToPNG // Draw_SaveRGBAToPNG
// //
// //
void Draw_SaveRGBAToPNG(char *filename, unsigned char *data, int width, void Draw_SaveRGBAToPNG(char *filename, unsigned char *data, int width, int height);
int height);
///////////////////////////// /////////////////////////////
// Draw_SaveScreenshoot // Draw_SaveScreenshoot

View File

@@ -69,8 +69,7 @@ Entity Entity_New() {
e->color[0] = e->color[1] = e->color[2] = e->color[3] = 1.0f; e->color[0] = e->color[1] = e->color[2] = e->color[3] = 1.0f;
e->light[0] = e->light[1] = e->light[2] = e->light[3] = 1.0f; e->light[0] = e->light[1] = e->light[2] = e->light[3] = 1.0f;
e->defaultColor[0] = e->defaultColor[1] = e->defaultColor[2] = e->defaultColor[0] = e->defaultColor[1] = e->defaultColor[2] = e->defaultColor[3] = 1.0f;
e->defaultColor[3] = 1.0f;
e->scale0[0] = 1.0f; e->scale0[0] = 1.0f;
e->scale0[1] = 1.0f; e->scale0[1] = 1.0f;
@@ -225,8 +224,7 @@ void Entity_CalcBBox(Entity e) {
// //
// //
int Entity_BBoxIntersect(Entity ent1, Entity ent2) { int Entity_BBoxIntersect(Entity ent1, Entity ent2) {
if (ent1->maxX >= ent2->minX && ent1->minX <= ent2->maxX && if (ent1->maxX >= ent2->minX && ent1->minX <= ent2->maxX && ent1->maxY >= ent2->minY && ent1->minY <= ent2->maxY) {
ent1->maxY >= ent2->minY && ent1->minY <= ent2->maxY) {
return (1); return (1);
} }
return (0); return (0);
@@ -240,7 +238,8 @@ void Entity_Draw(Entity e, int x, int y, float f) {
vec2 fPos; vec2 fPos;
float scale[2]; float scale[2];
if (e->internalFlags & EntityIntFlag_UpdatedColor) { if (e->internalFlags & EntityIntFlag_UpdatedColor) {
Draw_SetColor(e->color0[0] - f * (e->color0[0] - e->color[0]), Draw_SetColor(
e->color0[0] - f * (e->color0[0] - e->color[0]),
e->color0[1] - f * (e->color0[1] - e->color[1]), e->color0[1] - f * (e->color0[1] - e->color[1]),
e->color0[2] - f * (e->color0[2] - e->color[2]), e->color0[2] - f * (e->color0[2] - e->color[2]),
e->color0[3] - f * (e->color0[3] - e->color[3])); e->color0[3] - f * (e->color0[3] - e->color[3]));
@@ -278,8 +277,7 @@ int Entity_IsVisible(Entity e, int x, int y, int w, int h) {
ymin = y - ih; ymin = y - ih;
ymax = y + h + ih; ymax = y + h + ih;
if (e->pos[0] < xmin || e->pos[0] > xmax || e->pos[1] < ymin || if (e->pos[0] < xmin || e->pos[0] > xmax || e->pos[1] < ymin || e->pos[1] > ymax) {
e->pos[1] > ymax) {
return (0); return (0);
} }
return (1); return (1);
@@ -336,9 +334,7 @@ void Entity_PostProcess(Entity e, int ft) {
vec2_set(e->vel, 0, 0); vec2_set(e->vel, 0, 0);
} else { } else {
// Apply dynamic friction // Apply dynamic friction
vec2_scale(e->vel, e->vel, vec2_scale(e->vel, e->vel, 1.0f - (e->backFric_dynamic + (e->backFric_static / len)));
1.0f -
(e->backFric_dynamic + (e->backFric_static / len)));
} }
// Mark the update of the position. // Mark the update of the position.
@@ -362,8 +358,7 @@ void Entity_PostProcess(Entity e, int ft) {
// //
// //
CollisionInfo _free_collInfo = NULL; CollisionInfo _free_collInfo = NULL;
CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction) {
float t, vec2 n, int applyFriction) {
CollisionInfo collInfo; CollisionInfo collInfo;
if (!_free_collInfo) { if (!_free_collInfo) {
@@ -408,16 +403,14 @@ void CollisionInfo_Destroy(CollisionInfo *collInfoRef) {
// CollisionInfo_Add // CollisionInfo_Add
// //
// //
void CollisionInfo_Add(CollisionInfo *collInfoRef, int responseType, void CollisionInfo_Add(
Entity ent1, Entity ent2, float t, vec2 n, CollisionInfo *collInfoRef, int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction) {
int applyFriction) {
if (collInfoRef == NULL) { if (collInfoRef == NULL) {
return; return;
} }
CollisionInfo prevCollInfo = NULL; CollisionInfo prevCollInfo = NULL;
CollisionInfo collInfo = collInfoRef[0]; CollisionInfo collInfo = collInfoRef[0];
CollisionInfo newCollInfo = CollisionInfo newCollInfo = CollisionInfo_New(responseType, ent1, ent2, t, n, applyFriction);
CollisionInfo_New(responseType, ent1, ent2, t, n, applyFriction);
while (collInfo != NULL && collInfo->t < t) { while (collInfo != NULL && collInfo->t < t) {
prevCollInfo = collInfo; prevCollInfo = collInfo;
@@ -435,11 +428,9 @@ void CollisionInfo_Add(CollisionInfo *collInfoRef, int responseType,
// CollisionInfo_CheckRepetition // CollisionInfo_CheckRepetition
// //
// //
int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, Entity ent2) {
Entity ent2) {
while (collInfo != NULL) { while (collInfo != NULL) {
if ((collInfo->ent1 == ent1 && collInfo->ent2 == ent2) || if ((collInfo->ent1 == ent1 && collInfo->ent2 == ent2) || (collInfo->ent1 == ent2 && collInfo->ent2 == ent1)) {
(collInfo->ent1 == ent2 && collInfo->ent2 == ent1)) {
return (1); return (1);
} }
collInfo = collInfo->next; collInfo = collInfo->next;
@@ -451,8 +442,7 @@ int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1,
// Entity_CheckCollisions // Entity_CheckCollisions
// //
// //
int Entity_CheckCollision(Entity ent1, Entity ent2, int Entity_CheckCollision(Entity ent1, Entity ent2, CollisionInfo *collInfoRef) {
CollisionInfo *collInfoRef) {
float t; float t;
vec2 n; vec2 n;
vec2 vel; vec2 vel;
@@ -483,11 +473,9 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockTop) { if (flags & EntityFlag_BlockTop) {
vec2_set(auxN, 0, -1); vec2_set(auxN, 0, -1);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->height + ent_block->height) / 2);
(ent->height + ent_block->height) / 2);
block_len = ent_block->width + ent->width; block_len = ent_block->width + ent->width;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
@@ -498,11 +486,9 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockBottom) { if (flags & EntityFlag_BlockBottom) {
vec2_set(auxN, 0, 1); vec2_set(auxN, 0, 1);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->height + ent_block->height) / 2);
(ent->height + ent_block->height) / 2);
block_len = ent_block->width + ent->width; block_len = ent_block->width + ent->width;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
@@ -513,11 +499,9 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockRight) { if (flags & EntityFlag_BlockRight) {
vec2_set(auxN, 1, 0); vec2_set(auxN, 1, 0);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->width + ent_block->width) / 2);
(ent->width + ent_block->width) / 2);
block_len = ent_block->height + ent->height; block_len = ent_block->height + ent->height;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
@@ -528,11 +512,9 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockLeft) { if (flags & EntityFlag_BlockLeft) {
vec2_set(auxN, -1, 0); vec2_set(auxN, -1, 0);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->width + ent_block->width) / 2);
(ent->width + ent_block->width) / 2);
block_len = ent_block->height + ent->height; block_len = ent_block->height + ent->height;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
@@ -542,8 +524,7 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
} }
if (t < 1.0f) { if (t < 1.0f) {
CollisionInfo_Add(collInfoRef, CollisionResponse_Line, ent, CollisionInfo_Add(collInfoRef, CollisionResponse_Line, ent, ent_block, t, n, applyFriction);
ent_block, t, n, applyFriction);
return (1); return (1);
} }
@@ -552,10 +533,8 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
// Circle-Circle test from ent1 // Circle-Circle test from ent1
vec2_minus(vel, ent1->vel, ent2->vel); vec2_minus(vel, ent1->vel, ent2->vel);
if (Colision_CircleCircle(ent1->pos, ent1->radius, vel, ent2->pos, if (Colision_CircleCircle(ent1->pos, ent1->radius, vel, ent2->pos, ent2->radius, &t, n)) {
ent2->radius, &t, n)) { CollisionInfo_Add(collInfoRef, CollisionResponse_Circle, ent1, ent2, t, n, 0);
CollisionInfo_Add(collInfoRef, CollisionResponse_Circle, ent1, ent2, t,
n, 0);
return (1); return (1);
} }
return (0); return (0);
@@ -572,12 +551,10 @@ void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n) {
if (b1->mass > 0.0f && b2->mass > 0.0f) { if (b1->mass > 0.0f && b2->mass > 0.0f) {
// Calculate elasticity // Calculate elasticity
elast = (b1->mass * b1->elast + b2->mass * b2->elast) / elast = (b1->mass * b1->elast + b2->mass * b2->elast) / (b1->mass + b2->mass);
(b1->mass + b2->mass);
// Collision between two massed balls // Collision between two massed balls
moment = ((1.0f + elast) * b1->mass * b2->mass * moment = ((1.0f + elast) * b1->mass * b2->mass * (fabs(vec2_dot(b1->vel, n)) + fabs(vec2_dot(b2->vel, n)))) /
(fabs(vec2_dot(b1->vel, n)) + fabs(vec2_dot(b2->vel, n)))) /
(b1->mass + b2->mass); (b1->mass + b2->mass);
vec2_scale(temp, n, moment / b1->mass); vec2_scale(temp, n, moment / b1->mass);
vec2_minus(b1->vel, b1->vel, temp); vec2_minus(b1->vel, b1->vel, temp);
@@ -612,8 +589,7 @@ void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n) {
// Entity_CollisionResponseLine // Entity_CollisionResponseLine
// //
// Normal response to a collision with a line. // Normal response to a collision with a line.
void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm, void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm, int applyFriction) {
int applyFriction) {
vec2 pos2, vel2, velFric, intersection; vec2 pos2, vel2, velFric, intersection;
float dist, fric_static, fric_dynamic, fricLen; float dist, fric_static, fric_dynamic, fricLen;
@@ -640,8 +616,7 @@ void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm,
} else { } else {
// Apply dynamic friction // Apply dynamic friction
if (fricLen > 0.0f) { if (fricLen > 0.0f) {
vec2_scaleadd(pos2, intersection, velFric, vec2_scaleadd(pos2, intersection, velFric, 1.0f - (fric_dynamic + (fric_static / fricLen)));
1.0f - (fric_dynamic + (fric_static / fricLen)));
} else { } else {
vec2_scaleadd(pos2, intersection, velFric, 1.0f - fric_dynamic); vec2_scaleadd(pos2, intersection, velFric, 1.0f - fric_dynamic);
} }
@@ -671,16 +646,14 @@ int Entity_CollisionInfoResponse(CollisionInfo collInfo) {
// Check the collision methods // Check the collision methods
if (collInfo->ent1->collision) { if (collInfo->ent1->collision) {
rc = collInfo->ent1->collision(collInfo->ent1, collInfo->ent2, rc = collInfo->ent1->collision(collInfo->ent1, collInfo->ent2, collInfo->t, n1);
collInfo->t, n1);
if (rc == 0) if (rc == 0)
response = 0; response = 0;
if (rc > 1) if (rc > 1)
response = 2; response = 2;
} }
if (collInfo->ent2->collision) { if (collInfo->ent2->collision) {
rc = collInfo->ent2->collision(collInfo->ent2, collInfo->ent1, rc = collInfo->ent2->collision(collInfo->ent2, collInfo->ent1, collInfo->t, n2);
collInfo->t, n2);
if (rc == 0) if (rc == 0)
response = 0; response = 0;
if (rc > 1) if (rc > 1)
@@ -690,17 +663,14 @@ int Entity_CollisionInfoResponse(CollisionInfo collInfo) {
// Collision response // Collision response
if (response == 1) { if (response == 1) {
if (collInfo->responseType == CollisionResponse_Line) { if (collInfo->responseType == CollisionResponse_Line) {
Entity_CollisionResponseLine(collInfo->ent1, collInfo->ent2, Entity_CollisionResponseLine(
collInfo->t, collInfo->n, collInfo->ent1, collInfo->ent2, collInfo->t, collInfo->n, collInfo->applyFriction);
collInfo->applyFriction);
} else if (collInfo->responseType == CollisionResponse_Circle) { } else if (collInfo->responseType == CollisionResponse_Circle) {
if (vec2_dot(collInfo->ent1->vel, collInfo->ent1->vel) > if (vec2_dot(collInfo->ent1->vel, collInfo->ent1->vel) >
vec2_dot(collInfo->ent2->vel, collInfo->ent2->vel)) { vec2_dot(collInfo->ent2->vel, collInfo->ent2->vel)) {
Entity_CollisionResponseCircle( Entity_CollisionResponseCircle(collInfo->ent1, collInfo->ent2, collInfo->t, n2);
collInfo->ent1, collInfo->ent2, collInfo->t, n2);
} else { } else {
Entity_CollisionResponseCircle( Entity_CollisionResponseCircle(collInfo->ent2, collInfo->ent1, collInfo->t, n1);
collInfo->ent2, collInfo->ent1, collInfo->t, n1);
} }
} }
return (1); return (1);
@@ -970,8 +940,7 @@ void Entity_Iluminate(Entity e, Entity *elist, int n) {
float qrad; float qrad;
if (e->flags & EntityFlag_Light) { if (e->flags & EntityFlag_Light) {
Entity_SetColor(e, e->defaultColor[0], e->defaultColor[1], Entity_SetColor(e, e->defaultColor[0], e->defaultColor[1], e->defaultColor[2], e->defaultColor[3]);
e->defaultColor[2], e->defaultColor[3]);
return; return;
} }
@@ -990,13 +959,11 @@ void Entity_Iluminate(Entity e, Entity *elist, int n) {
qrad = elist[i]->light[3] * elist[i]->light[3]; qrad = elist[i]->light[3] * elist[i]->light[3];
if (qdist < qrad) { if (qdist < qrad) {
f = 1.0f - qdist / qrad; f = 1.0f - qdist / qrad;
Entity_AddColor(e, f * elist[i]->light[0], f * elist[i]->light[1], Entity_AddColor(e, f * elist[i]->light[0], f * elist[i]->light[1], f * elist[i]->light[2], 0.0f);
f * elist[i]->light[2], 0.0f);
} }
} }
Entity_MultColor(e, e->defaultColor[0], e->defaultColor[1], Entity_MultColor(e, e->defaultColor[0], e->defaultColor[1], e->defaultColor[2], e->defaultColor[3]);
e->defaultColor[2], e->defaultColor[3]);
e->internalFlags &= ~EntityIntFlag_UpdateLight; e->internalFlags &= ~EntityIntFlag_UpdateLight;
if (e->internalFlags & EntityIntFlag_UpdateColor) { if (e->internalFlags & EntityIntFlag_UpdateColor) {
@@ -1032,9 +999,8 @@ void Entity_MarkUpdateLight(Entity e, Entity *elist, int n) {
max[1] = e->pos0[1] + e->light[3]; max[1] = e->pos0[1] + e->light[3];
} }
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
if (elist[i] != NULL && min[0] <= elist[i]->pos0[0] && if (elist[i] != NULL && min[0] <= elist[i]->pos0[0] && max[0] >= elist[i]->pos0[0] &&
max[0] >= elist[i]->pos0[0] && min[1] <= elist[i]->pos0[1] && min[1] <= elist[i]->pos0[1] && max[1] >= elist[i]->pos0[1]) {
max[1] >= elist[i]->pos0[1]) {
elist[i]->internalFlags |= EntityIntFlag_UpdateLight; elist[i]->internalFlags |= EntityIntFlag_UpdateLight;
} }
} }
@@ -1051,13 +1017,9 @@ int Entity_IsLight(Entity e) { return (e->flags & EntityFlag_Light); }
///////////////////////////// /////////////////////////////
// Entity_IsUpdateLight // Entity_IsUpdateLight
// //
int Entity_IsUpdateLight(Entity e) { int Entity_IsUpdateLight(Entity e) { return (e->internalFlags & EntityIntFlag_UpdateLight); }
return (e->internalFlags & EntityIntFlag_UpdateLight);
}
///////////////////////////// /////////////////////////////
// Entity_IsMoving // Entity_IsMoving
// //
int Entity_IsMoving(Entity e) { int Entity_IsMoving(Entity e) { return (e->internalFlags & EntityIntFlag_UpdatedPos); }
return (e->internalFlags & EntityIntFlag_UpdatedPos);
}

View File

@@ -153,8 +153,7 @@ struct TCollisionInfo {
// CollisionInfo_New // CollisionInfo_New
// //
// //
CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction);
float t, vec2 n, int applyFriction);
///////////////////////////// /////////////////////////////
// CollisionInfo_Destroy // CollisionInfo_Destroy
@@ -166,15 +165,14 @@ void CollisionInfo_Destroy(CollisionInfo *collInfoRef);
// CollisionInfo_Add // CollisionInfo_Add
// //
// //
void CollisionInfo_Add(CollisionInfo *collInfo, int responseType, Entity ent1, void CollisionInfo_Add(
Entity ent2, float t, vec2 n, int applyFriction); CollisionInfo *collInfo, int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction);
///////////////////////////// /////////////////////////////
// CollisionInfo_CheckRepetition // CollisionInfo_CheckRepetition
// //
// //
int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, Entity ent2);
Entity ent2);
///////////////////////////// /////////////////////////////
// Entity_CheckCollision // Entity_CheckCollision
@@ -192,8 +190,7 @@ void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n);
// Entity_CollisionResponseLine // Entity_CollisionResponseLine
// //
// Normal response to a collision with a line. // Normal response to a collision with a line.
void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 n, void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 n, int applyFriction);
int applyFriction);
///////////////////////////// /////////////////////////////
// Entity_CollisionInfoResponse // Entity_CollisionInfoResponse

View File

@@ -229,17 +229,15 @@ void GameLib_ProcLoop(void *data) {
repeat = 0; repeat = 0;
CollisionInfo collInfo = NULL; CollisionInfo collInfo = NULL;
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
if (!(_entity[i]->flags & EntityFlag_Collision) || if (!(_entity[i]->flags & EntityFlag_Collision) || _entity[i]->mass < 0.0f)
_entity[i]->mass < 0.0f)
continue; continue;
if (_entity[i]->vel[0] <= 0.0f && _entity[i]->vel[0] >= -0.0f && if (_entity[i]->vel[0] <= 0.0f && _entity[i]->vel[0] >= -0.0f && _entity[i]->vel[1] <= 0.0f &&
_entity[i]->vel[1] <= 0.0f && _entity[i]->vel[1] >= -0.0f) { _entity[i]->vel[1] >= -0.0f) {
continue; continue;
} }
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (i == j || !(_entity[j]->flags & EntityFlag_Collision) || if (i == j || !(_entity[j]->flags & EntityFlag_Collision) ||
CollisionInfo_CheckRepetition(collInfo, _entity[i], CollisionInfo_CheckRepetition(collInfo, _entity[i], _entity[j]) ||
_entity[j]) ||
!Entity_BBoxIntersect(_entity[i], _entity[j])) { !Entity_BBoxIntersect(_entity[i], _entity[j])) {
continue; continue;
} }
@@ -256,8 +254,7 @@ void GameLib_ProcLoop(void *data) {
// Stop remaining collisions // Stop remaining collisions
if (count == 10) { if (count == 10) {
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
if (!(_entity[i]->flags & EntityFlag_Collision) || if (!(_entity[i]->flags & EntityFlag_Collision) || _entity[i]->mass < 0.0f)
_entity[i]->mass < 0.0f)
continue; continue;
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (i == j || !(_entity[j]->flags & EntityFlag_Collision) || if (i == j || !(_entity[j]->flags & EntityFlag_Collision) ||
@@ -281,8 +278,7 @@ void GameLib_ProcLoop(void *data) {
time = Time_GetTime(); time = Time_GetTime();
_entities_lock = 1; _entities_lock = 1;
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
if (!(_entity[i]->flags & EntityFlag_Overlap) || if (!(_entity[i]->flags & EntityFlag_Overlap) || _entity[i]->mass < 0.0f)
_entity[i]->mass < 0.0f)
continue; continue;
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (!(_entity[j]->flags & EntityFlag_Overlap) || i == j) if (!(_entity[j]->flags & EntityFlag_Overlap) || i == j)
@@ -376,9 +372,12 @@ void GameLib_DrawLoop(void *data, float f) {
// Draw parallax backgrounds // Draw parallax backgrounds
for (i = 0; i < _nParallaxBackgrounds; i++) { for (i = 0; i < _nParallaxBackgrounds; i++) {
Draw_ImgParallax( Draw_ImgParallax(
_parallaxBackground[i].img, _parallaxBackground[i].imgSize, _parallaxBackground[i].img,
_parallaxBackground[i].imgSize,
_parallaxBackground[i].imgOffset, _parallaxBackground[i].imgOffset,
_parallaxBackground[i].parallaxFactor, game_pos, _game_size); _parallaxBackground[i].parallaxFactor,
game_pos,
_game_size);
} }
// Draw entities // Draw entities
@@ -387,8 +386,7 @@ void GameLib_DrawLoop(void *data, float f) {
Entity e = _entity[i]; Entity e = _entity[i];
// Check visivility // Check visivility
if (!Entity_IsVisible(e, game_pos[0], game_pos[1], _game_size[0], if (!Entity_IsVisible(e, game_pos[0], game_pos[1], _game_size[0], _game_size[1])) {
_game_size[1])) {
continue; continue;
} }
@@ -425,8 +423,7 @@ void GameLib_DrawLoop(void *data, float f) {
} }
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
if (Input_GetKey(InputKey_DumpProfiling) == InputKey_Pressed && if (Input_GetKey(InputKey_DumpProfiling) == InputKey_Pressed && fproc_count > 0 && fdraw_count > 0) {
fproc_count > 0 && fdraw_count > 0) {
Print("Profiling:::::::::\n"); Print("Profiling:::::::::\n");
Print("t_proc.....:%6lldus\n", t_proc / fproc_count); Print("t_proc.....:%6lldus\n", t_proc / fproc_count);
Print("t_col......:%6lldus\n", t_col / fproc_count); Print("t_col......:%6lldus\n", t_col / fproc_count);
@@ -448,8 +445,7 @@ void GameLib_DrawLoop(void *data, float f) {
// GameLib_Loop // GameLib_Loop
// //
// Loops the game. // Loops the game.
void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void (*gamepredraw)(float f), void (*gamedraw)(float f)) {
void (*gamepredraw)(float f), void (*gamedraw)(float f)) {
_gameproc = gameproc; _gameproc = gameproc;
_gamepostproc = gamepostproc; _gamepostproc = gamepostproc;
_gamepredraw = gamepredraw; _gamepredraw = gamepredraw;
@@ -492,10 +488,8 @@ void GameLib_GetSize(int size[2]) {
size[1] = _game_size[1]; size[1] = _game_size[1];
} }
void GameLib_GetPosInstant(int pos[2], float f) { void GameLib_GetPosInstant(int pos[2], float f) {
pos[0] = _game_pos0[0] + pos[0] = _game_pos0[0] + f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]);
f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]); pos[1] = _game_pos0[1] + f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
pos[1] = _game_pos0[1] +
f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
} }
void GameLib_SetPosOffset(int posOffset[2]) { void GameLib_SetPosOffset(int posOffset[2]) {
_game_posOffset[0] = posOffset[0]; _game_posOffset[0] = posOffset[0];
@@ -513,12 +507,10 @@ void GameLib_MoveToPos(vec2 pos, float f) {
GameLib_MoveToPosV(pos, f); GameLib_MoveToPosV(pos, f);
} }
void GameLib_MoveToPosH(vec2 pos, float f) { void GameLib_MoveToPosH(vec2 pos, float f) {
_game_pos1[0] = _game_pos1[0] = _game_pos1[0] + (pos[0] - (_game_pos1[0] + (_game_size[0] / 2.0f))) * f;
_game_pos1[0] + (pos[0] - (_game_pos1[0] + (_game_size[0] / 2.0f))) * f;
} }
void GameLib_MoveToPosV(vec2 pos, float f) { void GameLib_MoveToPosV(vec2 pos, float f) {
_game_pos1[1] = _game_pos1[1] = _game_pos1[1] + (pos[1] - (_game_pos1[1] + (_game_size[1] / 2.0f))) * f;
_game_pos1[1] + (pos[1] - (_game_pos1[1] + (_game_size[1] / 2.0f))) * f;
} }
///////////////////////////// /////////////////////////////
@@ -584,8 +576,7 @@ int GameLib_EntityCustomCheckCollision(Entity ent, vec2 vel) {
Entity_CalcBBox(ent); Entity_CalcBBox(ent);
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (!(_entity[j]->flags & EntityFlag_Collision) || if (!(_entity[j]->flags & EntityFlag_Collision) || !Entity_BBoxIntersect(ent, _entity[j])) {
!Entity_BBoxIntersect(ent, _entity[j])) {
continue; continue;
} }
Entity_CheckCollision(ent, _entity[j], &collInfo); Entity_CheckCollision(ent, _entity[j], &collInfo);
@@ -669,14 +660,11 @@ void GameLib_EntitySetLight(Entity e, float r, float g, float b, float rad) {
// GameLib_ConvertScreenPositionToGamePosition // GameLib_ConvertScreenPositionToGamePosition
// //
// //
void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, float f) {
float f) {
int game_pos[2]; int game_pos[2];
game_pos[0] = _game_pos0[0] + game_pos[0] = _game_pos0[0] + f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]);
f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]); game_pos[1] = _game_pos0[1] + f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
game_pos[1] = _game_pos0[1] +
f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
gamePos[0] = (screenPos[0] * _game_size[0]) + game_pos[0]; gamePos[0] = (screenPos[0] * _game_size[0]) + game_pos[0];
gamePos[1] = (screenPos[1] * _game_size[1]) + game_pos[1]; gamePos[1] = (screenPos[1] * _game_size[1]) + game_pos[1];
@@ -686,8 +674,7 @@ void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos,
// GameLib_AddParallaxBackground // GameLib_AddParallaxBackground
// //
// //
void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2]) {
int imgOffset[2], float parallaxFactor[2]) {
int idx = _nParallaxBackgrounds; int idx = _nParallaxBackgrounds;
if ((idx + 1) >= MaxParallaxBackgrounds) { if ((idx + 1) >= MaxParallaxBackgrounds) {
Print("GameLib: Can't add parallaxBackground, limit reached."); Print("GameLib: Can't add parallaxBackground, limit reached.");

View File

@@ -39,8 +39,7 @@ int GameLib_DelEntity(Entity e);
// GameLib_Loop // GameLib_Loop
// //
// Loops the game. // Loops the game.
void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void (*gamepredraw)(float f), void (*gamedraw)(float f));
void (*gamepredraw)(float f), void (*gamedraw)(float f));
///////////////////////////// /////////////////////////////
// GameLib_GetPos // GameLib_GetPos
@@ -114,15 +113,13 @@ void GameLib_EntitySetLight(Entity e, float r, float g, float b, float rad);
// GameLib_ConvertScreenPositionToGamePosition // GameLib_ConvertScreenPositionToGamePosition
// //
// //
void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, float f);
float f);
///////////////////////////// /////////////////////////////
// GameLib_AddParallaxBackground // GameLib_AddParallaxBackground
// //
// //
void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2]);
int imgOffset[2], float parallaxFactor[2]);
///////////////////////////// /////////////////////////////
// GameLib_CleanParallaxBackgrounds // GameLib_CleanParallaxBackgrounds

View File

@@ -53,7 +53,8 @@ void Input_Frame() {
Input_SetKey(InputKey_Left, keys[SDL_SCANCODE_LEFT] | keys[SDL_SCANCODE_A]); Input_SetKey(InputKey_Left, keys[SDL_SCANCODE_LEFT] | keys[SDL_SCANCODE_A]);
Input_SetKey(InputKey_Right, keys[SDL_SCANCODE_RIGHT] | keys[SDL_SCANCODE_D]); Input_SetKey(InputKey_Right, keys[SDL_SCANCODE_RIGHT] | keys[SDL_SCANCODE_D]);
Input_SetKey(InputKey_Jump, keys[SDL_SCANCODE_SPACE]); Input_SetKey(InputKey_Jump, keys[SDL_SCANCODE_SPACE]);
Input_SetKey(InputKey_Continue, Input_SetKey(
InputKey_Continue,
keys[SDL_SCANCODE_RETURN] | keys[SDL_SCANCODE_RETURN2] | keys[SDL_SCANCODE_KP_ENTER] | _pointerDown); keys[SDL_SCANCODE_RETURN] | keys[SDL_SCANCODE_RETURN2] | keys[SDL_SCANCODE_KP_ENTER] | _pointerDown);
Input_SetKey(InputKey_DumpProfiling, keys[SDL_SCANCODE_M]); Input_SetKey(InputKey_DumpProfiling, keys[SDL_SCANCODE_M]);

View File

@@ -54,11 +54,7 @@ void Input_SetKey(InputKey key, int status);
// InputKeyStatus // // InputKeyStatus //
/////////////////// ///////////////////
// Key status enumeration. // Key status enumeration.
typedef enum { typedef enum { InputKey_Released, InputKey_Pressed, InputKey_Holded } InputKeyStatus;
InputKey_Released,
InputKey_Pressed,
InputKey_Holded
} InputKeyStatus;
///////////////////////////// /////////////////////////////
// Input_GetKey // Input_GetKey

View File

@@ -35,22 +35,19 @@ void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]) {
if (quadArray->resVertex <= quadArray->nVertex) { if (quadArray->resVertex <= quadArray->nVertex) {
// Grow vertexData // Grow vertexData
quadArray->resVertex *= 2; quadArray->resVertex *= 2;
float *newVertexData = float *newVertexData = malloc(sizeof(float) * Vertex2D_Length * quadArray->resVertex);
malloc(sizeof(float) * Vertex2D_Length * quadArray->resVertex); memcpy(newVertexData, quadArray->vertexData, sizeof(float) * Vertex2D_Length * quadArray->nVertex);
memcpy(newVertexData, quadArray->vertexData,
sizeof(float) * Vertex2D_Length * quadArray->nVertex);
free(quadArray->vertexData); free(quadArray->vertexData);
quadArray->vertexData = newVertexData; quadArray->vertexData = newVertexData;
} }
// Add the vertex // Add the vertex
memcpy(quadArray->vertexData + (Vertex2D_Length * quadArray->nVertex), v, memcpy(quadArray->vertexData + (Vertex2D_Length * quadArray->nVertex), v, sizeof(float) * Vertex2D_Length);
sizeof(float) * Vertex2D_Length);
quadArray->nVertex++; quadArray->nVertex++;
} }
void QuadArray2D_AddQuad(QuadArray2D quadArray, float x0, float y0, float u0, void QuadArray2D_AddQuad(
float v0, float x1, float y1, float u1, float v1, QuadArray2D quadArray, float x0, float y0, float u0, float v0, float x1, float y1, float u1, float v1,
float color[]) { float color[]) {
float v[Vertex2D_Length]; float v[Vertex2D_Length];

View File

@@ -24,8 +24,8 @@ void QuadArray2D_Clean(QuadArray2D quadArray);
void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]); void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]);
void QuadArray2D_AddQuad(QuadArray2D quadArray, float x0, float y0, float u0, void QuadArray2D_AddQuad(
float v0, float x1, float y1, float u1, float v1, QuadArray2D quadArray, float x0, float y0, float u0, float v0, float x1, float y1, float u1, float v1,
float color[]); float color[]);
#endif #endif

View File

@@ -38,9 +38,7 @@ void Rect_UnionRect(Rect r0, Rect r1, Rect rd) {
rd->y1 = MaximumInt(r0->y1, r1->y1); rd->y1 = MaximumInt(r0->y1, r1->y1);
} }
int Rect_PointInside(Rect r, int x, int y) { int Rect_PointInside(Rect r, int x, int y) { return (x >= r->x0 && x < r->x1 && y >= r->y0 && y < r->y1); }
return (x >= r->x0 && x < r->x1 && y >= r->y0 && y < r->y1);
}
int Rect_PointInsideAny(TRect r[], int rCount, int x, int y) { int Rect_PointInsideAny(TRect r[], int rCount, int x, int y) {
int insideAny = 0; int insideAny = 0;
@@ -183,8 +181,7 @@ int Intersec_RayUnitCircle(vec2 orig, vec2 vel, vec2 center, float *t) {
// Colision_CircleCircle // Colision_CircleCircle
// //
// Colision point of a circle against another circle. // Colision point of a circle against another circle.
int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2, int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2, float rad2, float *t, vec2 n) {
float rad2, float *t, vec2 n) {
vec2 vel_a, orig_a, cen_a, temp; vec2 vel_a, orig_a, cen_a, temp;
float rads, invrads; float rads, invrads;
float maxx, minx; float maxx, minx;
@@ -230,8 +227,7 @@ int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2,
// Intersect_RayEdge // Intersect_RayEdge
// //
// Intersection between a ray and a edge. // Intersection between a ray and a edge.
int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, float *t) {
float *t) {
vec2 pos2, intersection, perp, edgePos2; vec2 pos2, intersection, perp, edgePos2;
float delta, d1, d2, hLen; float delta, d1, d2, hLen;
@@ -322,9 +318,9 @@ int EndsWith(char *str, char *suffix) {
#define __seed_b 5 #define __seed_b 5
#define __seed_c 10 #define __seed_c 10
#define __seed_d 15 #define __seed_d 15
//#define __LGC_a 1664525ul // #define __LGC_a 1664525ul
//#define __LGC_c 1013904223ul // #define __LGC_c 1013904223ul
//#define __LGC_m 4294967296ul // #define __LGC_m 4294967296ul
#define __LGC_a 16807ul #define __LGC_a 16807ul
#define __LGC_c 2 #define __LGC_c 2
#define __LGC_m 2147483647ul #define __LGC_m 2147483647ul

View File

@@ -85,15 +85,13 @@ int Intersec_RayUnitCircle(vec2 orig, vec2 vel, vec2 center, float *t);
// Intersect_CircleCircle // Intersect_CircleCircle
// //
// Colision point of a circle against another circle. // Colision point of a circle against another circle.
int Colision_CircleCircle(vec2 cir1, float ra, vec2 vel, vec2 cb, float rb, int Colision_CircleCircle(vec2 cir1, float ra, vec2 vel, vec2 cb, float rb, float *t, vec2 n);
float *t, vec2 n);
///////////////////////////// /////////////////////////////
// Intersect_RayEdge // Intersect_RayEdge
// //
// Intersection between a ray and a edge. // Intersection between a ray and a edge.
int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, float *t);
float *t);
///////////////////////////// /////////////////////////////
// absmod // absmod

File diff suppressed because it is too large Load Diff

View File

@@ -28,7 +28,7 @@ freely, subject to the following restrictions:
#include <string.h> /*for size_t*/ #include <string.h> /*for size_t*/
extern const char* LODEPNG_VERSION_STRING; extern const char *LODEPNG_VERSION_STRING;
/* /*
The following #defines are used to create code sections. They can be disabled The following #defines are used to create code sections. They can be disabled
@@ -82,14 +82,13 @@ source files with custom allocators.*/
#endif #endif
#ifdef LODEPNG_COMPILE_CPP #ifdef LODEPNG_COMPILE_CPP
#include <vector>
#include <string> #include <string>
#include <vector>
#endif /*LODEPNG_COMPILE_CPP*/ #endif /*LODEPNG_COMPILE_CPP*/
#ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_PNG
/*The PNG color types (also used for raw).*/ /*The PNG color types (also used for raw).*/
typedef enum LodePNGColorType typedef enum LodePNGColorType {
{
LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/
LCT_RGB = 2, /*RGB: 8,16 bit*/ LCT_RGB = 2, /*RGB: 8,16 bit*/
LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/
@@ -113,38 +112,32 @@ colortype: the desired color type for the raw output image. See explanation on P
bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error). Return value: LodePNG error code (0 means no error).
*/ */
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode_memory(
const unsigned char* in, size_t insize, unsigned char **out, unsigned *w, unsigned *h, const unsigned char *in, size_t insize, LodePNGColorType colortype,
LodePNGColorType colortype, unsigned bitdepth); unsigned bitdepth);
/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ /*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/
unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode32(unsigned char **out, unsigned *w, unsigned *h, const unsigned char *in, size_t insize);
const unsigned char* in, size_t insize);
/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ /*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/
unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode24(unsigned char **out, unsigned *w, unsigned *h, const unsigned char *in, size_t insize);
const unsigned char* in, size_t insize);
#ifdef LODEPNG_COMPILE_DISK #ifdef LODEPNG_COMPILE_DISK
/* /*
Load PNG from disk, from file with given name. Load PNG from disk, from file with given name.
Same as the other decode functions, but instead takes a filename as input. Same as the other decode functions, but instead takes a filename as input.
*/ */
unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode_file(
const char* filename, unsigned char **out, unsigned *w, unsigned *h, const char *filename, LodePNGColorType colortype, unsigned bitdepth);
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ /*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/
unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode32_file(unsigned char **out, unsigned *w, unsigned *h, const char *filename);
const char* filename);
/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ /*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/
unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode24_file(unsigned char **out, unsigned *w, unsigned *h, const char *filename);
const char* filename);
#endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
/* /*
Converts raw pixel data into a PNG image in memory. The colortype and bitdepth Converts raw pixel data into a PNG image in memory. The colortype and bitdepth
@@ -162,17 +155,15 @@ colortype: the color type of the raw input image. See explanation on PNG color t
bitdepth: the bit depth of the raw input image. See explanation on PNG color types. bitdepth: the bit depth of the raw input image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error). Return value: LodePNG error code (0 means no error).
*/ */
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, unsigned lodepng_encode_memory(
const unsigned char* image, unsigned w, unsigned h, unsigned char **out, size_t *outsize, const unsigned char *image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth); LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ /*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32(unsigned char** out, size_t* outsize, unsigned lodepng_encode32(unsigned char **out, size_t *outsize, const unsigned char *image, unsigned w, unsigned h);
const unsigned char* image, unsigned w, unsigned h);
/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ /*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24(unsigned char** out, size_t* outsize, unsigned lodepng_encode24(unsigned char **out, size_t *outsize, const unsigned char *image, unsigned w, unsigned h);
const unsigned char* image, unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DISK #ifdef LODEPNG_COMPILE_DISK
/* /*
@@ -180,40 +171,36 @@ Converts raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output. Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning! NOTE: This overwrites existing files without warning!
*/ */
unsigned lodepng_encode_file(const char* filename, unsigned lodepng_encode_file(
const unsigned char* image, unsigned w, unsigned h, const char *filename, const unsigned char *image, unsigned w, unsigned h, LodePNGColorType colortype,
LodePNGColorType colortype, unsigned bitdepth); unsigned bitdepth);
/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ /*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32_file(const char* filename, unsigned lodepng_encode32_file(const char *filename, const unsigned char *image, unsigned w, unsigned h);
const unsigned char* image, unsigned w, unsigned h);
/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ /*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24_file(const char* filename, unsigned lodepng_encode24_file(const char *filename, const unsigned char *image, unsigned w, unsigned h);
const unsigned char* image, unsigned w, unsigned h);
#endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_CPP #ifdef LODEPNG_COMPILE_CPP
namespace lodepng namespace lodepng {
{
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype /*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype
is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ is the format to output the pixels to. Default is RGBA 8-bit per channel.*/
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, unsigned decode(
const unsigned char* in, size_t insize, std::vector<unsigned char> &out, unsigned &w, unsigned &h, const unsigned char *in, size_t insize,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, unsigned decode(
const std::vector<unsigned char>& in, std::vector<unsigned char> &out, unsigned &w, unsigned &h, const std::vector<unsigned char> &in,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK #ifdef LODEPNG_COMPILE_DISK
/* /*
Converts PNG file from disk to raw pixel data in memory. Converts PNG file from disk to raw pixel data in memory.
Same as the other decode functions, but instead takes a filename as input. Same as the other decode functions, but instead takes a filename as input.
*/ */
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, unsigned decode(
const std::string& filename, std::vector<unsigned char> &out, unsigned &w, unsigned &h, const std::string &filename,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_DECODER */ #endif /* LODEPNG_COMPILE_DECODER */
@@ -221,11 +208,11 @@ unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype /*Same as lodepng_encode_memory, but encodes to an std::vector. colortype
is that of the raw input data. The output PNG color type will be auto chosen.*/ is that of the raw input data. The output PNG color type will be auto chosen.*/
unsigned encode(std::vector<unsigned char>& out, unsigned encode(
const unsigned char* in, unsigned w, unsigned h, std::vector<unsigned char> &out, const unsigned char *in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned encode(std::vector<unsigned char>& out, unsigned encode(
const std::vector<unsigned char>& in, unsigned w, unsigned h, std::vector<unsigned char> &out, const std::vector<unsigned char> &in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK #ifdef LODEPNG_COMPILE_DISK
/* /*
@@ -233,11 +220,11 @@ Converts 32-bit RGBA raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output. Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning! NOTE: This overwrites existing files without warning!
*/ */
unsigned encode(const std::string& filename, unsigned encode(
const unsigned char* in, unsigned w, unsigned h, const std::string &filename, const unsigned char *in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned bitdepth = 8);
unsigned encode(const std::string& filename, unsigned encode(
const std::vector<unsigned char>& in, unsigned w, unsigned h, const std::string &filename, const std::vector<unsigned char> &in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ENCODER */
@@ -247,32 +234,29 @@ unsigned encode(const std::string& filename,
#ifdef LODEPNG_COMPILE_ERROR_TEXT #ifdef LODEPNG_COMPILE_ERROR_TEXT
/*Returns an English description of the numerical error code.*/ /*Returns an English description of the numerical error code.*/
const char* lodepng_error_text(unsigned code); const char *lodepng_error_text(unsigned code);
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
/*Settings for zlib decompression*/ /*Settings for zlib decompression*/
typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; typedef struct LodePNGDecompressSettings LodePNGDecompressSettings;
struct LodePNGDecompressSettings struct LodePNGDecompressSettings {
{
unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
/*use custom zlib decoder instead of built in one (default: null)*/ /*use custom zlib decoder instead of built in one (default: null)*/
unsigned (*custom_zlib)(unsigned char**, size_t*, unsigned (*custom_zlib)(
const unsigned char*, size_t, unsigned char **, size_t *, const unsigned char *, size_t, const LodePNGDecompressSettings *);
const LodePNGDecompressSettings*);
/*use custom deflate decoder instead of built in one (default: null) /*use custom deflate decoder instead of built in one (default: null)
if custom_zlib is used, custom_deflate is ignored since only the built in if custom_zlib is used, custom_deflate is ignored since only the built in
zlib function will call custom_deflate*/ zlib function will call custom_deflate*/
unsigned (*custom_inflate)(unsigned char**, size_t*, unsigned (*custom_inflate)(
const unsigned char*, size_t, unsigned char **, size_t *, const unsigned char *, size_t, const LodePNGDecompressSettings *);
const LodePNGDecompressSettings*);
const void* custom_context; /*optional custom settings for custom functions*/ const void *custom_context; /*optional custom settings for custom functions*/
}; };
extern const LodePNGDecompressSettings lodepng_default_decompress_settings; extern const LodePNGDecompressSettings lodepng_default_decompress_settings;
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); void lodepng_decompress_settings_init(LodePNGDecompressSettings *settings);
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
@@ -292,21 +276,18 @@ struct LodePNGCompressSettings /*deflate = compress*/
unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/
/*use custom zlib encoder instead of built in one (default: null)*/ /*use custom zlib encoder instead of built in one (default: null)*/
unsigned (*custom_zlib)(unsigned char**, size_t*, unsigned (*custom_zlib)(unsigned char **, size_t *, const unsigned char *, size_t, const LodePNGCompressSettings *);
const unsigned char*, size_t,
const LodePNGCompressSettings*);
/*use custom deflate encoder instead of built in one (default: null) /*use custom deflate encoder instead of built in one (default: null)
if custom_zlib is used, custom_deflate is ignored since only the built in if custom_zlib is used, custom_deflate is ignored since only the built in
zlib function will call custom_deflate*/ zlib function will call custom_deflate*/
unsigned (*custom_deflate)(unsigned char**, size_t*, unsigned (*custom_deflate)(
const unsigned char*, size_t, unsigned char **, size_t *, const unsigned char *, size_t, const LodePNGCompressSettings *);
const LodePNGCompressSettings*);
const void* custom_context; /*optional custom settings for custom functions*/ const void *custom_context; /*optional custom settings for custom functions*/
}; };
extern const LodePNGCompressSettings lodepng_default_compress_settings; extern const LodePNGCompressSettings lodepng_default_compress_settings;
void lodepng_compress_settings_init(LodePNGCompressSettings* settings); void lodepng_compress_settings_init(LodePNGCompressSettings *settings);
#endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_PNG
@@ -315,8 +296,7 @@ Color mode of an image. Contains all information required to decode the pixel
bits to RGBA colors. This information is the same as used in the PNG file bits to RGBA colors. This information is the same as used in the PNG file
format, and is used both for PNG and raw image data in LodePNG. format, and is used both for PNG and raw image data in LodePNG.
*/ */
typedef struct LodePNGColorMode typedef struct LodePNGColorMode {
{
/*header (IHDR)*/ /*header (IHDR)*/
LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/
unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/
@@ -334,7 +314,7 @@ typedef struct LodePNGColorMode
The palette is only supported for color type 3. The palette is only supported for color type 3.
*/ */
unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ unsigned char *palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/
size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/
/* /*
@@ -355,30 +335,30 @@ typedef struct LodePNGColorMode
} LodePNGColorMode; } LodePNGColorMode;
/*init, cleanup and copy functions to use with this struct*/ /*init, cleanup and copy functions to use with this struct*/
void lodepng_color_mode_init(LodePNGColorMode* info); void lodepng_color_mode_init(LodePNGColorMode *info);
void lodepng_color_mode_cleanup(LodePNGColorMode* info); void lodepng_color_mode_cleanup(LodePNGColorMode *info);
/*return value is error code (0 means no error)*/ /*return value is error code (0 means no error)*/
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); unsigned lodepng_color_mode_copy(LodePNGColorMode *dest, const LodePNGColorMode *source);
void lodepng_palette_clear(LodePNGColorMode* info); void lodepng_palette_clear(LodePNGColorMode *info);
/*add 1 color to the palette*/ /*add 1 color to the palette*/
unsigned lodepng_palette_add(LodePNGColorMode* info, unsigned
unsigned char r, unsigned char g, unsigned char b, unsigned char a); lodepng_palette_add(LodePNGColorMode *info, unsigned char r, unsigned char g, unsigned char b, unsigned char a);
/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ /*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/
unsigned lodepng_get_bpp(const LodePNGColorMode* info); unsigned lodepng_get_bpp(const LodePNGColorMode *info);
/*get the amount of color channels used, based on colortype in the struct. /*get the amount of color channels used, based on colortype in the struct.
If a palette is used, it counts as 1 channel.*/ If a palette is used, it counts as 1 channel.*/
unsigned lodepng_get_channels(const LodePNGColorMode* info); unsigned lodepng_get_channels(const LodePNGColorMode *info);
/*is it a greyscale type? (only colortype 0 or 4)*/ /*is it a greyscale type? (only colortype 0 or 4)*/
unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); unsigned lodepng_is_greyscale_type(const LodePNGColorMode *info);
/*has it got an alpha channel? (only colortype 2 or 6)*/ /*has it got an alpha channel? (only colortype 2 or 6)*/
unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); unsigned lodepng_is_alpha_type(const LodePNGColorMode *info);
/*has it got a palette? (only colortype 3)*/ /*has it got a palette? (only colortype 3)*/
unsigned lodepng_is_palette_type(const LodePNGColorMode* info); unsigned lodepng_is_palette_type(const LodePNGColorMode *info);
/*only returns true if there is a palette and there is a value in the palette with alpha < 255. /*only returns true if there is a palette and there is a value in the palette with alpha < 255.
Loops through the palette to check this.*/ Loops through the palette to check this.*/
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); unsigned lodepng_has_palette_alpha(const LodePNGColorMode *info);
/* /*
Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
@@ -386,14 +366,13 @@ Returns false if the image can only have opaque pixels.
In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
or if "key_defined" is true. or if "key_defined" is true.
*/ */
unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); unsigned lodepng_can_have_alpha(const LodePNGColorMode *info);
/*Returns the byte size of a raw image buffer with given width, height and color mode*/ /*Returns the byte size of a raw image buffer with given width, height and color mode*/
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode *color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*The information of a Time chunk in PNG.*/ /*The information of a Time chunk in PNG.*/
typedef struct LodePNGTime typedef struct LodePNGTime {
{
unsigned year; /*2 bytes used (0-65535)*/ unsigned year; /*2 bytes used (0-65535)*/
unsigned month; /*1-12*/ unsigned month; /*1-12*/
unsigned day; /*1-31*/ unsigned day; /*1-31*/
@@ -404,10 +383,9 @@ typedef struct LodePNGTime
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*Information about the PNG image, except pixels, width and height.*/ /*Information about the PNG image, except pixels, width and height.*/
typedef struct LodePNGInfo typedef struct LodePNGInfo {
{
/*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/
unsigned compression_method;/*compression method of the original file. Always 0.*/ unsigned compression_method; /*compression method of the original file. Always 0.*/
unsigned filter_method; /*filter method of the original file*/ unsigned filter_method; /*filter method of the original file*/
unsigned interlace_method; /*interlace method of the original file*/ unsigned interlace_method; /*interlace method of the original file*/
LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/
@@ -443,8 +421,8 @@ typedef struct LodePNGInfo
correctly and use lodepng_add_text and lodepng_clear_text. correctly and use lodepng_add_text and lodepng_clear_text.
*/ */
size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/
char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ char **text_keys; /*the keyword of a text chunk (e.g. "Comment")*/
char** text_strings; /*the actual text*/ char **text_strings; /*the actual text*/
/* /*
international text chunks (iTXt) international text chunks (iTXt)
@@ -452,10 +430,10 @@ typedef struct LodePNGInfo
"langtags" and "transkeys". "langtags" and "transkeys".
*/ */
size_t itext_num; /*the amount of international texts in this PNG*/ size_t itext_num; /*the amount of international texts in this PNG*/
char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ char **itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/
char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ char **itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ char **itext_transkeys; /*keyword translated to the international language - UTF-8 string*/
char** itext_strings; /*the actual international text - UTF-8 string*/ char **itext_strings; /*the actual international text - UTF-8 string*/
/*time chunk (tIME)*/ /*time chunk (tIME)*/
unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/
@@ -476,24 +454,25 @@ typedef struct LodePNGInfo
Do not allocate or traverse this data yourself. Use the chunk traversing functions declared Do not allocate or traverse this data yourself. Use the chunk traversing functions declared
later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.
*/ */
unsigned char* unknown_chunks_data[3]; unsigned char *unknown_chunks_data[3];
size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGInfo; } LodePNGInfo;
/*init, cleanup and copy functions to use with this struct*/ /*init, cleanup and copy functions to use with this struct*/
void lodepng_info_init(LodePNGInfo* info); void lodepng_info_init(LodePNGInfo *info);
void lodepng_info_cleanup(LodePNGInfo* info); void lodepng_info_cleanup(LodePNGInfo *info);
/*return value is error code (0 means no error)*/ /*return value is error code (0 means no error)*/
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); unsigned lodepng_info_copy(LodePNGInfo *dest, const LodePNGInfo *source);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ void lodepng_clear_text(LodePNGInfo *info); /*use this to clear the texts again after you filled them in*/
unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ unsigned lodepng_add_text(LodePNGInfo *info, const char *key, const char *str); /*push back both texts at once*/
void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ void lodepng_clear_itext(LodePNGInfo *info); /*use this to clear the itexts again after you filled them in*/
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, unsigned lodepng_add_itext(
const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ LodePNGInfo *info, const char *key, const char *langtag, const char *transkey,
const char *str); /*push back the 4 texts of 1 chunk at once*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/* /*
@@ -507,8 +486,8 @@ For < 8 bpp images, there should not be padding bits at the end of scanlines.
For 16-bit per channel colors, uses big endian format like PNG does. For 16-bit per channel colors, uses big endian format like PNG does.
Return value is LodePNG error code Return value is LodePNG error code
*/ */
unsigned lodepng_convert(unsigned char* out, const unsigned char* in, unsigned lodepng_convert(
const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned char *out, const unsigned char *in, const LodePNGColorMode *mode_out, const LodePNGColorMode *mode_in,
unsigned w, unsigned h); unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
@@ -516,8 +495,7 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
Settings for the decoder. This contains settings for the PNG and the Zlib Settings for the decoder. This contains settings for the PNG and the Zlib
decoder, but not the Info settings from the Info structs. decoder, but not the Info settings from the Info structs.
*/ */
typedef struct LodePNGDecoderSettings typedef struct LodePNGDecoderSettings {
{
LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
unsigned ignore_crc; /*ignore CRC checksums*/ unsigned ignore_crc; /*ignore CRC checksums*/
@@ -531,13 +509,12 @@ typedef struct LodePNGDecoderSettings
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGDecoderSettings; } LodePNGDecoderSettings;
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); void lodepng_decoder_settings_init(LodePNGDecoderSettings *settings);
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ /*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/
typedef enum LodePNGFilterStrategy typedef enum LodePNGFilterStrategy {
{
/*every filter at zero*/ /*every filter at zero*/
LFS_ZERO, LFS_ZERO,
/*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/
@@ -556,8 +533,7 @@ typedef enum LodePNGFilterStrategy
/*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding. /*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding.
Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/
typedef struct LodePNGColorProfile typedef struct LodePNGColorProfile {
{
unsigned colored; /*not greyscale*/ unsigned colored; /*not greyscale*/
unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/ unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/
unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/ unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/
@@ -566,24 +542,22 @@ typedef struct LodePNGColorProfile
unsigned alpha; /*alpha channel or alpha palette required*/ unsigned alpha; /*alpha channel or alpha palette required*/
unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/
unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/
unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ unsigned
bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/
} LodePNGColorProfile; } LodePNGColorProfile;
void lodepng_color_profile_init(LodePNGColorProfile* profile); void lodepng_color_profile_init(LodePNGColorProfile *profile);
/*Get a LodePNGColorProfile of the image.*/ /*Get a LodePNGColorProfile of the image.*/
unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, unsigned lodepng_get_color_profile(
const unsigned char* image, unsigned w, unsigned h, LodePNGColorProfile *profile, const unsigned char *image, unsigned w, unsigned h, const LodePNGColorMode *mode_in);
const LodePNGColorMode* mode_in);
/*The function LodePNG uses internally to decide the PNG color with auto_convert. /*The function LodePNG uses internally to decide the PNG color with auto_convert.
Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/ Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/
unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, unsigned lodepng_auto_choose_color(
const unsigned char* image, unsigned w, unsigned h, LodePNGColorMode *mode_out, const unsigned char *image, unsigned w, unsigned h, const LodePNGColorMode *mode_in);
const LodePNGColorMode* mode_in);
/*Settings for the encoder.*/ /*Settings for the encoder.*/
typedef struct LodePNGEncoderSettings typedef struct LodePNGEncoderSettings {
{
LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/
unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/
@@ -600,7 +574,7 @@ typedef struct LodePNGEncoderSettings
the same length as the amount of scanlines in the image, and each value must <= 5. You the same length as the amount of scanlines in the image, and each value must <= 5. You
have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero
must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ must be set to 0 to ensure this is also used on palette or low bitdepth images.*/
const unsigned char* predefined_filters; const unsigned char *predefined_filters;
/*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).
If colortype is 3, PLTE is _always_ created.*/ If colortype is 3, PLTE is _always_ created.*/
@@ -613,14 +587,12 @@ typedef struct LodePNGEncoderSettings
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGEncoderSettings; } LodePNGEncoderSettings;
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); void lodepng_encoder_settings_init(LodePNGEncoderSettings *settings);
#endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ENCODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
/*The settings, state and information for extended encoding and decoding.*/ /*The settings, state and information for extended encoding and decoding.*/
typedef struct LodePNGState typedef struct LodePNGState {
{
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
LodePNGDecoderSettings decoder; /*the decoding settings*/ LodePNGDecoderSettings decoder; /*the decoding settings*/
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
@@ -632,14 +604,14 @@ typedef struct LodePNGState
unsigned error; unsigned error;
#ifdef LODEPNG_COMPILE_CPP #ifdef LODEPNG_COMPILE_CPP
/* For the lodepng::State subclass. */ /* For the lodepng::State subclass. */
virtual ~LodePNGState(){} virtual ~LodePNGState() {}
#endif #endif
} LodePNGState; } LodePNGState;
/*init, cleanup and copy functions to use with this struct*/ /*init, cleanup and copy functions to use with this struct*/
void lodepng_state_init(LodePNGState* state); void lodepng_state_init(LodePNGState *state);
void lodepng_state_cleanup(LodePNGState* state); void lodepng_state_cleanup(LodePNGState *state);
void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); void lodepng_state_copy(LodePNGState *dest, const LodePNGState *source);
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
@@ -647,26 +619,21 @@ void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);
Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and
getting much more information about the PNG image and color mode. getting much more information about the PNG image and color mode.
*/ */
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode(
LodePNGState* state, unsigned char **out, unsigned *w, unsigned *h, LodePNGState *state, const unsigned char *in, size_t insize);
const unsigned char* in, size_t insize);
/* /*
Read the PNG header, but not the actual data. This returns only the information Read the PNG header, but not the actual data. This returns only the information
that is in the header chunk of the PNG, such as width, height and color type. The that is in the header chunk of the PNG, such as width, height and color type. The
information is placed in the info_png field of the LodePNGState. information is placed in the info_png field of the LodePNGState.
*/ */
unsigned lodepng_inspect(unsigned* w, unsigned* h, unsigned lodepng_inspect(unsigned *w, unsigned *h, LodePNGState *state, const unsigned char *in, size_t insize);
LodePNGState* state,
const unsigned char* in, size_t insize);
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ /*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/
unsigned lodepng_encode(unsigned char** out, size_t* outsize, unsigned lodepng_encode(
const unsigned char* image, unsigned w, unsigned h, unsigned char **out, size_t *outsize, const unsigned char *image, unsigned w, unsigned h, LodePNGState *state);
LodePNGState* state);
#endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ENCODER*/
/* /*
@@ -686,43 +653,43 @@ Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
There must be at least 4 bytes to read from. If the result value is too large, There must be at least 4 bytes to read from. If the result value is too large,
it may be corrupt data. it may be corrupt data.
*/ */
unsigned lodepng_chunk_length(const unsigned char* chunk); unsigned lodepng_chunk_length(const unsigned char *chunk);
/*puts the 4-byte type in null terminated string*/ /*puts the 4-byte type in null terminated string*/
void lodepng_chunk_type(char type[5], const unsigned char* chunk); void lodepng_chunk_type(char type[5], const unsigned char *chunk);
/*check if the type is the given type*/ /*check if the type is the given type*/
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); unsigned char lodepng_chunk_type_equals(const unsigned char *chunk, const char *type);
/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ /*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/
unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); unsigned char lodepng_chunk_ancillary(const unsigned char *chunk);
/*0: public, 1: private (see PNG standard)*/ /*0: public, 1: private (see PNG standard)*/
unsigned char lodepng_chunk_private(const unsigned char* chunk); unsigned char lodepng_chunk_private(const unsigned char *chunk);
/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ /*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); unsigned char lodepng_chunk_safetocopy(const unsigned char *chunk);
/*get pointer to the data of the chunk, where the input points to the header of the chunk*/ /*get pointer to the data of the chunk, where the input points to the header of the chunk*/
unsigned char* lodepng_chunk_data(unsigned char* chunk); unsigned char *lodepng_chunk_data(unsigned char *chunk);
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); const unsigned char *lodepng_chunk_data_const(const unsigned char *chunk);
/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ /*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/
unsigned lodepng_chunk_check_crc(const unsigned char* chunk); unsigned lodepng_chunk_check_crc(const unsigned char *chunk);
/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ /*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
void lodepng_chunk_generate_crc(unsigned char* chunk); void lodepng_chunk_generate_crc(unsigned char *chunk);
/*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/ /*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/
unsigned char* lodepng_chunk_next(unsigned char* chunk); unsigned char *lodepng_chunk_next(unsigned char *chunk);
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk); const unsigned char *lodepng_chunk_next_const(const unsigned char *chunk);
/* /*
Appends chunk to the data in out. The given chunk should already have its chunk header. Appends chunk to the data in out. The given chunk should already have its chunk header.
The out variable and outlength are updated to reflect the new reallocated buffer. The out variable and outlength are updated to reflect the new reallocated buffer.
Returns error code (0 if it went ok) Returns error code (0 if it went ok)
*/ */
unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk); unsigned lodepng_chunk_append(unsigned char **out, size_t *outlength, const unsigned char *chunk);
/* /*
Appends new chunk to out. The chunk to append is given by giving its length, type Appends new chunk to out. The chunk to append is given by giving its length, type
@@ -730,15 +697,13 @@ and data separately. The type is a 4-letter string.
The out variable and outlength are updated to reflect the new reallocated buffer. The out variable and outlength are updated to reflect the new reallocated buffer.
Returne error code (0 if it went ok) Returne error code (0 if it went ok)
*/ */
unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, unsigned lodepng_chunk_create(
const char* type, const unsigned char* data); unsigned char **out, size_t *outlength, unsigned length, const char *type, const unsigned char *data);
/*Calculate CRC32 of buffer*/ /*Calculate CRC32 of buffer*/
unsigned lodepng_crc32(const unsigned char* buf, size_t len); unsigned lodepng_crc32(const unsigned char *buf, size_t len);
#endif /*LODEPNG_COMPILE_PNG*/ #endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_ZLIB
/* /*
This zlib part can be used independently to zlib compress and decompress a This zlib part can be used independently to zlib compress and decompress a
@@ -748,9 +713,9 @@ part of zlib that is required for PNG, it does not support dictionaries.
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ /*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/
unsigned lodepng_inflate(unsigned char** out, size_t* outsize, unsigned lodepng_inflate(
const unsigned char* in, size_t insize, unsigned char **out, size_t *outsize, const unsigned char *in, size_t insize,
const LodePNGDecompressSettings* settings); const LodePNGDecompressSettings *settings);
/* /*
Decompresses Zlib data. Reallocates the out buffer and appends the data. The Decompresses Zlib data. Reallocates the out buffer and appends the data. The
@@ -758,9 +723,9 @@ data must be according to the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage. buffer and *outsize its size in bytes. out must be freed by user after usage.
*/ */
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, unsigned lodepng_zlib_decompress(
const unsigned char* in, size_t insize, unsigned char **out, size_t *outsize, const unsigned char *in, size_t insize,
const LodePNGDecompressSettings* settings); const LodePNGDecompressSettings *settings);
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
@@ -771,21 +736,21 @@ The data is output in the format of the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage. buffer and *outsize its size in bytes. out must be freed by user after usage.
*/ */
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, unsigned lodepng_zlib_compress(
const unsigned char* in, size_t insize, unsigned char **out, size_t *outsize, const unsigned char *in, size_t insize,
const LodePNGCompressSettings* settings); const LodePNGCompressSettings *settings);
/* /*
Find length-limited Huffman code for given frequencies. This function is in the Find length-limited Huffman code for given frequencies. This function is in the
public interface only for tests, it's used internally by lodepng_deflate. public interface only for tests, it's used internally by lodepng_deflate.
*/ */
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, unsigned
size_t numcodes, unsigned maxbitlen); lodepng_huffman_code_lengths(unsigned *lengths, const unsigned *frequencies, size_t numcodes, unsigned maxbitlen);
/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ /*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/
unsigned lodepng_deflate(unsigned char** out, size_t* outsize, unsigned lodepng_deflate(
const unsigned char* in, size_t insize, unsigned char **out, size_t *outsize, const unsigned char *in, size_t insize,
const LodePNGCompressSettings* settings); const LodePNGCompressSettings *settings);
#endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/ #endif /*LODEPNG_COMPILE_ZLIB*/
@@ -799,7 +764,7 @@ outsize: output parameter, size of the allocated out buffer
filename: the path to the file to load filename: the path to the file to load
return value: error code (0 means ok) return value: error code (0 means ok)
*/ */
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); unsigned lodepng_load_file(unsigned char **out, size_t *outsize, const char *filename);
/* /*
Save a file from buffer to disk. Warning, if it exists, this function overwrites Save a file from buffer to disk. Warning, if it exists, this function overwrites
@@ -809,41 +774,34 @@ buffersize: size of the buffer to write
filename: the path to the file to save to filename: the path to the file to save to
return value: error code (0 means ok) return value: error code (0 means ok)
*/ */
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); unsigned lodepng_save_file(const unsigned char *buffer, size_t buffersize, const char *filename);
#endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_DISK*/
#ifdef LODEPNG_COMPILE_CPP #ifdef LODEPNG_COMPILE_CPP
/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ /* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */
namespace lodepng namespace lodepng {
{
#ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_PNG
class State : public LodePNGState class State : public LodePNGState {
{
public: public:
State(); State();
State(const State& other); State(const State &other);
virtual ~State(); virtual ~State();
State& operator=(const State& other); State &operator=(const State &other);
}; };
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
/* Same as other lodepng::decode, but using a State for more settings and information. */ /* Same as other lodepng::decode, but using a State for more settings and information. */
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, unsigned
State& state, decode(std::vector<unsigned char> &out, unsigned &w, unsigned &h, State &state, const unsigned char *in, size_t insize);
const unsigned char* in, size_t insize); unsigned
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, decode(std::vector<unsigned char> &out, unsigned &w, unsigned &h, State &state, const std::vector<unsigned char> &in);
State& state,
const std::vector<unsigned char>& in);
#endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
/* Same as other lodepng::encode, but using a State for more settings and information. */ /* Same as other lodepng::encode, but using a State for more settings and information. */
unsigned encode(std::vector<unsigned char>& out, unsigned encode(std::vector<unsigned char> &out, const unsigned char *in, unsigned w, unsigned h, State &state);
const unsigned char* in, unsigned w, unsigned h, unsigned
State& state); encode(std::vector<unsigned char> &out, const std::vector<unsigned char> &in, unsigned w, unsigned h, State &state);
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
State& state);
#endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DISK #ifdef LODEPNG_COMPILE_DISK
@@ -851,35 +809,39 @@ unsigned encode(std::vector<unsigned char>& out,
Load a file from disk into an std::vector. Load a file from disk into an std::vector.
return value: error code (0 means ok) return value: error code (0 means ok)
*/ */
unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename); unsigned load_file(std::vector<unsigned char> &buffer, const std::string &filename);
/* /*
Save the binary data in an std::vector to a file on disk. The file is overwritten Save the binary data in an std::vector to a file on disk. The file is overwritten
without warning. without warning.
*/ */
unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename); unsigned save_file(const std::vector<unsigned char> &buffer, const std::string &filename);
#endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_PNG */ #endif /* LODEPNG_COMPILE_PNG */
#ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER #ifdef LODEPNG_COMPILE_DECODER
/* Zlib-decompress an unsigned char buffer */ /* Zlib-decompress an unsigned char buffer */
unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize, unsigned decompress(
const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); std::vector<unsigned char> &out, const unsigned char *in, size_t insize,
const LodePNGDecompressSettings &settings = lodepng_default_decompress_settings);
/* Zlib-decompress an std::vector */ /* Zlib-decompress an std::vector */
unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, unsigned decompress(
const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); std::vector<unsigned char> &out, const std::vector<unsigned char> &in,
const LodePNGDecompressSettings &settings = lodepng_default_decompress_settings);
#endif /* LODEPNG_COMPILE_DECODER */ #endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ENCODER
/* Zlib-compress an unsigned char buffer */ /* Zlib-compress an unsigned char buffer */
unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize, unsigned compress(
const LodePNGCompressSettings& settings = lodepng_default_compress_settings); std::vector<unsigned char> &out, const unsigned char *in, size_t insize,
const LodePNGCompressSettings &settings = lodepng_default_compress_settings);
/* Zlib-compress an std::vector */ /* Zlib-compress an std::vector */
unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, unsigned compress(
const LodePNGCompressSettings& settings = lodepng_default_compress_settings); std::vector<unsigned char> &out, const std::vector<unsigned char> &in,
const LodePNGCompressSettings &settings = lodepng_default_compress_settings);
#endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */ #endif /* LODEPNG_COMPILE_ZLIB */
} /* namespace lodepng */ } /* namespace lodepng */
@@ -896,10 +858,10 @@ TODO:
[X] let the "isFullyOpaque" function check color keys and transparent palettes too [X] let the "isFullyOpaque" function check color keys and transparent palettes too
[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" [X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
[ ] don't stop decoding on errors like 69, 57, 58 (make warnings) [ ] don't stop decoding on errors like 69, 57, 58 (make warnings)
[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ... [ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in
[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes text, ... [ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes [ ]
[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... [ ]
[ ] allow user to give data (void*) to custom allocator allow user to give data (void*) to custom allocator
*/ */
#endif /*LODEPNG_H inclusion guard*/ #endif /*LODEPNG_H inclusion guard*/