Example #1
0
void* init( const void* params){
	xen::ModuleApiGraphics* mod_ren = xen::getModuleApi<xen::ModuleApiGraphics>();
	xen::ModuleApiWindow*   mod_win = xen::getModuleApi<xen::ModuleApiWindow>();
	XenAssert(mod_ren != nullptr, "Graphics module must be loaded before cornell-box");
	XenAssert(mod_win != nullptr, "Window module must be loaded before cornell-box");

	state = (State*)xen::kernelAlloc(sizeof(State) + xen::kilobytes(1));
	state->arena.start = xen::ptrGetAdvanced(state, sizeof(State));
	state->arena.end   = xen::ptrGetAdvanced(state->arena.start, xen::kilobytes(1));
	state->arena.next_byte = state->arena.start;

	state->window        = mod_win->createWindow({600, 600}, "cornell-box");
	state->window_target = mod_ren->createWindowRenderTarget(state->window);

	initCamera();
	initSceneLights();
	initMeshes(mod_ren);
	initRenderCommands(mod_ren, state->arena);

	return state;
}
Example #2
0
//----------------------------------------------------------
// Begin main functions
int GzNewRender(GzRender **render, GzDisplay	*display)
{
/*  
- malloc a renderer struct 
- setup Xsp and anything only done once 
- save the pointer to display 
- init default camera 
*/ 
	//init a renderer struct
	if(render == NULL || display == NULL){
		errorCall("GzNewRender" , "render == NULL or display == NULL");
		return GZ_FAILURE;
	}
	
	*render = (GzRender*)malloc(sizeof(GzRender));
	(*render)->display = display;
	
	//init default camera
	initCamera((*render) -> camera);
	
	return GZ_SUCCESS;
}
Example #3
0
void CameraSensor::threadMain() {
	if (cam == 0)
		return;

	threadInit();

	robottime_t lastFrameTime = 0;

	// loop until we quit
	while (isRunning()) {
		// make sure we are still connected to a camera
		if (false == cam->isOpen()) {
			WARNING("Camera not active, trying to re-initiate");
			if (false == initCamera()) {
				ERROR("No camera ...");
				delay(250*milliseconds);
				continue;
			}
		}

		// update frame
		cs.enter();
		bool imageCaptured = cam->capture();
		cs.leave();

		if (imageCaptured) {
			// notify any other objects that want to know about this new image for processing
			services.getEvents().trigger(EVT_IMAGE_CAPTURED, image);

			lastFrameTime = getCurrentTime();

			// save image if required
			handleImageSaving();
		} else if (lastFrameTime + 3000*milliseconds < getCurrentTime()) {
			ERROR("Did not receive image data for several seconds!");
			// TODO: trigger watchdog in competition mode
		}
	}
}
/*------------------------------------------------------------------------
 * OpenGL main routine
 */
int main(int argc, char *argv[])
{
   int i;

   for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "-f") == 0) {
		  if ( i+1 >= argc ) {
			  printf("-f: missing data file.\n");
			  return 1;
		  }
		  datafile = GL_TRUE;
		  break;
      }
      else {
		 printf("Warrning: unknown parameter: %s\n", argv[i]);
	  }
   }

   if ( datafile ) {
	   if ( 0 != tubes.loadGeometry( argv[argc-1] ) ) {
		   return 1;
	   }
	   tubes.getExtent( Xminmax, Yminmax, Zminmax );
   }

   glutInit (&argc, argv);
   glutInitWindowPosition ( 0, 0 );
   glutInitWindowSize ( 1920, 1080 );
   glutInitDisplayMode	( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STEREO );
   glutCreateWindow ("brain stereoscopic rendering for visweek");
   initCamera();
   glutReshapeFunc(reshape);
   glutDisplayFunc(draw);
   glutKeyboardFunc(keyFunc);
   glutMainLoop();

   return 0;
}
Example #5
0
int main() {
	srand(time(NULL));
	if(!initCamera()) {
		fprintf(stderr, "Camera initialization failed.\n");
		return EXIT_FAILURE;
	}
	pthread_t cameraThread;
	if(pthread_create(&cameraThread, NULL, cameraLoop, NULL)) {
		fprintf(stderr, "pthread_create failed.\n");
		return EXIT_FAILURE;
	}
	
	usleep(30);
	
	/* We wait two frames for the camera to initialize itself. */
	for(int i = 0; i < 2; i++) {
		pthread_mutex_lock(&kinectMutex);
		while(!colorUpdate || !depthUpdate) {
			pthread_cond_wait(&kinectSignal, &kinectMutex);
		}
		pthread_mutex_unlock(&kinectMutex);
		
		swapColorBuffers();
		swapDepthBuffers();
	}
	
	createModel();

	pthread_t runThread;
	if(pthread_create(&runThread, NULL, runLoop, NULL)) {
		fprintf(stderr, "pthread_create failed.\n");
		return EXIT_FAILURE;
	}
	
	renderLoop();
	
	return EXIT_SUCCESS;
}
void actionButtonsMenu(){
	if(g_keys[' ']){
		initCamera();
		if(itemMenuSelect<5){
			std::ostringstream oss;
			oss << itemMenuSelect;
			std::string result = oss.str();
			if(result == "4"){//mode hardcore sélectionné
				loadSave("0");
				initVarLevel();
				loadPhysicsHardcore();
			}
			else{//un des trois slots de sauvegarde
				loadSave(result);
				itemMenuDroiteSelect = 1;
				initVarLevel();
				loadPhysicsNormal();
			}
		}
		else if(itemMenuSelect == 5){
			bestScores = true;
		}
		else if(itemMenuSelect == 6){
			commandes = true;
		}
		else if(itemMenuSelect == 7){
			credits = true;
		}
		menu = false;
	}
	else if(g_keys['z'] && itemMenuSelect >1){
		itemMenuSelect -=1;
		Sleep(200);
	}else if(g_keys['s'] && itemMenuSelect <7){
		itemMenuSelect +=1;
		Sleep(200);
	}
}
bool photoController::checkCameraDetection()
{
	START_CHRONOMETER();
	CameraList *list;
	gp_list_new (&list);
	int ret = auto_detect_action(list, context);
	DEBUG_PRINTF(V_MESSAGE, "gp_camera_autodetect return %d wanted %d\n", ret, GP_OK);
	if(ret >= GP_OK)
	{
		int cameraCount = gp_list_count(list);
		DEBUG_PRINTF(V_MESSAGE, "Camera count: %d\n", cameraCount);
		if(cameraCount > 0)
		{
			DEBUG_PRINTF(V_MESSAGE, "Got a camera\n");
			camera_detected = true;
			if(!camera && !initCamera())
			{
				camera = NULL;
			}
		}
	}
	else
	{
		if(camera)
		{
			DEBUG_PRINTF(V_MESSAGE, "Exit camera\n");
			gp_camera_exit(camera, context);
			camera = NULL;
		}
		camera_detected = false;
		DEBUG_PRINTF(V_MESSAGE, "Error while getting camera list\n");
	}
	
	gp_list_unref (list);
	STOP_CHRONOMETER("Camera detection");
	return camera_detected;
}
Example #8
0
void GLWidget::initializeGL()
{
    ResourceLoader::initializeGlew();
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glClearColor(0.5f, 0.5f, 0.5f, 0.0f);
    
    // Initialize shader programs.
    for (auto program = m_programs.begin(); program != m_programs.end(); ++program)
        (*program)->create();
    
    // Initialize textures.
    m_noiseTexture->createColorTexture(":/images/noise128.jpg", GL_LINEAR, GL_LINEAR);
    
    // Initialize framebuffers.
    int shadowMapRes = 2048;
    glm::vec2 finalSize = glm::vec2(2 * width(), 2 * height());
    for (auto framebuffer = m_framebuffers.begin(); framebuffer != m_framebuffers.end(); ++framebuffer)
        (*framebuffer)->create();
    m_hairShadowFramebuffer->generateDepthTexture(shadowMapRes, shadowMapRes, GL_NEAREST, GL_NEAREST);
    m_meshShadowFramebuffer->generateDepthTexture(shadowMapRes, shadowMapRes, GL_LINEAR, GL_LINEAR);
    m_opacityMapFramebuffer->generateColorTexture(shadowMapRes, shadowMapRes, GL_NEAREST, GL_NEAREST);
    m_opacityMapFramebuffer->generateDepthBuffer(shadowMapRes, shadowMapRes);
    m_finalFramebuffer->generateColorTexture(finalSize.x, finalSize.y, GL_LINEAR, GL_LINEAR);
    m_finalFramebuffer->generateDepthBuffer(finalSize.x, finalSize.y);
    m_depthPeel0Framebuffer->generateColorTexture(finalSize.x, finalSize.y, GL_LINEAR, GL_LINEAR);
    m_depthPeel0Framebuffer->generateDepthTexture(finalSize.x, finalSize.y, GL_NEAREST, GL_NEAREST);
    m_depthPeel1Framebuffer->generateColorTexture(finalSize.x, finalSize.y, GL_LINEAR, GL_LINEAR);
    m_depthPeel1Framebuffer->generateDepthBuffer(finalSize.x, finalSize.y);
    
    // Initialize simulation.
    initSimulation();
    
    initCamera();

    ErrorChecker::printGLErrors("end of initializeGL");
}
Example #9
0
void init(int w, int h) {

  /* OpenGL setup */
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
  glClearColor(0.0, 0.0, 0.0, 0.0);  

  /* low-level graphics setup */
  initCanvas(w,h);

  /* raytracer setup */
  initCamera(w,h);
  initScene();
  initLight();

  printf("DEPTH = %d. Computing the scene...          ",depth);
  list = glGenLists(1);
  glNewList(list, GL_COMPILE);
    drawScene();
    flushCanvas();
  glEndList();
  printf("Done\n");
}
Example #10
0
void nextCameraType(void) {
	int i;
	int current_cam_type = getSettingi("camType");
	int new_cam_type = (current_cam_type + 1) % CAM_COUNT;
	  
	setSettingi("camType", new_cam_type);

	/* update the cached setting */
	gSettingsCache.camType = new_cam_type;
	  
	for (i = 0; i < game->players; i++) {
		if (game->player[i].ai->active == AI_HUMAN) {
			initCamera(&gPlayerVisuals[i].camera, game->player[i].data, new_cam_type);
		}
	}

	if (getSettingi("debug_output")) {
		switch (new_cam_type) {
		case 0 :
			displayMessage(TO_CONSOLE, "[camera] Circling Camera");
			break;
		case 1 :
			displayMessage(TO_CONSOLE, "[camera] Behind Camera");
			break;
		case 2 :
			displayMessage(TO_CONSOLE, "[camera] Cockpit Camera");
			break;
		case 3 :
			displayMessage(TO_CONSOLE, "[camera] Mouse Camera");
			break;
		case 4 :
			displayMessage(TO_CONSOLE, "[camera] Offset Camera");
			break;
		}
	}
}
Example #11
0
/*!
  Set the camera format and video mode.
  This method has to be called before open().

  \param format : Camera video format.
  \param mode : Camera video mode.

  See the following table for the correspondances between the input
  format and mode and the resulting video color coding.

  <TABLE BORDER="1">
  <TR><TH> Format </TH><TH> Mode </TH><TH> (H) x (W) </TH><TH> Color  </TH></TR>
  <TR><TD>   0    </TD><TD>  0   </TD><TD> 160 x 120 </TD><TD> YUV444 </TD></TR>
  <TR><TD>   0    </TD><TD>  1   </TD><TD> 320 x 240 </TD><TD> YUV422 </TD></TR>
  <TR><TD>   0    </TD><TD>  2   </TD><TD> 640 x 480 </TD><TD> YUV411 </TD></TR>
  <TR><TD>   0    </TD><TD>  3   </TD><TD> 640 x 480 </TD><TD> YUV422 </TD></TR>
  <TR><TD>   0    </TD><TD>  4   </TD><TD> 640 x 480 </TD><TD>  RGB8  </TD></TR>
  <TR><TD>   0    </TD><TD>  5   </TD><TD> 640 x 480 </TD><TD>  MONO8 </TD></TR>
  <TR><TD>   0    </TD><TD>  6   </TD><TD> 640 x 480 </TD><TD> MONO16 </TD></TR>
  <TR><TD>   1    </TD><TD>  0   </TD><TD> 800 x 600 </TD><TD> YUV422 </TD></TR>
  <TR><TD>   1    </TD><TD>  1   </TD><TD> 800 x 600 </TD><TD>  RGB8  </TD></TR>
  <TR><TD>   1    </TD><TD>  2   </TD><TD> 800 x 600 </TD><TD>  MONO8 </TD></TR>
  <TR><TD>   1    </TD><TD>  3   </TD><TD>1024 x 768 </TD><TD> YUV422 </TD></TR>
  <TR><TD>   1    </TD><TD>  4   </TD><TD>1024 x 768 </TD><TD>  RGB8  </TD></TR>
  <TR><TD>   1    </TD><TD>  5   </TD><TD>1024 x 768 </TD><TD>  MONO8 </TD></TR>
  <TR><TD>   1    </TD><TD>  6   </TD><TD> 800 x 600 </TD><TD> MONO16 </TD></TR>
  <TR><TD>   1    </TD><TD>  7   </TD><TD>1024 x 768 </TD><TD> MONO16 </TD></TR>
  <TR><TD>   2    </TD><TD>  0   </TD><TD>1280 x 960 </TD><TD> YUV422 </TD></TR>
  <TR><TD>   2    </TD><TD>  1   </TD><TD>1280 x 960 </TD><TD>  RGB8  </TD></TR>
  <TR><TD>   2    </TD><TD>  2   </TD><TD>1280 x 960 </TD><TD>  MONO8 </TD></TR>
  <TR><TD>   2    </TD><TD>  3   </TD><TD>1600 x 1200</TD><TD> YUV422 </TD></TR>
  <TR><TD>   2    </TD><TD>  4   </TD><TD>1600 x 1200</TD><TD>  RGB8  </TD></TR>
  <TR><TD>   2    </TD><TD>  5   </TD><TD>1600 x 1200</TD><TD>  MONO8 </TD></TR>
  <TR><TD>   2    </TD><TD>  6   </TD><TD>1280 x 960 </TD><TD> MONO16 </TD></TR>
  <TR><TD>   2    </TD><TD>  7   </TD><TD>1600 x 1200</TD><TD> MONO16 </TD></TR>
  </TABLE>

 */
void 
vp1394CMUGrabber::setVideoMode( unsigned long format, unsigned long mode )
{
  initCamera();

  _format = format ;
  _mode = mode ;

  // Set format and mode
  if ((_format != -1) && (_mode != -1))
  {
    if (!camera->HasVideoMode(_format, _mode))
    {
      close();
      vpERROR_TRACE("vp1394CMUGrabber error: The image format is not supported by the IEEE 1394 camera number %i",index);
      throw (vpFrameGrabberException(vpFrameGrabberException::settingError,"Video mode not supported") );
    }

    if (camera->IsAcquiring()) {
      // stop acquisition
      if (camera->StopImageAcquisition() != CAM_SUCCESS)
      {
        close();
        vpERROR_TRACE("vp1394CMUGrabber error: Can't stop image acquisition from IEEE 1394 camera number %i",index);
        throw (vpFrameGrabberException(vpFrameGrabberException::otherError,
                                       "Error while stopping image acquisition") );
      }
    }

    if (camera->SetVideoFormat(_format) != CAM_SUCCESS)
    {
      close();
      vpERROR_TRACE("vp1394CMUGrabber error: Can't set video format of IEEE 1394 camera number %i",index);
      throw (vpFrameGrabberException(vpFrameGrabberException::settingError,"Can't set video format") );
    }

    if (camera->SetVideoMode(_mode) != CAM_SUCCESS)
    {
      close();
      vpERROR_TRACE("vp1394CMUGrabber error: Can't set video mode of IEEE 1394 camera number %i",index);
      throw (vpFrameGrabberException(vpFrameGrabberException::settingError,"Can't set video mode") );
    }
    
    // start acquisition
    if (camera->StartImageAcquisition() != CAM_SUCCESS)
    {
      close();
      vpERROR_TRACE("vp1394CMUGrabber error: Can't start image acquisition from IEEE 1394 camera number %i",index);
      throw (vpFrameGrabberException(vpFrameGrabberException::otherError,
                                     "Error while starting image acquisition") );
    }

    // Update Image dimension
    unsigned long w, h;
    camera->GetVideoFrameDimensions(&w, &h);
    this->width = w;
    this->height = h;

    // Update the color coding
    _color = getVideoColorCoding();
  }
}
Example #12
0
/*! 
   Enable auto shutter. 

   \sa setShutter()
   */
void vp1394CMUGrabber::setAutoShutter()
{
  initCamera();
  camera->GetCameraControl(FEATURE_SHUTTER)->SetAutoMode(true);
}
Example #13
0
/*! 
   Enable auto gain. 

   \sa setGain()
   */
void vp1394CMUGrabber::setAutoGain()
{
  initCamera();
  camera->GetCameraControl(FEATURE_GAIN)->SetAutoMode(true);
}
int  main()
{
	int width;
	char* bayer[] = {"RG","BG","GR","GB"};
	char* controls[MAX_CONTROL] = {"Exposure", "Gain", "Gamma", "WB_R", "WB_B", "Brightness", "USB Traffic"};

	int height;
	int i;
	char c;
	bool bresult;

	int time1,time2;
	int count=0;

	char buf[128]={0};

	int CamNum=0;
	
	///long exposure, exp_min, exp_max, exp_step, exp_flag, exp_default;
	//long gain, gain_min, gain_max,gain_step, gain_flag, gain_default;

	IplImage *pRgb;


	int numDevices = getNumberOfConnectedCameras();
	if(numDevices <= 0)
	{
		printf("no camera connected, press any key to exit\n");
		getchar();
		return -1;
	}
	else
		printf("attached cameras:\n");

	for(i = 0; i < numDevices; i++)
		printf("%d %s\n",i, getCameraModel(i));

	printf("\nselect one to privew\n");
	scanf("%d", &CamNum);


	bresult = openCamera(CamNum);
	if(!bresult)
	{
		printf("OpenCamera error,are you root?,press any key to exit\n");
		getchar();
		return -1;
	}

	printf("%s information\n",getCameraModel(CamNum));
	int iMaxWidth, iMaxHeight;
	iMaxWidth = getMaxWidth();
	iMaxHeight =  getMaxHeight();
	printf("resolution:%dX%d\n", iMaxWidth, iMaxHeight);
	if(isColorCam())
		printf("Color Camera: bayer pattern:%s\n",bayer[getColorBayer()]);
	else
		printf("Mono camera\n");
	
	for( i = 0; i < MAX_CONTROL; i++)
	{
			if(isAvailable((Control_TYPE)i))
				printf("%s support:Yes\n", controls[i]);
			else
				printf("%s support:No\n", controls[i]);
	}

	printf("\nPlease input the <width height bin image_type> with one space, ie. 640 480 2 0. use max resolution if input is 0. Press ESC when video window is focused to quit capture\n");
	int bin = 1, Image_type;
	scanf("%d %d %d %d", &width, &height, &bin, &Image_type);
	if(width == 0 || height == 0)
	{
		width = iMaxWidth;
		height = iMaxHeight;
	}

	initCamera(); //this must be called before camera operation. and it only need init once
	printf("sensor temperature:%02f\n", getSensorTemp());

//	IMG_TYPE image_type;
	
	while(!setImageFormat(width, height, bin, (IMG_TYPE)Image_type))//IMG_RAW8
	{
		printf("Set format error, please check the width and height\n ASI120's data size(width*height) must be integer multiple of 1024\n");
		printf("Please input the width and height again£¬ie. 640 480\n");
		scanf("%d %d %d %d", &width, &height, &bin, &Image_type);
	}
	printf("\nset image format %d %d %d %d success, start privew, press ESC to stop \n", width, height, bin, Image_type);

	
	if(Image_type == IMG_RAW16)
		pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_16U, 1);
	else if(Image_type == IMG_RGB24)
		pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 3);
	else
		pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 1);

	setValue(CONTROL_EXPOSURE, 100*1000, false); //ms//auto
	setValue(CONTROL_GAIN,getMin(CONTROL_GAIN), false); 
	setValue(CONTROL_BANDWIDTHOVERLOAD, getMin(CONTROL_BANDWIDTHOVERLOAD), false); //low transfer speed

	setValue(CONTROL_WB_B, 90, false);
 	setValue(CONTROL_WB_R, 48, false);
  	setAutoPara(getMax(CONTROL_GAIN)/2,10,150); //max auto gain and exposure and target brightness
//	EnableDarkSubtract("dark.bmp"); //dark subtract will be disabled when exposure set auto and exposure below 500ms
	startCapture(); //start privew


	

	bDisplay = 1;
#ifdef _LIN
	pthread_t thread_display;
	pthread_create(&thread_display, NULL, Display, (void*)pRgb);
#elif defined _WINDOWS
	HANDLE thread_setgainexp;
	thread_setgainexp = (HANDLE)_beginthread(Display,  NULL, (void*)pRgb);
#endif

	time1 = GetTickCount();
	int iStrLen = 0, iTextX = 40, iTextY = 60;
	void* retval;
//	int time0, iWaitMs = -1;
//	bool bGetImg;
	while(bMain)
	{

//		time0 = GetTickCount();
		getImageData((unsigned char*)pRgb->imageData, pRgb->imageSize, 200);

//		bGetImg = getImageData((unsigned char*)pRgb->imageData, pRgb->imageSize, iWaitMs);
		time2 = GetTickCount();
//		printf("waitMs%d, deltaMs%d, %d\n", iWaitMs, time2 - time0, bGetImg);
		count++;
		
		if(time2-time1 > 1000 )
		{
			sprintf(buf, "fps:%d dropped frames:%lu ImageType:%d",count, getDroppedFrames(), (int)getImgType());

			count = 0;
			time1=GetTickCount();	
			printf(buf);
			printf("\n");

		}
		if(Image_type != IMG_RGB24 && Image_type != IMG_RAW16)
		{
			iStrLen = strlen(buf);
			CvRect rect = cvRect(iTextX, iTextY - 15, iStrLen* 11, 20);
			cvSetImageROI(pRgb , rect);
			cvSet(pRgb, CV_RGB(180, 180, 180)); 
			cvResetImageROI(pRgb);
		}
		cvText(pRgb, buf, iTextX,iTextY );

		if(bChangeFormat)
		{
			bChangeFormat = 0;
			bDisplay = false;
			pthread_join(thread_display, &retval);
			cvReleaseImage(&pRgb);
			stopCapture();
			
			switch(change)
			{
				 case change_imagetype:
					Image_type++;
					if(Image_type > 3)
						Image_type = 0;
					
					break;
				case change_bin:
					if(bin == 1)
					{
						bin = 2;
						width/=2;
						height/=2;
					}
					else 
					{
						bin = 1;
						width*=2;
						height*=2;
					}
					break;
				case change_size_smaller:
					if(width > 320 && height > 240)
					{
						width/= 2;
						height/= 2;
					}
					break;
				
				case change_size_bigger:
				
					if(width*2*bin <= iMaxWidth && height*2*bin <= iMaxHeight)
					{
						width*= 2;
						height*= 2;
					}
					break;
			}
			setImageFormat(width, height, bin, (IMG_TYPE)Image_type);
			if(Image_type == IMG_RAW16)
				pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_16U, 1);
			else if(Image_type == IMG_RGB24)
				pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 3);
			else
				pRgb=cvCreateImage(cvSize(getWidth(),getHeight()), IPL_DEPTH_8U, 1);
			bDisplay = 1;
			pthread_create(&thread_display, NULL, Display, (void*)pRgb);
			startCapture(); //start privew
		}
	}
END:
	
	if(bDisplay)
	{
		bDisplay = 0;
#ifdef _LIN
   		pthread_join(thread_display, &retval);
#elif defined _WINDOWS
		Sleep(50);
#endif
	}
	
	stopCapture();
	closeCamera();
	cvReleaseImage(&pRgb);
	printf("main function over\n");
	return 1;
}
Example #15
0
void resetPlayerData(void) {
  int i;
  Data *data;
  AI *ai;
  int not_playing = 0;

  int *startIndex;
  startIndex = malloc( game->players * sizeof(int) );
  randomPermutation(game->players, startIndex);

  for(i = 0; i < game->players; i++) {
    float startpos[][2] = { 
			{ 0.5, 0.25 }, { 0.75, 0.5 }, { 0.5, 0.75 }, { 0.25, 0.5 }
    };
		float x, y;

    data = game->player[i].data;
    ai = game->player[i].ai;
    /* init ai */

		switch(i) {
		case 0: ai->active = getSettingi("ai_player1"); break;
		case 1: ai->active = getSettingi("ai_player2"); break;
		case 2: ai->active = getSettingi("ai_player3"); break;
		case 3: ai->active = getSettingi("ai_player4"); break;
		default:
			fprintf(stderr, "[error] player index #%d not caught!\n", i);
			ai->active = AI_NONE;
		}
		ai->tdiff = 0;

		/* arrange players in circle around center */

		/* randomize position on the grid */
		x = startpos[ startIndex[i] ][0] * getSettingi("grid_size");
		y = startpos[ startIndex[i] ][1] * getSettingi("grid_size");
		/* randomize starting direction */
		data->dir = trand() & 3;
		/* data->dir = startdir[i]; */
		data->last_dir = data->dir;

		/* if player is playing... */
		if(ai->active != AI_NONE) {
			data->speed = getSettingf("speed");
			data->booster = getSettingf("booster_max");
			data->boost_enabled = 0;
			data->trail_height = TRAIL_HEIGHT;
		} else {
			data->speed = SPEED_GONE;
			data->trail_height = 0;
			not_playing++;
		}
		// data->trail = data->trails;
		data->trailOffset = 0;

		data->trails[ data->trailOffset ].vStart.v[0] = x;
		data->trails[ data->trailOffset ].vStart.v[1] = y;
		
		data->trails[ data->trailOffset ].vDirection.v[0] = 0;
		data->trails[ data->trailOffset ].vDirection.v[1] = 0;

		{
			int camType;
			Camera *cam = game->player[i].camera;
			camType = (game->player[i].ai->active == AI_COMPUTER) ? 
				CAM_CIRCLE : gSettingsCache.camType;
			initCamera(cam, data, camType);
		}
	}

	free(startIndex);

	game->running = game->players - not_playing; /* not everyone is alive */
	/* printf("starting game with %d players\n", game->running); */
	game->winner = -1;
}
Example #16
0
int main(int argc, char** argv){

  bool loadedScene = false;
  for(int i=1; i<argc; i++){
    string header; string data;
    istringstream liness(argv[i]);
    getline(liness, header, '='); getline(liness, data, '=');
    if(strcmp(header.c_str(), "mesh")==0){
      //renderScene = new scene(data);
      mesh = new obj();
      objLoader* loader = new objLoader(data, mesh);
      mesh->buildVBOs();
      delete loader;
      loadedScene = true;
    }
  }

  if(!loadedScene){
    cout << "Usage: mesh=[obj file]" << endl;
    return 0;
  }

  frame = 0;
  seconds = time (NULL);
  fpstracker = 0;

  // Launch CUDA/GL
  #ifdef __APPLE__
  // Needed in OSX to force use of OpenGL3.2 
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
  glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  init();
  #else
  init(argc, argv);
  #endif

  initCamera();
  initLights();
  initCuda();

  initVAO();
  initTextures();

  GLuint passthroughProgram;
  passthroughProgram = initShader("shaders/passthroughVS.glsl", "shaders/passthroughFS.glsl");

  glUseProgram(passthroughProgram);
  glActiveTexture(GL_TEXTURE0);

  #ifdef __APPLE__
    // send into GLFW main loop
    while(1){
      display();
      if (glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS || !glfwGetWindowParam( GLFW_OPENED )){
          kernelCleanup();
          cudaDeviceReset(); 
          exit(0);
      }
    }

    glfwTerminate();
  #else
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
	glutMouseFunc(mouseButton);
	glutMotionFunc(mouseMove);

    glutMainLoop();
  #endif
  kernelCleanup();
  return 0;
}
Example #17
0
void keyboardPause(int key, int unicode, int x, int y) {
  int      i;
#ifdef __NETWORK__
  Packet   packet;
#endif

  switch(key) {
  case 27:
#ifdef __NETWORK__
    if( game2->mode == GAME_NETWORK_PLAY && isConnected )
      {
	isConnected = 0;
	isLogged = 0;
	serverstate=preGameState; //We hope that next time server will be to preGameState
	Net_disconnect();
      }
#endif
    switchCallbacks(&guiCallbacks);
    break;
  case ' ':
#ifdef __NETWORK__
    //restart game
    if( game2->mode == GAME_NETWORK_PLAY && (serverstate == preGameState) && (isConnected && slots[me].isMaster == 1)  )
      {
	makeping(0);
	printf("\nAsk to start the game\n");
	packet.which=me;
	packet.type=ACTION;
	packet.infos.action.type=STARTGAME;
	Net_sendpacket(&packet,  Net_getmainsock());
      } else {
	if( game2->mode == GAME_NETWORK_PLAY )
	    printf("\nOnly game master can start the game...\n");
	else {
#endif	
	    if(game->pauseflag & PAUSE_GAME_FINISHED)
	      initData();
	    /* lasttime = SystemGetElapsedTime(); */
	    switchCallbacks(&gameCallbacks);
#ifdef __NETWORK__
	  }
      }
#endif   
    break;
    /* case 'q': SystemExit(); break; */
  case SYSTEM_KEY_F1: defaultDisplay(0); break;
  case SYSTEM_KEY_F2: defaultDisplay(1); break;
  case SYSTEM_KEY_F3: defaultDisplay(2); break;
  case SYSTEM_KEY_F4: defaultDisplay(3); break;
    /* doesn't really work on my box */
    /*
  case SYSTEM_KEY_F6: 
    Gamma -= 0.1;
    shutdownDisplay(game->screen);
    SystemSetGamma(Gamma, Gamma, Gamma);
    setupDisplay(game->screen);
    break;
  case SYSTEM_KEY_F7: 
    Gamma += 0.1;
    shutdownDisplay(game->screen);
    SystemSetGamma(Gamma, Gamma, Gamma);
    setupDisplay(game->screen);
    break;
    */
  case SYSTEM_KEY_F10:
    game->settings->camType = (game->settings->camType + 1) % CAM_COUNT;
    for(i = 0; i < game->players; i++)
      if(game->player[i].ai->active == 0)
	initCamera(game->player[i].camera, 
		   game->player[i].data, 
		   game->settings->camType);
    break;
  case SYSTEM_KEY_F12: doScreenShot(game->screen->vp_w, game->screen->vp_h); break;
    
  case SYSTEM_KEY_UP: consoleScrollBackward(1); break;
  case SYSTEM_KEY_DOWN: consoleScrollForward(1); break;

  case SYSTEM_KEY_F5: saveSettings(); break;
  case SYSTEM_KEY_TAB: switchCallbacks(&promptCallbacks); break;
  }
}
Example #18
0
void VideoDevice::startCapture(int deviceID)
{
        initCamera(deviceID);
        captureThread = new std::thread(&VideoDevice::captureFromCamera, this);
}
Example #19
0
/**
 * @brief Flips the calibration vertically.
 */
void Camera::flip_vertical(){
	initCamera();
	cameraMatrix.col(1) *= -1.0;
}
Example #20
0
/**
 * @brief Flips the calibration horizontally.
 */
void Camera::flip_horizontal(){
	initCamera();
	cameraMatrix.col(0) *= -1.0;
}
Example #21
0
int initImageSync(){
    sem_init(&FileQSem, 0, 1); 
    sem_init(&NewFileSem, 0, 0);

    return initCamera();
}
Example #22
0
/* new scene */
int createScene (pScene sc, int idmesh) {
	pMesh mesh;
	char data[128];

	/* default */
	mesh = cv.mesh[idmesh];
	if (!quiet) fprintf(stdout, "   Computing 3D scene\n");

	/* set default mode */
	sc->idmesh = idmesh;
	sc->par.xi = sc->par.yi = 10;
	if (option == SCHNAUZER) {
		sc->par.xs = schw;
		sc->par.ys = schh;
	} else {
		if (sc->par.xs == 0) sc->par.xs = 600;

		if (sc->par.ys == 0) sc->par.ys = 600;
	}

	if (!sc->mode) sc->mode = HIDDEN;

	sc->item = 0;
	sc->shrink = 1.0;
	sc->slave = sc->master = -1;
	sc->picked = 0;
	if (mesh->nvn == 0) sc->type ^= S_FLAT;

	if (mesh->ne == 0) sc->item |= S_GEOM;

	/* compute scene depth */
	sc->dmax = sc->dmin = mesh->xmax - mesh->xmin;
	sc->dmax = max(sc->dmax, mesh->ymax - mesh->ymin);
	sc->dmin = min(sc->dmin, mesh->ymax - mesh->ymin);
	if (mesh->dim == 3) {
		sc->dmax = max(sc->dmax, mesh->zmax - mesh->zmin);
		sc->dmin = min(sc->dmin, mesh->zmax - mesh->zmin);
	}

	sc->dmax = fabs(sc->dmax);
	sc->dmin = fabs(sc->dmin);
	if (!sc->par.sunp) {
		sc->par.sunpos[0] *= 2.0 * sc->dmax;
		sc->par.sunpos[1] *= 2.0 * sc->dmax;
		sc->par.sunpos[2] *= 2.0 * sc->dmax;
	}

	sc->par.sunpos[3] = 1.0;

	/* create window */
	glutInitWindowSize(sc->par.xs, sc->par.ys);
	sc->idwin = glutCreateWindow("");
	assert(sc->idwin != 0);
	if (fullscreen) {
		glutFullScreen();
		sc->par.xs = glutGet(GLUT_SCREEN_WIDTH);
		sc->par.ys = glutGet(GLUT_SCREEN_HEIGHT);
	}

	/* set window name */
	sprintf(data, "Medit - [%s] #%d", mesh->name, sc->idwin);
	glutSetWindowTitle(data);
	glutSetIconTitle(data);

	/* required! to change background color */
	glClearColor(sc->par.back[0], sc->par.back[1],
	             sc->par.back[2], sc->par.back[3]);

	/* init perspective */
	sc->persp = initPersp(0, sc->dmax);
	sc->camera = (pCamera)initCamera(sc, Y_AXIS);
	if (mesh->typ == 2) {
		sc->persp->pmode = CAMERA;
		sc->persp->depth *= 0.5;
	}

	/* create default view */
	sc->view = (pTransform)createTransform();
	if (!sc->view) return (0);

	sc->type |= S_RESET + S_DECO;
	sc->clip = (pClip)createClip(sc, mesh);
	if (!sc->clip) return (0);

	sc->cube = (pCube)createCube(sc, mesh);
	if (!sc->cube) return (0);

	/* create menus */
	if (!createMenus(sc, mesh)) return (0);

	/* assign callbacks */
	if (sc->type & S_SCISSOR) {
		glutDisplayFunc(scissorScene);
	} else if (option == SCHNAUZER) {
		glutDisplayFunc(redrawSchnauzer);
	} else if (sc->persp->pmode == CAMERA) {
		glutMouseFunc(mouseCamera);
		glutMotionFunc(motionCamera);
		glutDisplayFunc(redrawScene);
	} else {
		glutMouseFunc(mouse);
		glutMotionFunc(motion);
		glutDisplayFunc(redrawScene);
	}

	glutReshapeFunc(reshapeScene);
	glutKeyboardFunc(keyScene);
	glutSpecialFunc(special);
	glutAttachMenu(GLUT_RIGHT_BUTTON);

	/* create display lists by geom type */
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	doLists(sc, mesh);
	sc->glist = geomList(sc, mesh);
	sc->type |= S_FOLLOW;

	/* local stack */
	if (!pilmat) {
		pilmat = (int *)calloc(sc->par.nbmat + 2, sizeof(int));
		if (!pilmat) return (0);
	}

	/* color list */
	setupPalette(sc, mesh);
	sc->stream = NULL;

	initGrafix(sc, mesh);
	return (1);
}
Example #23
0
int main(int argc, char** argv) {
	/*Check arguments to make sure you got a file*/
	//There must be at least some arguments to get a file
    if(errno != 0){
            perror("Unknown Error at start");
            errno = 0;
    }


	const char* filename = NULL;
	const char* outfile = NULL;
	bool gui = false;
	float nodeCharge = 3;
	bool output = true;
	bool isFile = true;

	layout_params* params = (layout_params*) malloc(sizeof(layout_params));
	params->ke = 500;
	params->kh = 0.0005;
	params->kl = -0.05;
	params->width = 1920;
	params->height = 1080;
	params->iterations = 10000;
	params->mass = 1;
	params->time = 1;
	params->coefficientOfRestitution = -0.9;
	params->mus = 0.2;
	params->muk = 0.04;
	params->kw = 3;
	params->kg = 0.06;
	params->wellMass = 1;
	params->edgeCharge = nodeCharge;
	params->forcemode = COULOMBS_LAW | HOOKES_LAW_SPRING | FRICTION | DRAG
			| BOUNCY_WALLS;
	params->cpuLoop = false;

	if (argc < 2) {
		usage();
		return EXIT_FAILURE;
	}

	for (int i = 1; i < argc; i++) {
    if(errno != 0){
            fprintf(stderr, "On Iter: %d ", i);
            perror("Unknown Error");
            errno = 0;
    }
		if (strcmp(argv[i], "-f") == 0) {
			if (filename != NULL) {
				printf(
						"An input directory has already been provided (%s).\nCan only use one of -f and -d.\n",
						filename);
				exit(-1);
			}
			filename = readString(argc, argv, ++i);
			isFile = true;
		} else if (strcmp(argv[i], "-d") == 0) {
			if (filename != NULL) {
				printf(
						"An input file has already been provided (%s).\nCan only use one of -f and -d.\n",
						filename);
				exit(-1);
			}
			filename = readString(argc, argv, ++i);
			isFile = false;
		} else if (strcmp(argv[i], "-o") == 0) {
			outfile = readString(argc, argv, ++i);
		} else if (strcmp(argv[i], "-Ke") == 0) {
			params->ke = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-Kh") == 0) {
			params->kh = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-Kl") == 0) {
			params->kl = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-nodeCharge") == 0) {
			nodeCharge = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-edgeCharge") == 0) {
			params->edgeCharge = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-Kg") == 0) {
			params->kg = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-nm") == 0) {
			params->wellMass = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-mus") == 0) {
			params->mus = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-muk") == 0) {
			params->muk = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-i") == 0) {
			params->iterations = readInt(argc, argv, ++i);
		} else if (strcmp(argv[i], "-width") == 0) {
			params->width = readInt(argc, argv, ++i);
		} else if (strcmp(argv[i], "-height") == 0) {
			params->height = readInt(argc, argv, ++i);
		} else if (strcmp(argv[i], "-gui") == 0) {
			gui = true;
		} else if (strcmp(argv[i], "-cpuLoop") == 0) {
			params->cpuLoop = true;
		} else if (strcmp(argv[i], "-noOutput") == 0) {
			output = false;
		} else if (strcmp(argv[i], "-t") == 0) {
			params->time = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-m") == 0) {
			params->mass = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-cRest") == 0) {
			params->coefficientOfRestitution = readFloat(argc, argv, ++i);
		} else if (strcmp(argv[i], "-friction") == 0) {
			int fricForce = readInt(argc, argv, ++i);
			params->forcemode = params->forcemode & ~(FRICTION | DRAG);
			params->forcemode = params->forcemode | (fricForce << 2);
		} else if (strcmp(argv[i], "-spring") == 0) {
			int springForce = readInt(argc, argv, ++i);
			params->forcemode = params->forcemode
					& ~(HOOKES_LAW_SPRING | LOG_SPRING);
			params->forcemode = params->forcemode | (springForce);
		} else if (strcmp(argv[i], "-walls") == 0) {
			int wallForce = readInt(argc, argv, ++i);
			params->forcemode = params->forcemode
					& ~(BOUNCY_WALLS | CHARGED_WALLS | GRAVITY_WELL);
			params->forcemode = params->forcemode | (wallForce << 4);
		} else if (strcmp(argv[i], "-forces") == 0) {
			int primForce = readInt(argc, argv, ++i);
			params->forcemode = params->forcemode
					& ~(COULOMBS_LAW | DEGREE_BASED_CHARGE
							| CHARGED_EDGE_CENTERS | WRAP_AROUND_FORCES);
			params->forcemode = params->forcemode | (primForce << 7);

		} else {
			fprintf(stderr, "Unknown option %s\n", argv[i]);
			return EXIT_FAILURE;
		}
	}

	if (filename == NULL) {
		fprintf(stderr, "You must include a filename\n");
		usage();
		return EXIT_FAILURE;
	}

	graph** g;
	int graphCount = 0;
	if (isFile) {
		debug("Reading graph: %s\n", filename);
		g = (graph**) malloc(sizeof(graph*));
		g[0] = readFile(filename);
		graphCount = 1;
	} else {
		g = readDir(filename, &graphCount);
	}

	if (g == NULL || graphCount < 1) {
		fprintf(stderr, "Creating a graph failed. Terminating\n");
		usage();
		return EXIT_FAILURE;
	}

	for (int i = 0; i < graphCount; i++) {
		graph_initRandom(g[i], 20, 10, params->width, params->height,
				nodeCharge);
	}

	if (gui && isFile) {
		glutInit(&argc, argv);
		glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
		glutInitWindowSize(params->width, params->height);
		glutCreateWindow("Force Directed Layout");

		glutDisplayFunc(display);
		//glutReshapeFunc(reshape);
		glutIdleFunc(idle);

		setLight();
		initCamera(params->width, params->height);
		glGraph = g;
		glParams = params;
		glutMainLoop();

	} else if (gui) {
		printf("Cannot use gui mode with a directory.\n");
		exit(-1);
	}

	/* The graph is now is a legal state.
	 * It is not using the GUI.
	 * It is possible to lay it out now
	 */
	struct timeval tstart, tend;
	gettimeofday(&tstart, NULL);


	graph_layout(g, graphCount, params);

	gettimeofday(&tend, NULL);
	long start = tstart.tv_sec * 1000000 + tstart.tv_usec;
	long end = tend.tv_sec * 1000000 + tend.tv_usec;
	long msElapsed = end - start;

	debug("Elapsed Time (us): %ld\n", msElapsed);

	if (outfile == NULL && isFile) {
		outfile = "after.svg";
	}
	if (output && (outfile != NULL)) {
		for (int i = 0; i < graphCount; i++) {
#define BUFF_SIZE 1024
			char thisOutFile[BUFF_SIZE];
			strncpy(thisOutFile,outfile,BUFF_SIZE);

			if(!isFile){
				//Does it end on a /
				int len = strlen(thisOutFile);
				if(thisOutFile[len-1] != '/'){
					if(len < BUFF_SIZE - 2){ //Keep enough space for the '\0'
						thisOutFile[len++] = '/';
						thisOutFile[len] = '\0';
					}else{
						fprintf(stderr,"File name too long (%s [/] %s [/] %s)\n. Not creating svg.\n", outfile, (g[i])->dir, g[i]->filename);
						continue;
					}
				}
				//Now concatenate the dir name
				if(g[i]->dir != NULL){
					int len2 = strlen(g[i]->dir);
					if(len + len2 +1 > BUFF_SIZE){
						fprintf(stderr,"File name too long (%s [/] %s [/] %s)\n. Not creating svg.\n", outfile, (g[i])->dir, g[i]->filename);
						continue;
					}
					 strcat(thisOutFile, g[i]->dir + (g[i]->dir[0]=='/'? 1: 0));
				}

				//Now the file name
				int len2 = strlen(g[i]->filename);
				if(len + len2 + 1 > BUFF_SIZE){
					fprintf(stderr,"File name too long (%s [/] %s [/] %s)\n. Not creating svg.\n", outfile, (g[i])->dir, g[i]->filename);
					continue;
				}
				strcat(thisOutFile,g[i]->filename);
				char* extension = strstr(thisOutFile, ".graphml");
				if(extension ==NULL){
					fprintf(stderr,"Something went wrong. Could not find .graphml in %s\nTerminating\n", thisOutFile);
					exit(EXIT_FAILURE);
				}
				strcpy(extension, ".svg");
				//Now the filename is finally right!

			}


			graph_toSVG(g[i], thisOutFile, params->width, params->height,
					(params->forcemode & (BOUNCY_WALLS | CHARGED_WALLS)) != 0,
					msElapsed, params);
		}
	}


	//Free all the graphs and the structure that holds it
	free(g[0]->nodes);
	bitarray_free(g[0]->edges);
	for (int i = 0; i < graphCount; i++) {
		graph_free(g[i]);
	}
	free(g);

	free(params);
	return EXIT_SUCCESS;

}
Example #24
0
CameraModel::CameraModel(Vec3 _camPosition, Vec3 _camDirection, double _fov, double _focalDistance, double _apertureRadius, unsigned int _width, unsigned int _height):
	camPosition(_camPosition), camDirection(_camDirection), fov(_fov), focalDistance(_focalDistance), apertureRadius(_apertureRadius), width(_width), height(_height)
{
	initCamera();
}
void vkeGameRendererDynamic::initDescriptorSets(){

	VulkanDC *dc = VulkanDC::Get();
	VulkanDC::Device *device = dc->getDefaultDevice();
	uint32_t count = 1;
	if (!dc) return;


	initCamera();

	vkResetDescriptorPool(device->getVKDevice(), getDescriptorPool(), 0);

	VkWriteDescriptorSet writes[5];

	/*----------------------------------------------------------
	Get the resource data for the bindings.
	----------------------------------------------------------*/


	/*
	Terrain textures.
	*/
	VkeTexture::Data terrain = m_textures.getTexture(0)->getData();

	/*
	Camera and Light uniforms
	*/
	VkDescriptorBufferInfo camInfo = m_camera->getDescriptor();
	VkDescriptorBufferInfo lightInfo = m_light->getDescriptor();

	/*
	Cube map texture.
	*/
	VkeCubeTexture::Data cube = m_cube_textures.getTexture(1)->getData();

	/*
	Create descriptor image info array
	for the terrain textures.
	*/
	VkDescriptorImageInfo fpSampler = { terrain.sampler, terrain.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };


	VkeMaterial *material = m_materials->getMaterial(0);


	/*
	Create descriptor image info array
	for the scene textures.
	*/
	uint32_t texCount = m_materials->count();

	VkDescriptorImageInfo *texImageInfo = (VkDescriptorImageInfo*)malloc(texCount * sizeof(VkDescriptorImageInfo));

	for (uint32_t i = 0; i < texCount; ++i){
		VkeMaterial *mtrl = m_materials->getMaterial(i);
		VkeTexture::Data texData = mtrl->getTextures().getTexture(0)->getData();
		texImageInfo[i].imageView = texData.view;
		texImageInfo[i].sampler = texData.sampler;
	}

	/*
	Create descriptor image info for
	the cube map texture.
	*/

	VkDescriptorImageInfo cubeTexture;
	cubeTexture.sampler = cube.sampler;
	cubeTexture.imageView = cube.view;
	cubeTexture.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;

	/*
	Capture the layouts for the scene descriptor
	sets and the texture descriptor sets.
	*/
	VkDescriptorSetLayout *textureLayouts = (VkDescriptorSetLayout*)malloc(sizeof(VkDescriptorSetLayout) * texCount);

	for (uint32_t i = 0; i < texCount; ++i){
		textureLayouts[i] = m_texture_descriptor_set_layout;
	}

	/*
	Allocate storage for the scene and
	texture descriptor sets.
	*/



	/*----------------------------------------------------------
	Allocate the descriptor sets.
	----------------------------------------------------------*/
	m_texture_descriptor_sets = (VkDescriptorSet*)malloc(sizeof(VkDescriptorSet));

	/*
	Set up the alocate info structure for
	the descriptor sets.
	*/
	VkDescriptorSetAllocateInfo descAlloc;
	memset(&descAlloc, 0, sizeof(descAlloc));
	descAlloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
	descAlloc.descriptorPool = getDescriptorPool();
	descAlloc.pSetLayouts = &m_scene_descriptor_layout;
	descAlloc.descriptorSetCount = 1;


	VKA_CHECK_ERROR(vkAllocateDescriptorSets(device->getVKDevice(), &descAlloc, &m_scene_descriptor_set), "Could not allocate descriptor sets.\n");

	/*
	Set up the texture descriptor sets.
	*/
	descAlloc.pSetLayouts = &m_texture_descriptor_set_layout;
	descAlloc.descriptorSetCount = 1;

	VKA_CHECK_ERROR(vkAllocateDescriptorSets(device->getVKDevice(), &descAlloc, m_texture_descriptor_sets), "Could not allocate texture descriptor sets.\n");

	/*
	Set up the skybox descriptor sets.
	*/
	descAlloc.pSetLayouts = &m_quad_descriptor_set_layout;
	descAlloc.descriptorSetCount = 1;

	VKA_CHECK_ERROR(vkAllocateDescriptorSets(device->getVKDevice(), &descAlloc, &m_quad_descriptor_set), "Could not allocate descriptor sets.\n");

	/*
	Set up the terrian descriptor sets.
	*/
	descAlloc.pSetLayouts = &m_terrain_descriptor_set_layout;
	descAlloc.descriptorSetCount = 1;

	VKA_CHECK_ERROR(vkAllocateDescriptorSets(device->getVKDevice(), &descAlloc, &m_terrain_descriptor_set), "Could not allocate descriptor sets.\n");


	/*
	Set up the transforms descriptor sets.
	*/
	descAlloc.pSetLayouts = &m_transform_descriptor_layout;
	descAlloc.descriptorSetCount = 1;

	VKA_CHECK_ERROR(vkAllocateDescriptorSets(device->getVKDevice(), &descAlloc, &m_transform_descriptor_set), "Could not allocate descriptor sets.\n");


	/*----------------------------------------------------------
	Update the descriptor sets with resource bindings.
	----------------------------------------------------------*/

	/*
	Scene layout bindings (set 0)
	Binding 0:		Environment Cube Map
	Binding 1:		Camera Matrix
	Binding 2:		Model Matrix
	Binding 3:		Material
	*/

	descriptorSetWrite(&writes[0], 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_NULL_HANDLE, &cubeTexture, 0, m_scene_descriptor_set);//cubemap
	descriptorSetWrite(&writes[1], 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &camInfo, VK_NULL_HANDLE, 0, m_scene_descriptor_set); //Camera
	descriptorSetWrite(&writes[2], 2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &m_uniforms_descriptor, VK_NULL_HANDLE, 0, m_scene_descriptor_set);//modelview
	descriptorSetWrite(&writes[3], 3, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &material->getDescriptor(), VK_NULL_HANDLE, 0, m_scene_descriptor_set);//material

	vkUpdateDescriptorSets(device->getVKDevice(), 4, writes, 0, NULL);

	/*
	Transform layout bindings (set 0)
	Binding 0:		Transform
	*/

	descriptorSetWrite(&writes[0], 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &m_transforms_descriptor, VK_NULL_HANDLE, 0, m_transform_descriptor_set);//transform
	vkUpdateDescriptorSets(device->getVKDevice(), 1, writes, 0, NULL);


	/*
	Scene layout bindings (set 1)
	Binding 0:		Scene texture array
	*/
	descriptorSetWrite(&writes[0], 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, texCount, VK_NULL_HANDLE, texImageInfo, 0, m_texture_descriptor_sets[0]);//cubemap

	vkUpdateDescriptorSets(device->getVKDevice(), (uint32_t)1, writes, 0, NULL);
	//Free the texture image info allocated earlier.
	free(texImageInfo);



	/*
	Skybox layout bindings (set 0)
	Binding 0:		Skybox Uniforms
	Binding 1:		Skybox Textures
	Binding 2:		Camera uniforms
	*/

	descriptorSetWrite(&writes[0], 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &m_screen_quad.getData().descriptor, VK_NULL_HANDLE, 0, m_quad_descriptor_set);
	descriptorSetWrite(&writes[1], 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_NULL_HANDLE, &cubeTexture, 0, m_quad_descriptor_set);
	descriptorSetWrite(&writes[2], 2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &camInfo, VK_NULL_HANDLE, 0, m_quad_descriptor_set);

	vkUpdateDescriptorSets(device->getVKDevice(), 3, writes, 0, NULL);


	/*
	Terrain layout bindings (set 0)
	Binding 0:		Terrain Uniforms
	Binding 1:		Camera Uniforms
	Binding 2:		Terrain texture array
	*/

	descriptorSetWrite(&writes[0], 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &m_terrain_quad.getData().descriptor, VK_NULL_HANDLE, 0, m_terrain_descriptor_set);
	descriptorSetWrite(&writes[1], 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &camInfo, VK_NULL_HANDLE, 0, m_terrain_descriptor_set);
	descriptorSetWrite(&writes[2], 2, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_NULL_HANDLE, &fpSampler, 0, m_terrain_descriptor_set);
	descriptorSetWrite(&writes[3], 3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_NULL_HANDLE, &cubeTexture, 0, m_terrain_descriptor_set);

	vkUpdateDescriptorSets(device->getVKDevice(), 4, writes, 0, NULL);


	/*----------------------------------------------------------
	Initialise the terrain and scene command buffers.
	----------------------------------------------------------*/
	initTerrainCommand();

	for (uint32_t i = 0; i < m_max_draw_calls; ++i){
		m_draw_calls[i]->initDescriptor();
	}

	//m_test_drawcall->initDrawCommands(m_node_data->count());

	//this needs to happen in the thread.
	//m_draw_calls[0]->initDrawCommands(m_node_data->count());


}
Example #26
0
/*!
  Initialization of the grabber using a greyscale image.
  \param I : gray level image.
  */
void 
vp1394CMUGrabber::open(vpImage<unsigned char> &I)
{
  initCamera();
  I.resize(this->height, this->width);
}
Example #27
0
void ofxLibdc::setup(int cameraNumber) {
	initCamera(cameraNumber);
	applySettings();
}
Example #28
0
/*!
  Initialization of the grabber using a color image.
  \param I : color image.
  */
void 
vp1394CMUGrabber::open(vpImage<vpRGBa> &I)
{
  initCamera();
  I.resize(this->height, this->width);
}
Example #29
0
int initPositionnement(){
	pthread_t thread;
	threadArg arg;
	char message[32];
	string messageEnvoi, messageRecu;
	short angleRotationR = 0;

	// Faire l'initialisation de la caméra:
	initCamera();
	
	//Initialisation du magnétomètre:
	sem_wait(Arg.verrou_I2C);
	if (i2c_w(ADDR_MAGNETOMETRE, CALIBRATION_START, NULL) != 0){
		puts("Magnétomètre failed");
		// Arrêt du programme
		finProgramme = true;
		pthread_exit(NULL);
	}
	robot.pivotRight(20);
	sleep(20);
	if (i2c_w(ADDR_MAGNETOMETRE, CALIBRATION_END, NULL) != 0){
		puts("Magnétomètre failed");
		// Arrêt du programme
		finProgramme = true;
		pthread_exit(NULL);
	}
	if (i2c_w(ADDR_MAGNETOMETRE, CMD_A, NULL) != 0){
		puts("Magnétomètre failed");
		// Arrêt du programme
		finProgramme = true;
		pthread_exit(NULL);
	}
	sem_post(Arg.verrou_I2C);

	// Initialisation des variables indiquant l'état dans lequel on se trouve
	robotTourne = false;
	robotAvance = true;
	flagVirage = 0;
	flagStop = true;
	taskDone = false;

	// On tente de trouver la personne en activant la caméra puis en vérifiant que la personne et le robot
	// soient dans la même direction. -> Si la caméra détecte une personne on va lancer la prise de photo.
	do{
		// On regarde dans quelles positions se trouvent la personne par rapport au robot avec les magnéto.
		taskDone = false;
		pthread_create(&thread, NULL, magnetometre, (void *) &arg);
		while(taskDone != true){/* On attend la fin de ta tache */}
		pthread_join(thread, NULL);
		// Si c'est dans le thread magnéto qu'on a reçu l'ordre d'arrêt
		if (finProgramme == true){
			// Fin du thread
			pthread_exit(NULL);
		}

		// Lance la vérif avec le magnétomètre et la caméra sur 360° par palier de 30°:
		while (abs(differenceAngle) > ANGLE_LIMITE){
			sprintf(message, "A: %d", differenceAngle);
			messageEnvoi = message;
			zigbee_w(messageEnvoi);
			// Petite tempo pour laisser le temps à la beagle de la personne de faire des modifs
			usleep(100000);
			// On refait une acquisition des magnéto
			taskDone = false;
			pthread_create(&thread, NULL, magnetometre, NULL);
			while(taskDone != true){/* On attend la fin de ta tache */}
			pthread_join(thread, NULL);
			// Si c'est dans le thread magnéto qu'on a reçu l'ordre d'arrêt
			if (finProgramme == true){
				// Fin du thread
				pthread_exit(NULL);
			}
		}
		// Message indiquant que la personne et le robot sont dans la même direction
		zigbee_w("M: magneto_success");
		// On attend que le son est bien été joué
		zigbee_r(messageRecu);
		if (strcmp(messageRecu.c_str(), "need_synchro") == 0){
			string synchro = "";
			while (strcmp(synchro.c_str(), "synchro_success") != 0){
				zigbee_w("synchronize");
				zigbee_r(synchro);
			}
		}
		else if (strcmp(messageRecu.c_str(), "end_program") == 0){
			// Arrêt du programme
			finProgramme = true;
			pthread_exit(NULL);
		}

		// Mnt que le robot et la personne sont dans la même direction on va pouvoir faire une acquisition
		// pour voir si on trouve quelqu'un.
		cameraInformation = camera();
		if (cameraInformation.flagDetect == false){
			// Si on ne détecte toujours pas la personne on va alors faire pivoter le robot sur lui même de 30°
			// Et ainsi de suite jusqu'à balayer un angle de 180° permettant de vérifier la zone se trouvant à 
			// l'arrière du robot au moment où on s'est rendu compte de la perte de la personne 
			zigbee_w("M: detection_failed");
			// On attend que le son est bien été joué
			zigbee_r(messageRecu);
			if (strcmp(messageRecu.c_str(), "need_synchro") == 0){
				string synchro = "";
				while (strcmp(synchro.c_str(), "synchro_success") != 0){
					zigbee_w("synchronize");
					zigbee_r(synchro);
				}
			}
			else if (strcmp(messageRecu.c_str(), "end_program") == 0){
				// Arrêt du programme
				finProgramme = true;
				pthread_exit(NULL);
			}

			angleRotationR += 30;
			if (angleRotationR >= 360)
			{
				puts("Aucune personne n'a été détectée, arrêt du programme");
				zigbee_w("I: not_found");
				// Arrêt du programme
				finProgramme = true;
				pthread_exit(NULL);
			}
			// Modifier la direction du robot:
			robot.pivotRight(100, 30);
		}
		// Petite tempo pour laisser le temps à la personne de se replacer
		usleep(1500000);
	}while (cameraInformation.flagDetect == false);

	// Si on détecte un visage, on va supposer que c'est la personne qui veut être guidée.
	// On va lancer la prise de photo
	takePicture();

	// Initialisation des ultrasons:
	if (i2c_w(ADDR_ULTRASON_3, REGISTRE_W_RANGE, DETECTION_MAX, NULL) != 0){
		finProgramme = true;
		pthread_exit(NULL);
	}
	if (i2c_w(ADDR_ULTRASON_2, REGISTRE_W_RANGE, DETECTION_MAX, NULL) != 0){
		finProgramme = true;
		pthread_exit(NULL);
	}
	if (i2c_w(ADDR_ULTRASON_4, REGISTRE_W_RANGE, DETECTION_MAX, NULL) != 0){
		finProgramme = true;
		pthread_exit(NULL);
	}
	if (i2c_w(ADDR_ULTRASON_1, REGISTRE_W_RANGE, DETECTION_MAX, NULL) != 0){
		finProgramme = true;
		pthread_exit(NULL);
	}
	if (i2c_w(ADDR_ULTRASON_5, REGISTRE_W_RANGE, DETECTION_MAX, NULL) != 0){
		finProgramme = true;
		pthread_exit(NULL);
	}

	flagInit = true;

	return 0;
}
Example #30
0
void initGame(void)
{
	lcdMainOnTop();
	int oldv=getMemFree();
	NOGBA("mem free : %dko (%do)",getMemFree()/1024,getMemFree());
	NOGBA("initializing...");
	videoSetMode(MODE_5_3D | DISPLAY_BG3_ACTIVE);
	videoSetModeSub(MODE_5_2D | DISPLAY_BG3_ACTIVE);
	
	glInit();
	
	vramSetPrimaryBanks(VRAM_A_TEXTURE,VRAM_B_TEXTURE,VRAM_C_LCD,VRAM_D_MAIN_BG_0x06000000);
	vramSetBankH(VRAM_H_SUB_BG);
	vramSetBankI(VRAM_I_SUB_BG_0x06208000);
	
	glEnable(GL_TEXTURE_2D);
	// glEnable(GL_ANTIALIAS);
	glDisable(GL_ANTIALIAS);
	glEnable(GL_BLEND);
	glEnable(GL_OUTLINE);
	
	glSetOutlineColor(0,RGB15(0,0,0)); //TEMP?
	glSetOutlineColor(1,RGB15(0,0,0)); //TEMP?
	glSetOutlineColor(7,RGB15(31,0,0)); //TEMP?
	glSetToonTableRange(0, 15, RGB15(8,8,8)); //TEMP?
	glSetToonTableRange(16, 31, RGB15(24,24,24)); //TEMP?
	
	glClearColor(31,31,0,31);
	glClearPolyID(63);
	glClearDepth(0x7FFF);

	glViewport(0,0,255,191);
	
	// initVramBanks(1);
	initVramBanks(2);
	initTextures();
	initSound();
	
	initCamera(NULL);
	
	initPlayer(NULL);
	
	initLights();
	initParticles();
	
	initMaterials();
	
	loadMaterialSlices("slices.ini");
	loadMaterials("materials.ini");
	loadControlConfiguration("config.ini");
	
	initElevators();
	initWallDoors();
	initTurrets();
	initBigButtons();
	initTimedButtons();
	initEnergyBalls();
	initPlatforms();
	initCubes();
	initEmancipation();
	initDoors();
	initSludge();
	initPause();

	initText();

	NOGBA("lalala");

	getPlayer()->currentRoom=&gameRoom;
	
	currentBuffer=false;
	
	getVramStatus();
	fadeIn();
	
	mainBG=bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
	bgSetPriority(mainBG, 0);
	REG_BG0CNT=BG_PRIORITY(3);
	
	#ifdef DEBUG_GAME
		consoleInit(&bottomScreen, 3, BgType_Text4bpp, BgSize_T_256x256, 16, 0, false, true);
		consoleSelect(&bottomScreen);
	#endif
	
	// glSetToonTableRange(0, 14, RGB15(16,16,16));
	// glSetToonTableRange(15, 31, RGB15(26,26,26));
	
	initPortals();
	
	//PHYSICS
	initPI9();

	strcpy(&mapFilePath[strlen(mapFilePath)-3], "map");
	newReadMap(mapFilePath, NULL, 255);
	
	transferRectangles(&gameRoom);
	makeGrid();
	generateRoomGrid(&gameRoom);
	gameRoom.displayList=generateRoomDisplayList(&gameRoom, vect(0,0,0), vect(0,0,0), false);
	
	getVramStatus();
	
	startPI();

	NOGBA("START mem free : %dko (%do)",getMemFree()/1024,getMemFree());
	NOGBA("vs mem free : %dko (%do)",oldv/1024,oldv);

	levelInfoCounter=60;
}