You Are Here Home > C Programming

C Programming

Animation Curves and Tweening; Understanding Animation Curves

These equations are by Robert Penner, you can find a document here that explains this in much greater detail:
http://www.robertpenner.com/easing/

The correct linear tween function looks like this:

float linear_tween(float t, float start, float end)
{
    if (t > 1.0f) return end;
    return t * end + (1.0f - t) * start;
}

t is the time since the start of animation started and it has to be between 0 and 1, start and end are the values that you want to interpolate between them…

To understand this equation you can so something very simple, assume start is 1 and end is 20, then at timestep 0 you will have:

0 * end + (1 – 0) * start => start

At time step 1 which is the end of your animation you get:

1 * end + (1 – 1) * start => end

And all the values between these are going to be interpolated linearly.

Now quadratic ease in function is where the changes in interpolated value are smaller in the beginning and larger at the end, how can we achieve this? We can do it by faking the time steps, if you we could somehow make it so that the time steps would look smaller to the linear tween function at the start of the animation and larger at the end, then we would achieve this, that way, in the beginning, the time steps look smaller so the function will change the value by just a little bit but at the end, the time steps look larger so the function will change the value by a larger amount.

The way to do this is very easy, the fact that the time step number is clamped to between 0 and 1 will help us in this case and this is the solution:

float quadratic_easein(float t, float start, float end)
{
    if (t > 1.0f) return end;
    return linear_tween(t * t, start, end);
}

When we multiply the time step by itself the numbers that are less than one get smaller, for example if you are at the time step 1/10th of a second:

1/10 * 1/10 => 1/100
2/10 * 2/10 => 4/100 (3/100 change)
3/10 * 3/10 => 9/100 (5/100 change)
4/10 * 4/10 => 16/100 (7/100 change)

8/10 * 8/10 => 64/100
9/10 * 9/10 => 81/100 (17/100 change)

Now let’s look at quadratic_easeout:

float quadratic_easeout(float t, float start, float end)
{
    if (t > 1.0f) return end;
    return linear_tween(2 * t - t * t, start, end);
}

Deriving 2*t – t*t is very easy knowing the fact above; to do this we need to reverse what happens above so we can do something:

t = 1 – t;

Now 1/10 becomes 9/10 so when we do:

t = t * t

The numbers are going to change more at the beginning of the time step but the problem is that now we converted 1/10 to 9/10 and t*t will result in 81/100 and that’s the end of our time step and the animation will play backwards, to fix it we need to do:

t = 1 – t

One more time so then 81/100 becomes 19/100, now let’s simplify this:

1 – t => 1 – t * t => 1 – ((1 – t) * (1 – t)) => 1 – (1 – t – t + t * t) => 2 * t – t * t

I hope this helps :)

Animation Curves and Tweening; Understanding Animation Curves
Comments (1)   Filed under: C Programming,C/C++,Mac,Objective-C,OpenGL   Posted by: Codehead

iPhone: libpng error: CgBI: unknown critical chunk

If you get this error when trying your app on the device, you have PNG compression on in Xcode, in Xcode 4 goto “Build Settings” search for PNG in the search box and turn off PNG compression…

iPhone: libpng error: CgBI: unknown critical chunk
Comments (1)   Filed under: C Programming,iPhone SDK,Mac Programming,Xcode   Posted by: Hamid

Popen+ a Bidirectional Popen Implementation With Ability to Access PID and Kill/Terminate Processes

On Github:
https://github.com/Codingrecipes/Popen+

This is a little popen implementation which will make it easier to kill processes and will give you access to the PID of the process, I don’t know why they didn’t do this in popen but I’m sure they had good reasons because those guys are way too smart…

popen_plus.h:

/*
 ** Author: Hamid Alipour http://codingrecipes.com http://twitter.com/code_head
 ** SQLite style license:
 ** 
 ** 2001 September 15
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
 **
 **    May you do good and not evil.
 **    May you find forgiveness for yourself and forgive others.
 **    May you share freely, never taking more than you give.
 **/
 
#ifndef POPEN_PLUS_H
#define POPEN_PLUS_H
 
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <paths.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
 
#define READ 0
#define WRITE 1
 
struct popen_plus_process {
    pthread_mutex_t mutex;
    pid_t pid;
    FILE *read_fp;
    FILE *write_fp;
};
 
struct popen_plus_process *popen_plus(const char *command);
int popen_plus_close(struct popen_plus_process *process);
int popen_plus_kill(struct popen_plus_process *process);
int popen_plus_kill_by_id(int process_id);
int popen_plus_terminate(struct popen_plus_process *process);
int popen_plus_terminate_with_id(int process_id);
 
#endif

popen_plus.c:

/*
 ** Author: Hamid Alipour http://codingrecipes.com http://twitter.com/code_head
 ** SQLite style license:
 ** 
 ** 2001 September 15
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
 **
 **    May you do good and not evil.
 **    May you find forgiveness for yourself and forgive others.
 **    May you share freely, never taking more than you give.
 **/
 
#include <errno.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <paths.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include "popen_plus.h"
 
struct popen_plus_process *popen_plus(const char *command)
{
    int inpipe[2];
    int outpipe[2];
    char *argv[4];
    struct popen_plus_process *process = malloc(sizeof(struct popen_plus_process));
 
    if (!process)
        goto error_out;
 
    if (pipe(inpipe) != 0)
        goto clean_process_out;
 
    if (pipe(outpipe) != 0)
        goto clean_inpipe_out;
 
    process->read_fp = fdopen(outpipe[READ], "r");
    if (!process->read_fp)
        goto clean_outpipe_out;
 
    process->write_fp = fdopen(inpipe[WRITE], "w");
    if (!process->write_fp)
        goto clean_read_fp_out;
 
    if (pthread_mutex_init(&process->mutex, NULL) != 0)
        goto clean_write_fp_out;
 
    process->pid = fork();
    if (process->pid == -1)
        goto clean_mutex_out;
 
    if (process->pid == 0) {
        close(outpipe[READ]);
        close(inpipe[WRITE]);
 
        if (inpipe[READ] != STDIN_FILENO) {
            dup2(inpipe[READ], STDIN_FILENO);
            close(inpipe[READ]);
        }
 
        if (outpipe[WRITE] != STDOUT_FILENO) {
            dup2(outpipe[WRITE], STDOUT_FILENO);
            close(outpipe[WRITE]);
        }
 
        argv[0] = "sh";
        argv[1] = "-c";
        argv[2] = (char *) command;
        argv[3] = NULL;
 
        execv(_PATH_BSHELL, argv);
        exit(127);
    }
 
    close(outpipe[WRITE]);
    close(inpipe[READ]);
 
    return process;
 
clean_mutex_out:
    pthread_mutex_destroy(&process->mutex);
 
clean_write_fp_out:
    fclose(process->write_fp);
 
clean_read_fp_out:
    fclose(process->read_fp);
 
clean_outpipe_out:
    close(outpipe[READ]);
    close(outpipe[WRITE]);
 
clean_inpipe_out:
    close(inpipe[READ]);
    close(inpipe[WRITE]);
 
clean_process_out:
    free(process);
 
error_out:
    return NULL;
}
 
int popen_plus_close(struct popen_plus_process *process)
{
    int pstat;
    pid_t pid;
 
    /**
     * If someone else destrys this mutex, then this call will fail and we know
     * that another thread already cleaned up the process so we can safely return
     * and since we are destroying this mutex bellow then we don't need to unlock
     * it...
     */
    if (pthread_mutex_lock(&process->mutex) != 0)
        return 0;
 
    if (process->pid != -1) {
        do {
            pid = waitpid(process->pid, &pstat, 0);
        } while (pid == -1 && errno == EINTR);
    }
 
    if (process->read_fp)
        fclose(process->read_fp);
 
    if (process->write_fp)
        fclose(process->write_fp);
 
    pthread_mutex_destroy(&process->mutex);
 
    free(process);
 
    return (pid == -1 ? -1 : pstat);
}
 
int popen_plus_kill(struct popen_plus_process *process)
{
    char command[64];
 
    sprintf(command, "kill -9 %d", process->pid);
    system(command);
 
    return 0;
}
 
int popen_plus_kill_by_id(int process_id)
{
    char command[64];
 
    sprintf(command, "kill -9 %d", process_id);
    system(command);
 
    return 0;
}
 
int popen_plus_terminate(struct popen_plus_process *process)
{
    char command[64];
 
    sprintf(command, "kill -TERM %d", process->pid);
    system(command);
 
    return 0;
}
 
int popen_plus_terminate_with_id(int process_id)
{
    char command[64];
 
    sprintf(command, "kill -TERM %d", process_id);
    system(command);
 
    return 0;
}

This code was inspired by many sources and I think I perfected it, although you might find bugs or issues and if you do, please let me know if the comments section.

You can use it like so:

struct popen_plus_process *process = popen_plus("ls -l");
if (!process) {
     /* Failed do something and return or exit */
     return -1;
}
 
int MAX_BUFFER = 256;
char buffer[256];
 
while (!feof(process->read_fp))
     if (fgets(buffer, MAX_BUFFER, process->read_fp) != NULL)
          printf("%s\n", buffer);
 
popen_plus_close(process);

To kill a process:

popen_plus_kill(process);
popen_plus_close(process);

Terminate is similar to kill…

I hope this helps someone!

:)

Popen+ a Bidirectional Popen Implementation With Ability to Access PID and Kill/Terminate Processes

SQLite And The Problem Of Storing Long Long Integers

Recently, I was trying to store a very large integer value in a SQLite column, it didn’t matter wether I used INTEGER or UNSIGNED BIG INT, SQLite rounded it for me and I was left with an integer value that wasn’t even close to what I needed.

So one solution was to just use a VARCHAR or TEXT or event a BLOB and insert the number with quotes around it but guess what? SQLite did it again!!!

It turns out that SQLite tries to convert your values to ints to give you some benefits with sorting and comparing etc. – in case you didn’t know you really wanted an int rather than a BLOB – and that happens here in one of it’s functions:

/*
** Try to convert a value into a numeric representation if we can
** do so without loss of information.  In other words, if the string
** looks like a number, convert it into a number.  If it does not
** look like a number, leave it alone.
*/
static void applyNumericAffinity(Mem *pRec){
  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
    double rValue;
    i64 iValue;
    u8 enc = pRec->enc;
    if( (pRec->flags&MEM_Str)==0 ) return;
    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
      pRec->u.i = iValue;
      pRec->flags |= MEM_Int;
    }else{
      pRec->r = rValue;
      pRec->flags |= MEM_Real;
    }
  }
}

The solution to this issue is to prepend a 0 to your number and use a BLOB or TEXT type column and insert it like this: ’0THEVERYLARGENUMBER’

Don’t get me wrong, SQLite is a great library that I’ve been using, it’s very well tested and works great, it’s fast and thread safe, I specially like it’s licensee:

/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************

I hope this helps…

SQLite And The Problem Of Storing Long Long Integers

How Not To Write Code

I’m working on a website and it’s absolutely awful, almost all the design choices are bad so I will compile a list here as I encounter them:

1 – Don’t have fields in your database like “extra1″, “extra2″ or “extra3″ you probably need to refactor and rethink your design…

2 – Don’t have a global object and access and manipulate it from deep inside your code, here for example there is a $tpl variable which – wrongly – is called $class_tpl and it’s global, the authors are calling a pager function to create an array for rendering a pager and after they call they manipulate the $class_tpl a bit by adding paging data to it and you would think that was it, but guess what? In their pager function they again access $class_tpl and manipulate a bit more!!!

3 – Don’t ever, ever, ever, ever query your database from within your templates, never…

4 – Don’t die or exit out of functions, return error messages…

5 – Don’t output out of function either, no “echo $blah;” in a function, they should return the text string rather than printing it…

6 – Don’t ever, ever, ever repeat yourself, if you are too lazy to write a function or rethink that portion of your code, then you suck as a programmer… To be honest, I do suck sometimes, but I try my very best :)

How Not To Write Code
Comments (0)   Filed under: C Programming,General,PHP,Web Development   Posted by: Hamid

C: Determining Size Of a Malloced C Pointer At Runtime

There is no direct/cross-platform way of doing this but you could do something cool, you could do what malloc does… (Although malloc stores more data than this)

Say you want to allocate a chunk that is 100 bytes and you want to somehow attach this size to it, so you can check the size anytime later on, what you do is this: you allocate 100 bytes + sizeof(size_t) and then store the size of this chunk which is 100 at the beginning of the chunk, then you return the address of the chunk starting right after the 100:

struct chunk_header {
    size_t size;
};
 
 void *my_malloc(size_t size)
{
    size_t header_size = sizeof(struct chunk_header);
    size_t alloc_size = header_size + size;
    void *chunk = malloc(alloc_size);
    struct chunk_header *header;
    if (!chunk)
        return NULL;
    header = (struct chunk_header *) chunk;
    header->size = alloc_size; /* Or just size, it's up to you... */
    return (char *) chunk + header_size; /* char * hack, go look it up... */
}

Later on, you can check the size like so:

size_t header_size = sizeof(struct chunk_header)
void *chunk = (char *) p - header_size;
struct chunk_header *header = (struct chunk_header *) chunk;
printf("This chunk of memory is: %d bytes...\n", (int) header->size);
C: Determining Size Of a Malloced C Pointer At Runtime
Comments (1)   Filed under: C Programming,C/C++   Posted by: Hamid

Xcode: Embedding Lua In iPhone Apps

This is very simple, even though I can’t find so many resource regarding this online; follow these steps:

1- Download the latest version of Lua from: http://www.lua.org/ftp/

2- Obviously unpack it and find the “src” folder.

3- Delete the files: “lua.c”, “luac.c” and “print.c”

4- Grab the “src” file and drop it in your project’s left pane, under your projects’s name along with “Classes”, “Resources” etc.

5- Rename this newly added “src” to “lua”

Now you should be able to follow these types of tutorials:
http://www.ibm.com/developerworks/opensource/library/l-embed-lua/index.html

Hope this works for you!

Xcode: Embedding Lua In iPhone Apps
Comments (0)   Filed under: C Programming,iPhone SDK,Lua,Xcode   Posted by: Hamid

C: Set An Entire Array Of Pointers To NULL

Apparently you can’t use memset() to do this:

memset(the_pointer, '0', sizeof(the array));

This will set all the bits in the array to zero but 0 is not guaranteed to be the representation of a NULL pointer so this might be true:

if (the_pointer_array[10] != NULL) {}

You must loop through and set them one by one…

C: Set An Entire Array Of Pointers To NULL
Comments (0)   Filed under: C Programming,C/C++   Posted by: Hamid

OpenGL ES: Unbinding Vertex Buffer Objects – VBOs

I couldn’t find this mentioned anywhere online, but the solution is very easy:

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

I hope this helps!

OpenGL ES: Unbinding Vertex Buffer Objects – VBOs
Comments (1)   Filed under: C Programming,C/C++,OpenGL   Posted by: Codehead

Understanding Pointers In C – C Pointers Tutorial

We need to cover some ground so be patient and you will learn all about pointers.

A computer stores variables in it’s memory and the memory is basically a series of zeros and ones.

So if you could see the raw contents of your RAM you would see something similar to this:

010010010111111101010010101001010100101111001010100111001

Although your memory will have much more number of zeros and ones but it’s basically laid out like this.

In C when you say:

int x = 5;

This line basically telling the compiler to store 5 in variable x that is of type int.

The int datatype is 2 or 4 bytes depending on the implementation – and on my computer it’s 4

bytes but I assume 2 bytes here – so the compiler allocates 2 bytes of memory to store the number 5.

It will convert it to binary for you and 5 is 101 in binary but your compiler will store this in 2 bites so it will look like this:

0000000000000101

Note that it’s just padded with zeros so it can fit in a 2 byte space.

Depending on your operating system this could look like this:

1010000000000000

The first one looks more intuitive and mathematically correct so we use the first type in our examples. It is also called big endian architecture.

So if you were to map the memory, it would look something like this:

0100100101111111010100100000000000001010101001010100101111001010100111001

Can you see our number in there? How about now:

01001001011111110101001|0000000000000101|0101001010100101111001010100111001

Let’s define a pointer and set it to point to our number in memory:

int x = 5;
int *y = &x;

The second line is telling the compiler that y is a pinter to int, pointer is the address of our

variable in memory so y is basically this:

01001001011111110101001->|0000000000000101|0101001010100101111001010100111001

The & operator behind x returns it’s position in memory, if you count it’s 23.

So if you print y it will print the address of the variable which in our simple example is 23 so:

printf("%d", y);

Would print 23, but the cool thing is that you can do this:

printf("%d", *y);

The * is derefrancing operator, what it does is simple asks the compiler to dereference y and find the variable it’s pointing to and print that, so the program won’t print the number 23 anymore, instead it goes to the address 23 and grabs the value that is sitting there and prints that:

01001001011111110101001->|0000000000000101|0101001010100101111001010100111001

But you see, there are so many zeros and ones there, how does the compiler know how many of them

are actually part of our variable, because it picks only 5 of them:

01001001011111110101001->|00000|<-00000000101|0101001010100101111001010100111001

They will all be zeros and we know that this is wrong, our value was 5 not zero.

That’s why you defined a pointer to int, the compiler knows that it’s looking for an int so when you say *y – or derefrence y – the compiler goes to address 23 and grabs 2 bytes from there:

01001001011111110101001->|0000000000000101|<-0101001010100101111001010100111001

This is basically what a pointer is and one of the thing that can be done with a pointer is to modify the original variable without touching the original variable, so if you where to do this:

int x = 5;
int *y = &x;
*y = 20;

The compiler would look at y and go to address 23 and modify the contents in there to 20 rather than 5, so if you print x, you will get 20 rather than 5.

Pointers enable us to do some advanced stuff using C, that would be the subject of my next post.

Note: this tutorials are meant to be as simple as possible so a lot of details such as how pointers are stored are omitted to prevent confusion and will be discussed at some future point.

Understanding Pointers In C – C Pointers Tutorial
Comments (0)   Filed under: C Programming,Data Structures,Programming   Posted by: Codehead
Older Posts »