Ejemplo n.º 1
0
static size_t widthOfUTF8String(const String & s)
{
	size_t res = 0;
	for (auto c : s)	/// Skip UTF-8 continuation bytes.
		res += (UInt8(c) <= 0x7F || UInt8(c) >= 0xC0);
	return res;
}
Ejemplo n.º 2
0
void writeBitsImpl(DataType value, int bitCount,
    StreamBuffer& streamBuffer, int& holdingBitCount, int& totalBitCount)
{
    assert(isEnoughBits<DataType>(bitCount));

    if (! isEnoughBits<DataType>(bitCount)) {
        throw StreamingException(__FILE__, __LINE__, "invalid bitCount");
    }

    DataType theValue = resetUnusedBits(value, bitCount);
    if (holdingBitCount > 0) {
        if (streamBuffer.empty()) {
            throw StreamingException(__FILE__, __LINE__, "buffer is empty");
        }
        streamBuffer.back() |= UInt8(theValue << holdingBitCount);
    }
    else {
        streamBuffer.push(UInt8(theValue));
    }

    const int bitShiftCount = CHAR_BIT - holdingBitCount;
    if (bitCount > bitShiftCount) {
        int leftBitCount = bitCount - bitShiftCount;
        theValue >>= bitShiftCount;
        do {
            streamBuffer.push(UInt8(theValue));
            theValue >>= CHAR_BIT;
            leftBitCount -= CHAR_BIT;
        }
        while (leftBitCount > 0);
    }
MouseWheelEventDetailsBase::MouseWheelEventDetailsBase(void) :
    Inherited(),
    _sfScrollType             (UInt8(MouseWheelEventDetails::UNIT_SCROLL)),
    _sfScrollOrientation      (UInt8(MouseWheelEventDetails::SCROLL_ORIENTATION_VERTICAL)),
    _sfWheelRotation          (Int32(0)),
    _sfLocation               (Pnt2f(0.0f,0.0f)),
    _sfViewport               (NULL)
{
}
Ejemplo n.º 4
0
void runTests(bool write,BinaryDataHandler &pMem)
{
    runTest  (write,pMem, std::string("Hallo") );
    runTest1 (write,pMem, Time(222.22) );
    runTest  (write,pMem, Color3f(1.1,2.2,3.3) );
    runTest  (write,pMem, Color4f(1.1,2.2,3.3,4.4) );
    runTest  (write,pMem, Color3ub(1,2,3) );
    runTest  (write,pMem, Color4ub(1,2,3,4) );
    runTest  (write,pMem, DynamicVolume(DynamicVolume::BOX_VOLUME) );
    runTest  (write,pMem, DynamicVolume(DynamicVolume::SPHERE_VOLUME) );
    runTest1 (write,pMem, BitVector(0xabcd) );
    runTest  (write,pMem, Plane(Vec3f(1.0,0),0.222) );
    runTest  (write,pMem, Matrix(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) );
    runTest  (write,pMem, Quaternion(Vec3f(1,2,3),22) );
    runTest2<bool>(write,pMem, true );
    runTest  (write,pMem, Int8(-22) );
    runTest  (write,pMem, UInt8(11) );
    runTest  (write,pMem, Int16(-10233) );
    runTest  (write,pMem, UInt16(20233) );
    runTest  (write,pMem, Int32(-222320233) );
    runTest  (write,pMem, UInt32(522320233) );
    runTest<Int64>  (write,pMem, Int64(-522323334) );
    runTest  (write,pMem, UInt64(44523423) );
    runTest  (write,pMem, Real32(22.333224) );
    runTest  (write,pMem, Real64(52.334534533224) );
    runTest  (write,pMem, Vec2f(1.1,2.2) );
    runTest  (write,pMem, Vec3f(1.1,2.2,3.3) );
    runTest  (write,pMem, Vec4f(1.1,2.2,3.3,4.4) );
    runTest  (write,pMem, Pnt2f(1.1,2.2) );
    runTest  (write,pMem, Pnt2d(1.1,2.2) );
    runTest  (write,pMem, Pnt3f(1.1,2.2,3.3) );
    runTest  (write,pMem, Pnt3d(1.1,2.2,3.3) );
    runTest  (write,pMem, Pnt4f(1.1,2.2,3.3,4.4) );
    runTest  (write,pMem, Pnt4d(1.1,2.2,3.3,4.4) );
}
Ejemplo n.º 5
0
//---------------------------------------------------------------------------
void __fastcall TFrDeviceExplorer::btnWriteClick(TObject *Sender)
{
	TBluetoothLEDevice * ADevice = NULL;
	ADevice = GetCurrentDevice();
	if(ADevice != NULL) {
		TBluetoothGattService * AService = ADevice->Services->Items[CurrentService];
		TBluetoothGattCharacteristic * AChar = AService->Characteristics->Items[CurrentCharacteristic];
		if((AChar->Properties.Contains(TBluetoothProperty::Write)) || (AChar->Properties.Contains(TBluetoothProperty::WriteNoResponse))
			|| (AChar->Properties.Contains(TBluetoothProperty::SignedWrite)))
		{
			if(CbWriteTypes->ItemIndex ==  0) AChar->SetValueAsString(EdCharacWrite->Text);
			if(CbWriteTypes->ItemIndex ==  1) AChar->SetValueAsString(EdCharacWrite->Text, false);
			if(CbWriteTypes->ItemIndex ==  2) AChar->SetValueAsUInt8(UInt8(StrToInt(EdCharacWrite->Text)));
			if(CbWriteTypes->ItemIndex ==  3) AChar->SetValueAsUInt16(UInt16(StrToInt(EdCharacWrite->Text)));
			if(CbWriteTypes->ItemIndex ==  4) AChar->SetValueAsUInt32(UInt32(StrToInt(EdCharacWrite->Text)));
			if(CbWriteTypes->ItemIndex ==  5) AChar->SetValueAsUInt64(StrToInt(EdCharacWrite->Text));
			if(CbWriteTypes->ItemIndex ==  6) AChar->SetValueAsInt8(Int8(StrToInt(EdCharacWrite->Text)));
			if(CbWriteTypes->ItemIndex ==  7) AChar->SetValueAsInt16(Int16(StrToInt(EdCharacWrite->Text)));
			if(CbWriteTypes->ItemIndex ==  8) AChar->SetValueAsInt32(Int32(StrToInt(EdCharacWrite->Text)));
			if(CbWriteTypes->ItemIndex ==  9) AChar->SetValueAsInt64(StrToInt(EdCharacWrite->Text));
			if(CbWriteTypes->ItemIndex == 10) AChar->SetValueAsDouble(StrToFloat(EdCharacWrite->Text));
			if(CbWriteTypes->ItemIndex == 11) AChar->SetValueAsSingle(StrToFloat(EdCharacWrite->Text));
			ADevice->WriteCharacteristic(AChar);
		}
		else {
			ShowMessage("This characteristic doesn''t allow Write");
        }
	}
	else {
		ShowMessage(EdCurrentDevice->Text + " is not available");
	}
}
SearchWindowEventDetailsBase::SearchWindowEventDetailsBase(void) :
    Inherited(),
    _sfOption                 (UInt8(SearchWindowEventDetails::DIALOG_OPTION_SEARCH)),
    _sfSearchText             (),
    _sfReplaceText            ()
{
}
void registerCodecDelta(CompressionCodecFactory & factory)
{
    UInt8 method_code = UInt8(CompressionMethodByte::Delta);
    factory.registerCompressionCodecWithType("Delta", method_code, [&](const ASTPtr & arguments, DataTypePtr column_type) -> CompressionCodecPtr
    {
        UInt8 delta_bytes_size = 1;
        if (column_type && column_type->haveMaximumSizeOfValue())
        {
            size_t max_size = column_type->getSizeOfValueInMemory();
            if (max_size == 1 || max_size == 2 || max_size == 4 || max_size == 8)
                delta_bytes_size = static_cast<UInt8>(max_size);
        }

        if (arguments && !arguments->children.empty())
        {
            if (arguments->children.size() > 1)
                throw Exception("Delta codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE);

            const auto children = arguments->children;
            const ASTLiteral * literal = static_cast<const ASTLiteral *>(children[0].get());
            size_t user_bytes_size = literal->value.safeGet<UInt64>();
            if (user_bytes_size != 1 && user_bytes_size != 2 && user_bytes_size != 4 && user_bytes_size != 8)
                throw Exception("Delta value for delta codec can be 1, 2, 4 or 8, given " + toString(user_bytes_size), ErrorCodes::ILLEGAL_CODEC_PARAMETER);
            delta_bytes_size = static_cast<UInt8>(user_bytes_size);
        }
        return std::make_shared<CompressionCodecDelta>(delta_bytes_size);
    });
}
SimpleStatisticsForegroundBase::SimpleStatisticsForegroundBase(void) :
    Inherited(),
    _mfFormats                (),
    _sfSize                   (Real32(16)),
    _sfColor                  (Color4f(1,1,1,1)),
    _sfShadowColor            (Color4f(0,0,0,1)),
    _sfBgColor                (Color4f(0,0,0,0)),
    _sfFamily                 (),
    _sfShadowOffset           (Vec2f(1,-1)),
    _sfHorizontalAlign        (UInt8(0)),
    _sfVerticalAlign          (UInt8(0)),
    _sfBorderColor            (Color4f(0,0,0,0)),
    _sfBorderOffset           (Vec2f(4,4)),
    _sfTextMargin             (Vec2f(0,0))
{
}
Ejemplo n.º 9
0
QVariant UInt8Codec::value( const PODData& data, int* byteCount ) const
{
    const quint8* pointer = (quint8*)data.pointer( 1 );

    *byteCount = pointer ? 1 : 0;
    return pointer ? QVariant::fromValue<UInt8>( UInt8(*pointer) ) : QVariant();
}
Ejemplo n.º 10
0
Persistent::Base::Error SimMovingShape::write(StreamIO &s, int ver, int b)
{
	s.write(SimMovingShape::version());
	Parent::write(s,ver,b);

	// Attributes
	s.write(objectMask);
	s.write(sizeof(record.flags),&record.flags);
	s.write(record.timeScale);
	s.write(record.forwardDelay);
	s.write(record.backwardDelay);
	s.write(record.startSoundId);
	s.write(record.stopSoundId);
	s.write(record.runningSoundId);
	s.write(record.collisionMask);
	s.write(record.collisionDamage);

	// Current state
	s.write(UInt8(state));
	s.write(time);
	s.write(wayPoint);
	if (state == Forward || state == Backward) {
		s.write(sizeof(lPosition),&lPosition);
		s.write(sizeof(lVector),&lVector);
		s.write(sizeof(aPosition),&aPosition);
		s.write(sizeof(aVector),&aVector);
	}
	return (s.getStatus() == STRM_OK)? Ok: WriteError;
}
DialogWindowEventDetailsBase::DialogWindowEventDetailsBase(void) :
    Inherited(),
    _sfOption                 (UInt8(DialogWindowEventDetails::DIALOG_OPTION_OK)),
    _sfInput                  (),
    _sfInputIndex             (UInt32(0))
{
}
ConditionalParticleAffectorBase::ConditionalParticleAffectorBase(void) :
    Inherited(),
    _sfConditionalAttribute   (),
    _sfConditionalOperator    (UInt8(1)),
    _sfConditionalValue       (UInt32(0.0)),
    _mfAffectors              ()
{
}
Ejemplo n.º 13
0
dmz::Boolean
dmz::NetExtPacketCodecObjectNative::encode_object (
      const Handle ObjectHandle,
      const NetObjectEncodeEnum EncodeMode,
      Marshal &data) {

   Boolean result (False);

   if (_attrMod && _objMod) {

      UUID objectID;

      if (_objMod->lookup_uuid (ObjectHandle, objectID)) {

         data.set_next_uuid (_SysID);
         data.set_next_uuid (objectID);

         if (EncodeMode == NetObjectDeactivate) {

            data.set_next_int8 (0);
            result = True;
         }
         else {

            const ObjectType Type (_objMod->lookup_object_type (ObjectHandle));
            ArrayUInt32 typeArray;

            if (_attrMod->to_net_object_type (Type, typeArray)) {

               const Int32 TypeSize (typeArray.get_size ());
               data.set_next_int8 (Int8 (TypeSize));

               for (Int32 ix = 0; ix < TypeSize; ix++) {

                  data.set_next_uint8 (UInt8 (typeArray.get (ix)));
               }

               ObjectAttributeAdapter *current (_adapterList);

               while (current) {

                  current->encode (ObjectHandle, *_objMod, data);
                  current = current->next;
               }

               result = True;
            }

            _objMod->store_time_stamp (
               ObjectHandle,
               _lnvHandle,
               _time.get_last_frame_time ());
         }
      }
   }

   return result;
}
Ejemplo n.º 14
0
LabelBase::LabelBase(void) :
    Inherited(),
    _sfPosition               (Pnt3f(0,0,0)),
    _sfPixelOffset            (Vec2f(0,0)),
    _sfOrientation            (Real32(0.0)),
    _sfHorizontalAlign        (UInt8(1)),
    _sfVerticalAlign          (UInt8(1)),
    _sfMargin                 (Vec2f(0,0)),
    _sfColor                  (Color4f(1,1,1,1)),
    _sfBgColor                (Color4f(0,0,0,0)),
    _sfShadowColor            (Color4f(0,0,0,1)),
    _sfShadowOffset           (Vec2f(1,-1)),
    _sfBorderColor            (Color4f(0,0,0,0)),
    _sfBorderOffset           (Vec2f(4,4)),
    _sfImportance             (Real32(1)),
    _sfTextureObject          (NULL)
{
}
Ejemplo n.º 15
0
AbstractTextBase::AbstractTextBase(void) :
    _sfPosition               (), 
    _sfFont                   (), 
    _mfText                   (), 
    _sfVerticalLineDistance   (), 
    _sfAlignment              (UInt8(0)), 
    Inherited() 
{
}
Ejemplo n.º 16
0
// Note: Not a heck of a lot of room for error in this function...
//
void imageFile::LoadTextAlphaPAL(void)
{
   FILE *fp;
   if((fp = fopen(Filename,"rb")) == NULL)
   {
       printf("ERROR - Cannot read Palette from : %s\n",Filename);
       exit(0);
   }

   for (int i = 0; i < 256; i++) {
      int red, green, blue, alpha;
      fscanf(fp, "%d %d %d %d", &red,
                                &green,
                                &blue,
                                &alpha);
      Pal[i].peRed   = UInt8(red);
      Pal[i].peGreen = UInt8(green);
      Pal[i].peBlue  = UInt8(blue);
      Pal[i].peFlags = UInt8(alpha);
   }
   fclose(fp);
}
Ejemplo n.º 17
0
bool SynthGroupElement::ChannelMessage(UInt16 controllerID, UInt16 inValue)
{
	bool handled = true;
#if DEBUG_PRINT
	printf("SynthGroupElement::ChannelMessage(0x%x, %u)\n", controllerID, inValue);
#endif
	// Sustain and sostenuto are "pedal events", and are handled during render cycle
	if (controllerID <= kMidiController_RPN_MSB && controllerID != kMidiController_Sustain && controllerID != kMidiController_Sostenuto)
		handled = mMidiControlHandler->SetController(controllerID, UInt8(inValue));
	else 
	{
		switch (controllerID)
		{
			case kMidiMessage_ProgramChange:
				handled = mMidiControlHandler->SetProgramChange(inValue);
				break;
			case kMidiMessage_PitchWheel:
				handled = mMidiControlHandler->SetPitchWheel(inValue);
				break;
			case kMidiMessage_ChannelPressure:
#if DEBUG_PRINT
				printf("SynthGroupElement::ChannelMessage: Channel Pressure %u\n", inValue);
#endif
				handled = mMidiControlHandler->SetChannelPressure(UInt8(inValue));
				break;
			case kMidiMessage_PolyPressure:
			{	UInt8 inKey = inValue >> 7;
				UInt8 val = inValue & 0xf;
				handled = mMidiControlHandler->SetPolyPressure(inKey, val);
				break;
			}
			default:
				handled = false;
				break;
		}
	}
	return handled;
}
Ejemplo n.º 18
0
CgFXMaterialBase::CgFXMaterialBase(void) :
    Inherited(),
    _sfTreatTechniquesAsVariants(bool(false)),
    _sfEffectFile             (),
    _sfParameterValueSource   (UInt8(CgFXMaterial::DEFAULT)),
    _sfEffectString           (),
    _mfCompilerOptions        (),
    _sfVariables              (this,
                          VariablesFieldId,
                          ShaderProgramVariables::ParentsFieldId),
    _sfSelectedTechnique      (),
    _sfStateVariables         (UInt32(0)),
    _mfTechniques             (),
    _mfTextures               (),
    _sfGLId                   (GLenum(0))
{
}
Ejemplo n.º 19
0
void registerCodecZSTD(CompressionCodecFactory & factory)
{
    UInt8 method_code = UInt8(CompressionMethodByte::ZSTD);
    factory.registerCompressionCodec("ZSTD", method_code, [&](const ASTPtr & arguments) -> CompressionCodecPtr
    {
        int level = CompressionCodecZSTD::ZSTD_DEFAULT_LEVEL;
        if (arguments && !arguments->children.empty())
        {
            if (arguments->children.size() > 1)
                throw Exception("ZSTD codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE);

            const auto children = arguments->children;
            const auto * literal = children[0]->as<ASTLiteral>();
            level = literal->value.safeGet<UInt64>();
            if (level > ZSTD_maxCLevel())
                throw Exception("ZSTD codec can't have level more that " + toString(ZSTD_maxCLevel()) + ", given " + toString(level), ErrorCodes::ILLEGAL_CODEC_PARAMETER);
        }

        return std::make_shared<CompressionCodecZSTD>(level);
    });
}
WindowActivityBase::WindowActivityBase(void) :
    _sfWindowEventProducer    (WindowEventProducerPtr(NullFC)), 
    _sfActivityType           (UInt8(WindowActivity::WINDOW_CLOSE)), 
    Inherited() 
{
}
Ejemplo n.º 21
0
int
main(int         in_argc,
     const char* in_argv[])
{
   MPMGlobalState::initGlobalState();

   if (processCommandLine(in_argc, in_argv) == false) {
      cout << "MPMerger v" << sg_pProgramVersion << '\n'
           << " MultiPalette Merger\n"
           << " @ Dynamix 1998, Original author Dave Moore\n\n";
      usage();
      return EXIT_FAILURE;
   }

   MPMGlobalState* pGlobalState = MPMGlobalState::getGlobalState();

   // Set up the options for this run...
   //
   MPMOptions  instOptions;           // Options for this run
   MPMFileList procFileList;          // List of files to process
   if (instOptions.attachResponseFile(pGlobalState->getResponseFileName()) == false) {
      cerr << "Unable to open response file: "
           << pGlobalState->getResponseFileName() << '\n'
           << " - ABORTING - \n";
      return EXIT_FAILURE;
   }
   if (instOptions.validateOptions() == false) {
      cerr << "Invalid options detected, exiting...\n\n";
      exit(1);
   }
   
   instOptions.processResponseFile(procFileList);
   AssertFatal(procFileList.getNumFiles() <= MAX_MULTI_PALETTES, "Too many palettes, exiting...");

   // Whether we are choosing colors or rendering, we need the unquantized palettes,
   //  so load them into memory...
   //
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      MPMFileEntry& rFileEntry = procFileList.getFile(i);
      AssertFatal(rFileEntry.pRawPalette == NULL, "Huh?");
      AssertFatal(rFileEntry.pFileName   != NULL, "Huh?");

      rFileEntry.pRawPalette = GFXPalette::load(rFileEntry.pFileName);

      if (rFileEntry.pRawPalette == NULL) {
         cerr << "main(): Unable to load file: " << rFileEntry.pFileName << '\n';
         exit(1);
      }
   }

   // We will need an authoritative final palette either way as well...
   //
   GFXPalette* pFinalMasterPalette = new GFXPalette;
   memset(pFinalMasterPalette->palette[0].color, 0, sizeof(PALETTEENTRY) * 256);
   if (instOptions.hasBasePalette() == true) {
      const char* pPaletteName = instOptions.getBasePalName();
      AssertFatal(pPaletteName != NULL, "No base palette name?  Here?");

      Bool palLoadSuccess = pFinalMasterPalette->read(pPaletteName);
      if (palLoadSuccess == false) {
         cerr << "Unable to load base palette: " << pPaletteName << ". Exiting...\n";
         exit(1);
      }
   }

   // We are always choosing colors for the master palette, so create a Popularity Table,
   //  and register our colors...
   //
   MPMPopularityTable popTable(instOptions);
   popTable.prepFixedColors(instOptions, pFinalMasterPalette);
   bool haveSomeRealColors = false;
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      MPMFileEntry& rFileEntry = procFileList.getFile(i);
      AssertFatal(rFileEntry.pRawPalette != NULL, "Huh?");

      if (rFileEntry.pRawPalette->palette[0].paletteType == GFXPalette::ColorQuantPaletteType) {
         printf(".");
         popTable.registerRGBColors(rFileEntry.pRawPalette, rFileEntry.fileWeight);
         haveSomeRealColors = true;
      } else
         printf("*");
   }

   // If we have NO files, we're just copying from the base palette to the new palette...
   if (procFileList.getNumFiles() == 0) {
      
   } else {
      AssertFatal(haveSomeRealColors == true, "Must have a least _one_ non-alpha palette...");
      
      // Quantize out the master palette..
      popTable.quantizeColors(instOptions, pFinalMasterPalette);
   }

   // Insert the mandatory entries into the master palette.  These are:
   //  palette[0].type  = HazeShadePaletteType
   //  palette[0].index = DWORD(-1)
   //           color[0]: (0, 0, 0)
   //         color[255]: (1, 1, 1)
   //         color[254]: instOptions.hazeColor
   //          hazeColor: 254
   //       correct bitvector entries.  renderStart-Last + 0, 254, 254
   //
   PALETTEENTRY hazeColor;
   PALETTEENTRY black, white;
   black.peRed = black.peGreen = black.peBlue = black.peFlags = 0;
   white.peRed = white.peGreen = white.peBlue = 255;
   white.peFlags = 0;
   hazeColor.peRed   = UInt8((instOptions.getHazeColor().red   * 255.0f) + 0.5f);
   hazeColor.peGreen = UInt8((instOptions.getHazeColor().green * 255.0f) + 0.5f);
   hazeColor.peBlue  = UInt8((instOptions.getHazeColor().blue  * 255.0f) + 0.5f);
   hazeColor.peFlags = 0;
   pFinalMasterPalette->palette[0].color[0]     = black;
   pFinalMasterPalette->palette[0].color[255]   = white;
   pFinalMasterPalette->palette[0].color[254]   = hazeColor;
   pFinalMasterPalette->palette[0].paletteIndex = DWORD(-1);
   pFinalMasterPalette->palette[0].paletteType  = GFXPalette::ShadeHazePaletteType;
   pFinalMasterPalette->hazeColor = 254;

   UInt32 renderFirst, renderLast;
   instOptions.getMasterRenderRange(renderFirst, renderLast);
   pFinalMasterPalette->allowedColorMatches.zero();
   for (UInt32 i = renderFirst; i <= renderLast; i++)
      pFinalMasterPalette->allowedColorMatches.set(i);
   pFinalMasterPalette->allowedColorMatches.set(0);
//   pFinalMasterPalette->allowedColorMatches.set(255);
   pFinalMasterPalette->allowedColorMatches.set(254);

   // Insert the shadow palette...
   //
   pFinalMasterPalette->palette[1].paletteIndex = -2;
   pFinalMasterPalette->palette[1].paletteType  = GFXPalette::TranslucentPaletteType;
   for (int i = 0; i < 256; i++) {
      pFinalMasterPalette->palette[1].color[i].peRed   = 0;
      pFinalMasterPalette->palette[1].color[i].peGreen = 0;
      pFinalMasterPalette->palette[1].color[i].peBlue  = 0;
      pFinalMasterPalette->palette[1].color[i].peFlags = i;
   } 
   pFinalMasterPalette->numPalettes++;

   // Ok, now we need to map the multipalettes into the master palette...
   //
   MPMMerger mpmMerger(instOptions);
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      MPMFileEntry& rFileEntry = procFileList.getFile(i);
      mpmMerger.insertPalette(pFinalMasterPalette, rFileEntry.pRawPalette);
   }

   // And create the remap tables if necessary...
   //
   mpmMerger.createRemapTables(pFinalMasterPalette);

   // And we are DONE!  Write out the master palette to the specified name...
   //
   // First make sure that in no palettes any color other than 0 is fully black
   //
   for (int i = 0; i < pFinalMasterPalette->numPalettes; i++) {
      GFXPalette::MultiPalette& rMPalette = pFinalMasterPalette->palette[i];

      for (int j = 1; j < 256; j++) {
         PALETTEENTRY& rPEntry = rMPalette.color[j];
         if (rPEntry.peRed   == 0 &&
             rPEntry.peGreen == 0 &&
             rPEntry.peBlue  == 0)
            rPEntry.peBlue = 1;
      }
   }

   AssertFatal(instOptions.getOutputPalName() != NULL, "Error, no output name!");
   pFinalMasterPalette->write(instOptions.getOutputPalName());

   //-------------------------------------- Clean-up
   delete pFinalMasterPalette;
   MPMGlobalState::shutdownGlobalState();
   return EXIT_SUCCESS;
}
Ejemplo n.º 22
0
void GFXFont::getCharInfo(int index, const GFXBitmap **bmp, RectI *in_subRegion, GFXCharInfo **charInfo)
{
	static GFXBitmap bitmap;

	// Lookup char info and create a sub-bitmap for drawing this font
	int lookupTableIndex;
   if (fi.flags & FONT_LOWERCAPS) lookupTableIndex = toupper(char(index)) - charTableLookupOffset;
   else lookupTableIndex = index - charTableLookupOffset;
	int charTableIndex;

	if ((lookupTableIndex < 0) || 
	    (lookupTableIndex > charTableLookupSize) ||
        ((charTableIndex = charTableLookup[lookupTableIndex]) == -1))
	{
		// The requested index is not in the character set, create a
		// "missing" bitmap (pink box) and return that instead.

	 	static GFXCharInfo missingInfo;
		missingInfo.bitmapNo = 0;
		missingInfo.baseline = 0;
		missingInfo.width    = max_UInt8(UInt8(fi.fontWidth), UInt8(5));
		missingInfo.height   = max_UInt8(UInt8(fi.fontHeight), UInt8(1));
		missingInfo.x        = 0;
		missingInfo.y        = 0;

		if (bmp)
		{
			if (!missing || missing->getWidth() != missingInfo.width || missing->getHeight() != missingInfo.height)
			{
				delete missing;
				missing = GFXBitmap::create(missingInfo.width, missingInfo.height);
				memset(missing->pBits, 253, missing->getStride()*missing->getHeight()); //fill with hot pink! 
			}
			// can't call bitmap.free(), so we have to do it manually...
			if (bitmap.pBits && (bitmap.attribute & BMA_OWN_MEM))
				delete [] bitmap.pBits;
			if (bitmap.pPalette)
				delete bitmap.pPalette;
			bitmap.pPalette   = NULL;
			bitmap.width      = missing->width;
			bitmap.height     = missing->height;
			bitmap.stride     = missing->stride;
			bitmap.imageSize  = missing->imageSize;
			bitmap.attribute  = missing->attribute & ~BMA_OWN_MEM;
			bitmap.bitDepth   = missing->bitDepth;
			bitmap.pBits      = missing->pBits;
			*bmp = &bitmap;

		}
		if (charInfo)
			*charInfo = &missingInfo;
    }
	else
	{
		GFXCharInfo *cInfo = &(charTable[charTableIndex]);
		if (charInfo)
			// The user wants the character information, look it up
	 		*charInfo = cInfo;

		if (bmp)
		{
			// The client wants the bitmap, cut it out of the bitmap sheet
			*in_subRegion = RectI(cInfo->x, cInfo->y, 
			            cInfo->x + cInfo->width - 1,
						cInfo->y + cInfo->height - 1);
			GFXBitmap *bitmapSheet = *(bma.array + cInfo->bitmapNo);

			//bitmap.makeSubBitmap(bitmapSheet, &bound);
			//bitmap.attribute     |= (bitmapSheet->attribute & (BMA_TRANSPARENT | BMA_TRANSLUCENT));
			//*bmp = &bitmap;
         *bmp = bitmapSheet;
		}
	}
}
ImageProcessedForegroundBase::ImageProcessedForegroundBase(void) :
    _sfFilter                 (TextureFilterPtr(NullFC)), 
    _sfOutputSlot             (UInt8(0)), 
    Inherited() 
{
}
Ejemplo n.º 24
0
int
main(int argc, const char* argv[])
{
   PNGlobalState::initGlobalState();

   if (processCommandLine(argc, argv) == false) {
      cout << "PicaNew v" << sg_pProgramVersion << '\n'
           << " Based on Pica by Joel Franklin which was\n"
           << " Based on DynaColor by Rhett Anderson\n"
           << " Glorious Thanks and Praise to the PNG and ZLib Folks...\n"
           << " @ Dynamix 1998, Original author Dave Moore\n\n";
      usage();
      return EXIT_FAILURE;
   }

   PNGlobalState* pGlobalState = PNGlobalState::getGlobalState();

   PNOptions  instOptions;           // Options for this run
   PNFileList procFileList;          // List of files to process

   if (instOptions.attachResponseFile(pGlobalState->getResponseFileName()) == false) {
      cerr << "Unable to open response file: "
           << pGlobalState->getResponseFileName() << '\n'
           << " - ABORTING - \n";
      return EXIT_FAILURE;
   }

   if (instOptions.validateOptions() == false) {
      cerr << "Invalid options detected, exiting...\n\n";
      exit(1);
   }

   instOptions.processResponseFile(procFileList);

   // Whether we are choosing colors or rendering, we need the unquantized images,
   //  so load them into memory...
   //
   PNUQImageFactory& rUQFactory = PNUQImageFactory::getInstance();
   for (int i = 0; i < procFileList.getNumFiles(); i++) {
      PNFileEntry& rFileEntry = procFileList.getFile(i);
      AssertFatal(rFileEntry.pUQImage  == NULL, "Huh?");
      AssertFatal(rFileEntry.pFileName != NULL, "Huh?");

      rFileEntry.pUQImage = rUQFactory.createUQImage(rFileEntry.pFileName);

      if (rFileEntry.pUQImage == NULL) {
         cerr << "main(): Unable to load file: " << rFileEntry.pFileName << '\n';
         exit(1);
      }
   }

   // We will need an authoritative final palette either way as well...
   //
   GFXPalette* pAuthPalette = new GFXPalette;
   memset(pAuthPalette->palette[0].color, 0, sizeof(PALETTEENTRY) * 256);
   if (instOptions.hasBasePalette() == true) {
      const char* pPaletteName = instOptions.getBasePalName();
      AssertFatal(pPaletteName != NULL, "No base palette name?  Here?");

      if (strstr(pPaletteName, ".tap") == NULL &&
          strstr(pPaletteName, ".TAP") == NULL) {
         Bool palLoadSuccess = pAuthPalette->read(pPaletteName);
         if (palLoadSuccess == false) {
            cerr << "Unable to load base palette: " << pPaletteName << ". Exiting...\n";
            exit(1);
         }
      } else {
         FILE *fp;
         if((fp = fopen(pPaletteName, "rb")) == NULL) {
             cerr << "ERROR - Cannot read Palette from : " << pPaletteName << "\n";
             exit(0);
         }

         for (int i = 0; i < 256; i++) {
            int red, green, blue, alpha;
            fscanf(fp, "%d %d %d %d", &red,
                                      &green,
                                      &blue,
                                      &alpha);
            pAuthPalette->palette[0].color[i].peRed   = UInt8(red);
            pAuthPalette->palette[0].color[i].peGreen = UInt8(green);
            pAuthPalette->palette[0].color[i].peBlue  = UInt8(blue);
            pAuthPalette->palette[0].color[i].peFlags = UInt8(alpha);
         }
         fclose(fp);
      }
   }
   // Always, always, always, the first color must be all 0
   //
   memset(&(pAuthPalette->palette[0].color[0]), 0, sizeof(PALETTEENTRY));


   // If we are choosing colors, set up the popularity table, and go to it...
   //
   if (instOptions.areChoosingColors() == true && procFileList.getNumFiles() != 0) {
      PNPopularityTable popularityTable(instOptions);

      // Files must register their colors with the popularity table..
      //
      PseudoTrace& tracer = PseudoTrace::getTracerObject();
      tracer.pushVerbosityLevel(1);
      tracer << "Scanning:  ";
      
      for (int i = 0; i < procFileList.getNumFiles(); i++) {
         PNFileEntry& rFileEntry = procFileList.getFile(i);
         AssertFatal(rFileEntry.pUQImage != NULL, "Huh?");

         rFileEntry.pUQImage->registerColors(popularityTable,
                                             rFileEntry.fileWeight);
         tracer << '.';
         tracer.flush();
      }
      tracer << " done\n";
      tracer.popVerbosityLevel();

      // Set up any fixed colors that may be required...
      //
      popularityTable.prepFixedColors(instOptions, pAuthPalette);

      // And quantize away!
      //
      popularityTable.quantizeColors(instOptions, pAuthPalette);
   }

   // If we are rendering the bitmaps, set up a color matching ditherer, and
   //  render away!
   //
   if (instOptions.areRenderingBitmaps() == true && procFileList.getNumFiles() != 0) {
      PNQuantizedRenderer pnRenderer(instOptions, pAuthPalette);

      PseudoTrace& tracer = PseudoTrace::getTracerObject();
      tracer.pushVerbosityLevel(1);
      tracer << "Rendering: ";
      
      for (int i = 0; i < procFileList.getNumFiles(); i++) {
         PNFileEntry& rFileEntry = procFileList.getFile(i);
         AssertFatal(rFileEntry.pUQImage != NULL, "Huh?");

         pnRenderer.renderUQImage(rFileEntry.pUQImage);

         if (instOptions.getExtrudingMipLevels() == false)
            tracer << '.';
         else
            tracer << '*';
         tracer.flush();
      }
      tracer << " done\n";
      tracer.popVerbosityLevel();

      // Store off the computed weights into the Palette...
      //
      const UInt32* pChosenFreqs = pnRenderer.getChosenFreqs();
      if (pAuthPalette->hasQuantizationInfo() == false)
         pAuthPalette->initQuantizationInfo();

      for (int i = 0; i < 256; i++)
         pAuthPalette->m_pColorWeights[i] += float(pChosenFreqs[i]);

      UInt32 renderStart, renderEnd;
      instOptions.getRenderRange(renderStart, renderEnd);
      pAuthPalette->m_usedRangeStart = renderStart;
      pAuthPalette->m_usedRangeEnd   = renderEnd;
   }

   // Write out the palette, and we're finished!
   //
   if (instOptions.getStripQuantizationInfo() == true)
      pAuthPalette->stripQuantizationInfo();

   if (instOptions.areChoosingColors() == true) {
      // First copy in the unique paletteKey, which we stuff into index 0
      //
      pAuthPalette->palette[0].paletteIndex = instOptions.getPaletteKey();

      // Now, technically, we're lying a bit about which type of palette this is,
      //  but the mpMerger tool will fix this up for us...
      //
      if (instOptions.getColorSpace() == PNOptions::ColorSpaceAlpha) {
         pAuthPalette->palette[0].paletteType = GFXPalette::AlphaQuantPaletteType;
      } else if (instOptions.getColorSpace() == PNOptions::ColorSpaceAdditive) {
         pAuthPalette->palette[0].paletteType = GFXPalette::AdditiveQuantPaletteType;
      } else if (instOptions.getColorSpace() == PNOptions::ColorSpaceSubtractive) {
         pAuthPalette->palette[0].paletteType = GFXPalette::SubtractiveQuantPaletteType;
      } else {
         pAuthPalette->palette[0].paletteType = GFXPalette::ColorQuantPaletteType;
      }

      if (instOptions.isStandAlonePalette() == true) {
         pAuthPalette->palette[0].paletteType = GFXPalette::NoRemapPaletteType;
      }

      for (int i = 1; i < 256; i++) {
         PALETTEENTRY& rPEntry = pAuthPalette->palette[0].color[i];
         if (rPEntry.peRed   == 0 &&
             rPEntry.peGreen == 0 &&
             rPEntry.peBlue  == 0)
            rPEntry.peBlue = 1;
      }

      // Write out our auth palette to the specified output name...
      //
      const char* pPaletteName = instOptions.getOutputPalName();
      pAuthPalette->write(pPaletteName);
   } else if (instOptions.areRenderingBitmaps() == true) {
      // Just write the palette back out to the base palette...
      //
      AssertFatal(instOptions.hasBasePalette() == true,
                  "If we aren't choosing colors, we must have a base palette...");
      pAuthPalette->write(instOptions.getBasePalName());
   } else {
      // Write out our auth palette to the specified output name...
      //
      pAuthPalette->palette[0].paletteIndex = instOptions.getPaletteKey();
      const char* pPaletteName = instOptions.getOutputPalName();
      if (pPaletteName != NULL)
         pAuthPalette->write(pPaletteName);
   }

   // Cleanup
   delete pAuthPalette;
   instOptions.unattachResponseFile();
   PNGlobalState::shutdownGlobalState();
   return EXIT_SUCCESS;
}
Ejemplo n.º 25
0
// Main function
//
void MAppMain()
{
  MString str;                  // Program's output
  MVector<UInt32> L0, L1, L2;   // Database lists
// Encode List 1 (2-3-letter combinations from "exclude.txt")
  MStrings exc;
  MTextFile(dir+"/exclude.txt").readAll().parseTo(exc,"\r\n");
  for (MStrings::CIter it(exc); it(); ++it)
  {
    const MString& s = (*it).convToLower();
    if (s.cnt() == 2)
      L1.append(ch2int1(s[0]) + ch2int1(s[1])*28);
    else if (s.cnt() == 3)
      L1.append(ch2int1(s[0]) + ch2int1(s[1])*28 + ch2int1(s[2])*784);
  }
// Encode List 0 and List 2 (converted to lowercase in the process)
  MStrings words;
  MTextFile(dir+"/words.txt").readAll().parseTo(words,"\r\n");  // Load dictionary
  for (MStrings::CIter it(words); it(); ++it)
  {
    const MString s = (*it).convToLower();
  // Encode 1-4-length words to List 2 (as is, no signatures)
    if (s.cnt() >= 1 && s.cnt() <= 4)
    {
      if (s.cnt() == 1)
        L2.append(ch2int2(s[0]));
      else if (s.cnt() == 2)
        L2.append(ch2int2(s[0]) + ch2int2(s[1])*28);
      else if (s.cnt() == 3)
        L2.append(ch2int2(s[0]) + ch2int2(s[1])*28 + ch2int2(s[2])*784);
      else if (s.cnt() == 4)
        L2.append(ch2int2(s[0])     + ch2int2(s[1])*28 +
                  ch2int2(s[2])*784 + ch2int2(s[3])*21952);
    }
  // Skip words with "wrong" lengths (<5 - handled above, >15 - too few to care)
    if (s.cnt() < 5 || s.cnt() > 15) continue;
  // Encode 5-15-length words to List 0 as signatures
    UInt32 sig = (1-s.cnt()%2)<<ch2int0('*');           // Encode length bit (Note: produces a slightly smaller database than "s.cnt()%2")
    for (MNum i = 0; i < s.cnt(); ++i)  // Encode 19 letter bits
      sig |= (1 << ch2int0(s[i]));
    L0.append(sig);
  }
// Sort and merge the lists
  unique(L0);
  unique(L1);
  unique(L2); L2.setCnt(c2,0);
  MVector<UInt32> L = L0;                  // Merged list
  L.append(L1);
  L.append(L2);
// Calculate element differences (at lists' edges add initial element)
  MVector<UInt32> diffs;
  for (MNum i = 1; i < L.cnt(); ++i)
    if (L.get(i) > L.get(i-1))
      diffs.append(L.get(i) - L.get(i-1));
// Encode 'diffs' as optimized bitmaps (in a string form for convenience)
// Each diff value is encoded as "0..01n..n": 'z' zeroes, followed by 1,
// followed by bitmap of the 'x-a' number, where 'x' is the diff and 'a' is
// the nearest (smaller or equal) to 'x' power of 2
  MString bits;
  for (MNum i = 0; i < diffs.cnt(); ++i)
  {
    UInt32 d = diffs.get(i);
    for (UInt32 z = 0; ; ++z)
    {
      UInt32 a = (1<<z), b = a*2-1;   // [a,b] - suitable range of 'd' to process
      if (d<a || d>b) continue;       // Outside of proper range - keep looking
      for (UInt32 k = 0; k < z; ++k)
        bits << '0';
      bits << '1';
      for (UInt32 k = 0; k < z; ++k)
        bits << (GetBits(d-a,UInt8(k),UInt8(k))?'1':'0');
      break;
    }
  }
  while (bits.cnt()%8) bits << '0';   // Pad with zeroes to complete the last byte
// Encode the intermediary 'bits' string to actual bit vector
  MVector<UInt8> bytes;
  for (MNum i = 0; i < bits.cnt(); i+=8)
  {
    UInt8 b = 0;
    for (MNum j = 0; j < 8; ++j) if (bits[i+j]=='1') b |= (1<<j);
    bytes.append(b);
  }
// Save the data to the file and compress it, if 7z is available at the sprcified location
  MFile(dir+"/data",fmOverwrite) << bytes;
  if (MSys::getFileInfo(GZipExe).name.cnt())
  {
    MSys::deleteFile(dir+"/data.gz");
    MSys::open(GZipExe, (MString)"a -tgzip -mx=9 -sdel \""+dir+"/data.gz\" \""+dir+"/data\"");
  }
// Compile some useful information (needed for hardcoding in the Node.js file)
 // Prepare sizes
  int size1 = 0;
  while (!size1)
  {
    MApp::sleep(500);
    size1 = (UInt32)MSys::getFileInfo(dir+"/data.gz").size;
  }
  int size2 = (int)MSys::getFileInfo(dir+"/solution.js").size;
 // Initial elements and sizes
  str <<"w=["<<L0.get(0)<<","<<L1.get(0)<<","<<L2.get(0)<<","
      <<L0.cnt()<<","<<L1.cnt()<<","<<L2.cnt()<<"]\n";
 // Letter->index conversion string for L0
  str<<"C0: \" ";
  for (int j='a'; j<='z'; ++j) str<<MChar(int('a'+ch2int0(j)-1));
  str<<MChar(int('a'+ch2int0('\'')-1))<<"\"\n";
 // Letter->index conversion string for L1
  MString c1 = " ...........................";
  for (int j='a'; j<='z'; ++j) c1.setChar(ch2int1(j),j);
  c1.setChar(ch2int1('\''),'\'');
  str<<"C1: \""<<c1<<"\"\n";
 // Letter->index conversion string for L2
  str<<"C2: \" ";
  for (int j='a'; j<='z'; ++j) str<<MChar(int('a'+ch2int2(j)-1));
  str<<MChar(int('a'+ch2int2('\'')-1))<<"\"\n";
// Size report
  str <<"\n"<<words.cnt()<<" words => "<<L.cnt()<<" signatures => "
      <<bytes.cnt()<<" bytes =>\n"<<size1<<"+"<<size2<<" final bytes ("
      <<(65536-size1-size2)<<" left)\n\n";
// Display the information
  MMainFrame wnd;                                       // Create app's mainframe window
  wnd.plugBar(MEditBoxPtr(wnd,AutoRect,None,true,str)); // Create a text box
  wnd.setCaption("Data file written");
  wnd.runMessageLoop();                                 // Run the app
}
Ejemplo n.º 26
0
//! react to field changes
void DVRLookupTable::changed(BitVector whichField, UInt32 origin)
{
    SINFO << "DVRLookupTable::changed" << std::endl;

    if(whichField & DataFieldMask) 
    {
        // copy data from interleaved field to single fields
        UInt32 iter = 0;

        for(UInt32 i = 0; i < _sfDimension.getValue(); i++) 
        {
            for(UInt32 j = 0; j < _mfSize[i]; j++) 
            {
                for (UInt32 k = 0; k < _sfChannel.getValue(); k++) 
                {

#if 1
                    //!! TODO: REMOVE as soon as the loader works correctly
                    if(_mfDataR.size() < _mfData.size() / 4) 
                    {
                        int size = _mfData.size() / 4;

                        _mfDataR.resize(size);
                        _mfDataG.resize(size);
                        _mfDataB.resize(size);
                        _mfDataA.resize(size);
                    }
#endif
	    
                    //!! setValue ( <value>, index )
                    if(k == 0)
                    {
                        _mfDataR[j] = 
                            Real32(_mfData[iter++]) / 
                            Real32(TypeTraits<UInt8>::getMax());
                    }
                    else if(k == 1)
                    {
                        _mfDataG[j] =
                            Real32(_mfData[iter++]) / 
                            Real32(TypeTraits<UInt8>::getMax());
                    }
                    else if(k == 2)
                    {
                        _mfDataB[j] = 
                            Real32(_mfData[iter++]) / 
                            Real32(TypeTraits<UInt8>::getMax());
                    }
                    else if(k == 3)
                    {
                        _mfDataA[j] =
                            Real32(_mfData[iter++]) / 
                            Real32(TypeTraits<UInt8>::getMax());
                    }
                }
            }
        }
    }


    if(whichField & DataRFieldMask) 
    {
        // copy data from R field to channel 0 of interleaved field
        UInt32 iter        = 0;
        UInt32 numChannels = _sfChannel.getValue();

        for(UInt32 i = 0; i < _sfDimension.getValue(); i++) 
        {
            for(UInt32 j = 0; j < _mfSize[i]; j++) 
            {
                //!! setValue ( <value>, index )
                
                _mfData[iter] = 
                    UInt8(Real32(_mfDataR[j]) * 
                          Real32(TypeTraits<UInt8>::getMax()));

                iter += numChannels;
            }
        }
    }

    
    if(whichField & DataGFieldMask) 
    {
        // copy data from G field to channel 1 of interleaved field
        UInt32 iter        = 1;
        UInt32 numChannels = _sfChannel.getValue();

        for(UInt32 i = 0; i < _sfDimension.getValue(); i++) 
        {
            for(UInt32 j = 0; j < _mfSize[i]; j++) 
            {
                //!! setValue ( <value>, index )
                _mfData[iter] = 
                    UInt8(Real32(_mfDataG[j]) * 
                          Real32(TypeTraits<UInt8>::getMax()));

                iter += numChannels;
            }
        }
    }

    if(whichField & DataBFieldMask) 
    {
        // copy data from B field to channel 2 of interleaved field
        UInt32 iter        = 2;
        UInt32 numChannels = _sfChannel.getValue();
        
        for(UInt32 i = 0; i < _sfDimension.getValue(); i++) 
        {
            for(UInt32 j = 0; j < _mfSize[i]; j++) 
            {
                //!! setValue ( <value>, index )
                _mfData[iter] =
                    UInt8(Real32(_mfDataB[j]) * 
                          Real32(TypeTraits<UInt8>::getMax()));

                iter += numChannels;
            }
        }
    }

    
    if(whichField & DataAFieldMask) 
    {
        // copy data from A field to to channel 3 interleaved field
        UInt32 iter        = 3;
        UInt32 numChannels = _sfChannel.getValue();
        
        for(UInt32 i = 0; i < _sfDimension.getValue(); i++) 
        {
            for(UInt32 j = 0; j < _mfSize[i]; j++) 
            {
                //!! setValue ( <value>, index )
                _mfData[iter] = 
                    UInt8(Real32(_mfDataA[j]) * 
                          Real32(TypeTraits<UInt8>::getMax()));

                iter += numChannels;
            }
        }
    }

    
    if(whichField & (DimensionFieldMask | SizeFieldMask | ChannelFieldMask)) 
    {
        SINFO << "DVRLookupTable::changed - DimensionFieldMask | "
              << "SizeFieldMask | ChannelFieldMask " 
              << std::endl;

        if(whichField & DimensionFieldMask) 
        {
            SINFO << "DVRLookupTable::changed - dimension " 
                  << _sfDimension.getValue() 
                  << std::endl;
        }

        if(whichField & SizeFieldMask) 
        {
            SINFO << "DVRLookupTable::changed - size " 
                  << _mfSize[0] 
                  << std::endl;
        }

        if(whichField & ChannelFieldMask) 
        {
            SINFO << "DVRLookupTable::changed - channel " 
                  << _sfChannel.getValue() 
                  << std::endl;
        }

#if 0
        commonConstructor();
#endif
    }

    if(whichField & TouchedFieldMask) 
    {
        SINFO << "DVRLookupTable::changed - touched " << std::endl;
    }

#if 0
    // mark table as being changed
    setTouched( true );
#endif
    

    // notify parent if appearance 
    // CHECK
#if 0
    MFFieldContainerPtr *par = getMFParents();

    for(UInt32 i = 0; i < par->size(); i++) 
    {
    }
#endif

    Inherited::changed(whichField, origin);
}