Exemplo n.º 1
0
BOOL LLImageTGA::updateData()
{
	resetLastError();

	// Check to make sure that this instance has been initialized with data
	if (!getData() || (0 == getDataSize()))
	{
		setLastError("LLImageTGA uninitialized");
		return FALSE;
	}
	
	// Pull image information from the header...
	U8	flags;
	U8	junk[256];

	/****************************************************************************
	**
	**	For more information about the original Truevision TGA(tm) file format,
	**	or for additional information about the new extensions to the
	**	Truevision TGA file, refer to the "Truevision TGA File Format
	**	Specification Version 2.0" available from Truevision or your
	**	Truevision dealer.
	**
	**  FILE STRUCTURE FOR THE ORIGINAL TRUEVISION TGA FILE				
	**	  FIELD 1 :	NUMBER OF CHARACTERS IN ID FIELD (1 BYTES)	
	**	  FIELD 2 :	COLOR MAP TYPE (1 BYTES)			
	**	  FIELD 3 :	IMAGE TYPE CODE (1 BYTES)			
	**					= 0	NO IMAGE DATA INCLUDED		
	**					= 1	UNCOMPRESSED, COLOR-MAPPED IMAGE
	**					= 2	UNCOMPRESSED, TRUE-COLOR IMAGE	
	**					= 3	UNCOMPRESSED, BLACK AND WHITE IMAGE
	**					= 9	RUN-LENGTH ENCODED COLOR-MAPPED IMAGE
	**					= 10 RUN-LENGTH ENCODED TRUE-COLOR IMAGE
	**					= 11 RUN-LENGTH ENCODED BLACK AND WHITE IMAGE
	**	  FIELD 4 :	COLOR MAP SPECIFICATION	(5 BYTES)		
	**				4.1 : COLOR MAP ORIGIN (2 BYTES)	
	**				4.2 : COLOR MAP LENGTH (2 BYTES)	
	**				4.3 : COLOR MAP ENTRY SIZE (2 BYTES)	
	**	  FIELD 5 :	IMAGE SPECIFICATION (10 BYTES)			
	**				5.1 : X-ORIGIN OF IMAGE (2 BYTES)	
	**				5.2 : Y-ORIGIN OF IMAGE (2 BYTES)	
	**				5.3 : WIDTH OF IMAGE (2 BYTES)		
	**				5.4 : HEIGHT OF IMAGE (2 BYTES)		
	**				5.5 : IMAGE PIXEL SIZE (1 BYTE)		
	**				5.6 : IMAGE DESCRIPTOR BYTE (1 BYTE) 	
	**	  FIELD 6 :	IMAGE ID FIELD (LENGTH SPECIFIED BY FIELD 1)	
	**	  FIELD 7 :	COLOR MAP DATA (BIT WIDTH SPECIFIED BY FIELD 4.3 AND
	**				NUMBER OF COLOR MAP ENTRIES SPECIFIED IN FIELD 4.2)
	**	  FIELD 8 :	IMAGE DATA FIELD (WIDTH AND HEIGHT SPECIFIED IN
	**				FIELD 5.3 AND 5.4)				
	****************************************************************************/

	mDataOffset = 0;
	mIDLength = *(getData()+mDataOffset++);
	mColorMapType = *(getData()+mDataOffset++);
	mImageType = *(getData()+mDataOffset++);
	mColorMapIndexLo = *(getData()+mDataOffset++);
	mColorMapIndexHi = *(getData()+mDataOffset++);
	mColorMapLengthLo = *(getData()+mDataOffset++);
	mColorMapLengthHi = *(getData()+mDataOffset++);
	mColorMapDepth = *(getData()+mDataOffset++);
	mXOffsetLo = *(getData()+mDataOffset++);
	mXOffsetHi = *(getData()+mDataOffset++);
	mYOffsetLo = *(getData()+mDataOffset++);
	mYOffsetHi = *(getData()+mDataOffset++);
	mWidthLo = *(getData()+mDataOffset++);
	mWidthHi = *(getData()+mDataOffset++);
	mHeightLo = *(getData()+mDataOffset++);
	mHeightHi = *(getData()+mDataOffset++);
	mPixelSize = *(getData()+mDataOffset++);
	flags = *(getData()+mDataOffset++);
	mAttributeBits = flags & 0xf;
	mOriginRightBit = (flags & 0x10) >> 4;
	mOriginTopBit = (flags & 0x20) >> 5;
	mInterleave = (flags & 0xc0) >> 6;

	switch( mImageType )
	{
	case 0:
		// No image data included in file
		setLastError("Unable to load file.  TGA file contains no image data.");
		return FALSE;
	case 1:
		// Colormapped uncompressed
		if( 8 != mPixelSize )
		{
			setLastError("Unable to load file.  Colormapped images must have 8 bits per pixel.");
			return FALSE;
		}
		break;
	case 2:
		// Truecolor uncompressed
		break;
	case 3:
		// Monochrome uncompressed
		if( 8 != mPixelSize )
		{
			setLastError("Unable to load file.  Monochrome images must have 8 bits per pixel.");
			return FALSE;
		}
		break;
	case 9:
		// Colormapped, RLE
		break;
	case 10:
		// Truecolor, RLE
		break;
	case 11:
		// Monochrome, RLE
		if( 8 != mPixelSize )
		{
			setLastError("Unable to load file.  Monochrome images must have 8 bits per pixel.");
			return FALSE;
		}
		break;
	default:
		setLastError("Unable to load file.  Unrecoginzed TGA image type.");
		return FALSE;
	}

	// discard the ID field, if any
	if (mIDLength)
	{
		memcpy(junk, getData()+mDataOffset, mIDLength);	/* Flawfinder: ignore */
		mDataOffset += mIDLength;
	}
	
	// check to see if there's a colormap since even rgb files can have them
	S32 color_map_bytes = 0;
	if( (1 == mColorMapType) && (mColorMapDepth > 0) )
	{
		mColorMapStart = (S32(mColorMapIndexHi) << 8) + mColorMapIndexLo;
		mColorMapLength = (S32(mColorMapLengthHi) << 8) + mColorMapLengthLo;
		
		if( mColorMapDepth > 24 )
		{
			mColorMapBytesPerEntry = 4;
		}
		else
		if( mColorMapDepth > 16 )
		{
			mColorMapBytesPerEntry = 3;
		}
		else
		if( mColorMapDepth > 8 )
		{
			mColorMapBytesPerEntry = 2;
		}
		else
		{
			mColorMapBytesPerEntry = 1;
		}
		color_map_bytes = mColorMapLength * mColorMapBytesPerEntry;

		// Note: although it's legal for TGA files to have color maps and not use them
		// (some programs actually do this and use the color map for other ends), we'll
		// only allocate memory for one if _we_ intend to use it.
		if ( (1 == mImageType) || (9 == mImageType)  )
		{
			mColorMap = new U8[ color_map_bytes ];  
			if (!mColorMap)
			{
				llerrs << "Out of Memory in BOOL LLImageTGA::updateData()" << llendl;
				return FALSE;
			}
			memcpy( mColorMap, getData() + mDataOffset, color_map_bytes );	/* Flawfinder: ignore */
		}

		mDataOffset += color_map_bytes;
	}

	// heights are read as bytes to prevent endian problems
	S32 height = (S32(mHeightHi) << 8) + mHeightLo;
	S32 width = (S32(mWidthHi) << 8) + mWidthLo;

	// make sure that it's a pixel format that we understand
	S32 bits_per_pixel;
	if( mColorMap )
	{
		bits_per_pixel = mColorMapDepth;
	}
	else
	{
		bits_per_pixel = mPixelSize;
	}

	S32 components;
	switch(bits_per_pixel)
	{
	case 24:
		components = 3;
		break;
	case 32:
		components = 4;
//		Don't enforce this.  ACDSee doesn't bother to set the attributes bits correctly. Arrgh!
//		if( mAttributeBits != 8 )
//		{
//			setLastError("Unable to load file. 32 bit TGA image does not have 8 bits of alpha.");
//			return FALSE;
//		}
		mAttributeBits = 8;
		break;
	case 15:
	case 16:
		components = 3;
		mIs15Bit = TRUE;  // 16th bit is used for Targa hardware interupts and is ignored.
		break;
	case 8:
		components = 1;
		break;
	default:
		setLastError("Unable to load file. Unknown pixel size.");
		return FALSE;
	}
	setSize(width, height, components);
	
	return TRUE;
}
Exemplo n.º 2
0
string Assets::getPlayerName(int i){
    return getData("player_" + ofToString(i))["name"].asString();
}
Exemplo n.º 3
0
string Assets::getPlayerAttributes(int i){
    return getData("player_" + ofToString(i))["color"].asString();
}
Exemplo n.º 4
0
int main(int argc, char const* argv[]) {

	//struct addrinfo hints, *ai, *ai0;
	int sock, error;
	uint32_t get_data;
	uint32_t stock_data[ELEM];
	uint32_t default_data[ELEM];
	/*
	int buf_len;
	uint32_t buf;
	*/

	char host[16];
	char port[16];
	strcpy(host, argv[1]);
	strcpy(port, argv[2]);

	sock = makesock(port);
	printf("sock : %d\n", sock);

	int i;

	// game start
	while(true) {
		get_data = getData(&sock, stock_data);
		if(stock_data[1] == LIST) {
			printf("can connect to game.\n");
			break;
		}
	}

	//printf("\n");
	//printf("first dump.\n");
	//dump_data(stock_data);
/*
	printf("2222222222\n");
		get_data = getData(&sock, stock_data);
	printf("3333333333\n");
		get_data = getData(&sock, stock_data);
*/


	bool list_flag = false;
	uint32_t math;
	uint32_t buy_id;
	uint32_t code = stock_data[1];
	uint32_t value;
	uint32_t key = stock_data[0];
	int turn = 0;
	uint32_t budget = 10000;

	uint32_t my_stock[COMPANY];
	int j;
	for(j = 0; j < COMPANY; j++) {
		my_stock[j] = 0;
	}

	printf("\n");
	printf("game start.\n");

	int read_len = -1;
	int buy_flag = 0;

	int s;
	// doing game
	//while(1) {
	for(s = 0; s < TURNS; s++) {

		uint32_t tmp_data[ELEM];
		//printf("turn begin -> budget: %d, turn: %d, key: %u, code: %x\n", budget, s + 1, stock_data[0], stock_data[1]);

		int a;
		/*
		for(a = 0; a < 22; a++) {
			printf("%u, ", stock_data[a]);
		}
		*/
		//status(&budget, my_stock, &s, &math, &buy_id, &code);
		read_len = -1;
		//if(read_len = getData(sock, stock_data) > 0 && stock_data[1] == 0 && read_len >= 22) {


/*
		while(1) {
			if(read_len = getData(&sock, stock_data) > 0) {
				break;
			}
		}
*/
		/*
		math = 10;
		buy_id = 1;
		code = PURCHASE;
		request(&sock, stock_data, &math, &buy_id, &code);
*/
		//stock_data[1] = 0;
		//if(read_len = getData(&sock, tmp_data) > 0 && tmp_data[1] == LIST) {
		

		list_flag = true;
		printf("\n ====== begin turn. before request. ======\n");


		for(i = 0; i < 5; i++) {
			if(s % 2 == 0) {
				code = PURCHASE;
			} else {
				code = SALE;
			}

			math = 10;
			buy_id = i;
			key = tmp_data[0];
			//request(&sock, stock_data, &math, &buy_id, &code);
			request(&sock, &key, &math, &buy_id, &code);
			int l;
			l = getData(&sock, tmp_data);
			if(tmp_data[1] != ACCEPT) {
				printf("\nnot accepted request.\n");
			} else {
				printf("\naccepted request.\n");
				status(&budget, my_stock, &s, &math, &buy_id, &code);
			//	status(&budget, my_stock, &turn, &math, &buy_id, &code);
			}
		}



		while(list_flag == true) {
			
			if(read_len = getData(&sock, tmp_data) > 0 && tmp_data[1] == LIST) {
				//if(tmp_data[1] == LIST) {
				code = tmp_data[1];
				key = tmp_data[0];
				tmp_data[1] = 0x11111111;
				list_flag = false;
				//	tmp_data[1] = 0;
			}
			//if(stock_data[1] == LIST) {
			//}

			/*
			if(stock_data[1] == 0x001) {
				list_flag = true;
				turn++;
			} else if(stock_data[2] == 0x002) {
				printf("last budget is %d\n", budget);
				break;
			}*/
			//if(list_flag == true) {
						//list_flag = false;
			//}
		}
		
		
		
		// read list
		printf("result -> budget: %d, turn: %d, key: %u, code: %x\n", budget, s + 1, tmp_data[0], tmp_data[1]);

	}
	
	return 0;
}
String MemoryOutputStream::toUTF8() const
{
    const char* const d = static_cast <const char*> (getData());
    return String (CharPointer_UTF8 (d), CharPointer_UTF8 (d + getDataSize()));
}
Exemplo n.º 6
0
	void TrickHelper::valueIterator( CardGroup group , IterData& iterData , int outIndex[] , int* power )
	{
		switch( group )
		{
		case CG_SINGLE:
			valueIteratorSingle( iterData.face[0] , outIndex , power );
			break;
		case CG_ONE_PAIR:
			valueIteratorOnePair( iterData.face[0] , outIndex , power );
			break;
		case CG_THREE_OF_KIND:
			valueIteratorThreeOfKind( iterData.face[0] , outIndex , power );
			break;
		case CG_TWO_PAIR:
			break;
		case CG_STRAIGHT:
			{
				IterStraight& straight = iterData.straight;
				int idxGroup = getData( POS_STRAIGHT ).index[ iterData.condition ];

				for( int i = 0 ; i < 4 ; ++i )
					outIndex[i] = mFaceGroups[ idxGroup + i ].index + straight.index[i];

				if ( mFaceGroups[ idxGroup ].rank == Card::toRank( Card::eN10 ) )
					outIndex[4] = mFaceGroups[ 0 ].index + straight.index[4];
				else
					outIndex[4] = mFaceGroups[ idxGroup + 4 ].index + straight.index[4];

				if ( power )
				{
					Card cards[5];
					for( int i = 0 ; i < 5 ; ++ i )
						cards[i] = mParseCards[ outIndex[i] ];
					*power = TrickUtility::calcPower( CG_STRAIGHT , cards );
				}
			}
			break;
		case CG_FLUSH:
			{
				IterFlush& data = iterData.flush;
				int idxGroup = getData( POS_FLUSH ).index[ data.count ];
				for( int i = 0 ; i < 5 ; ++i )
					outIndex[i] = mSuitGroup[ idxGroup ].index[ data.combine[i] ];

				if ( power )
				{
					Card cards[5];
					for( int i = 0 ; i < 5 ; ++ i )
						cards[i] = mParseCards[ outIndex[i] ];
					*power = TrickUtility::calcPower( CG_FLUSH , cards );
				}
			}	
			break;

		case CG_FULL_HOUSE:
			{
				valueIteratorOnePair( iterData.face[1] , outIndex , NULL );
				valueIteratorThreeOfKind( iterData.face[0] , outIndex + 2 , NULL );
				
				if ( power )
				{
					Card cards[5];
					for( int i = 0 ; i < 5 ; ++ i )
						cards[i] = mParseCards[ outIndex[i] ];
					*power = TrickUtility::calcPower( CG_FULL_HOUSE , cards );
				}
			}
			break;
		case CG_FOUR_OF_KIND:
			{
				int idxGroup = getData( POS_FOUR_OF_KIND ).index[ iterData.face[0].count ];

				valueIteratorSingle( iterData.face[1] , outIndex , NULL );
				for( int i = 0 ; i < 4 ; ++i )
					outIndex[i + 1] = mFaceGroups[ idxGroup ].index + i;

				if ( power )
				{
					Card cards[5];
					for( int i = 0 ; i < 5 ; ++ i )
						cards[i] = mParseCards[ outIndex[i] ];
					*power = TrickUtility::calcPower( CG_FOUR_OF_KIND , cards );
				}	
			}
			break;
		case CG_STRAIGHT_FLUSH:
			{
				int valueGroup = getData( POS_STRAIGHT_FLUSH ).index[ iterData.face[0].count ];
				int idxGroup = valueGroup >> 2;
				int suit     = valueGroup & 0x3;

				for( int i = 0 ; i < 4 ; ++i )
				{
					int idx = idxGroup + i;
					int count = 0;
					for( int n = 0 ; n < suit ; ++n )
					{
						if ( BIT( n ) & mFaceGroups[ idx ].suitMask )
							++count;
					}
					outIndex[i] = mFaceGroups[ idx ].index + count;
				}
				{
					int idx = ( mFaceGroups[ idxGroup ].rank == Card::toRank( Card::eN10 ) ) ? 0 : idxGroup + 4;
					int count = 0;
					for( int n = 0 ; n < suit ; ++n )
					{
						if ( BIT( n ) & mFaceGroups[ idx ].suitMask )
							++count;
					}
					outIndex[4] = mFaceGroups[ idx ].index + count;
				}

				if ( power )
				{
					Card cards[5];
					for( int i = 0 ; i < 5 ; ++ i )
						cards[i] = mParseCards[ outIndex[i] ];
					*power = TrickUtility::calcPower( CG_STRAIGHT_FLUSH , cards );
				}	
			}
			break;
		}
	}
Exemplo n.º 7
0
	void load(uint32 offset) {
		byte *item = getData(offset);
		messageNum = READ_LE_UINT16(item + 0);
		messageParam = READ_LE_UINT32(item + 4);
	}
Exemplo n.º 8
0
void LLTemplateMessageReader::getS32(const char *block, const char *var, 
										 S32 &d, S32 blocknum)
{
	getData(block, var, &d, sizeof(S32), blocknum);
}
Exemplo n.º 9
0
void LLTemplateMessageReader::getU64(const char *block, const char *var, 
									 U64 &d, S32 blocknum)
{
	getData(block, var, &d, sizeof(U64), blocknum);
}
Exemplo n.º 10
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void EMCalculation::execute()
{
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
    tbb::task_scheduler_init init;
  //  int threads = init.default_num_threads();
 //   std::cout << "TBB Thread Count: " << threads << std::endl;
#endif
  EMMPM_Data* data = m_Data.get();
  int k;
  int emiter = data->emIterations;
  real_t* simAnnealKappas = NULL;
  bool stop = false;

  float totalLoops = (float)(data->emIterations * data->mpmIterations + data->mpmIterations);
  float currentLoopCount = 0.0;

  size_t ccostLoopDelay = data->ccostLoopDelay;

  char msgbuff[256];
  memset(msgbuff, 0, 256);
  data->currentEMLoop = 0;
  data->currentMPMLoop = 0;

  //Copy in the users Beta Value
  data->workingKappa = 1.0;

  // If we are using Sim Anneal then create a ramped beta
  if (data->simulatedAnnealing != 0 && data->emIterations > 1)
  {
    simAnnealKappas=(real_t*)(malloc(sizeof(real_t)*data->emIterations));
    for (int i = 0; i < data->emIterations; ++i)
    {
      simAnnealKappas[i] = data->workingKappa + pow(i/(data->emIterations-1.0), 8) * (10.0*data->workingKappa - data->workingKappa);
    }
    data->workingKappa = simAnnealKappas[0];
  }


  /* Perform a single MPM Loop to get things initialized. This is Jeff Simmons'
   * idea and is a good idea.  */
  k = 0; // Simulate first loop of EM by setting k=0;
  // Possibly update the beta value due to simulated Annealing
  if (data->simulatedAnnealing != 0 && data->emIterations > 1)
  {
    data->workingKappa = simAnnealKappas[k];
  }

  data->calculateBetaMatrix(data->in_beta);


  MorphFilter::Pointer morphFilt = MorphFilter::New();

  /* After curveLoopDelay iterations, begin calculating curvature costs */
  if (k >= ccostLoopDelay && data->useCurvaturePenalty)
  {
    notify("Performing Morphological Filter on input data", 0, UpdateProgressMessage);
    morphFilt->multiSE(data);
  }

  // Zero out the Mean, Variance and N values for both the current and previous
  EMMPMUtilities::ZeroMeanVariance(data->classes, data->dims, data->prev_mu, data->prev_variance, data->N);

  notify("Performing Initial MPM Loop", 0, UpdateProgressMessage);

  /* Perform initial MPM - (Estimation) */
  MPMCalculation::Pointer acvmpm = MPMCalculation::New();
  acvmpm->setData(getData());
  acvmpm->setObservers(getObservers());
  acvmpm->setStatsDelegate(getStatsDelegate());
  acvmpm->execute();


  /* -----------------------------------------------------------
  *                Perform EM Loops
  * ------------------------------------------------------------ */
  for (k = 0; k < emiter; k++)
  {

    /* Send back the Progress Stats and the segmented image. If we never get into this loop because
    * emiter == 0 then we will still send back the stats just after the end of the EM Loops */
    EMMPMUtilities::ConvertXtToOutputImage(getData());
    if (m_StatsDelegate != NULL)
    {
      m_StatsDelegate->reportProgress(getData());
    }

    snprintf(msgbuff, 256, "EM Loop %d", data->currentEMLoop);
    notify(msgbuff, 0, UpdateProgressMessage);

    /* Check to see if we are canceled */
    if (data->cancel) { data->progress = 100.0; break; }

    data->inside_em_loop = 1;
    data->currentEMLoop = k+1;
    data->currentMPMLoop = 0;
    currentLoopCount = (float)( (data->mpmIterations * data->currentEMLoop) + data->currentMPMLoop);

    data->progress = currentLoopCount/totalLoops * 100.0;

    /* Check if the "Error" is less than a user defined Tolerance and if it is then
     * bail out of the loop now.
     */
    stop = EMMPMUtilities::isStoppingConditionLessThanTolerance(getData());
    if (stop == true)
    {
        break;
    }

    /* Copy the current Mean and Variance Values to the "prev_*" variables */
    EMMPMUtilities::copyCurrentMeanVarianceValues(getData());

    /* Reset model parameters to zero */
    EMMPMUtilities::ZeroMeanVariance(data->classes, data->dims, data->mean, data->variance, data->N);

    /* Update Means and Variances */
    EMMPMUtilities::UpdateMeansAndVariances(getData());

#if 0
    /* Monitor estimates of mean and variance */
    if (emiter < 10 || (k + 1) % (emiter / 10) == 0)
    {
      EMMPM_MonitorMeansAndVariances(data, callbacks);
    }
#endif

#if 1
    /* Eliminate any classes that have zero probability */
    EMMPMUtilities::RemoveZeroProbClasses(getData());
#endif

    // Possibly update the beta value due to simulated Annealing
    if (data->simulatedAnnealing != 0 && data->emIterations > 1)
    {
      data->workingKappa = simAnnealKappas[k];
      data->calculateBetaMatrix(data->in_beta);
    }


    /* After curveLoopDelay iterations, begin calculating curvature costs */
    if (k >= ccostLoopDelay && data->useCurvaturePenalty)
    {
      morphFilt->multiSE(data);
    }

    /* Perform MPM - (Estimation) */
    acvmpm->execute();
  } /* EM Loop End */

  EMMPMUtilities::ConvertXtToOutputImage(getData());

  data->inside_em_loop = 0;
  free(simAnnealKappas);
}
Exemplo n.º 11
0
void LLTemplateMessageReader::getU8(const char *block, const char *var, 
										U8 &u, S32 blocknum)
{
	getData(block, var, &u, sizeof(U8), blocknum);
}
Exemplo n.º 12
0
BOOL LLImageTGA::decodeTruecolorRle32( LLImageRaw* raw_image, BOOL &alpha_opaque )
{
	llassert( getComponents() == 4 );
	alpha_opaque = TRUE;

	U8* dst = raw_image->getData();
	U32* dst_pixels = (U32*) dst;

	U8* src = getData() + mDataOffset;
	U8* last_src = src + getDataSize();

	U32 rgba;
	U8* rgba_byte_p = (U8*) &rgba;

	U32* last_dst_pixel = dst_pixels + getHeight() * getWidth() - 1;
	while( dst_pixels <= last_dst_pixel )
	{
		// Read RLE block header
		
		if (src >= last_src)
			return FALSE;

		U8 block_header_byte = *src;
		src++;

		U32 block_pixel_count = (block_header_byte & 0x7F) + 1;
		if( block_header_byte & 0x80 )
		{
			// Encoded (duplicate-pixel) block

			if (src + 3 >= last_src)
				return FALSE;
			
			rgba_byte_p[0] = src[2];
			rgba_byte_p[1] = src[1];
			rgba_byte_p[2] = src[0];
			rgba_byte_p[3] = src[3];
			if (rgba_byte_p[3] != 255)
			{
				alpha_opaque = FALSE;
			}

			src += 4;
			register U32 value = rgba;
			do
			{
				*dst_pixels = value;
				dst_pixels++;
				block_pixel_count--;
			}
			while( block_pixel_count > 0 );
		}
		else 
		{
			// Unencoded block
			do
			{
				if (src + 3 >= last_src)
					return FALSE;
				
				((U8*)dst_pixels)[0] = src[2];
				((U8*)dst_pixels)[1] = src[1];
				((U8*)dst_pixels)[2] = src[0];
				((U8*)dst_pixels)[3] = src[3];
				if (src[3] != 255)
				{
					alpha_opaque = FALSE;
				}
				src += 4;
				dst_pixels++;
				block_pixel_count--;
			}
			while( block_pixel_count > 0 );
		}
	}

	return TRUE; 
}
Exemplo n.º 13
0
BOOL LLImageTGA::encode(const LLImageRaw* raw_image, F32 encode_time)
{
	llassert_always(raw_image);
	
	deleteData();

	setSize(raw_image->getWidth(), raw_image->getHeight(), raw_image->getComponents());

	// Data from header
	mIDLength = 0;		// Length of identifier string
	mColorMapType = 0;	// 0 = No Map

	// Supported: 2 = Uncompressed true color, 3 = uncompressed monochrome without colormap
	switch( getComponents() )
	{
	case 1:
		mImageType = 3;		
		break;
	case 2:	 // Interpret as intensity plus alpha
	case 3:
	case 4:
		mImageType = 2;		
		break;
	default:
		return FALSE;
	}

	// Color map stuff (unsupported)
	mColorMapIndexLo = 0;		// First color map entry (low order byte)
	mColorMapIndexHi = 0;		// First color map entry (high order byte)
	mColorMapLengthLo = 0;		// Color map length (low order byte)
	mColorMapLengthHi = 0;		// Color map length (high order byte)
	mColorMapDepth = 0;	// Size of color map entry (15, 16, 24, or 32 bits)

	// Image offset relative to origin.
	mXOffsetLo = 0;		// X offset from origin (low order byte)
	mXOffsetHi = 0;		// X offset from origin (hi order byte)
	mYOffsetLo = 0;		// Y offset from origin (low order byte)
	mYOffsetHi = 0;		// Y offset from origin (hi order byte)

	// Height and width
	mWidthLo = U8(getWidth() & 0xFF);			// Width (low order byte)
	mWidthHi = U8((getWidth() >> 8) & 0xFF);	// Width (hi order byte)
	mHeightLo = U8(getHeight() & 0xFF);			// Height (low order byte)
	mHeightHi = U8((getHeight() >> 8) & 0xFF);	// Height (hi order byte)

	S32 bytes_per_pixel;
	switch( getComponents() )
	{
	case 1:
		bytes_per_pixel = 1;		
		break;
	case 3:
		bytes_per_pixel = 3;		
		break;
	case 2:	 // Interpret as intensity plus alpha.  Store as RGBA.
	case 4:
		bytes_per_pixel = 4;		
		break;
	default:
		return FALSE;
	}
	mPixelSize = U8(bytes_per_pixel * 8);		// 8, 16, 24, 32 bits per pixel

	mAttributeBits = (4 == bytes_per_pixel) ? 8 : 0;	// 4 bits: number of attribute bits (alpha) per pixel
	mOriginRightBit = 0;	// 1 bit: origin, 0 = left, 1 = right
	mOriginTopBit = 0;	// 1 bit: origin, 0 = bottom, 1 = top
	mInterleave = 0;	// 2 bits: interleaved flag, 0 = none, 1 = interleaved 2, 2 = interleaved 4


	const S32 TGA_HEADER_SIZE = 18;
	const S32 COLOR_MAP_SIZE = 0;
	mDataOffset = TGA_HEADER_SIZE + mIDLength + COLOR_MAP_SIZE; // Offset from start of data to the actual header.

	S32 pixels = getWidth() * getHeight();
	S32 datasize = mDataOffset + bytes_per_pixel * pixels;
	U8* dst = allocateData(datasize);

	// Write header
	*(dst++) = mIDLength;		
	*(dst++) = mColorMapType;	
	*(dst++) = mImageType;		
	*(dst++) = mColorMapIndexLo;		
	*(dst++) = mColorMapIndexHi;		
	*(dst++) = mColorMapLengthLo;		
	*(dst++) = mColorMapLengthHi;		
	*(dst++) = mColorMapDepth;	
	*(dst++) = mXOffsetLo;		
	*(dst++) = mXOffsetHi;		
	*(dst++) = mYOffsetLo;		
	*(dst++) = mYOffsetHi;		
	*(dst++) = mWidthLo;		
	*(dst++) = mWidthHi;		
	*(dst++) = mHeightLo;		
	*(dst++) = mHeightHi;		
	*(dst++) = mPixelSize;		
	*(dst++) =
		((mInterleave & 3) << 5) |
		((mOriginTopBit & 1) << 4) |
		((mOriginRightBit & 1) << 3) |
		((mAttributeBits & 0xF) << 0);	

	// Write pixels
	const U8* src = raw_image->getData();
	llassert( dst == getData() + mDataOffset );
	S32 i = 0;
	S32 j = 0;
	switch( getComponents() )
	{
	case 1:
		memcpy( dst, src, bytes_per_pixel * pixels );	/* Flawfinder: ignore */
		break;

	case 2:
		while( pixels-- )
		{
			dst[i + 0] = src[j + 0];	// intensity
			dst[i + 1] = src[j + 0];	// intensity
			dst[i + 2] = src[j + 0];	// intensity
			dst[i + 3] = src[j + 1];	// alpha
			i += 4;
			j += 2;
		}
		break;

	case 3:
		while( pixels-- )
		{
			dst[i + 0] = src[i + 2];	// blue
			dst[i + 1] = src[i + 1];	// green
			dst[i + 2] = src[i + 0];	// red
			i += 3;
		}
		break;

	case 4:
		while( pixels-- )
		{
			dst[i + 0] = src[i + 2];	// blue
			dst[i + 1] = src[i + 1];	// green
			dst[i + 2] = src[i + 0];	// red
			dst[i + 3] = src[i + 3];	// alpha
			i += 4;
		}
		break;
	}
	
	return TRUE;
}
Exemplo n.º 14
0
BOOL LLImageTGA::decodeColorMap( LLImageRaw* raw_image, BOOL rle, BOOL flipped )
{
	// If flipped, origin is the top left.  Need to reverse the order of the rows.
	// Otherwise the origin is the bottom left.

	if( 8 != mPixelSize )
	{
		return FALSE;
	}

	U8* src = getData() + mDataOffset;
	U8* dst = raw_image->getData();	// start from the top
	
	void (LLImageTGA::*pixel_decoder)( U8*, const U8* );

	switch( mColorMapBytesPerEntry )
	{
		case 1:	pixel_decoder = &LLImageTGA::decodeColorMapPixel8;  break;
		case 2:	pixel_decoder = &LLImageTGA::decodeColorMapPixel15; break;
		case 3:	pixel_decoder = &LLImageTGA::decodeColorMapPixel24; break;
		case 4:	pixel_decoder = &LLImageTGA::decodeColorMapPixel32; break;
		default: llassert(0); return FALSE;
	}

	if( rle )
	{
		U8* last_dst = dst + getComponents() * (getHeight() * getWidth() - 1);
		while( dst <= last_dst )
		{
			// Read RLE block header
			U8 block_header_byte = *src;
			src++;

			U8 block_pixel_count = (block_header_byte & 0x7F) + 1;
			if( block_header_byte & 0x80 )
			{
				// Encoded (duplicate-pixel) block
				do
				{
					(this->*pixel_decoder)( dst, src );
					dst += getComponents();
					block_pixel_count--;
				}
				while( block_pixel_count > 0 );
				src++;
			}
			else 
			{
				// Unencoded block
				do
				{
					(this->*pixel_decoder)( dst, src );
					dst += getComponents();
					src++;
					block_pixel_count--;
				}
				while( block_pixel_count > 0 );
			}
		}

		raw_image->verticalFlip();
	}
	else
	{
		S32 src_row_bytes = getWidth();
		S32 dst_row_bytes = getWidth() * getComponents();

		if( flipped )
		{
			U8* src_last_row_start = src + (getHeight() - 1) * src_row_bytes;
			src = src_last_row_start;		// start from the bottom
			src_row_bytes *= -1;
		}


		S32 i;
		S32 j;

		for( S32 row = 0; row < getHeight(); row++ )
		{
			for( i = 0, j = 0; j < getWidth(); i += getComponents(), j++ )
			{
				(this->*pixel_decoder)( dst + i, src + j );
			}

			dst += dst_row_bytes;
			src += src_row_bytes;
		}
	}

	return TRUE;
}
Exemplo n.º 15
0
	bool TrickHelper::initIterator( CardGroup group , IterData& iterData )
	{
		iterData.condition = -1;

		switch( group )
		{
		case CG_SINGLE:
			if ( initIteratorSingle( iterData.face[0] ) )
			{
				iterData.condition = 0;
				return true;
			}
			break;
		case CG_ONE_PAIR:
			if ( initIteratorOnePair( iterData.face[0] ) )
			{
				iterData.condition = 0;
				return true;
			}
			break;
		case CG_THREE_OF_KIND:
			if ( initIteratorThreeOfKind( iterData.face[0] ) )
			{
				iterData.condition = 0;
				return true;
			}
			break;
		case CG_TWO_PAIR:
			break;
		case CG_STRAIGHT:
			{
				IterStraight& straight = iterData.straight;
				if ( getData( POS_STRAIGHT ).num )
				{
					iterData.condition = 0;
					for( int i = 0 ; i < 5 ; ++i )
						straight.index[i] = 0;
					straight.cur = 4;
					return true;
				}
			}
			break;
		case CG_FLUSH:
			{
				IterFlush& data = iterData.flush;
				if ( getData( POS_FLUSH ).num )
				{
					iterData.condition = 0;
					data.count = 0;
					data.cur = 0;
					int idxGroup = getData( POS_FLUSH ).index[0];
					data.initCombine( mSuitGroup[ idxGroup ].num );
					return true;
				}
			}
			break;
		case CG_FULL_HOUSE:
			if ( initIteratorThreeOfKind( iterData.face[0] ) &&
				 initIteratorOnePair( iterData.face[1] ) )
			{
				iterData.condition = 0;
				if ( iterData.face[1].cur == iterData.face[0].cur + 1 )
				{
					iterData.face[2] = iterData.face[1];
					do 
					{
						if ( !nextIteratorOnePair( iterData.face[1] ) )
							return false;
					} while ( iterData.face[1].cur  == iterData.face[0].cur + 1 );
					iterData.condition = 1;
				}
				return true;
			}
			break;
		case CG_FOUR_OF_KIND:
			{
				if ( !getData( POS_FOUR_OF_KIND ).num )
					return false;

				iterData.face[0].cur   = 0;
				iterData.face[0].count = 0;

				if ( mNumFaceGroup < 2 )
					return false;

				iterData.face[1].cur   = 0;
				iterData.face[1].count = 0;
				if ( iterData.face[1].cur == getData( POS_FOUR_OF_KIND ).index[ 0 ] )
					iterData.face[1].cur = 1;

				iterData.condition = 0;
				return true;
			}
			break;
		case CG_STRAIGHT_FLUSH:
			{
				if ( !getData( POS_STRAIGHT_FLUSH ).num )
					return false;

				iterData.face[0].cur   = 0;
				iterData.face[0].count = 0;

				iterData.condition = 0;
				return true;
			}
		default:
			break;
		}
		return false;
	}
Exemplo n.º 16
0
void LLTemplateMessageReader::getUUID(const char *block, const char *var, 
									  LLUUID &u, S32 blocknum)
{
	getData(block, var, &u.mData[0], sizeof(u.mData), blocknum);
}
Exemplo n.º 17
0
	bool TrickHelper::nextIterator( CardGroup group , IterData& iterData )
	{
		if ( iterData.condition == -1 )
			return false;

		switch( group )
		{
		case CG_SINGLE:        return nextIteratorSingle( iterData.face[0] );
		case CG_ONE_PAIR:      return nextIteratorOnePair( iterData.face[0] );
		case CG_THREE_OF_KIND: return nextIteratorThreeOfKind( iterData.face[0] );

		case CG_STRAIGHT:
			{
				IterStraight& straight = iterData.straight;

				bool needRest = false;

				while ( 1 )
				{
					straight.index[ straight.cur ] += 1;
					int idxGroup = getData( POS_STRAIGHT ).index[ iterData.condition ];
					if ( straight.cur == 4 && mFaceGroups[ idxGroup ].rank == 9 )
					{
						idxGroup = 0;
					}
					else
					{
						idxGroup += straight.cur;
					}

					if (  straight.index[ straight.cur ] < mFaceGroups[ idxGroup ].num )
					{
						if ( needRest )
							straight.cur = 4;
						break;
					}

					straight.cur -= 1;
					if ( straight.cur == -1 )
					{
						iterData.condition += 1;
						if(  iterData.condition < getData( POS_STRAIGHT ).num )
						{
							for( int i = 0 ; i < 4 ; ++i )
								straight.index[i] = 0;
							straight.cur = 4;
							return true;
						}
						else
						{
							iterData.condition = -1;
							return false;
						}
					}
					else
					{
						for ( int i = 4; i > straight.cur ; --i )
						{
							straight.index[i] = 0;
						}
						needRest = true;
					}
				}
				return true;
			}
			break;
		case CG_FLUSH:
			{
				IterFlush& data = iterData.flush;
				if ( data.count < mDataGroups[ CG_FLUSH ].num )
				{
					int idxGroup = mDataGroups[POS_FLUSH].index[ data.count ];
					if ( data.nextCombine( mSuitGroup[ idxGroup ].num , 5 ) )
						return true;
					data.initCombine( mSuitGroup[ idxGroup ].num );
					data.count += 1;
				}
				if ( data.count >= mDataGroups[ CG_FLUSH ].num )
				{
					data.cur = -1;
					return false;
				}
				return true;
			}
			break;

		case CG_FULL_HOUSE:
			{
				if ( iterData.condition == 1 )
				{
					iterData.face[1] = iterData.face[2];
					iterData.condition = 0;
				}

				if( !nextIteratorThreeOfKind( iterData.face[0] ) )
				{
					if ( !nextIteratorOnePair( iterData.face[1] ) )
					{
						iterData.condition = -1;
						return false;
					}
					else
					{
						initIteratorThreeOfKind( iterData.face[0] );
					}
				}

				if ( iterData.face[1].cur == iterData.face[0].cur + 1 &&
					iterData.face[0].count == iterData.face[1].count )
				{
					iterData.face[2] = iterData.face[1];
					do
					{
						if ( !nextIteratorOnePair( iterData.face[1] ) )
						{
							iterData.condition = -1;
							return false;
						}
					}
					while( iterData.face[1].cur == iterData.face[0].cur + 1 &&
						  iterData.face[0].count == iterData.face[1].count );

					if ( getData( POS_THREE_OF_KIND ).num > 1 )
						iterData.condition = 1;
				}
				return true;
			}
			break;
		case CG_FOUR_OF_KIND:
			{
				if ( iterData.condition == 1 )
				{
					iterData.face[1] = iterData.face[2];
					iterData.condition = 0;
				}

				iterData.face[0].count += 1;
				if ( iterData.face[0].count >= getData( POS_FOUR_OF_KIND ).num )
				{
					if ( !nextIteratorSingle( iterData.face[1] ) )
					{
						iterData.condition = -1;
						return false;
					}
					else
					{
						iterData.face[0].cur   = 0;
						iterData.face[0].count = 0;
					}
				}

				if ( getData( POS_FOUR_OF_KIND ).index[ iterData.face[0].count ] == iterData.face[1].cur )
				{
					iterData.face[2] = iterData.face[1];
					do
					{
						if ( !nextIteratorSingle( iterData.face[1] ) )
						{
							iterData.condition = -1;
							return false;
						}
					}
					while( getData( POS_FOUR_OF_KIND ).index[ iterData.face[0].count ] ==  iterData.face[1].cur );

					if ( getData( POS_FOUR_OF_KIND ).num > 1 )
						iterData.condition = 1;
				}
				return true;
			}
			break;
		case CG_STRAIGHT_FLUSH:
			{
				IterFace& data = iterData.face[0];
				data.count += 1;
				if ( data.count < mDataGroups[ CG_STRAIGHT_FLUSH ].num )
					return true;

				iterData.condition = -1;
				return false;
			}
			break;
		}
		return false;
	}
Exemplo n.º 18
0
inline void LLTemplateMessageReader::getIPAddr(const char *block, const char *var, U32 &u, S32 blocknum)
{
	getData(block, var, &u, sizeof(U32), blocknum);
}
Exemplo n.º 19
0
int main(void) {
	SYS_Init(); // Init Atmel Lightweight Mesh stack

	SYS_TaskHandler(); // Call the system task handler once before we configure the radio
	NWK_SetAddr(eeprom_read_word((uint16_t*)0));
	NWK_SetPanId(0); // Default PAN ID will be 0, can be changed using the set PAN command
	PHY_SetChannel(APP_CHANNEL);
	//NWK_SetSecurityKey(APP_SECURITY_KEY);
	PHY_SetRxState(true);
	NWK_OpenEndpoint(APP_ENDPOINT, rfReceivePacket);
	PHY_SetTxPower(0);

	// Seed the pseudorandom number generator
	srand(eeprom_read_word((uint16_t*)0));

	// Read eeprom data
	eeprom_read_block(&deviceCalibration, (void*)8, sizeof(deviceCalibration));
	if (eeprom_read_byte((uint8_t*)26)) { // There is valid data in the network information struct
		eeprom_read_block(baseStationList, (void*)27, sizeof(struct baseStation));
		uint8_t ch = 17;
		while ((baseStationList[0].name[ch] == ' ') || (baseStationList[0].name[ch] == '\0') || (baseStationList[0].name[ch] == 0xFF)) {
			baseStationList[0].name[ch] = ' ';
			ch -= 1;
		}
		baseStationList[0].nameLen = ch+1;
		baseStationListLength += 1;

		for (int cnt = 0; cnt < BASESTATION_LIST_SIZE; cnt++) {
			baseStationList[cnt].name[16] = ' ';
			baseStationList[cnt].name[17] = ' ';
		}
		sendConnectionRequest(0, &deviceCalibration);
	}	

	initDataAck();
	initLCD(display_cmd_buffer, 64);
	initUI();

	TCCR0B |= (1<<CS01);
	TCCR3B |= (1<<CS32) | (1<<CS30);

	sei();
	startDataAck();

	while (1) {
		SYS_TaskHandler();

		if (receivedDataRequest) {
			handleDataRequest();
			receivedDataRequest = false;
		}

		if (receivedColdStart) {
			if (connectedBaseStation == -1)
				sendConnectionRequest(0, &deviceCalibration);
			else
				sendConnectionRequest(connectedBaseStation, &deviceCalibration);
			ui_baseStationDisconnected();
			receivedColdStart = false;
		}

		updateUI();

		if (sampleCount > 40000) {
			if (dataPacket.sampleCount != 0)
				removeSamples(&dataPacket); // If the last transmitted data has not been acked then first remove the old data.
			getData(&dataPacket); // Sample new data
			ui_updatePowerValues(&dataPacket); // Update display
			removeSamples(&dataPacket); // Get rid of these samples now
		}
		
		if (TCNT0 > 80) {
			serviceLCD();
			TCNT0 = 0;
		}

		TCCR3B &= ~((1<<CS32) | (1<<CS30));
		if (TCNT3 != 0) {
			for (uint8_t cnt = 0; cnt < DATA_REQ_BUFFER_CNT; cnt++) {
				if (dataReqBusy[cnt] && (retransmit_time[cnt] != 0)) {
					if (retransmit_time[cnt] <= TCNT3) {
						NWK_DataReq(&(nwkPacket[cnt]));
						retransmit_time[cnt] = 0;
					}
					else
						retransmit_time[cnt] -= TCNT3;
				}
			}
		}
		TCNT3 = 0;
		TCCR3B |= (1<<CS32) | (1<<CS30);
	}
}
Exemplo n.º 20
0
inline void LLTemplateMessageReader::getIPPort(const char *block, const char *var, U16 &u, S32 blocknum)
{
	getData(block, var, &u, sizeof(U16), blocknum);
	u = ntohs(u);
}
Exemplo n.º 21
0
const char *getStringP(uint32 offset) {
	return offset != 0 ? (const char*)getData(offset) : NULL;
}
Exemplo n.º 22
0
inline void LLTemplateMessageReader::getString(const char *block, const char *var, S32 buffer_size, char *s, S32 blocknum )
{
	s[0] = '\0';
	getData(block, var, s, 0, blocknum, buffer_size);
	s[buffer_size - 1] = '\0';
}
Exemplo n.º 23
0
MemoryBlock MemoryOutputStream::getMemoryBlock() const
{
    return MemoryBlock (getData(), getDataSize());
}
Exemplo n.º 24
0
int main(int argc, char** argv)
{
   FileEntry fe;
   int len;
   int i;
   uchar authSecret[47];
   int authlen = 21;
   uchar signSecret[11] = {(uchar)'s',(uchar)'i',(uchar)'g',(uchar)'n',
                           (uchar)' ',(uchar)'s',(uchar)'e',(uchar)'c',
                           (uchar)'r',(uchar)'e',(uchar)'t'};
   int signlen = 11;
   int ischars;


   SHACopr copr;
   SHAUser user;

   //could be different ports.
   copr.portnum = 0;
   user.portnum = 0;

   // check for required port name
   if (argc != 2)
   {
      printf("1-Wire Net name required on command line!\n"
             " (example: \"COM1\" (Win32 DS2480),\"/dev/cua0\" "
             "(Linux DS2480),\"{1,5}\" (Win32 TMEX)\n");
      exit(1);
   }

   if((copr.portnum = owAcquireEx(argv[1])) < 0)
   {
      printf("Failed to acquire port.\n");
      exit(1);
   }

   user.portnum = copr.portnum;

   // MANUALLY SETTING DATA FOR COPROCESSOR
   memcpy(copr.serviceFilename, "DLSM", 4);
   copr.serviceFilename[4] = (uchar) 102;
   copr.signPageNumber     = (uchar) 8;
   copr.authPageNumber     = (uchar) 7;
   copr.wspcPageNumber     = (uchar) 9;
   copr.versionNumber      = (uchar) 1;
   memcpy(copr.bindCode, "bindcde", 7);
   for(i=0;i<8;i++)
   {
      memcpy(&copr.bindData[i*4], "bind", 4);
   }
   copr.encCode           = 0x01;
   copr.ds1961Scompatible = 0x01;

   // Prompt for password
   printf("Enter up to 47 bytes of the Authentication Secret.\n");
   printf("  Data Entry Mode\n");
   printf("  (0) Text (single line)\n");
   printf("  (1) Hex (XX XX XX XX ...)\n");
   len = getData(authSecret,47,getNumber(0,1));
   // padd the data with spaces or 0's depending on type
   if(len < 47)
   {
      for(i = len; i < 47; i++)
         authSecret[i] = 0x00;
   }

   ReformatSecretFor1961S(authSecret, authlen);
   copr.ds1961Scompatible = 0x55;
   InstallAuthSecretVM(&copr, authSecret, authlen);
   InstallSignSecretVM(&copr, signSecret, signlen);

   puts("\nStarting SHA Software Authentication\n");
   puts("\nPlease place token on the 1-Wire bus.\n");

   memcpy(fe.Name, "DLSM", 4);
   fe.Ext = 102;

   for(;;)
   {
      if(FindUserSA(&user,&fe,FALSE))
      {
         if(VerifyUser(&copr, &user, TRUE))
         {
            PrintSerialNum(&user.devAN[0]);
            printf(", user data = ");
            // print the user data
            ischars = TRUE;
            for(i=0;i<7;i++)
            {
               if ((user.accountFile[i+22] < 0x20) ||
                   (user.accountFile[i+22] > 0x7E))
                   ischars = FALSE;
            }
            for(i=0;i<7;i++)
            {
               if (ischars)
                  printf("%c", user.accountFile[i+22]);
               else
                  printf("%02X ", user.accountFile[i+22]);
            }
            printf(", VALID\n");
            FindNewSHA(user.portnum, &user.devAN[0], TRUE);
         }
         else
         {
            PrintSerialNum(&user.devAN[0]);
            printf(", invalid\n");
            FindNewSHA(user.portnum, &user.devAN[0], TRUE);
         }
      }
      else
      {
         printf("NO DEVICE, invalid\n");
         FindNewSHA(user.portnum, &user.devAN[0], TRUE);
      }
   }

   owRelease(copr.portnum);

   return TRUE;
}
Exemplo n.º 25
0
String MemoryOutputStream::toString() const
{
    return String::createStringFromData (getData(), (int) getDataSize());
}
Exemplo n.º 26
0
BOOL LLImageBMP::updateData()
{
	resetLastError();

	// Check to make sure that this instance has been initialized with data
	U8* mdata = getData();
	if (!mdata || (0 == getDataSize()))
	{
		setLastError("Uninitialized instance of LLImageBMP");
		return FALSE;
	}

	// Read the bitmap headers in order to get all the useful info
	// about this image

	////////////////////////////////////////////////////////////////////
	// Part 1: "File Header"
	// 14 bytes consisting of
	// 2 bytes: either BM or BA
	// 4 bytes: file size in bytes
	// 4 bytes: reserved (always 0)
	// 4 bytes: bitmap offset (starting position of image data in bytes)
	const S32 FILE_HEADER_SIZE = 14;
	if ((mdata[0] != 'B') || (mdata[1] != 'M'))
    {
		if ((mdata[0] != 'B') || (mdata[1] != 'A'))
		{
			setLastError("OS/2 bitmap array BMP files are not supported");
			return FALSE;
		}
		else
		{
			setLastError("Does not appear to be a bitmap file");
			return FALSE;
		}
	}

	mBitmapOffset = mdata[13];
	mBitmapOffset <<= 8; mBitmapOffset += mdata[12];
	mBitmapOffset <<= 8; mBitmapOffset += mdata[11];
	mBitmapOffset <<= 8; mBitmapOffset += mdata[10];


	////////////////////////////////////////////////////////////////////
	// Part 2: "Bitmap Header"
	const S32 BITMAP_HEADER_SIZE = 40;
	LLBMPHeader header;
	llassert( sizeof( header ) == BITMAP_HEADER_SIZE );

	memcpy(	/* Flawfinder: ignore */
		(void*)&header,
		mdata + FILE_HEADER_SIZE,
		BITMAP_HEADER_SIZE);

	// convert BMP header from little endian (no-op on little endian builds)
	llendianswizzleone(header.mSize);
	llendianswizzleone(header.mWidth);
	llendianswizzleone(header.mHeight);
	llendianswizzleone(header.mPlanes);
	llendianswizzleone(header.mBitsPerPixel);
	llendianswizzleone(header.mCompression);
	llendianswizzleone(header.mAlignmentPadding);
	llendianswizzleone(header.mImageSize);
	llendianswizzleone(header.mHorzPelsPerMeter);
	llendianswizzleone(header.mVertPelsPerMeter);
	llendianswizzleone(header.mNumColors);
	llendianswizzleone(header.mNumColorsImportant);

	BOOL windows_nt_version = FALSE;
	BOOL windows_95_version = FALSE;
	if( 12 == header.mSize )
	{
		setLastError("Windows 2.x and OS/2 1.x BMP files are not supported");
		return FALSE;
	}
	else
	if( 40 == header.mSize )
	{
		if( 3 == header.mCompression )
		{
			// Windows NT
			windows_nt_version = TRUE;
		}
		else
		{
			// Windows 3.x
		}
	}
	else
	if( 12 <= header.mSize && 64 <= header.mSize )
	{
		setLastError("OS/2 2.x BMP files are not supported");
		return FALSE;
	}
	else
	if( 108 == header.mSize )
	{
		// BITMAPV4HEADER
		windows_95_version = TRUE;
	}
	else
	if( 108 < header.mSize )
	{
		// BITMAPV5HEADER or greater
		// Should work as long at Microsoft maintained backwards compatibility (which they did in V4 and V5)
		windows_95_version = TRUE;
	}

	S32 width = header.mWidth;
	S32 height = header.mHeight;
	if (height < 0)
	{
		mOriginAtTop = TRUE;
		height = -height;
	}
	else
	{
		mOriginAtTop = FALSE;
	}

	mBitsPerPixel = header.mBitsPerPixel;
	S32 components;
	switch( mBitsPerPixel )
	{
	case 8:
		components = 1;
		break;
	case 24:
	case 32:
		components = 3;
		break;
	case 1:
	case 4:
	case 16: // Started work on 16, but doesn't work yet
		// These are legal, but we don't support them yet.
		setLastError("Unsupported bit depth");
		return FALSE;
	default:
		setLastError("Unrecognized bit depth");
		return FALSE;
	}

	setSize(width, height, components);
	
	switch( header.mCompression )
	{
	case 0:
		// Uncompressed
		break;

	case 1:
		setLastError("8 bit RLE compression not supported.");
		return FALSE;

	case 2: 
		setLastError("4 bit RLE compression not supported.");
		return FALSE;

	case 3:
		// Windows NT or Windows 95
		break;

	default:
		setLastError("Unsupported compression format.");
		return FALSE;
	}

	////////////////////////////////////////////////////////////////////
	// Part 3: Bitfield Masks and other color data
	S32 extension_size = 0;
	if( windows_nt_version )
	{
		if( (16 != header.mBitsPerPixel) && (32 != header.mBitsPerPixel) )
		{
			setLastError("Bitfield encoding requires 16 or 32 bits per pixel.");
			return FALSE;
		}

		if( 0 != header.mNumColors )
		{
			setLastError("Bitfield encoding is not compatible with a color table.");
			return FALSE;
		}

		
		extension_size = 4 * 3;
		memcpy( mBitfieldMask, mdata + FILE_HEADER_SIZE + BITMAP_HEADER_SIZE, extension_size);	/* Flawfinder: ignore */
	}
	else
	if( windows_95_version )
	{
		Win95BmpHeaderExtension win_95_extension;
		extension_size = sizeof( win_95_extension );

		llassert( sizeof( win_95_extension ) + BITMAP_HEADER_SIZE == 108 );
		memcpy( &win_95_extension, mdata + FILE_HEADER_SIZE + BITMAP_HEADER_SIZE, sizeof( win_95_extension ) );	/* Flawfinder: ignore */

		if( 3 == header.mCompression )
		{
			memcpy( mBitfieldMask, mdata + FILE_HEADER_SIZE + BITMAP_HEADER_SIZE, 4 * 4);	/* Flawfinder: ignore */
		}

		// Color correction ignored for now
	}
	

	////////////////////////////////////////////////////////////////////
	// Part 4: Color Palette (optional)
	// Note: There's no color palette if there are 16 or more bits per pixel
	S32 color_palette_size = 0;
	mColorPaletteColors = 0;
	if( header.mBitsPerPixel < 16 )
	{
		if( 0 == header.mNumColors )
		{
			mColorPaletteColors = (1 << header.mBitsPerPixel);
		}
		else
		{
			mColorPaletteColors = header.mNumColors;
		}
	}
	color_palette_size = mColorPaletteColors * 4;

	if( 0 != mColorPaletteColors )
	{
		mColorPalette = new U8[color_palette_size];
		if (!mColorPalette)
		{
			llerrs << "Out of memory in LLImageBMP::updateData()" << llendl;
			return FALSE;
		}
		memcpy( mColorPalette, mdata + FILE_HEADER_SIZE + BITMAP_HEADER_SIZE + extension_size, color_palette_size );	/* Flawfinder: ignore */
	}

	return TRUE;
}
Exemplo n.º 27
0
int Assets::getPlayerPosition(int i){
    return getData("player_" + ofToString(i))["position"].asInt();
}
Exemplo n.º 28
0
BOOL LLImageBMP::encode(const LLImageRaw* raw_image, F32 encode_time)
{
	llassert_always(raw_image);
	
	resetLastError();

	S32 src_components = raw_image->getComponents();
	S32 dst_components =  ( src_components < 3 ) ? 1 : 3;

	if( (2 == src_components) || (4 == src_components) )
	{
		llinfos << "Dropping alpha information during BMP encoding" << llendl;
	}

	setSize(raw_image->getWidth(), raw_image->getHeight(), dst_components);
	
	U8 magic[14];
	LLBMPHeader header;
	int header_bytes = 14+sizeof(header);
	llassert(header_bytes == 54);
	if (getComponents() == 1)
	{
		header_bytes += 1024; // Need colour LUT.
	}
	int line_bytes = getComponents() * getWidth();
	int alignment_bytes = (3 * line_bytes) % 4;
	line_bytes += alignment_bytes;
	int file_bytes = line_bytes*getHeight() + header_bytes;

	// Allocate the new buffer for the data.
	if(!allocateData(file_bytes)) //memory allocation failed
	{
		return FALSE ;
	}

	magic[0] = 'B'; magic[1] = 'M';
	magic[2] = (U8) file_bytes;
	magic[3] = (U8)(file_bytes>>8);
	magic[4] = (U8)(file_bytes>>16);
	magic[5] = (U8)(file_bytes>>24);
	magic[6] = magic[7] = magic[8] = magic[9] = 0;
	magic[10] = (U8) header_bytes;
	magic[11] = (U8)(header_bytes>>8);
	magic[12] = (U8)(header_bytes>>16);
	magic[13] = (U8)(header_bytes>>24);
	header.mSize = 40;
	header.mWidth = getWidth();
	header.mHeight = getHeight();
	header.mPlanes = 1;
	header.mBitsPerPixel = (getComponents()==1)?8:24;
	header.mCompression = 0;
	header.mAlignmentPadding = 0;
	header.mImageSize = 0;
#if LL_DARWIN
	header.mHorzPelsPerMeter = header.mVertPelsPerMeter = 2834;	// 72dpi
#else
	header.mHorzPelsPerMeter = header.mVertPelsPerMeter = 0;
#endif
	header.mNumColors = header.mNumColorsImportant = 0;

	// convert BMP header to little endian (no-op on little endian builds)
	llendianswizzleone(header.mSize);
	llendianswizzleone(header.mWidth);
	llendianswizzleone(header.mHeight);
	llendianswizzleone(header.mPlanes);
	llendianswizzleone(header.mBitsPerPixel);
	llendianswizzleone(header.mCompression);
	llendianswizzleone(header.mAlignmentPadding);
	llendianswizzleone(header.mImageSize);
	llendianswizzleone(header.mHorzPelsPerMeter);
	llendianswizzleone(header.mVertPelsPerMeter);
	llendianswizzleone(header.mNumColors);
	llendianswizzleone(header.mNumColorsImportant);

	U8* mdata = getData();
	
	// Output magic, then header, then the palette table, then the data.
	U32 cur_pos = 0;
	memcpy(mdata, magic, 14);
	cur_pos += 14;
	memcpy(mdata+cur_pos, &header, 40);	/* Flawfinder: ignore */
	cur_pos += 40;
	if (getComponents() == 1)
	{
		S32 n;
		for (n=0; n < 256; n++)
		{
			mdata[cur_pos++] = (U8)n;
			mdata[cur_pos++] = (U8)n;
			mdata[cur_pos++] = (U8)n;
			mdata[cur_pos++] = 0;
		}
	}
	
	// Need to iterate through, because we need to flip the RGB.
	const U8* src = raw_image->getData();
	U8* dst = mdata + cur_pos;

	for( S32 row = 0; row < getHeight(); row++ )
	{
		for( S32 col = 0; col < getWidth(); col++ )
		{
			switch( src_components )
			{
			case 1:
				*dst++ = *src++;
				break;
			case 2:
				{
					U32 lum = src[0];
					U32 alpha = src[1];
					*dst++ = (U8)(lum * alpha / 255);
					src += 2;
					break;
				}
			case 3:
			case 4:
				dst[0] = src[2];
				dst[1] = src[1];
				dst[2] = src[0];
				src += src_components;
				dst += 3;
				break;
			}

		}
		for( S32 i = 0; i < alignment_bytes; i++ )
		{
			*dst++ = 0;
		}
	}

	return TRUE;
}
Exemplo n.º 29
0
int Assets::getNumLaps(){
    return getData("num_laps").asInt();
}
Exemplo n.º 30
0
// Decoded and process the image for use in avatar gradient masks.
// Processing happens during the decode for speed.
BOOL LLImageTGA::decodeAndProcess( LLImageRaw* raw_image, F32 domain, F32 weight )
{
	llassert_always(raw_image);
	
	// "Domain" isn't really the right word.  It refers to the width of the 
	// ramp portion of the function that relates input and output pixel values.
	// A domain of 0 gives a step function.
	// 
	//   |                      /----------------
	//  O|                     / |
	//  u|                    /  |
	//  t|                   /   |
	//	p|------------------/    |
	//  u|                  |    | 
	//  t|<---------------->|<-->|
	//	 |  "offset"         "domain"
	//   |
	// --+---Input--------------------------------
	//   |

	if (!getData() || (0 == getDataSize()))
	{
		setLastError("LLImageTGA trying to decode an image with no data!");
		return FALSE;
	}

	// Only works for unflipped monochrome RLE images
	if( (getComponents() != 1) || (mImageType != 11) || mOriginTopBit || mOriginRightBit ) 
	{
		llerrs << "LLImageTGA trying to alpha-gradient process an image that's not a standard RLE, one component image" << llendl;
		return FALSE;
	}

	raw_image->resize(getWidth(), getHeight(), getComponents());

	U8* dst = raw_image->getData();
	U8* src = getData() + mDataOffset;
	U8* last_dst = dst + getHeight() * getWidth() - 1;

	if( domain > 0 )
	{
		// Process using a look-up table (lut)
		const S32 LUT_LEN = 256;
		U8 lut[LUT_LEN];
		S32 i;

		F32 scale = 1.f / domain;
		F32 offset = (1.f - domain) * llclampf( 1.f - weight );
		F32 bias = -(scale * offset);
		
		for( i = 0; i < LUT_LEN; i++ )
		{
			lut[i] = (U8)llclampb( 255.f * ( i/255.f * scale + bias ) );
		}

		while( dst <= last_dst )
		{
			// Read RLE block header
			U8 block_header_byte = *src;
			src++;

			U8 block_pixel_count = (block_header_byte & 0x7F) + 1;
			if( block_header_byte & 0x80 )
			{
				// Encoded (duplicate-pixel) block
				memset( dst, lut[ *src ], block_pixel_count );
				dst += block_pixel_count;
				src++;
			}
			else 
			{
				// Unencoded block
				do
				{
					*dst = lut[ *src ];
					dst++;
					src++;
					block_pixel_count--;
				}
				while( block_pixel_count > 0 );
			}
		}
	}
	else
	{
		// Process using a simple comparison agains a threshold
		const U8 threshold = (U8)(0xFF * llclampf( 1.f - weight ));

		while( dst <= last_dst )
		{
			// Read RLE block header
			U8 block_header_byte = *src;
			src++;

			U8 block_pixel_count = (block_header_byte & 0x7F) + 1;
			if( block_header_byte & 0x80 )
			{
				// Encoded (duplicate-pixel) block
				memset( dst, ((*src >= threshold) ? 0xFF : 0), block_pixel_count );
				dst += block_pixel_count;
				src++;
			}
			else 
			{
				// Unencoded block
				do
				{
					*dst = (*src >= threshold) ? 0xFF : 0;
					dst++;
					src++;
					block_pixel_count--;
				}
				while( block_pixel_count > 0 );
			}
		}
	}
	return TRUE;
}