Exemple #1
0
void initLed()
{
	initOutput(&clkPort, 0);
	initOutput(&dataPort, 0);
	initOutput(&oePort, 0);
	
	chainDescriptors.ledsNum_ = TOTAL_LED_PINS;
	chainDescriptors.regsNum_ = REGS_NUM;
	chainDescriptors.clk_ = &clkPort;
	chainDescriptors.data_ = &dataPort;
	chainDescriptors.oe_ = &oePort;
	chainDescriptors.buffer_ = ledBuffer;
	chainDescriptors.ledNumTable_ = (uint8_t*)&ledsNumTable;//data in PROGMEM!!
}
void MultiWii_setup() {
    
  SerialOpen(SERIAL0_COM_SPEED);

#if defined(TRACE)
  Serial.println("Start MultiWii_setup");
#endif 
  
  initOutput();

  LoadDefaults();
       
  configureReceiver();

  initSensors();

  previousTime = micros();

  calibratingA = 0;
  calibratingG = 512;

#if defined(TRACE)
  Serial.println("End MultiWii_setup");
#endif 
  
}
DrmQPainterBackend::DrmQPainterBackend(DrmBackend *backend)
    : QObject()
    , QPainterBackend()
    , m_backend(backend)
{
    const auto outputs = m_backend->outputs();
    for (auto output: outputs) {
        initOutput(output);
    }
    connect(m_backend, &DrmBackend::outputAdded, this, &DrmQPainterBackend::initOutput);
    connect(m_backend, &DrmBackend::outputRemoved, this,
        [this] (DrmOutput *o) {
            auto it = std::find_if(m_outputs.begin(), m_outputs.end(),
                [o] (const Output &output) {
                    return output.output == o;
                }
            );
            if (it == m_outputs.end()) {
                return;
            }
            delete (*it).buffer[0];
            delete (*it).buffer[1];
            m_outputs.erase(it);
        }
    );
}
Exemple #4
0
PsUpdateDownloader::PsUpdateDownloader(QThread *thread, const QString &url) : reply(0), already(0), full(0) {
	updateUrl = url;
	moveToThread(thread);
	manager.moveToThread(thread);
	App::setProxySettings(manager);

	connect(thread, SIGNAL(started()), this, SLOT(start()));
	initOutput();
}
Exemple #5
0
PsUpdateDownloader::PsUpdateDownloader(QThread *thread, const MTPDhelp_appUpdate &update) : reply(0), already(0), full(0) {
	updateUrl = qs(update.vurl);
	moveToThread(thread);
	manager.moveToThread(thread);
	App::setProxySettings(manager);

	connect(thread, SIGNAL(started()), this, SLOT(start()));
	initOutput();
}
Exemple #6
0
// puts header info at top of PACKET_ORDER_FILE_NAME
void finalizeOutput( void )
{ FILE *fp; long len; char *buf;
  fclose(FHpacketOrderOut);
  rename(PACKET_ORDER_FILE_NAME,".psfq.tmp");
  initOutput(); fp=fopen(".psfq.tmp","rb");
  //go to end //get position at end (length) //go to beg.  //malloc buffer //read into buffer
  fseek(fp,0,SEEK_END); len=ftell(fp); fseek(fp,0,SEEK_SET); buf=(char *)malloc(len); fread(buf,len,1,fp);     
  fclose(fp); remove(".psfq.tmp"); // close fh, remove temp file
  fprintf(FHpacketOrderOut,"%d %d %d // numNodes numPackets numSuccRuns .. move to first line\n", numNodes, numPackets, numSuccRuns);
  fprintf(FHpacketOrderOut,"%s",buf); fclose(FHpacketOrderOut);
}
QgsRasterDataProvider *QgsRasterFileWriter::createMultiBandRaster( Qgis::DataType dataType, int width, int height, const QgsRectangle &extent, const QgsCoordinateReferenceSystem &crs, int nBands )
{
  if ( mTiledMode )
    return nullptr;  // does not make sense with tiled mode

  double pixelSize;
  double geoTransform[6];
  globalOutputParameters( extent, width, height, geoTransform, pixelSize );

  return initOutput( width, height, crs, geoTransform, nBands, dataType, QList<bool>(), QList<double>() );
}
void ParallelTable::forwardProp(std::shared_ptr<TorchData> input) {
  RASSERT(input->type() == TorchDataType::TABLE_DATA);

  Table* in = (Table*)input.get();
  // Make sure table size matches the number of parallel stages:
  RASSERT(in->tableSize() == network_.size());
  for (uint32_t i = 0; i < network_.size(); i++) {
    network_[i]->forwardProp((*in)(i));
  }
  initOutput();  // Init output just copies the pointers from the output
                 // of all the parallel stages and fills up a table with them
}
int runNBodySimulation(const NBodyFlags* nbf)
{
    NBodyCtx* ctx = &_ctx;
    NBodyState* st = &_st;

    int rc = 0;
    real chisq;
    double ts = 0.0, te = 0.0;

    nbodySetCtxFromFlags(ctx, nbf);
    if (setupRun(ctx, st, &ctx->histogramParams, nbf))
    {
        return warn1("Failed to setup run\n");
    }

    if (initOutput(st, nbf))
    {
        return warn1("Failed to open output files\n");
    }

    if (createSharedScene(st, ctx, nbf->inputFile))
    {
        return warn1("Failed to create shared scene\n");
    }

    ts = mwGetTime();
    rc = runSystem(ctx, st, nbf);
    if (rc)
        return warn1("Error running system\n");
    te = mwGetTime();

    if (nbf->printTiming)
    {
        printf("<run_time> %f </run_time>\n", te - ts);
    }

    /* Get the likelihood */
    chisq = nbodyChisq(ctx, st, nbf, &ctx->histogramParams);
    if (isnan(chisq))
    {
        warn("Failed to calculate chisq\n");
        rc = 1;
    }

    finalOutput(ctx, st, nbf, chisq);
    destroyNBodyState(st);

    return rc;
}
Exemple #10
0
void AudioOutput::init()
{
    initOutput();
    _stream = new QDataStream(_byteArray, QIODevice::ReadOnly);

    _ioDevice = _stream->device();

    _ioDevice->open(QIODevice::ReadWrite);
    _audioOutput->start(_ioDevice);

    _audioThread = new AudioOutputDataThread(_audioOutput, _ioDevice, _byteArray, _byteList);
    QObject::connect( _audioThread, SIGNAL( finished() ), this, SLOT( finishedThread() ) );

    _audioThread->start();
}
Exemple #11
0
 void Parallel::forwardProp(TorchData& input) {
   if (input.type() != TorchDataType::TABLE_DATA) {
     throw std::runtime_error("Parallel::forwardProp() - "
       "Table expected!");
   }
   Table& in = (Table&)input;
   if (in.tableSize() != network_->size()) {
     throw std::runtime_error("Parallel::forwardProp() - ERROR: "
       "Table size does not match number of parallel stages!");
   }
   for (uint32_t i = 0; i < network_->size(); i++) {
     (*network_)[i]->forwardProp(*in(i));
   }
   initOutput();  // Init output just copies the pointers from the output
                  // of all the parallel stages and fills up a table with them
 }
Exemple #12
0
int main(int argc, char *argv[])
{
    XcomPose a(argc, argv);

    QCoreApplication::setOrganizationName("Baltram");
    QCoreApplication::setApplicationName("xcomPose");

	registerGetDirFunc();

    rmBool log = false;
    if (argc > 1) {
	if (strcmp(argv[1], "log") == 0) {
	    log = true;
	}
    }
    initOutput(argv[0], log);

    MainWindow w;
    outMan_parent = &w;
    w.show();

    return a.exec();
}
QgsRasterFileWriter::WriterError QgsRasterFileWriter::writeImageRaster( QgsRasterIterator *iter, int nCols, int nRows, const QgsRectangle &outputExtent,
    const QgsCoordinateReferenceSystem &crs, QgsRasterBlockFeedback *feedback )
{
  QgsDebugMsgLevel( "Entered", 4 );
  if ( !iter )
  {
    return SourceProviderError;
  }

  const QgsRasterInterface *iface = iter->input();
  if ( !iface )
    return SourceProviderError;

  Qgis::DataType inputDataType = iface->dataType( 1 );
  if ( inputDataType != Qgis::ARGB32 && inputDataType != Qgis::ARGB32_Premultiplied )
  {
    return SourceProviderError;
  }

  iter->setMaximumTileWidth( mMaxTileWidth );
  iter->setMaximumTileHeight( mMaxTileHeight );

  void *redData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  void *greenData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  void *blueData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  void *alphaData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  int iterLeft = 0, iterTop = 0, iterCols = 0, iterRows = 0;
  int fileIndex = 0;

  //create destProvider for whole dataset here
  double pixelSize;
  double geoTransform[6];
  globalOutputParameters( outputExtent, nCols, nRows, geoTransform, pixelSize );

  std::unique_ptr< QgsRasterDataProvider > destProvider( initOutput( nCols, nRows, crs, geoTransform, 4, Qgis::Byte ) );

  iter->startRasterRead( 1, nCols, nRows, outputExtent, feedback );

  int nParts = 0;
  if ( feedback )
  {
    int nPartsX = nCols / iter->maximumTileWidth() + 1;
    int nPartsY = nRows / iter->maximumTileHeight() + 1;
    nParts = nPartsX * nPartsY;
  }

  std::unique_ptr< QgsRasterBlock > inputBlock;
  while ( iter->readNextRasterPart( 1, iterCols, iterRows, inputBlock, iterLeft, iterTop ) )
  {
    if ( !inputBlock )
    {
      continue;
    }

    if ( feedback && fileIndex < ( nParts - 1 ) )
    {
      feedback->setProgress( 100.0 * fileIndex / static_cast< double >( nParts ) );
      if ( feedback->isCanceled() )
      {
        break;
      }
    }

    //fill into red/green/blue/alpha channels
    qgssize nPixels = static_cast< qgssize >( iterCols ) * iterRows;
    // TODO: should be char not int? we are then copying 1 byte
    int red = 0;
    int green = 0;
    int blue = 0;
    int alpha = 255;
    for ( qgssize i = 0; i < nPixels; ++i )
    {
      QRgb c = inputBlock->color( i );
      alpha = qAlpha( c );
      red = qRed( c );
      green = qGreen( c );
      blue = qBlue( c );

      if ( inputDataType == Qgis::ARGB32_Premultiplied )
      {
        double a = alpha / 255.;
        QgsDebugMsgLevel( QString( "red = %1 green = %2 blue = %3 alpha = %4 p = %5 a = %6" ).arg( red ).arg( green ).arg( blue ).arg( alpha ).arg( static_cast< int >( c ), 0, 16 ).arg( a ), 5 );
        red /= a;
        green /= a;
        blue /= a;
      }
      memcpy( reinterpret_cast< char * >( redData ) + i, &red, 1 );
      memcpy( reinterpret_cast< char * >( greenData ) + i, &green, 1 );
      memcpy( reinterpret_cast< char * >( blueData ) + i, &blue, 1 );
      memcpy( reinterpret_cast< char * >( alphaData ) + i, &alpha, 1 );
    }

    //create output file
    if ( mTiledMode )
    {
      //delete destProvider;
      std::unique_ptr< QgsRasterDataProvider > partDestProvider( createPartProvider( outputExtent,
          nCols, iterCols, iterRows,
          iterLeft, iterTop, mOutputUrl, fileIndex,
          4, Qgis::Byte, crs ) );

      if ( partDestProvider )
      {
        //write data to output file
        partDestProvider->write( redData, 1, iterCols, iterRows, 0, 0 );
        partDestProvider->write( greenData, 2, iterCols, iterRows, 0, 0 );
        partDestProvider->write( blueData, 3, iterCols, iterRows, 0, 0 );
        partDestProvider->write( alphaData, 4, iterCols, iterRows, 0, 0 );

        addToVRT( partFileName( fileIndex ), 1, iterCols, iterRows, iterLeft, iterTop );
        addToVRT( partFileName( fileIndex ), 2, iterCols, iterRows, iterLeft, iterTop );
        addToVRT( partFileName( fileIndex ), 3, iterCols, iterRows, iterLeft, iterTop );
        addToVRT( partFileName( fileIndex ), 4, iterCols, iterRows, iterLeft, iterTop );
      }
    }
    else if ( destProvider )
    {
      destProvider->write( redData, 1, iterCols, iterRows, iterLeft, iterTop );
      destProvider->write( greenData, 2, iterCols, iterRows, iterLeft, iterTop );
      destProvider->write( blueData, 3, iterCols, iterRows, iterLeft, iterTop );
      destProvider->write( alphaData, 4, iterCols, iterRows, iterLeft, iterTop );
    }

    ++fileIndex;
  }
  destProvider.reset();

  qgsFree( redData );
  qgsFree( greenData );
  qgsFree( blueData );
  qgsFree( alphaData );

  if ( feedback )
  {
    feedback->setProgress( 100.0 );
  }

  if ( mTiledMode )
  {
    QString vrtFilePath( mOutputUrl + '/' + vrtFileName() );
    writeVRT( vrtFilePath );
    if ( mBuildPyramidsFlag == QgsRaster::PyramidsFlagYes )
    {
      buildPyramids( vrtFilePath );
    }
  }
  else
  {
    if ( mBuildPyramidsFlag == QgsRaster::PyramidsFlagYes )
    {
      buildPyramids( mOutputUrl );
    }
  }
  return ( feedback && feedback->isCanceled() ) ? WriteCanceled : NoError;
}
Exemple #14
0
int
main(void)
{
    initOutput();
    clearOutput();
}
bool			PAudioStream::init()
{
  if (Pa_Initialize() != paNoError)
    return (false);
  return (_codec.init() && initInput() && initOutput());
}
Exemple #16
0
int main(int argc, char *argv[])
{
	if (!parseCommandLine(argc, argv))
		return 1;

	configHashTable();
	/****************************************************
	 * INDEXING
	 ***************************************************/
	if (indexingMode)
	{
		int i;
		/********************************
		 * Regulard Mode
		 ********************************/
		if (!bisulfiteMode)
		{
			configHashTable();
			for (i = 0; i < fileCnt; i++)
			{
				generateHashTable(fileName[i][0], fileName[i][1]);
			}
		}
		else
		/********************************
		 * Bisulfite Mode
		 ********************************/
		{ // TODO
		}
	}
	/****************************************************
	 * SEARCHING
	 ***************************************************/
	else
	{
		Read *seqList;
		unsigned int seqListSize;
		int fc;
		int samplingLocsSize;
		int *samplingLocs;
		double totalLoadingTime = 0;
		double totalMappingTime = 0;
		double startTime;
		double loadingTime;
		double mappingTime;
		double lstartTime;
		double ppTime;
		double tmpTime;;
		char *prevGen = getMem(CONTIG_NAME_SIZE);
		prevGen[0]='\0';
		char *curGen;
		int	flag;
		double maxMem=0;
		char fname1[FILE_NAME_LENGTH];
		char fname2[FILE_NAME_LENGTH];
		char fname3[FILE_NAME_LENGTH];
		char fname4[FILE_NAME_LENGTH];
		char fname5[FILE_NAME_LENGTH];
		// Loading Sequences & Sampling Locations
		startTime = getTime();
		if (bisulfiteMode && !pairedEndMode && seqFile1 == NULL)
		{
		    //TODO
		}
		else
		{
			if (!readAllReads(seqFile1, seqFile2, seqCompressed, &seqFastq, pairedEndMode, &seqList, &seqListSize))
			{
				return 1;
			}
		}

		//loadSamplingLocations(&samplingLocs, &samplingLocsSize);
		totalLoadingTime += getTime()-startTime;




		if (pairedEndMode)
		{
			//Switching to Inferred Size 
			minPairEndedDistance = minPairEndedDistance - SEQ_LENGTH + 2;
			maxPairEndedDistance = maxPairEndedDistance - SEQ_LENGTH + 2;
			if (pairedEndDiscordantMode)
			{
				maxPairEndedDiscordantDistance = maxPairEndedDiscordantDistance - SEQ_LENGTH + 2;
				minPairEndedDiscordantDistance = minPairEndedDiscordantDistance - SEQ_LENGTH + 2;
			}
			
			/* The size between the ends;
			minPairEndedDistance = minPairEndedDistance + SEQ_LENGTH + 1;
			maxPairEndedDistance = maxPairEndedDistance + SEQ_LENGTH + 1;
			if (pairedEndDiscordantMode)
			{
				maxPairEndedDiscordantDistance = maxPairEndedDiscordantDistance + SEQ_LENGTH + 1;
				minPairEndedDiscordantDistance = minPairEndedDiscordantDistance + SEQ_LENGTH + 1;
			}*/
			sprintf(fname1, "%s__%s__1", mappingOutputPath, mappingOutput);
			sprintf(fname2, "%s__%s__2", mappingOutputPath, mappingOutput);
			sprintf(fname3, "%s__%s__disc", mappingOutputPath, mappingOutput);
			sprintf(fname4, "%s__%s__oea1", mappingOutputPath, mappingOutput);
			sprintf(fname5, "%s__%s__oea2", mappingOutputPath, mappingOutput);
			unlink(fname1);
			unlink(fname2);
			unlink(fname3);
			unlink(fname4);
			unlink(fname5);
		}

		// Preparing output
		initOutput(mappingOutput, outCompressed);

		fprintf(stdout, "-----------------------------------------------------------------------------------------------------------\n");
		fprintf(stdout, "| %15s | %15s | %15s | %15s | %15s %15s |\n","Genome Name","Loading Time", "Mapping Time", "Memory Usage(M)","Total Mappings","Mapped reads");
		fprintf(stdout, "-----------------------------------------------------------------------------------------------------------\n");

		/********************************
		 * Regular Mode
		 ********************************/
		if (!bisulfiteMode)
		{
			if (!pairedEndMode)
			{
				for (fc = 0; fc <fileCnt; fc++)
				{
					if (!initLoadingHashTable(fileName[fc][1]))
					{
						return 1;
					}

					loadSamplingLocations(&samplingLocs, &samplingLocsSize);

					mappingTime = 0;
					loadingTime = 0;
					prevGen[0] = '\0';
					flag = 1;
					
					do
					{
						flag = loadHashTable ( &tmpTime );  			// Reading a fragment
						curGen = getRefGenomeName();

						// First Time
						if (flag && prevGen[0]== '\0')
						{
							sprintf(prevGen, "%s", curGen);
						}

						if ( !flag || strcmp(prevGen, curGen)!=0)
						{

							fprintf(stdout, "| %15s | %15.2f | %15.2f | %15.2f | %15lld %15lld |\n",
									prevGen,loadingTime, mappingTime, maxMem, mappingCnt , mappedSeqCnt);
							fflush(stdout);

							totalMappingTime += mappingTime;
							totalLoadingTime += loadingTime;

							loadingTime = 0;
							mappingTime = 0;
							maxMem = 0;

							if (!flag)
							{
								break;
							}
						}
						else if (progressRep && mappingTime != 0)
						{
							fprintf(stdout, "| %15s | %15.2f | %15.2f | %15.2f | %15lld %15lld |\n",
									prevGen,loadingTime, mappingTime, maxMem, mappingCnt , mappedSeqCnt);
							fflush(stdout);
						}

						sprintf(prevGen, "%s", curGen);

						loadingTime += tmpTime;
						lstartTime = getTime();

						initFAST(seqList, seqListSize, samplingLocs, samplingLocsSize, fileName[fc][0]);

						mapSingleEndSeq();

						mappingTime += getTime() - lstartTime;
						if (maxMem < getMemUsage())
						{
							maxMem = getMemUsage();
						}
					} while (flag);

				} // end for;
				finalizeFAST();
				finalizeLoadingHashTable();

			}
			// Pairedend Mapping Mode
			else
			{

				for (fc = 0; fc <fileCnt; fc++)
				{
					if (!initLoadingHashTable(fileName[fc][1]))
					{
						return 1;
					}
					

					loadSamplingLocations(&samplingLocs, &samplingLocsSize);
					
					mappingTime = 0;
					loadingTime = 0;
					prevGen[0] = '\0';
					flag = 1;

					do
					{
						flag = loadHashTable ( &tmpTime );  			// Reading a fragment
						curGen = getRefGenomeName();

						// First Time
						if (flag && prevGen[0]== '\0')
						{
							sprintf(prevGen, "%s", curGen);
						}

						if ( !flag || strcmp(prevGen, curGen)!=0)
						{

							// DISCORDANT
							lstartTime = getTime();					
							outputPairedEnd();
							mappingTime += getTime() - lstartTime;
							//DISCORDANT			

							fprintf(stdout, "| %15s | %15.2f | %15.2f | %15.2f | %15lld %15lld |\n",
									prevGen,loadingTime, mappingTime, maxMem, mappingCnt , mappedSeqCnt);
							fflush(stdout);

							totalMappingTime += mappingTime;
							totalLoadingTime += loadingTime;

							loadingTime = 0;
							mappingTime = 0;
							maxMem = 0;

							if (!flag)
							{
								break;
							}
						}
						else if (progressRep && mappingTime != 0)
						{
							fprintf(stdout, "| %15s | %15.2f | %15.2f | %15.2f | %15lld %15lld |\n",
									prevGen,loadingTime, mappingTime, maxMem, mappingCnt , mappedSeqCnt);
							fflush(stdout);
						}

						sprintf(prevGen, "%s", curGen);

						loadingTime += tmpTime;
						lstartTime = getTime();
						
						initFAST(seqList, seqListSize, samplingLocs, samplingLocsSize, fileName[fc][0]);
						
						mapPairedEndSeq();
							
						mappingTime += getTime() - lstartTime;
						if (maxMem < getMemUsage())
						{
							maxMem = getMemUsage();
						}
					} while (flag);

				} // end for;

				finalizeLoadingHashTable();
				if (pairedEndDiscordantMode)
				{
					lstartTime = getTime();							
					outputPairedEndDiscPP();
					ppTime = getTime() - lstartTime;
				}
				finalizeFAST();
			}
		}
		/********************************
		 * Bisulfite Mode
		 ********************************/
		{
			//TODO
		}


		finalizeOutput();

		fprintf(stdout, "-----------------------------------------------------------------------------------------------------------\n");
		fprintf(stdout, "%19s%16.2f%18.2f\n\n", "Total:",totalLoadingTime, totalMappingTime);
		if (pairedEndDiscordantMode)
			fprintf(stdout, "Post Processing Time: %18.2f \n", ppTime);
		fprintf(stdout, "%-30s%10.2f\n","Total Time:", totalMappingTime+totalLoadingTime);
		fprintf(stdout, "%-30s%10d\n","Total No. of Reads:", seqListSize);
		fprintf(stdout, "%-30s%10lld\n","Total No. of Mappings:", mappingCnt);
		fprintf(stdout, "%-30s%10.0f\n\n","Avg No. of locations verified:", ceil((float)verificationCnt/seqListSize));

		int cof = (pairedEndMode)?2:1;

		if (progressRep && maxHits != 0)
		{
			int frequency[maxHits+1];
			int i;
			for ( i=0 ; i <= maxHits; i++)
			{
				frequency[i] = 0;
			}


			for (fc = 0; fc < seqListSize; fc++)
			{
				frequency[*(seqList[fc*cof].hits)]++;
			}
			frequency[maxHits] = completedSeqCnt;
			for ( i=0 ; i <= maxHits; i++)
			{
				fprintf(stdout, "%-30s%10d%10d%10.2f%%\n","Reads Mapped to ", i, frequency[i], 100*(float)frequency[i]/(float)seqListSize);
			}
		}


		if (strcmp(unmappedOutput, "") == 0)
		{
			char fn[strlen(mappingOutputPath) + strlen(mappingOutput) + 6 ];
			sprintf(fn, "%s%s.nohit", mappingOutputPath, mappingOutput );
			finalizeReads(fn);
		}
		else
		{
			finalizeReads(unmappedOutput);
		}



		freeMem(prevGen, CONTIG_NAME_SIZE);
	}



	return 0;
}
Exemple #17
0
glong indic_ot_reorder(const gunichar *chars, const glong *utf8_offsets, glong char_count, const IndicOTClassTable *class_table, gunichar *out_chars, glong *char_indices, gulong *char_tags, MPreFixups **outMPreFixups)
{
    MPreFixups *mpreFixups = NULL;
    Output output;
    glong i, prev = 0;
    gboolean last_in_word = FALSE;

    if (outMPreFixups && (class_table->scriptFlags & SF_MPRE_FIXUP)) {
	mpreFixups = indic_mprefixups_new (char_count);
    }

    initOutput(&output, utf8_offsets, out_chars, char_indices, char_tags, mpreFixups);

    while (prev < char_count) {
	glong syllable = indic_ot_find_syllable(class_table, chars, prev, char_count);
	glong matra, vmabove, vmpost = syllable;

	while (vmpost > prev && indic_ot_is_vm_post(class_table, chars[vmpost - 1])) {
	    vmpost -= 1;
	}

	vmabove = vmpost;
	while (vmabove > prev && indic_ot_is_vm_above(class_table, chars[vmabove - 1])) {
	    vmabove -= 1;
	}

	matra = vmabove - 1;
	initMatra(&output, prev, blwf_p, !last_in_word);
	while (noteMatra(&output, class_table, chars[matra]) &&
	       matra != prev)
	    matra--;

	last_in_word = TRUE;
	switch (indic_ot_get_char_class(class_table, chars[prev]) & CF_CLASS_MASK) {
	case CC_RESERVED:
	    last_in_word = FALSE;
	    /* Fall through */
	case CC_INDEPENDENT_VOWEL:
	case CC_ZERO_WIDTH_MARK:
	    for (i = prev; i < syllable; i += 1) {
		writeChar(&output, chars[i], /*i*/ prev, blwf_p);
	    }

	    break;

	case CC_MODIFYING_MARK_ABOVE:
	case CC_MODIFYING_MARK_POST:
	case CC_NUKTA:
	case CC_VIRAMA:
	    /* patch for rendering fix for Malayalam SAMVRUTHOKARA by suresh */
	    if (chars[prev - 1] == 0x0D41) {
	       	 writeChar(&output, chars[prev], prev, blwf_p);
		 break;
	    }
	    /* end patch */

	case CC_AL_LAKUNA:
	    writeChar(&output, C_DOTTED_CIRCLE, prev, blwf_p);
	    writeChar(&output, chars[prev], prev, blwf_p);
	    break;

	case CC_DEPENDENT_VOWEL:
	    writeMpre(&output);
	    writeChar(&output, C_DOTTED_CIRCLE, prev, blwf_p);
	    writeMbelow(&output);
	    writeMabove(&output);
	    writeMpost(&output);
	    writeLengthMark(&output);
	    writeAlLakuna(&output);
	    break;

	case CC_CONSONANT:
	case CC_CONSONANT_WITH_NUKTA:
	{
	    guint32 length = vmabove - prev;
	    glong lastConsonant = vmabove - 1;
	    glong baseLimit = prev;
	    glong baseConsonant, postBase, postBaseLimit;
	    gboolean seenVattu, seenBelowBaseForm, supressVattu;
	    glong bcSpan;

	    /* Check for REPH at front of syllable */
	    if (length > 2 && indic_ot_is_reph(class_table, chars[prev]) && indic_ot_is_virama(class_table, chars[prev + 1])) {
		baseLimit += 2;

		/* Check for eyelash RA, if the script supports it */
		if ((class_table->scriptFlags & SF_EYELASH_RA) != 0 &&
		    chars[baseLimit] == C_SIGN_ZWJ) {
		    if (length > 3) {
			baseLimit += 1;
		    } else {
			baseLimit -= 2;
		    }
		}
	    }

	    while (lastConsonant > baseLimit && !indic_ot_is_consonant(class_table, chars[lastConsonant])) {
		lastConsonant -= 1;
	    }

	    baseConsonant = lastConsonant;
	    postBase = lastConsonant + 1;

	    postBaseLimit = class_table->scriptFlags & SF_POST_BASE_LIMIT_MASK;
	    seenVattu = false;
	    seenBelowBaseForm = false;
	    supressVattu = true;

	    while (baseConsonant > baseLimit) {
		IndicOTCharClass charClass = indic_ot_get_char_class(class_table, chars[baseConsonant]);

		if (IS_CONSONANT(charClass)) {
		    if (postBaseLimit == 0 || seenVattu ||
			(baseConsonant > baseLimit && !indic_ot_is_virama(class_table, chars[baseConsonant - 1])) ||
			!HAS_POST_OR_BELOW_BASE_FORM(charClass)) {
			break;
		    }

		    seenVattu = IS_VATTU(charClass);

		    if (HAS_POST_BASE_FORM(charClass)) {
			if (seenBelowBaseForm) {
			    break;
			}

			postBase = baseConsonant;
		    } else if (HAS_BELOW_BASE_FORM(charClass)) {
			seenBelowBaseForm = true;
		    }

		    postBaseLimit -= 1;
		}

		baseConsonant -= 1;
	    }

	    /* Write Mpre */
	    writeMpre(&output);

	    /* Write eyelash RA */
	    /* NOTE: baseLimit == prev + 3 iff eyelash RA present... */
	    if (baseLimit == prev + 3) {
		writeChar(&output, chars[prev], prev, half_p);
		writeChar(&output, chars[prev + 1], prev /*+ 1*/, half_p);
		writeChar(&output, chars[prev + 2], prev /*+ 2*/, half_p);
	    }

	    /* write any pre-base consonants */
	    supressVattu = true;

	    for (i = baseLimit; i < baseConsonant; i += 1) {
		gunichar ch = chars[i];
		/* Applying blwf to the first consonant doesn't makes sense
		 * since the below-form follows the consonant that it is
		 * put under */
		gulong tag = (i == baseLimit) ? half_p : blwf_p;
		IndicOTCharClass charClass = indic_ot_get_char_class(class_table, ch);

		if (IS_CONSONANT(charClass)) {
		    if (IS_VATTU(charClass) && supressVattu) {
			tag = nukt_p;
		    }
		    else if ((i + 2 < baseConsonant) && (chars[i + 2] == C_SIGN_ZWNJ)) {
			tag = nukt_p;
		    }

		    supressVattu = IS_VATTU(charClass);
		} else if (IS_VIRAMA(charClass) && chars[i + 1] == C_SIGN_ZWNJ)
		{
		    tag = nukt_p;
		}

		writeChar(&output, ch, /*i*/ prev, tag);
	    }

	    bcSpan = baseConsonant + 1;

	    if (bcSpan < vmabove && indic_ot_is_nukta(class_table, chars[bcSpan])) {
		bcSpan += 1;
	    }

	    if (baseConsonant == lastConsonant && bcSpan < vmabove && indic_ot_is_virama(class_table, chars[bcSpan])) {
		bcSpan += 1;

		if (bcSpan < vmabove && chars[bcSpan] == C_SIGN_ZWNJ) {
		    bcSpan += 1;
		}
	    }

	    /* note the base consonant for post-GSUB fixups */
	    noteBaseConsonant(&output);

	    /* write base consonant */
	    for (i = baseConsonant; i < bcSpan; i += 1) {
		writeChar(&output, chars[i], /*i*/ prev, nukt_p);
	    }

	    if ((class_table->scriptFlags & SF_MATRAS_AFTER_BASE) != 0) {
		gboolean is_for_0C48 = FALSE;
		if (output.fOutChars != NULL) {  /*for 0x0C48 of Telugu*/
		    int t;
		    for (t = prev; t < syllable; t++) {
			if (chars[t] == 0x0C48) {
			    writeMabove(&output);
			    writeMbelow(&output);
			    writeMpost(&output);

			    is_for_0C48 = TRUE;
			    break;
			}
		    }
		}

		if (!is_for_0C48) {
		    writeMbelow(&output);
		    writeMabove(&output);
		    writeMpost(&output);
		}
	    }

	    /* write below-base consonants */
	    if (baseConsonant != lastConsonant) {
		for (i = bcSpan + 1; i < postBase; i += 1) {
		    writeChar(&output, chars[i], /*i*/ prev, blwf_p);
		}

		if (postBase > lastConsonant) {
		    /* write halant that was after base consonant */
		    writeChar(&output, chars[bcSpan], /*bcSpan*/ prev, blwf_p);
		}
	    }

	    /* write Mbelow, Mabove */
	    if ((class_table->scriptFlags & SF_MATRAS_AFTER_BASE) == 0) {
		writeMbelow(&output);
		writeMabove(&output);
	    }

	   if ((class_table->scriptFlags & SF_REPH_AFTER_BELOW) != 0) {
		if (baseLimit == prev + 2) {
		    writeChar(&output, chars[prev], prev, rphf_p);
		    writeChar(&output, chars[prev + 1], prev /*+ 1*/, rphf_p);
		}

		/* write VMabove */
		for (i = vmabove; i < vmpost; i += 1) {
		    writeChar(&output, chars[i], /*i*/ prev, blwf_p);
		}
	    }

	    /* write post-base consonants */
	    if (baseConsonant != lastConsonant) {
		if (postBase <= lastConsonant) {
		    for (i = postBase; i <= lastConsonant; i += 1) {
			writeChar(&output, chars[i], /*i*/ prev, pstf_p);
		    }

		    /* write halant that was after base consonant */
		    writeChar(&output, chars[bcSpan], /*bcSpan*/ prev, blwf_p);
		}

		/* write the training halant, if there is one */
		if (lastConsonant < matra && indic_ot_is_virama(class_table, chars[matra])) {
		    writeChar(&output, chars[matra], /*matra*/ prev, nukt_p);
		}
	    }

	    /* write Mpost */
	    if ((class_table->scriptFlags & SF_MATRAS_AFTER_BASE) == 0) {
		writeMpost(&output);
	    }

	    writeLengthMark(&output);
	    writeAlLakuna(&output);

	    /* write reph */
	    if ((class_table->scriptFlags & SF_REPH_AFTER_BELOW) == 0) {
		if (baseLimit == prev + 2) {
		    writeChar(&output, chars[prev], prev, rphf_p);
		    writeChar(&output, chars[prev + 1], prev /*+ 1*/, rphf_p);
		}

		/* write VMabove */
		for (i = vmabove; i < vmpost; i += 1) {
		    writeChar(&output, chars[i], /*i*/ prev, blwf_p);
		}
	    }

	    /* write VMpost */
	    for (i = vmpost; i < syllable; i += 1) {
		writeChar(&output, chars[i], /*i*/ prev, blwf_p);
	    }

	    break;
	}

	default:
	    break;
	}


	prev = syllable;
    }

    if (outMPreFixups) {
	*outMPreFixups = mpreFixups;
    }

    return getOutputIndex(&output);
}
Exemple #18
0
void pinMode(IOPin pin, int mode) {
	if(mode == OUTPUT)
		initOutput(pin);
	else
		initInput(pin, NO_PULL);
}
Exemple #19
0
int main(void) {
	static uint8_t buffer[BufferSize + 1];
	int8_t   i;
	uint8_t  message[4] = { 0, 0, CID, P2CID };
	uint16_t received;
	snesIO   port0 = 0xffff, port1 = 0xffff;


	// Initialise basic I/O.
	initLed();
	initInput();
	initOutput();


	// Switched mode: B + Y.
	port0 = recvInput();
	if (port0 == 0xfffc) {
		switchedMode = Enabled;
		ledSignal(5);
	}
	ledOnRed();


	// Initialise network interface.
	enc28j60Init(mymac);
	_delay_ms(100);
	// Magjack leds configuration, see enc28j60 datasheet, page 11
	// LEDB=yellow LEDA=green
	// 0x476 is PHLCON LEDA=links status, LEDB=receive/transmit
	// enc28j60PhyWrite(PHLCON,0b0000 0100 0111 01 10);
	enc28j60PhyWrite(PHLCON, 0x476);
	_delay_ms(100);


	// Get the initial IP via DHCP and configure network.
	init_mac(mymac);
	while (i != 1) {
		received = enc28j60PacketReceive(BufferSize, buffer);
		buffer[BufferSize] = '\0';
		i = packetloop_dhcp_initial_ip_assignment(buffer, received, mymac[5]);
	}
	dhcp_get_my_ip(myip, netmask, gwip);
	client_ifconfig(myip, netmask);


	// Resolve MAC address from server IP.
	if (route_via_gw(serverip)) // Must be routed via gateway.
		get_mac_with_arp(gwip, TransNumGwmac, &arpresolverResultCallback);
	else                        // Server is on local network.
		get_mac_with_arp(serverip, TransNumGwmac, &arpresolverResultCallback);

	while (get_mac_with_arp_wait()) {
		received = enc28j60PacketReceive(BufferSize, buffer);
		// Call packetloop to process ARP reply.
		packetloop_arp_icmp_tcp(buffer, received);
	}


	// Lookup DNS of the server hostname.
	while (dnslkup_haveanswer() != 1) {
		uint16_t tmp;
		received = enc28j60PacketReceive(BufferSize, buffer);
		tmp      = packetloop_arp_icmp_tcp(buffer, received);

		if (received == 0) {
			if (!enc28j60linkup()) continue;
			dnslkup_request(buffer, ServerVHost, gwmac);
			_delay_ms(100);
			continue;
		}

		if (tmp == 0)
			udp_client_check_for_dns_answer(buffer, received);
	}
	dnslkup_get_ip(serverip);


	ledOnGreen(); // Connected.


	while (1) { // Main loop start.
		received = enc28j60PacketReceive(BufferSize, buffer);


		// Software reset: L + R + Select + Start.
		if (port0 == 0xf3f3) reset();


		// Do something while no packet in queue.
		if (received == 0) {
			port0 = recvInput();

			// Prepare message and send it to the server.
			for (i = 0; i < 8; i++) { // Lo-Byte.
				char *c = message;

				*c = port0 & (1 << i)
					? *c |  (1 << i)
					: *c & ~(1 << i);
			}

			for (i = 0; i < 8; i++) { // Hi-Byte.
				char *c = message + 1;

				*c = port0 & (1 << i + 8)
					? *c |  (1 << i)
					: *c & ~(1 << i);
			}

			send_udp(buffer, message, sizeof(message), 57351, serverip, 57350, gwmac);


			// Send controller data to SNES.
			if (switchedMode == Disabled)
				sendOutput(port0, port1);
			else
				sendOutput(port1, port0);

			continue;
		}


		// Answer to ARP requests.
		if (eth_type_is_arp_and_my_ip(buffer, received)) {
			make_arp_answer_from_request(buffer, received);
			continue;
		}


		// Check if IP packets (ICMP or UDP) are for us.
		if (eth_type_is_ip_and_my_ip(buffer, received) == 0)
			continue;


		// Answer ping with pong.
		if (
			buffer[IP_PROTO_P]  == IP_PROTO_ICMP_V &&
			buffer[ICMP_TYPE_P] == ICMP_TYPE_ECHOREQUEST_V) {

			make_echo_reply_from_request(buffer, received);
			continue;
		}


		// Listen for UDP packets on port 57351 (0xe007) and process
		// received data.
		if (
			buffer[IP_PROTO_P]       == IP_PROTO_UDP_V &&
			buffer[UDP_DST_PORT_H_P] == 0xe0 &&
			buffer[UDP_DST_PORT_L_P] == 0x07) {

			for (i = 0; i < 8; i++) {
				uint16_t *c = &port1;

				*c = buffer[UDP_DATA_P] & (1 << i)
					? *c |  (1 << i)
					: *c & ~(1 << i);
			}

			for (i = 0; i < 8; i++) {
				uint16_t *c = &port1;

				*c = buffer[UDP_DATA_P + 1] & (1 << i)
					? *c |  (1 << i + 8)
					: *c & ~(1 << i + 8);
			}
		}
	} // Main loop end.


	return (0);
}
QgsRasterFileWriter::WriterError QgsRasterFileWriter::writeImageRaster( QgsRasterIterator* iter, int nCols, int nRows, const QgsRectangle& outputExtent,
    const QgsCoordinateReferenceSystem& crs, QProgressDialog* progressDialog )
{
  QgsDebugMsg( "Entered" );
  if ( !iter )
  {
    return SourceProviderError;
  }

  const QgsRasterInterface* iface = iter->input();
  QGis::DataType inputDataType = iface->dataType( 1 );
  if ( !iface || ( inputDataType != QGis::ARGB32 &&
                   inputDataType != QGis::ARGB32_Premultiplied ) )
  {
    return SourceProviderError;
  }

  iter->setMaximumTileWidth( mMaxTileWidth );
  iter->setMaximumTileHeight( mMaxTileHeight );

  void* redData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  void* greenData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  void* blueData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  void* alphaData = qgsMalloc( mMaxTileWidth * mMaxTileHeight );
  QgsRectangle mapRect;
  int iterLeft = 0, iterTop = 0, iterCols = 0, iterRows = 0;
  int fileIndex = 0;

  //create destProvider for whole dataset here
  QgsRasterDataProvider* destProvider = 0;
  double pixelSize;
  double geoTransform[6];
  globalOutputParameters( outputExtent, nCols, nRows, geoTransform, pixelSize );

  destProvider = initOutput( nCols, nRows, crs, geoTransform, 4, QGis::Byte );

  iter->startRasterRead( 1, nCols, nRows, outputExtent );

  int nParts = 0;
  if ( progressDialog )
  {
    int nPartsX = nCols / iter->maximumTileWidth() + 1;
    int nPartsY = nRows / iter->maximumTileHeight() + 1;
    nParts = nPartsX * nPartsY;
    progressDialog->setMaximum( nParts );
    progressDialog->show();
    progressDialog->setLabelText( QObject::tr( "Reading raster part %1 of %2" ).arg( fileIndex + 1 ).arg( nParts ) );
  }

  QgsRasterBlock *inputBlock = 0;
  while ( iter->readNextRasterPart( 1, iterCols, iterRows, &inputBlock, iterLeft, iterTop ) )
  {
    if ( !inputBlock )
    {
      continue;
    }

    if ( progressDialog && fileIndex < ( nParts - 1 ) )
    {
      progressDialog->setValue( fileIndex + 1 );
      progressDialog->setLabelText( QObject::tr( "Reading raster part %1 of %2" ).arg( fileIndex + 2 ).arg( nParts ) );
      QCoreApplication::processEvents( QEventLoop::AllEvents, 1000 );
      if ( progressDialog->wasCanceled() )
      {
        delete inputBlock;
        break;
      }
    }

    //fill into red/green/blue/alpha channels
    qgssize nPixels = ( qgssize )iterCols * iterRows;
    // TODO: should be char not int? we are then copying 1 byte
    int red = 0;
    int green = 0;
    int blue = 0;
    int alpha = 255;
    for ( qgssize i = 0; i < nPixels; ++i )
    {
      QRgb c = inputBlock->color( i );
      alpha = qAlpha( c );
      red = qRed( c ); green = qGreen( c ); blue = qBlue( c );

      if ( inputDataType == QGis::ARGB32_Premultiplied )
      {
        double a = alpha / 255.;
        QgsDebugMsgLevel( QString( "red = %1 green = %2 blue = %3 alpha = %4 p = %5 a = %6" ).arg( red ).arg( green ).arg( blue ).arg( alpha ).arg(( int )c, 0, 16 ).arg( a ), 5 );
        red /= a;
        green /= a;
        blue /= a;
      }
      memcpy(( char* )redData + i, &red, 1 );
      memcpy(( char* )greenData + i, &green, 1 );
      memcpy(( char* )blueData + i, &blue, 1 );
      memcpy(( char* )alphaData + i, &alpha, 1 );
    }
    delete inputBlock;

    //create output file
    if ( mTiledMode )
    {
      //delete destProvider;
      QgsRasterDataProvider* partDestProvider = createPartProvider( outputExtent,
          nCols, iterCols, iterRows,
          iterLeft, iterTop, mOutputUrl, fileIndex,
          4, QGis::Byte, crs );

      if ( partDestProvider )
      {
        //write data to output file
        partDestProvider->write( redData, 1, iterCols, iterRows, 0, 0 );
        partDestProvider->write( greenData, 2, iterCols, iterRows, 0, 0 );
        partDestProvider->write( blueData, 3, iterCols, iterRows, 0, 0 );
        partDestProvider->write( alphaData, 4, iterCols, iterRows, 0, 0 );

        addToVRT( partFileName( fileIndex ), 1, iterCols, iterRows, iterLeft, iterTop );
        addToVRT( partFileName( fileIndex ), 2, iterCols, iterRows, iterLeft, iterTop );
        addToVRT( partFileName( fileIndex ), 3, iterCols, iterRows, iterLeft, iterTop );
        addToVRT( partFileName( fileIndex ), 4, iterCols, iterRows, iterLeft, iterTop );
        delete partDestProvider;
      }
    }
    else if ( destProvider )
    {
      destProvider->write( redData, 1, iterCols, iterRows, iterLeft, iterTop );
      destProvider->write( greenData, 2, iterCols, iterRows, iterLeft, iterTop );
      destProvider->write( blueData, 3, iterCols, iterRows, iterLeft, iterTop );
      destProvider->write( alphaData, 4, iterCols, iterRows, iterLeft, iterTop );
    }

    ++fileIndex;
  }

  if ( destProvider )
    delete destProvider;

  qgsFree( redData ); qgsFree( greenData ); qgsFree( blueData ); qgsFree( alphaData );

  if ( progressDialog )
  {
    progressDialog->setValue( progressDialog->maximum() );
  }

  if ( mTiledMode )
  {
    QString vrtFilePath( mOutputUrl + "/" + vrtFileName() );
    writeVRT( vrtFilePath );
    if ( mBuildPyramidsFlag == QgsRaster::PyramidsFlagYes )
    {
      buildPyramids( vrtFilePath );
    }
  }
  else
  {
    if ( mBuildPyramidsFlag == QgsRaster::PyramidsFlagYes )
    {
      buildPyramids( mOutputUrl );
    }
  }
  return NoError;
}
QgsRasterFileWriter::WriterError QgsRasterFileWriter::writeDataRaster( const QgsRasterPipe* pipe, QgsRasterIterator* iter, int nCols, int nRows, const QgsRectangle& outputExtent,
    const QgsCoordinateReferenceSystem& crs, QProgressDialog* progressDialog )
{
  QgsDebugMsg( "Entered" );
  if ( !iter )
  {
    return SourceProviderError;
  }

  const QgsRasterInterface* iface = pipe->last();
  if ( !iface )
  {
    return SourceProviderError;
  }

  QgsRasterDataProvider* srcProvider = const_cast<QgsRasterDataProvider*>( dynamic_cast<const QgsRasterDataProvider*>( iface->srcInput() ) );
  if ( !srcProvider )
  {
    QgsDebugMsg( "Cannot get source data provider" );
    return SourceProviderError;
  }

  iter->setMaximumTileWidth( mMaxTileWidth );
  iter->setMaximumTileHeight( mMaxTileHeight );

  int nBands = iface->bandCount();
  if ( nBands < 1 )
  {
    return SourceProviderError;
  }


  //check if all the bands have the same data type size, otherwise we cannot write it to the provider
  //(at least not with the current interface)
  int dataTypeSize = QgsRasterBlock::typeSize( srcProvider->srcDataType( 1 ) );
  for ( int i = 2; i <= nBands; ++i )
  {
    if ( QgsRasterBlock::typeSize( srcProvider->srcDataType( 1 ) ) != dataTypeSize )
    {
      return DestProviderError;
    }
  }

  // Output data type - source data type is preferred but it may happen that we need
  // to set 'no data' value (which was not set on source data) if output extent
  // is larger than source extent (with or without reprojection) and there is no 'free'
  // (not used) value available
  QList<bool> destHasNoDataValueList;
  QList<double> destNoDataValueList;
  QList<QGis::DataType> destDataTypeList;
  for ( int bandNo = 1; bandNo <= nBands; bandNo++ )
  {
    QgsRasterNuller *nuller = pipe->nuller();

    bool srcHasNoDataValue = srcProvider->srcHasNoDataValue( bandNo );
    bool destHasNoDataValue = false;
    double destNoDataValue = std::numeric_limits<double>::quiet_NaN();
    QGis::DataType destDataType = srcProvider->srcDataType( bandNo );
    // TODO: verify what happens/should happen if srcNoDataValue is disabled by setUseSrcNoDataValue
    QgsDebugMsg( QString( "srcHasNoDataValue = %1 srcNoDataValue = %2" ).arg( srcHasNoDataValue ).arg( srcProvider->srcNoDataValue( bandNo ) ) );
    if ( srcHasNoDataValue )
    {

      // If source has no data value, it is used by provider
      destNoDataValue = srcProvider->srcNoDataValue( bandNo );
      destHasNoDataValue = true;
    }
    else if ( nuller && nuller->noData( bandNo ).size() > 0 )
    {
      // Use one user defined no data value
      destNoDataValue = nuller->noData( bandNo ).value( 0 ).min();
      destHasNoDataValue = true;
    }
    else
    {
      // Verify if we realy need no data value, i.e.
      QgsRectangle srcExtent = outputExtent;
      QgsRasterProjector *projector = pipe->projector();
      if ( projector && projector->destCrs() != projector->srcCrs() )
      {
        QgsCoordinateTransform ct( projector->destCrs(), projector->srcCrs() );
        srcExtent = ct.transformBoundingBox( outputExtent );
      }
      if ( !srcProvider->extent().contains( srcExtent ) )
      {
        // Destination extent is larger than source extent, we need destination no data values
        // Get src sample statistics (estimation from sample)
        QgsRasterBandStats stats = srcProvider->bandStatistics( bandNo, QgsRasterBandStats::Min | QgsRasterBandStats::Max, srcExtent, 250000 );

        // Test if we have free (not used) values
        double typeMinValue = QgsContrastEnhancement::maximumValuePossible(( QGis::DataType )srcProvider->srcDataType( bandNo ) );
        double typeMaxValue = QgsContrastEnhancement::maximumValuePossible(( QGis::DataType )srcProvider->srcDataType( bandNo ) );
        if ( stats.minimumValue > typeMinValue )
        {
          destNoDataValue = typeMinValue;
        }
        else if ( stats.maximumValue < typeMaxValue )
        {
          destNoDataValue = typeMaxValue;
        }
        else
        {
          // We have to use wider type
          destDataType = QgsRasterBlock::typeWithNoDataValue( destDataType, &destNoDataValue );
        }
        destHasNoDataValue = true;
      }
    }

    if ( nuller && destHasNoDataValue )
    {
      nuller->setOutputNoDataValue( bandNo, destNoDataValue );
    }

    QgsDebugMsg( QString( "bandNo = %1 destDataType = %2 destHasNoDataValue = %3 destNoDataValue = %4" ).arg( bandNo ).arg( destDataType ).arg( destHasNoDataValue ).arg( destNoDataValue ) );
    destDataTypeList.append( destDataType );
    destHasNoDataValueList.append( destHasNoDataValue );
    destNoDataValueList.append( destNoDataValue );
  }

  QGis::DataType destDataType = destDataTypeList.value( 0 );
  // Currently write API supports one output type for dataset only -> find the widest
  for ( int i = 1; i < nBands; i++ )
  {
    if ( destDataTypeList.value( i ) > destDataType )
    {
      destDataType = destDataTypeList.value( i );
      // no data value may be left per band (for future)
    }
  }

  //create destProvider for whole dataset here
  QgsRasterDataProvider* destProvider = 0;
  double pixelSize;
  double geoTransform[6];
  globalOutputParameters( outputExtent, nCols, nRows, geoTransform, pixelSize );

  // initOutput() returns 0 in tile mode!
  destProvider = initOutput( nCols, nRows, crs, geoTransform, nBands, destDataType, destHasNoDataValueList, destNoDataValueList );

  WriterError error = writeDataRaster( pipe, iter, nCols, nRows, outputExtent, crs, destDataType, destHasNoDataValueList, destNoDataValueList, destProvider, progressDialog );

  if ( error == NoDataConflict )
  {
    // The value used for no data was found in source data, we must use wider data type
    if ( destProvider ) // no tiles
    {
      destProvider->remove();
      delete destProvider;
      destProvider = 0;
    }
    else // VRT
    {
      // TODO: remove created VRT
    }

    // But we don't know which band -> wider all
    for ( int i = 0; i < nBands; i++ )
    {
      double destNoDataValue;
      QGis::DataType destDataType = QgsRasterBlock::typeWithNoDataValue( destDataTypeList.value( i ), &destNoDataValue );
      destDataTypeList.replace( i, destDataType );
      destNoDataValueList.replace( i, destNoDataValue );
    }
    destDataType =  destDataTypeList.value( 0 );

    // Try again
    destProvider = initOutput( nCols, nRows, crs, geoTransform, nBands, destDataType, destHasNoDataValueList, destNoDataValueList );
    error = writeDataRaster( pipe, iter, nCols, nRows, outputExtent, crs, destDataType, destHasNoDataValueList, destNoDataValueList, destProvider, progressDialog );
  }

  if ( destProvider )
    delete destProvider;

  return error;
}
Exemple #22
0
void QBrotliDecoder::decode()
{
    if (m_pInputDevice == nullptr || m_pOutputDevice == nullptr)
    {
        emit onError("IO devices not set.");
        return;
    }

    if (!m_pInputDevice->isReadable())
    {
        emit onError("Input not readable.");
        return;
    }

    if (!m_pOutputDevice->isWritable())
    {
        emit onError("Output not writeable.");
        return;
    }


    BrotliState state;
    qint64 totalsize=-1;

    if (!m_pInputDevice->isSequential())
        totalsize = m_pInputDevice->size();

    BrotliStateInit(&state);

    int finish = 0;
    BrotliResult r;

    BrotliInput input = initInput(m_pInputDevice);
    BrotliOutput output = initOutput(m_pOutputDevice);

    for (;;)
    {
        r = BrotliDecompressStreaming(input,output,finish,&state);
        if (r==0)
        {
            //error
            emit onError("Decoding error.");
            break;
        }
        else if (r==1)
        {
            //done
            break;
        }

        if (totalsize!=-1)
            emit onProgress((double)m_pInputDevice->pos()/(double)totalsize);


        if (m_pInputDevice->atEnd())
            finish=1;
    }

    emit onProgress(1.0);
    emit onDone();

    BrotliStateCleanup(&state);
}
int main(int argc, char *argv[])
{
  int i, j;

  initOutput();

  void *h = dlopen("/usr/lib/pulse-0.9.15/modules/module-nokia-record.so", RTLD_LAZY);
  EAP_WfirInt32_FilterFptr filter = (EAP_WfirInt32_FilterFptr)dlsym(h,"EAP_WfirThreeBandsInt32_filter");
  EAP_WfirInt32_ProcessFptr process = (EAP_WfirInt32_ProcessFptr)dlsym(h,"EAP_WfirThreeBandsInt32_Process");
  EAP_WfirInt32_InitFptr filterinit = (EAP_WfirInt32_InitFptr)dlsym(h,"EAP_WfirThreeBandsInt32_Init");

  filterinit((EAP_WfirInt32 *)&instn, 22050);
  EAP_WfirThreeBandsInt32_Init((EAP_WfirInt32 *)&inst, 22050);

  if(memcmp(&inst, &instn, sizeof(inst)))
  {
    printf("filterbanks differ after init");
    abort();
  }

  process((EAP_WfirInt32 *)&instn,
          leftLowOutputBuffersn,
          rightLowOutputBuffersn,
          leftHighOutputn,
          rightHighOutputn,
          lowInput,
          lowInput,
          lowInput,
          lowInput,
         SAMPLES);

  EAP_WfirThreeBandsInt32_Process((EAP_WfirInt32 *)&inst,
                                  leftLowOutputBuffers,
                                  rightLowOutputBuffers,
                                  leftHighOutput,
                                  rightHighOutput,
                                  lowInput,
                                  lowInput,
                                  lowInput,
                                  lowInput,
                                  SAMPLES);

  if(memcmp(&inst, &instn, sizeof(inst)))
  {
    printf("filterbanks differ after init");
    abort();
  }

  for (i = 0; i < BANDS; i++)
  {
    for(j = 0; j < SAMPLES; j++)
    {
      if(leftLowOutputBuffers[i][j] != leftLowOutputBuffersn[i][j])
      {
        printf("leftLowOutputBuffers[%d][%d] differ [%x] - [%x]\n", i, j,
               leftLowOutputBuffers[i][j], leftLowOutputBuffersn[i][j]);
        abort();
      }
      if(rightLowOutputBuffers[i][j] != rightLowOutputBuffersn[i][j])
      {
        printf("rightLowOutputBuffers[%d][%d] differ [%x] - [%x]\n", i, j,
               rightLowOutputBuffers[i][j], rightLowOutputBuffersn[i][j]);
        abort();
      }
    }
  }

  for (i = 0; i < SAMPLES; i++)
  {
    if(leftHighOutput[i] != leftHighOutputn[i])
    {
      printf("leftHighOutput[%d] differ [%x] - [%x]\n", i,
             leftHighOutput[i], leftHighOutputn[i]);
      abort();
    }
    if(rightHighOutput[i] != rightHighOutputn[i])
    {
      printf("rightHighOutput[%d] differ [%x] - [%x]\n", i,
             rightHighOutput[i], rightHighOutputn[i]);
      abort();
    }
  }

#if 1
  printf("Timing EAP_WfirThreeBandsInt32_Process with 3 x %d runs, %d samples\n", BENCHCNT, SAMPLES);

  printf("FOSS replacement:\n");
  for (i = 0; i < 3; i++)
  {
      timing(
        for (j = 0; j < BENCHCNT; j++)
          EAP_WfirThreeBandsInt32_Process((EAP_WfirInt32 *)&inst,
                                          leftLowOutputBuffers,
                                          rightLowOutputBuffers,
                                          leftHighOutput,
                                          rightHighOutput,
                                          lowInput,
                                          lowInput,
                                          lowInput,
                                          lowInput,
                                          SAMPLES)
      );
  }
  printf("Nokia stock:\n");
  for (i = 0; i < 3; i++)
  {
    timing(
      for (j = 0; j < BENCHCNT; j++)
        process((EAP_WfirInt32 *)&inst,
                leftLowOutputBuffers,
                rightLowOutputBuffers,
                leftHighOutput,
                rightHighOutput,
                lowInput,
                lowInput,
                lowInput,
                lowInput,
               SAMPLES)
        );
  }
#endif
}
IndexOutputPtr MMapDirectory::createOutput(const String& name) {
    initOutput(name);
    return newLucene<SimpleFSIndexOutput>(FileUtils::joinPath(directory, name));
}
Exemple #25
0
int main()
{ ReadInputNetwork(); initOutput(); TestPSFQ();
  //RunMultipleProbability();
}
Exemple #26
0
static struct DriverInstance*
GL_new_instance(const char* server_name,
		int xpos, int ypos,
		int width, int height,int mmx_supported,
		char* error_text, int text_len)
{
#ifdef VERBOSE_GL_OUTPUT
  std::cout << "GL_new_instance: " << std::endl;
  std::cout << "server_name: \"" << server_name << "\"" << std::endl;
  std::cout << "xpos: " << xpos << std::endl;
  std::cout << "ypos: " << ypos << std::endl;
  std::cout << "width: " << width << std::endl;
  std::cout << "height: " << height << std::endl;
#endif
  try
    {
      std::auto_ptr<DriverInstance> sh(new DriverInstance);
      
      sh->win_xsize = width;
      sh->win_ysize = height;
      
      // resize texture lazy during blit. init with a minimum
      sh->tex_xsize = 1; 
      sh->tex_ysize = 1;
      
      if (!initOutput("Ge-Phex OpenGL Output Window",
		     server_name,sh->win_xsize, sh->win_ysize, 32))
	{
	  throw std::runtime_error("Could not initialize the GLOutput window!"); 
	}
      
      // print info about the OpenGL implementation
      
#ifdef VERBOSE_GL_OUTPUT
      std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
      std::cout << "Renderer:" << glGetString(GL_RENDERER)<< std::endl;
      std::cout << "Version: " << glGetString(GL_VERSION)<< std::endl;
      std::cout << "Extensions: " << glGetString(GL_EXTENSIONS)<< std::endl;
#endif
      
      glDisable(GL_BLEND);
      glDisable(GL_DEPTH_TEST);
      glDepthMask(GL_FALSE);
      glDisable(GL_CULL_FACE);
      
      glEnable(GL_TEXTURE_2D);
      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      
      glClearColor(0.0, 0.0, 0.0, 0.0);
      glClear(GL_COLOR_BUFFER_BIT);
      
      return sh.release();
    }
  catch (std::exception& e)
    {
      snprintf(error_text, text_len,e.what());
      return 0;
    }
  catch (...)
    {
      snprintf(error_text, text_len,"could not initialize GL output");
      return 0;
    }
}
Exemple #27
0
bool OpenAL::reinitOutput(const QString& outDevDesc)
{
    QMutexLocker locker(&audioLock);
    cleanupOutput();
    return initOutput(outDevDesc);
}
/*!
* @brief	Initializes the whole system and runs the desired application
*
* This is the main function of the project. It calls initialization functions
* of the MCU and the sensors. In the infinite loop it repeatedly checks
* the USART module read buffer and Streams sensor data periodically (100 ms) via USART.
*
*/
int main(void)
{
	/********************* Initialize global variables **********************/

	bmf055_input_state = USART_INPUT_STATE_PRINT_DATA;
	
	/************************* Initializations ******************************/
	
	/*Initialize SAMD20 MCU*/
	system_init();
	
	/*Initialize clock module of SAMD20 MCU - Internal RC clock*/
	//clock_initialize(); // done via conf_clocks.h --> ASF
	
	/*SPI master for communicating with sensors*/
	spi_initialize();
	
	/*eeprom emulator for configuration storage */
	eeprom_emulator_initialize();
	
	/*Initialize timers */
	tc_initialize();
	
	/*Initialize UART for communication with PC*/
	usart_initialize();
	
	/*Enable the system interrupts*/
	system_interrupt_enable_global();/* All interrupts have a priority of level 0 which is the highest. */
	
	/* Initialize the sensors */
	bmf055_sensors_initialize();
	
	readEEPROM();
	checkFirstTime(0);
	//readEEPROM();
	
	configureReceiver();
	initSensors();
	previousTime = micros();
	calibratingG = 400;
	f.SMALL_ANGLES_25=1; // important for gyro only conf
  if(conf.copterType == 0){//0=Bi,1=Tri,2=QUADP,3=QUADX,4=Y4,5=Y6,6=H6P,7=H6X,8=Vtail4
    MULTITYPE      = 4;
    NUMBER_MOTOR   = 2;
  }
  if(conf.copterType == 1){
    MULTITYPE      = 1;
    NUMBER_MOTOR   = 3;
  }
  if(conf.copterType == 2){
    MULTITYPE      = 2;
    NUMBER_MOTOR   = 4;
  }
  if(conf.copterType == 3){
    MULTITYPE      = 3;
    NUMBER_MOTOR   = 4;
  }
  if(conf.copterType == 4){
    MULTITYPE      = 9;
    NUMBER_MOTOR   = 4;
  }
  if(conf.copterType == 5){
    MULTITYPE      = 6;
    NUMBER_MOTOR   = 6;
  }
  if(conf.copterType == 6){
    MULTITYPE      = 7;
    NUMBER_MOTOR   = 6;
  }
  if(conf.copterType == 7){
    MULTITYPE      = 10;
    NUMBER_MOTOR   = 6;
  }     
  if(conf.copterType == 8){
    MULTITYPE      = 17;
    NUMBER_MOTOR   = 4;
  }
  
  initOutput();
	
	/************************** Infinite Loop *******************************/
	while (true)
	{

		
		static uint8_t rcDelayCommand; // this indicates the number of time (multiple of RC measurement at 50Hz) the sticks must be maintained to run or switch off motors
  static uint8_t beepon = 0;
  uint8_t axis,i;
  int16_t error,errorAngle;
  int16_t delta,deltaSum;
  int16_t PTerm=0,ITerm=0,PTermACC=0,ITermACC=0,PTermGYRO=0,ITermGYRO=0,DTerm=0;
  static int16_t lastGyro[3] = {0,0,0};
  static int16_t delta1[3],delta2[3];
  static int16_t errorGyroI[3] = {0,0,0};
  static int16_t errorAngleI[2] = {0,0};
  static uint32_t rcTime  = 0;
  static uint32_t BeepTime  = 0;
  static uint8_t stickarmed = 0;
  //static int16_t initialThrottleHold;
  
  if(!rcOptions[BOXARM] && stickarmed == 0 && f.ARMED == 0){
    if(rcData[YAW]<conf.MINCHECK && rcData[ROLL]>conf.MAXCHECK){
      conf.calibState=1;
      writeParams(1);
      while(true){
        //blinkLED(10,30,1);
      }      
    }
  } 
 
  while(SetupMode == 1){
    checkSetup();
  }
 
 
  if(conf.RxType == 1 || conf.RxType == 2){
    if (rcFrameComplete) computeRC();
  }
  
  if(!rcOptions[BOXARM] && stickarmed == 0) {
    f.ARMED = 0;
  }

  if (currentTime > rcTime ) { // 50Hz
    rcTime = currentTime + 20000;
    if(failsave < 250)failsave++;
    debug[0] = failsave;
    if(conf.RxType != 1 && conf.RxType != 2){
      computeRC();
    }
  
    if ((rcData[THROTTLE] < conf.MINCHECK && s3D == 0) || (rcData[THROTTLE] > (1500-conf.MIDDLEDEADBAND) && rcData[THROTTLE] < (1500+conf.MIDDLEDEADBAND) && s3D == 1 && f.ARMED == 0)) {
      errorGyroI[ROLL] = 0; errorGyroI[PITCH] = 0; errorGyroI[YAW] = 0;
      errorAngleI[ROLL] = 0; errorAngleI[PITCH] = 0;

      rcDelayCommand++;
      if (rcData[YAW] < conf.MINCHECK && rcData[PITCH] < conf.MINCHECK && !f.ARMED) {
        if (rcDelayCommand == 20 && failsave < 20) {
          calibratingG=400;
        }
      }else if (rcData[YAW] > conf.MAXCHECK && rcData[PITCH] > conf.MAXCHECK && !f.ARMED) {
        if (rcDelayCommand == 20) {
          previousTime = micros();
        }
      }else if (conf.activate[BOXARM] > 0) {
        if ( rcOptions[BOXARM] && f.OK_TO_ARM && good_calib) {
	  f.ARMED = 1;
          stickarmed = 0;
        } else if (f.ARMED) f.ARMED = 0;
        rcDelayCommand = 0;
        
      
      } else if ( (rcData[YAW] < conf.MINCHECK ) && f.ARMED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 0) {
        if (rcDelayCommand == 20) f.ARMED = 0; // rcDelayCommand = 20 => 20x20ms = 0.4s = time to wait for a specific RC command to be acknowledged
      } else if ( (rcData[YAW] > conf.MAXCHECK ) && rcData[PITCH] < conf.MAXCHECK && !f.ARMED && calibratingG == 0 && f.ACC_CALIBRATED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 0) {
        if (rcDelayCommand == 20 && good_calib) {
	  f.ARMED = 1;
          stickarmed = 1;
        }
  
       } else if ( (rcData[ROLL] < conf.MINCHECK ) && f.ARMED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 1) {
        if (rcDelayCommand == 20) f.ARMED = 0; // rcDelayCommand = 20 => 20x20ms = 0.4s = time to wait for a specific RC command to be acknowledged
      } else if ( (rcData[ROLL] > conf.MAXCHECK ) && rcData[PITCH] < conf.MAXCHECK && !f.ARMED && calibratingG == 0 && f.ACC_CALIBRATED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 1) {
        if (rcDelayCommand == 20 && good_calib) {
	  f.ARMED = 1;
          stickarmed = 1;
        }       
        
        
      } else
        rcDelayCommand = 0;
    } else if (rcData[THROTTLE] > conf.MAXCHECK && !f.ARMED) {
      if (rcData[YAW] < conf.MINCHECK && rcData[PITCH] < conf.MINCHECK) {        // throttle=max, yaw=left, pitch=min
        if (rcDelayCommand == 20) calibratingA=400;
        rcDelayCommand++;
      } else if (rcData[PITCH] > conf.MAXCHECK) {
         conf.angleTrim[PITCH]+=2;writeParams(1);
      } else if (rcData[PITCH] < conf.MINCHECK) {
         conf.angleTrim[PITCH]-=2;writeParams(1);
      } else if (rcData[ROLL] > conf.MAXCHECK) {
         conf.angleTrim[ROLL]+=2;writeParams(1);
      } else if (rcData[ROLL] < conf.MINCHECK) {
         conf.angleTrim[ROLL]-=2;writeParams(1);
      } else {
        rcDelayCommand = 0;
      }
    }
    
    

    uint16_t auxState = 0;
    for(i=0;i<4;i++)
      auxState |= (rcData[AUX1+i]<1300)<<(3*i) | (1300<rcData[AUX1+i] && rcData[AUX1+i]<1700)<<(3*i+1) | (rcData[AUX1+i]>1700)<<(3*i+2);
    for(i=0;i<CHECKBOXITEMS;i++)
      rcOptions[i] = (auxState & conf.activate[i])>0;
      
      
     if(failsave > 200 && f.ARMED){
      rcOptions[BOXACC] = 1;
      s3D = 0;
      rcData[THROTTLE] = 1190;
      rcCommand[THROTTLE] = 1190;
    }

    if (rcOptions[BOXACC] && s3D == 0) { 
      // bumpless transfer to Level mode
      if (!f.ACC_MODE) {
        errorAngleI[ROLL] = 0; errorAngleI[PITCH] = 0;
        f.ACC_MODE = 1;
      }  
    } else {
      // failsafe support
      f.ACC_MODE = 0;
    }
    if (rcOptions[BOXBEEP]) { 
      f.FSBEEP = 1;
      if(currentTime > BeepTime){
        BeepTime = currentTime + 50000;
        if(beepon == 0){
          if(conf.RxType == 0){
            //digitalWrite(A2,HIGH); 
          }else{
            //digitalWrite(8,HIGH); 
          }          
          beepon = 1;
        }else{
          if(conf.RxType == 0){
            //digitalWrite(A2,LOW); 
          }else{
            //digitalWrite(8,LOW); 
          }
          beepon = 0;
        }
      }
    } else {
      f.FSBEEP = 0;
      if(conf.RxType == 0){
        //digitalWrite(A2,LOW); 
      }else{
        //digitalWrite(8,LOW); 
      }
    }    

    
    if (rcOptions[BOXHORIZON] && s3D == 0) { 
      // bumpless transfer to Horizon mode
      if (!f.HORIZON_MODE) {
        errorAngleI[ROLL] = 0; errorAngleI[PITCH] = 0;
        f.HORIZON_MODE = 1;
      }  
    } else {
      f.HORIZON_MODE = 0;
    }
    
    if (rcOptions[BOX3D] && conf.F3D == 1) {  
      if(f.ARMED == 0 && s3D == 0){
        s3D = 1;
        f.ACC_MODE = 0;
        f.HORIZON_MODE = 0;
      }
    } else if(f.ARMED == 0){
      s3D = 0;
    }   
    

    if (rcOptions[BOXARM] == 0) f.OK_TO_ARM = 1;
  }
 
  computeIMU();
  int16_t prop;
  if (f.HORIZON_MODE)
    prop = max(abs(rcCommand[PITCH]),abs(rcCommand[ROLL])); // range [0;500]  
  
  
  if (f.ACC_MODE){
    if(Zadd > 0)Zadd--;
    if(Zadd < 0)Zadd++;
  }else{
    Zadd = 0;
  }

  

  //**** PITCH & ROLL & YAW PID ****    
  for(axis=0;axis<3;axis++) {
    if ((f.ACC_MODE || f.HORIZON_MODE) && axis<2 ) { //LEVEL MODE
      // 50 degrees max inclination
      errorAngle = constrain(2*rcCommand[axis],-500,+500) - angle[axis] + conf.angleTrim[axis]; //16 bits is ok here
      #ifdef LEVEL_PDF
        PTermACC      = -(int32_t)angle[axis]*conf.P8[PIDLEVEL]/100 ;
      #else  
        PTermACC      = (int32_t)errorAngle*conf.P8[PIDLEVEL]/100 ;                          // 32 bits is needed for calculation: errorAngle*P8[PIDLEVEL] could exceed 32768   16 bits is ok for result
      #endif
      PTermACC = constrain(PTermACC,-conf.D8[PIDLEVEL]*5,+conf.D8[PIDLEVEL]*5);

      errorAngleI[axis]  = constrain(errorAngleI[axis]+errorAngle,-10000,+10000);    // WindUp     //16 bits is ok here
      ITermACC           = ((int32_t)errorAngleI[axis]*conf.I8[PIDLEVEL])>>12;            // 32 bits is needed for calculation:10000*I8 could exceed 32768   16 bits is ok for result
    }
    if ( !f.ACC_MODE || f.HORIZON_MODE || axis == 2 ) { // MODE relying on GYRO or YAW axis
      if (abs(rcCommand[axis])<350) error =          rcCommand[axis]*10*8/conf.P8[axis] ; // 16 bits is needed for calculation: 350*10*8 = 28000      16 bits is ok for result if P8>2 (P>0.2)
                               else error = (int32_t)rcCommand[axis]*10*8/conf.P8[axis] ; // 32 bits is needed for calculation: 500*5*10*8 = 200000   16 bits is ok for result if P8>2 (P>0.2)
      error -= gyroData[axis];

      PTermGYRO = rcCommand[axis];
      
      errorGyroI[axis]  = constrain(errorGyroI[axis]+error,-16000,+16000);          // WindUp   16 bits is ok here
      if (abs(gyroData[axis])>640) errorGyroI[axis] = 0;
      ITermGYRO         = (errorGyroI[axis]/125*conf.I8[axis])>>6;                                   // 16 bits is ok here 16000/125 = 128 ; 128*250 = 32000
    }
    if ( f.HORIZON_MODE && axis<2) {
      PTerm = ((int32_t)PTermACC*(500-prop) + (int32_t)PTermGYRO*prop)/500;
      ITerm = ((int32_t)ITermACC*(500-prop) + (int32_t)ITermGYRO*prop)/500;
    } else {
      if ( f.ACC_MODE && axis<2) {
        PTerm = PTermACC;
        ITerm = ITermACC;
      } else {
        PTerm = PTermGYRO;
        ITerm = ITermGYRO;
      }
    }
    if (abs(gyroData[axis])<160) PTerm -=          gyroData[axis]*dynP8[axis]/10/8; // 16 bits is needed for calculation   160*200 = 32000         16 bits is ok for result
                            else PTerm -= (int32_t)gyroData[axis]*dynP8[axis]/10/8; // 32 bits is needed for calculation   

    delta          = gyroData[axis] - lastGyro[axis];                               // 16 bits is ok here, the dif between 2 consecutive gyro reads is limited to 800
    lastGyro[axis] = gyroData[axis];
    deltaSum       = delta1[axis]+delta2[axis]+delta;
    delta2[axis]   = delta1[axis];
    delta1[axis]   = delta;
 
    if (abs(deltaSum)<640) DTerm = (deltaSum*dynD8[axis])>>5;                       // 16 bits is needed for calculation 640*50 = 32000           16 bits is ok for result 
                      else DTerm = ((int32_t)deltaSum*dynD8[axis])>>5;              // 32 bits is needed for calculation
                      
    axisPID[axis] =  PTerm + ITerm - DTerm;
  }
Exemple #29
0
/**
 * @brief Initialize audio output device, if not initialized.
 *
 * @return true, if device was initialized; false otherwise
 */
bool OpenAL::autoInitOutput()
{
    return alOutDev ? true : initOutput(Settings::getInstance().getOutDev());
}