Beispiel #1
0
/*static*/ status_t
BPathMonitor::StopWatching(const char* path, BMessenger target)
{
	if (sLocker == NULL)
		return B_NO_INIT;

	TRACE("StopWatching(%s)\n", path);

	BAutolock _(sLocker);

	WatcherMap::iterator iterator = sWatchers.find(target);
	if (iterator == sWatchers.end())
		return B_BAD_VALUE;

	Watcher* watcher = iterator->second;
	HandlerMap::iterator i = watcher->handlers.find(path);

	if (i == watcher->handlers.end())
		return B_BAD_VALUE;

	PathHandler* handler = i->second;
	watcher->handlers.erase(i);

	handler->Quit();

	if (watcher->handlers.empty()) {
		sWatchers.erase(iterator);
		delete watcher;
	}

	return B_OK;
}
Beispiel #2
0
/*static*/ status_t
BPathMonitor::StopWatching(BMessenger target)
{
	if (sLocker == NULL)
		return B_NO_INIT;

	BAutolock _(sLocker);

	WatcherMap::iterator iterator = sWatchers.find(target);
	if (iterator == sWatchers.end())
		return B_BAD_VALUE;

	Watcher* watcher = iterator->second;
	while (!watcher->handlers.empty()) {
		HandlerMap::iterator i = watcher->handlers.begin();
		PathHandler* handler = i->second;
		watcher->handlers.erase(i);

		handler->Quit();
	}

	sWatchers.erase(iterator);
	delete watcher;

	return B_OK;
}
Beispiel #3
0
EventHandler::EventHandler(std::string file, int seed) {
	DistrLoader *dl = DistrLoader::getInstance();
	PathHandler *pa = PathHandler::getInstance();
	std::string path = pa->getEvent(file);
#ifdef DEBUG
	std::cout << "FOUND: " << path << " for file " << file << std::endl;
#endif
	std::string cont = get_file_contents(path.c_str());
	json::Object o = json::Deserialize(cont);
		
	for (auto it : o) {
		//FIRST:  Name of the event
		//SECOND: distribution
		if (it.second.GetType() == json::ValueType::ObjectVal) {
			json::Object obj = it.second; //It contains the name and the arguments
			obj["seed"] = seed; //Sets the same seed to all the elements
			std::string file = obj["name"]; //name of the distribution
			std::shared_ptr<DistrCreator> build = dl->load(file);
			std::shared_ptr<Distribution> distr{build->creator(obj)};
			newEventGen(String_to_EventEnumType(it.first),distr);
		} else {  
#ifdef DEBUG
			std::cout << "End" << std::endl;
#endif
		}
	}
};
bool OFTexturePaletteRecord::readTexAttr(TexAttr &attr)
{
    bool        returnValue = false;
    PathHandler *ph         = ImageFileHandler::the()->getPathHandler();

    if(ph != NULL)
    {
        std::string imgFile  = szFilename;
        std::string attrFile = imgFile + ".attr";

        attrFile = ph->findFile(attrFile.c_str());

        if(attrFile.empty() == false)
        {
            OSG_OPENFLIGHT_LOG(("OFTexturePaletteRecord::readTexAttr: [%s]\n",
                                attrFile.c_str()));

            std::ifstream ifs;
            ifs.open(attrFile.c_str(), std::ios::in | std::ios::binary);

            Inherited::readVal(ifs, attr.numTexelU);
            Inherited::readVal(ifs, attr.numTexelV);
            Inherited::readVal(ifs, attr.realSizeU);
            Inherited::readVal(ifs, attr.realSizeV);
            Inherited::readVal(ifs, attr.upX);
            Inherited::readVal(ifs, attr.upY);
            Inherited::readVal(ifs, attr.fileFormat);
            Inherited::readVal(ifs, attr.minFilter);
            Inherited::readVal(ifs, attr.magFilter);
            Inherited::readVal(ifs, attr.wrapUV);
            Inherited::readVal(ifs, attr.wrapU);
            Inherited::readVal(ifs, attr.wrapV);
            Inherited::readVal(ifs, attr.modified);
            Inherited::readVal(ifs, attr.pivotX);
            Inherited::readVal(ifs, attr.pivotY);
            Inherited::readVal(ifs, attr.envMode);

            if(attr.wrapU == 3)
                attr.wrapU = attr.wrapUV;
            if(attr.wrapV == 3)
                attr.wrapV = attr.wrapUV;

            returnValue = true;
        }
    }

    return returnValue;
}
Beispiel #5
0
void save(string filename, Terrain& terr, Renderer &r,PathHandler& p,LightHandler &l, ParticleHandler &part)
{
	terr.save(path,filename);
	r.saveModels(path,filename);
	p.save(path,filename);
	l.save(path,filename);
	part.save(path,filename);
}
OSG_USING_NAMESPACE

// Documentation for this class is emited in the
// OSGProxyGroupBase.cpp file.
// To modify it, please change the .fcd file (OSGProxyGroup.fcd) and
// regenerate the base file.

/*-------------------------------------------------------------------------*/
/*                               Sync                                      */

void ProxyGroup::changed(ConstFieldMaskArg whichField, 
                         UInt32            origin,
                         BitVector         details)
{
    if(whichField & (UrlFieldMask))
    {
        if(getAbsoluteUrl().empty())
        {
            PathHandler *ph = SceneFileHandler::the()->getPathHandler();

            if(ph != NULL) 
            {
                setAbsoluteUrl(ph->findFile(getUrl().c_str()));
            }

            if(getAbsoluteUrl().empty())
            {
                setAbsoluteUrl(getUrl());
            }

            setState(NOT_LOADED);
        }
    }
    if(whichField & (StateFieldMask |
                     UrlFieldMask   |
                     VolumeFieldMask))
    {
        for(UInt32 i = 0; i < _mfParents.size(); i++)
        {
            _mfParents[i]->invalidateVolume();
        }
    }

    Inherited::changed(whichField, origin, details);
}
Beispiel #7
0
/*static*/ status_t
BPathMonitor::StartWatching(const char* path, uint32 flags, BMessenger target)
{
	TRACE("StartWatching(%s)\n", path);

	status_t status = _InitLockerIfNeeded();
	if (status != B_OK)
		return status;

	// use the global looper for receiving node monitor notifications
	status = _InitLooperIfNeeded();
	if (status < B_OK)
		return status;

	BAutolock _(sLocker);

	WatcherMap::iterator iterator = sWatchers.find(target);
	Watcher* watcher = NULL;
	if (iterator != sWatchers.end())
		watcher = iterator->second;

	PathHandler* handler = new (nothrow) PathHandler(path, flags, target,
		sLooper);
	if (handler == NULL)
		return B_NO_MEMORY;
	status = handler->InitCheck();
	if (status < B_OK) {
		delete handler;
		return status;
	}

	if (watcher == NULL) {
		watcher = new (nothrow) BPrivate::Watcher;
		if (watcher == NULL) {
			delete handler;
			return B_NO_MEMORY;
		}
		sWatchers[target] = watcher;
	}

	watcher->handlers[path] = handler;
	return B_OK;
}
Beispiel #8
0
CalCoreModel *CharacterModel::loadConfig(std::string filename)
{
    PathHandler ph;
    std::string pfile;
    
    ph.setBaseFile(filename.c_str());
    
    // open the model configuration file
    std::ifstream file;
    file.open(filename.c_str(), std::ios::in | std::ios::binary);
    if(!file)
    {
        SWARNING << "Failed to open model configuration file '" 
                 << filename << "'." << endLog;
        return NULL;
    }

    CalCoreModel *model = new CalCoreModel("dummy");
    
    // parse all lines from the model configuration file
    int line;
    for(line = 1; ; line++)
    {
        // read the next model configuration line
        std::string strBuffer;
        std::getline(file, strBuffer);

        // stop if we reached the end of file
        if(file.eof()) break;

        // check if an error happend while reading from the file
        if(!file)
        {
            SWARNING << "Error while reading from the model configuration file '" 
                     << filename << "'." << endLog;
            return NULL;
        }

        // find the first non-whitespace character
        std::string::size_type pos;
        pos = strBuffer.find_first_not_of(" \t");

        // check for empty lines
        if((pos == std::string::npos) || (strBuffer[pos] == '\n') || 
           (strBuffer[pos] == '\r') || (strBuffer[pos] == 0)) 
            continue;

        // check for comment lines
        if(strBuffer[pos] == '#') continue;

        // get the key
        std::string strKey;
        strKey = strBuffer.substr(pos, strBuffer.find_first_of(" =\t\n\r", pos) - pos);
        pos += strKey.size();

        // get the '=' character
        pos = strBuffer.find_first_not_of(" \t", pos);
        if((pos == std::string::npos) || (strBuffer[pos] != '='))
        {
            SWARNING << filename << "(" << line << "): Invalid syntax." 
                     << endLog;
            return false;
        }

        // find the first non-whitespace character after the '=' character
        pos = strBuffer.find_first_not_of(" \t", pos + 1);

        // get the data
        std::string strData;
        strData = strBuffer.substr(pos, 
                            strBuffer.find_first_of("\n\r", pos) - pos);

        // handle the model creation
        if(strKey == "scale")
        {
            // set rendering scale factor
            //m_scale = atof(strData.c_str());
        }
        else if(strKey == "skeleton")
        {
            pfile = ph.findFile(strData.c_str());

            // load core skeleton
            SINFO << "Loading skeleton '" << pfile << "'..." << endLog;
            
            if(!model->loadCoreSkeleton(pfile.c_str()))
            {
                CalError::printLastError();
                return false;
            }
        }
        else if(strKey == "animation")
        {
            pfile = ph.findFile(strData.c_str());
            
            // load core animation
            SINFO << "Loading animation '" << pfile 
                  << "'..." << endLog;
            if(model->loadCoreAnimation(pfile.c_str()) == -1)
            {
                CalError::printLastError();
                return false;
            }
        }
        else if(strKey == "mesh")
        {
            pfile = ph.findFile(strData.c_str());

            // load core mesh
            SINFO << "Loading mesh '" << pfile << "'..." << endLog;
            if(model->loadCoreMesh(pfile.c_str()) == -1)
            {
                CalError::printLastError();
                return false;
            }
        }
        else if(strKey == "material")
        {
            pfile = ph.findFile(strData.c_str());

            // load core material
            SINFO << "Loading material '" << pfile << "'..." << endLog;
            if(model->loadCoreMaterial(pfile.c_str()) == -1)
            {
                CalError::printLastError();
                return false;
            }
        }
        else
        {
            // everything else triggers an error message, but is ignored
            SWARNING << filename << "(" << line << "): Invalid syntax." 
                     << endLog;
        }
    }

    // create material threads
    int mid;
    for(mid = 0; mid < model->getCoreMaterialCount(); mid++)
    {
        model->createCoreMaterialThread(mid);
        model->setCoreMaterialId(mid, 0, mid);
    }

    file.close();

    return model;
}
bool DATImageFileType::read(      Image *image,
                            const Char8 *fileName)
{
    bool retCode = false;

    std::ifstream inDat(fileName), inVolS;
    std::istream *inVol;
    std::string keyStr, objectFileName;
    const UInt32 lineBufferSize = 1024;
    Char8 *value, *keySepPos, lineBuffer[lineBufferSize];
    const Char8 keySep = ':';
    int fileOffset, keyL, valueL;
    std::map<std::string, KeyType>::iterator keyI;
    std::map<std::string, FormatDesc>::iterator formatI;
    KeyType key;
    Image::Type formatType;
    UInt32 channel = 1;
    UInt32 res[3];
    UInt32 dataSize = 0;
    Image::PixelFormat pixelFormat = Image::OSG_L_PF;
    char *dataBuffer = 0;
    bool needConversion = false;
    // default endian type is big endian
    bool big_endian = true;

    res[0] = res[1] = res[2] = 0;
    fileOffset = 0;
    formatType = Image::OSG_INVALID_IMAGEDATATYPE;
    dataSize = 0;
    dataBuffer = 0;

    initTypeMap();

    // read the data file
    for(lineBuffer[0] = 0;
        inDat.getline(lineBuffer, lineBufferSize);
        lineBuffer[0] = 0)
    {
        if((keySepPos = strchr(lineBuffer,keySep)))
        {
            keyL = keySepPos - lineBuffer;
            keyStr.assign( lineBuffer, keyL );
            keyI = _keyStrMap.find(keyStr);
            key = ((keyI == _keyStrMap.end()) ? UNKNOWN_KT : keyI->second);
            value = keySepPos + 1;

            while (value && isspace(*value))
                value++;

            valueL = int(strlen(value));

            while (isspace(value[valueL-1]))
                value[--valueL] = 0;

            switch (key)
            {
                case OBJECT_FILE_NAME_KT:
                    objectFileName = value;
                    image->setAttachmentField ( keyStr, value );
                    break;
                case CHANNEL_KT:
                    sscanf ( value, "%u", &(channel) );
                    image->setAttachmentField ( keyStr, value );
                    break;
                case RESOLUTION_KT:
                    sscanf ( value, "%u %u %u",
                             &(res[0]), &(res[1]), &(res[2]));
                    image->setAttachmentField ( keyStr, value );
                    break;
                case FORMAT_KT:
                    formatI = _formatStrMap.find(value);
                    if (formatI != _formatStrMap.end())
                    {
                        formatType = formatI->second.type;
                    }
                    else
                    {
                        formatType = Image::OSG_INVALID_IMAGEDATATYPE;
                    }
                    image->setAttachmentField ( keyStr, value );
                    break;
                case ENDIAN_KT:
                    if(!strcmp(value, "LITTLE"))
                        big_endian = false;
                    image->setAttachmentField ( keyStr, value );
                    break;
                case FILE_OFFSET_KT:
                    sscanf ( value, "%d", &fileOffset );
                    image->setAttachmentField ( keyStr, value );
                    break;
                case UNKNOWN_KT:
                    FNOTICE (( "Uknown DAT file key: >%s<\n",
                                 keyStr.c_str() ));
                    image->setAttachmentField ( keyStr, value );
                    break;
                case SLICE_THICKNESS_KT:
                default:
                    image->setAttachmentField ( keyStr, value );
                    break;
            }
        }
        else
        {
            FINFO (("Skip DAT line\n"));
        }
    }

    // set pixelformat
    switch (channel) 
    {
        case 4:
            pixelFormat = Image::OSG_RGBA_PF;
            break;
        case 3:
            pixelFormat = Image::OSG_RGB_PF;
            break;
        case 2:
            pixelFormat = Image::OSG_LA_PF;
            break;
        default:
            pixelFormat = Image::OSG_L_PF;
            break;
    }

    // check the setting and read the raw vol data
    if (objectFileName.empty() == false)
    {
        if((res[0] > 0) && (res[1] > 0) && (res[2] > 0))
        {
            if(formatType != Image::OSG_INVALID_IMAGEDATATYPE)
            {
                inVolS.open(objectFileName.c_str(),
                            std::ios::in | std::ios::binary);

                if (inVolS.fail() && ImageFileHandler::the()->getPathHandler())
                {
                    // Try to find the file in the search path
                    inVolS.clear(); // reset the error state

                    PathHandler *ph =
                        ImageFileHandler::the()->getPathHandler();

                    inVolS.open(ph->findFile(objectFileName.c_str()).c_str(),
                                std::ios::in | std::ios::binary );
                }

                if(inVolS.fail())
                {
                    // Maybe compressed and name not changed?
                    std::string gzname = objectFileName + ".gz";

                    inVolS.clear(); // reset the error state

                    inVolS.open(gzname.c_str(),
                                std::ios::in | std::ios::binary );

                    if(inVolS.fail() &&
                       ImageFileHandler::the()->getPathHandler())
                    {
                        // Try to find the file in the search path
                        inVolS.clear(); // reset the error state

                        PathHandler *ph =
                            ImageFileHandler::the()->getPathHandler();

                        inVolS.open(ph->findFile(gzname.c_str()).c_str(),
                                    std::ios::in | std::ios::binary );
                    }
                }

                if(inVolS.good())
                {
#ifdef OSG_WITH_ZLIB
                    zip_istream *unzipper = NULL;
#endif

                    image->set(pixelFormat,
                               res[0], res[1], res[2],
                               1, 1, 0.0, 0,
                               formatType);

                    image->clear();

                    dataSize = image->getSize();

                    UInt32 fileDataSize = dataSize;

                    if(isGZip(inVolS))
                    {
#ifdef OSG_WITH_ZLIB
                        unzipper = new zip_istream(inVolS);
                        inVol = unzipper;
#else
                        SFATAL << "Compressed streams are not supported! "
                               << "Configure with --enable-png "
                               << "--with-png=DIR options." << std::endl;
#endif
                    }
                    else
                    {
                        inVol = &inVolS;

                        // get length of the stream.
                        inVol->seekg(0, std::ios::end);
                        UInt64 length = inVol->tellg();
                        inVol->seekg(0, std::ios::beg);

                        if(length < dataSize - fileOffset)
                        {
                            // correct dataSize.
                            fileDataSize = length;
                            FWARNING (( "RAW file length to small!\n" ));
                        }
                        else if(length > dataSize - fileOffset)
                        {
                            FWARNING (( "RAW file length to big!\n" ));
                        }
                    }

                    if(needConversion)
                    {
                        dataBuffer = new char [ dataSize ];
                    }
                    else
                    {
                        dataBuffer = 
                            reinterpret_cast<char *>(image->editData());
                    }

                    if(fileOffset != 0)
                        inVol->ignore (fileOffset);

                    inVol->read ( dataBuffer, fileDataSize );

#ifdef OSG_WITH_ZLIB
                    if(unzipper != NULL)
                        delete unzipper;
#endif
                }
                else
                {
                    FWARNING (( "Can not open %s image data\n",
                                objectFileName.c_str() ));
                }
            }
            else
            {
                FWARNING (( "Invalid/Missing DAT Format\n" ));
            }
        }
        else
        {
            FWARNING (( "Invalid/Missing DAT Resolution\n" ));
        }
    }
    else
    {
        FWARNING (( "Invalid/Missing DAT ObjectFileName\n" ));
    }

    // check/reformat vol data
    if (dataSize && dataBuffer)
    {
        // check host endian type
        UInt16 word = 0x0001;
        UInt8 *byte = reinterpret_cast<UInt8 *>(&word);
        bool host_big_endian = byte[0] ? false : true;

        if(big_endian != host_big_endian)
            image->swapDataEndian();

        if (needConversion)
        {
            FLOG (("DAT-Data convert not impl. yet !\n"));
            {
                switch (formatType)
                {
                    case Image::OSG_UINT8_IMAGEDATA:
                        break;
                    case Image::OSG_UINT16_IMAGEDATA:
                        break;
                    case Image::OSG_UINT32_IMAGEDATA:
                        break;
                    case Image::OSG_FLOAT32_IMAGEDATA:
                        break;
                    default:
                        ;
                }
            }
        }
        else
        {
            retCode = true;
        }
    }


    /* TODO
       std::ifstream in(fileName);
       Head head;
       void *headData = (void*)(&head);
       unsigned dataSize, headSize = sizeof(Head);

       if ( in &&
       in.read(static_cast<char *>(headData),
       headSize) && head.netToHost() &&
       image.set ( Image::PixelFormat(head.pixelFormat),
       head.width, head.height, head.depth, head.mipmapCount,
       head.frameCount, float(head.frameDelay) / 1000.0) &&
       (dataSize = image.getSize()) &&
       in.read((char *)(image.getData()), dataSize ))
       retCode = true;
       else
       retCode = false;
    */

    return retCode;
}
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
	cout << "Testing screen aligned text generation and file-IO." << endl;
	
    if(argc == 1)
    {
        FFATAL(("Need *.txf or *.ttf font file\n"));
        return -1;
    }

    // OSG init
    osgInit(argc, argv);

    // GLUT init
    int             winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr   gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    PathHandler paths;

    paths.push_backPath(".");

    //paths.push_backPath("/home/elmi/wrk/development/texFont");
    // create the scene
    FontStyle   *fontStyle = FontStyleFactory::the().create( paths, argv[1], 
															 0.25);
	cout << fontStyle->getFontName() << endl;

    // create the scene
    NodePtr pTorus = makeTorus( 0.02, 0.55, 16, 16);
	ChunkMaterialPtr mat = ChunkMaterial::create();

    MaterialChunkPtr pmc = MaterialChunk::create();
    pmc->setDiffuse( Color4f( 1,0,0,0.5 ) );
    pmc->setAmbient( Color4f( 0,1,0,0.5 ) );
    pmc->setSpecular( Color4f( 0,0,1,0.5 ) );
	pmc->setLit( true );
    pmc->setShininess( 20 );

	beginEditCP(mat);
	{
	mat->addChunk( pmc );
	}
	endEditCP(mat);

    scene = Node::create();
	GroupPtr group = Group::create();
    beginEditCP( scene );
    {
        scene->setCore( group );
	}
    endEditCP( scene );

	SharedFontStylePtr sfs = SharedFontStyle::create(); 
	sfs->setContainedFontStyle( fontStyle );

	for( int x=0; x<100; x += 20 )
	{
		for( int y=0; y<100; y += 20 )
		{
			for( int z=0; z<100; z += 20 )
			{
				ScreenAlignedTextPtr scaText = ScreenAlignedText::create();
				if( scaText == NullFC )
				{
					exit (2);
				}
				SharedFontStyleWrapperPtr pFSWrapper = SharedFontStyleWrapper::create();
				pFSWrapper->setFStyleContainer( sfs );
				ostringstream cString;
				cString << '(' 
						<< x 
						<< ',' 
						<< y
						<< ','
						<< z
						<< ')'
						<< endl;

				beginEditCP(scaText);
				{
					scaText->setPosition( Vec3f ( x, y, z ) );
					scaText->setFont( pFSWrapper );
					scaText->setVerticalLineDistance( 0.20 );
					scaText->setAlignment( 0 );
					scaText->editMFText()->push_back( cString.str() );
					scaText->setMaterial( mat );
				}
				endEditCP(scaText);
				NodePtr pTextNode = Node::create();
				beginEditCP( pTextNode );
				{
					pTextNode->setCore( scaText );
				}
				beginEditCP( scene );
				{
					scene->addChild( pTextNode );
				}
				endEditCP( scene );	
				cout << "Erzeugt : " 
					 << cString.str() 
					 << endl;
			}
		}
    }

	//NodePtr pCopied = scene;

#if 1
	{
		ofstream outFileStream( "/tmp/text.osg" );

		if( !outFileStream )
		{
			cerr << "cannot open file" << endl;
			exit(2);
		}
		//FILE *pFile = fopen( "isolinien.osg","w" );
		//BINWriter writer( pFile );
		OSGWriter writer( outFileStream );
		writer.write( scene );
	}
#endif

#if 0
	VRMLWriteAction *pWriter = VRMLWriteAction::create();
	scene->dump();
	pWriter->open("allesscheisse.wrl");
	pWriter->write( scene);
	pWriter->close();
	delete pWriter;
#endif

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin);
    mgr->setRoot( scene );

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
void TiledImageBlockAccessor::open(const Char8 *szFilename)
{
    fprintf(stderr, "Open Tiled %s\n", szFilename);

    FILE *pFile = fopen(szFilename, "r");

    Char8 szRow[1024];

    const Char8 *szDelim = " \t\n ";

    std::string szBuffer;

    if(pFile != NULL)
    {
        while(!feof(pFile))
        {
            fgets(szRow, 1024, pFile);
            
            szBuffer.append(szRow);
        }
 
        PathHandler *pOrgHandler = ImageFileHandler::the()->getPathHandler();
        PathHandler  tmpHandler;

        tmpHandler.setBaseFile(szFilename);

        ImageFileHandler::the()->setPathHandler(&tmpHandler);

        fprintf(stderr, "got %s\n", szBuffer.c_str());

        string_token_iterator cIt (szBuffer, szDelim);
        string_token_iterator cEnd;

        _uiColumns = TypeTraits<UInt32>::getFromCString((*cIt).c_str());

        fprintf(stderr, "C: %d\n", _uiColumns);

        ++cIt;

        _uiRows = TypeTraits<UInt32>::getFromCString((*cIt).c_str());

        fprintf(stderr, "R: %d\n", _uiRows);
        
        ++cIt;

        for(UInt32 i = 0; i < _uiRows * _uiColumns; ++i)
        {
            if(cIt == cEnd)
            {
                break;
            }

            fprintf(stderr, "File -%s-\n", (*cIt).c_str());

            ImageBlockAccessorPtr pAccess;

            if(strncmp((*cIt).c_str(), "default:", 7) == 0)
            {
                DefaultBlockAccessorPtr pDefAccess( 
                    new DefaultBlockAccessor());

                pAccess = pDefAccess;

                pDefAccess->open((*cIt).c_str());
            }
            else
            {
                pAccess = ImageFileHandler::the()->open((*cIt).c_str());
            }

            _vImages.push_back(pAccess);

            ++cIt;

        }

        ImageFileHandler::the()->setPathHandler(pOrgHandler);

        if(_vImages.size() != _uiRows * _uiColumns || _vImages.size() == 0)
        {
            fprintf(stderr, "Images missing %" PRISize " %d\n",
                    _vImages.size(),
                    _uiRows * _uiColumns);

            _vImages.clear();

            return;
        }

        _vSampleDescs.resize(_vImages.size());

        UInt32 uiIdx      = 0;
        UInt32 uiOtherIdx = 0;

        _vSampleDescs[0].setBounds( 0, 
                                    0, 
                                   _vImages[0]->getSize()[0],
                                   _vImages[0]->getSize()[1]);

        for(UInt32 i = 1; i < _uiRows; ++i)
        {
            uiIdx      = i * _uiColumns;
            uiOtherIdx = uiIdx - _uiColumns;

            _vSampleDescs[uiIdx].setBounds(
                _vSampleDescs[uiOtherIdx].x0,
                _vSampleDescs[uiOtherIdx].y1,
                _vImages     [uiIdx     ]->getSize()[0],
                _vImages     [uiIdx     ]->getSize()[1]);
        }

        for(UInt32 i = 1; i < _uiColumns; ++i)
        {
            _vSampleDescs[i].setBounds(
                _vSampleDescs[i - 1].x1,
                _vSampleDescs[i - 1].y0,
                _vImages     [i    ]->getSize()[0],
                _vImages     [i    ]->getSize()[1]);
        }


        for(UInt32 i = 1; i < _uiRows; ++i)
        {
            for(UInt32 j = 1; j < _uiColumns; ++j)
            { 
                uiIdx      =  i      * _uiColumns +  j;
                uiOtherIdx = (i - 1) * _uiColumns + (j - 1);

                _vSampleDescs[uiIdx].setBounds(
                    _vSampleDescs[uiOtherIdx].x1,
                    _vSampleDescs[uiOtherIdx].y1,
                    _vImages     [uiIdx     ]->getSize()[0],
                    _vImages     [uiIdx     ]->getSize()[1]);
            }
        }

        for(UInt32 i = 0; i < _uiRows; ++i)
        {
            for(UInt32 j = 0; j < _uiColumns; ++j)
            {
                uiIdx = i * _uiColumns + j;

                fprintf(stderr, "(%d)(%d %d) | %d %d %d %d\n",
                        uiIdx, i, j,
                        _vSampleDescs[uiIdx].x0,
                        _vSampleDescs[uiIdx].y0,
                        _vSampleDescs[uiIdx].x1,
                        _vSampleDescs[uiIdx].y1);
            }
        }

        _vSize.setValues(_vSampleDescs.back().x1,
                         _vSampleDescs.back().y1);
                         
        GeoReferenceAttachment *pFirstRef = 
            _vImages.front()->getGeoRef();

        if(pFirstRef != NULL)
        {
            _pGeoRef = GeoReferenceAttachment::create();
            
            _pGeoRef->setOrigin       (pFirstRef->getOrigin       ());
            _pGeoRef->setPixelSize    (pFirstRef->getPixelSize    ());
            _pGeoRef->setEllipsoidAxis(pFirstRef->getEllipsoidAxis());
            _pGeoRef->setDatum        (pFirstRef->getDatum        ());
            _pGeoRef->setNoDataValue  (pFirstRef->getNoDataValue  ());
        }

        _eImgType     = _vImages.front()->getType  ();
        _eImgFormat   = _vImages.front()->getFormat();

        _fNoDataValue = _vImages.front()->getNoDataValue();

        fclose(pFile);
    }
}
Beispiel #12
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc, argv);

    // GLUT init
    int             winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr   gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    PathHandler paths;
    paths.push_backPath(".");

    // create the scene
    // build a special txf-font with only a little set of characters
    FontStyle   *fontStyle = FontStyleFactory::the().create(paths, argv[1], 1);
    assert(fontStyle);
    //((TTFontStyle *) fontStyle)->createTXFMap((UChar8 *) ". fps0123456789");
    ((TTFontStyle *) fontStyle)->createTXFMap();

    // write it somewhere
#if 1
    std::ofstream    target;
    target.open("statistics.txf");
    fontStyle->dump(target);
    target.close();
#else
    ostrstream  target;
    fontStyle->dump(target);
#endif
#if 1
    std::ifstream    source;
    source.open("statistics.txf");
#else
#if 0
    // Hack, to get the stuff into memory
    int     bufSize = 100000;
    char    *buffer = new char[bufSize];
    int     numRead;
    FILE    *in = fopen("statistics.txf", "r");

    numRead = fread(buffer, 1, bufSize, in);

    fclose(in);

    istrstream  source(buffer, numRead);
#else
    istrstream  source(target.str(), target.pcount());
#endif
#endif
    TXFFont     *font = new TXFFont("test.txf", source);
    font->initFont();

    fontText.setSize(1);
    font->createInstance(&fontText);

    fontText.setJustifyMajor(MIDDLE_JT);

    lineVec.push_back("0000.00 fps");

    // TXF-Style Texture+Geometry
    n = Node::create();
    txfGeo = Geometry::create();

    ImagePtr  pTxfImg = Image::create();

    if(fontText.fillTXFGeo(*txfGeo, true, lineVec))
    {
        fontText.fillTXFImage(pTxfImg);

        SimpleTexturedMaterialPtr   mat = SimpleTexturedMaterial::create();
        beginEditCP(mat);
        {
            mat->setImage(pTxfImg);
        }

        endEditCP(mat);
        txfGeo->setMaterial(mat);
        beginEditCP(n, Node::CoreFieldMask);
        {
            n->setCore(txfGeo);
        }
    }

    scene = Node::create();

    // add a transformation to make it move
    trans = Transform::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
    {
        scene->setCore(trans);
        scene->addChild(n);
    }

    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin);
    mgr->setRoot(scene);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
Beispiel #13
0
void load(string filename, Terrain &terr, Renderer &r, PathHandler& p, LightHandler &l, ParticleHandler &part,MeshHandler &m)
{
	ifstream stream;
	string fullPath = path+filename+".txt";
	stream.open(fullPath.c_str());
	if(stream.is_open())
	{
		r.clear();
		l.clear();
		p.clear();
		part.clear();
		int mapsize=0;
		
		int highBind=0;
		string bmp1="";
		string bmp2="";
		int width=0;
		while(!stream.eof())
		{
			char buf[1024];
			char key[1024];
			stream.getline(buf, 1024);
			sscanf(buf, "%s", key);

			if(strcmp(key, "bmp1:") == 0)
			{
				char file[100];
				sscanf(buf, "bmp1: %s", &file);
				bmp1= string(file);
			}
			else if(strcmp(key, "bmp2:") == 0)
			{
				char file[100];
				sscanf(buf, "bmp2: %s", &file);
				bmp2= string(file);
				
				if(width == 128)
					mapsize=1;
				if(width==256)
					mapsize=2;
				terr.createNewMap(mapsize);
				terr.loadMaps(path+bmp1,path+bmp2,path+filename+"gm.png");
			}
			else if(strcmp(key, "width:") == 0)
			{
				sscanf(buf, "width: %d", &width);
			}		
			else if(strcmp(key, "Surfaceplanes:") == 0)
			{
				string texture;
				int surfCounter=-1;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "SF:") == 0)
					{
						char in[100];
						sscanf(buf, "SF: %s", &in);
						texture = string(in);
						surfCounter++;
					}
					else if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else // Else its an actual road piece (at least we hope so because else we are screwed)
					{
						float rot,scale;
						float x, z;
						sscanf(buf, "%f %f %f %f", &rot, &x, &z,&scale);
						terr.addSurface(vec3(x,0,z),rot,surfCounter,scale);
						

						//m_roads.push_back(g_graphicsEngine->createRoad(texture, FLOAT3(x, 0.0f, -z), rot));
					}
				}
			}
			else if(strcmp(key, "MODELS:") == 0)
			{
				string s;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else
					{
						char in[100];
						vec3 position;
						vec3 rotation;
						float scale;
						int id = 0;
						sscanf(buf, "%s %f %f %f %f %f %f %f %d", &in, &position.x, &position.y, &position.z, &rotation.x, &rotation.y, &rotation.z, &scale,&id);
						Model model;
						string modelName = string(in);
						int meshIndex = m.getMeshByName(modelName);
						model.setMesh(m.getMeshInfo(meshIndex));
						model.setBoundingBox(m.getBoundingBox(meshIndex));
						model.setMeshName(m.getMeshName(meshIndex));
						model.setPos(position);
						model.rotateX(rotation.x);
						model.rotateY(rotation.y);
						model.rotateZ(rotation.z);
						model.scaleXYZ(scale);
						model.bindId(id);
						r.addModel(model);
						if(id>bindCounter)
							bindCounter=id;
					}
				}
			}
			else if(strcmp(key, "LIGHTS:") == 0)
			{
				string s;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else
					{
						char in[100];
						sscanf(buf, "%s", &in);

						if(strcmp(key, "AM") == 0)
						{
							vec3 direction;
							vec3 color;
							vec3 rot;
							vec3 pos;

							sscanf(buf, "AM %f %f %f %f %f %f %f %f %f %f %f %f", &direction.x, &direction.y, &direction.z, &color.x, &color.y, &color.z,&rot.x,&rot.y,&rot.z,&pos.x,&pos.y,&pos.z);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(pos);
							tmpLight.setRadius(0);
							tmpLight.setLightType(LightType::AMBIENT);
							tmpLight.rotateX(rot.x);
							tmpLight.rotateY(rot.y);
							tmpLight.rotateZ(rot.z);
							l.addLight(tmpLight);
						}
						else if(strcmp(key, "PLS") == 0)
						{
							vec3 position;
							vec3 rotation;
							vec3 color;
							float radius;
							int id=0;
							sscanf(buf, "PLS %f %f %f %f %f %f %f %f %f %f %d", &position.x, &position.y, &position.z, &rotation.x, &rotation.y, &rotation.z, &color.x, &color.y, &color.z, &radius,&id);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(position);
							tmpLight.setRadius(radius);
							tmpLight.setLightType(LightType::POINTLIGHTSHADOW);
							tmpLight.rotateX(rotation.x);
							tmpLight.rotateY(rotation.y);
							tmpLight.rotateZ(rotation.z);
							tmpLight.bindId(id);
							l.addLight(tmpLight);

						}
						else if(strcmp(key, "PL") == 0)
						{
							vec3 position;
							vec3 rotation;
							vec3 color;
							float radius;
							int id=0;
							sscanf(buf, "PL %f %f %f %f %f %f %f %f %f %f %f", &position.x, &position.y, &position.z, &rotation.y, &rotation.x, &rotation.z, &color.x, &color.y, &color.z, &radius,&id);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(position);
							tmpLight.setRadius(radius);
							tmpLight.setLightType(LightType::POINTLIGHT);
							tmpLight.rotateX(rotation.x);
							tmpLight.rotateY(rotation.y);
							tmpLight.rotateZ(rotation.z);
							tmpLight.bindId(id);
							l.addLight(tmpLight);
						}
						else if(strcmp(key, "SL") == 0)
						{
							vec3 position;
							vec3 direction;
							vec3 color;
							vec3 rot;
							sscanf(buf, "SL %f %f %f %f %f %f %f %f %f %f %f %f", &position.x, &position.y, &position.z, &direction.x, &direction.y, &direction.z, &color.x, &color.y, &color.z,&rot.x, &rot.y, &rot.z);
							
							Light tmpLight;
							tmpLight.setColor(color);
							tmpLight.setContrast(1.0f);
							tmpLight.setPos(position);
							tmpLight.setRadius(0);
							tmpLight.setLightType(LightType::SPOTLIGHT);
							tmpLight.rotateX(rot.x);
							tmpLight.rotateY(rot.y);
							tmpLight.rotateZ(rot.z);
							l.addLight(tmpLight);
						}
					}
				}
			}
			else if(strcmp(key, "path") == 0)
			{
				p.addPath();
				stream.getline(buf, 1024);
				sscanf(buf, "%s", key);

				int nrOfPoints = 0;
				vec3 points[100];
				while(strcmp(key, "end") != 0)
				{
					float notInvertZ;
					points[nrOfPoints]=vec3(0.0f);
					sscanf(buf, "%f %f", &points[nrOfPoints].x, &points[nrOfPoints].z);
					nrOfPoints++;
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
				}

				for(int i = 0; i < nrOfPoints; i++)
				{
					p.addFlagToCurrentPath(points[i]);
				}

			}
			else if(strcmp(key, "PARTICLESYSTEMS:") == 0)
			{
				string s;
				bool done = false;
				while(!done)
				{
					stream.getline(buf, 1024);
					sscanf(buf, "%s", key);
					
					if(strcmp(key, "end") == 0)
					{
						done = true;
					}
					else
					{
						vec3 position;
						vec3 rotation;
						vec3 color;

						sscanf(buf, "%s %f %f %f %f %f %f %f %f %f", &key, &position.x, &position.y, &position.z, &rotation.x, &rotation.y, &rotation.z, &color.x, &color.y, &color.z);
						
						Particle particle;
						particle.setPos(position);
						particle.rotateX(rotation.x);
						particle.rotateY(rotation.y);
						particle.rotateZ(rotation.z);
						particle.setColor(color);
						string particleType=key;
						if(particleType=="GLOWRING")
							particle.setParticleType(ParticleType::GLOWRING);
						if(particleType=="FIRE")
							particle.setParticleType(ParticleType::FIRE);
						if(particleType=="EMIT")
							particle.setParticleType(ParticleType::EMIT);
						if(particleType=="FLOW")
							particle.setParticleType(ParticleType::FLOW);
						if(particleType=="SMOKE")
							particle.setParticleType(ParticleType::SMOKE);
						part.addParticleModel(particle);

						//Create particle system
						int lol = 0;
					}
				}
			}
			sscanf("bugfix", "%s", key);
		}	
		bindCounter++;
		stream.close();
	}
}
Beispiel #14
0
void CharacterModel::convertMaterials(std::string configfile)
{
    getMaterials().clear();
    UInt32 mcnt = 0;
    PathHandler ph;
    
    ph.setBaseFile(configfile.c_str());
       
    for(int mid = 0; mid < _coreModel->getCoreMaterialCount(); mid++)
    {
        CalCoreMaterial *coremat = _coreModel->getCoreMaterial(mid);
        SimpleMaterialPtr mat = SimpleMaterial::create();

        beginEditCP(mat);

        CalCoreMaterial::Color &calamb = coremat->getAmbientColor();
        CalCoreMaterial::Color &caldif = coremat->getDiffuseColor();
        CalCoreMaterial::Color &calspec = coremat->getSpecularColor();

        mat->setAmbient(Color3f(calamb.red / 255.0f, calamb.green / 255.0f, calamb.blue / 255.0f));
        mat->setDiffuse(Color3f(caldif.red / 255.0f, caldif.green / 255.0f, caldif.blue / 255.0f));
        mat->setSpecular(Color3f(calspec.red / 255.0f, calspec.green / 255.0f, calspec.blue / 255.0f));
        
        mat->setShininess(coremat->getShininess() * 100.f);
        mat->setLit(true);
        mat->setColorMaterial(GL_NONE);
        
        for(int mapId = 0; mapId < coremat->getMapCount(); mapId++)
        {
            std::string file = coremat->getMapFilename(mapId);
            std::string pfile = ph.findFile(file.c_str());
            SINFO << "Loading texture '" << pfile << "'..." << endLog;

            ImagePtr img = Image::create();
            
             if(!img->read(pfile.c_str()))
            {
                SWARNING << "CharacterModel::convertMaterials: error "
                         << "loading image " << file << endLog;
            }
            else
            {
                // amz with my test scene paladin.cfg all textures were
                // upside down so I disabled the vertical flipping perhaps
                // they fixed the bug in Cal3D?
#if 0
                beginEditCP(img);
                {
                // For some reason Cal3D expects textures upside down ???
                UInt32 bpl = img->getBpp() * img->getWidth();
                UChar8 *t = img->getData(), 
                       *b = t + (img->getHeight() - 1) * bpl,
                        dum;

                for(UInt32 y = img->getHeight() / 2; y > 0; --y)
                {
                    for(UInt32 x = bpl; x > 0; --x, ++t, ++b)
                    {
                        dum = *t;
                        *t = *b;
                        *b = dum;
                    }
                    b -= bpl * 2;
                }
                }
                endEditCP(img);
#endif
                
                TextureChunkPtr tex = TextureChunk::create();
                
                beginEditCP(tex);
                tex->setImage(img);
                tex->setEnvMode(GL_MODULATE);
                endEditCP(tex);
                
                mat->addChunk(tex);
            }
        }
            
        endEditCP(mat);
        
        coremat->setUserData((Cal::UserData)mcnt);
        getMaterials().push_back(mat);
        mcnt ++;
    }    
}
int main() {
	SQLiteHandler* sqliteHandler = new SQLiteHandler();
	sqliteHandler->openDB("subwayDB.db");
	PathHandler *pc = new PathHandler();
	pc->setLineList(sqliteHandler);
	sqliteHandler->closeDB();
	cout << "로딩완료" << endl;
	cout << endl;
	
	string order = "0";
	int intorder = 0;
	string startStation="";
	string centerStation = "";
	string endStation = "";
	bool isExistStation;
	bool flag = true;
	while (flag) {
		cout << "명령을 선택해주세요(1: 경로검색, 2: 프로그램종료):";
		cin >> order;
		if(order != "1" && order != "2"){
			cout << "올바른 명령이 아닙니다." << endl;
			order = "0";
			continue;
		}
		intorder = atoi(order.c_str());
		switch (intorder) {
		case FIND_PATH:
			while (true) {
				cout << "출발역을 입력해주세요(ex: 수원): ";
				cin >> startStation;
				isExistStation = pc->isExistStation(startStation);				
				if (isExistStation)
					break;
				cout << "해당역은 존재하지 않습니다." << endl;
			}
			while (true) {
				cout << "도착역을 입력해주세요: ";
				cin >> endStation;
				isExistStation = pc->isExistStation(endStation);
				if (isExistStation)
					break;
				cout << "해당역은 존재하지 않습니다." << endl;
			}
			while (true) {
				cout << "경유역을 입력해주세요(없으면 x 입력):";
				cin >> centerStation;
				if (centerStation == "x")
					break;
				isExistStation = pc->isExistStation(centerStation);
				if (isExistStation)
					break;
				cout << "해당역은 존재하지 않습니다." << endl;
			}
			cout << endl;
			if (centerStation == "x")
				pc->findShortestPath(startStation, endStation);
			else
				pc->findShortestPath(startStation, endStation, centerStation);
			cout << endl;
			startStation = "";
			centerStation = "";
			endStation = "";
			break;
		case EXIT:
			flag = false;
		}
	}

	delete(sqliteHandler);
	delete(pc);

	return 0;
}
Int32 OBJSceneFileType::readMTL ( const Char8 *fileName,
                                  std::map<std::string,
                                  SimpleTexturedMaterialUnrecPtr> & mtlMap )
  const
{
    if(fileName == NULL || strlen(fileName) == 0)
        return 0;

    Int32 mtlCount = 0;

    PathHandler *pathHandler = SceneFileHandler::the()->getPathHandler();
    std::string fullFilePath;

    if(pathHandler != NULL)
        fullFilePath = pathHandler->findFile(fileName);
    else
        fullFilePath = fileName;

    if(fullFilePath.empty())
    {
        FWARNING (("Couldn't open '%s'!\n", fileName));
        return 0;
    }

    std::ifstream in(fullFilePath.c_str());
    SimpleTexturedMaterialUnrecPtr mtlPtr = NULL;
    Real32 a,b,c;
    std::string elem;
    std::map<std::string, MaterialElem>::const_iterator elemI;
    MaterialElem mtlElem;
    std::map<std::string, OSG::ImageUnrecPtr> imageMap;
    std::map<std::string, OSG::ImageUnrecPtr>::iterator iI;
    ImageUnrecPtr image = NULL;
    bool constDiffuse = false, constAmbient = false, constSpecular = false;

    if (in)
    {
        for (in >> elem; in.eof() == false; in >> elem)
        {
            if (elem[0] == '#' || elem[0] == '$' )
            {
                in.ignore(INT_MAX, '\n');
            }
            else
            {
                elemI = _mtlElemMap.find(elem);
                mtlElem = ((elemI == _mtlElemMap.end()) ?
                     UNKNOWN_ME : elemI->second);
                if (mtlElem == NEW_MTL_ME)
                {
                    in >> elem;
                    mtlPtr = SimpleTexturedMaterial::create();
                    mtlPtr->setColorMaterial(GL_NONE);
                    mtlPtr->setEnvMode(GL_MODULATE);
                    mtlMap[elem] = mtlPtr;
                    mtlCount++;
                    constDiffuse  = false;
                    constAmbient  = false;
                    constSpecular = false;
                }
                else
                {
                    if (mtlPtr == NULL)
                    {
                        FFATAL (( "Invalid Mtl token: %s, newmtl expected in %s\n",
                                elem.c_str(), fileName ));
                        in.ignore(INT_MAX, '\n');
                    }
                    else
                    {
                        switch (mtlElem)
                        {
                            case MTL_DIFFUSE_ME:
                                in >> a >> b >> c;
                                if (!constDiffuse)
                                    mtlPtr->setDiffuse( Color3f( a,b,c ));
                            break;
                            case MTL_AMBIENT_ME:
                                in >> a >> b >> c;
                                if (!constAmbient)
                                    mtlPtr->setAmbient( Color3f( a,b,c ));
                            break;
                            case MTL_SPECULAR_ME:
                                in >> a >> b >> c;
                                if (!constSpecular)
                                    mtlPtr->setSpecular( Color3f( a,b,c ));
                            break;
                            case MTL_SHININESS_ME:
                                in >> a;
                                mtlPtr->setShininess(a);
                            break;
                            case MTL_ILLUM_ME:
                                ; // TODO: What to do with illum ?!?
                                in >> elem;
                                // FFATAL (("obj mtl illum not handled yet\n"));
                            break;
                            case MTL_REFL_ME:
                                mtlPtr->setEnvMap(true);
                            break;
                            case MTL_TRANSPARENCY_ME:
                                in >> a;
                                mtlPtr->setTransparency(a);
                            break;
                            case MTL_DISSOLVE_ME:
                                in >> a;
                                mtlPtr->setTransparency(1.f - a);
                                break;
                            case MTL_MAP_KD_ME:
                            case MTL_MAP_KA_ME:
                            case MTL_MAP_KS_ME:
                                image = NULL;
                                in >> elem;
                                iI = imageMap.find(elem);
                                if (iI == imageMap.end())
                                {
                                    std::string fullElemPath;
                                    if(pathHandler != NULL)
                                        fullElemPath = pathHandler->findFile(elem.c_str());
                                    else
                                        fullElemPath = elem.c_str();
                                    image = OSG::ImageFileHandler::the()->read(fullElemPath.c_str());

                                    if(image != NULL)
                                    {
                                        image->setForceAlphaBinary(
                                            image->calcIsAlphaBinary());

                                        imageMap[elem] = image;
                                    }
                                }
                                else
                                {
                                    image = iI->second;
                                }
                                if (image != NULL)
                                {
                                    mtlPtr->setImage(image);
                                    switch (mtlElem)
                                    {
                                        case MTL_MAP_KD_ME:
                                            constDiffuse = true;
                                            mtlPtr->setDiffuse  ( Color3f( 1.f, 1.f, 1.f) );
                                        break;
                                        case MTL_MAP_KA_ME:
                                            constAmbient = true;
                                            mtlPtr->setAmbient  ( Color3f( 1.f, 1.f, 1.f) );
                                        break;
                                        case MTL_MAP_KS_ME:
                                            constSpecular = true;
                                            mtlPtr->setSpecular ( Color3f( 1.f, 1.f, 1.f) );
                                        break;
                                        default:
                                        break;
                                    }
                                }
                                else
                                {
                                    FFATAL (( "Can not find %s texture file in mtl %s \n",
                                            elem.c_str(), fileName ));
                                }
                            break;
                            default:
                                FWARNING (( "Invalid %s entry in %s\n",
                                            elem.c_str(), fileName ));
                                in.ignore(INT_MAX, '\n');
                        }
                    }
                }
            }
        }
Beispiel #17
0
int main(int argc, char **argv)
{
	int width,height;
	Camera cam;
	int mousedx=0;
	int mousedy=0;
	int fps=0;
	int nrOfObjects=0;
	int nrOfLights=0;
	float tdropoff=0.0f;
	float topacity=0.0f;
	float tradius=0.0f;
	int nrOfPaths=0;
	int nrOfParticleSystems=0;
	float gr=0.0f;
	float gg=0.0f;
	float gb=0.0f;
	sf::Clock clock;

	//window options
	width=1280;
	height=720;
	sf::WindowSettings settings;
	settings.DepthBits         = 24;
	settings.StencilBits       = 8;
	settings.AntialiasingLevel = 1;  
	sf::Window app;
	app.Create(sf::VideoMode(width, height, 32), "Saints Edit", sf::Style::Close|sf::Style::Resize, settings);
	app.UseVerticalSync(true);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		cout<<"ERROR starting GLEW: "<< glewGetErrorString(err);
	}
	
	
	//Start renderer after glewinit,GLSPprog needs it (could add init method for global renderer)
	Renderer rend;
	GUI gui;

	gui.init();
	gui.drawSplashScreen();
	app.Display();
	
	//sets up the terrain
	Terrain terrain(0);
	PathHandler ph;
	LightHandler lh;
	ParticleHandler particleHandler;
	particleHandler.init();
	lh.init();
	ph.init();
	terrain.setRadius(gui.getSliderRadius());
	terrain.setOpacity(gui.getSliderOpacity());
	gui.setSurfaceTexHandles(terrain.getSurfaceTexHandles());

	//the gui needs the textures for browsing
	gui.setTerrainInfo(terrain.getTerrInfo());
	rend.updateProjMatrix(width,height);
	rend.updateViewMatrix(cam.getViewMatrix());
	terrain.updateProjMatrix(width,height);
	terrain.updateViewMatrix(cam.getViewMatrix());
	ph.updateProjectionMatrix(width,height);
	ph.updateViewMatrix(cam.getViewMatrix());
	glViewport(0,0,width,height);

	MeshHandler mh("./models/");

	for(int i=0; i<mh.getNrOfMeshes(); i++)
	{
		Model tmp;
		tmp.setMesh(mh.getMeshInfo(i));
		tmp.setBoundingBox(mh.getBoundingBox(i));
		tmp.setMeshName(mh.getMeshName(i));
		tmp.setType(mh.getMeshType(i));
		gui.addDisplayModel(tmp);
	}


	sf::Event event;

	Model m;
	
	TwInit(TW_OPENGL_CORE,NULL);
	TwWindowSize(width,height);
	TwBar *myBar;
	myBar = TwNewBar("info");
	TwDefine(" info position='25 40' size='240 320' help='Information about the map etc.' refresh=0.1 ");
	TwAddButton(myBar, "gi", NULL, NULL, " label='General info' ");
	TwAddVarRO(myBar,"fps ", TW_TYPE_INT32, &fps,NULL);
	TwAddVarRO(myBar,"# Models ", TW_TYPE_INT32, &nrOfObjects,NULL);
	TwAddVarRO(myBar,"# Lights ", TW_TYPE_INT32, &nrOfLights,NULL);
	TwAddVarRO(myBar,"# Particlesystems ", TW_TYPE_INT32, &nrOfParticleSystems,NULL);
	TwAddVarRO(myBar,"# Paths ", TW_TYPE_INT32, &nrOfPaths,NULL);
	TwAddSeparator(myBar, "sep1", NULL);
	TwAddButton(myBar, "di", NULL, NULL, " label='Brush info' ");
	TwAddVarRO(myBar,"Radius", TW_TYPE_FLOAT, &tradius,NULL);
	TwAddVarRO(myBar,"Dropoff", TW_TYPE_FLOAT, &tdropoff,NULL);
	TwAddVarRO(myBar,"Opacity", TW_TYPE_FLOAT, &topacity,NULL);
	TwAddSeparator(myBar, "sep2", NULL);
	TwAddButton(myBar, "ci", NULL, NULL, " label='Color selected' ");
	TwAddVarRO(myBar,"Red", TW_TYPE_FLOAT, &gr,NULL);
	TwAddVarRO(myBar,"Green", TW_TYPE_FLOAT, &gg,NULL);
	TwAddVarRO(myBar,"Blue", TW_TYPE_FLOAT, &gb,NULL);

	while (app.IsOpened())
	{
		float normalisedx = 0;
		float normalisedy = 0;
		nrOfObjects=rend.getNrOfModels();
		nrOfLights=lh.getNrOfLights();
		tradius=gui.getSliderRadius();
		tdropoff=gui.getSliderDropoff();
		topacity=gui.getSliderOpacity();
		nrOfParticleSystems=particleHandler.getNrOfParticleSystems();
		nrOfPaths=ph.getNrOfPaths();
		gr=gui.getNormalizedColor().x;
		gg=gui.getNormalizedColor().y;
		gb=gui.getNormalizedColor().z;
		

		getNormalizedXY(app.GetInput().GetMouseX(), app.GetInput().GetMouseY(),width,height,normalisedx, normalisedy);
		//events
		int handled;
		while(app.GetEvent(event))
		{
			handled = TwEventSFML(&event, 1,6);
			if(!handled)
			{
				if(event.Type==sf::Event::Closed)
				{
					app.Close();
				}
				if((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape))
				{
					app.Close();
				}
				if(event.Type==sf::Event::MouseMoved)
				{
					if(gui.getState()==GUIstate::PAINT)
					{
						vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
						terrain.setWorldXY(cam.getPos(),ray);
					}
				}


				if(event.Type == sf::Event::Resized)
				{
					height = app.GetHeight();
					width = app.GetWidth();
					glViewport(0,0,width,height);
					rend.updateProjMatrix(width,height);
					terrain.updateProjMatrix(width,height);
					ph.updateProjectionMatrix(width,height);
				}
				if(event.Type == sf::Event::MouseWheelMoved)
				{
					if(event.MouseWheel.Delta>0)
						cam.zoomIn(event.MouseWheel.Delta*2);
					else
						cam.zoomOut(-event.MouseWheel.Delta*2);
					rend.updateViewMatrix(cam.getViewMatrix());
					terrain.updateViewMatrix(cam.getViewMatrix());
					ph.updateViewMatrix(cam.getViewMatrix());
				}

				if(event.Type == sf::Event::MouseButtonPressed)
				{
					if(event.MouseButton.Button==sf::Mouse::Right)
					{
						gui.showMenu(true);
						gui.setRightClickXY(normalisedx,normalisedy);
						particleHandler.unselectAllParticleModels();
					}
				}

				if(event.Type == sf::Event::MouseButtonPressed)
				{
					if(event.MouseButton.Button==sf::Mouse::Left)
					{
						gui.setLeftClick(normalisedx,normalisedy);
						terrain.setActiveTex(gui.getActiveTex());
						

						if(gui.checkDialogAnswer()=="GRID")
						{
							terrain.showHideGridMap();
							gui.resetDialogAns();
						}

						if(!gui.isSaveMapDialogUp()&&!gui.isLoadMapDialogUp()&&!gui.isNewMapDialogUp())
						{
							
							if(gui.getState()==GUIstate::PARTICLE)
							{
								if(gui.isInDrawWindow(normalisedx,normalisedy))
								{
									vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
									float x=-1;
									float z=1;
									terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
									if(gui.isPlacingParticleSystems())
									{
										if(x>0)
										{
											particleHandler.unselectAllParticleModels();
											Particle p;
											p=gui.getActiveParticleModel();
											p.setPos(vec3(x,gui.getActiveParticleModel().getPos().y,-z));
											particleHandler.addParticleModel(p);
											gui.setActiveParticleModel(particleHandler.getSelectedParticle());
										}
									}
									else
									{
										particleHandler.selectParticles(normalisedx,normalisedy,cam.getPos(),rend.getProjMatrix(),cam.getViewMatrix());
										gui.setActiveParticleModel(particleHandler.getSelectedParticle());
									}
								}
							}
							if(gui.getState()==GUIstate::ROAD)
							{
								if(gui.checkDialogAnswer()=="RS")
								{
									terrain.removeSelectedSurfaces();
									gui.resetDialogAns();
								}
							}
							if(gui.getState()==GUIstate::NONE)
							{
								if(gui.checkDialogAnswer()=="DEL") 
								{
									vector<Model> rm = rend.removeSelectedModels();
									lh.removeLightsBoundToModels(rm);
									vector<Model> tm =rend.getModels();
									terrain.recalcGridAroundModel(rm,tm);

									terrain.removeSelectedSurfaces();
									gui.resetDialogAns();
								}
							}
							if(gui.getState()==GUIstate::PARTICLE)
							{
								if(gui.checkDialogAnswer()=="DEL") 
								{
									particleHandler.removeSelectedParticles();
									gui.resetDialogAns();
								}
							}

							if(gui.getState()==GUIstate::PATH)
							{
								if(gui.checkDialogAnswer()=="DEL")
								{
									ph.removeSelectedPaths();
									gui.resetDialogAns();
								}
								if(gui.checkDialogAnswer()=="CRP")
								{
									ph.addPath();
									gui.resetDialogAns();
								}
								if(gui.isInDrawWindow(normalisedx,normalisedy))
								{
									if(gui.isSelectingRoad())
									{
										vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
										float x=-1;
										float z=1;
										terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
										if(x>0)
										{
											ph.addFlagToCurrentPath(vec3(x,0,-z));
										}
									}
									else
									{
										ph.selectPaths(normalisedx,normalisedy,cam.getPos());
									}
								}
							}
							if(gui.getState()==GUIstate::MODEL||gui.getState()==GUIstate::NONE)
							{
								if(gui.getState()==GUIstate::MODEL)
								{
									if(gui.isInDrawWindow(normalisedx,normalisedy))
									{
										vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
										float x=-1;
										float z=1;
										terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
										if(x>0)
										{
											if(m.getType()=="light")
											{
												m.bindId(bindCounter);
												vec3 lpos = m.getPos();
												lpos.y+=1;
												Light tmpLight;
												tmpLight.setColor(gui.getNormalizedColor());
												tmpLight.setPos(lpos);
												tmpLight.setRadius(gui.getSliderLightRadius());
												tmpLight.bindId(bindCounter);
												tmpLight.setContrast(gui.getContrast());
												tmpLight.setLightType(LightType::POINTLIGHTSHADOW);
												lh.addLight(tmpLight);
												bindCounter++;
											}
											rend.addModel(m);
											terrain.setWorldXY(cam.getPos(),ray);
											terrain.makeGridUnderModel(m);
										}
									}
								}
								if(gui.getState()==GUIstate::NONE)
								{
									if(gui.isInDrawWindow(normalisedx,normalisedy))
									{
										rend.selectModel(normalisedx,normalisedy,cam.getPos());

									}
								}
							}
							if(gui.getState()==GUIstate::ROAD)
							{
								vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
								terrain.setWorldXY(cam.getPos(),ray);
								terrain.selectTexSurfaces(0.5,cam.getPos(),ray);
							}
							
							if(gui.getState()==GUIstate::LIGHT)
							{
								if(gui.isInDrawWindow(normalisedx,normalisedy))
								{
									if(gui.isPlacingLightMode())
									{
										vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
										float x=-1;
										float z=1;
										terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
										if(x>0)
										{
											Light l = gui.getActiveLight();
											lh.deselectAllLights();
											l.setPos(vec3(x,l.getPos().y,-z));
											lh.addLight(l);
										}
									}
									else
									{
										int lightPos=lh.selectLight(normalisedx,normalisedy,cam.getPos(),rend.getProjMatrix(),cam.getViewMatrix());
										if(lightPos>=0)
										{
											Light tmpl = lh.getSelectedLight();
											gui.setSliderLightRadius(tmpl.getRadius());
											gui.setNormalizedColor(tmpl.getColor(),tmpl.getContrast());
											gui.setActiveLightModel(tmpl);
										}
									}
								}
								if(gui.checkDialogAnswer()=="DEL")
								{
									lh.removeSelectedLights();
								}
							}
						}

						if(gui.isSaveMapDialogUp())
						{
							if(gui.checkDialogAnswer()=="svOK")
							{
								save(gui.getInputText(),terrain,rend,ph,lh,particleHandler);
								gui.hideSaveMapDialog();
							}
							if(gui.checkDialogAnswer()=="svC")
							{
								gui.hideSaveMapDialog();
							}
						}
						if(gui.isNewMapDialogUp())
						{
							if(gui.checkDialogAnswer()=="nmCS")
							{
								terrain.createNewMap(0);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							
							if(gui.checkDialogAnswer()=="nmCM")
							{
								terrain.createNewMap(1);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							
							if(gui.checkDialogAnswer()=="nmCL")
							{
								terrain.createNewMap(2);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							if(gui.checkDialogAnswer()=="nmOK")
							{
								terrain.createNewMap(0);
								rend.clear();
								ph.clear();
								lh.clear();
								particleHandler.clear();
								gui.hideNewMapDialog();
							}
							if(gui.checkDialogAnswer()=="nmC")
							{
								gui.hideNewMapDialog();
							}
						}
						if(gui.isLoadMapDialogUp())
						{
							if(gui.checkDialogAnswer()=="lmOK")
							{
								load(gui.getInputText(),terrain,rend,ph,lh,particleHandler,mh);
								gui.hideLoadMapDialog();
							}
							if(gui.checkDialogAnswer()=="lmC")
							{
								gui.hideLoadMapDialog();
							}
						}
					}
				}

				if(event.Type == sf::Event::MouseButtonReleased)
				{
					if(event.MouseButton.Button==sf::Mouse::Right)
					{
						gui.showMenu(false);
						rend.unselectAllModels();
					}
				}
				//if the gui excpects text input
				if(gui.isInTextMode())
				{
					if(event.Type == sf::Event::KeyPressed)
					{
						if(int(event.Key.Code)>=97&&event.Key.Code<=122)
							gui.addChar(char(event.Key.Code));
					}
					if((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Back))
					{
						gui.removeChar();
					}
				}
			}
		}

		//realtime input
		
		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Left))
		{
			if(!handled)
			{
				if(!gui.isSaveMapDialogUp()&&!gui.isLoadMapDialogUp()&&!gui.isNewMapDialogUp())
				{
					if(gui.isInDrawWindow(normalisedx,normalisedy))
					{
						if(gui.getState()==GUIstate::PAINT)
						{
							terrain.setTerState(TerrState::PAINT);
							terrain.paint(cam.getPos(),inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos()));
						}
						if(gui.getState()==GUIstate::ROAD)
						{
							terrain.setTerState(TerrState::DRAWSURFACE);
							vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
							terrain.addSurface(cam.getPos(),ray, gui.getActiveSurfaceTexHandle());
						}
					} 
					else 
					{
						gui.moveSliders(normalisedx,normalisedy);
						if(gui.getState()==GUIstate::PAINT)
						{
							terrain.setRadius(gui.getSliderRadius());
							terrain.setOpacity(gui.getSliderOpacity());
							terrain.setDropoff(gui.getSliderDropoff());
						}
						if(gui.getState()==GUIstate::ROAD)
						{
							terrain.setRoadSpacing(gui.getRoadSliderSpacing());
							terrain.setRoadScale(gui.getRoadSliderScale());
						}
						if(gui.getState()==GUIstate::PARTICLE)
						{
							particleHandler.assignParticleNewParticle(gui.getActiveParticleModel());
						}
						
						if(gui.getState()==GUIstate::LIGHT)
							lh.assignLightAnotherLight(gui.getActiveLight());
					}
				}
			}
		}
		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Right))
		{
			gui.setMouseXY(normalisedx,normalisedy);
			terrain.deselectAllSurfaceTex();
			lh.deselectAllLights();
		}


		//if the user isnt in text mode, it should be able to move
		if(!gui.isInTextMode())
		{
			if(app.GetInput().IsKeyDown(sf::Key::Delete))
			{
				if(gui.getState()==GUIstate::MODEL||gui.getState()==GUIstate::NONE)
				{
					vector<Model> rm = rend.removeSelectedModels();
					lh.removeLightsBoundToModels(rm);
					vector<Model> tm =rend.getModels();
					terrain.recalcGridAroundModel(rm,tm);
				}
				if(gui.getState()==GUIstate::PATH)
				{
					ph.removeSelectedPaths();
				}
				if(gui.getState()==GUIstate::PARTICLE)
				{
					particleHandler.removeSelectedParticles();
				}
				if(gui.getState()==GUIstate::ROAD)
				{
					terrain.removeSelectedSurfaces();
				}
				if(gui.getState()==GUIstate::LIGHT)
				{
					lh.removeSelectedLights();
				}
				
			}
			if(gui.getState()==GUIstate::PAINT)
			{
					vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
					terrain.setWorldXY(cam.getPos(),ray);
			}
			if(app.GetInput().IsKeyDown(sf::Key::W))
			{
				cam.moveForeward(0.1);
			}
			if(app.GetInput().IsKeyDown(sf::Key::S))
			{
				cam.moveBackward(0.1);
			}
			if(app.GetInput().IsKeyDown(sf::Key::A))
			{
				cam.strafeLeft(0.1);
			}
			if(app.GetInput().IsKeyDown(sf::Key::D))
			{
				cam.strafeRight(0.1);
			}
			rend.updateViewMatrix(cam.getViewMatrix());
			terrain.updateViewMatrix(cam.getViewMatrix());
			ph.updateViewMatrix(cam.getViewMatrix());
			if(gui.getState()==GUIstate::MODEL)
			{
				if(app.GetInput().IsKeyDown(sf::Key::Q))
					gui.rotateActiveModelLeft(1.0f);

				if(app.GetInput().IsKeyDown(sf::Key::E))
					gui.rotateActiveModelRight(1.0f);
				if(app.GetInput().IsKeyDown(sf::Key::R))
					gui.raiseActiveModel(0.01);
				if(app.GetInput().IsKeyDown(sf::Key::F))
					gui.raiseActiveModel(-0.01);
			}
		}
		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Middle))
		{
			cam.rotateLeft(mousedx-app.GetInput().GetMouseX());
			cam.rotateUp(mousedy-app.GetInput().GetMouseY());
			rend.updateViewMatrix(cam.getViewMatrix());
			terrain.updateViewMatrix(cam.getViewMatrix());
			ph.updateViewMatrix(cam.getViewMatrix());
		}

		if(app.GetInput().IsMouseButtonDown(sf::Mouse::Right))
		{
			gui.showMenu(true);
			if(gui.getState()==GUIstate::PAINT)
			{
				terrain.showCircle();
			}
			else
				terrain.hideCircle();
		}
		//saves the position of the mouse, used for rotation
		mousedx=app.GetInput().GetMouseX();
		mousedy=app.GetInput().GetMouseY();

		glClearColor(0.75f, 0.87f, 0.85f, 0.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		terrain.draw();
		rend.draw();

		if(gui.getState()==GUIstate::PATH)
		{
			ph.drawPaths();
			if(gui.isSelectingRoad())
			{
				vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
				float x=-1;
				float z=1;
				terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
				if(x>0)
					ph.drawFlag(vec3(x,0,-z));
			}
		}
		if(gui.getState()==GUIstate::ROAD)
		{
			vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
			terrain.drawSurface(cam.getPos(),ray, gui.getActiveSurfaceTexHandle(),app.GetInput().IsMouseButtonDown(sf::Mouse::Left));
		}
		if(gui.getState()==GUIstate::LIGHT)
		{
			lh.drawLights(rend.getProjMatrix(),cam.getViewMatrix());
			
			if(gui.isPlacingLightMode())
			{
				vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
				float x=-1;
				float z=1;
				terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
				if(x>0)
				{
					Light l = gui.getActiveLight();
					l.setPos(vec3(x,l.getPos().y,-z));
					//l.select();
					lh.drawLight(rend.getProjMatrix(),cam.getViewMatrix(),l);
				}
			}
		}
		if(gui.getState()==GUIstate::MODEL &&gui.isInDrawWindow(normalisedx,normalisedy) )
		{
			vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
			float x=-1;
			float z=1;
			terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
			if(x>0)
			{
				m=gui.getActiveModel();
				m.setPos(vec3(x,gui.getActiveModel().getPos().y,-z));
				m.scaleXYZ(m.getScale());
				m.rotateY(m.getRot().y);
				rend.drawModel(m);
			}
		}
		if(gui.getState()==GUIstate::PARTICLE)
		{
			particleHandler.drawParticleModels(rend.getProjMatrix(),cam.getViewMatrix());
			
			if(gui.isPlacingParticleSystems())
			{
				vec3 ray = inters.getClickRay(app.GetInput().GetMouseX(),app.GetInput().GetMouseY(),cam.getViewMatrix(),rend.getProjMatrix(),width,height,cam.getPos());
				float x=-1;
				float z=1;
				terrain.rayIntersectTerrain(cam.getPos(), ray, x, z);
				if(x>0)
				{
					Particle p = gui.getActiveParticleModel();
					p.setPos(vec3(x,gui.getActiveParticleModel().getPos().y,-z));
					particleHandler.drawParticleModel(rend.getProjMatrix(),cam.getViewMatrix(),p);
				}
			}
		}
		gui.draw();

		fps= 1.0f/clock.GetElapsedTime();
		clock.Reset();
		TwDraw();
		app.Display();
	}
	TwTerminate();
	lh.free();
	
	return EXIT_SUCCESS;
}