Example #1
0
std::string getEtcHostsContent() {
  std::string content;
  readFile(fs::path(kTestDataPath) / "test_hosts.txt", content);
  return content;
}
Example #2
0
 string procStat()
 {
     string result;
     readFile("/proc/self/stat", result);
     return result;
 }
Example #3
0
void LogReader::readFile(int i)
{
    qint64 index = configuration.getIndex();
    QString lastLine;

    QFile file(directory.absolutePath()+fileList.at(i));
    if (!file.exists())
        return;
    if (!file.open(QIODevice::ReadOnly)){
        qDebug() << "File not found or can't be read.";
        return;
    }
    qDebug() << "File " + directory.absolutePath()+fileList.at(i) + " opened at " + QDateTime::currentDateTime().toString();

    QTextStream in(&file);
    in.seek(index);

    // O objeto recebe o conteúdo da linha na posição 'index' do arquivo texto
    lastLine = in.readLine();
    /*
     * Testa se o index não aponta para o inicio da linha.
     * Testa se o conteudo do objeto é o mesmo do conteudo do registro salvo.
     * No caso de ser diferente, ele invoca este mesmo programa \
     * para ver se o conteudo do objeto está no outro arquivo.
     * Se no final do processo ele não achar, seta o index como 0 \
     * para que o arquivo seja lido desde o inicio.
    */
    if (lastLine != configuration.getLastLine()) {
        if (i < fileList.size()-1) {
            qDebug() << "Last string readed not found, searching in a older file...";
            readFile(i+1);
        }
        index = 0;
        in.seek(index);
    }

    qDebug() << "Reading file...";
    emit(readToWrite());

    /*
     * Posiciona entrada de dados na última posição lida no arquivo;
     * Como essa linha já foi lida e processada na última vez, ele lê ela
     * e não faz nada, para que no próximo passo ele possa processar dados novos.
     * O objeto lastLine recebe os dados para que caso ele não tenha mais nada que processar,
     * não salve o lastLine em branco no procedimento de salvar.
     */
    while (!in.atEnd()) {
        lastLine = in.readLine();
        //qDebug () << lastLine;
        /*
         * Aqui processará os dados contidos no objeto lastLine
        */
        emit dataReceived(lastLine);
    }

    emit(writenDone());
    /*
     * O valor do index é igual a posição atual no arquivo, diminuido do tamanho do registro anterior,
     * e decrementado 2(duas) unidades, que é o valor do '\n'.
     *
     */
    index = in.pos()-lastLine.size()-2;

    configuration.setIndex(index);
    configuration.setLastLine(lastLine);
    configuration.doWrite();

    file.close();
    qDebug() << "File " + directory.absolutePath()+fileList.at(i) + " closed at " + QDateTime::currentDateTime().toString();
}
Example #4
0
 virtual ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
 {
     return readFile(NODE,fileName,options);
 }
Example #5
0
/*FGROUP SSM_VME_Access ReadSSM
Analyze SSM memory - like AS python + check of serial versus TTC
*/
int analyze(){    
 int i,j,bit,word,ier;
 //int first=1;
 /*         L0 L1s L2s AE  */
 char *SIGname[]={"ORB","PP ","L0 ","L1s","L1d","L2s","L2d","sBU","lBU","1FF","2FF","ChA","ChB","TBU","PPT","SST","STA","AER"};
 int NPR=6;
 char *PRINT[]={"PP ","L0 ","L1s","L2s","AER","LBH"};
 int COUNT[18]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};  /* COUNT SSM signals */
 int COUNTe[18]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* COUNT errors */
 int COUNTl[18]={0,0,-DISTL0,-DISTL1,0,-DISTL2,0,0,0,0,0,0,0,0,0,0,0,0}; /* How close they can be ? */
 int COUNTa[18]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* Is signal active ? */
 int DIST[18]={0,0,DISTL0,DISTL1,0,DISTL2,0,0,0,0,0,0,0,0,0,0,1,0}; /* How close the signals can be ? */
 int L1DATA[NL1dat],L2DATA[NL2dat];
 int iL1d=0,iL2d=0,ivmes=0;
 int iorbi=0,ipp=0,ialls=0;
 int isdb=0,iltb=0,il1fi=0,il2fi=0,icha=0,ittcbusy=0,ippt=0;
 if(readFile()!=0) exit(9);
 dump=NULL;
 analTTCB();
 printf("analTTCB finished \n");
 ttcboffset=1;
 for(i=ttcboffset;i<Mega;i++){
   //if(i %10000 ==0)printf("%i \n",i);
   word=SSMem[i];
   // start only after first L0
   //bit= ( (word & 4) == 4);
   //if(bit) first=0;
   //if(first) continue;
   for(j=0;j<18;j++){
    bit= ( (word & (1<<j)) == (1<<j));
    switch(j){
     case  0:    /* ORBIT   */
	   lsig(0,bit,i,COUNT,COUNTa,&iorbi,"ORBIT");  
           break;
     case  1:    /* PREPULSE    */
           lsig(1,bit,i,COUNT,COUNTa,&ipp," PP");
	   break;
     case  2:  /* L0 */
	   ssig(2,bit,i,COUNT,COUNTa,COUNTl,COUNTe,DIST,"L0");
           break;
     case  3:  /* L1s */  	   
	   asig(3,bit,i,COUNT,COUNTa,COUNTl,COUNTe,DIST,"L1S");
           break;
     case  4:   /* L1data */
	   ier=data(4,bit,i,COUNTa,L1DATA,NL1dat,&iL1d,"L1DATA");
           break;
     case  5:   /* L2 strobe */
           asig(5,bit,i,COUNT,COUNTa,COUNTl,COUNTe,DIST,"L2S");
	   break;
     case  6:   /* L2 data */
	   ier=data(6,bit,i,COUNTa,L2DATA,NL2dat,&iL2d,"L2DATA");
           break;
     case  7: /* Sub Detector Busy */
	   lsig(7,bit,i,COUNT,COUNTa,&isdb,"SBUSY");
           break;
     case  8: /* LTU BUSY */
	   lsig(8,bit,i,COUNT,COUNTa,&iltb,"ALLBUSY");
           break;
     case  9: /* L1 FIFO Nearly Full */
	   lsig(9,bit,i,COUNT,COUNTa,&il1fi,"L1NF");
           break;
     case 10: /* L2 FIFO Nearly Full */
	   lsig(10,bit,i,COUNT,COUNTa,&il2fi,"L2NF");
           break;
     case 11: /* Channel A (L0) */
	   lsig(11,bit,i,COUNT,COUNTa,&icha,"ChanA");
           break;
     case 12:    /*  Channel B */
           //channelB(12,bit,i,COUNT,COUNTa,&ichb,TT,"ChanB");
           break;
     case 13:   /* TTC  BUSY */
           lsig(13,bit,i,COUNT,COUNTa,&ittcbusy,"TTCBUSY"); 
           break;
     case 14:          /* PP transmit */
           lsig(14,bit,i,COUNT,COUNTa,&ippt,"PPT"); 
           break;
     case 15:    /*  vme SLAVE strobe  */
	   lsig(15,bit,i,COUNT,COUNTa,&ivmes,"VMES");
           break;
     case 16:   /* START ALL - emulator */
	   //lsig(16,bit,i,COUNT,COUNTa,&ialls,"ALLSTART");
	   break;
     case 17: /* ANY ERROR */
	   ssig(17,bit,i,COUNT,COUNTa,COUNTl,COUNTe,DIST,"ANYERR");
           break;
    }
   }
 }
 // to take into acount signals up in all memory
 lsig(1,0,Mega,COUNT,COUNTa,&ipp," PP");
 lsig(7,0,Mega,COUNT,COUNTa,&isdb,"SBUSY");
 lsig(8,0,Mega,COUNT,COUNTa,&iltb,"ALLBUSY");
 lsig(9,0,Mega,COUNT,COUNTa,&il1fi,"L1NF");
 lsig(10,0,Mega,COUNT,COUNTa,&il2fi,"L2NF");
 lsig(11,0,Mega,COUNT,COUNTa,&icha,"LBHALT");
 //lsig(12,0,Mega,COUNT,COUNTa,&ivmem,"VMEM");
 lsig(13,0,Mega,COUNT,COUNTa,&ittcbusy,"TTCBUSY"); 
 lsig(15,0,Mega,COUNT,COUNTa,&ivmes,"VMES");
 lsig(16,0,Mega,COUNT,COUNTa,&ialls,"ALLSTART");
 for(i=0;i<NPR;i++){
  for(j=0;j<18;j++)if(SIGname[j] == PRINT[i])
	  printf("<%s=%i> ",SIGname[j],COUNT[j]);
 }
 printf("\n");
 writeLog();
 return 0;
}
Example #6
0
void TutorialLevel::setup(){
    INFO("Generating Tutorial Level...");
    readFile();
    initalizeGrid();
    createRenders();
    createLevel();
    waterSurfaceManager = WaterSurfaceManagerPtr(new WaterSurfaceManager());
    addGameObject(waterSurfaceManager);
    INFO("Removal String so less of make");
    INFO("Setting up the cameras for the Test Level...");
    CameraPtr cam3(new Camera(glm::vec3(25, 30, 0), glm::vec3(10, 20, 6),
                             glm::vec3(0, 1, 0)));
    cam3->setProjectionMatrix(
        glm::perspective(glm::radians(90.0f),
                        (float) Global::ScreenWidth/Global::ScreenHeight,
                        0.1f, 100.f));

    addCamera("CinematicCamera", cam3);
    setMainCamera("CinematicCamera");
    setCullingCamera("CinematicCamera");

    CameraPtr cam1(new Camera(glm::vec3(4, 10, -5), glm::vec3(4, 4, -10),
                              glm::vec3(0, 1, 0)));
    cam1->setProjectionMatrix(
        glm::perspective(glm::radians(90.0f),
                         (float) Global::ScreenWidth/Global::ScreenHeight,
                         0.1f, 100.f));
    addCamera("Camera1", cam1);
 
    CameraPtr cam2(new Camera(glm::vec3(0, 1, 0), glm::vec3(-6, -3, 6),
                              glm::vec3(0, 1, 0)));
    cam2->setProjectionMatrix(
        glm::perspective(glm::radians(90.0f),
                         (float) Global::ScreenWidth/Global::ScreenHeight,
                         0.1f, 100.f));
    l1 = LightPtr(new Light(glm::vec3(1), 30.0f, glm::vec3(0, 30, 0)));
    l1->setPosition(l1->getDirection());

    Uniform3DGridPtr<int> typeGrid = getTypeGrid();
    gridCenter = glm::vec3((typeGrid->getMaxX() - typeGrid->getMinX())/2.0f,
                           (typeGrid->getMaxY() - typeGrid->getMinY())/2.0f,
                           (typeGrid->getMinZ() - typeGrid->getMaxZ())/2.0f);
    l1->setViewMatrix(glm::lookAt(

        l1->getPosition(),
        gridCenter, glm::vec3(0, 1, 0)));
    l1->setProjectionMatrix(glm::ortho<float>(-30,30,-30,30,-70,70));

    addLight("Sun", l1);
    INFO("Setting up the player for the Test Level...");
    cinematicPlayer = CinematicPlayerPtr(new CinematicPlayer(cam3));
    cinematicPlayer->setup();
    addGameObject("cinematicPlayer", cinematicPlayer);

    player = PlayerPtr(new Player(cam1, 2));
    player->setup();
    addGameObject("player" , player);
    CollisionManager::addCollisionObjectToList(player);
    debugPlayer = DebugPlayerPtr(new DebugPlayer(cam2));
    debugPlayer->setup();
    addGameObject("debugPlayer" , debugPlayer);
    //Text
    addCamera("DebugCamera", cam2);

    sky = ObjectPtr(new Object(
        LoadManager::getMesh("sphere.obj"),
        MaterialManager::getMaterial("None")));

    sky->applyTexture(LoadManager::getTexture("Sky"));
    sky->enableTexture();
    sky->scale(glm::vec3(-90.0f,-90.0f,-90.0f));
    sky->translate(Director::getScene()->getCamera()->getEye());
    RenderEngine::getRenderElement("textured")->addObject(sky);

    ExclamationPtr exclamation = ExclamationPtr(new Exclamation(glm::vec3(30, 26, -48)));
    exclamation->setup();
    addGameObject("exclamation", exclamation);
}
Example #7
0
 virtual ReadResult readObject(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
 {
     return readFile(OBJECT,fileName,options);
 }
Example #8
0
Status readFile(const fs::path& path, bool blocking) {
  std::string blank;
  return readFile(path, blank, 0, true, false, blocking);
}
Example #9
0
Status forensicReadFile(const fs::path& path,
                        std::string& content,
                        bool blocking) {
  return readFile(path, content, 0, false, true, blocking);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void VtkStructuredPointsReader::dataCheck()
{
  initialize();
  setErrorCondition(0);

  QFileInfo fi(getInputFile());
  if (getInputFile().isEmpty() == true)
  {
    QString ss = QObject::tr("The input file must be set");
    setErrorCondition(-61000);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }
  else if (fi.exists() == false)
  {
    QString ss = QObject::tr("The input file does not exist");
    setErrorCondition(-61001);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }

  // First shot Sanity Checks.
  if(!getReadCellData() && !getReadPointData())
  {
    QString ss = QObject::tr("At least one of Read Point Data or Read Cell Data must be checked");
    setErrorCondition(-61002);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }

  // Last chance sanity check
  if(getErrorCondition() < 0) { return; }

  // Create a Vertex Data Container even though we may remove it later. We need it later
  // on in order to set the proper AttributeMatrix
  DataContainer::Pointer pointData_DataContainer = getDataContainerArray()->createNonPrereqDataContainer<AbstractFilter>(this, getVertexDataContainerName());
  if(getErrorCondition() < 0 && NULL == pointData_DataContainer) { return; }

  ImageGeom::Pointer pointDataGeom = ImageGeom::CreateGeometry(getVertexDataContainerName());
  pointData_DataContainer->setGeometry(pointDataGeom);

  QVector<size_t> tDims(1, 0);
  AttributeMatrix::Pointer pointAttrMat = pointData_DataContainer->createNonPrereqAttributeMatrix<AbstractFilter>(this, getVertexAttributeMatrixName(), tDims, SIMPL::AttributeMatrixType::Cell);
  if(getErrorCondition() < 0) { return; }

  // Create a Volume Data Container even though we may remove it later. We need it later
  // on in order to set the proper AttributeMatrix
  DataContainer::Pointer cellData_DataContainer = getDataContainerArray()->createNonPrereqDataContainer<AbstractFilter>(this, getVolumeDataContainerName());
  if(getErrorCondition() < 0 && NULL == cellData_DataContainer) { return; }

  ImageGeom::Pointer cellDataGeom = ImageGeom::CreateGeometry(getVolumeDataContainerName());
  cellData_DataContainer->setGeometry(cellDataGeom);

  tDims.resize(3);
  tDims[0] = 0;
  tDims[1] = 0;
  tDims[2] = 0;
  AttributeMatrix::Pointer cellAttrMat = cellData_DataContainer->createNonPrereqAttributeMatrix<AbstractFilter>(this, getCellAttributeMatrixName(), tDims, SIMPL::AttributeMatrixType::Cell);
  if(getErrorCondition() < 0) { return; }

  // Scan through the file
  readFile();

  // now check to see what the user wanted
  if (!getReadPointData())
  {
    getDataContainerArray()->removeDataContainer(getVertexDataContainerName());
  }
  if (!getReadCellData())
  {
    getDataContainerArray()->removeDataContainer(getVolumeDataContainerName());
  }

  // If there was no Cell Data, remove that dataContainer
  if (cellAttrMat->getNumAttributeArrays() == 0)
  {
    getDataContainerArray()->removeDataContainer(getVolumeDataContainerName());
  }

  // If there were no Point Arrays then remove that dataContainer
  if (pointAttrMat->getNumAttributeArrays() == 0)
  {
    getDataContainerArray()->removeDataContainer(getVertexDataContainerName());
  }
}
Example #11
0
/** initialization */
bool GameControl::init(const char *configFileName, const char *logFileName, bool restart) 
{
	/** HALT */
    _lastCommand = 'H';
    _lastCommandCounter = 0;

    /** set enabled to true */
    _enabled = true;
    
    /** will be set to true if found */
    _hasSerial = false;
    
    /** default serial device */
    _serialDevice = (char *)"/dev/ttyS0";


    /** default multicast address */
    _multicastAddress = "224.5.23.1";
    
    /** default multicast port */
    _multicastPort = 10001;
  
    printf("checking file\n");
    
    if (!readFile(configFileName)) {
        printf("filename bad.\n");
        fprintf(stderr, "ERROR: Cannot read config file %s\n", configFileName);
        return (false);
    }
    
    printf("filename ok\n");
    
    /* test multicast address and multicast port number */
    printf("MulticastAddress: %s\n", _multicastAddress.c_str());
    printf("MulticastPort: %hd\n", _multicastPort);

    try {
    	
    	_broadcast.setDestination(_multicastAddress.c_str(),_multicastPort);
    	
    }
    catch (UDP_Broadcast::IOError& e)
    {
        std::cerr << "Broadcast: " << e.what() << std::endl;
    }
    
    // a little user output
    print();

    /** open the serial port */
    fprintf(stderr, "Opening Serial Connection on device %s ...\n", _serialDevice);
    if (!_serial.open(_serialDevice, COMM_BAUD_RATE)) {
        fprintf(stderr, "ERROR: Cannot open serial connection..\n");
        //return (false);  // temporarily commented out
    } else {
        _hasSerial = true;
    }
    
    /** intialize the timer */
    _gameInfo.resetTimer();
    _tLast = getCurrentTime();

    if (!_gameInfo.openLog(logFileName)) {
        fprintf(stderr, "ERROR: Cannot open log file %s..\n", logFileName);
        return (false);
    }

    /** restart from saved state */
    if (restart) {
        _gameInfo.load(_saveName);
    }

    return (true);
}
Example #12
0
int main(void)
{
	Node * headNew = NULL,
			 * tailNew = headNew,
			 * headReady = NULL,            // linked list head pointer
       * tailReady = headReady,       // linked list tail pointer
       * headTerminated = NULL,
       * tailTerminated = headTerminated; 


	pthread_mutex_init(&mutexNew, NULL);
	pthread_mutex_init(&mutexReady, NULL);
	pthread_mutex_init(&mutexTerminated, NULL);

	FILE *ptr_file = NULL;              // File pointer


	// read the file
	readFile(ptr_file, &headNew, &tailNew);
	
	
	time_t startSimTime,
				 endSimTime;
				 
				 
	time(&startSimTime);
	
	pthread_t ThreadA;
	
	
	while(LinkedListgetSize(headTerminated, &mutexTerminated) != jobcount)
	{
		if (headNew)
		{			
			Args1 *args1 = (Args1 *)malloc(sizeof(Args1));
			args1 -> head1 = &headNew;
			args1 -> head2 = &headReady;
			args1 -> tail1 = &tailReady;
			args1 -> head3 = &headTerminated;
			args1 -> tail2 = &tailTerminated;
				
			pthread_create(&ThreadA, NULL, admitted, (void *)args1);
		}
		
		CPUExecution(&headReady, &tailReady, &headTerminated, &tailTerminated);
	}		
	
	
	time(&endSimTime);
	
	
	double throughPut = calcThroughPut(startSimTime, endSimTime);
	double avgWaitTime = calcAvgWaitTime(headTerminated);
	double avgTurnAroundTime = calcAvgTurnAroundTime(startSimTime, headTerminated);
	
	printf("The size of the job queue is: %i\n", LinkedListgetSize(headReady, &mutexReady));
	printf("The size of the terminated queue is: %i\n", LinkedListgetSize(headTerminated, &mutexTerminated));
	
	
	printf("\nThe throughput is: %lf\n", throughPut);
	printf("The avg wait time is: %lf\n", avgWaitTime);
	printf("The avg turn around time is: %lf\n", avgTurnAroundTime);

	pthread_mutex_destroy(&mutexNew);
	pthread_mutex_destroy(&mutexReady);
	
	return 0;
}
Example #13
0
void myInit(void)
{	
	glClearColor(0.0,0.0,0.0,0.0);
	//------------------------------------------------------------Object & Texture
	readFile("/Users/jiharu/svn/594CM/gl_obj/obj/triangular/Shatter1.obj");
	loadTextures();
	
	//DEFINE NIGTHS in some INIT function..
	glEnable(GL_LIGHTING); //enable lighting
	glShadeModel (GL_SMOOTH); //GL_SMOOTH, GL_FLAT
#pragma mark -
#pragma mark light
	//------------------------------------------------------------Light
	//define the lighting model
	float ambient[] = {0.08, 0.08, 0.01, 1.0};
	float diffuse[] = {0.7, 0.7, 0.0, 1.0};
	float specular[] = {0.3, 0.3, 0.3, 1.0};
	
	glEnable(GL_LIGHT0); //turn on one of the lights
	//	glDisable(GL_LIGHT0);
	glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);	
	glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
	
	//------------------------------------------------------------Spot Light 1, 2, & 3
	float spot_direction1[] = { 0.0, -1.0, 0.0 }; 
	float ambient1[] = {0.01, .2, 0.5, 1.0};
	float diffuse1[] = {0.01, 0.5, 0.5, 1.0};
	float specular1[] = {0.0, 0.3, 1.0, 1.0};
	
	glEnable(GL_LIGHT1); //turn on one of the lights
	//	glDisable(GL_LIGHT1);	
	glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
	glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);	
	glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
	
	glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, spot_direction1);
	glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.5); 
	glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.5); 
	glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0.2);
	glLightf (GL_LIGHT1, GL_SPOT_CUTOFF, 30.0);	// degrees
	glLightf (GL_LIGHT1, GL_SPOT_EXPONENT, 2.0);
	
	float spot_direction2[] = { 0.0, -1.0, 0.0 }; 	
	float ambient2[] = {0.9, 0.1, 0.01, 1.0};
	float diffuse2[] = {0.9, 0.5, 0.0, 1.0};
	float specular2[] = {1.0, 0.1, 0.1, 1.0};
	
	glEnable(GL_LIGHT2); //turn on one of the lights
	//	glDisable(GL_LIGHT2);	
	glLightfv(GL_LIGHT2, GL_AMBIENT, ambient2);
	glLightfv(GL_LIGHT2, GL_DIFFUSE, diffuse2);	
	glLightfv(GL_LIGHT2, GL_SPECULAR, specular2);
	
	glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, spot_direction2);
	glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, 1.5); 
	glLightf(GL_LIGHT2, GL_LINEAR_ATTENUATION, 0.8); 
	glLightf(GL_LIGHT2, GL_QUADRATIC_ATTENUATION, 0.2);
	glLightf (GL_LIGHT2, GL_SPOT_CUTOFF, 45.0);	// degrees
	glLightf (GL_LIGHT2, GL_SPOT_EXPONENT, 1.0);
		
	float spot_direction3[] = { .5, -1.0, 0.0 }; 
	float ambient3[] = {0.5, 0.5, 0.5, 1.0};
	float diffuse3[] = {1.0, 1.0, 1.0, 1.0};
	float specular3[] = {1.0, 1.0, 1.0, 1.0};
	
	glEnable(GL_LIGHT3); //turn on one of the lights
	//	glDisable(GL_LIGHT2);	
	glLightfv(GL_LIGHT3, GL_AMBIENT, ambient3);
	glLightfv(GL_LIGHT3, GL_DIFFUSE, diffuse3);	
	glLightfv(GL_LIGHT3, GL_SPECULAR, specular3);
	
	glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, spot_direction3);
	glLightf(GL_LIGHT3, GL_CONSTANT_ATTENUATION, 0.5); 
	glLightf(GL_LIGHT3, GL_LINEAR_ATTENUATION, 0.8); 
	glLightf(GL_LIGHT3, GL_QUADRATIC_ATTENUATION, 0.2);
	glLightf (GL_LIGHT3, GL_SPOT_CUTOFF, 45.0);	// degrees
	glLightf (GL_LIGHT3, GL_SPOT_EXPONENT, 2.0);
	
	#pragma mark material
	//------------------------------------------------------------material
	//define the material of the object
	float mat_shininess[] = { 50. };
	float mat_ambient[] = { 0.7, 0.7, 0.7, 1.0 };
	float mat_diffuse[] = { 0.1, 0.5, 0.8, 1.0 };
	float mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
	float mat_emission[] = {1.0, 0.1, 0.1, 1.0};
	
	glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
	glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); 
	glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); 
	glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
	glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission); 
	
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glClearAccum(0.0, 0.0, 0.0, 0.0);
	
	checkForGLErrors("clearInit");
}
Example #14
0
std::string getEtcProtocolsContent() {
  std::string content;
  readFile(fs::path(kTestDataPath) / "test_protocols.txt", content);
  return content;
}
Example #15
0
PLYPMVS_Reader::PLYPMVS_Reader(const char* fileP):IOInterface(fileP){
	readFile();
}
Example #16
0
int main(int argc, char *argv[])
{
  std::string incr_kernel_str;

  /* Provide names of the OpenCL kernels
   * and cl file that they're kept in */
  std::string incr_name_str = 
    std::string("incr");
  std::string incr_kernel_file = 
    std::string("incr.cl");

  cl_vars_t cv; 
  cl_kernel incr;

  /* Read OpenCL file into STL string */
  readFile(incr_kernel_file,
	   incr_kernel_str);
  
  /* Initialize the OpenCL runtime 
   * Source in clhelp.cpp */
  initialize_ocl(cv);
  
  /* Compile all OpenCL kernels */
  compile_ocl_program(incr, cv, incr_kernel_str.c_str(),
		      incr_name_str.c_str());
  
  /* Arrays on the host (CPU) */
  float *h_Y, *h_YY;
  /* Arrays on the device (GPU) */
  cl_mem g_Y;

  // Allocate arrays on the host and fill with random data.
  int n = (1<<20);
  h_Y = new float[n];
  h_YY = new float[n];
   
  for(int i = 0; i < n; i++)
    {
      h_YY[i] = h_Y[i] = (float)drand48();
    }

  cl_int err = CL_SUCCESS;
  /* CS194: Allocate memory for arrays on 
   * the GPU */

  // Allocate the buffer memory objects.
  g_Y = clCreateBuffer(cv.context,CL_MEM_READ_WRITE,sizeof(float)*n,NULL,&err);
  CHK_ERR(err);

  // Write data from CPU to GPU.(this is opposite of clEnqueueReadBuffer())
  err = clEnqueueWriteBuffer(cv.commands, g_Y, true, 0, sizeof(float)*n,
			     h_Y, 0, NULL, NULL);
  CHK_ERR(err);
   
  // Define the global and local workgroup sizes.
  size_t global_work_size[1] = {n};
  size_t local_work_size[1] = {128};
    
  // Set the kernel args values.
  err = clSetKernelArg(incr, 0, sizeof(cl_mem), &g_Y);
  CHK_ERR(err);
  err = clSetKernelArg(incr, 1, sizeof(int), &n);
  CHK_ERR(err);

  // Call kernel on the GPU.
  err = clEnqueueNDRangeKernel(cv.commands,
			       incr,
			       1,//work_dim,
			       NULL, //global_work_offset
			       global_work_size, //global_work_size
			       local_work_size, //local_work_size
			       0, //num_events_in_wait_list
			       NULL, //event_wait_list
			       NULL //
			       );
  CHK_ERR(err);

  /* Read result of GPU on host CPU */
  err = clEnqueueReadBuffer(cv.commands, g_Y, true, 0, sizeof(float)*n,
			    h_Y, 0, NULL, NULL);
  CHK_ERR(err);

  /* Check answer */
  bool er = false;
  for(int i = 0; i < n; i++)
    {
      float d = (h_YY[i] + 1.0f);
      if(h_Y[i] != d)
	{
	  printf("error at %d :(\n", i);
	  er = true;
	  break;
	}
    }
  if(!er)
    {
      printf("CPU and GPU results match\n");
    }

  uninitialize_ocl(cv);
  
  delete [] h_Y;
  delete [] h_YY;

  clReleaseMemObject(g_Y);
  
  return 0;
}
Example #17
0
/****************************************************************************
**
** Copyright (C) 2016
**
** This file is generated by the Magus toolkit
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/

// Include
#include "constants.h"
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QMenuBar>
#include "mainwindow.h"
#include "OgreItem.h"
#include "OgreHlmsPbs.h"
#include "OgreHlmsUnlit.h"
#include "OgreHlmsPbsDatablock.h"
#include "OgreHlmsUnlitDatablock.h"
#include "OgreHlmsManager.h"

//****************************************************************************/
MainWindow::MainWindow(void) :
    mIsClosing(false),
    mFirst(true)
{
    installEventFilter(this);

    // Create the Ogre Manager
    mOgreManager = new Magus::OgreManager();
    mHlmsName = QString("");
    mTempString = QString("");
    
	// Perform standard functions
    createActions();
    createMenus();
    createToolBars();
    createStatusBar();
    createDockWindows();
    mMaterialBrowser = new MaterialBrowserDialog(this);
    loadMaterialBrowserCfg();

    mOgreManager->initialize();

    // Set the title
    setWindowTitle(QString("HLMS editor"));

    // Set the stylesheet of the application
    QFile File(QString("dark.qss"));
    File.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(File.readAll());
    setStyleSheet(styleSheet);
	showMaximized();
}

//****************************************************************************/
MainWindow::~MainWindow(void)
{
    delete mOgreManager;
}

//****************************************************************************/
bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
    if (event->type()==QEvent::KeyPress)
    {
        QKeyEvent* key = static_cast<QKeyEvent*>(event);
        if (key->key() == Qt::Key_F5)
        {
            // F5 was pressed
            mNodeEditorDockWidget->generateDatablock();
        }
        if (key->key() == Qt::Key_S && (QApplication::keyboardModifiers() & Qt::ControlModifier))
        {
            // CTRL+S was pressed
            doSaveDatablockMenuAction();
        }
    }
    return QObject::eventFilter(object, event);
}

//****************************************************************************/
void MainWindow::closeEvent(QCloseEvent* event)
{
    mIsClosing = true;
}

//****************************************************************************/
void MainWindow::createActions(void)
{
    // File menu
    mNewHlmsPbsAction = new QAction(QString("Pbs"), this);
    connect(mNewHlmsPbsAction, SIGNAL(triggered()), this, SLOT(doNewHlmsPbsAction()));
    mNewHlmsUnlitAction = new QAction(QString("Unlit"), this);
    connect(mNewHlmsUnlitAction, SIGNAL(triggered()), this, SLOT(doNewHlmsUnlitAction()));
    mOpenDatablockMenuAction = new QAction(QString("Open Hlms"), this);
    connect(mOpenDatablockMenuAction, SIGNAL(triggered()), this, SLOT(doOpenDatablockMenuAction()));
    mSaveDatablockMenuAction = new QAction(QString("Save Hlms"), this);
    connect(mSaveDatablockMenuAction, SIGNAL(triggered()), this, SLOT(doSaveDatablockMenuAction()));
    mSaveAsDatablockMenuAction = new QAction(QString("Save Hlms as"), this);
    connect(mSaveAsDatablockMenuAction, SIGNAL(triggered()), this, SLOT(doSaveAsDatablockMenuAction()));
    mQuitMenuAction = new QAction(QString("Quit"), this);
    connect(mQuitMenuAction, SIGNAL(triggered()), this, SLOT(doQuitMenuAction()));

    // Materials menu
    mMaterialBrowserOpenMenuAction = new QAction(QString("Open browser"), this);
    connect(mMaterialBrowserOpenMenuAction, SIGNAL(triggered()), this, SLOT(doMaterialBrowserOpenMenuAction()));
    mMaterialBrowserAddMenuAction = new QAction(QString("Add Hlms to browser"), this);
    connect(mMaterialBrowserAddMenuAction, SIGNAL(triggered()), this, SLOT(doMaterialBrowserAddMenuAction()));

    // Window menu
    mResetWindowLayoutMenuAction = new QAction(QString("Reset Window Layout"), this);
    connect(mResetWindowLayoutMenuAction, SIGNAL(triggered()), this, SLOT(doResetWindowLayoutMenuAction()));
}

//****************************************************************************/
void MainWindow::createMenus(void)
{
    mFileMenu = menuBar()->addMenu(QString("&File"));
    mMaterialBrowserMenu = menuBar()->addMenu(QString("&Materials"));
    QMenu* fileMenuAction = mFileMenu->addMenu("New Hlms");
    fileMenuAction->addAction(mNewHlmsPbsAction);
    fileMenuAction->addAction(mNewHlmsUnlitAction);
    mFileMenu->addAction(mOpenDatablockMenuAction);
    mFileMenu->addAction(mSaveDatablockMenuAction);
    mFileMenu->addAction(mSaveAsDatablockMenuAction);
    mFileMenu->addAction(mQuitMenuAction);
    mMaterialBrowserMenu->addAction(mMaterialBrowserOpenMenuAction);
    mMaterialBrowserMenu->addAction(mMaterialBrowserAddMenuAction);
    mWindowMenu = menuBar()->addMenu(QString("&Window"));
    mWindowMenu->addAction(mResetWindowLayoutMenuAction);

}

//****************************************************************************/
void MainWindow::createToolBars(void)
{

}

//****************************************************************************/
void MainWindow::createStatusBar(void)
{

}

//****************************************************************************/
void MainWindow::createDockWindows(void)
{
    mRenderwindowDockWidget = new RenderwindowDockWidget("Renderwindow", this);
    addDockWidget(Qt::LeftDockWidgetArea, mRenderwindowDockWidget);
    mPropertiesDockWidget = new PropertiesDockWidget("Properties", this);
    addDockWidget(Qt::LeftDockWidgetArea, mPropertiesDockWidget);
    mNodeEditorDockWidget = new NodeEditorDockWidget("NodeEditor", this);
    setCentralWidget(mNodeEditorDockWidget);
}

//****************************************************************************/
void MainWindow::doNewHlmsPbsAction(void)
{
    initDatablocks();
    mPropertiesDockWidget->clear();
    mNodeEditorDockWidget->newHlmsPbsAndSampler();
}

//****************************************************************************/
void MainWindow::doNewHlmsUnlitAction(void)
{
    initDatablocks();
    mPropertiesDockWidget->clear();
    mNodeEditorDockWidget->newHlmsUnlitAndSampler();
}

//****************************************************************************/
void MainWindow::doOpenDatablockMenuAction(void)
{
    // Load the materials
    QString fileName;
    fileName = QFileDialog::getOpenFileName(this, QString("Open Hlms file"),
                                            QString(""),
                                            QString("Json material (*.json)"));
    loadDatablock(fileName);
}

//****************************************************************************/
void MainWindow::loadDatablock(const QString jsonFileName)
{
    // Load the materials
    if (!jsonFileName.isEmpty())
    {
        // Read the json file as text file and feed it to the HlmsManager::loadMaterials() function
        // Note, that the resources (textures, etc.) must be present

        // First, delete all datablocks before loading the new ones
        initDatablocks();
        mPropertiesDockWidget->clear();

        // Read the json file
        Ogre::HlmsManager* hlmsManager = mOgreManager->getOgreRoot()->getHlmsManager();
        QFile file(jsonFileName);
        file.open(QFile::ReadOnly | QFile::Text);
        QTextStream readFile(&file);
        QString jsonString = readFile.readAll();
        QByteArray ba = jsonString.toLatin1();
        char* jsonChar = ba.data();
        Ogre::String fname = jsonFileName.toStdString();
        Ogre::HlmsJson hlmsJson(hlmsManager);
        try
        {
            // Load the datablocks (which also creates them)
            hlmsJson.loadMaterials(fname, jsonChar);
        }
        catch (Ogre::Exception e)
        {
            Ogre::LogManager::getSingleton().logMessage("MainWindow::doOpenDatablockMenuAction(); Could not load the materials\n");
        }
        file.close();
        mHlmsName = jsonFileName;

        // Get the (list of) datablocks and assign the first one to the current 'item' to be rendered
        getAndSetFirstDatablock();
    }
}

//****************************************************************************/
void MainWindow::destroyAllDatablocks(void)
{
    // Get the datablock from the item and remove it
    mOgreManager->getOgreWidget(OGRE_WIDGET_RENDERWINDOW)->setDefaultDatablockItem();
    Ogre::HlmsManager* hlmsManager = mOgreManager->getOgreRoot()->getHlmsManager();
    Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS));
    Ogre::HlmsUnlit* hlmsUnlit = static_cast<Ogre::HlmsUnlit*>( hlmsManager->getHlms(Ogre::HLMS_UNLIT));

    // Iterate through all pbs datablocks and remove them
    Ogre::Hlms::HlmsDatablockMap::const_iterator itorPbs = hlmsPbs->getDatablockMap().begin();
    Ogre::Hlms::HlmsDatablockMap::const_iterator endPbs  = hlmsPbs->getDatablockMap().end();
    Ogre::HlmsPbsDatablock* pbsDatablock;
    while( itorPbs != endPbs)
    {
        pbsDatablock = static_cast<Ogre::HlmsPbsDatablock*>(itorPbs->second.datablock);
        if (pbsDatablock != hlmsPbs->getDefaultDatablock() &&
                pbsDatablock != hlmsUnlit->getDefaultDatablock())
        {
            hlmsPbs->destroyDatablock(pbsDatablock->getName());
            itorPbs = hlmsPbs->getDatablockMap().begin(); // Start from the beginning again
        }
        else
            ++itorPbs;
    }

    // Iterate through all unlit datablocks and remove them
    Ogre::Hlms::HlmsDatablockMap::const_iterator itorUnlit = hlmsUnlit->getDatablockMap().begin();
    Ogre::Hlms::HlmsDatablockMap::const_iterator endUnlit  = hlmsUnlit->getDatablockMap().end();
    Ogre::HlmsUnlitDatablock* unlitDatablock;
    while( itorUnlit != endUnlit)
    {
        unlitDatablock = static_cast<Ogre::HlmsUnlitDatablock*>(itorUnlit->second.datablock);
        if (unlitDatablock != hlmsPbs->getDefaultDatablock() &&
                unlitDatablock != hlmsUnlit->getDefaultDatablock())
        {
            hlmsUnlit->destroyDatablock(unlitDatablock->getName());
            itorUnlit = hlmsUnlit->getDatablockMap().begin(); // Start from the beginning again
        }
        else
            ++itorUnlit;
    }
}

//****************************************************************************/
void MainWindow::getAndSetFirstDatablock(void)
{
    // Get the name/fullname from the current item in the renderwindow
    Ogre::Item* item = mOgreManager->getOgreWidget(OGRE_WIDGET_RENDERWINDOW)->getItem();
    Ogre::HlmsDatablock* oldDatablock = item->getSubItem(0)->getDatablock();
    Ogre::String oldDatablockName = *oldDatablock->getFullName();
    Ogre::IdString oldDatablockId = oldDatablock->getName();

    // Determine whether the HlmsManager contains a HLMS_PBS datablock or a HLMS_UNLIT datablock.
    // Depending on the result, the datablock of that type is retrieved and set in the mesh (item).
    Ogre::HlmsManager* hlmsManager = mOgreManager->getOgreRoot()->getHlmsManager();
    Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS));
    Ogre::HlmsUnlit* hlmsUnlit = static_cast<Ogre::HlmsUnlit*>( hlmsManager->getHlms(Ogre::HLMS_UNLIT));
    if (hlmsPbs)
    {
        int size = hlmsPbs->getDatablockMap().size();
        //QMessageBox::information(0, QString("info"), QVariant(size).toString());
        if (size> 1)
        {
            // It is a PBS; Note, that there is also a default (so always 1)
            Ogre::Hlms::HlmsDatablockMap::const_iterator itor = hlmsPbs->getDatablockMap().begin();
            Ogre::Hlms::HlmsDatablockMap::const_iterator end  = hlmsPbs->getDatablockMap().end();
            Ogre::HlmsPbsDatablock* newDatablock;
            Ogre::String newDatablockName;
            while( itor != end )
            {
                newDatablock = static_cast<Ogre::HlmsPbsDatablock*>(itor->second.datablock);
                if (newDatablock != hlmsPbs->getDefaultDatablock() && newDatablock != hlmsUnlit->getDefaultDatablock())
                {
                    // Get the first datablock
                    newDatablockName = *newDatablock->getFullName();
                    if (oldDatablockName != newDatablockName)
                    {
                        // Assign the datablock to the item (and destroy the items' old datablock, if still available)
                        item->setDatablock(newDatablock);
                        if (oldDatablock != hlmsPbs->getDefaultDatablock() && oldDatablock != hlmsUnlit->getDefaultDatablock())
                        {
                            if (oldDatablock->getCreator()->getType() == Ogre::HLMS_PBS)
                                hlmsPbs->destroyDatablock(oldDatablockId);
                            else if (hlmsUnlit && oldDatablock->getCreator()->getType() == Ogre::HLMS_UNLIT)
                                hlmsUnlit->destroyDatablock(oldDatablockId);
                        }

                        // Create the node structure
                        QString s = newDatablockName.c_str();
                        mNodeEditorDockWidget->createPbsNodeStructure(s);
                        mPropertiesDockWidget->setTextureTypePropertyVisible(true);
                        mPropertiesDockWidget->setMapWeightPropertyVisible(true);
                        break;
                    }
                }
                ++itor;
            }
            return;
        }
    }

    if (hlmsUnlit)
    {
        int size = hlmsUnlit->getDatablockMap().size();
        //QMessageBox::information(0, QString("info"), QVariant(size).toString());
        if (size > 1)
        {
            // It is an Unlit; Note, that there is also a default (so always 1)
            Ogre::Hlms::HlmsDatablockMap::const_iterator itor = hlmsUnlit->getDatablockMap().begin();
            Ogre::Hlms::HlmsDatablockMap::const_iterator end  = hlmsUnlit->getDatablockMap().end();
            Ogre::HlmsUnlitDatablock* newDatablock;
            Ogre::String newDatablockName;
            while( itor != end )
            {
                newDatablock = static_cast<Ogre::HlmsUnlitDatablock*>(itor->second.datablock);
                if (newDatablock != hlmsPbs->getDefaultDatablock() && newDatablock != hlmsUnlit->getDefaultDatablock())
                {
                    // Get the first datablock
                    newDatablockName = *newDatablock->getFullName();
                    if (oldDatablockName != newDatablockName)
                    {
                        // Assign the datablock to the item (and destroy the items' old datablock, if still available)
                        item->setDatablock(newDatablock);
                        if (oldDatablock != hlmsPbs->getDefaultDatablock() && oldDatablock != hlmsUnlit->getDefaultDatablock())
                        {
                            if (oldDatablock->getCreator()->getType() == Ogre::HLMS_UNLIT)
                                hlmsUnlit->destroyDatablock(oldDatablockId);
                            else if (hlmsPbs && oldDatablock->getCreator()->getType() == Ogre::HLMS_PBS)
                                hlmsPbs->destroyDatablock(oldDatablockId);
                        }

                        // Create the node structure
                        QString s = newDatablockName.c_str();
                        mNodeEditorDockWidget->createUnlitNodeStructure(s);
                        mPropertiesDockWidget->setTextureTypePropertyVisible(false);
                        mPropertiesDockWidget->setMapWeightPropertyVisible(false);
                        break;
                    }
                }
                ++itor;
            }
            return;
        }
    }
}

//****************************************************************************/
void MainWindow::getListOfResources(void)
{
    Ogre::ResourceGroupManager::ResourceManagerIterator it =
        Ogre::ResourceGroupManager::getSingletonPtr()->getResourceManagerIterator();
    while (it.hasMoreElements())
    {
        Ogre::ResourceManager* man = it.getNext();
        Ogre::LogManager::getSingleton().logMessage("Resource Type = " + man->getResourceType());
        Ogre::ResourceManager::ResourceMapIterator mapit = man->getResourceIterator() ;
        while (mapit.hasMoreElements())
        {
            Ogre::ResourcePtr ptr = mapit.getNext();
            Ogre::LogManager::getSingleton().logMessage("Resource Name = " + ptr->getName());
        }
    }
}

//****************************************************************************/
void MainWindow::doSaveDatablockMenuAction(void)
{
    if (mHlmsName.isEmpty())
        doSaveAsDatablockMenuAction();
    else
        saveDatablock();
}

//****************************************************************************/
void MainWindow::doSaveAsDatablockMenuAction(void)
{
    // Get hlms name
    mHlmsName = QString(mNodeEditorDockWidget->getCurrentDatablockName());
    mHlmsName = mHlmsName + QString(".material.json");
    QString fileName = mHlmsName;

    // Save all datablocks to one file
    fileName = QFileDialog::getSaveFileName(this,
                                            QString("Save the Hlms"),
                                            mHlmsName,
                                            QString("Json material (*.json)"));

    if (!fileName.isEmpty())
    {
        mHlmsName = fileName;
        saveDatablock();
    }
}

//****************************************************************************/
void MainWindow::saveDatablock(void)
{
    Ogre::String fname = mHlmsName.toStdString();
    QString baseNameJson = mHlmsName;
    baseNameJson = getBaseFileName(baseNameJson);
    QString thumb = baseNameJson + ".png";
    mOgreManager->getOgreWidget(OGRE_WIDGET_RENDERWINDOW)->saveToFile(THUMBS_PATH + thumb.toStdString());

    Ogre::HlmsManager* hlmsManager = mOgreManager->getOgreRoot()->getHlmsManager();
    if (getCurrentDatablockType() == EditorHlmsTypes::HLMS_PBS)
    {
        hlmsManager->saveMaterials (Ogre::HLMS_PBS, fname);
        mMaterialBrowser->addMaterial(baseNameJson, mHlmsName, thumb, HLMS_PBS);
    }
    else if (getCurrentDatablockType() == EditorHlmsTypes::HLMS_UNLIT)
    {
        hlmsManager->saveMaterials (Ogre::HLMS_UNLIT, fname);
        mMaterialBrowser->addMaterial(baseNameJson, mHlmsName, thumb, HLMS_UNLIT);
    }
}

//****************************************************************************/
void MainWindow::loadMaterialBrowserCfg(void)
{
    QVector<Magus::QtResourceInfo*> resources;
    QFile file(FILE_MATERIAL_BROWSER);
    QString line;
    if (file.open(QFile::ReadOnly))
    {
        QTextStream readFile(&file);
        Magus::QtResourceInfo* info;
        while (!readFile.atEnd())
        {
            line = readFile.readLine();
            QStringList elements = line.split('\t', QString::SkipEmptyParts);

            if (elements.size() == 6)
            {
                info = new Magus::QtResourceInfo();
                info->topLevelId = QVariant(elements[0]).toInt();
                info->parentId = QVariant(elements[1]).toInt();
                info->resourceId = QVariant(elements[2]).toInt();
                info->resourceName = elements[3];
                info->fullQualifiedName = elements[4];
                info->resourceType = QVariant(elements[5]).toInt();

                if (info->topLevelId == TOOL_SOURCES_LEVEL_X000_PBS &&
                        info->resourceType == TOOL_RESOURCETREE_KEY_TYPE_TOPLEVEL_GROUP)
                    info->iconName = TOOL_RESOURCE_ICON_PBS;
                else if (info->topLevelId == TOOL_SOURCES_LEVEL_X000_PBS &&
                         info->resourceType == TOOL_RESOURCETREE_KEY_TYPE_GROUP)
                    info->iconName = TOOL_RESOURCE_ICON_SMALL_PBS;

                if (info->topLevelId == TOOL_SOURCES_LEVEL_X000_UNLIT &&
                        info->resourceType == TOOL_RESOURCETREE_KEY_TYPE_TOPLEVEL_GROUP)
                    info->iconName = TOOL_RESOURCE_ICON_UNLIT;
                else if (info->topLevelId == TOOL_SOURCES_LEVEL_X000_UNLIT &&
                         info->resourceType == TOOL_RESOURCETREE_KEY_TYPE_GROUP)
                    info->iconName = TOOL_RESOURCE_ICON_SMALL_UNLIT;

                resources.append(info);
            }
        }

        // In case the file is empty or contains garbage, add toplevel items
        if (resources.size() == 0)
        {
             info = new QtResourceInfo();
             info->topLevelId = TOOL_SOURCES_LEVEL_X000_PBS;
             info->parentId = 0;
             info->resourceId = TOOL_SOURCES_LEVEL_X000_PBS;
             info->resourceName = QString("PBS");
             info->fullQualifiedName = QString("PBS");
             info->resourceType = TOOL_RESOURCETREE_KEY_TYPE_TOPLEVEL_GROUP;
             info->iconName = TOOL_RESOURCE_ICON_PBS;
             resources.append(info);

             info = new QtResourceInfo();
             info->topLevelId = TOOL_SOURCES_LEVEL_X000_UNLIT;
             info->parentId = 0;
             info->resourceId = TOOL_SOURCES_LEVEL_X000_UNLIT;
             info->resourceName = QString("Unlit");
             info->fullQualifiedName = QString("Unlit");
             info->resourceType = TOOL_RESOURCETREE_KEY_TYPE_TOPLEVEL_GROUP;
             info->iconName = TOOL_RESOURCE_ICON_UNLIT;
             resources.append(info);
        }

        // Set the resources
        mMaterialBrowser->setResources(resources);
        file.close();
    }
}
Example #18
0
int main (int argc, char** argv) {
    signal(SIGSEGV, AnsiSignalHandler);
    //    printf("SILK V0.1\n");
    char *startup;
    const char *progName;
    signal(SIGSEGV, AnsiSignalHandler);
    signal(SIGINT, AnsiSignalHandler);

    if (argc < 2) {
        startup = readFile("/usr/local/silkjs/builtin/interpreter.js");
        if (!startup) {
            startup = readFile("/usr/share/silkjs/builtin/interpreter.js");
        }
        progName = "interpreter";
    }
    else {
        startup = readFile(argv[1]);
        progName = argv[1];
    }
    if (!startup) {
        printf("%s not found\n", argv[1]);
        exit(1);
    }
    if (startup[0] == '#' && startup[1] == '!') {
        startup[0] = startup[1] = '/';
    }
    
    // v8 command line switches
    const char *switches = "--harmony";
    V8::SetFlagsFromString(switches, strlen(switches));
    
    {
        //		Isolate *isolate = Isolate::New();
        //		isolate->Enter();
        //		Locker lock(isolate);
        Locker locker;
        HandleScope scope;

        init_global_object();
        V8::SetCaptureStackTraceForUncaughtExceptions(true, 50); // , StackTrace::kDetailed);
        context = Context::New(NULL, globalObject);
        Context::Scope context_scope(context);
        {
            Locker locker;
            //			Debug::SetDebugMessageDispatchHandler(debugger, true);
            //			Debug::EnableAgent("silkjs", 5858);

            Handle<Script>init = Script::New(String::New("global=this; module = {}; include('builtin/all.js');"), String::New("builtin"));
            init->Run();
            V8::SetCaptureStackTraceForUncaughtExceptions(true, 50, StackTrace::kDetailed);
            TryCatch tryCatch;
            mainScript = Persistent<Script>::New(Script::Compile(String::New(startup), String::New(progName)));
            if (mainScript.IsEmpty()) {
                ReportException(&tryCatch);
                exit(1);
            }
            Handle<Value>v = mainScript->Run();
            if (v.IsEmpty()) {
                ReportException(&tryCatch);
                exit(1);
            }
            Handle<String> process_name = String::New("main");
            Handle<Value> process_val = context->Global()->Get(process_name);
            if (!process_val.IsEmpty() && process_val->IsFunction()) {
                Handle<Function> process_fun = Handle<Function>::Cast(process_val);
                mainFunc = Persistent<Function>::New(process_fun);
                int ac = argc - 2;
                if (ac < 0) {
                    ac = 0;
                }
                Handle<Value>av[ac];
                for (int i = 2; i < argc; i++) {
                    av[i - 2] = String::New(argv[i]);
                }
                v = mainFunc->Call(context->Global(), ac, av);
                if (v.IsEmpty()) {
                    ReportException(&tryCatch);
                    exit(1);
                }
            }
        }
        context.Dispose();
    }
}
Example #19
0
 virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const
 {
     if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);
     else return readFile(ARCHIVE,fileName,options);
 }
Example #20
0
bool CKaraokeLyricsTextUStar::Load()
{
  // Header parameters
  std::string coverimage, bgimage;
  int bpm = 0, startoffsetms = 0;
  bool relative = false;

  // Read the text file
  std::vector< std::string > lines = readFile( m_lyricsFile, true );

  if ( lines.size() == 0 )
    return false;

  // Clear the lyrics array
  clearLyrics();

  // Parse and validate the header according to 
  // http://ultrastardeluxe.xtremeweb-hosting.net/wiki/doku.php?id=editor:txt_file
  unsigned int idx = 0;

  for ( ; idx < lines.size() && lines[idx][0] == '#'; idx++ )
  {
    // Parse into key:value
    size_t offset = lines[idx].find(':');
    if (offset == std::string::npos)
    {
      CLog::Log( LOGERROR, "UStar lyric loader: invalid line '%s', no semicolon", lines[idx].c_str() );
      return false;
    }

    std::string key = lines[idx].substr(1, offset - 1);
    std::string value = lines[idx].substr(offset + 1);

    if ( key == "TITLE" )
      m_songName = value;
    else if ( key == "ARTIST" )
      m_artist = value;
    else if ( key == "VIDEO" )
    {
      m_videoFile = URIUtils::GetDirectory(m_lyricsFile);
      m_videoFile = URIUtils::AddFileToFolder(m_videoFile, value);

      if ( !XFILE::CFile::Exists( m_videoFile ) )
      {
        CLog::Log( LOGERROR, "UStar lyric loader: VIDEO entry is present, but video file %s is not found", m_videoFile.c_str() );
        m_videoFile.clear();
      }
    }
    else if ( key == "COVER" )
      coverimage = value;
    else if ( key == "BACKGROUND" )
      bgimage = value;
    else if ( key == "VIDEOGAP" )
      m_videoOffset = atoi( value.c_str() );
    else if ( key == "BPM" )
      bpm = atoi( value.c_str() );
    else if ( key == "GAP" )
      startoffsetms = atoi( value.c_str() );
    else if ( key == "RELATIVE" )
      relative = StringUtils::EqualsNoCase(value, "YES");
    else if ( key == "LANGUAGE" || key == "EDITION" || key == "GENRE" || key == "YEAR" || key == "MP3" )
    {
      ; // do nothing
    }
    else
      CLog::Log( LOGWARNING, "UStar lyric loader: unsupported keyword '%s'", key.c_str() );
  }

  // BPM must be defined
  if ( bpm == 0 )
  {
    CLog::Log( LOGERROR, "UStar lyric loader: BPM is not defined, file is invalid" );
    return false;
  }

  // Should be more lines
  if ( idx == lines.size() )
  {
    CLog::Log( LOGERROR, "UStar lyric loader: no lyrics found besides the header" );
    return false;
  }

  double beatstep = 60.0 / bpm / 4.0;
  CLog::Log( LOGDEBUG, "UStar lyric loader: found valid lyrics, BPM is %d (%g)", bpm, beatstep );

  // Now parse the words/notes part
  int lyric_flags = 0;

  for ( ; idx < lines.size() && lines[idx][0] != 'E'; idx++ )
  {
    char type = lines[idx][0];

    // A valid type should be followed by space
    if ( type != 'F' && type != ':' && type != '*' && type != '-' && lines[idx][1] != ' ' )
    {
      CLog::Log( LOGERROR, "UStar lyric loader: invalid line '%s', bad note type or no tail space", lines[idx].c_str() );
      return false;
    }

    // Parse the numbers in the line into the vector
    int numbercount = (type == '-') ? 1 : 3;
    char * p = &(lines[idx][1]);
    std::vector< int > numbers;

    while ( numbercount > 0 )
    {
      unsigned int length = 0;

      // Skip all leading space
      while ( isspace( *p ) )
        p++;

      // skip non-space
      while ( p[length] && !isspace( p[length] ) )
      {
        if ( !isdigit( p[length] ) )
        {
          CLog::Log( LOGERROR, "UStar lyric loader: invalid line '%s', bad digit at back-position %d", lines[idx].c_str(), numbercount );
          return false;
        }

        length++;
      }

      p[length++] = '\0';

      if ( strlen(p) == 0 )
      {
        CLog::Log( LOGERROR, "UStar lyric loader: invalid line '%s', empty digit at back-position %d", lines[idx].c_str(), numbercount );
        return false;
      }

      numbers.push_back( atoi( p ) );

      // Adjust p
      p += length;
      numbercount--;
    }

    int notestart_timing = (int)((numbers[0] * beatstep) * 10 + (startoffsetms / 100));

    if ( type != '-' )
    {
      // Pitch is not used yet; notelenght will not be used at all
      //int notelength = numbers[1] * beatstep * 10;
      //int notepitch = numbers[2];

      addLyrics( p, notestart_timing, lyric_flags | LYRICS_CONVERT_UTF8 );
      lyric_flags = 0;

      //CLog::Log( LOGDEBUG, ":: %d %d [%d - %d] %d '%s'", numbers[0], numbers[1], notestart_timing, notelength, notepitch, text );
    }
    else
    {
      lyric_flags = CKaraokeLyricsText::LYRICS_NEW_LINE;
      addLyrics( " ", notestart_timing, lyric_flags | LYRICS_CONVERT_UTF8 );

      // If we're relative, adjust to the pause start
      if ( relative )
        startoffsetms += (int)((numbers[0] * beatstep) * 10);

      //CLog::Log( LOGERROR, ":: [stop] %d [%d]", numbers[0], notestart_timing );
    }
  }

  // Indicate that lyrics have pitch
  m_hasPitch = true;
  return true;
}
Example #21
0
 virtual ReadResult readHeightField(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
 {
     return readFile(HEIGHTFIELD,fileName,options);
 }
Example #22
0
// Inital match file reader constructor
IMatch_Reader::IMatch_Reader(const char* fileP,IntVecPair& fPair,
                             vector<int>& numM, vector<IntVecPair>& mList):IOInterface(fileP){
	readFile(fPair,numM,mList);
}
Example #23
0
inline void genSafariExtension(const std::string& uid,
                               const std::string& path,
                               QueryData& results) {
  Row r;
  r["uid"] = uid;
  r["path"] = path;

  // Loop through (Plist key -> table column name) in kSafariExtensionKeys.
  struct archive* ext = archive_read_new();
  if (ext == nullptr) {
    return;
  }

  // Perform a dry run of the file read.
  if (!readFile(path).ok()) {
    return;
  }

  // Finally drop privileges to the user controlling the extension.
  auto dropper = DropPrivileges::get();
  if (!dropper->dropToParent(path)) {
    return;
  }

  // Use open_file, instead of the preferred open_filename for OS X 10.9.
  archive_read_support_format_xar(ext);
  if (archive_read_open_filename(ext, path.c_str(), 10240) != ARCHIVE_OK) {
    archive_read_finish(ext);
    return;
  }

  struct archive_entry* entry = nullptr;
  while (archive_read_next_header(ext, &entry) == ARCHIVE_OK) {
    auto item_path = archive_entry_pathname(entry);
    // Documentation for libarchive mentions these APIs may return NULL.
    if (item_path == nullptr) {
      archive_read_data_skip(ext);
      continue;
    }

    // Assume there is no non-root Info.
    if (std::string(item_path).find("Info.plist") == std::string::npos) {
      archive_read_data_skip(ext);
      continue;
    }

    // Read the decompressed Info.plist content.
    auto content = std::string(archive_entry_size(entry), '\0');
    archive_read_data_into_buffer(ext, &content[0], content.size());

    // If the Plist can be parsed, extract important keys into columns.
    pt::ptree tree;
    if (parsePlistContent(content, tree).ok()) {
      for (const auto& it : kSafariExtensionKeys) {
        r[it.second] = tree.get(it.first, "");
      }
    }
    break;
  }

  archive_read_close(ext);
  archive_read_finish(ext);
  results.push_back(std::move(r));
}
Example #24
0
TXT_Reader::TXT_Reader(const char* fileP):IOInterface(fileP){
	readFile();
}
int main(int argc, char* argv[]){


	//Debug place holder for input data creating  
	CreateMatrix(50, 10, "v.data");	
	
	
	//debug add input data form here
	CreateMatrix(50, 10, "x.data");
	CreateMatrix(50, 10, "y.data");	
	CreateMatrix(50, 10, "h.data");
	



	myArray MatX;
	MatX.name = "Matrix X coordinate of target";
	MatX.ar = readFile("x.data", &(MatX.row), &(MatX.col));

	myArray MatY;
	MatY.name = "Matrix Y coordinate of target";
	MatY.ar = readFile("y.data", &(MatY.row), &(MatY.col));
	
	myArray MatH;
	MatH.name = "Matrix with relative height coordinate of target";
	MatH.ar = readFile("h.data", &(MatH.row), &(MatH.col));
	
	myArray MatV;
	MatV.name = "Matrix with relative height coordinate of target";
	MatV.ar = readFile("v.data", &(MatV.row), &(MatV.col));

	myArray MatDefec;
	MatDefec.name = "defection to target";
	MatDefec.row = MatY.row;
	MatDefec.col = MatY.col;
	MatDefec.ar = malloc(sizeof(double)*(MatY.row * MatY.col));
	
	myArray MatElev;
	MatElev.name = "Elevation to target";
	MatElev.row = MatY.row;
	MatElev.col = MatY.col;
	MatElev.ar = malloc(sizeof(double)*(MatY.row * MatY.col));

	
	printf("-----------------------------------------------\n");
	
	printf("Oringinal X and Y\n-----------------------------------------------\n");
	printf("XXXX printing original matrixX ");
	printArray(MatX.row, MatX.col, MatX.ar);
	
	printf("YYYYYprinting original matrixY ");
	printArray(MatY.row, MatY.col, MatY.ar);
	
	printf("\n-----------------------------------------------\n");
	printf("-----------------------------------------------\n");
	

	printf("printing original matrix Defelction to target\n");	
	printArray(MatDefec.row, MatDefec.col, MatDefec.ar);
	
	printf("performing the operation\n");
	Defection(&MatX, &MatY, &MatDefec);
 	// Defection2(MatX.ar, MatY.ar, MatDefec.ar, MatX.row * MatY.col);
	
	printf("-----------------------------------------------\n");
	
	printf("printing original matrix Defelction to target\n");	
	printArray(MatDefec.row, MatDefec.col, MatDefec.ar);
	
	printf("-----------------------------------------------\n");
	printf("-----------------------------------------------\n");
	printf("printing elevation to target\n");	
	
	elevation(&MatX, &MatY, &MatH,  &MatV, &MatElev);

	printArray(MatElev.row, MatElev.col, MatElev.ar);
	
	



	//Thou shalt free all that thy malloc
	free(MatDefec.ar);
	free(MatY.ar);
	free(MatX.ar);
	free(MatH.ar);
	free(MatElev.ar);
	free(MatV.ar);
	return 0;
}
Example #26
0
// Key file reader constructor
Key_Reader::Key_Reader(const char* fileP,vector<cv::Point2f>& featurePoints):IOInterface(fileP){
	readFile(featurePoints);
}
Example #27
0
ConveyorBelt* makeConveyorBelt(char *filename) {
  return readFile(filename, MAX_CONVEYOR_SIZE, BUFSIZE);
}
Example #28
0
Key_Reader::Key_Reader(const char* fileP,vector<cv::Point2f>& featurePoints, double px, double py):IOInterface(fileP){
	readFile(featurePoints,px,py);
}
Example #29
0
char*
AnyOption::readFile()
{
	return ( readFile(filename) );
}
Example #30
0
std::string getCACertificateContent() {
  std::string content;
  readFile(fs::path(kTestDataPath) / "test_cert.pem", content);
  return content;
}