<commit_before>#include <allegro.h>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <vector>
#include <map>

#include "globals.h"
#include "mugen_reader.h"
#include "mugen_section.h"
#include "mugen_item_content.h"
#include "mugen_item.h"
#include "mugen_character.h"
#include "mugen_animation.h"
#include "mugen_sprite.h"

#include "util/bitmap.h"
#include "util/funcs.h"

#include "factory/font_render.h"

#include "gui/keyinput_manager.h"

using namespace std;

/* testing spellcasters code
static int sff_memloadInt(unsigned char *data, int *ofs) {
    int a,b;
    a = data[*ofs];
    (*ofs)++;
    b = data[*ofs];
    (*ofs)++;
    return a + (b <<8);
}

static RGB* sffLoadPaletteFromMemory(unsigned char *data) {
    RGB* pal = (RGB*) malloc(sizeof(RGB) * 256);
    int  a, ofs;
    ofs = 0;
    for (a=0; a < 256; ++a) {
        pal[a].r = data[ofs++] / 4;
        pal[a].g = data[ofs++] / 4;
        pal[a].b = data[ofs++] / 4;
    }
    return pal;
}

static BITMAP* sffLoadPcxFromMemory(unsigned char* data) {
    BITMAP *bmp = NULL;

    // skip the first 3 bytes
    int     ofs = 3;
    //char    planes = data[ofs++];
    int     width  = -sff_memloadInt(data, &ofs);
    int     height = -sff_memloadInt(data, &ofs);
    int     bpp  = 0;
    int     bytesPerLine = 0;
    int     x,y;
    int     value;
    int     count;

    width += sff_memloadInt(data, &ofs) +1;
    height+= sff_memloadInt(data, &ofs) +1;

    // skip 4 bytes (dpi)
    ofs += 4;

    // skip 16 color palette
    ofs += 48;

    /// padding
    ofs++;

    bpp  = data[ofs++] *8;
    if (bpp != 8) { // || bpp != 24) {
        return NULL;
    }

    bytesPerLine = sff_memloadInt(data, &ofs);

    // image data starts at ofs 128
    ofs = 128;
    bmp = create_bitmap_ex(bpp, width, height);
    for (y=0; y < height; ++y) {
        x = 0;
        while (x < bytesPerLine) {
            value = data[ofs++];

            // check if upper 2 bit are set
            if ((value & 0xc0) == 0xc0) {
                // bits are set, that means the
                 //  lower 6 bit contain the repeat count,
                 //  and the color is stored in the next byte

                count = value & 0x3f;
                value = data[ofs++];
            } else {
                // value contains the color already
                count = 1;
            }
            if (bpp == 8) {
                while (count > 0) {
                    if (x < bmp->w) {
                        bmp->line[y][x] = value;
                    }
                    ++x;
                    --count;
                }
            }
        }
    }

    return bmp;
}
*/

static bool isArg( const char * s1, const char * s2 ){
	return strcasecmp( s1, s2 ) == 0;
}

static void showOptions(){
    Global::debug(0) << "M.U.G.E.N. Config Reader:" << endl;
    Global::debug(0) << "-f <file>: Load a M.U.G.E.N. config file and output to screen." << endl;
    Global::debug(0) << "-c <name>: Load a M.U.G.E.N. character and output some data about it.\n         ie: 'data/mugen/chars/name' only pass name." << endl;
    Global::debug(0) << endl;
}

/* testing testing 1 2 3 */
void testPCX(){
    unsigned char data[1 << 18];
    FILE * f = fopen("x.pcx", "r");
    int length;
    length = fread(data, sizeof(char), 1<<18, f);
    Global::debug(0) << "Size is " << length << endl;
    fclose(f);
    Bitmap b = Bitmap::memoryPCX(data, length);
    // Bitmap b("x.pcx");
    if (b.getError()){
        Global::debug(0) << "what the hell" << endl;
    }
    Bitmap work(640, 480);
    work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0));
    b.draw(0, 0, work);
    Global::debug(0) << "Width " << b.getWidth() << " Height " << b.getHeight() << endl;
    work.BlitToScreen();
    Util::rest(3000);
}

int main( int argc, char ** argv ){

	if(argc <= 1){
	    showOptions();
	    return 0;
	}

	const char * FILE_ARG = "-f";
	const char * LOC_ARG = "-c";
        const char * DEBUG_ARG = "-l";
	std::string ourFile;
	bool configLoaded = false;

        allegro_init();
        install_timer();
	install_keyboard();
        set_color_depth(16);
        Bitmap::setGfxModeWindowed(640, 480);

	for ( int q = 1; q < argc; q++ ){
		if ( isArg( argv[ q ], FILE_ARG ) ){
			q += 1;
			if ( q < argc ){
				ourFile = std::string( argv[ q ] );
				configLoaded = !configLoaded;
			}
			else{
                            Global::debug(0) << "Error no file given!" << endl;
			  showOptions();
			  return 0;
			}
		} else if ( isArg( argv[ q ], LOC_ARG ) ){
			q += 1;
			if ( q < argc ){
				ourFile = std::string( argv[ q ] );
			}
			else{
                            Global::debug(0) << "Error no file given!" << endl;
			  showOptions();
			  return 0;
			}
		} else if (isArg(argv[q], DEBUG_ARG)){
                    q += 1;
                    if (q < argc){
                        istringstream i( argv[ q ] );
                        int f;
                        i >> f;
                        Global::setDebug( f );
                    } else {
                        Global::debug(0) << "No number given for " << DEBUG_ARG << endl;
                    }
                } else {
		    // WHAT?
		    showOptions();
		    return 0;
		}
	}

	if( configLoaded ){
	    MugenReader reader( ourFile );

	    std::vector< MugenSection * > collection;

	    try{
		collection = reader.getCollection();
                Global::debug(0) << endl << "---------------------------------------------------------" << endl;
		for( unsigned int i = 0; i < collection.size(); ++i ){
                    Global::debug(0) << collection[i]->getHeader() << endl;
                    Global::debug(0) << "---------------------------------------------------------" << endl;
		    while( collection[i]->hasItems() ){
			MugenItemContent *content = collection[i]->getNext();
                        while( content->hasItems() ){
                            Global::debug(0) << content->getNext()->query();
                            if( content->hasItems() ) Global::debug(0) << ",";
                        }
                        Global::debug(0) << endl;
		    }
                    Global::debug(0) << "---------------------------------------------------------" << endl;
		}
                Global::debug(0) << endl;
	    }
	    catch( MugenException &ex){
                Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl;
		return 1;
	    }
	}
	else{
	    try{
                Global::debug(0) << "Trying to load character: " << ourFile << "..." << endl;
		MugenCharacter character( ourFile );
		character.load();
		/*
                for (map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); it != character.getAnimations().end(); it++){
                    Global::debug(0) << "Animation " << it->first << endl;
                    const vector<MugenFrame*> & frames = it->second->getFrames();
                    for (vector<MugenFrame*>::const_iterator frame = frames.begin(); frame != frames.end(); frame++){
                        MugenSprite * sprite = (*frame)->sprite;
                        if (sprite == 0){
                            continue;
                        }
                        Bitmap b = new Bitmap(sffLoadPcxFromMemory( (char*) sprite->pcx ));;//Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
                        b.BlitToScreen();
                        Util::rest(1000);
                    }
                }
		*/
		Global::debug(0) << "Loaded character: \"" << character.getName() << "\" successfully." << endl;
		bool quit = false;
		bool animate = false;
		int ticks = 0;
		int loop = 0;

		map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin();
		unsigned int currentAnim = 0;
		unsigned int lastAnim = character.getAnimations().size() -1;
		unsigned int currentFrame = 0;
		unsigned int lastFrame = it->second->getFrames().size() -1;

		MugenSprite * sprite = it->second->getFrames()[currentFrame]->sprite;

		//BITMAP *b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
		//Bitmap b = Bitmap(b_buff, true);//Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
		//destroy_bitmap(b_buff);
		Bitmap b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);

		Bitmap work( 640, 480 );

		while( !quit ){
		    work.clear();
		    keyInputManager::update();
		    ++ticks;
		    // Since -1 is to stop the animation completely, we'll give it a pause of 150 ticks, because we want to see the loop
		    const int time = it->second->getFrames()[currentFrame]->time == -1 ? 150 : it->second->getFrames()[currentFrame]->time;
		    if(animate && ticks >= 15 + time){
			ticks = 0;
			if( it->second->getFrames()[currentFrame]->loopstart ) loop = currentFrame;
			if( currentFrame < lastFrame )currentFrame++;
			else currentFrame = loop;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			   /*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff);*/
			   b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }

		    if( keyInputManager::keyState(keys::UP, true) ){
			if( currentAnim < lastAnim ){
			    currentAnim++;
			    it++;
			}
			loop = 0;
			currentFrame = 0;
			lastFrame = it->second->getFrames().size()-1;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			  /* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff);*/
			  b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::DOWN, true) ){
			if( currentAnim > 0 ){
			    currentAnim--;
			    it--;
			}
			loop = 0;
			currentFrame = 0;
			lastFrame = it->second->getFrames().size()-1;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			   /*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff);*/
			   b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::LEFT, true) && !animate){
			if( currentFrame > 0 )currentFrame--;
			else currentFrame = lastFrame;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			  /*  b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff); */
			  b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){
			if( currentFrame < lastFrame )currentFrame++;
			else currentFrame = 0;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			   /*  b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff); */
			  b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::SPACE, true) ){
			animate = !animate;
		    }
		    quit |= keyInputManager::keyState(keys::ESC, true );

		    b.Blit(240 + it->second->getFrames()[currentFrame]->xoffset, 100 + it->second->getFrames()[currentFrame]->yoffset, work);
		    Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, "Current Animation: %i, Current Frame: %i", 0, currentAnim, currentFrame );
		    if(sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, "Length: %d | x: %d | y: %d | Group: %d | Image: %d", sprite->length, sprite->x, sprite->y, sprite->groupNumber, sprite->imageNumber);
		    work.BlitToScreen();
		    Util::rest(1);
		}
	    }
	    catch( MugenException &ex){
                Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl;
		return 1;
	    }
	}

	return 0;
}
<commit_msg>Corrected print info in test<commit_after>#include <allegro.h>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <vector>
#include <map>

#include "globals.h"
#include "mugen_reader.h"
#include "mugen_section.h"
#include "mugen_item_content.h"
#include "mugen_item.h"
#include "mugen_character.h"
#include "mugen_animation.h"
#include "mugen_sprite.h"

#include "util/bitmap.h"
#include "util/funcs.h"

#include "factory/font_render.h"

#include "gui/keyinput_manager.h"

using namespace std;

/* testing spellcasters code
static int sff_memloadInt(unsigned char *data, int *ofs) {
    int a,b;
    a = data[*ofs];
    (*ofs)++;
    b = data[*ofs];
    (*ofs)++;
    return a + (b <<8);
}

static RGB* sffLoadPaletteFromMemory(unsigned char *data) {
    RGB* pal = (RGB*) malloc(sizeof(RGB) * 256);
    int  a, ofs;
    ofs = 0;
    for (a=0; a < 256; ++a) {
        pal[a].r = data[ofs++] / 4;
        pal[a].g = data[ofs++] / 4;
        pal[a].b = data[ofs++] / 4;
    }
    return pal;
}

static BITMAP* sffLoadPcxFromMemory(unsigned char* data) {
    BITMAP *bmp = NULL;

    // skip the first 3 bytes
    int     ofs = 3;
    //char    planes = data[ofs++];
    int     width  = -sff_memloadInt(data, &ofs);
    int     height = -sff_memloadInt(data, &ofs);
    int     bpp  = 0;
    int     bytesPerLine = 0;
    int     x,y;
    int     value;
    int     count;

    width += sff_memloadInt(data, &ofs) +1;
    height+= sff_memloadInt(data, &ofs) +1;

    // skip 4 bytes (dpi)
    ofs += 4;

    // skip 16 color palette
    ofs += 48;

    /// padding
    ofs++;

    bpp  = data[ofs++] *8;
    if (bpp != 8) { // || bpp != 24) {
        return NULL;
    }

    bytesPerLine = sff_memloadInt(data, &ofs);

    // image data starts at ofs 128
    ofs = 128;
    bmp = create_bitmap_ex(bpp, width, height);
    for (y=0; y < height; ++y) {
        x = 0;
        while (x < bytesPerLine) {
            value = data[ofs++];

            // check if upper 2 bit are set
            if ((value & 0xc0) == 0xc0) {
                // bits are set, that means the
                 //  lower 6 bit contain the repeat count,
                 //  and the color is stored in the next byte

                count = value & 0x3f;
                value = data[ofs++];
            } else {
                // value contains the color already
                count = 1;
            }
            if (bpp == 8) {
                while (count > 0) {
                    if (x < bmp->w) {
                        bmp->line[y][x] = value;
                    }
                    ++x;
                    --count;
                }
            }
        }
    }

    return bmp;
}
*/

static bool isArg( const char * s1, const char * s2 ){
	return strcasecmp( s1, s2 ) == 0;
}

static void showOptions(){
    Global::debug(0) << "M.U.G.E.N. Config Reader:" << endl;
    Global::debug(0) << "-f <file>: Load a M.U.G.E.N. config file and output to screen." << endl;
    Global::debug(0) << "-c <name>: Load a M.U.G.E.N. character and output some data about it.\n         ie: 'data/mugen/chars/name' only pass name." << endl;
    Global::debug(0) << endl;
}

/* testing testing 1 2 3 */
void testPCX(){
    unsigned char data[1 << 18];
    FILE * f = fopen("x.pcx", "r");
    int length;
    length = fread(data, sizeof(char), 1<<18, f);
    Global::debug(0) << "Size is " << length << endl;
    fclose(f);
    Bitmap b = Bitmap::memoryPCX(data, length);
    // Bitmap b("x.pcx");
    if (b.getError()){
        Global::debug(0) << "what the hell" << endl;
    }
    Bitmap work(640, 480);
    work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0));
    b.draw(0, 0, work);
    Global::debug(0) << "Width " << b.getWidth() << " Height " << b.getHeight() << endl;
    work.BlitToScreen();
    Util::rest(3000);
}

int main( int argc, char ** argv ){

	if(argc <= 1){
	    showOptions();
	    return 0;
	}

	const char * FILE_ARG = "-f";
	const char * LOC_ARG = "-c";
        const char * DEBUG_ARG = "-l";
	std::string ourFile;
	bool configLoaded = false;

        allegro_init();
        install_timer();
	install_keyboard();
        set_color_depth(16);
        Bitmap::setGfxModeWindowed(640, 480);

	for ( int q = 1; q < argc; q++ ){
		if ( isArg( argv[ q ], FILE_ARG ) ){
			q += 1;
			if ( q < argc ){
				ourFile = std::string( argv[ q ] );
				configLoaded = !configLoaded;
			}
			else{
                            Global::debug(0) << "Error no file given!" << endl;
			  showOptions();
			  return 0;
			}
		} else if ( isArg( argv[ q ], LOC_ARG ) ){
			q += 1;
			if ( q < argc ){
				ourFile = std::string( argv[ q ] );
			}
			else{
                            Global::debug(0) << "Error no file given!" << endl;
			  showOptions();
			  return 0;
			}
		} else if (isArg(argv[q], DEBUG_ARG)){
                    q += 1;
                    if (q < argc){
                        istringstream i( argv[ q ] );
                        int f;
                        i >> f;
                        Global::setDebug( f );
                    } else {
                        Global::debug(0) << "No number given for " << DEBUG_ARG << endl;
                    }
                } else {
		    // WHAT?
		    showOptions();
		    return 0;
		}
	}

	if( configLoaded ){
	    MugenReader reader( ourFile );

	    std::vector< MugenSection * > collection;

	    try{
		collection = reader.getCollection();
                Global::debug(0) << endl << "---------------------------------------------------------" << endl;
		for( unsigned int i = 0; i < collection.size(); ++i ){
                    Global::debug(0) << collection[i]->getHeader() << endl;
                    Global::debug(0) << "---------------------------------------------------------" << endl;
		    while( collection[i]->hasItems() ){
			MugenItemContent *content = collection[i]->getNext();
                        while( content->hasItems() ){
                            Global::debug(0) << content->getNext()->query();
                            if( content->hasItems() ) Global::debug(0) << ",";
                        }
                        Global::debug(0) << endl;
		    }
                    Global::debug(0) << "---------------------------------------------------------" << endl;
		}
                Global::debug(0) << endl;
	    }
	    catch( MugenException &ex){
                Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl;
		return 1;
	    }
	}
	else{
	    try{
                Global::debug(0) << "Trying to load character: " << ourFile << "..." << endl;
		MugenCharacter character( ourFile );
		character.load();
		/*
                for (map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); it != character.getAnimations().end(); it++){
                    Global::debug(0) << "Animation " << it->first << endl;
                    const vector<MugenFrame*> & frames = it->second->getFrames();
                    for (vector<MugenFrame*>::const_iterator frame = frames.begin(); frame != frames.end(); frame++){
                        MugenSprite * sprite = (*frame)->sprite;
                        if (sprite == 0){
                            continue;
                        }
                        Bitmap b = new Bitmap(sffLoadPcxFromMemory( (char*) sprite->pcx ));;//Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
                        b.BlitToScreen();
                        Util::rest(1000);
                    }
                }
		*/
		Global::debug(0) << "Loaded character: \"" << character.getName() << "\" successfully." << endl;
		bool quit = false;
		bool animate = false;
		int ticks = 0;
		int loop = 0;

		map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin();
		unsigned int currentAnim = 0;
		unsigned int lastAnim = character.getAnimations().size() -1;
		unsigned int currentFrame = 0;
		unsigned int lastFrame = it->second->getFrames().size() -1;

		MugenSprite * sprite = it->second->getFrames()[currentFrame]->sprite;

		//BITMAP *b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
		//Bitmap b = Bitmap(b_buff, true);//Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
		//destroy_bitmap(b_buff);
		Bitmap b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);

		Bitmap work( 640, 480 );

		while( !quit ){
		    work.clear();
		    keyInputManager::update();
		    ++ticks;
		    // Since -1 is to stop the animation completely, we'll give it a pause of 150 ticks, because we want to see the loop
		    const int time = it->second->getFrames()[currentFrame]->time == -1 ? 150 : it->second->getFrames()[currentFrame]->time;
		    if(animate && ticks >= 15 + time){
			ticks = 0;
			if( it->second->getFrames()[currentFrame]->loopstart ) loop = currentFrame;
			if( currentFrame < lastFrame )currentFrame++;
			else currentFrame = loop;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			   /*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff);*/
			   b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }

		    if( keyInputManager::keyState(keys::UP, true) ){
			if( currentAnim < lastAnim ){
			    currentAnim++;
			    it++;
			}
			loop = 0;
			currentFrame = 0;
			lastFrame = it->second->getFrames().size()-1;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			  /* b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff);*/
			  b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::DOWN, true) ){
			if( currentAnim > 0 ){
			    currentAnim--;
			    it--;
			}
			loop = 0;
			currentFrame = 0;
			lastFrame = it->second->getFrames().size()-1;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			   /*b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff);*/
			   b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::LEFT, true) && !animate){
			if( currentFrame > 0 )currentFrame--;
			else currentFrame = lastFrame;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			  /*  b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff); */
			  b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){
			if( currentFrame < lastFrame )currentFrame++;
			else currentFrame = 0;
			sprite = it->second->getFrames()[currentFrame]->sprite;
			if (sprite != 0){
			   /*  b_buff = sffLoadPcxFromMemory( (unsigned char*) sprite->pcx );
			   b = Bitmap(b_buff, true);
			   destroy_bitmap(b_buff); */
			  b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->reallength);
			}
		    }
		    else if( keyInputManager::keyState(keys::SPACE, true) ){
			animate = !animate;
		    }
		    quit |= keyInputManager::keyState(keys::ESC, true );

		    b.Blit(240 + it->second->getFrames()[currentFrame]->xoffset, 100 + it->second->getFrames()[currentFrame]->yoffset, work);
		    Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, "Current Animation: %i, Current Frame: %i", 0, currentAnim, currentFrame );
		    if(sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, "Length: %d | x: %d | y: %d | Group: %d | Image: %d",0, sprite->length, sprite->x, sprite->y, sprite->groupNumber, sprite->imageNumber);
		    work.BlitToScreen();
		    Util::rest(1);
		}
	    }
	    catch( MugenException &ex){
                Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl;
		return 1;
	    }
	}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Bugfix: `Scene::get_turbo_factor`: return `NAN` as a fallback.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: iframe.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 23:22:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#include "iframe.hxx"
#include <sfx2/sfxdlg.hxx>
#include <sfx2/sfxsids.hrc>

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#include <tools/urlobj.hxx>
#include <tools/debug.hxx>
#include <rtl/ustring.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <svtools/miscopt.hxx>
#include <vcl/window.hxx>

using namespace ::com::sun::star;

namespace sfx2
{

class IFrameWindow_Impl : public Window
{
    uno::Reference < frame::XFrame > mxFrame;
    sal_Bool                bActive;
    sal_Bool                bBorder;

public:
    IFrameWindow_Impl( Window *pParent,
                       sal_Bool bHasBorder,
                       WinBits nWinBits = 0 );

public:
    void            SetBorder( sal_Bool bNewBorder = sal_True );
    sal_Bool        HasBorder() const { return bBorder; }
};

IFrameWindow_Impl::IFrameWindow_Impl( Window *pParent, sal_Bool bHasBorder, WinBits nWinBits )
    : Window( pParent, nWinBits | WB_CLIPCHILDREN | WB_NODIALOGCONTROL | WB_DOCKBORDER )
    , bActive(sal_False)
    , bBorder(bHasBorder)
{
    if ( !bHasBorder )
        SetBorderStyle( WINDOW_BORDER_NOBORDER );
    else
        SetBorderStyle( WINDOW_BORDER_NORMAL );
    //SetActivateMode( ACTIVATE_MODE_GRABFOCUS );
}

void IFrameWindow_Impl::SetBorder( sal_Bool bNewBorder )
{
    if ( bBorder != bNewBorder )
    {
        Size aSize = GetSizePixel();
        bBorder = bNewBorder;
        if ( bBorder )
            SetBorderStyle( WINDOW_BORDER_NORMAL );
        else
            SetBorderStyle( WINDOW_BORDER_NOBORDER );
        if ( GetSizePixel() != aSize )
            SetSizePixel( aSize );
    }
}

#define PROPERTY_UNBOUND 0

SfxItemPropertyMap aIFramePropertyMap_Impl[] =
{
    { "FrameIsAutoBorder",    17, 1, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameIsAutoScroll",    17, 2, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameIsBorder",        13, 3, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameIsScrollingMode", 20, 4, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameMarginHeight",    17, 5, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },
    { "FrameMarginWidth",     16, 6, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },
    { "FrameName",             9, 7, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },
    { "FrameURL",              8, 8, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },
    {0,0,0,0,0,0}
};

SFX_IMPL_XSERVICEINFO( IFrameObject, "com.sun.star.embed.SpecialEmbeddedObject", "com.sun.star.comp.sfx2.IFrameObject" )
SFX_IMPL_SINGLEFACTORY( IFrameObject );

IFrameObject::IFrameObject( const uno::Reference < lang::XMultiServiceFactory >& rFact )
    : mxFact( rFact )
    , maPropSet( aIFramePropertyMap_Impl )
{
}

IFrameObject::~IFrameObject()
{
}

void SAL_CALL IFrameObject::initialize( const uno::Sequence< uno::Any >& aArguments ) throw ( uno::Exception, uno::RuntimeException )
{
    if ( aArguments.getLength() )
        aArguments[0] >>= mxObj;
}

sal_Bool SAL_CALL IFrameObject::load(
    const uno::Sequence < com::sun::star::beans::PropertyValue >& /*lDescriptor*/,
    const uno::Reference < frame::XFrame >& xFrame )
throw( uno::RuntimeException )
{
    if ( SvtMiscOptions().IsPluginsEnabled() )
    {
        DBG_ASSERT( !mxFrame.is(), "Frame already existing!" );
        Window* pParent = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
        IFrameWindow_Impl* pWin = new IFrameWindow_Impl( pParent, maFrmDescr.IsFrameBorderOn() );
        pWin->SetSizePixel( pParent->GetOutputSizePixel() );
        pWin->SetBackground();
        pWin->Show();

        uno::Reference < awt::XWindow > xWindow( pWin->GetComponentInterface(), uno::UNO_QUERY );
        xFrame->setComponent( xWindow, uno::Reference < frame::XController >() );

        // we must destroy the IFrame before the parent is destroyed
        xWindow->addEventListener( this );

        mxFrame = uno::Reference< frame::XFrame >( mxFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.frame.Frame" ) ),
                    uno::UNO_QUERY );
        uno::Reference < awt::XWindow > xWin( pWin->GetComponentInterface(), uno::UNO_QUERY );
        mxFrame->initialize( xWin );
        mxFrame->setName( maFrmDescr.GetName() );

        uno::Reference< frame::XDispatchProvider > xProv( mxFrame, uno::UNO_QUERY );

        util::URL aTargetURL;
        aTargetURL.Complete = ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );
        uno::Reference < util::XURLTransformer > xTrans( mxFact->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), uno::UNO_QUERY );
        xTrans->parseStrict( aTargetURL );

        uno::Sequence < beans::PropertyValue > aProps(2);
        aProps[0].Name = ::rtl::OUString::createFromAscii("PluginMode");
        aProps[0].Value <<= (sal_Int16) 2;
        aProps[1].Name = ::rtl::OUString::createFromAscii("ReadOnly");
        aProps[1].Value <<= (sal_Bool) sal_True;
        uno::Reference < frame::XDispatch > xDisp = xProv->queryDispatch( aTargetURL, ::rtl::OUString::createFromAscii("_self"), 0 );
        if ( xDisp.is() )
            xDisp->dispatch( aTargetURL, aProps );

        return TRUE;
    }

    return FALSE;
}

void SAL_CALL IFrameObject::cancel() throw( com::sun::star::uno::RuntimeException )
{
    try
    {
        uno::Reference < util::XCloseable > xClose( mxFrame, uno::UNO_QUERY );
        if ( xClose.is() )
            xClose->close( sal_True );
        mxFrame = 0;
    }
    catch ( uno::Exception& )
    {}
}

void SAL_CALL IFrameObject::close( sal_Bool /*bDeliverOwnership*/ ) throw( com::sun::star::util::CloseVetoException, com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::addCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::removeCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::disposing( const com::sun::star::lang::EventObject& ) throw (com::sun::star::uno::RuntimeException)
{
    cancel();
}

uno::Reference< beans::XPropertySetInfo > SAL_CALL IFrameObject::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException )
{
    return maPropSet.getPropertySetInfo();
}

void SAL_CALL IFrameObject::setPropertyValue(const ::rtl::OUString& aPropertyName, const uno::Any& aAny)
    throw ( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException)
{
    if ( aPropertyName.equalsAscii("FrameURL") )
    {
        ::rtl::OUString aURL;
        aAny >>= aURL;
        maFrmDescr.SetURL( String(aURL) );
    }
    else if ( aPropertyName.equalsAscii("FrameName") )
    {
        ::rtl::OUString aName;
        if ( aAny >>= aName )
            maFrmDescr.SetName( aName );
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoScroll") )
    {
        sal_Bool bIsAutoScroll = sal_Bool();
        if ( (aAny >>= bIsAutoScroll) && bIsAutoScroll )
            maFrmDescr.SetScrollingMode( ScrollingAuto );
    }
    else if ( aPropertyName.equalsAscii("FrameIsScrollingMode") )
    {
        sal_Bool bIsScroll = sal_Bool();
        if ( aAny >>= bIsScroll )
            maFrmDescr.SetScrollingMode( bIsScroll ? ScrollingYes : ScrollingNo );
    }
    else if ( aPropertyName.equalsAscii("FrameIsBorder") )
    {
        sal_Bool bIsBorder = sal_Bool();
        if ( aAny >>= bIsBorder )
            maFrmDescr.SetFrameBorder( bIsBorder );
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoBorder") )
    {
        sal_Bool bIsAutoBorder = sal_Bool();
        if ( (aAny >>= bIsAutoBorder) )
        {
            BOOL bBorder = maFrmDescr.IsFrameBorderOn();
            maFrmDescr.ResetBorder();
            if ( bIsAutoBorder )
                maFrmDescr.SetFrameBorder( bBorder );
        }
    }
    else if ( aPropertyName.equalsAscii("FrameMarginWidth") )
    {
        sal_Int32 nMargin = 0;
        Size aSize = maFrmDescr.GetMargin();
        if ( aAny >>= nMargin )
        {
            aSize.Width() = nMargin;
            maFrmDescr.SetMargin( aSize );
        }
    }
    else if ( aPropertyName.equalsAscii("FrameMarginHeight") )
    {
        sal_Int32 nMargin = 0;
        Size aSize = maFrmDescr.GetMargin();
        if ( aAny >>= nMargin )
        {
            aSize.Height() = nMargin;
            maFrmDescr.SetMargin( aSize );
        }
    }
    else
         throw beans::UnknownPropertyException();
}

uno::Any SAL_CALL IFrameObject::getPropertyValue(const ::rtl::OUString& aPropertyName)
        throw ( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)
{
    uno::Any aAny;
    if ( aPropertyName.equalsAscii("FrameURL") )
    {
        aAny <<= ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );
    }
    else if ( aPropertyName.equalsAscii("FrameName") )
    {
        aAny <<= ::rtl::OUString( maFrmDescr.GetName() );
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoScroll") )
    {
        sal_Bool bIsAutoScroll = ( maFrmDescr.GetScrollingMode() == ScrollingAuto );
        aAny <<= bIsAutoScroll;
    }
    else if ( aPropertyName.equalsAscii("FrameIsScrollingMode") )
    {
        sal_Bool bIsScroll = ( maFrmDescr.GetScrollingMode() == ScrollingYes );
        aAny <<= bIsScroll;
    }
    else if ( aPropertyName.equalsAscii("FrameIsBorder") )
    {
        sal_Bool bIsBorder = maFrmDescr.IsFrameBorderOn();
        aAny <<= bIsBorder;
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoBorder") )
    {
        sal_Bool bIsAutoBorder = !maFrmDescr.IsFrameBorderSet();
        aAny <<= bIsAutoBorder;
    }
    else if ( aPropertyName.equalsAscii("FrameMarginWidth") )
    {
        aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Width();
    }
    else if ( aPropertyName.equalsAscii("FrameMarginHeight") )
    {
        aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Height();
    }
    else
         throw beans::UnknownPropertyException();
    return aAny;
}

void SAL_CALL IFrameObject::addPropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::removePropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::addVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::removeVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

::sal_Int16 SAL_CALL IFrameObject::execute() throw (::com::sun::star::uno::RuntimeException)
{
    SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
    VclAbstractDialog* pDlg = pFact->CreateEditObjectDialog( NULL, SID_INSERT_FLOATINGFRAME, mxObj );
    if ( pDlg )
        pDlg->Execute();
    return 0;
}

void SAL_CALL IFrameObject::setTitle( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException)
{
}

}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.216); FILE MERGED 2008/04/01 12:40:48 thb 1.10.216.2: #i85898# Stripping all external header guards 2008/03/31 13:38:27 rt 1.10.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: iframe.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#include "iframe.hxx"
#include <sfx2/sfxdlg.hxx>
#include <sfx2/sfxsids.hrc>
#include <com/sun/star/frame/XDispatchProvider.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>

#include <tools/urlobj.hxx>
#include <tools/debug.hxx>
#include <rtl/ustring.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <svtools/miscopt.hxx>
#include <vcl/window.hxx>

using namespace ::com::sun::star;

namespace sfx2
{

class IFrameWindow_Impl : public Window
{
    uno::Reference < frame::XFrame > mxFrame;
    sal_Bool                bActive;
    sal_Bool                bBorder;

public:
    IFrameWindow_Impl( Window *pParent,
                       sal_Bool bHasBorder,
                       WinBits nWinBits = 0 );

public:
    void            SetBorder( sal_Bool bNewBorder = sal_True );
    sal_Bool        HasBorder() const { return bBorder; }
};

IFrameWindow_Impl::IFrameWindow_Impl( Window *pParent, sal_Bool bHasBorder, WinBits nWinBits )
    : Window( pParent, nWinBits | WB_CLIPCHILDREN | WB_NODIALOGCONTROL | WB_DOCKBORDER )
    , bActive(sal_False)
    , bBorder(bHasBorder)
{
    if ( !bHasBorder )
        SetBorderStyle( WINDOW_BORDER_NOBORDER );
    else
        SetBorderStyle( WINDOW_BORDER_NORMAL );
    //SetActivateMode( ACTIVATE_MODE_GRABFOCUS );
}

void IFrameWindow_Impl::SetBorder( sal_Bool bNewBorder )
{
    if ( bBorder != bNewBorder )
    {
        Size aSize = GetSizePixel();
        bBorder = bNewBorder;
        if ( bBorder )
            SetBorderStyle( WINDOW_BORDER_NORMAL );
        else
            SetBorderStyle( WINDOW_BORDER_NOBORDER );
        if ( GetSizePixel() != aSize )
            SetSizePixel( aSize );
    }
}

#define PROPERTY_UNBOUND 0

SfxItemPropertyMap aIFramePropertyMap_Impl[] =
{
    { "FrameIsAutoBorder",    17, 1, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameIsAutoScroll",    17, 2, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameIsBorder",        13, 3, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameIsScrollingMode", 20, 4, &::getBooleanCppuType(), PROPERTY_UNBOUND, 0 },
    { "FrameMarginHeight",    17, 5, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },
    { "FrameMarginWidth",     16, 6, &::getCppuType( (sal_Int32*)0 ), PROPERTY_UNBOUND, 0 },
    { "FrameName",             9, 7, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },
    { "FrameURL",              8, 8, &::getCppuType((const ::rtl::OUString*)0), PROPERTY_UNBOUND, 0 },
    {0,0,0,0,0,0}
};

SFX_IMPL_XSERVICEINFO( IFrameObject, "com.sun.star.embed.SpecialEmbeddedObject", "com.sun.star.comp.sfx2.IFrameObject" )
SFX_IMPL_SINGLEFACTORY( IFrameObject );

IFrameObject::IFrameObject( const uno::Reference < lang::XMultiServiceFactory >& rFact )
    : mxFact( rFact )
    , maPropSet( aIFramePropertyMap_Impl )
{
}

IFrameObject::~IFrameObject()
{
}

void SAL_CALL IFrameObject::initialize( const uno::Sequence< uno::Any >& aArguments ) throw ( uno::Exception, uno::RuntimeException )
{
    if ( aArguments.getLength() )
        aArguments[0] >>= mxObj;
}

sal_Bool SAL_CALL IFrameObject::load(
    const uno::Sequence < com::sun::star::beans::PropertyValue >& /*lDescriptor*/,
    const uno::Reference < frame::XFrame >& xFrame )
throw( uno::RuntimeException )
{
    if ( SvtMiscOptions().IsPluginsEnabled() )
    {
        DBG_ASSERT( !mxFrame.is(), "Frame already existing!" );
        Window* pParent = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
        IFrameWindow_Impl* pWin = new IFrameWindow_Impl( pParent, maFrmDescr.IsFrameBorderOn() );
        pWin->SetSizePixel( pParent->GetOutputSizePixel() );
        pWin->SetBackground();
        pWin->Show();

        uno::Reference < awt::XWindow > xWindow( pWin->GetComponentInterface(), uno::UNO_QUERY );
        xFrame->setComponent( xWindow, uno::Reference < frame::XController >() );

        // we must destroy the IFrame before the parent is destroyed
        xWindow->addEventListener( this );

        mxFrame = uno::Reference< frame::XFrame >( mxFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.frame.Frame" ) ),
                    uno::UNO_QUERY );
        uno::Reference < awt::XWindow > xWin( pWin->GetComponentInterface(), uno::UNO_QUERY );
        mxFrame->initialize( xWin );
        mxFrame->setName( maFrmDescr.GetName() );

        uno::Reference< frame::XDispatchProvider > xProv( mxFrame, uno::UNO_QUERY );

        util::URL aTargetURL;
        aTargetURL.Complete = ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );
        uno::Reference < util::XURLTransformer > xTrans( mxFact->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), uno::UNO_QUERY );
        xTrans->parseStrict( aTargetURL );

        uno::Sequence < beans::PropertyValue > aProps(2);
        aProps[0].Name = ::rtl::OUString::createFromAscii("PluginMode");
        aProps[0].Value <<= (sal_Int16) 2;
        aProps[1].Name = ::rtl::OUString::createFromAscii("ReadOnly");
        aProps[1].Value <<= (sal_Bool) sal_True;
        uno::Reference < frame::XDispatch > xDisp = xProv->queryDispatch( aTargetURL, ::rtl::OUString::createFromAscii("_self"), 0 );
        if ( xDisp.is() )
            xDisp->dispatch( aTargetURL, aProps );

        return TRUE;
    }

    return FALSE;
}

void SAL_CALL IFrameObject::cancel() throw( com::sun::star::uno::RuntimeException )
{
    try
    {
        uno::Reference < util::XCloseable > xClose( mxFrame, uno::UNO_QUERY );
        if ( xClose.is() )
            xClose->close( sal_True );
        mxFrame = 0;
    }
    catch ( uno::Exception& )
    {}
}

void SAL_CALL IFrameObject::close( sal_Bool /*bDeliverOwnership*/ ) throw( com::sun::star::util::CloseVetoException, com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::addCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::removeCloseListener( const com::sun::star::uno::Reference < com::sun::star::util::XCloseListener >& ) throw( com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::disposing( const com::sun::star::lang::EventObject& ) throw (com::sun::star::uno::RuntimeException)
{
    cancel();
}

uno::Reference< beans::XPropertySetInfo > SAL_CALL IFrameObject::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException )
{
    return maPropSet.getPropertySetInfo();
}

void SAL_CALL IFrameObject::setPropertyValue(const ::rtl::OUString& aPropertyName, const uno::Any& aAny)
    throw ( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException)
{
    if ( aPropertyName.equalsAscii("FrameURL") )
    {
        ::rtl::OUString aURL;
        aAny >>= aURL;
        maFrmDescr.SetURL( String(aURL) );
    }
    else if ( aPropertyName.equalsAscii("FrameName") )
    {
        ::rtl::OUString aName;
        if ( aAny >>= aName )
            maFrmDescr.SetName( aName );
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoScroll") )
    {
        sal_Bool bIsAutoScroll = sal_Bool();
        if ( (aAny >>= bIsAutoScroll) && bIsAutoScroll )
            maFrmDescr.SetScrollingMode( ScrollingAuto );
    }
    else if ( aPropertyName.equalsAscii("FrameIsScrollingMode") )
    {
        sal_Bool bIsScroll = sal_Bool();
        if ( aAny >>= bIsScroll )
            maFrmDescr.SetScrollingMode( bIsScroll ? ScrollingYes : ScrollingNo );
    }
    else if ( aPropertyName.equalsAscii("FrameIsBorder") )
    {
        sal_Bool bIsBorder = sal_Bool();
        if ( aAny >>= bIsBorder )
            maFrmDescr.SetFrameBorder( bIsBorder );
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoBorder") )
    {
        sal_Bool bIsAutoBorder = sal_Bool();
        if ( (aAny >>= bIsAutoBorder) )
        {
            BOOL bBorder = maFrmDescr.IsFrameBorderOn();
            maFrmDescr.ResetBorder();
            if ( bIsAutoBorder )
                maFrmDescr.SetFrameBorder( bBorder );
        }
    }
    else if ( aPropertyName.equalsAscii("FrameMarginWidth") )
    {
        sal_Int32 nMargin = 0;
        Size aSize = maFrmDescr.GetMargin();
        if ( aAny >>= nMargin )
        {
            aSize.Width() = nMargin;
            maFrmDescr.SetMargin( aSize );
        }
    }
    else if ( aPropertyName.equalsAscii("FrameMarginHeight") )
    {
        sal_Int32 nMargin = 0;
        Size aSize = maFrmDescr.GetMargin();
        if ( aAny >>= nMargin )
        {
            aSize.Height() = nMargin;
            maFrmDescr.SetMargin( aSize );
        }
    }
    else
         throw beans::UnknownPropertyException();
}

uno::Any SAL_CALL IFrameObject::getPropertyValue(const ::rtl::OUString& aPropertyName)
        throw ( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException)
{
    uno::Any aAny;
    if ( aPropertyName.equalsAscii("FrameURL") )
    {
        aAny <<= ::rtl::OUString( maFrmDescr.GetURL().GetMainURL( INetURLObject::NO_DECODE ) );
    }
    else if ( aPropertyName.equalsAscii("FrameName") )
    {
        aAny <<= ::rtl::OUString( maFrmDescr.GetName() );
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoScroll") )
    {
        sal_Bool bIsAutoScroll = ( maFrmDescr.GetScrollingMode() == ScrollingAuto );
        aAny <<= bIsAutoScroll;
    }
    else if ( aPropertyName.equalsAscii("FrameIsScrollingMode") )
    {
        sal_Bool bIsScroll = ( maFrmDescr.GetScrollingMode() == ScrollingYes );
        aAny <<= bIsScroll;
    }
    else if ( aPropertyName.equalsAscii("FrameIsBorder") )
    {
        sal_Bool bIsBorder = maFrmDescr.IsFrameBorderOn();
        aAny <<= bIsBorder;
    }
    else if ( aPropertyName.equalsAscii("FrameIsAutoBorder") )
    {
        sal_Bool bIsAutoBorder = !maFrmDescr.IsFrameBorderSet();
        aAny <<= bIsAutoBorder;
    }
    else if ( aPropertyName.equalsAscii("FrameMarginWidth") )
    {
        aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Width();
    }
    else if ( aPropertyName.equalsAscii("FrameMarginHeight") )
    {
        aAny <<= (sal_Int32 ) maFrmDescr.GetMargin().Height();
    }
    else
         throw beans::UnknownPropertyException();
    return aAny;
}

void SAL_CALL IFrameObject::addPropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::removePropertyChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::addVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

void SAL_CALL IFrameObject::removeVetoableChangeListener(const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener > & ) throw( ::com::sun::star::uno::RuntimeException )
{
}

::sal_Int16 SAL_CALL IFrameObject::execute() throw (::com::sun::star::uno::RuntimeException)
{
    SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
    VclAbstractDialog* pDlg = pFact->CreateEditObjectDialog( NULL, SID_INSERT_FLOATINGFRAME, mxObj );
    if ( pDlg )
        pDlg->Execute();
    return 0;
}

void SAL_CALL IFrameObject::setTitle( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException)
{
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: appbas.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 12:41:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SFX_APPBAS_HXX
#define _SFX_APPBAS_HXX

#ifndef _SBXDEF_HXX //autogen
#include <basic/sbxdef.hxx>
#endif

class StarBASIC;
class SbxObject;

//=========================================================================

SbxVariable* MakeVariable( StarBASIC *pBas, SbxObject *pObject,
                   const char *pName, ULONG nSID, SbxDataType eType=SbxOBJECT,
                   SbxClassType = SbxCLASS_PROPERTY );

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.132); FILE MERGED 2005/09/06 13:05:21 rt 1.2.132.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appbas.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:54:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFX_APPBAS_HXX
#define _SFX_APPBAS_HXX

#ifndef _SBXDEF_HXX //autogen
#include <basic/sbxdef.hxx>
#endif

class StarBASIC;
class SbxObject;

//=========================================================================

SbxVariable* MakeVariable( StarBASIC *pBas, SbxObject *pObject,
                   const char *pName, ULONG nSID, SbxDataType eType=SbxOBJECT,
                   SbxClassType = SbxCLASS_PROPERTY );

#endif

<|endoftext|>


<commit_before>#include <stdio.h>
#include <float.h>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

#include "raytracing.h"

//temporary variables
//these are only used to illustrate
//a simple debug drawing. A ray
Vec3Df testRayOrigin;
Vec3Df testRayDestination;
Vec3Df testColor;

//use this function for any preprocessing of the mesh.
void init()
{
	//load the mesh file
	//please realize that not all OBJ files will successfully load.
	//Nonetheless, if they come from Blender, they should, if they
	//are exported as WavefrontOBJ.
	//PLEASE ADAPT THE LINE BELOW TO THE FULL PATH OF THE dodgeColorTest.obj
	//model, e.g., "C:/temp/myData/GraphicsIsFun/dodgeColorTest.obj",
	//otherwise the application will not load properly

	MyMesh.loadMesh(FILE_LOCATION, true);
	MyMesh.computeVertexNormals();

	//one first move: initialize the first light source
	//at least ONE light source has to be in the scene!!!
	//here, we set it to the current location of the camera
	MyLightPositions.push_back(MyCameraPosition);
}

//return the color of your pixel.
Vec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)
{
	int level = 0;
	return trace(origin, dest, level);

	//  if(intersect(level, ray, max, &hit)) {
	//    Shade(level, hit, &color);
	//  }
	//  else
	//    color=BackgroundColor

	//return Vec3Df(dest[0],dest[1],dest[2]);
}

Vec3Df trace(const Vec3Df & origin, const Vec3Df & dir, int level){
	float depth = FLT_MAX;
	Vec3Df color = Vec3Df(0, 0, 0);
	for (int i = 0; i < MyMesh.triangles.size(); i++){
		Triangle triangle = MyMesh.triangles.at(i);
		Vertex v0 = MyMesh.vertices.at(triangle.v[0]);
		Vertex v1 = MyMesh.vertices.at(triangle.v[1]);
		Vertex v2 = MyMesh.vertices.at(triangle.v[2]);

		Vec3Df N = Vec3Df(0, 0, 0);
		Vec3Df intersection = rayTriangleIntersect(origin, dir, v0.p, v1.p, v2.p, depth, N);
		if (!isNulVector(intersection)){
			// save color and depth
			color = shade(dir, intersection, level, i, N);
		}

	}
	return color;
}

Vec3Df shade(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex, const Vec3Df N){
	Vec3Df color = Vec3Df(0, 0, 0);
	Vec3Df lightDirection = Vec3Df(0, 0, 0);
	//lightDirection = lightVector(intersection, origin);
	color += diffuse(dir, N, triangleIndex);
	color += ambient(dir, intersection, level, triangleIndex);
	color += speculair(dir, intersection, level, triangleIndex);
	return color;
}

Vec3Df diffuse(const Vec3Df lightSource, const Vec3Df normal, int triangleIndex){
	Vec3Df color = Vec3Df(0, 0, 0);
	unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
	color = MyMesh.materials.at(triMat).Kd();

	// diffuser = Kd * dot(lightsource, normal) * Od * Ld
	// Od = object color
	// Ld = lightSource color
	//Vec3Df diffuser = color * (Vec3Df::dotProduct(lightSource, normal)) / pow(normal.getLength(), 2) * 1 * 1;
	return color;
}

Vec3Df ambient(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
	Vec3Df color = Vec3Df(0, 0, 0);
	unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
	color = MyMesh.materials.at(triMat).Ka();
	return color;
}

Vec3Df speculair(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
	Vec3Df color = Vec3Df(0, 0, 0);
	unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
	color = MyMesh.materials.at(triMat).Ks();
	return color;
}

Vec3Df lightVector(const Vec3Df point, const Vec3Df lightPoint){
	Vec3Df lightDir = Vec3Df(0, 0, 0);
	lightDir = lightPoint - point;
	return lightDir;
}

Vec3Df reflectionVector(const Vec3Df lightDirection, const Vec3Df normalVector) {
	Vec3Df reflection = Vec3Df(0, 0, 0);
	reflection = lightDirection - 2 * (Vec3Df::dotProduct(lightDirection, normalVector) / pow(normalVector.getLength(), 2))*normalVector;
	return reflection;
}
// We can also add textures!

// The source of this function is:
// http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution
// Returns the point of intersection
Vec3Df rayTriangleIntersect(const Vec3Df &orig, const Vec3Df &dir, const Vec3Df v0, const Vec3Df v1, const Vec3Df v2, float &depth, Vec3Df &N)
{
	Vec3Df nulVector = Vec3Df(0, 0, 0);
	// compute plane's normal
	Vec3Df v0v1 = v1 - v0;
	Vec3Df v0v2 = v2 - v0;
	// no need to normalize
	N = Vec3Df::crossProduct(v0v1, v0v2); // N

	// Step 1: finding P (the point where the ray intersects the plane)

	// check if ray and plane are parallel ?
	float NdotRayDirection = Vec3Df::dotProduct(N, dir);
	if (fabs(NdotRayDirection) < 0.000000001) // almost 0
		return nulVector; // they are parallel so they don't intersect !

	// compute d parameter using equation 2 (d is the distance from the origin (0, 0, 0) to the plane)
	float d = Vec3Df::dotProduct(N, v0);

	// compute t (equation 3) (t is distance from the ray origin to P)
	float t = (-Vec3Df::dotProduct(N, orig) + d) / NdotRayDirection;
	// check if the triangle is in behind the ray
	if (t < 0) return nulVector; // the triangle is behind
	if (t > depth) return nulVector; // already have something closerby

	// compute the intersection point P using equation 1
	Vec3Df P = orig + t * dir;

	// Step 2: inside-outside test
	Vec3Df C; // vector perpendicular to triangle's plane

	// edge 0
	Vec3Df edge0 = v1 - v0;
	Vec3Df vp0 = P - v0;
	C = Vec3Df::crossProduct(edge0, vp0);
	if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side

	// edge 1
	Vec3Df edge1 = v2 - v1;
	Vec3Df vp1 = P - v1;
	C = Vec3Df::crossProduct(edge1, vp1);
	if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side

	// edge 2
	Vec3Df edge2 = v0 - v2;
	Vec3Df vp2 = P - v2;
	C = Vec3Df::crossProduct(edge2, vp2);
	if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side;

	depth = t;
	return P; // this is the intersectionpoint
}

//Shade(level, hit, &color){
//  for each lightsource
//    ComputeDirectLight(hit, &directColor);
//  if(material reflects && (level < maxLevel))
//    computeReflectedRay(hit, &reflectedray);
//    Trace(level+1, reflectedRay, &reflectedColor);
//  color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}

void yourDebugDraw()
{
	//draw open gl debug stuff
	//this function is called every frame

	//let's draw the mesh
	MyMesh.draw();

	//let's draw the lights in the scene as points
	glPushAttrib(GL_ALL_ATTRIB_BITS); //store all GL attributes
	glDisable(GL_LIGHTING);
	glColor3f(1, 1, 1);
	glPointSize(10);
	glBegin(GL_POINTS);
	for (int i = 0; i<MyLightPositions.size(); ++i)
		glVertex3fv(MyLightPositions[i].pointer());
	glEnd();
	glPopAttrib();//restore all GL attributes
	//The Attrib commands maintain the state.
	//e.g., even though inside the two calls, we set
	//the color to white, it will be reset to the previous
	//state after the pop.

	//as an example: we draw the test ray, which is set by the keyboard function
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glDisable(GL_LIGHTING);
	glBegin(GL_LINES);
	glColor3f(testColor[0], testColor[1], testColor[2]);
	glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);
	glColor3f(testColor[0], testColor[1], testColor[2]);
	glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]);
	glEnd();
	glPointSize(10);
	glBegin(GL_POINTS);
	glVertex3fv(MyLightPositions[0].pointer());
	glEnd();
	glPopAttrib();

	//draw whatever else you want...
	////glutSolidSphere(1,10,10);
	////allows you to draw a sphere at the origin.
	////using a glTranslate, it can be shifted to whereever you want
	////if you produce a sphere renderer, this
	////triangulated sphere is nice for the preview
}

//yourKeyboardFunc is used to deal with keyboard input.
//t is the character that was pressed
//x,y is the mouse position in pixels
//rayOrigin, rayDestination is the ray that is going in the view direction UNDERNEATH your mouse position.
//
//A few keys are already reserved:
//'L' adds a light positioned at the camera location to the MyLightPositions vector
//'l' modifies the last added light to the current
//    camera position (by default, there is only one light, so move it with l)
//    ATTENTION These lights do NOT affect the real-time rendering.
//    You should use them for the raytracing.
//'r' calls the function performRaytracing on EVERY pixel, using the correct associated ray.
//    It then stores the result in an image "result.ppm".
//    Initially, this function is fast (performRaytracing simply returns
//    the target of the ray - see the code above), but once you replaced
//    this function and raytracing is in place, it might take a
//    while to complete...
void yourKeyboardFunc(char t, int x, int y, const Vec3Df & rayOrigin, const Vec3Df & rayDestination)
{

	//here, as an example, I use the ray to fill in the values for my upper global ray variable
	//I use these variables in the debugDraw function to draw the corresponding ray.
	//try it: Press a key, move the camera, see the ray that was launched as a line.
	testRayOrigin = rayOrigin;
	testRayDestination = rayDestination;
	testColor = performRayTracing(rayOrigin, rayDestination);

	std::cout << " The color from the ray is " << testColor[0] << "," << testColor[1] << "," << testColor[2] << std::endl;
	// do here, whatever you want with the keyboard input t.

	//      Trace(0, ray, &color);
	//      PutPixel(x, y, color);

	std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl;
}

bool isNulVector(Vec3Df vector){
	Vec3Df nullVector = Vec3Df(0, 0, 0);
	return vector == nullVector;
}

// Pseudocode From slides

//RayTrace (view)
//{
//  for (y=0; y<view.yres; ++y){
//    for(x=0; x<view.xres; ++x){
//      ComputeRay(x, y, view, &ray);
//      Trace(0, ray, &color);
//      PutPixel(x, y, color);
//    }
//  }
//}
//
//Trace( level, ray, &color){
//  if(intersect(level, ray, max, &hit)) {
//    Shade(level, hit, &color);
//  }
//  else
//    color=BackgroundColor
//}
//
//Shade(level, hit, &color){
//  for each lightsource
//    ComputeDirectLight(hit, &directColor);
//  if(material reflects && (level < maxLevel))
//    computeReflectedRay(hit, &reflectedray);
//    Trace(level+1, reflectedRay, &reflectedColor);
//  color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}
<commit_msg>diffusing small change<commit_after>#include <stdio.h>
#include <float.h>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

#include "raytracing.h"

//temporary variables
//these are only used to illustrate
//a simple debug drawing. A ray
Vec3Df testRayOrigin;
Vec3Df testRayDestination;
Vec3Df testColor;

//use this function for any preprocessing of the mesh.
void init()
{
	//load the mesh file
	//please realize that not all OBJ files will successfully load.
	//Nonetheless, if they come from Blender, they should, if they
	//are exported as WavefrontOBJ.
	//PLEASE ADAPT THE LINE BELOW TO THE FULL PATH OF THE dodgeColorTest.obj
	//model, e.g., "C:/temp/myData/GraphicsIsFun/dodgeColorTest.obj",
	//otherwise the application will not load properly

	MyMesh.loadMesh(FILE_LOCATION, true);
	MyMesh.computeVertexNormals();

	//one first move: initialize the first light source
	//at least ONE light source has to be in the scene!!!
	//here, we set it to the current location of the camera
	MyLightPositions.push_back(MyCameraPosition);
}

//return the color of your pixel.
Vec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)
{
	int level = 0;
	return trace(origin, dest, level);

	//  if(intersect(level, ray, max, &hit)) {
	//    Shade(level, hit, &color);
	//  }
	//  else
	//    color=BackgroundColor

	//return Vec3Df(dest[0],dest[1],dest[2]);
}

Vec3Df trace(const Vec3Df & origin, const Vec3Df & dir, int level){
	float depth = FLT_MAX;
	Vec3Df color = Vec3Df(0, 0, 0);
	for (int i = 0; i < MyMesh.triangles.size(); i++){
		Triangle triangle = MyMesh.triangles.at(i);
		Vertex v0 = MyMesh.vertices.at(triangle.v[0]);
		Vertex v1 = MyMesh.vertices.at(triangle.v[1]);
		Vertex v2 = MyMesh.vertices.at(triangle.v[2]);

		Vec3Df N = Vec3Df(0, 0, 0);
		Vec3Df intersection = rayTriangleIntersect(origin, dir, v0.p, v1.p, v2.p, depth, N);
		if (!isNulVector(intersection)){
			// save color and depth
			color = shade(dir, intersection, level, i, N);
		}

	}
	return color;
}

Vec3Df shade(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex, const Vec3Df N){
	Vec3Df color = Vec3Df(0, 0, 0);
	Vec3Df lightDirection = Vec3Df(0, 0, 0);
	lightDirection = lightVector(intersection, dir);
	color += diffuse(intersection, N, triangleIndex);
	color += ambient(dir, intersection, level, triangleIndex);
	color += speculair(dir, intersection, level, triangleIndex);
	return color;
}

Vec3Df diffuse(const Vec3Df lightSource, const Vec3Df normal, int triangleIndex){
	Vec3Df color = Vec3Df(0, 0, 0);
	unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
	color = MyMesh.materials.at(triMat).Kd();

	// diffuser = Kd * dot(lightsource, normal) * Od * Ld
	// Od = object color
	// Ld = lightSource color
	Vec3Df diffuser = color * (Vec3Df::dotProduct(lightSource, normal)) / pow(normal.getLength(), 2) * 1 * 1;
	return diffuser;
}

Vec3Df ambient(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
	Vec3Df color = Vec3Df(0, 0, 0);
	unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
	color = MyMesh.materials.at(triMat).Ka();
	return color;
}

Vec3Df speculair(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
	Vec3Df color = Vec3Df(0, 0, 0);
	unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
	color = MyMesh.materials.at(triMat).Ks();
	return color;
}

Vec3Df lightVector(const Vec3Df point, const Vec3Df lightPoint){
	Vec3Df lightDir = Vec3Df(0, 0, 0);
	lightDir = point - lightPoint;
	return lightDir;
}

Vec3Df reflectionVector(const Vec3Df lightDirection, const Vec3Df normalVector) {
	Vec3Df reflection = Vec3Df(0, 0, 0);
	reflection = lightDirection - 2 * (Vec3Df::dotProduct(lightDirection, normalVector) / pow(normalVector.getLength(), 2))*normalVector;
	return reflection;
}
// We can also add textures!

// The source of this function is:
// http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution
// Returns the point of intersection
Vec3Df rayTriangleIntersect(const Vec3Df &orig, const Vec3Df &dir, const Vec3Df v0, const Vec3Df v1, const Vec3Df v2, float &depth, Vec3Df &N)
{
	Vec3Df nulVector = Vec3Df(0, 0, 0);
	// compute plane's normal
	Vec3Df v0v1 = v1 - v0;
	Vec3Df v0v2 = v2 - v0;
	// no need to normalize
	N = Vec3Df::crossProduct(v0v1, v0v2); // N

	// Step 1: finding P (the point where the ray intersects the plane)

	// check if ray and plane are parallel ?
	float NdotRayDirection = Vec3Df::dotProduct(N, dir);
	if (fabs(NdotRayDirection) < 0.000000001) // almost 0
		return nulVector; // they are parallel so they don't intersect !

	// compute d parameter using equation 2 (d is the distance from the origin (0, 0, 0) to the plane)
	float d = Vec3Df::dotProduct(N, v0);

	// compute t (equation 3) (t is distance from the ray origin to P)
	float t = (-Vec3Df::dotProduct(N, orig) + d) / NdotRayDirection;
	// check if the triangle is in behind the ray
	if (t < 0) return nulVector; // the triangle is behind
	if (t > depth) return nulVector; // already have something closerby

	// compute the intersection point P using equation 1
	Vec3Df P = orig + t * dir;

	// Step 2: inside-outside test
	Vec3Df C; // vector perpendicular to triangle's plane

	// edge 0
	Vec3Df edge0 = v1 - v0;
	Vec3Df vp0 = P - v0;
	C = Vec3Df::crossProduct(edge0, vp0);
	if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side

	// edge 1
	Vec3Df edge1 = v2 - v1;
	Vec3Df vp1 = P - v1;
	C = Vec3Df::crossProduct(edge1, vp1);
	if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side

	// edge 2
	Vec3Df edge2 = v0 - v2;
	Vec3Df vp2 = P - v2;
	C = Vec3Df::crossProduct(edge2, vp2);
	if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side;

	depth = t;
	return P; // this is the intersectionpoint
}

//Shade(level, hit, &color){
//  for each lightsource
//    ComputeDirectLight(hit, &directColor);
//  if(material reflects && (level < maxLevel))
//    computeReflectedRay(hit, &reflectedray);
//    Trace(level+1, reflectedRay, &reflectedColor);
//  color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}

void yourDebugDraw()
{
	//draw open gl debug stuff
	//this function is called every frame

	//let's draw the mesh
	MyMesh.draw();

	//let's draw the lights in the scene as points
	glPushAttrib(GL_ALL_ATTRIB_BITS); //store all GL attributes
	glDisable(GL_LIGHTING);
	glColor3f(1, 1, 1);
	glPointSize(10);
	glBegin(GL_POINTS);
	for (int i = 0; i<MyLightPositions.size(); ++i)
		glVertex3fv(MyLightPositions[i].pointer());
	glEnd();
	glPopAttrib();//restore all GL attributes
	//The Attrib commands maintain the state.
	//e.g., even though inside the two calls, we set
	//the color to white, it will be reset to the previous
	//state after the pop.

	//as an example: we draw the test ray, which is set by the keyboard function
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glDisable(GL_LIGHTING);
	glBegin(GL_LINES);
	glColor3f(testColor[0], testColor[1], testColor[2]);
	glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);
	glColor3f(testColor[0], testColor[1], testColor[2]);
	glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]);
	glEnd();
	glPointSize(10);
	glBegin(GL_POINTS);
	glVertex3fv(MyLightPositions[0].pointer());
	glEnd();
	glPopAttrib();

	//draw whatever else you want...
	////glutSolidSphere(1,10,10);
	////allows you to draw a sphere at the origin.
	////using a glTranslate, it can be shifted to whereever you want
	////if you produce a sphere renderer, this
	////triangulated sphere is nice for the preview
}

//yourKeyboardFunc is used to deal with keyboard input.
//t is the character that was pressed
//x,y is the mouse position in pixels
//rayOrigin, rayDestination is the ray that is going in the view direction UNDERNEATH your mouse position.
//
//A few keys are already reserved:
//'L' adds a light positioned at the camera location to the MyLightPositions vector
//'l' modifies the last added light to the current
//    camera position (by default, there is only one light, so move it with l)
//    ATTENTION These lights do NOT affect the real-time rendering.
//    You should use them for the raytracing.
//'r' calls the function performRaytracing on EVERY pixel, using the correct associated ray.
//    It then stores the result in an image "result.ppm".
//    Initially, this function is fast (performRaytracing simply returns
//    the target of the ray - see the code above), but once you replaced
//    this function and raytracing is in place, it might take a
//    while to complete...
void yourKeyboardFunc(char t, int x, int y, const Vec3Df & rayOrigin, const Vec3Df & rayDestination)
{

	//here, as an example, I use the ray to fill in the values for my upper global ray variable
	//I use these variables in the debugDraw function to draw the corresponding ray.
	//try it: Press a key, move the camera, see the ray that was launched as a line.
	testRayOrigin = rayOrigin;
	testRayDestination = rayDestination;
	testColor = performRayTracing(rayOrigin, rayDestination);

	std::cout << " The color from the ray is " << testColor[0] << "," << testColor[1] << "," << testColor[2] << std::endl;
	// do here, whatever you want with the keyboard input t.

	//      Trace(0, ray, &color);
	//      PutPixel(x, y, color);

	std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl;
}

bool isNulVector(Vec3Df vector){
	Vec3Df nullVector = Vec3Df(0, 0, 0);
	return vector == nullVector;
}

// Pseudocode From slides

//RayTrace (view)
//{
//  for (y=0; y<view.yres; ++y){
//    for(x=0; x<view.xres; ++x){
//      ComputeRay(x, y, view, &ray);
//      Trace(0, ray, &color);
//      PutPixel(x, y, color);
//    }
//  }
//}
//
//Trace( level, ray, &color){
//  if(intersect(level, ray, max, &hit)) {
//    Shade(level, hit, &color);
//  }
//  else
//    color=BackgroundColor
//}
//
//Shade(level, hit, &color){
//  for each lightsource
//    ComputeDirectLight(hit, &directColor);
//  if(material reflects && (level < maxLevel))
//    computeReflectedRay(hit, &reflectedray);
//    Trace(level+1, reflectedRay, &reflectedColor);
//  color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}
<|endoftext|>


<commit_before>#include "socket_wrap.h"

static Nan::Persistent<FunctionTemplate> socket_constructor;

SocketWrap::SocketWrap () {
  on_end = NULL;
  on_data = NULL;
  on_close = NULL;
  on_drain = NULL;
  on_error = NULL;
  on_connect = NULL;

  needs_drain = 0;

  write_buffer = (struct utp_iovec *) malloc(16 * sizeof(struct utp_iovec));
  write_buffer_length = 16;
  write_buffer_used = 0;
  write_buffer_offset = 0;
}

SocketWrap::~SocketWrap () {
  if (on_end) delete on_end;
  if (on_data) delete on_data;
  if (on_close) delete on_close;
  if (on_drain) delete on_drain;
  if (on_error) delete on_error;
  if (on_connect) delete on_connect;
  free(write_buffer);
}

int
SocketWrap::Drain () {
  Nan::HandleScope scope;

  if (!this->write_buffer_used) return 0;

  int needs_drain = this->needs_drain;
  this->needs_drain = 0;

  int wrote = utp_uv_socket_writev(this->handle, this->socket, this->write_buffer, this->write_buffer_used);
  if (wrote < 0) return -1;

  size_t wrote_bytes = (size_t) wrote;
  struct utp_iovec *next = this->write_buffer + this->write_buffer_offset;

  while (wrote_bytes && this->write_buffer_used) {
    if (wrote_bytes >= next->iov_len) {
      wrote_bytes -= next->iov_len;
      this->write_buffer_offset++;
      next++;
    } else {
      char *base = (char *) next->iov_base;
      base += wrote_bytes;
      next->iov_base = base;
      next->iov_len -= wrote_bytes;
      wrote_bytes = 0;
    }
  }

  if (this->write_buffer_used == this->write_buffer_offset) {
    this->write_buffer_used = 0;
    this->write_buffer_offset = 0;
    if (needs_drain && this->on_drain) this->on_drain->Call(0, NULL);
  } else {
    this->needs_drain = 1;
  }

  return 0;
}

int
SocketWrap::EnsureBuffer (int inc) {
  while (this->write_buffer_used + inc >= this->write_buffer_length) {
    size_t double_size = 2 * this->write_buffer_length * sizeof(struct utp_iovec);
    struct utp_iovec *bigger = (struct utp_iovec *) realloc(this->write_buffer, double_size);
    if (bigger == NULL) return 1;
    this->write_buffer_length *= 2;
    this->write_buffer = bigger;
  }
  return 0;
}

NAN_METHOD(SocketWrap::New) {
  SocketWrap* obj = new SocketWrap();
  obj->Wrap(info.This());
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(SocketWrap::Write) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());

  if (self->EnsureBuffer(1)) {
    Nan::ThrowError("Could not grow write buffer");
    return;
  }

  struct utp_iovec *holder = self->write_buffer + (self->write_buffer_used++);

  Local<Value> buffer = info[0]->ToObject();
  holder->iov_len = node::Buffer::Length(buffer);
  holder->iov_base = node::Buffer::Data(buffer);

  if (self->Drain()) {
    Nan::ThrowError("Write failed");
    return;
  }

  if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());
  else info.GetReturnValue().Set(Nan::False());
}

NAN_METHOD(SocketWrap::Writev) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());

  Local<Array> writes = info[0].As<Array>();
  Local<Value> chunk = Nan::New<String>("chunk").ToLocalChecked();
  uint32_t length = writes->Length();

  if (self->EnsureBuffer((int) length)) {
    Nan::ThrowError("Could not grow write buffer");
    return;
  }

  struct utp_iovec *next = self->write_buffer + self->write_buffer_used;

  for (uint32_t i = 0; i < length; i++) {
    Local<Value> buffer = Nan::Get(writes->Get(i)->ToObject(), chunk).ToLocalChecked();

    next->iov_len = node::Buffer::Length(buffer);
    next->iov_base = node::Buffer::Data(buffer);

    next++;
    self->write_buffer_used++;
  }

  if (self->Drain()) {
    Nan::ThrowError("Write failed");
    return;
  }

  if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());
  else info.GetReturnValue().Set(Nan::False());
}

NAN_METHOD(SocketWrap::End) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  utp_uv_socket_end(self->handle, self->socket);
}

NAN_METHOD(SocketWrap::OnData) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_data = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnEnd) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_end = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnClose) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_close = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnDrain) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_drain = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnError) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_error = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnConnect) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_connect = new Nan::Callback(info[0].As<Function>());
}

void SocketWrap::Init () {
  Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(SocketWrap::New);
  socket_constructor.Reset(tpl);
  tpl->SetClassName(Nan::New("SocketWrap").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Nan::SetPrototypeMethod(tpl, "write", SocketWrap::Write);
  Nan::SetPrototypeMethod(tpl, "writev", SocketWrap::Writev);
  Nan::SetPrototypeMethod(tpl, "end", SocketWrap::End);
  Nan::SetPrototypeMethod(tpl, "ondata", SocketWrap::OnData);
  Nan::SetPrototypeMethod(tpl, "onend", SocketWrap::OnEnd);
  Nan::SetPrototypeMethod(tpl, "onclose", SocketWrap::OnClose);
  Nan::SetPrototypeMethod(tpl, "ondrain", SocketWrap::OnDrain);
  Nan::SetPrototypeMethod(tpl, "onerror", SocketWrap::OnError);
  Nan::SetPrototypeMethod(tpl, "onconnect", SocketWrap::OnConnect);
}

Local<Value> SocketWrap::NewInstance () {
  Nan::EscapableHandleScope scope;

  Local<Object> instance;

  Local<FunctionTemplate> constructorHandle = Nan::New<FunctionTemplate>(socket_constructor);
  instance = constructorHandle->GetFunction()->NewInstance(0, NULL);

  return scope.Escape(instance);
}
<commit_msg>fix some drain bugs<commit_after>#include "socket_wrap.h"

static Nan::Persistent<FunctionTemplate> socket_constructor;

SocketWrap::SocketWrap () {
  on_end = NULL;
  on_data = NULL;
  on_close = NULL;
  on_drain = NULL;
  on_error = NULL;
  on_connect = NULL;

  needs_drain = 0;

  write_buffer = (struct utp_iovec *) malloc(16 * sizeof(struct utp_iovec));
  write_buffer_length = 16;
  write_buffer_used = 0;
  write_buffer_offset = 0;
}

SocketWrap::~SocketWrap () {
  if (on_end) delete on_end;
  if (on_data) delete on_data;
  if (on_close) delete on_close;
  if (on_drain) delete on_drain;
  if (on_error) delete on_error;
  if (on_connect) delete on_connect;
  free(write_buffer);
}

int
SocketWrap::Drain () {
  Nan::HandleScope scope;

  size_t len = this->write_buffer_used - this->write_buffer_offset;
  if (!len) return 0;

  struct utp_iovec *next = this->write_buffer + this->write_buffer_offset;
  int needs_drain = this->needs_drain;
  this->needs_drain = 0;

  int wrote = utp_uv_socket_writev(this->handle, this->socket, next, len);
  if (wrote < 0) return -1;

  size_t wrote_bytes = (size_t) wrote;

  while (wrote_bytes) {
    if (wrote_bytes >= next->iov_len) {
      wrote_bytes -= next->iov_len;
      this->write_buffer_offset++;
      next++;
    } else {
      char *base = (char *) next->iov_base;
      base += wrote_bytes;
      next->iov_base = base;
      next->iov_len -= wrote_bytes;
      wrote_bytes = 0;
    }
  }

  if (this->write_buffer_used == this->write_buffer_offset) {
    this->write_buffer_used = 0;
    this->write_buffer_offset = 0;
    if (needs_drain && this->on_drain) this->on_drain->Call(0, NULL);
  } else {
    this->needs_drain = 1;
  }

  return 0;
}

int
SocketWrap::EnsureBuffer (int inc) {
  while (this->write_buffer_used + inc >= this->write_buffer_length) {
    size_t double_size = 2 * this->write_buffer_length * sizeof(struct utp_iovec);
    struct utp_iovec *bigger = (struct utp_iovec *) realloc(this->write_buffer, double_size);
    if (bigger == NULL) return 1;
    this->write_buffer_length *= 2;
    this->write_buffer = bigger;
  }
  return 0;
}

NAN_METHOD(SocketWrap::New) {
  SocketWrap* obj = new SocketWrap();
  obj->Wrap(info.This());
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(SocketWrap::Write) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());

  if (self->EnsureBuffer(1)) {
    Nan::ThrowError("Could not grow write buffer");
    return;
  }

  struct utp_iovec *holder = self->write_buffer + (self->write_buffer_used++);

  Local<Value> buffer = info[0]->ToObject();
  holder->iov_len = node::Buffer::Length(buffer);
  holder->iov_base = node::Buffer::Data(buffer);

  if (self->Drain()) {
    Nan::ThrowError("Write failed");
    return;
  }

  if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());
  else info.GetReturnValue().Set(Nan::False());
}

NAN_METHOD(SocketWrap::Writev) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());

  Local<Array> writes = info[0].As<Array>();
  Local<Value> chunk = Nan::New<String>("chunk").ToLocalChecked();
  uint32_t length = writes->Length();

  if (self->EnsureBuffer((int) length)) {
    Nan::ThrowError("Could not grow write buffer");
    return;
  }

  struct utp_iovec *next = self->write_buffer + self->write_buffer_used;

  for (uint32_t i = 0; i < length; i++) {
    Local<Value> buffer = Nan::Get(writes->Get(i)->ToObject(), chunk).ToLocalChecked();

    next->iov_len = node::Buffer::Length(buffer);
    next->iov_base = node::Buffer::Data(buffer);

    next++;
    self->write_buffer_used++;
  }

  if (self->Drain()) {
    Nan::ThrowError("Write failed");
    return;
  }

  if (self->write_buffer_used == 0) info.GetReturnValue().Set(Nan::True());
  else info.GetReturnValue().Set(Nan::False());
}

NAN_METHOD(SocketWrap::End) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  utp_uv_socket_end(self->handle, self->socket);
}

NAN_METHOD(SocketWrap::OnData) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_data = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnEnd) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_end = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnClose) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_close = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnDrain) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_drain = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnError) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_error = new Nan::Callback(info[0].As<Function>());
}

NAN_METHOD(SocketWrap::OnConnect) {
  SocketWrap *self = Nan::ObjectWrap::Unwrap<SocketWrap>(info.This());
  self->on_connect = new Nan::Callback(info[0].As<Function>());
}

void SocketWrap::Init () {
  Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(SocketWrap::New);
  socket_constructor.Reset(tpl);
  tpl->SetClassName(Nan::New("SocketWrap").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Nan::SetPrototypeMethod(tpl, "write", SocketWrap::Write);
  Nan::SetPrototypeMethod(tpl, "writev", SocketWrap::Writev);
  Nan::SetPrototypeMethod(tpl, "end", SocketWrap::End);
  Nan::SetPrototypeMethod(tpl, "ondata", SocketWrap::OnData);
  Nan::SetPrototypeMethod(tpl, "onend", SocketWrap::OnEnd);
  Nan::SetPrototypeMethod(tpl, "onclose", SocketWrap::OnClose);
  Nan::SetPrototypeMethod(tpl, "ondrain", SocketWrap::OnDrain);
  Nan::SetPrototypeMethod(tpl, "onerror", SocketWrap::OnError);
  Nan::SetPrototypeMethod(tpl, "onconnect", SocketWrap::OnConnect);
}

Local<Value> SocketWrap::NewInstance () {
  Nan::EscapableHandleScope scope;

  Local<Object> instance;

  Local<FunctionTemplate> constructorHandle = Nan::New<FunctionTemplate>(socket_constructor);
  instance = constructorHandle->GetFunction()->NewInstance(0, NULL);

  return scope.Escape(instance);
}
<|endoftext|>


<commit_before>
#include "test_utils.hh"
#include <src/registrardb-internal.hh>
#include "../registrardb.hh"

using namespace std;
bool sUseSyslog;

struct MyListener : public RegistrarDbListener {
	RegistrarDb::BindParameters params;
	MyListener(const RegistrarDb::BindParameters &params): params(params) {};
	virtual void onRecordFound(Record *r) {
// 		cout << "record found : ";
// 		r->print(cout);
// 		cout << endl;
		auto ecc=firstContact(*r);
		long rExpire=ecc.mExpireAt-ecc.mUpdatedTime;
		check("expire",atol(params.sip.contact->m_expires), rExpire);
	}
	virtual void onError() {
		BAD("RegistrarDbListener:error");
	}
	virtual void onInvalid() {
		BAD("RegistrarDbListener:invalid");
	}
};

SofiaHome home;

void checkExpireHandling() {
	check("resolve expire1", ExtendedContact::resolve_expire(NULL, 5), 5);
	check("resolve expire2", ExtendedContact::resolve_expire(NULL, -1), -1);
	check("resolve expire3", ExtendedContact::resolve_expire("5", 6), 5);
	check("resolve expire4", ExtendedContact::resolve_expire("5", -1), 5);
}

static sip_contact_t *uid_ct(const char *urlparams, const char* ctparams) {
	return sip_contact_format(
		home.h, "<%s%s>%s", "sip:localhost:12345",
		urlparams,
		ctparams);
}
void checkUniqueIdExtraction() {
	#define UID_PARAM theparam
	string theparam = "UID_PARAM";
	check("+sip.instance in ct param",
		Record::extractUniqueId(uid_ct("", ";+sip.instance=UID_PARAM"))
		, theparam);

	check("+sip.instance in url param",
		Record::extractUniqueId(uid_ct(";+sip.instance=UID_PARAM", ""))
		, theparam);

	check("line in ct param",
		Record::extractUniqueId(uid_ct("", ";line=UID_PARAM"))
		, theparam);

	check("line url param",
		Record::extractUniqueId(uid_ct(";line=UID_PARAM", ""))
		, theparam);
}
int main(int argc, char **argv) {
	init_tests();

	checkExpireHandling();
	checkUniqueIdExtraction();

	int expire_delta= 1000;
	list<string> paths{"path1", "path2", "path3"};
	string contactid {"ip:5223"};
	string callid {"callid"};
	string line {"line"};
	string contact = "sip:" + contactid + ";line="+line;
	string contactWithChev = "<" + contact + ">";
	uint32_t cseq=123456;
	float quality=1;
	bool alias=false;
	const url_t *from=url_make(home.h, "sip:guillaume@bc");

	ExtendedContactCommon ecc(contactid.c_str(),paths, callid.c_str(), line.c_str());

	sip_contact_t *sip_contact= sip_contact_format(home.h, "<%s>;q=%f;expires=%d",
			contact.c_str(), quality, expire_delta);
	sip_path_t *sip_path=path_fromstl(home.h ,paths);

	RegistrarDbInternal registrar("preferred_ip");
	RegistrarDb::BindParameters params(
		RegistrarDb::BindParameters::SipParams(
			from, sip_contact, callid.c_str(), cseq, sip_path
		), 55555, alias
	);
	auto listener=make_shared<MyListener>(params);
	registrar.bind(params, listener);

	registrar.clearAll();
	cout << "success" << endl;
	return 0;
}

<commit_msg>Correct include for out-of-source compilation<commit_after>
#include "test_utils.hh"
#include "../registrardb-internal.hh"
#include "../registrardb.hh"

using namespace std;
bool sUseSyslog;

struct MyListener : public RegistrarDbListener {
	RegistrarDb::BindParameters params;
	MyListener(const RegistrarDb::BindParameters &params): params(params) {};
	virtual void onRecordFound(Record *r) {
// 		cout << "record found : ";
// 		r->print(cout);
// 		cout << endl;
		auto ecc=firstContact(*r);
		long rExpire=ecc.mExpireAt-ecc.mUpdatedTime;
		check("expire",atol(params.sip.contact->m_expires), rExpire);
	}
	virtual void onError() {
		BAD("RegistrarDbListener:error");
	}
	virtual void onInvalid() {
		BAD("RegistrarDbListener:invalid");
	}
};

SofiaHome home;

void checkExpireHandling() {
	check("resolve expire1", ExtendedContact::resolve_expire(NULL, 5), 5);
	check("resolve expire2", ExtendedContact::resolve_expire(NULL, -1), -1);
	check("resolve expire3", ExtendedContact::resolve_expire("5", 6), 5);
	check("resolve expire4", ExtendedContact::resolve_expire("5", -1), 5);
}

static sip_contact_t *uid_ct(const char *urlparams, const char* ctparams) {
	return sip_contact_format(
		home.h, "<%s%s>%s", "sip:localhost:12345",
		urlparams,
		ctparams);
}
void checkUniqueIdExtraction() {
	#define UID_PARAM theparam
	string theparam = "UID_PARAM";
	check("+sip.instance in ct param",
		Record::extractUniqueId(uid_ct("", ";+sip.instance=UID_PARAM"))
		, theparam);

	check("+sip.instance in url param",
		Record::extractUniqueId(uid_ct(";+sip.instance=UID_PARAM", ""))
		, theparam);

	check("line in ct param",
		Record::extractUniqueId(uid_ct("", ";line=UID_PARAM"))
		, theparam);

	check("line url param",
		Record::extractUniqueId(uid_ct(";line=UID_PARAM", ""))
		, theparam);
}
int main(int argc, char **argv) {
	init_tests();

	checkExpireHandling();
	checkUniqueIdExtraction();

	int expire_delta= 1000;
	list<string> paths{"path1", "path2", "path3"};
	string contactid {"ip:5223"};
	string callid {"callid"};
	string line {"line"};
	string contact = "sip:" + contactid + ";line="+line;
	string contactWithChev = "<" + contact + ">";
	uint32_t cseq=123456;
	float quality=1;
	bool alias=false;
	const url_t *from=url_make(home.h, "sip:guillaume@bc");

	ExtendedContactCommon ecc(contactid.c_str(),paths, callid.c_str(), line.c_str());

	sip_contact_t *sip_contact= sip_contact_format(home.h, "<%s>;q=%f;expires=%d",
			contact.c_str(), quality, expire_delta);
	sip_path_t *sip_path=path_fromstl(home.h ,paths);

	RegistrarDbInternal registrar("preferred_ip");
	RegistrarDb::BindParameters params(
		RegistrarDb::BindParameters::SipParams(
			from, sip_contact, callid.c_str(), cseq, sip_path
		), 55555, alias
	);
	auto listener=make_shared<MyListener>(params);
	registrar.bind(params, listener);

	registrar.clearAll();
	cout << "success" << endl;
	return 0;
}

<|endoftext|>