Example #1
0
void	BasicGpuDemo::clientResetScene()
{
	/*
	exitPhysics();
	initPhysics();
	*/


	int i;
	for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
	{
		btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
		btRigidBody* body = btRigidBody::upcast(obj);
		if (body && body->getMotionState())
		{
			delete body->getMotionState();
		}
		m_dynamicsWorld->removeCollisionObject( obj );//reset will take care of this
		delete obj;
	}

	//delete collision shapes
	for (int j=0;j<m_collisionShapes.size();j++)
	{
		btCollisionShape* shape = m_collisionShapes[j];
		delete shape;
	}
	m_collisionShapes.clear();

	((b3GpuDynamicsWorld*)m_dynamicsWorld)->reset();

	createObjects();
}
Example #2
0
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent) {
    createObjects();
    createUI();
    createConnects();
    resize(800,600);
}
Example #3
0
/* main function - program entry point */
int main(int argc, char** argv)
{
    particleInit();
    createObjects();
    
	glutInit(&argc, argv);		//starts up GLUT
	
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	
	
	glutInitWindowSize(800, 800);
	glutInitWindowPosition(100, 100);
    
	glutCreateWindow("Assignment 2");	//creates the window
    
	glutDisplayFunc(display);	//registers "display" as the display callback function
	glutKeyboardFunc(keyboard);
	glutSpecialFunc(special);
    glutIdleFunc(idle);
    
	glEnable(GL_DEPTH_TEST);
	init();
    
	glutMainLoop();				//starts the event loop
    
	return(0);					//return may not be necessary on all compilers
}
Example #4
0
int allocWindow(DictionaryIterator *rdi) {
    Tuple *t;
  
    MyWindow *mw = malloc(sizeof(MyWindow));
    if (mw == NULL) {
      return -ENOMEM;
    }
    mw->myTextLayers = createObjects(myTextLayerDestructor);
    if (mw == NULL) {
      free(mw);
      return -ENOMEM;
    }
  
    for (int i = 0;i < NUM_BUTTONS; ++i) {
      mw->button_config[i] = 0;
    }
  
    mw->id = 0;
    mw->w = window_create();
    mw->appTimer = NULL;

  if (mw->w == NULL) {
      freeObjects(mw->myTextLayers);
      free(mw);
      return -ENOMEM;
    }  

    window_set_user_data(mw->w, mw);
  
    // Set handlers to manage the elements inside the Window
    window_set_window_handlers(mw->w, (WindowHandlers) {
      .load = window_load,
      .unload = window_unload
    });
ItemsTab::ItemsTab()
{
    createObjects();
    createConnexions();
    createInterface();
    createObjectsName();
}
Example #6
0
GLvoid TOpenGL_Form::initializeGL(GLsizei width, GLsizei height)
{
    GLfloat     maxObjectSize, aspect;
    GLdouble    near_plane;

    glClearIndex( (GLfloat)BLACK_INDEX);

    glClearDepth( 1.0 );

    glEnable(GL_DEPTH_TEST);

    glMatrixMode( GL_PROJECTION );
    aspect = (GLfloat) width / height;
    gluPerspective( 45.0, aspect, 3.0, 7.0 );
    glMatrixMode( GL_MODELVIEW );

    near_plane = 3.0;
    maxObjectSize = 3.0F;
    radius = near_plane + maxObjectSize/2.0;

    latitude = 0.0F;
    longitude = 0.0F;
    latinc = 6.0F;
    longinc = 2.5F;

    createObjects();
}
/* OpenGL code */
GLvoid initializeGL(GLsizei width, GLsizei height)
{
	ovrvision.CheckGPU();

	// Open with OpenGL sharing mode
	if (ovrvision.Open(0, OVR::Camprop::OV_CAMHD_FULL, 0) == 0) 
		puts("Can't open OvrvisionPro");

	//////////////////////////////////////////////////////////////////////////////
	// 肌色推定

	// Set scaling and size of scaled image
	size = ovrvision.SetSkinScale(2);
#ifdef HAND_TEXTURE
	cv::Mat images[2];
	images[0].create(size.height, size.width, CV_8UC4);
	images[1].create(size.height, size.width, CV_8UC4);

	// Estimate skin color range with 120 frames
	ovrvision.DetectHand(120);
	for (bool done = false; done == false;)
	{
		ovrvision.Capture(OVR::Camqt::OV_CAMQT_DMS);
		done = ovrvision.GetScaledImageRGBA(images[0].data, images[1].data);
		cv::waitKey(1);
		cv::imshow("L", images[0]);
		cv::imshow("R", images[1]);
	}
	cv::destroyAllWindows();
#endif // HAND_TEXTURE
	//////////////////////////////////////////////////////////////////////////////

	// GPU共有テクスチャー開始
	createObjects();
}
void MyDirectXWindow::init()
{
	mCamera.initializeOnDevice(mDevice);
	createDepthStencilState();
	createRasterizerStates();
	createBlendingStates();
	createObjects();
}
void project_readInput()
//
//  Input:   none
//  Output:  none
//  Purpose: retrieves project data from input file.
//
{
    // --- create hash tables for fast retrieval of objects by ID names
    createHashTables();

    // --- count number of objects in input file and create them
    input_countObjects();
    createObjects();

    // --- read project data from input file
    input_readData();
    if ( ErrorCode ) return;

    // --- establish starting & ending date/time
    StartDateTime = StartDate + StartTime;
    EndDateTime   = EndDate + EndTime;
    ReportStart   = ReportStartDate + ReportStartTime;
    ReportStart   = MAX(ReportStart, StartDateTime);

    // --- check for valid starting & ending date/times
    if ( EndDateTime <= StartDateTime )
    {
        report_writeErrorMsg(ERR_START_DATE, "");
    }
    else if ( EndDateTime <= ReportStart )
    {
        report_writeErrorMsg(ERR_REPORT_DATE, "");
    }
    else
    {
////  Following code segment was modified for release 5.1.009.  ////           //(5.1.009)
////
        // --- compute total duration of simulation in seconds
        TotalDuration = floor((EndDateTime - StartDateTime) * SECperDAY);

        // --- reporting step must be <= total duration
        if ( (double)ReportStep > TotalDuration )
        {
            ReportStep = (int)(TotalDuration);
        }

        // --- reporting step can't be < routing step
        if ( (double)ReportStep < RouteStep )
        {
            report_writeErrorMsg(ERR_REPORT_STEP, "");
        }

        // --- convert total duration to milliseconds
        TotalDuration *= 1000.0;
    }
////
}
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    createObjects();
    configureGUI();
    printIpAddresses();
    connectSlots();
}
Example #11
0
void Scene1105::update() {
	Scene::update();
	if (_countdown != 0 && (--_countdown == 0))
		createObjects();
	if (_isClosePanelDone && !isSoundPlaying(1))
		leaveScene(_leaveResult);
	if (_doMoveTeddy && !isSoundPlaying(2)) {
		sendMessage(_asTeddyBear, 0x2002, 0);
		_doMoveTeddy = false;
	}
}
Example #12
0
// *******
// * QYCBCRLabView
// *******
YCbCrLabView::YCbCrLabView(QWidget *parent) :
    QWidget(parent),
    m_pGraphicsView(NULL),
    m_pGraphicsViewOverlay(NULL),
    m_pGraphicsScene(NULL),
    m_pGraphicsSceneOverlay(NULL)
{
    createObjects();
    createActions();
    initObjects();
    createAnimations();
}
Example #13
0
int main()

{
	int num =20;
	srand(time(NULL));
	int knapSize=rand()%100;
 	object *items = createObjects(num);
	printf(" \n  KNAPSACK SIZE ::: %d ", knapSize);
	printObjects(items,num);
	int numEleminSack = 0 ; 
	object *result = getKnapSackObjects(items,num,knapSize,&numEleminSack);
	printResult(result,numEleminSack);
}	
Example #14
0
void TestWebChannel::benchClassInfo()
{
    QWebChannel channel;
    channel.connectTo(m_dummyTransport);

    QObject parent;
    const QHash<QString, QObject*> objects = createObjects(&parent);

    QBENCHMARK {
        foreach (const QObject *object, objects) {
            channel.d_func()->publisher->classInfoForObject(object, m_dummyTransport);
        }
    }
Example #15
0
void project_readInput()
//
//  Input:   none
//  Output:  none
//  Purpose: retrieves project data from input file.
//
{
    // --- create hash tables for fast retrieval of objects by ID names
    createHashTables();

    // --- count number of objects in input file and create them
    input_countObjects();
    createObjects();

    // --- read project data from input file
    input_readData();
    if ( ErrorCode ) return;

    // --- establish starting & ending date/time
    StartDateTime = StartDate + StartTime;
    EndDateTime   = EndDate + EndTime;
    ReportStart   = ReportStartDate + ReportStartTime;
    ReportStart   = MAX(ReportStart, StartDateTime);

    // --- check for valid starting & ending date/times
    if ( EndDateTime <= StartDateTime )
    {
        report_writeErrorMsg(ERR_START_DATE, "");
    }
    else if ( EndDateTime <= ReportStart )
    {
        report_writeErrorMsg(ERR_REPORT_DATE, "");
    }
    else
    {
        // --- compute total duration of simulation in milliseconds
        //     (add on 1 msec to account for any roundoff)
        TotalDuration = (EndDateTime - StartDateTime) * MSECperDAY;
        TotalDuration += 1.0;

        // --- reporting step must be <= total duration
        if ( (double)ReportStep > TotalDuration/1000.0 )
        {
            ReportStep = (int)(TotalDuration/1000.0);
        }
        if ( (float)ReportStep < RouteStep )
        {
            report_writeErrorMsg(ERR_REPORT_STEP, "");
        }
    }
}
Example #16
0
void	BasicGpuDemo::initPhysics()
{
	gUseLargeBatches = true;//for testing, this option is faster on NVIDIA GPUs
	//use the Bullet 2.x btQuickprof for profiling of Bullet 3.x
	b3SetCustomEnterProfileZoneFunc(CProfileManager::Start_Profile);
	b3SetCustomLeaveProfileZoneFunc(CProfileManager::Stop_Profile);

	setTexturing(true);
	setShadows(false);//too slow with many objects
	
	
	///collision configuration contains default setup for memory, collision setup
	m_collisionConfiguration = 0;
	//m_collisionConfiguration->setConvexConvexMultipointIterations();

	///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
	m_dispatcher = 0;

	m_broadphase = 0;

	///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
	
	m_solver = 0;

	initCL(-1,-1);


	if (!m_clData->m_clInitialized)
	{
		printf("Error: cannot initialize OpenCL\n");
		exit(0);
	}

	b3Config config;
	m_np = new b3GpuNarrowPhase(m_clData->m_clContext,m_clData->m_clDevice,m_clData->m_clQueue,config);
	m_bp = new b3GpuSapBroadphase(m_clData->m_clContext,m_clData->m_clDevice,m_clData->m_clQueue);
	
	b3DynamicBvhBroadphase* broadphaseDbvt = new b3DynamicBvhBroadphase(config.m_maxConvexBodies);
	
	m_rbp = new b3GpuRigidBodyPipeline(m_clData->m_clContext,m_clData->m_clDevice,m_clData->m_clQueue, m_np, m_bp,broadphaseDbvt,config);

	m_dynamicsWorld = new b3GpuDynamicsWorld(m_bp,m_np,m_rbp);
	
	m_dynamicsWorld->setDebugDrawer(&gDebugDraw);
	
	m_dynamicsWorld->setGravity(btVector3(0,-10,0));


	createObjects();
}
MyHorizontalLayoutWidget::MyHorizontalLayoutWidget(QWidget *parent) :
    QWidget(parent)
{
    createObjects();
    createLayout();
    setLayout(horizontalLayout);

    connect(graphicsScene, SIGNAL(signalBarchart()), this, SLOT(createItemsForBarchart()));
    connect(graphicsScene, SIGNAL(signalLinechart()), this, SLOT(createItemsForLinechart()));
    connect(graphicsScene, SIGNAL(signalPiechart()), this, SLOT(createItemsForPiechart()));
    connect(tableWidget, SIGNAL(cellChanged(int,int)), dynamic_cast<MyTabWidget *>(parentWidget()), SLOT(insertStarAfter()));
    connect(tableWidget, SIGNAL(rowAdded()), dynamic_cast<MyTabWidget *>(parentWidget()), SLOT(insertStarAfter()));
    connect(tableWidget, SIGNAL(rowDeleted()), dynamic_cast<MyTabWidget *>(parentWidget()), SLOT(insertStarAfter()));
}
bool BIControlGazeEngine::open(Searchable& config) {
        count=0;
		scaleFactorX=5;
		scaleFactorY=10;
		clampingThreshold=1;
		countLayer=2;

		if(!thread->start()){
			fprintf(stderr,"Error opening interfaces");
		}
	

		createObjects();
		openPortImage();

		port.open(getName("in")); 
		port0.open(getName("out0"));
		port1.open(getName("out1"));
        port2.open(getName("out2")); 
		portCmd.open(getName("inCmd"));
		portCmd.setStrict();
		
		img0=new ImageOf<PixelRgb>;
		img0->resize(320,240);
		img2=new ImageOf<PixelRgb>;
		img2->resize(320,240);
		ptr_inputImage2=new ImageOf<PixelRgb>;
		ptr_inputImage2->resize(320,240);

		runFreely=false;
		runClamped=false;

		//im_out = ippiMalloc_8u_C1(320,240,&psb);		
		//im_tmp_tmp= ippiMalloc_8u_C1(320,240,&psb);
		//im_tmp[0]=im_out;
		//im_tmp[1]=im_out;
		//im_tmp[2]=im_out;
		//red_tmp= ippiMalloc_8u_C1(320,240,&psb);
		//blue_tmp= ippiMalloc_8u_C1(320,240,&psb);
		//green_tmp= ippiMalloc_8u_C1(320,240,&psb);
		/*for(int i=0;i<320*240;i++){
			red_tmp[i]=255;
			blue_tmp[i]=255;
			green_tmp[i]=255;
		}*/
			

		engineModule=this;
        return true;
    }
Example #19
0
int CNetscapeFontModule::InitFontModule( )
{
	if( m_fontModuleStatus != FMSTATUS_NULL )
		return( FONTERR_OK );			// already initialized

	if( createObjects() ) 
		return( FONTERR_CreateObjectFail );

	if ( getInterfaces() )
		return( FONTERR_GetInterfacesFail );

    if ( registerFontDisplayer() )
		return( FONTERR_RegisterFontDisplayerFail );
    
	m_fontModuleStatus = FMSTATUS_IntialOK;

   	// create the RC object
	m_workingRC			= convertDC(NULL);

	return( FONTERR_OK );
}
Example #20
0
bool MapView::load()
{
	// Create scene manager.
	mManager = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_EXTERIOR_CLOSE);

	// Create fog.
	mManager->setFog(
		Ogre::FOG_LINEAR,
		Ogre::ColourValue(0.54f, 0.62f, 0.98f),
		0.0f, 768.0f, 1024.0f);

	// Create camera.
	mCamera = mManager->createCamera(mManager->getName());
	setIsOrthographic(mIsOrthographic);

	// Create light.
	mLight = mManager->createLight(mManager->getName());
	mLight->setType(Ogre::Light::LT_DIRECTIONAL);
	mLight->setDirection(Ogre::Vector3(0.1, -0.7, 0.3));
	mLight->setDiffuseColour(0.35, 0.35, 0.38);
	mLight->setSpecularColour(0.2, 0.2, 1);

	// Create ray query (mouse selection).
	mRayQuery = mManager->createRayQuery(Ogre::Ray());
	mRayQuery->setSortByDistance(true);

	// Create volume query (box selection).
	mVolumeQuery = mManager->createPlaneBoundedVolumeQuery(Ogre::PlaneBoundedVolumeList());

	mIsLoaded = true;

//	createTerrain();

	// Faster, but not editable.
	createTerrainFromFile();

	createObjects();

	return true;
}
Example #21
0
int resetWindows(DictionaryIterator *rdi) {
  MyWindow *mw;
  int rh;
  objects *tmpWindows;
  APP_LOG(APP_LOG_LEVEL_DEBUG, "resetWindows");
  
  // Doesn't currently work once windows exist.
  if (myWindows != NULL) {
    return 0;
  }
  
  tmpWindows = myWindows;
  myWindows = NULL;
  
  APP_LOG(APP_LOG_LEVEL_DEBUG, "About to create windows structure.");
  myWindows = createObjects(MyWindowDestructor);
  
  APP_LOG(APP_LOG_LEVEL_DEBUG, "objects created. ");
  // Need to create a window to keep the app from
  // exiting, so we might as well make it available.
  rh = allocWindow(NULL);
  APP_LOG(APP_LOG_LEVEL_DEBUG, "root window handle = %d", rh);
  if (rh != 0) {
    APP_LOG(APP_LOG_LEVEL_ERROR, "Root window handle %d != 0", rh);
  }
  mw = getWindowByHandle(rh);
  if (mw == NULL) {
    APP_LOG(APP_LOG_LEVEL_ERROR, "Root window null");
  }
  
  pushWindow(mw, rdi);
  
  if (tmpWindows) {
    freeObjects(tmpWindows);
  }

  return 0;
}
Example #22
0
int
test_object(int argc, char *argv[])
{

#ifdef PKIX_USER_OBJECT_TYPE
    PKIX_PL_Object *obj, *obj2, *obj3, *obj4;
    PKIX_UInt32 actualMinorVersion;
    PKIX_UInt32 j = 0;

    PKIX_TEST_STD_VARS();

    startTests("Objects");

    PKIX_TEST_EXPECT_NO_ERROR(
        PKIX_PL_NssContext_Create(0, PKIX_FALSE, NULL, &plContext));

    subTest("PKIX_PL_Object_Create");
    createObjects(&obj, &obj2, &obj3, &obj4);

    PKIX_TEST_EQ_HASH_TOSTR_DUP(obj, obj3, obj2, NULL, Object, PKIX_FALSE);

    subTest("PKIX_PL_Object_GetType");
    testGetType(obj, obj2, obj3);

    subTest("PKIX_PL_Object_Compare");
    testCompare(obj2, obj4);

    subTest("PKIX_PL_Object_Destroy");
    testDestroy(obj, obj2, obj3, obj4);

cleanup:

    PKIX_Shutdown(plContext);

    endTests("Objects");
#endif /* PKIX_USER_OBJECT_TYPE */
    return (0);
}
Example #23
0
//----------------------------------------------------------------------------------------
void BaseLevelBuilder::createBacks()
{
	ASSERT(m_level->m_levelDataReference != NULL, "error; level data is NULL");

	const char* pFileName =GameResourceManager::sharedManager()->storedFullPathFromRelativePath(
		(std::string("GameBin/allLevel.bin")).c_str());

	CATLObjectInfo info;
	info.Load(pFileName);


	std::vector<STileLayerInfo>  aa;
	sLevelData *bb = m_level->m_levelDataReference;

#if _WIN32
	#if _DEBUG
	{
		bool bHadMap = false;
		for(size_t i = 0; i < info.m_levels.size(); i++)
		{
			int id = atoi(info.m_levels[i]->name.c_str());
			if(id == m_level->m_levelDataReference->levelID)
			{
				bHadMap = true;
				break;
			}
		}
		if(!bHadMap)
		{
			ASSERT(0, "Can't find the map!!!");
		}
	}
	
	#endif

#endif

	for(size_t i = 0; i < info.m_levels.size(); i++)
	{
		int id = atoi(info.m_levels[i]->name.c_str());
		if(id == m_level->m_levelDataReference->levelID)
		{
			for(size_t j = 0; j < info.m_levels[i]->layers.size(); j++)
			{
				CATLObjectInfo::LAYER::TILED* pTiled = dynamic_cast<CATLObjectInfo::LAYER::TILED*>(info.m_levels[i]->layers[j]);
				if(pTiled != NULL)
				{
					STileLayerInfo tileInfo;
					tileInfo.isVisible = true;
					tileInfo.name = pTiled->mapFile;
					tileInfo.zorder = j;
					aa.push_back(tileInfo);
				}
			}
		}		
	}

	CCSprite* tileLayer = LevelObjectCreator::sCreateTileLayer(aa, bb);
	tileLayer->setPosition(ccp(0, 0));
	tileLayer->setVertexZ(-1.0f);
	m_level->addChild(tileLayer, MAP_Z_TILE_BACKGROUND);

	createObjects(info);
}
Example #24
0
bool ApplicationDesktop::init()
{
    if(SDL_Init(0) < 0){
        // ToDo: Error handling
    }

    // ToDo: Maybe this stuff will be moved back to renderer
    //       in this case ther would be a renderer for desktop and android

    if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0){ /* Initialize SDL's Video subsystem */
        LOG(ERROR) << "SDL Video subsystem could not been initialized.";
        return false;
    }

    //Request opengl 4.2 context.
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
 
    //Turn on double buffering with a 24bit Z buffer.
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    // R8G8B8A8
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);


    // Create the window
    mainwindow = SDL_CreateWindow("OpenGLTest", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        getScreenSize().x, getScreenSize().y, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
    if (!mainwindow){ /* Die if creation failed */
        LOG(ERROR) << "Main window could not been created" << std::endl;
        return false;
    }

   // create the OpenGL context
    maincontext = SDL_GL_CreateContext(mainwindow);

    // Swap in sync with the refresh rate
    SDL_GL_SetSwapInterval(1);

    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        LOG(ERROR) << "Glew initialization failed.";
        return false;
    }

    const GLubyte* versionStr = glGetString(GL_VERSION);

    LOG(INFO) << "OpenGL Version = " << versionStr;

    if( !getRenderer().init() ){
        return false;
    }

    createObjects();

    return true;
}
Example #25
0
	/* Incremental cached-based lookup method. */
void
_TDL_TDLStatement::cacheDescendInto ( int4    theChildIndex,
				      BOOLEAN theIsDescendingIntoBranch,
				      BOOLEAN theCanCreateNewNodes )
{
  _TDL_Snode    * newStatementData = (_TDL_Snode    *) NULL;
  _TDL_TreeNode * newTreeNode      = (_TDL_TreeNode *) NULL;
  _TDL_TreeNode * oldTreeNode      = getCachedTreeNodeNonConst();
  const char    * errorMessage     = (const char    *) NULL;


  if ( getTopmostTreeNode() == (_TDL_TreeNode *) NULL )
  {
    setCachedTreeNode ( (_TDL_TreeNode *) NULL );
  }

	/* Ie: getCachedTreeNode() == NULL */
  else if ( hasCachedTreeNode() == FALSE )
  {
	/* We've hit a bug. */
    TDL::getLogStream()
      << "[_TDL_TDLStatement:cacheDescendInto("
      << theChildIndex << "," 
      << ( (theIsDescendingIntoBranch == TRUE) ? "BRANCH,"   : "NODE," )
      << ( (theCanCreateNewNodes      == TRUE) ? "NEW-NODES" : "NO-new-nodes" )
      << "):\"" << getName() << "\"] Error:  "
      << "cachedTreeNode is NULL." << endl;
    return; /* Abort further action.  Do not try to create this node. */
  }

	/* If doDestroy() has been invoked, there will be a terminating *
	 * (destroyed) leaf-node created.  Don't descend past it.       */
  else if (   (     getCachedTreeNode() -> isTreeNodeBranch()      == FALSE   )
	   && (   ( getCachedTreeNode() -> getIsDestroyedSubtree() == TRUE  )
	       || (   ( getCachedTreeNode()
				     -> isSpawnStatementTreeNode() == TRUE )
		   && ( getCachedTreeNode()
				     -> getSpawnStatementTreeNodeConst()
				     -> isDestroyed()              == TRUE )) )
	   )
  {
    return; /* Abort further action.  Do not try to create this node. */
  }

	/* Singleton case. */
  else if (   ( theChildIndex             == _TDL_TreeNode::NO_ARRAY_INDEX )
	   && ( theIsDescendingIntoBranch == FALSE                         )
	   && ( getCachedTreeNode()       == getTopmostTreeNode()          )
	   && ( getCachedTreeNode()
		  -> isTreeNodeBranch()   == FALSE                         )
	   && ( getCachedTreeNode()
		  -> getArrayIndex()      == _TDL_TreeNode::NO_ARRAY_INDEX ) )
  {	/* The Singleton node already exists...                         *
	 * And there is nothing more to be done for a singleton lookup. */
    return;  /* All done. */
  }

	/* Otherwise we are descending to our target node. */

  else if ( getCachedTreeNode() -> isTreeNodeBranch() == FALSE )
  {
	/* We've hit a premature-endpoint bug. */
    TDL::getLogStream()
      << "[_TDL_TDLStatement:cacheDescendInto("
      << theChildIndex << "," 
      << ( (theIsDescendingIntoBranch == TRUE) ? "BRANCH,"   : "NODE," )
      << ( (theCanCreateNewNodes      == TRUE) ? "NEW-NODES" : "NO-new-nodes" )
      << "):\"" << getName() << "\"] Error:  "
      << "cachedTreeNode is *NOT* a branch!!!." << endl;
    setCachedTreeNode ( (_TDL_TreeNode *) NULL );
    return; /* Abort further action.  Do not try to create this node. */
  }

  else
  {
    setCachedTreeNode ( getCachedTreeNode()
			  -> getTreeNodeBranchConst()
			  -> getChildWithArrayIndex ( theChildIndex ) );
  }



	/* If we can create new tree members, and this member does not exist.*/
  if (   ( theCanCreateNewNodes == TRUE  )
      && ( hasCachedTreeNode()  == FALSE ) )
  {
	/* Do we need to create a topmost-TreeNodeBranch??. */
    if (   ( getTopmostTreeNode() == (_TDL_TreeNode *) NULL        )
	&& ( theChildIndex        != _TDL_TreeNode::NO_ARRAY_INDEX ) )
    {
      oldTreeNode = getCachedTopmostTreeNodeBranch ( TRUE );
    }

	/**************************************/
	/* Now we can create our new TreeNode */
	/**************************************/

    if (   ( theIsDescendingIntoBranch == TRUE                     )

	    /* Note:  Abort descending into complex tree's if we have been *
	     * destroyed.  Instead, create a destroyed child leaf ASAP.    */
	&& (   ( oldTreeNode == (_TDL_TreeNode *) NULL           )
	    || ( oldTreeNode -> getIsDestroyedSubtree() == FALSE ) )
	)
    {
      newTreeNode = new _TDL_TreeNodeBranch();
      addObjectToDelete  ( (_TDL_TreeNodeBranch *) newTreeNode );
    }
    else /* Ie:  Descending into a node. */
    {
      if ( createObjects ( newStatementData, newTreeNode ) == FAILURE )
      {
	errorMessage = "Unable to create child node.";
      }

      else if ( newStatementData == (_TDL_Snode *) NULL )
      {
	errorMessage = "newStatementData is NULL!";
      }

      else if ( newTreeNode == (_TDL_TreeNode *) NULL )
      {
	errorMessage = "newTreeNode is NULL!";
      }

      else if ( addDataObject ( newStatementData ) == FAILURE )
      {
	errorMessage = "Unable to addDataObject ( newStatementData ).";
      }

      if ( errorMessage != (const char *) NULL )
      {
	TDL::getLogStream()
	  << "[_TDL_TDLStatement:cacheDescendInto("
	  << theChildIndex << "):\"" << getName() << "\"]  "
	  << "Error:  " << errorMessage << endl;
	deleteObjects ( newStatementData, newTreeNode );
	return;
      }

	/* If we are creating a destroyed child-leaf, then destroy it! */
      if (   ( oldTreeNode != (_TDL_TreeNode *) NULL          )
	  && ( oldTreeNode -> getIsDestroyedSubtree() == TRUE ) )
      {
	newTreeNode -> destroy();
      }

    } /* IF ( theIsDescendingIntoBranch == TRUE ) ... ELSE ... */


		/* Configure the new TreeNode. */
    newTreeNode -> setArrayIndex ( theChildIndex );
    if ( getTopmostTreeNode() == (_TDL_TreeNode *) NULL )
    {
      setTopmostTreeNode ( newTreeNode );
      newTreeNode -> setParent ( (_TDL_TreeNodeBranch *) NULL );
    }
    else
    {
      oldTreeNode -> getTreeNodeBranch() -> addChild ( newTreeNode );
      newTreeNode -> setParent ( oldTreeNode -> getTreeNodeBranch() );
    }
    setCachedTreeNode ( newTreeNode );

  } /* IF ( theCanCreateNewNodes == TRUE &&  hasCachedTreeNode() == FALSE ) */
} /* void _TDL_TDLStatement::cacheDescendInto ( ... ) */
Example #26
0
osg::Node* createIsland(const osg::Vec3& center = osg::Vec3( 0,0,0 ), float radius = 8192 * 0.5 )
{
    float height = 1000;

    osg::ref_ptr<osg::Group> group = new osg::Group;

    osg::ref_ptr<osg::Image> heightMap = new osg::Image();
    heightMap->setImage( 64, 64, 1, 
                         GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 
                         orderBytes( heightTexture, sizeof( heightTexture ) ), 
                         osg::Image::NO_DELETE );

    osg::ref_ptr<osg::Image> colorMap = NULL; // osgDB::readImageFile("Images/colorMap.png");
    if ( !colorMap )
    {
        
        struct colorElevation 
        {
            colorElevation(unsigned int elev, const osg::Vec4ub& c):
                elevation(elev), color(c) {}
                
            unsigned int elevation; 
            osg::Vec4ub color;
        };
        
        colorElevation colorElevationMap[] =
            {
                colorElevation(0, osg::Vec4ub( 0, 128, 255, 255 )), 
                colorElevation(8, osg::Vec4ub( 192, 192, 128, 255 )),
                colorElevation(32, osg::Vec4ub( 0, 255, 0, 255 )),
                colorElevation(128, osg::Vec4ub( 128, 128, 128, 255 )),
                colorElevation(192, osg::Vec4ub( 96, 96, 96, 255 )),
                colorElevation(255, osg::Vec4ub( 255, 255, 255, 255 )),
                colorElevation(256, osg::Vec4ub( 255, 255, 255, 255 ))
            };        

        colorMap = new osg::Image();
        colorMap->allocateImage( heightMap->s(), heightMap->t(),1, GL_RGBA, GL_UNSIGNED_BYTE );
        unsigned int margin = 0;
        for( unsigned int r=margin; r< colorMap->t()-margin; ++r)
        {
            for(unsigned int c=margin; c< colorMap->s()-margin; ++c)
            {
                unsigned int h = *heightMap->data(c,r);
                unsigned int i = 0;
                while( h > colorElevationMap[i+1].elevation ) ++i;

                float f0 = float( h - colorElevationMap[i].elevation ) /
                           ( colorElevationMap[i+1].elevation - colorElevationMap[i].elevation );

                float f1 = 1.f - f0;

                               
                *(osg::Vec4ub*)colorMap->data(c,r) = 
                    colorElevationMap[i].color * f1 + colorElevationMap[i+1].color * f0;
            }
        }
    }

    osg::Vec3 origin(center - osg::Vec3( radius, radius, 0 ));
    origin.z() = 0.0;

    osg::HeightField* grid = new osg::HeightField;
    grid->allocate(heightMap->s(),heightMap->t());
    grid->setOrigin( origin );
    grid->setXInterval( radius*2.0f/(grid->getNumColumns()-1.0) );
    grid->setYInterval( radius*2.0f/(grid->getNumRows()-1.0) );

    for( unsigned int r=0;r<grid->getNumRows()-0;++r)
    {
        for(unsigned int c=0;c<grid->getNumColumns()-0;++c)
        {
            grid->setHeight( c, r, height * exp( *heightMap->data(c,r) / 255.f ) / exp( 1.0 ) );
        }
    }

    osg::ref_ptr<osgTerrain::TerrainTile> terrainTile = new osgTerrain::TerrainTile;

    osg::ref_ptr<osgTerrain::Locator> locator = new osgTerrain::Locator;
    locator->setCoordinateSystemType(osgTerrain::Locator::PROJECTED);
    locator->setTransformAsExtents(center.x()-radius, center.y()-radius, center.x()+radius, center.y()+radius);

    terrainTile->setLocator(locator.get());

    osg::ref_ptr<osgTerrain::HeightFieldLayer> hfl = new osgTerrain::HeightFieldLayer;
    hfl->setHeightField(grid);
    hfl->setLocator(locator.get());
    terrainTile->setElevationLayer(hfl.get());

    osg::ref_ptr<osgTerrain::ImageLayer> imageLayer = new osgTerrain::ImageLayer;
    imageLayer->setImage(colorMap.get());
    imageLayer->setLocator(locator.get());
    terrainTile->setColorLayer(0, imageLayer.get());

    osg::StateSet* stateset = terrainTile->getOrCreateStateSet();
    stateset->setAttributeAndModes( new osg::CullFace(), osg::StateAttribute::ON );

    group->addChild(terrainTile.get());
    
    group->addChild( createObjects( grid, 1 ) );

    return group.release();
}
Example #27
0
bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(mWindow->isClosed())
        return false;

    //run save code then shut down

    if(mShutDown)
    {
        if(mStats->isLoggedIn())
        {
            mStats->save();
        }
        return false;
    }
    // Need to capture/update each device
    mKeyboard->capture();
    mMouse->capture();
    if(!mMusic)
    {
        Mix_PauseMusic();
        Mix_Volume(-1, 0);
        if(bgm)
        {
             Mix_ResumeMusic();
        }
        if(soundeffect)
        {
             Mix_Volume(-1, 110);
        }
    }
    else if(mMusic)
    {
        Mix_ResumeMusic();
        Mix_Volume(-1, 110);
        if(!bgm)
        {
             Mix_PauseMusic();
        }
        if(!soundeffect)
        {
             Mix_Volume(-1, 0);
        }
    }
    if(mGameStart && !mInMenu)
    {
        if(player->levelFinished)
        {
            if(mStats->isLoggedIn())
            {
                mStats->update(mDifficulty, mLevel, mDeathCounter, mStopwatch->elapsedTime(), true);
            }
            calcNextLevel();
            deleteMap();
            createObjects();
            mLevelName->setCaption(gameMap->getName());
            mStopwatch->reset();
            mDeathCounter = 0;
            mNumDeaths->setCaption(patch::to_string(mDeathCounter) + " deaths");
            //SAVE AND LOAD
        }

        mPlayerHp->setProgress((player->health)/100.0);
        mPlayerHp->setCaption("current HP is " + patch::to_string(player->health) + "/100");
        mTime->setCaption(patch::to_string(int(mStopwatch->elapsedTime() / 100.0 ) / 10.0) + " seconds");
        Ogre::SceneNode* tem = mSceneMgr->getSceneNode("playerNode");    
        Ogre::Vector3 position = tem->getPosition();
        mCamera->setPosition(position.x , 300, position.z+200);
        if(gameMap->isPlayerAlive())
        {
            if(wisDown)
                gameMap->move(0);
            else if(disDown)
                gameMap->move(1);
            else if(sisDown)
                gameMap->move(2);
            else if(aisDown)
                gameMap->move(3);
            if(!mStopwatch->isRunning() && (sisDown || wisDown || disDown || aisDown))
            {
                mStopwatch->start();
            }
        }
        else
        {
            setupDeathMenu();  
            mTrayMgr->showCursor();
            mCanRespawn = true;
        }
        gameMap->simulate(evt.timeSinceLastFrame);  
        // mSimulator->stepSimulation(evt.timeSinceLastFrame, music2);
    }
    else if (!mGameStart) //should be the loadinglevel
    {
        if(!levelLoaded)
        {
            mDifficulty = 0;
            mLevel = 0;
            mOldDifficulty =0;
            createObjects();       
            levelLoaded = true;   
            Ogre::SceneNode* tem = mSceneMgr->getSceneNode("playerNode");    
            Ogre::Vector3 position = tem->getPosition();
            mCamera->setPosition(position.x , 300, position.z+300);        
        }
        else
        {
            gameMap->simulate(evt.timeSinceLastFrame);
        }
    }

    mTrayMgr->frameRenderingQueued(evt);

    if (!mTrayMgr->isDialogVisible())
    {
        mCameraMan->frameRenderingQueued(evt);   // If dialog isn't up, then update the camera
        if (mDetailsPanel->isVisible())          // If details panel is visible, then update its contents
        {
            mDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(mCamera->getDerivedPosition().x));
            mDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(mCamera->getDerivedPosition().y));
            mDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(mCamera->getDerivedPosition().z));
            mDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().w));
            mDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().x));
            mDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().y));
            mDetailsPanel->setParamValue(7, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().z));
        }
    }

    return true;
}
Example #28
0
void BaseApplication::buttonHit(OgreBites::Button* button)
{
    //over kill for now
    mTypingPassword = false;
    mTypingUsername = false;

    if(button->getName().compare("account") == 0)        
    {
        removeMainMenu();
        setupAccountMenu();      
        return;
    }
        if(button->getName().compare("create") == 0)
        {
            removeAccountMenu();
            setupCreateAccountMenu();
            return;
        }
            if(button->getName().compare("create uname") == 0)
            {
                mTypingUsername = true;
                mUsername = "";
                mUsernameButton->setCaption(mUsername);
                return;
            }
            if(button->getName().compare("create pass") == 0)
            {
                mTypingPassword = true;
                mPassword = "";
                mPasswordButton->setCaption(mPassword);
                return;
            }
            if(button->getName().compare("confirm account") == 0)
            {
                if(mUsername == "")
                {
                    mMenuLabel->setCaption("Please Enter a Username");
                    return;
                }
                if(mPassword == "")
                {
                    mMenuLabel->setCaption("Please Enter a Password");
                    return;
                }
                if(mStats->createAccount(mUsername, mPassword))
                {
                    mStats->save();
                    removeCreateAccountMenu();
                    setupMainMenu();
                }   
                else
                {
                    mMenuLabel->setCaption("Username is Taken :(");
                }

                return;
            }
            if(button->getName().compare("back from create account") == 0)
            {
                if(!mStats->isLoggedIn())
                {
                    mUsername = "";
                    mPassword = "";
                }
                removeCreateAccountMenu();
                setupAccountMenu();
                return;
            }
        if(button->getName().compare("login") == 0)
        {
            removeAccountMenu();
            setupLoginMenu();
            return;
        }
            if(button->getName().compare("login uname") == 0)
            {
                mTypingUsername = true;
                mUsername = "";
                mUsernameButton->setCaption(mUsername);
                return;
            }
            if(button->getName().compare("login pass") == 0)
            {
                mTypingPassword = true;
                mPassword = "";
                mPasswordButton->setCaption(mPassword);
                return;
            }
            if(button->getName().compare("login to account") == 0)
            {
                if(mUsername == "")
                {
                    mMenuLabel->setCaption("Please Enter a Username");
                    return;
                }
                if(mPassword == "")
                {
                    mMenuLabel->setCaption("Please Enter a Password");
                    return;
                }
                if(mStats->login(mUsername, mPassword))
                {
                    removeLoginMenu();
                    setupMainMenu();
                }   
                else
                {
                    mMenuLabel->setCaption("Failed to Log in :(");
                }

                return;
            }
            if(button->getName().compare("back from login") == 0)
            {
                if(!mStats->isLoggedIn())
                {
                    mUsername = "";
                    mPassword = "";
                }
                removeLoginMenu();
                setupAccountMenu();
                return;
            }
        if(button->getName().compare("logout") == 0)
        {
            mStats->logout();
            mUsername = "";
            mPassword = "";
            removeAccountMenu();
            setupAccountMenu();
            return;
        }
        if(button->getName().compare("backfromsetup") == 0)
        {
            removeAccountMenu();
            setupMainMenu();
            return;
        }
    if(button->getName().compare("start") == 0)        
    {
        removeMainMenu();
        setupDifficultyMenu();      
        return;
    }       
    else if(button->getName().compare("sound") == 0 )
    {  
        removeMainMenu();
        setupSoundMenu();  
        return;
    }
    else if(button->getName().compare("help") == 0 )
    {  
        removeMainMenu();
        setupHelpMenu();  
        return;
    }
        else if(button->getName().compare("helpToMain") == 0 )
        {  
            removeHelpMenu();
            setupMainMenu();  
            return;
        }
        else if(button->getName().compare("control") == 0 )
        {  
            removeHelpMenu();
            setupControlMenu();  
            return;
        }
            else if(button->getName().compare("back from control") == 0 )
            {  
                removeControlMenu();
                setupHelpMenu();  
                return;
            }
        else if(button->getName().compare("info") == 0)
        {
            removeHelpMenu();
            setupInfoMenu();
            return;
        }
            else if(button->getName().compare("back from info") == 0 )
            {  
                removeInfoMenu();
                setupHelpMenu();  
                return;
            }
    else if(button->getName().compare("credit") == 0)
    {
        removeMainMenu(); 
        deleteMap(); // delete loading level
        mDifficulty = 5;
        mLevel = 1; 
        createObjects();              
        mGameStart= true;        
        mTrayMgr->hideCursor();      
        setupGUI(gameMap->getName()); 
        return;

    }
    else if(button->getName().compare("quit") == 0)
    {
        removeMainMenu();
        if(mStats->isLoggedIn())
        {
            mStats->save();
        }
        mShutDown = true;
    }
    else if(button->getName().compare("on") == 0 )
    {
        mMusic = true;
        bgm = true;
        soundeffect =true;        
        return;
    }
    else if(button->getName().compare("off") == 0 )
    {  
        mMusic = false;
        bgm = false;
        soundeffect =false;       
        return;
    }
    else if(button->getName().compare("bgm on") == 0 )
    {
        bgm = true;        
        return;
    }
    else if(button->getName().compare("bgm off") == 0 )
    {  
        bgm = false;       
        return;
    }
    else if(button->getName().compare("effect on") == 0 )
    {
        soundeffect = true;        
        return;
    }
    else if(button->getName().compare("effect off") == 0 )
    {  
        soundeffect = false;       
        return;
    }
    else if(button->getName().compare("sound to main") == 0 )
    {
        removeSoundMenu();         
        setupMainMenu();
        return;
    }
    for(int x = 1; x <= Level::numDifficulties(); x++)
    {
        // for clicking on the difficulty and loading the levels
        if(button->getName().compare(Level::difficultyName(x)) == 0 )       
        {       
            removeDifficultyMenu();
            setupLevelSelect(x);
            return;
        }
        // for clicking back to select difficulty
        if(button->getName().compare("back to select difficulty " + Level::difficultyName(x)) == 0)
        {
            removeLevelSelect(x);
            setupDifficultyMenu();   
            return;
        }
    }
    if(button->getName().compare("back to main menu") == 0 )
    {
        removeDifficultyMenu();
        setupMainMenu(); 
        return;
    }
    for(int x = 1; x <= Level::numDifficulties(); x++)
    {
        for(int y = 1; y <= Level::numLevels(x); y++)
        {
            std::string name = Level::difficultyName(x) + " " + patch::to_string(y);
            if(button->getName().compare(name) == 0)
            {
                removeLevelSelect(x);
                deleteMap();
                mDifficulty =x;
                mLevel = y; 
                createObjects();              
                mGameStart = true;        
                mTrayMgr->hideCursor();      
                setupGUI(gameMap->getName()); 
                return;   
            }
        }
    }


    if(button->getName().compare("quit level") == 0 )
    {
        removeLevelMenu();
        deleteMap();
        mGameStart = false;
        setupMainMenu();
        levelLoaded = false;
        music = Mix_LoadMUS("Music/0/bgm2.mp3");
        Mix_PlayMusic(music,-1);
        if(mStats->isLoggedIn())
        {
            mStats->update(mDifficulty, mLevel, mDeathCounter, mStopwatch->elapsedTime(), false);
        }
        mStopwatch->reset();
        mDeathCounter = 0;
        return;
    }
    else if(button->getName().compare("resume level") == 0 )
    {
        removeLevelMenu();
        setupGUI(gameMap->getName());
        mStopwatch->unpause();
        return;
    }
    else if(button->getName().compare("surrender") == 0 )
    {
        removeDeathMenu();
        deleteMap();
        mGameStart = false;
        setupMainMenu();
        levelLoaded = false;
        music = Mix_LoadMUS("Music/0/bgm2.mp3");
        Mix_PlayMusic(music,-1);
        if(mStats->isLoggedIn())
        {
            mStats->update(mDifficulty, mLevel, mDeathCounter+1, mStopwatch->elapsedTime(), false);
        }
        mStopwatch->reset();
        mDeathCounter = 0;
        //SAVE AND LOAD
        return;
    }
    else if(button->getName().compare("better") == 0 )
    {
        mCanRespawn = false;
        removeDeathMenu();
        setupGUI(gameMap->getName());
        gameMap->respawn();
        mDeathCounter += 1;
        if(mDeathCounter == 1)
        {
            mNumDeaths->setCaption(patch::to_string(mDeathCounter) + " death");
        }
        else
        {
            mNumDeaths->setCaption(patch::to_string(mDeathCounter) + " deaths");
        }
        mTrayMgr->hideCursor();
        return;
    }


   
}
Example #29
0
int main(){
	//random number generator seeded
	srand(time(NULL));

	//sdl screen info and sprite data
	SDLDrawMetaData sdl;
	SpriteData sprites;

	//setup camera
	cam = new camera();
	camBoundingBox = createCamBB();
	//move above floor!
	cam->Location[1]+=0.2;
	//camera forces we will use. Keyboard input will modify these values and move us
	shared_ptr<Force> UpForce = cam->addForce(cam->Up,0);
	shared_ptr<Force> ForwardForce = cam->addForce(cam->Target,0);
	shared_ptr<Force> RightForce = cam->addForce(cam->Right,0);

	draw_AABB=true;
	draw_SOM=true;
	draw_HGrid=true;

	//create 10 random objects to test hierarchal bounding tree
	MyObjects = createObjects();
	//add floor to scene
	MyObjects->insert(createFloor());
	MyGrid.Add(*MyObjects);

	//self organizing map creation
	TSPFileReader trainingVectorFactory;
	vector<neuron> TrainingNeurons;
	//we will use 3d vectors and a colour array to demo
	TrainingNeurons = trainingVectorFactory.retrieveTrainingVectors("./maps/RGB.tsp");
	//SOM will eventually be scaled between 0 and 1. here we define 20x20 grid
	float meshSize = 0.05;
	mySOM =  initializeNewSOM(meshSize,0.0,255.0);
	//SOM training counter
	int trainingIterations = 100;
	int iTrain = trainingIterations;
	SOMbricks = createSOMBricks(meshSize);
	//add our som bricks to our spatial partitioning structure (collision detection)
	MyGrid.Add(*SOMbricks);
	MyGrid.Add(camBoundingBox);

	init(sdl.screen_w,sdl.screen_h);
	//cube texture
	SDL_Surface* cobblestoneFloor;
	SDL_Render::loadimage("./sprites/6903.jpg" ,&cobblestoneFloor);	
	
	//transfer SDL surface into openGL texture
	nOfColors = cobblestoneFloor->format->BytesPerPixel;
	if(nOfColors == 4){
		if(cobblestoneFloor->format->Rmask = 0x000000ff){
			texture_format = GL_RGBA;
		}else{
			texture_format = GL_BGRA;
		}
	}else if(nOfColors == 3){
		if(cobblestoneFloor->format->Rmask = 0x000000ff){
			texture_format = GL_RGB;
		}else{
			texture_format = GL_BGR;
		}
		
	}
	//openGL texturing and depth map configuration
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glDepthFunc(GL_LEQUAL);
	glDepthRange(0.0f,1.0f);

	glBindTexture(GL_TEXTURE_2D,1);
	glPixelStorei(GL_UNPACK_ALIGNMENT,1);

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT);
	glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);

	glTexImage2D( GL_TEXTURE_2D,0,nOfColors,cobblestoneFloor->w,cobblestoneFloor->h,0,texture_format,GL_UNSIGNED_BYTE,cobblestoneFloor->pixels);
	

	//sdl cursor initialization
	mouseX=0;
	mouseY=0;
	SDL_Event event;
	SDL_ShowCursor(0);
	SDL_WM_GrabInput(SDL_GRAB_ON);
	bool quit = false;



	//game loop
	while(!quit){

		//keyboard/mouse handler
		while(SDL_PollEvent(&event)){
			if(event.type==SDL_QUIT){
				quit=true;
			}else if(event.type == SDL_KEYDOWN){
				switch(event.key.keysym.sym){
					case SDLK_w:ForwardForce->magnitude += 0.1 ; break;
					case SDLK_s:ForwardForce->magnitude -= 0.1 ; break;
					case SDLK_d:RightForce->magnitude -= 0.1 ; break;
					case SDLK_a:RightForce->magnitude += 0.1 ; break;
					case SDLK_e:UpForce->magnitude -= 0.1 ; break;
					case SDLK_q:UpForce->magnitude +=0.1 ; break;
					case SDLK_i:cam->rotateX(5) ; break;
					case SDLK_k:cam->rotateX(-5) ; break;
					case SDLK_j:cam->rotateY(5) ; break;
					case SDLK_l:cam->rotateY(-5) ; break;
					case SDLK_o:cam->rotateZ(5) ; break;
					case SDLK_u:cam->rotateZ(-5) ; break;
					case SDLK_b:draw_AABB=!draw_AABB ; break;
					case SDLK_n:draw_SOM=!draw_SOM ; break;
					case SDLK_m:draw_HGrid=!draw_HGrid ; break;
					case SDLK_z:quit=true; break;
				}
			}else if(event.type == SDL_KEYUP){
				switch(event.key.keysym.sym){
					case SDLK_w:ForwardForce->magnitude -= 0.1 ; break;
					case SDLK_s:ForwardForce->magnitude += 0.1 ; break;
					case SDLK_d:RightForce->magnitude += 0.1 ; break;
					case SDLK_a:RightForce->magnitude -= 0.1 ; break;
					case SDLK_e:UpForce->magnitude += 0.1 ; break;
					case SDLK_q:UpForce->magnitude -=0.1 ; break;
				}
			}else if(event.type == SDL_MOUSEMOTION ){
                //		MouseMove(event.motion.xrel, event.motion.yrel, sdl.screen_h/2,sdl.screen_w/2);
			}


		}
		update();
		if(iTrain>0){
			iTrain--;
			mySOM = train(mySOM,TrainingNeurons,iTrain,trainingIterations,false);
		}
		render();
	}

	return 0;

}
Example #30
0
void Level::restart() {
    world->reset();
    createObjects();
    state = LevelState::Playing;
}