Esempio n. 1
0
    Bitmap GetWindow( HWND h ) {
        RECT rect;
        RECT rect2;

        Bitmap ret;
        if( !GetClientRect( h, &rect ) ) {
            return ret;
        }
        if( !GetWindowRect( h, &rect2 ) ) {
            return ret;
        }



        int width = rect2.right - rect2.left;
        int height = rect2.bottom - rect2.top;
        if( width <= 0 || height <= 0 ) { return ret; }
        int x = ( int )( rect2.left ); // + ((int)(rect.right-rect.left) - (int)(rect2.right-rect2.left))/2;
        int y = ( int )( rect2.top ); // + ((int)(rect.bottom-rect.top) - (int)(rect2.bottom-rect2.top)) - x;

        if( h == GetDesktopWindow() ) {
            width = GetSystemMetrics ( SM_CXVIRTUALSCREEN );
            height = GetSystemMetrics ( SM_CYVIRTUALSCREEN );
            x = GetSystemMetrics ( SM_XVIRTUALSCREEN );
            y = GetSystemMetrics ( SM_YVIRTUALSCREEN );
        }
        h = GetDesktopWindow();

        HDC hDC = GetDC( h );
        HDC hCaptureDC = CreateCompatibleDC( hDC );
        HBITMAP hCaptureBitmap = CreateCompatibleBitmap( hDC,
                                 width, height );
        HGDIOBJ hOld = SelectObject( hCaptureDC, hCaptureBitmap );
        BitBlt( hCaptureDC, 0, 0, width, height,
                hDC, x, y, SRCCOPY | CAPTUREBLT );


        SelectObject( hCaptureDC, hOld );

        BITMAPINFOHEADER bmi = {0};
        bmi.biSize = sizeof( BITMAPINFOHEADER );
        bmi.biPlanes = 1;
        bmi.biBitCount = 32;
        bmi.biWidth = width;
        bmi.biHeight = -height;
        bmi.biCompression = BI_RGB;
        bmi.biSizeImage = 0;// 3 * ScreenX * ScreenY;


        BYTE* ScreenData = ( BYTE* )malloc( 4 * width * height );

        GetDIBits( hCaptureDC, hCaptureBitmap, 0, height, ScreenData, ( BITMAPINFO* )&bmi, DIB_RGB_COLORS );

        ret.Write( width, height, ScreenData );
        free( ScreenData );


        // SaveCapturedBitmap(hCaptureBitmap); //Place holder - Put your code
        //here to save the captured image to disk
        ReleaseDC( h, hDC );
        DeleteDC( hCaptureDC );
        DeleteObject( hCaptureBitmap );

        return ret;
    }
Esempio n. 2
0
void
Canvas::CopyAnd(const Bitmap &src)
{
  CopyAnd(0, 0, GetWidth(), GetHeight(),
          src.GetNative(), 0, 0);
}
Esempio n. 3
0
void AlphaMask::setAlpha(Bitmap& bmp) const {
	if (!alpha) return;
	Image img = bmp.ConvertToImage();
	setAlpha(img);
	bmp = Bitmap(img);
}
/*
** Draws the meter on the double buffer
**
*/
bool CMeterBitmap::Draw(Graphics& graphics)
{
	if (!CMeter::Draw(graphics)) return false;

	int newY, newX;

	if (m_FrameCount == 0 || !m_Image.IsLoaded()) return false;	// Unable to continue

	Bitmap* bitmap = m_Image.GetImage();

	int x = GetX();
	int y = GetY();

	if (m_Extend)
	{
		int value = (int)m_Value;
		value = max(0, value);		// Only positive integers are supported

		int transitionValue = (int)m_TransitionStartValue;
		transitionValue = max(0, transitionValue);		// Only positive integers are supported

		// Calc the number of numbers
		int numOfNums = 0;

		if (m_Digits > 0)
		{
			numOfNums = m_Digits;
		}
		else
		{
			int tmpValue = value;

			do
			{
				++numOfNums;
				if (m_FrameCount == 1)
				{
					tmpValue /= 2;
				}
				else
				{
					tmpValue /= m_FrameCount;
				}
			}
			while (tmpValue > 0);
		}

		// Blit the images
		int offset;
		if (m_Align == ALIGN_RIGHT)
		{
			offset = 0;
		}
		else if (m_Align == ALIGN_CENTER)
		{
			offset = numOfNums * (m_W + m_Separation) / 2;
		}
		else
		{
			offset = numOfNums * (m_W + m_Separation);
		}

		do
		{
			offset = offset - (m_W + m_Separation);

			Rect r(x + offset, y, m_W, m_H);

			int realFrames = (m_FrameCount / (m_TransitionFrameCount + 1));
			int frame = (value % realFrames) * (m_TransitionFrameCount + 1);

			// If transition is ongoing the pick the correct frame
			if (m_TransitionStartTicks > 0)
			{
				int diffTicks = (int)(CSystem::GetTickCount64() - m_TransitionStartTicks);

				int range = ((value % realFrames) - (transitionValue % realFrames)) * (m_TransitionFrameCount + 1);
				if (range < 0)
				{
					range += m_FrameCount;
				}
				int frameAdjustment = range * diffTicks / ((m_TransitionFrameCount + 1) * m_MeterWindow->GetTransitionUpdate());
				if (frameAdjustment > range)
				{
					m_TransitionStartTicks = 0;		// The transition is over. Draw with the real value.
				}
				else
				{
					frame = (transitionValue % realFrames) * (m_TransitionFrameCount + 1);
					frame += frameAdjustment;
					frame %= m_FrameCount;
				}
			}

//			LogWithArgs(LOG_DEBUG, L"[%u] Value: %f Frame: %i (Transition = %s)", GetTickCount(), m_Value, frame, m_TransitionStartTicks > 0 ? L"true" : L"false");

			if (bitmap->GetHeight() > bitmap->GetWidth())
			{
				newX = 0;
				newY = m_H * frame;
			}
			else
			{
				newX = m_W * frame;
				newY = 0;
			}

			graphics.DrawImage(bitmap, r, newX, newY, m_W, m_H, UnitPixel);
			if (m_FrameCount == 1)
			{
				value /= 2;
				transitionValue /= 2;
			}
			else
			{
				value /= realFrames;
				transitionValue /= realFrames;
			}
			--numOfNums;
		}
		while (numOfNums > 0);
	}
	else
	{
		int frame = 0;
		int realFrames = (m_FrameCount / (m_TransitionFrameCount + 1));

		if (m_ZeroFrame)
		{
			// Use the first frame only if the value is zero
			if (m_Value > 0)
			{
				frame = (int)(m_Value * (realFrames - 1)) * (m_TransitionFrameCount + 1);
			}
		}
		else
		{
			// Select the correct frame linearly
			frame = (int)(m_Value * realFrames) * (m_TransitionFrameCount + 1);
		}

		// If transition is ongoing the pick the correct frame
		if (m_TransitionStartTicks > 0)
		{
			int diffTicks = (int)(CSystem::GetTickCount64() - m_TransitionStartTicks);

			if (diffTicks > ((m_TransitionFrameCount + 1) * m_MeterWindow->GetTransitionUpdate()))
			{
				m_TransitionStartTicks = 0;		// The transition is over. Draw with the real value.
			}
			else
			{
				double range = (m_Value - m_TransitionStartValue);
				double adjustment = range * diffTicks / ((m_TransitionFrameCount + 1) * m_MeterWindow->GetTransitionUpdate());
				double frameAdjustment = adjustment * m_FrameCount;

				frame = (int)(m_TransitionStartValue * realFrames) * (m_TransitionFrameCount + 1);
				frame += (int)frameAdjustment;
				frame %= m_FrameCount;
				frame = max(0, frame);
			}
		}

//		LogWithArgs(LOG_DEBUG, L"[%u] Value: %f Frame: %i (Transition = %s)", GetTickCount(), m_Value, frame, m_TransitionStartTicks > 0 ? L"true" : L"false");

		if (bitmap->GetHeight() > bitmap->GetWidth())
		{
			newX = 0;
			newY = frame * m_H;
		}
		else
		{
			newX = frame * m_W;
			newY = 0;
		}

		// Blit the image
		Rect r(x, y, m_W, m_H);
		graphics.DrawImage(bitmap, r, newX, newY, m_W, m_H, UnitPixel);
	}

	return true;
}
Esempio n. 5
0
void
Canvas::Copy(const Bitmap &src)
{
  Copy(0, 0, src.GetWidth(), src.GetHeight(), src, 0, 0);
}
Esempio n. 6
0
// adapted from http://cpansearch.perl.org/src/RJRAY/Image-Size-3.230/lib/Image/Size.pm
Size BitmapSizeFromData(const char *data, size_t len)
{
    Size result;
    ByteReader r(data, len);
    switch (GfxFormatFromData(data, len)) {
    case Img_BMP:
        if (len >= sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)) {
            BITMAPINFOHEADER bmi;
            bool ok = r.UnpackLE(&bmi, sizeof(bmi), "3d2w6d", sizeof(BITMAPFILEHEADER));
            CrashIf(!ok);
            result.Width = bmi.biWidth;
            result.Height = bmi.biHeight;
        }
        break;
    case Img_GIF:
        if (len >= 13) {
            // find the first image's actual size instead of using the
            // "logical screen" size which is sometimes too large
            size_t ix = 13;
            // skip the global color table
            if ((r.Byte(10) & 0x80))
                ix += 3 * (1 << ((r.Byte(10) & 0x07) + 1));
            while (ix + 8 < len) {
                if (r.Byte(ix) == 0x2C) {
                    result.Width = r.WordLE(ix + 5);
                    result.Height = r.WordLE(ix + 7);
                    break;
                }
                else if (r.Byte(ix) == 0x21 && r.Byte(ix + 1) == 0xF9)
                    ix += 8;
                else if (r.Byte(ix) == 0x21 && r.Byte(ix + 1) == 0xFE) {
                    const char *commentEnd = r.Find(ix + 2, 0x00);
                    ix = commentEnd ? commentEnd - data + 1 : len;
                }
                else if (r.Byte(ix) == 0x21 && r.Byte(ix + 1) == 0x01 && ix + 15 < len) {
                    const char *textDataEnd = r.Find(ix + 15, 0x00);
                    ix = textDataEnd ? textDataEnd - data + 1 : len;
                }
                else if (r.Byte(ix) == 0x21 && r.Byte(ix + 1) == 0xFF && ix + 14 < len) {
                    const char *applicationDataEnd = r.Find(ix + 14, 0x00);
                    ix = applicationDataEnd ? applicationDataEnd - data + 1 : len;
                }
                else
                    break;
            }
        }
        break;
    case Img_JPEG:
        // find the last start of frame marker for non-differential Huffman/arithmetic coding
        for (size_t ix = 2; ix + 9 < len && r.Byte(ix) == 0xFF; ) {
            if (0xC0 <= r.Byte(ix + 1) && r.Byte(ix + 1) <= 0xC3 ||
                0xC9 <= r.Byte(ix + 1) && r.Byte(ix + 1) <= 0xCB) {
                result.Width = r.WordBE(ix + 7);
                result.Height = r.WordBE(ix + 5);
            }
            ix += r.WordBE(ix + 2) + 2;
        }
        break;
    case Img_JXR:
    case Img_TIFF:
        if (len >= 10) {
            bool isBE = r.Byte(0) == 'M', isJXR = r.Byte(2) == 0xBC;
            CrashIf(!isBE && r.Byte(0) != 'I' || isJXR && isBE);
            const WORD WIDTH = isJXR ? 0xBC80 : 0x0100, HEIGHT = isJXR ? 0xBC81 : 0x0101;
            size_t idx = r.DWord(4, isBE);
            WORD count = idx <= len - 2 ? r.Word(idx, isBE) : 0;
            for (idx += 2; count > 0 && idx <= len - 12; count--, idx += 12) {
                WORD tag = r.Word(idx, isBE), type = r.Word(idx + 2, isBE);
                if (r.DWord(idx + 4, isBE) != 1)
                    continue;
                else if (WIDTH == tag && 4 == type)
                    result.Width = r.DWord(idx + 8, isBE);
                else if (WIDTH == tag && 3 == type)
                    result.Width = r.Word(idx + 8, isBE);
                else if (WIDTH == tag && 1 == type)
                    result.Width = r.Byte(idx + 8);
                else if (HEIGHT == tag && 4 == type)
                    result.Height = r.DWord(idx + 8, isBE);
                else if (HEIGHT == tag && 3 == type)
                    result.Height = r.Word(idx + 8, isBE);
                else if (HEIGHT == tag && 1 == type)
                    result.Height = r.Byte(idx + 8);
            }
        }
        break;
    case Img_PNG:
        if (len >= 24 && str::StartsWith(data + 12, "IHDR")) {
            result.Width = r.DWordBE(16);
            result.Height = r.DWordBE(20);
        }
        break;
    case Img_TGA:
        if (len >= 16) {
            result.Width = r.WordLE(12);
            result.Height = r.WordLE(14);
        }
        break;
    case Img_WebP:
        if (len >= 30 && str::StartsWith(data + 12, "VP8 ")) {
            result.Width = r.WordLE(26) & 0x3fff;
            result.Height = r.WordLE(28) & 0x3fff;
        }
        else {
            result = webp::SizeFromData(data, len);
        }
        break;
    case Img_JP2:
        if (len >= 32) {
            size_t ix = 0;
            while (ix < len - 32) {
                uint32_t lbox = r.DWordBE(ix);
                uint32_t tbox = r.DWordBE(ix + 4);
                if (0x6A703268 /* jp2h */ == tbox) {
                    ix += 8;
                    if (r.DWordBE(ix) == 24 && r.DWordBE(ix + 4) == 0x69686472 /* ihdr */) {
                        result.Width = r.DWordBE(ix + 16);
                        result.Height = r.DWordBE(ix + 12);
                    }
                    break;
                }
                else if (lbox != 0 && ix < UINT32_MAX - lbox) {
                    ix += lbox;
                }
                else {
                    break;
                }
            }
        }
        break;
    }

    if (result.Empty()) {
        // let GDI+ extract the image size if we've failed
        // (currently happens for animated GIF)
        Bitmap *bmp = BitmapFromData(data, len);
        if (bmp)
            result = Size(bmp->GetWidth(), bmp->GetHeight());
        delete bmp;
    }

    return result;
}
Esempio n. 7
0
void FontSupport::drawText(const WFont& font, const WRectF& rect,
			   const WTransform& transform, Bitmap& bitmap,
			   WFlags<AlignmentFlag> flags,
			   const WString& text)
{
  PANGO_LOCK;

  enabledFontFormats = enabledFontFormats_;

  PangoMatrix matrix;
  matrix.xx = transform.m11();
  matrix.xy = transform.m21();
  matrix.yx = transform.m12();
  matrix.yy = transform.m22();
  matrix.x0 = transform.dx();
  matrix.y0 = transform.dy();

  std::string utf8 = text.toUTF8();

  std::vector<PangoGlyphString *> glyphs;
  int width;

  pango_context_set_matrix(context_, &matrix);

  /*
   * Oh my god, somebody explain me why we need to do this...
   */
  WFont f = font;
  f.setSize(font.sizeLength().toPixels()
	    / pango_matrix_get_font_scale_factor(&matrix));

  GList *items = layoutText(f, utf8, glyphs, width);
  pango_context_set_matrix(context_, nullptr);

  AlignmentFlag hAlign = flags & AlignHorizontalMask;

  /* FIXME handle bidi ! */

  double x;
  switch (hAlign) {
  case AlignmentFlag::Left:
    x = rect.left();
    break;
  case AlignmentFlag::Right:
    x = rect.right() - pangoUnitsToDouble(width);
    break;
  case AlignmentFlag::Center:
    x = rect.center().x() - pangoUnitsToDouble(width/2);
    break;
  default:
    x = 0;
  }

  AlignmentFlag vAlign = flags & AlignVerticalMask;

  PangoFont *pangoFont = matchFont(font).pangoFont();
  PangoFontMetrics *metrics = pango_font_get_metrics(pangoFont, nullptr);

  double ascent
    = pangoUnitsToDouble(pango_font_metrics_get_ascent(metrics));
  double descent 
    = pangoUnitsToDouble(pango_font_metrics_get_descent(metrics));

  pango_font_metrics_unref(metrics);

  double baseline = ascent;
  double height = ascent + descent;

  double y;
  switch (vAlign) {
  case AlignmentFlag::Top:
    y = rect.top() + baseline;
    break;
  case AlignmentFlag::Middle:
    y = rect.center().y() - height / 2 + baseline;
    break;
  case AlignmentFlag::Bottom:
    y = rect.bottom() - height + baseline;
    break;
  default:
    y = 0;
  }

  FT_Bitmap bmp;
  bmp.buffer = bitmap.buffer();
  bmp.width = bitmap.width();
  bmp.rows = bitmap.height();
  bmp.pitch = bitmap.pitch();
  bmp.pixel_mode = FT_PIXEL_MODE_GRAY;
  bmp.num_grays = 16; // ???

  GList *elem;
  unsigned i = 0;

  for (elem = items; elem; elem = elem->next) {
    PangoItem *item = (PangoItem *)elem->data;
    PangoAnalysis *analysis = &item->analysis;

    PangoGlyphString *gl = glyphs[i++];

    pango_ft2_render_transformed(&bmp, &matrix,
				 analysis->font, gl,
				 pangoUnitsFromDouble(x),
				 pangoUnitsFromDouble(y));

    x += pangoUnitsToDouble(pango_glyph_string_get_width(gl));

    pango_glyph_string_free(gl);
    pango_item_free(item);
  }

  g_list_free(items);
}
Esempio n. 8
0
	~ImageOpenRAII()
	{
		if (!imageIsOk) bmp->freeMem();
		if (fp) fclose(fp); fp = NULL;
	}
Esempio n. 9
0
bool plDistributor::IFailsProbBitmap(int iFace, const Point3& bary) const
{
    // If we don't have a probability map, or we don't have
    // valid coordinates into it, just return false. That is,
    // with no valid probability map, everything goes.
    int uvwChan = 1;
    Matrix3 uvtrans(true);
    Bitmap* bm = nil;
    UINT filtType = BMM_FILTER_PYRAMID;
    if( fProbBitmapTex )
    {
        uvwChan = fProbBitmapTex->GetMapChannel();
        fProbBitmapTex->GetUVTransform(uvtrans);

        bm = fProbBitmapTex->GetBitmap(TimeValue(0));

        if( bm && !bm->HasFilter() )
        {
            switch( fProbBitmapTex->GetFilterType() )
            {
            default:
            case FILTER_PYR:
                filtType = BMM_FILTER_PYRAMID;
                break;
            case FILTER_SAT:
                filtType = BMM_FILTER_SUM;
                break;
            case FILTER_NADA:
                filtType = BMM_FILTER_NONE;
                break;
            }
        }
    }
    else if( fProbLayerTex )
    {
        uvwChan = fProbLayerTex->GetMapChannel();
        fProbLayerTex->GetUVTransform(uvtrans);

        bm = fProbLayerTex->GetBitmap(TimeValue(0));

    }

    if( !bm )
        return false;

    if( !bm->HasFilter() )
        bm->SetFilter(filtType);

    bm->PrepareGChannels(&bm->Storage()->bi);

    if( !fSurfMesh->mapSupport(uvwChan) )
        return false;

    if( !fSurfMesh->mapFaces(uvwChan) || !fSurfMesh->mapVerts(uvwChan) )
        return false;

    // Lookup the appropriate texel value
    Point3 uvw;
    uvw = fSurfMesh->mapVerts(uvwChan)[fSurfMesh->mapFaces(uvwChan)[iFace].getTVert(0)] * bary[0];
    uvw += fSurfMesh->mapVerts(uvwChan)[fSurfMesh->mapFaces(uvwChan)[iFace].getTVert(1)] * bary[1];
    uvw += fSurfMesh->mapVerts(uvwChan)[fSurfMesh->mapFaces(uvwChan)[iFace].getTVert(2)] * bary[2];

    uvw = uvw * uvtrans;

    float fu = uvw.x - int(uvw.x);
    if( fu < 0 )
        fu += 1.f;
    float fv = 1.0f - (uvw.y - int(uvw.y));
    if( fv < 0 )
        fv += 1.f;
    float du = 1.f / bm->Width();
    float dv = 1.f / bm->Height();

    BMM_Color_fl evCol;
    bm->GetFiltered(fu, fv, du, dv, &evCol);
    
    float frac;
    switch( fProbColorChan )
    {
    case kRed:
        frac = evCol.r;
        break;
    case kGreen:
        frac = evCol.g;
        break;
    case kBlue:
        frac = evCol.b;
        break;
    case kAlpha:
        frac = evCol.a;
        break;
    case kAverageRedGreen:
        frac = (evCol.r + evCol.g) / 2.f;
        break;
    case kAverageRedGreenTimesAlpha:
        frac = (evCol.r + evCol.g) / 2.f * evCol.a;
        break;
    case kAverage:
        frac = (evCol.r + evCol.g + evCol.b ) / 3.f;
        break;
    case kAverageTimesAlpha:
        frac = (evCol.r + evCol.g + evCol.b ) / 3.f * evCol.a;
        break;
    case kMax:
    case kMaxColor:
        frac = hsMaximum(evCol.r, hsMaximum(evCol.g, evCol.b));
        break;
    case kMaxColorTimesAlpha:
        frac = hsMaximum(evCol.r, hsMaximum(evCol.g, evCol.b)) * evCol.a;
        break;
    case kMaxRedGreen:
        frac = hsMaximum(evCol.r, evCol.g);
        break;
    case kMaxRedGreenTimesAlpha:
        frac = hsMaximum(evCol.r, evCol.g) * evCol.a;
        break;
    }

    if( fProbRemapFromHi != fProbRemapFromLo )
        frac = fProbRemapToLo + (frac - fProbRemapFromLo) / (fProbRemapFromHi - fProbRemapFromLo) * (fProbRemapToHi - fProbRemapToLo);
    else
        frac = frac > fProbRemapFromHi ? fProbRemapToHi : fProbRemapToLo;

    return frac < fRand.RandZeroToOne();
}
Esempio n. 10
0
int main (int argc, char * Files []) {

	cout << "PCX to VBM Converter Version 0.1Beta\n" << "Working . . .\n";

	if ( argc < 2 ) {
		cout << "Not Enough Arguments\n" << "Usage:\n" <<
			"\tpcx2vbm pcxfile1 pcxfile2 . . . pcxfilen" <<
			"\tWhere pcxfile1 to pcxfile2 are PCX files to be converted\n";
	}

	for (int tru = 1; tru <= (argc - 1); tru++) {

		//make names usable
      //char * thisFile = strcpy(thisFile, *(Files + tru));
      //char * writeFile = strcpy(writeFile, *(Files + tru));
      char thisFile[128];
      char writeFile[128];
      //char * thisFile = new char [12];
      //char * writeFile = new char [12];
      strcpy(thisFile, *(Files + tru));
      strcpy(writeFile, *(Files + tru));
		int repplace = 0;
		for (int tru2 = 0; tru2 < 20; tru2++) {
			char thechar = *(writeFile + tru2);
			if (thechar == '.') {
				repplace = tru2;
            break;
			}
		}
		char * vbmstr = ".vbm";
		memcpy(writeFile + repplace, vbmstr, 4);

		cout << "Converting " << thisFile <<  " to " << writeFile << "\n";

		LINEAR_BITMAP * TempBitmap = new LINEAR_BITMAP;
		UCHAR PCXPal[256][3];

		//load the pcx file
		TempBitmap = LoadPCX(thisFile, PCXPal);
		if (TempBitmap == NULL) {
			delete TempBitmap;
			cout << "\nCan't load file: " << thisFile << "\n";
			return 1;
		}

		//transfer stuff from one bitmap to another
		Bitmap * MyBitmap = new Bitmap;
		UCHAR * tPointer = (UCHAR *)&(TempBitmap->Data);
		//convert stuff
		MyBitmap->MakeNewBmp (TempBitmap->Width, TempBitmap->Height, tPointer, PCXPal);
		//save it
		MyBitmap->SaveToDisk (writeFile);
      //TheScreen->SetMode13h(); //set mode13h (don't forget)
      //MyBitmap->PutRegular (0, 0, VGAMEMORY);
      //getch();
      //TheScreen->SetTextMode(); //set mode13h (don't forget)
      delete MyBitmap;
	}

	cout << "Done";

	return 0;
}
Esempio n. 11
0
//************************************
// Method:    getBitmapFromComplex
// FullName:  CFFTMachine::getBitmapFromComplex
// Access:    protected 
// Returns:   Bitmap*
// Qualifier:
// Parameter: LPCOMPLEX pSource
// Parameter: INT nWidth
// Parameter: INT nHeight
//************************************
Bitmap* CFFTMachine::getBitmapFromComplex(LPCOMPLEX* ppSource,INT  in_nWidth,INT in_nHeight)
{
	ASSERT(ppSource);
	BYTE* pBuffer = NULL;
	pBuffer = new BYTE[in_nWidth * in_nHeight * 3];
	
	//change the coordinate and calculate the value to display
	/*
			0	   --->		cols (x)
		  0	+-------+-------+	
	  		|	1	|   2   |
		  |	|		|		|
		  |	+-------+-------+
		  Y	|	3  	|	4	|
			|		|		|
	   rows	+-------+-------+
	    (y)

		Coordinate transform
		1<->4; 2<->3 
	*/

	if(pBuffer != NULL)
	{
		FillMemory(pBuffer, in_nWidth * in_nHeight * 3, 0);
		INT nWidth_2  = in_nWidth/2;
		INT nHeight_2 = in_nHeight/2;
		
		for(INT y=0; y<in_nHeight; y++)
		{
			for (INT x=0; x<in_nWidth; x++)	
			{
				BYTE nPixelVal = 0;
				//in the part1 --> move to part 4
				if((x<nWidth_2)&&(y<nHeight_2))
					nPixelVal = valueTransform(ppSource[y + nHeight_2][x + nWidth_2].real);
				//in the part2 --> move to part 3
				else if ((x>=nWidth_2)&&(y<nHeight_2))
					nPixelVal = valueTransform(ppSource[y + nHeight_2][x - nWidth_2].real);
				//in the part3 --> move to part 2
				else if((x<nWidth_2)&&(y>=nHeight_2))
					nPixelVal = valueTransform(ppSource[y - nHeight_2][x + nWidth_2].real);
				//in the part4 --> move to part 1
				else
					nPixelVal = valueTransform(ppSource[y - nHeight_2][x - nWidth_2].real);					
					
				*(pBuffer + 3*(y*in_nWidth + x) + 0) = nPixelVal;	//R
				*(pBuffer + 3*(y*in_nWidth + x) + 1) = nPixelVal;	//G
				*(pBuffer + 3*(y*in_nWidth + x) + 2) = nPixelVal;	//B
			}
		}
		//adjust image
		for (INT j=0;j<nHeight_2;j++)
		{
			for(INT k=0;k<in_nWidth;k++)
			{
				BYTE temp = *(pBuffer + 3*(j*in_nWidth + k) + 0);
				*(pBuffer + 3*(j*in_nWidth + k) + 0) = *(pBuffer + 3*((in_nHeight- j -1)*in_nWidth+k));	//R
				*(pBuffer + 3*(j*in_nWidth + k) + 1) = *(pBuffer + 3*((in_nHeight- j -1)*in_nWidth+k));
				*(pBuffer + 3*(j*in_nWidth + k) + 2) = *(pBuffer + 3*((in_nHeight- j -1)*in_nWidth+k));
				*(pBuffer + 3*((in_nHeight- j -1)*in_nWidth+k) + 0) =  temp;
				*(pBuffer + 3*((in_nHeight- j -1)*in_nWidth+k) + 1) =  temp;
				*(pBuffer + 3*((in_nHeight- j -1)*in_nWidth+k) + 2) =  temp;
			}
		}
	}

	Bitmap* pRetBmp = NULL; 
	BITMAPINFO t_BMPinfo;
	BITMAPINFOHEADER* pBMPInfoHeader = &(t_BMPinfo.bmiHeader); 
	memset(pBMPInfoHeader, 0, sizeof(BITMAPINFOHEADER));
	//Create bitmap header	
	pBMPInfoHeader->biSize			= sizeof(BITMAPINFOHEADER);
	pBMPInfoHeader->biWidth			= in_nWidth;
	pBMPInfoHeader->biHeight		= in_nHeight;
	pBMPInfoHeader->biPlanes		= 1;
	pBMPInfoHeader->biCompression	= BI_RGB;
	pBMPInfoHeader->biBitCount		= IMP_MONOBMP_BITS * 3;
	pBMPInfoHeader->biSizeImage		= in_nWidth * in_nHeight * 3;

	if(pBuffer != NULL)	pRetBmp = Bitmap::FromBITMAPINFO(&t_BMPinfo,pBuffer);		
	
	if(pRetBmp == NULL)
	{
		delete[] pBuffer;
		pBuffer = NULL;
	}

	
#ifdef _DEBUG
	if(pRetBmp != NULL)
	{
		CLSID pngClsid;
		CUtility::GetEncoderClsid(L"image/bmp", &pngClsid);
		Status res = pRetBmp->Save(L".\\Fourier.bmp", &pngClsid, NULL);	
	}	
#endif
	
	return pRetBmp;
}
Esempio n. 12
0
void FirmOffensive2::put_info(int refreshFlag)
{
    if( !should_show_info() )
        return;

    vga.active_buf->put_bitmap( INFO_X1, INFO_Y1, image_gameif.read("MISSBASE") );

    int hitPoints;
    String str;
    int offsetX = 0;
    int offsetY = 0;

    if( hit_points > (float)0 && hit_points < (float)1 )
        hitPoints = 1;		// display 1 for value between 0 and 1
    else
        hitPoints = (int) hit_points;

    if ( max_hit_points() )
    {
        offsetX = -35;
        offsetY = -14;
        short*	hitPointBitmap =NULL;
        int ratio = hitPoints *40 / (int)max_hit_points();
        int size = hitPoints *76 / (int)max_hit_points();

        //106 x 35 --- 15 to 90 ie. 0 to 40
        hitPointBitmap = (short *)mem_add( BitmapW::size(15 +size, 35) );
        if (ratio <11)
            vga.active_buf->put_bitmap_trans( INFO_X1 +80 +20 +offsetX, INFO_Y1 +49 +offsetY, image_spict.read("MTR_B2"));
        else if (ratio <40)
            vga.active_buf->put_bitmap_trans( INFO_X1 +80 +20 +offsetX, INFO_Y1 +49 +offsetY, image_spict.read("MTR_B3"));
        else
            vga.active_buf->put_bitmap_trans( INFO_X1 +80 +20 +offsetX, INFO_Y1 +49 +offsetY, image_spict.read("MTR_B4"));

        vga.active_buf->read_bitmapW( INFO_X1 +80 +20 +offsetX, INFO_Y1 +49 +offsetY, INFO_X1 +94 +20 +size +offsetX, INFO_Y1 +80 +offsetY, hitPointBitmap );
        vga.active_buf->put_bitmap_trans( INFO_X1 +80 +20 +offsetX, INFO_Y1 +49 +offsetY, image_spict.read("MTR_B1"));
        vga.active_buf->put_bitmapW( INFO_X1 +80 +20 +offsetX, INFO_Y1 +49 +offsetY, hitPointBitmap );
        mem_del( hitPointBitmap );

        font_whbl.center_put( INFO_X1 +43, INFO_Y1 +45, INFO_X1 +65, INFO_Y1 +57, m.format((int)hitPoints,4));
        font_whbl.center_put( INFO_X1 +169, INFO_Y1 +45, INFO_X1 +191, INFO_Y1 +57, m.format((int)max_hit_points(),4) );
    }

    // font_whbl.center_put( INFO_X1 +12, INFO_Y1 +9, INFO_X2, INFO_Y1 +21, "Offensive Building 3", 0, 1 );
    font_whbl.center_put( INFO_X1 +12, INFO_Y1 +9, INFO_X2, INFO_Y1 +21, firm_name(), 0, 1 );

    FirmBuild* firmBuild = firm_res.get_build(firm_build_id);
    short *colorRemapTable = firmBuild->get_color_remap_table(nation_recno, firm_array.selected_recno == firm_recno);
    colorRemapTable = firm_res.calc_color_remap_table( colorRemapTable, 1.0f );

    FirmBitmap* firmBitmap = firm_res.get_bitmap(firmBuild->first_bitmap(1));
    if( firmBitmap )
    {
        Bitmap* bitmapPtr = (Bitmap *) firmBuild->res_bitmap.read_imported(firmBitmap->bitmap_ptr);

        int x1;
        int y1;
        int srcX2;
        int srcY2;

        if (config.building_size == 1)
        {
            x1 = INFO_X1 +130;
            y1 = INFO_Y1 +140;
        }
        else
        {
            x1 = INFO_X1 +120;
            y1 = INFO_Y1 +142;
        }

        x1 += firmBitmap->offset_x;
        y1 += firmBitmap->offset_y;
        int x2 = x1 + bitmapPtr->get_width() -1;
        int y2 = y1 + bitmapPtr->get_height() -1;
        int srcX1 = max(x1, INFO_X1+15)-x1;
        int srcY1 = 0;

        if (config.building_size == 1)
        {
            srcX2 = min(x2, INFO_X2)-x1;
            srcY2 = min(y2, INFO_Y1+227)-y1;
        }
        else
        {
            srcX2 = min(x2, INFO_X2)-x1;
            srcY2 = min(y2, INFO_Y2)-y1;
        }

        vga.active_buf->put_bitmap_area_trans_remap_decompress(x1, y1, (char *) bitmapPtr, srcX1, srcY1, srcX2, srcY2, colorRemapTable);
    }
    /*
    	if (config.building_size == 1)
    		return;

    	firmBitmap = firm_res.get_bitmap(firmBuild->first_bitmap(firm_cur_frame[0]));
    	if( firmBitmap && firmBitmap->display_layer == 1 )
    	{
    		Bitmap* bitmapPtr = (Bitmap *) firmBuild->res_bitmap.read_imported(firmBitmap->bitmap_ptr);

    		int x1 = INFO_X1 +120 +firmBitmap->offset_x;
    		int y1 = INFO_Y1 +142 +firmBitmap->offset_y;
    		int x2 = x1 + bitmapPtr->get_width() -1;
    		int y2 = y1 + bitmapPtr->get_height() -1;
    		int srcX1 = max(x1, INFO_X1+15)-x1;
    		int srcY1 = 0;
    		int srcX2 = min(x2, INFO_X2)-x1;
    		int srcY2 = min(y2, INFO_Y2)-y1;

    		vga.active_buf->put_bitmap_area_trans_remap_decompress(x1, y1, (char *) bitmapPtr, srcX1, srcY1, srcX2, srcY2, colorRemapTable);

    	//	vga_back.put_bitmap_trans_remap_decompress(INFO_X1 +113 +firmBitmap->offset_x,
    	//		INFO_Y1 +158 +firmBitmap->offset_y, bitmapPtr, colorRemapTable);
    	}*/
}
Esempio n. 13
0
bool RichEditHost::RenderTo(Graphics& graphics, const MiniRect& rcRender)
{
    if (!m_pTextServices || !m_pEdit)
    {
        return false;
    }

    MiniRect rcRootRender = rcRender;
    MiniRect rcRoot;
    m_pEdit->GetClientRect(rcRoot);
    rcRootRender += rcRoot.TopLeft();

    Bitmap* pBitmap = graphics.GetBitmap();
    byte* pBytes = (byte*)pBitmap->LockBits(rcRootRender);
    for (int i = 0; i < rcRender.Height(); ++i)
    {
        MiniARGB* pSrc = (MiniARGB*)(pBytes + i * pBitmap->GetBytesWidth());
        MiniARGB* pDst = (MiniARGB*)(m_dib.GetData() + (i + rcRender.top) * m_dib.GetBytesWidth()) + rcRender.left;
        for (int j = 0; j < rcRender.Width(); ++j)
        {
            uint32 c = gTable[pSrc->alpha];
            pDst->blue = (uint32)(c * (uint32)pSrc->blue + (1 << 23)) >> 24;
            pDst->green = (uint32)(c * (uint32)pSrc->green + (1 << 23)) >> 24;
            pDst->red = (uint32)(c * (uint32)pSrc->red + (1 << 23)) >> 24;
            pDst->alpha = 0xFF;
            pDst++;
            pSrc++;
        }
    }

    RECTL rc = {0, 0, m_size.cx, m_size.cy};
    HRESULT hr = m_pTextServices->TxDraw(DVASPECT_CONTENT, 0, 0, 0, m_dib, 0, &rc, 0, 0, 0, 0, TXTVIEW_ACTIVE);
    if (SUCCEEDED(hr))
    {
        if (m_bFocus && m_bShowCaret && m_bEnableCaret && m_bCaretState && !GetReadOnly())
        {
            if (!m_hCaret)
            {
                ::PatBlt((HDC)m_dib, m_rcCaret.left, m_rcCaret.top, m_rcCaret.Width(), m_rcCaret.Height(), DSTINVERT);
            }
            else
            {
                HDC hdcMem = CreateCompatibleDC((HDC)m_dib);
                HGDIOBJ hOld = ::SelectObject(hdcMem, m_hCaret);    
                ::BitBlt((HDC)m_dib, m_rcCaret.left, m_rcCaret.top, m_rcCaret.Width(), m_rcCaret.Height(), hdcMem, 0, 0, SRCINVERT);
                ::SelectObject(hdcMem, hOld);
                ::DeleteDC(hdcMem);
            }
        }

        for (int i = 0; i < rcRender.Height(); ++i)
        {
            MiniARGB* pSrc = (MiniARGB*)(m_dib.GetData() + (i + rcRender.top) * m_dib.GetBytesWidth()) + rcRender.left;
            MiniARGB* pDst = (MiniARGB*)(pBytes + i * pBitmap->GetBytesWidth());
            for (int j = 0; j < rcRender.Width(); ++j)
            {
                uint32 alpha = (uint32)pDst->alpha + 1;
                pDst->blue = ((uint32)pSrc->blue * alpha) >> 8;
                pDst->green = ((uint32)pSrc->green * alpha) >> 8;
                pDst->red = ((uint32)pSrc->red * alpha) >> 8;
                pDst++;
                pSrc++;
            }
        }
    }

    return true;
}
Esempio n. 14
0
static bool EncodeBitmap(Bitmap& image, const WCHAR* pcszEncodeFormat, UINT32* ulSize, unsigned char** pData)
{
    // Setup encoder parameters
    // Create stream with 0 size
    IStream* pIStream = nullptr;

    if (CreateStreamOnHGlobal(nullptr, TRUE, (LPSTREAM*)&pIStream) != S_OK)
    {

        Log(logERROR, "Failed to create stream on global memory!\n");
        return false;
    }

    CLSID pngClsid;
    GetEncoderClsid(pcszEncodeFormat, &pngClsid);

    // Setup encoder parameters
    EncoderParameters encoderParameters;
    EncoderParameters* pEncoderParameters = &encoderParameters;
    ULONG quality = 50; // setup compression level for jpeg

    if (wcscmp(pcszEncodeFormat, L"image/jpeg") == 0)
    {
        encoderParameters.Count = 1;
        encoderParameters.Parameter[0].Guid = EncoderQuality;
        encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
        encoderParameters.Parameter[0].NumberOfValues = 1;

        // setup compression level
        encoderParameters.Parameter[0].Value = &quality;
    }
    else if (wcscmp(pcszEncodeFormat, L"image/png") == 0)
    {
        pEncoderParameters = nullptr;
    }
    else
    {
        Log(logERROR, "Failed to save image: Unrecognized format.");
        return false;
    }

    //  Save the image to the stream
    Status SaveStatus = image.Save(pIStream, &pngClsid, pEncoderParameters);

    if (SaveStatus != Ok)
    {
        // this should free global memory used by the stream

        // according to MSDN

        pIStream->Release();
        Log(logERROR, "Failed to save to stream!\n");
        return false;
    }

    // get the size of the stream
    ULARGE_INTEGER ulnSize;
    LARGE_INTEGER lnOffset;
    lnOffset.QuadPart = 0;

    if (pIStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize) != S_OK)
    {
        pIStream->Release();
        Log(logERROR, "Failed to get the size of the stream!\n");
        return false;
    }

    // now move the pointer to the beginning of the file
    if (pIStream->Seek(lnOffset, STREAM_SEEK_SET, nullptr) != S_OK)
    {
        pIStream->Release();
        Log(logERROR, "Failed to move the file pointer to the beginning of the stream!\n");
        return false;
    }

    unsigned char* pBuff = (unsigned char*)malloc((size_t)ulnSize.QuadPart);
    PsAssert(pBuff != nullptr)

    if (pBuff == nullptr)
    {
        return false;
    }

    ULONG ulBytesRead;

    if (pIStream->Read(pBuff, (ULONG)ulnSize.QuadPart, &ulBytesRead) != S_OK)
    {
        pIStream->Release();
        free(pBuff);
        return false;
    }

    *pData  = pBuff;
    *ulSize  = ulBytesRead;
    /*
       // I am going to save it to the file just so we can
       // load the jpg to a gfx program
       FILE *fFile;
       fFile = fopen("c:\\test.jpg", "w");
       if(fFile)
       {
           char *pBuff = new char[ulnSize.QuadPart];

           // Read the stream directly into the buffer

           ULONG ulBytesRead;
           if(pIStream->Read(pBuff, ulnSize.QuadPart, &ulBytesRead) != S_OK)
           {
               pIStream->Release();
               delete pBuff;
               return false;
           }

           fwrite(pBuff, ulBytesRead, 1, fFile);
           fclose(fFile);
           delete pBuff;
       }
       else printf("Failed to save data to the disk!");

       // Free memory used by the stream
    */
    pIStream->Release();

    return true;
}
LONG BitmapButton::ProcessMessage(HWND hWnd, size_t msg, size_t wParam, LONG lParam)
{
	if (msg == WM_LBUTTONDOWN)
	{
		long res = CallWindowProc(DefaultHandler, hWnd, msg, wParam, lParam);
		SendMessage(hWnd, BM_SETSTATE, (WPARAM)BST_PUSHED, 0);
		InvalidateRect(hWnd, NULL, false);
		return res;
	}
	else if (msg == WM_LBUTTONUP)
	{
		long res = CallWindowProc(DefaultHandler, hWnd, msg, wParam, lParam);
		SendMessage(hWnd, BM_SETSTATE, (WPARAM)0, 0);
		InvalidateRect(hWnd, NULL, false);
		return res;
	}
	else if ((msg == WM_COMMAND) || (msg == BN_CLICKED))
	{
		if (clickHandler)
		{
			clickHandler();
			return true;
		}
		else if (dClickHandler)
		{
			(clickListener->*dClickHandler)();
			return true;
		}
		else 
			return false;
	}
	else if (msg == WM_ERASEBKGND)
	{
/*
		HBRUSH hOldBrush;
		HPEN hOldPen;
		RECT rect;
		HDC hDC;

		hDC = GetDC(hWnd);
		hOldBrush = (HBRUSH)SelectObject(hDC, erasePen);
		hOldPen = (HPEN)SelectObject(hDC, eraseBrush);

		GetUpdateRect(hWnd, &rect, FALSE);
		::Rectangle(hDC, rect.left, rect.top, rect.right, rect.bottom);

		SelectObject(hDC, hOldPen);
		SelectObject(hDC, hOldBrush);

		InvalidateRect(hWnd, NULL, FALSE);
*/
		return true;	
	}
	else if (msg == WM_PAINT)
	{
		HDC tmp = dc;
		PAINTSTRUCT ps;
		RECT rect;

		BeginPaint(hWnd, &ps);

		rect.left = 0; rect.right = Width();
		rect.top = 0; rect.bottom = Height();

		HBRUSH hOldBrush = (HBRUSH)SelectObject(dc, erasePen);
		HPEN hOldPen = (HPEN)SelectObject(dc, eraseBrush);
		::Rectangle(dc, rect.left, rect.top, rect.right, rect.bottom);

		SelectObject(dc, hOldPen);
		SelectObject(dc, hOldBrush);

		int state = SendMessage(hWnd, BM_GETSTATE, 0, 0);
		Bitmap *bit;
		int offset;
		if ((state & BST_PUSHED) == 0)
		{
			DrawEdge(dc, &rect, EDGE_RAISED, BF_ADJUST | BF_RECT);
			if (IsEnabled())
				bit = upBitmap;
			else
				bit = disabledBitmap;
			offset = 0;
		}
		else
		{
			DrawEdge(dc, &rect, EDGE_SUNKEN, BF_ADJUST | BF_RECT);
			bit = downBitmap;
			offset = 1;
		}

		bit->Copy(*this, (Width() - bit->Width()) / 2 + offset, (Height() - bit->Height()) / 2 + offset, bit->Width(), 
				  bit->Height(), 0, 0);

		dc = tmp;
		return false;
	}

	return false;
}
Esempio n. 16
0
void draw_text_window_and_bar(Bitmap **text_window_ds, bool should_free_ds,
                              int*xins,int*yins,int*xx,int*yy,int*wii,color_t *set_text_color,int ovrheight, int ifnum) {

    draw_text_window(text_window_ds, should_free_ds, xins, yins, xx, yy, wii, set_text_color, ovrheight, ifnum);

    if ((topBar.wantIt) && (text_window_ds && *text_window_ds)) {
        // top bar on the dialog window with character's name
        // create an enlarged window, then free the old one
        Bitmap *ds = *text_window_ds;
        Bitmap *newScreenop = BitmapHelper::CreateBitmap(ds->GetWidth(), ds->GetHeight() + topBar.height, game.GetColorDepth());
        newScreenop->Blit(ds, 0, 0, 0, topBar.height, ds->GetWidth(), ds->GetHeight());
        delete *text_window_ds;
        *text_window_ds = newScreenop;
        ds = *text_window_ds;

        // draw the top bar
        color_t draw_color = ds->GetCompatibleColor(play.top_bar_backcolor);
        ds->FillRect(Rect(0, 0, ds->GetWidth() - 1, topBar.height - 1), draw_color);
        if (play.top_bar_backcolor != play.top_bar_bordercolor) {
            // draw the border
            draw_color = ds->GetCompatibleColor(play.top_bar_bordercolor);
            for (int j = 0; j < play.top_bar_borderwidth; j++)
                ds->DrawRect(Rect(j, j, ds->GetWidth() - (j + 1), topBar.height - (j + 1)), draw_color);
        }

        // draw the text
        int textx = (ds->GetWidth() / 2) - wgettextwidth_compensate(topBar.text, topBar.font) / 2;
        color_t text_color = ds->GetCompatibleColor(play.top_bar_textcolor);
        wouttext_outline(ds, textx, play.top_bar_borderwidth + 1, topBar.font, text_color, topBar.text);

        // don't draw it next time
        topBar.wantIt = 0;
        // adjust the text Y position
        yins[0] += topBar.height;
    }
    else if (topBar.wantIt)
        topBar.wantIt = 0;
}
Esempio n. 17
0
//************************************
// Method:    OnBnClickedCmdSaveallslices
// FullName:  CCutoutSegDlg::OnBnClickedCmdSaveallslices
// Access:    public 
// Returns:   void
// Qualifier:
//************************************
void CCutoutSegDlg::OnBnClickedCmdSaveallslices()
{
	// User prompt to get the information: directory, file extension
	CSegmentExportDlg dlgSave;
	CString sDirPath = _T(".");
	CString sFileExt;
	CString strOutputFile;	
	strOutputFile.Format(_T("%s_%dx%d"),SV_EXP_DEFAULTNAME, m_pDataSet->GetSize().ndx, m_pDataSet->GetSize().ndx);

	CSize sliceSize(m_pDataSet->GetSize().ndx,m_pDataSet->GetSize().ndy);
	UCHAR* pBuffer = new UCHAR[sliceSize.cx * sliceSize.cy * 3];
	UCHAR* pByteBuffer = new UCHAR[sliceSize.cx * sliceSize.cy];
	if (dlgSave.DoModal() == IDOK)
	{
		sDirPath = dlgSave.m_sDirPath;
		sFileExt = dlgSave.m_sExt;
		// TODO: Add your control notification handler code here
		for (int iSlice=0; iSlice < m_pDataSet->GetSize().ndz; iSlice++)
		{
			//Get Raw Slice
			GetRawSliceFromDataSet(iSlice);

			//Cut it out
			CutOut(m_pSourceByteImg, pByteBuffer, sliceSize.cx, sliceSize.cy);
	

			//Save it
			CString numbers;
			numbers.Format(_T("_%.3d"), iSlice);
			CString FullPath = sDirPath + strOutputFile + numbers + _T(".")+ sFileExt;

			for (int i=0; i<sliceSize.cx * sliceSize.cy; i++)
			{			
				memset(pBuffer + i*3, pByteBuffer[i], 3);
			}

			BITMAPINFO bm;
			memset(&bm, 0, sizeof(BITMAPINFO));
			bm.bmiHeader = bmInfo;
			Bitmap* bmp = Bitmap::FromBITMAPINFO(&bm,pBuffer);

			CLSID pngClsid;	
			if( sFileExt == "raw")
			{			
				CFile oFile;
				CFileException ex;
				BOOL bflagOpen = oFile.Open(FullPath, CFile::modeWrite | CFile::modeCreate, &ex);
				if(bflagOpen)
				{
					UINT nLength = m_pDataSet->GetSize().ndx*m_pDataSet->GetSize().ndy;
					oFile.Write(pByteBuffer, nLength);		
					oFile.Flush();
					oFile.Close();
				}	
			}
			else if(sFileExt == "bmp")
			{
				CUtility::GetEncoderClsid(L"image/bmp", &pngClsid);
				bmp->Save(FullPath, &pngClsid, NULL);
			}
			else if(sFileExt == "jpg")
			{
				CUtility::GetEncoderClsid(L"image/jpeg", &pngClsid);
				bmp->Save(FullPath, &pngClsid, NULL);			
			}
		}
	}

	delete[] pBuffer;
	delete[] pByteBuffer;

	//Re update m_pSourceByteImg slice back to current slice
	UpdateSourceSlice();
	
}
Esempio n. 18
0
P(GmMaterial) GmUtil::createGmMaterial( Mtl* material, Mtl* bakedmaterial )
{
	require( material );

	P(GmMaterial) s = new GmMaterial;

	// get name
	static int unnamedCount = 0;
	if ( material->GetName().data() )
		s->name = material->GetName().data();
	else
		s->name = "noname #"+String::valueOf( ++unnamedCount );

	// Standard material (+Diffuse) (+ Reflection)
	if ( material->ClassID() == Class_ID(DMTL_CLASS_ID,0) )
	{
		StdMat* stdmat		= static_cast<StdMat*>(material);
	    StdMat* bakedmat	= static_cast<StdMat*>(bakedmaterial);

		// StdMat2?
		StdMat2* stdmat2 = 0;
		if ( stdmat->SupportsShaders() )
			stdmat2 = static_cast<StdMat2*>( stdmat );

		// uniform transparency
		s->opacity = stdmat->GetOpacity(0);

		// self illumination
		s->selfIllum = stdmat->GetSelfIllum(0);

		// two-sided material?
		s->twosided = ( 0 != stdmat->GetTwoSided() );

		// blending mode
		s->blend = GmMaterial::BLEND_COPY;
		if ( s->opacity < 1.f )
			s->blend = GmMaterial::BLEND_MULTIPLY;
		if ( stdmat->GetTransparencyType() == TRANSP_ADDITIVE )
			s->blend = GmMaterial::BLEND_ADD;

		// diffuse color
		s->diffuseColor = toColorf( stdmat->GetDiffuse(0) );

		// specular highlights
		float shinStr = stdmat->GetShinStr(0);
		s->specular = (shinStr > 0.f);
		if ( s->specular )
		{
			float shininess = stdmat->GetShininess(0);
			s->specularExponent = Math::pow( 2.f, shininess*10.f + 2.f );
			s->specularColor = toColorf( stdmat->GetSpecular(0) ) * shinStr;
		}
		if ( bakedmat )
		{
			shinStr = bakedmat->GetShinStr(0);
			s->specular = (shinStr > 0.f);
			if ( s->specular )
			{
				float shininess = bakedmat->GetShininess(0);
				s->specularExponent = Math::pow( 2.f, shininess*10.f + 2.f );
				s->specularColor = toColorf( bakedmat->GetSpecular(0) ) * shinStr;
			}
		}

		// diffuse texture layer
		BitmapTex* tex	= SceneExportUtil::getStdMatBitmapTex( stdmat, ID_DI );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->diffuseLayer;
			setLayerTex( layer, tex, s->name );
		}

		// opacity texture layer
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_OP );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->opacityLayer;
			setLayerTex( layer, tex, s->name );

			// check alpha channel validity
			Bitmap* bmp = tex->GetBitmap(0);
			if ( bmp && !bmp->HasAlpha() )
				Debug::printlnError( "Material \"{0}\" opacity map \"{1}\" must have image alpha channel.", s->name, tex->GetMapName() );
				//throw IOException( Format("Material \"{0}\" opacity map \"{1}\" must have image alpha channel.", s->name, tex->GetMapName()) );
			s->blend = GmMaterial::BLEND_MULTIPLY;

			// check that opacity map is the same as diffuse map
			if ( s->opacityLayer.filename != s->diffuseLayer.filename )
				throw IOException( Format("Material \"{0}\" diffuse bitmap needs to be the same in opacity map.(diffuse map is \"{1}\" and opacity map is \"{2}\")", s->name, s->diffuseLayer.filename, s->opacityLayer.filename) );
			if ( s->opacityLayer.coordset != s->diffuseLayer.coordset )
				throw IOException( Format("Material \"{0}\" diffuse map texture coordinate set needs to be the same in opacity map.", s->name) );
			if ( s->opacityLayer.env != s->diffuseLayer.env )
				throw IOException( Format("Material \"{0}\" diffuse map texture coordinate generator needs to be the same in opacity map.", s->name) );
		}

		// reflection texture layer
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_RL );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->reflectionLayer;
			setLayerTex( layer, tex, s->name );
		}

		// glossiness (shininess strength, SS) texture layer
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_SS );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->glossinessLayer;
			setLayerTex( layer, tex, s->name );

			// check alpha channel validity
			Bitmap* bmp = tex->GetBitmap(0);
			//if ( bmp && !bmp->HasAlpha() )
			//	throw IOException( Format("Material \"{0}\" glossiness map \"{1}\" must have image alpha channel.", s->name, tex->GetMapName()) );
			if ( bmp && !bmp->HasAlpha() )
				Debug::printlnError("Material \"{0}\" glossiness map \"{1}\" must have image alpha channel.", s->name, tex->GetMapName() );

			// check that glossiness map is the same as diffuse map
			if ( s->glossinessLayer.filename != s->diffuseLayer.filename )
				throw IOException( Format("Material \"{0}\" diffuse bitmap needs to be the same in glossiness map.(diffuse map is \"{1}\" and glossiness map is \"{2}\")", s->name, s->diffuseLayer.filename, s->glossinessLayer.filename) );
			if ( s->glossinessLayer.coordset != s->diffuseLayer.coordset )
				throw IOException( Format("Material \"{0}\" diffuse map texture coordinate set needs to be the same in glossiness map.", s->name) );
			if ( s->glossinessLayer.env != s->diffuseLayer.env )
				throw IOException( Format("Material \"{0}\" diffuse map texture coordinate generator needs to be the same in glossiness map.", s->name) );

			// check that reflection map has been set
			if ( s->reflectionLayer.filename.length() == 0 )
				throw IOException( Format("Material \"{0}\" glossiness map requires reflection map to be set.", s->name) );
		}

		// bump texture layer
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_BU );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->bumpLayer;
			setLayerTex( layer, tex, s->name );
		}

		// specular color texture layer
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_SP );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->specularColorLayer;
			setLayerTex( layer, tex, s->name );
		}

		// specular level texture layer
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_SH );
		if ( tex )
		{
			GmMaterial::TextureLayer& layer = s->specularLevelLayer;
			setLayerTex( layer, tex, s->name );
		}

		// lightmap texture layer ( from self-illumination map of baked material )
		tex = SceneExportUtil::getStdMatBitmapTex( stdmat, ID_SI );
		BitmapTex* tex2 = 0;
		if ( bakedmat ) 
			tex2 = SceneExportUtil::getStdMatBitmapTex( bakedmat, ID_SI );
		
		if ( tex || tex2 )
		{
			GmMaterial::TextureLayer& layer = s->lightMapLayer;
	
			if ( tex && !tex2 )
				setLayerTex( layer, tex, s->name );
			else if ( tex2 )
				setLayerTex( layer, tex2, s->name );
		}
	}

	return s;
}
Esempio n. 19
0
int InventoryScreen::Redraw()
{
    Bitmap *ds = GetVirtualScreen();

    numitems=0;
    widest=0;
    highest=0;
    if (charextra[game.playercharacter].invorder_count < 0)
        update_invorder();
    if (charextra[game.playercharacter].invorder_count == 0) {
        DisplayMessage(996);
        in_inv_screen--;
        return -1;
    }

    if (inv_screen_newroom >= 0) {
        in_inv_screen--;
        NewRoom(inv_screen_newroom);
        return -1;
    }

    for (int i = 0; i < charextra[game.playercharacter].invorder_count; ++i) {
        if (game.invinfo[charextra[game.playercharacter].invorder[i]].name[0]!=0) {
            dii[numitems].num = charextra[game.playercharacter].invorder[i];
            dii[numitems].sprnum = game.invinfo[charextra[game.playercharacter].invorder[i]].pic;
            int snn=dii[numitems].sprnum;
            if (spritewidth[snn] > widest) widest=spritewidth[snn];
            if (spriteheight[snn] > highest) highest=spriteheight[snn];
            numitems++;
        }
    }
    if (numitems != charextra[game.playercharacter].invorder_count)
        quit("inconsistent inventory calculations");

    widest += get_fixed_pixel_size(4);
    highest += get_fixed_pixel_size(4);
    num_visible_items = (MAX_ITEMAREA_HEIGHT / highest) * ICONSPERLINE;

    windowhit = highest * (numitems/ICONSPERLINE) + get_fixed_pixel_size(4);
    if ((numitems%ICONSPERLINE) !=0) windowhit+=highest;
    if (windowhit > MAX_ITEMAREA_HEIGHT) {
        windowhit = (MAX_ITEMAREA_HEIGHT / highest) * highest + get_fixed_pixel_size(4);
    }
    windowhit += BUTTONAREAHEIGHT;

    windowwid = widest*ICONSPERLINE + get_fixed_pixel_size(4);
    if (windowwid < get_fixed_pixel_size(105)) windowwid = get_fixed_pixel_size(105);
    windowxp=play.viewport.GetWidth()/2-windowwid/2;
    windowyp=play.viewport.GetHeight()/2-windowhit/2;
    buttonyp=windowyp+windowhit-BUTTONAREAHEIGHT;
    color_t draw_color = ds->GetCompatibleColor(play.sierra_inv_color);
    ds->FillRect(Rect(windowxp,windowyp,windowxp+windowwid,windowyp+windowhit), draw_color);
    draw_color = ds->GetCompatibleColor(0); 
    bartop = windowyp + get_fixed_pixel_size(2);
    barxp = windowxp + get_fixed_pixel_size(2);
    ds->FillRect(Rect(barxp,bartop, windowxp + windowwid - get_fixed_pixel_size(2),buttonyp-1), draw_color);
    for (int i = top_item; i < numitems; ++i) {
        if (i >= top_item + num_visible_items)
            break;
        Bitmap *spof=spriteset[dii[i].sprnum];
        wputblock(ds, barxp+1+((i-top_item)%4)*widest+widest/2-spof->GetWidth()/2,
            bartop+1+((i-top_item)/4)*highest+highest/2-spof->GetHeight()/2,spof,1);
    }
#define BUTTONWID Math::Max(1, spritewidth[btn_select_sprite])
    // Draw select, look and OK buttons
    wputblock(ds, windowxp+2, buttonyp + get_fixed_pixel_size(2), spriteset[btn_look_sprite], 1);
    wputblock(ds, windowxp+3+BUTTONWID, buttonyp + get_fixed_pixel_size(2), spriteset[btn_select_sprite], 1);
    wputblock(ds, windowxp+4+BUTTONWID*2, buttonyp + get_fixed_pixel_size(2), spriteset[btn_ok_sprite], 1);

    // Draw Up and Down buttons if required
    Bitmap *arrowblock = BitmapHelper::CreateTransparentBitmap (ARROWBUTTONWID, ARROWBUTTONWID);
    draw_color = arrowblock->GetCompatibleColor(0);
    if (play.sierra_inv_color == 0)
        draw_color = ds->GetCompatibleColor(14);

    arrowblock->DrawLine(Line(ARROWBUTTONWID/2, 2, ARROWBUTTONWID-2, 9), draw_color);
    arrowblock->DrawLine(Line(ARROWBUTTONWID/2, 2, 2, 9), draw_color);
    arrowblock->DrawLine(Line(2, 9, ARROWBUTTONWID-2, 9), draw_color);
	arrowblock->FloodFill(ARROWBUTTONWID/2, 4, draw_color);

    if (top_item > 0)
        wputblock(ds, windowxp+windowwid-ARROWBUTTONWID, buttonyp + get_fixed_pixel_size(2), arrowblock, 1);
    if (top_item + num_visible_items < numitems)
        arrowblock->FlipBlt(arrowblock, windowxp+windowwid-ARROWBUTTONWID, buttonyp + get_fixed_pixel_size(4) + ARROWBUTTONWID, Common::kBitmap_VFlip);
    delete arrowblock;

    //domouse(1);
    set_mouse_cursor(cmode);
    wasonitem=-1;

    prepare_gui_screen(windowxp, windowyp, windowwid, windowhit, true);
    return 0;
}
Esempio n. 20
0
/*
// [DEPRECATED]
void GetGlobalString (int index, char *strval) {
    if ((index<0) | (index >= MAXGLOBALSTRINGS))
        quit("!GetGlobalString: invalid index");
    strcpy (strval, play.globalstrings[index]);
}
*/
int RunAGSGame (const char *newgame, unsigned int mode, int data) {

    can_run_delayed_command();

    int AllowedModes = RAGMODE_PRESERVEGLOBALINT | RAGMODE_LOADNOW;

    if ((mode & (~AllowedModes)) != 0)
        quit("!RunAGSGame: mode value unknown");

    if (editor_debugging_enabled)
    {
        quit("!RunAGSGame cannot be used while running the game from within the AGS Editor. You must build the game EXE and run it from there to use this function.");
    }

    if ((mode & RAGMODE_LOADNOW) == 0) {
        // need to copy, since the script gets destroyed
        get_install_dir_path(gamefilenamebuf, newgame);
        game_file_name = gamefilenamebuf;
        usetup.main_data_filename = game_file_name;
        play.takeover_data = data;
        load_new_game_restore = -1;

        if (inside_script) {
            curscript->queue_action(ePSARunAGSGame, mode | RAGMODE_LOADNOW, "RunAGSGame");
            ccInstance::GetCurrentInstance()->Abort();
        }
        else
            load_new_game = mode | RAGMODE_LOADNOW;

        return 0;
    }

    int ee;

    unload_old_room();
    displayed_room = -10;

    unload_game_file();

    if (Common::AssetManager::SetDataFile(game_file_name) != Common::kAssetNoError)
        quitprintf("!RunAGSGame: unable to load new game file '%s'", game_file_name.GetCStr());

    Bitmap *ds = GetVirtualScreen();
    ds->Fill(0);
    show_preload();

    HError err = load_game_file();
    if (!err)
        quitprintf("!RunAGSGame: error loading new game file:\n%s", err->FullMessage().GetCStr());

    spriteset.reset();
    if (spriteset.initFile ("acsprset.spr"))
        quit("!RunAGSGame: error loading new sprites");

    if ((mode & RAGMODE_PRESERVEGLOBALINT) == 0) {
        // reset GlobalInts
        for (ee = 0; ee < MAXGSVALUES; ee++)
            play.globalscriptvars[ee] = 0;  
    }

    engine_init_game_settings();
    play.screen_is_faded_out = 1;

    if (load_new_game_restore >= 0) {
        try_restore_save(load_new_game_restore);
        load_new_game_restore = -1;
    }
    else
        start_game();

    return 0;
}
Esempio n. 21
0
void 
dlgWayPointDetailsShowModal(SingleWindow &parent, const Waypoint& way_point)
{
  selected_waypoint = &way_point;

  TCHAR sTmp[128];
  double sunsettime;
  int sunsethours;
  int sunsetmins;
  WndProperty *wp;

  if (Layout::landscape)
    wf = LoadDialog(CallBackTable,
                        parent, _T("IDR_XML_WAYPOINTDETAILS_L"));
  else
    wf = LoadDialog(CallBackTable,
                        parent, _T("IDR_XML_WAYPOINTDETAILS"));

  nTextLines = 0;

  if (!wf)
    return;

  Profile::GetPath(szProfileWayPointFile, szWaypointFile);
  ExtractDirectory(Directory, szWaypointFile);

  _stprintf(path_modis, _T("%s" DIR_SEPARATOR_S "modis-%03d.jpg"),
           Directory,
           selected_waypoint->id+1);
  _stprintf(path_google,_T("%s" DIR_SEPARATOR_S "google-%03d.jpg"),
           Directory,
           selected_waypoint->id+1);

  _stprintf(sTmp, _T("%s: '%s'"), wf->GetCaption(), selected_waypoint->Name.c_str());
  wf->SetCaption(sTmp);

  wp = ((WndProperty *)wf->FindByName(_T("prpWpComment")));
  wp->SetText(selected_waypoint->Comment.c_str());

  Units::LongitudeToString(selected_waypoint->Location.Longitude, sTmp, sizeof(sTmp)-1);
  ((WndProperty *)wf->FindByName(_T("prpLongitude")))
    ->SetText(sTmp);

  Units::LatitudeToString(selected_waypoint->Location.Latitude, sTmp, sizeof(sTmp)-1);
  ((WndProperty *)wf->FindByName(_T("prpLatitude")))
    ->SetText(sTmp);

  Units::FormatUserAltitude(selected_waypoint->Altitude, sTmp, sizeof(sTmp)-1);
  ((WndProperty *)wf->FindByName(_T("prpAltitude")))
    ->SetText(sTmp);

  SunEphemeris sun;
  sunsettime = sun.CalcSunTimes
    (selected_waypoint->Location,
     XCSoarInterface::Basic().DateTime,
     GetUTCOffset()/3600);

  sunsethours = (int)sunsettime;
  sunsetmins = (int)((sunsettime - sunsethours) * 60);

  _stprintf(sTmp, _T("%02d:%02d"), sunsethours, sunsetmins);
  ((WndProperty *)wf->FindByName(_T("prpSunset")))->SetText(sTmp);

  fixed distance;
  Angle bearing;
  DistanceBearing(XCSoarInterface::Basic().Location,
                  selected_waypoint->Location,
                  &distance,
                  &bearing);

  TCHAR DistanceText[MAX_PATH];
  Units::FormatUserDistance(distance, DistanceText, 10);
  ((WndProperty *)wf->FindByName(_T("prpDistance"))) ->SetText(DistanceText);

  _stprintf(sTmp, _T("%d")_T(DEG), iround(bearing.value_degrees()));
  ((WndProperty *)wf->FindByName(_T("prpBearing"))) ->SetText(sTmp);

  GlidePolar glide_polar = protected_task_manager.get_glide_polar();
  GlidePolar safety_polar = protected_task_manager.get_safety_polar();

  UnorderedTaskPoint t(way_point, XCSoarInterface::SettingsComputer());
  GlideResult r;

  // alt reqd at current mc

  const AIRCRAFT_STATE aircraft_state =
    ToAircraftState(XCSoarInterface::Basic());
  r = TaskSolution::glide_solution_remaining(t, aircraft_state, glide_polar);
  wp = (WndProperty *)wf->FindByName(_T("prpMc2"));
  if (wp) {
    _stprintf(sTmp, _T("%.0f %s"),
              (double)Units::ToUserAltitude(r.AltitudeDifference),
              Units::GetAltitudeName());
    wp->SetText(sTmp);
  }

  // alt reqd at mc 0

  glide_polar.set_mc(fixed_zero);
  r = TaskSolution::glide_solution_remaining(t, aircraft_state, glide_polar);
  wp = (WndProperty *)wf->FindByName(_T("prpMc0"));
  if (wp) {
    _stprintf(sTmp, _T("%.0f %s"),
              (double)Units::ToUserAltitude(r.AltitudeDifference),
              Units::GetAltitudeName());
    wp->SetText(sTmp);
  }

  // alt reqd at safety mc

  r = TaskSolution::glide_solution_remaining(t, aircraft_state, safety_polar);
  wp = (WndProperty *)wf->FindByName(_T("prpMc1"));
  if (wp) {
    _stprintf(sTmp, _T("%.0f %s"),
              (double)Units::ToUserAltitude(r.AltitudeDifference),
              Units::GetAltitudeName());
    wp->SetText(sTmp);
  }

  wf->SetKeyDownNotify(FormKeyDown);

  ((WndButton *)wf->FindByName(_T("cmdClose")))->SetOnClickNotify(OnCloseClicked);

  wInfo = ((WndFrame *)wf->FindByName(_T("frmInfos")));
  wCommand = ((WndFrame *)wf->FindByName(_T("frmCommands")));
  wSpecial = ((WndFrame *)wf->FindByName(_T("frmSpecial")));
  wImage = ((WndOwnerDrawFrame *)wf->FindByName(_T("frmImage")));
  wDetails = (WndListFrame*)wf->FindByName(_T("frmDetails"));
  wDetails->SetPaintItemCallback(OnPaintDetailsListItem);

  assert(wInfo != NULL);
  assert(wCommand != NULL);
  assert(wSpecial != NULL);
  assert(wImage != NULL);
  assert(wDetails != NULL);

  nTextLines = TextToLineOffsets(way_point.Details.c_str(), LineOffsets, MAXLINES);
  wDetails->SetLength(nTextLines);

  /*
  TODO enhancement: wpdetails
  wp = ((WndProperty *)wf->FindByName(_T("prpWpDetails")));
  wp->SetText(way_point.Details);
  */

  wCommand->hide();
  wSpecial->hide();
  wImage->SetCaption(_("Blank!"));
  wImage->SetOnPaintNotify(OnImagePaint);

  WndButton *wb;

  wb = ((WndButton *)wf->FindByName(_T("cmdGoto")));
  if (wb)
    wb->SetOnClickNotify(OnGotoClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdReplace")));
  if (wb)
    wb->SetOnClickNotify(OnReplaceClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdNewHome")));
  if (wb)
    wb->SetOnClickNotify(OnNewHomeClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdSetAlternate1")));
  if (wb)
    wb->SetOnClickNotify(OnSetAlternate1Clicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdSetAlternate2")));
  if (wb)
    wb->SetOnClickNotify(OnSetAlternate2Clicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdClearAlternates")));
  if (wb)
    wb->SetOnClickNotify(OnClearAlternatesClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdTeamCode")));
  if (wb)
    wb->SetOnClickNotify(OnTeamCodeClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdInserInTask")));
  if (wb)
    wb->SetOnClickNotify(OnInsertInTaskClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdAppendInTask")));
  if (wb)
    wb->SetOnClickNotify(OnAppendInTaskClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdRemoveFromTask")));
  if (wb)
    wb->SetOnClickNotify(OnRemoveFromTaskClicked);

  hasimage1 = jpgimage1.load_file(path_modis);
  hasimage2 = jpgimage2.load_file(path_google);

  page = 0;

  NextPage(0); // JMW just to turn proper pages on/off

  wf->ShowModal();

  delete wf;

  wf = NULL;
}
Esempio n. 22
0
/********************************************************************
 GdipBitmapFromResource - read a GDI+ image out of a resource stream

********************************************************************/
extern "C" HRESULT DAPI GdipBitmapFromResource(
    __in_opt HINSTANCE hinst,
    __in_z LPCSTR szId,
    __out Bitmap **ppBitmap
    )
{
    HRESULT hr = S_OK;
    LPVOID pvData = NULL;
    DWORD cbData = 0;
    HGLOBAL hGlobal = NULL;;
    LPVOID pv = NULL;
    IStream *pStream = NULL;
    Bitmap *pBitmap = NULL;
    Status gs = Ok;

    hr = ResReadData(hinst, szId, &pvData, &cbData);
    ExitOnFailure(hr, "Failed to load GDI+ bitmap from resource.");

    // Have to copy the fixed resource data into moveable (heap) memory
    // since that's what GDI+ expects.
    hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, cbData);
    ExitOnNullWithLastError(hGlobal, hr, "Failed to allocate global memory.");

    pv = ::GlobalLock(hGlobal);
    ExitOnNullWithLastError(pv, hr, "Failed to lock global memory.");

    memcpy(pv, pvData, cbData);

    ::GlobalUnlock(pv); // no point taking any more memory than we have already
    pv = NULL;

    hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, &pStream);
    ExitOnFailure(hr, "Failed to allocate stream from global memory.");

    hGlobal = NULL; // we gave the global memory to the stream object so it will close it

    pBitmap = Bitmap::FromStream(pStream);
    ExitOnNull(pBitmap, hr, E_OUTOFMEMORY, "Failed to allocate bitmap from stream.");

    gs = pBitmap->GetLastStatus();
    ExitOnGdipFailure(gs, hr, "Failed to load bitmap from stream.");

    *ppBitmap = pBitmap;
    pBitmap = NULL;

LExit:
    if (pBitmap)
    {
        delete pBitmap;
    }

    ReleaseObject(pStream);

    if (pv)
    {
        ::GlobalUnlock(pv);
    }

    if (hGlobal)
    {
        ::GlobalFree(hGlobal);
    }

    return hr;
}
Esempio n. 23
0
	Bitmap* SoftGlow::Process1(const Bitmap* src, int radius, float sharpness, float brightness)
	{
		assert(src && src->IsValid());

		int width = src->Width();
		int height = src->Height();

		Bitmap* tmp = new Bitmap(width, height, 8);
		assert(tmp);

		for (int y = 0; y < height; y++)
		{
			uint8* p0 = src->Get(0, y);
			uint8* p1 = tmp->Get(0, y);

			for (int x = 0; x < width; x++)
			{
				uint8 b = *(p0 + 0);
				uint8 g = *(p0 + 1);
				uint8 r = *(p0 + 2);

				*p1 = (uint8)rgb_to_l(r, g, b);

				*p1 = (uint8)CalcSharpAndBright(*p1, sharpness, brightness);

				p0 += src->PixelBytes();
				p1 += tmp->PixelBytes();
			}
		}

		Gaussion(tmp, (float)radius);

#ifdef _DEBUG
		tmp->Save("f:\\tmp0.bmp");
#endif
		Bitmap* dst = new Bitmap(src->Width(), src->Height(), src->biBitCount);
		assert(dst);
		int temp;
		for (int y = 0; y < height; y++)
		{
			uint8* p0 = src->Get(0, y);
			uint8* p1 = tmp->Get(0, y);
			uint8* p2 = dst->Get(0, y);

			for (int x = 0; x < width; x++)
			{
				//screen op
				*(p2 + 0) = 255 - INT_MULT((255 - *(p0 + 0)), (255 - *p1), temp);
				*(p2 + 1) = 255 - INT_MULT((255 - *(p0 + 1)), (255 - *p1), temp);
				*(p2 + 2) = 255 - INT_MULT((255 - *(p0 + 2)), (255 - *p1), temp);

				p0 += src->PixelBytes();
				p1 += tmp->PixelBytes();
				p2 += dst->PixelBytes();
			}
		}

		delete tmp;

		return dst;
	}
Esempio n. 24
0
/*
** Draws the meter on the double buffer
**
*/
bool CMeterImage::Draw(Gfx::Canvas& canvas)
{
	if (!CMeter::Draw(canvas)) return false;

	if (m_Image.IsLoaded())
	{
		// Copy the image over the doublebuffer
		Bitmap* drawBitmap = m_Image.GetImage();

		int imageW = drawBitmap->GetWidth();
		int imageH = drawBitmap->GetHeight();

		if (imageW == 0 || imageH == 0 || m_W == 0 || m_H == 0) return true;

		int x = GetX();
		int y = GetY();

		int drawW = m_W;
		int drawH = m_H;

		if (drawW == imageW && drawH == imageH &&
			m_ScaleMargins.left == 0 && m_ScaleMargins.top == 0 && m_ScaleMargins.right == 0 && m_ScaleMargins.bottom == 0)
		{
			canvas.DrawBitmap(drawBitmap, Rect(x, y, drawW, drawH), Rect(0, 0, imageW, imageH));
		}
		else if (m_DrawMode == DRAWMODE_TILE)
		{
			Gdiplus::Graphics& graphics = canvas.BeginGdiplusContext();

			ImageAttributes imgAttr;
			imgAttr.SetWrapMode(WrapModeTile);

			Rect r(x, y, drawW, drawH);
			graphics.DrawImage(drawBitmap, r, 0, 0, drawW, drawH, UnitPixel, &imgAttr);

			canvas.EndGdiplusContext();
		}
		else if (m_DrawMode == DRAWMODE_KEEPRATIO || m_DrawMode == DRAWMODE_KEEPRATIOANDCROP)
		{
			int cropX = 0;
			int cropY = 0;
			int cropW = imageW;
			int cropH = imageH;

			if (m_WDefined && m_HDefined)
			{
				REAL imageRatio = imageW / (REAL)imageH;
				REAL meterRatio = m_W / (REAL)m_H;

				if (imageRatio != meterRatio)
				{
					if (m_DrawMode == DRAWMODE_KEEPRATIO)
					{
						if (imageRatio > meterRatio)
						{
							drawH = m_W * imageH / imageW;
							y += (m_H - drawH) / 2;
						}
						else
						{
							drawW = m_H * imageW / imageH;
							x += (m_W - drawW) / 2;
						}
					}
					else
					{
						if (imageRatio > meterRatio)
						{
							cropW = (int)(imageH * meterRatio);
							cropX = (imageW - cropW) / 2;
						}
						else
						{
							cropH = (int)(imageW / meterRatio);
							cropY = (imageH - cropH) / 2;
						}
					}
				}
			}

			Rect r(x, y, drawW, drawH);
			canvas.DrawBitmap(drawBitmap, r, Rect(cropX, cropY, cropW, cropH));
		}
		else
		{
			const RECT& m = m_ScaleMargins;

			if (m.top > 0)
			{
				if (m.left > 0)
				{
					// Top-Left
					Rect r(x, y, m.left, m.top);
					canvas.DrawBitmap(drawBitmap, r, Rect(0, 0, m.left, m.top));
				}

				// Top
				Rect r(x + m.left, y, drawW - m.left - m.right, m.top);
				canvas.DrawBitmap(drawBitmap, r, Rect(m.left, 0, imageW - m.left - m.right, m.top));

				if (m.right > 0)
				{
					// Top-Right
					Rect r(x + drawW - m.right, y, m.right, m.top);
					canvas.DrawBitmap(drawBitmap, r, Rect(imageW - m.right, 0, m.right, m.top));
				}
			}

			if (m.left > 0)
			{
				// Left
				Rect r(x, y + m.top, m.left, drawH - m.top - m.bottom);
				canvas.DrawBitmap(drawBitmap, r, Rect(0, m.top, m.left, imageH - m.top - m.bottom));
			}

			// Center
			Rect r(x + m.left, y + m.top, drawW - m.left - m.right, drawH - m.top - m.bottom);
			canvas.DrawBitmap(drawBitmap, r, Rect(m.left, m.top, imageW - m.left - m.right, imageH - m.top - m.bottom));

			if (m.right > 0)
			{
				// Right
				Rect r(x + drawW - m.right, y + m.top, m.right, drawH - m.top - m.bottom);
				canvas.DrawBitmap(drawBitmap, r, Rect(imageW - m.right, m.top, m.right, imageH - m.top - m.bottom));
			}

			if (m.bottom > 0)
			{
				if (m.left > 0)
				{
					// Bottom-Left
					Rect r(x, y + drawH - m.bottom, m.left, m.bottom);
					canvas.DrawBitmap(drawBitmap, r, Rect(0, imageH - m.bottom, m.left, m.bottom));
				}

				// Bottom
				Rect r(x + m.left, y + drawH - m.bottom, drawW - m.left - m.right, m.bottom);
				canvas.DrawBitmap(drawBitmap, r, Rect(m.left, imageH - m.bottom, imageW - m.left - m.right, m.bottom));

				if (m.right > 0)
				{
					// Bottom-Right
					Rect r(x + drawW - m.right, y + drawH - m.bottom, m.right, m.bottom);
					canvas.DrawBitmap(drawBitmap, r, Rect(imageW - m.right, imageH - m.bottom, m.right, m.bottom));
				}
			}
		}
	}

	return true;
}
Esempio n. 25
0
		void FreeMap() { if (bm) bm->DeleteThis(); bm = NULL; } 
Esempio n. 26
0
File: Image.cpp Progetto: 456z/gosu
Gosu::Image::Image(Graphics& graphics, const Bitmap& source, bool tileable)
{
	// Forward.
	Image(graphics, source, 0, 0, source.width(), source.height(), tileable).data.swap(data);
}
Esempio n. 27
0
void MarkerTool::highlightRegion(RECT rc)
{
	Bitmap* canvasBm = canvas_->currentDocument()->getBitmap();
	BitmapData canvasData;
	int w = min(canvasBm->GetWidth()-rc.left,rc.right - rc.left);
	int h = min(canvasBm->GetHeight()-rc.top, rc.bottom - rc.top);
	rc.left = max(0,rc.left);
	rc.top = max(0,rc.top);
	Rect rc2 (rc.left , rc.top, w, h);
	segments_.markRect( rc );
	if (canvasBm->LockBits(& rc2, ImageLockModeRead|ImageLockModeWrite, PixelFormat32bppARGB, & canvasData) == Ok) {
		UINT stride;
		uint8_t * source= (uint8_t *) canvasData.Scan0;
		uint8_t * brSource= (uint8_t *) circleData_;
		if (canvasData.Stride > 0) {
			stride = canvasData.Stride;
		} else {
			stride = - canvasData.Stride;
		}
		/*int lum = 0;
		int disp = 0;
		for ( int i =0; i < h; i++ ) {
		for ( int j = 0; j < w; j++ ) {
		int offset = i*stride+j*4;
		int Y = 0.299 * source[offset] + 0.587 * source[offset+1] + 0.114 * source[offset+2];
		lum += Y;
		}
		}

		lum = float(lum) / ( w * h);
		for ( int i =0; i < h; i++ ) {
		for ( int j = 0; j < w; j++ ) {
		int offset = i*stride+j*4;
		int Y = 0.299 * source[offset] + 0.587 * source[offset+1] + 0.114 * source[offset+2];
		if ( abs(Y-lum) > disp ) {
		disp = abs(Y-lum);
		}
		}
		}*/

		for ( int i =0; i < h; i++ ) {
			for ( int j = 0; j < w; j++ ) {
				/*if ( affectedRegion_.IsVisible(i+rc.top, j+rc.left) ) {
				continue;
				}*/
				int offset = i*stride+j*4;
				int circleOffset = i * circleStride_ + j* 4;
				int Y = 0.299 * source[offset] + 0.587 * source[offset+1] + 0.114 * source[offset+2];

				float srcA =  pow(brSource[circleOffset+3]/255.0 * (Y/255.0),15); // why pow 15 ?? I don't know
				uint8_t srcR=  brSource[circleOffset];
				uint8_t srcG=  brSource[circleOffset+1];
				uint8_t srcB=  brSource[circleOffset+2];
				if ( Y != 255 ) {
					srcA = srcA;
				}

				float dstA =  source[offset+3]/255.0;
				uint8_t dstR=  source[offset];
				uint8_t dstG=  source[offset+1];
				uint8_t dstB=  source[offset+2];
				float outA = srcA + dstA*(1-srcA);
				uint8_t outR=  (srcR * srcA + dstR * dstA * ( 1 - srcA))/ outA;
				uint8_t outG=  (srcG * srcA + dstG * dstA* ( 1 - srcA))/ outA;
				uint8_t outB=  (srcB * srcA + dstB * dstA* ( 1 - srcA))/ outA;
				source[offset] = outR;
				source[offset+1] = outG ;
				source[offset+2] = outB;
				source[offset+3] = outA * 255; 

			}
		}

		canvasBm->UnlockBits(&canvasData);
	}

}
Esempio n. 28
0
bool Font::GenerateOpenglGlyphs( std::string configFileName)
{
    unsigned int area = 0;
    Bitmap *bitmap;


    for (auto i = glyphsBitmapList.begin(); i != glyphsBitmapList.end(); i++)
    {
        bitmap = (*i).bitmap;
        area += bitmap->GetHeight() * bitmap->GetWidth();
    }

    unsigned int sideAtlas = (unsigned int)(sqrt( float(area) ));
    sideAtlas = next_p2( sideAtlas );

    float diff = float(sideAtlas * sideAtlas) / float(area);
    if( diff < 1.8f )
        sideAtlas <<= 1;

    if(!glyphAtlas.Create(Bitmap::FORMAT_RGBA, sideAtlas, sideAtlas))
    {
        //LOG_ERROR(
        return false;
    }

    glyphsBitmapList.sort();

    iRect rect;
    Bitmap *atlasBitmap = glyphAtlas.GetAtlas();

    for (auto i = glyphsBitmapList.begin(); i != glyphsBitmapList.end(); i++)
    {
        if( !glyphAtlas.InsertImage( (*i).bitmap, rect ) )
        {
            //LOG(WARNING) << "font atlass ERROR";
            delete (*i).bitmap;
            (*i).bitmap = nullptr;
            continue;
        }

        FontTexture fontTexture;

        fontTexture.width = (*i).bitmap->GetWidth();
        fontTexture.height = (*i).bitmap->GetHeight();
        fontTexture.offsetDown = (*i).offsetDown;

        GenerateTextCoord(atlasBitmap, &rect, fontTexture.texture);

        glyphsTextureMap[(*i).key] = fontTexture;

        delete (*i).bitmap;
        (*i).bitmap = nullptr;
    }

    // CreateAtlasOpenglTexture
    unsigned int ogltexture = GenerateOpenglBitmap(*atlasBitmap, false, false);
    tex = new Texture();
    tex->textureId = ogltexture;
    tex->name = configFileName;
    tex->height = atlasBitmap->GetHeight();
    tex->width = atlasBitmap->GetWidth();
    for (auto i = glyphsTextureMap.begin(); i != glyphsTextureMap.end(); i++)
    {
        (*i).second.texture.textureId = ogltexture;

    }

    glyphsBitmapList.clear();
    glyphAtlas.GetAtlas()->Save(configFileName+".png");

    glyphAtlas.Remove();
    return true;
}
Esempio n. 29
0
unsigned int GenerateOpenglBitmap(Bitmap &bitmap, bool smoothing, bool mipmap)
{
	unsigned int glBitmap = 0;
	glGenTextures(1, &glBitmap);
	glBindTexture(GL_TEXTURE_2D, glBitmap);

	// Когда картинка будет увеличиваться(нет большей Мипмапы), используем LINEAR фильтрацию
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smoothing ? GL_LINEAR : GL_NEAREST);
	
	if(mipmap)
	{
		// Когда минимизируем — берем две ближних мипмапы и лиейно смешиваем цвета
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smoothing ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_NEAREST);
	}
	else
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smoothing ? GL_LINEAR : GL_NEAREST);
	}

	unsigned int format = bitmap.GetFormat();
	unsigned int colorType = GL_RGB;
	switch (format)
	{
	case Bitmap::FORMAT_LUMINANCE:
		{
			colorType = GL_LUMINANCE;
			break;
		}

	case Bitmap::FORMAT_LUMINANCE_ALPHA:
		{
			colorType = GL_LUMINANCE_ALPHA;
			break;
		}

	case Bitmap::FORMAT_RGB:
		{
			colorType = GL_RGB;
			break;
		}

	case Bitmap::FORMAT_RGBA:
		{
			colorType = GL_RGBA;
			break;
		}

	default:
		{
			//LOG(LOG_WARNING, "Generate GLBitmap. Не поддерживаемый тип цвета.");
			break;
		}
	}

	//glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glTexImage2D(GL_TEXTURE_2D, 0, colorType, bitmap.GetWidth(), bitmap.GetHeight(), 0, colorType, GL_UNSIGNED_BYTE, bitmap.GetData());
	//OPENGL_CHECK_ERRORS();

	if(mipmap)
	{
		// Создаем сами мипмапы.
		glGenerateMipmap(GL_TEXTURE_2D);
		//OPENGL_CHECK_ERRORS();
	}

	return glBitmap;
}
Esempio n. 30
0
void DxStdMtl2::LoadTextureData(IHLSLCodeGenerator * codeGen)
{
	Bitmap * bmap;
	BitmapInfo stBI;

	TimeValue t = GetCOREInterface()->GetTime();
	int nWidth,nHeight;

	int numberOfTextures = elementContainer.NumberofElementsByType(EffectElements::kEleTex);
	for(int i=0; i<numberOfTextures;i++)
	{
		bool bBump;
		TextureElement * texEle = static_cast<TextureElement*>(elementContainer.GetElementByType(i,EffectElements::kEleTex));

		TSTR mapType = texEle->GetMapName();
		Texmap *texmap = codeGen->GetShaderDefinedTexmap(map,mapType.data(),bBump);

		if(texmap)
		{
			BMM_Color_64 *p;
			nWidth = nHeight = DIMDEFAULT;
			BitmapDimensions(nWidth,nHeight,texmap);
			// load and create the D3D texture;
/*			if(texmap->ClassID() == Class_ID(BMTEX_CLASS_ID, 0))
			{
				BitmapTex *pBT;
				Bitmap *pTex;
				pBT = (BitmapTex *)texmap;
				pTex = pBT->GetBitmap(t);
				if (pTex)
				{
					nWidth = getClosestPowerOf2(pTex->Width());
					nHeight = getClosestPowerOf2(pTex->Height());
				}

			}
*/				
			stBI.SetType(BMM_TRUE_32);
			stBI.SetWidth(nWidth);
			stBI.SetHeight(nHeight);        
			bmap = TheManager->Create(&stBI);

			if (bmap)
			{
//				LPDIRECT3DTEXTURE9 pRenderTex = texEle->GetD3DTexture();

				texmap->RenderBitmap(t, bmap, MAPSCALE3D * 2.0f);
				p = new BMM_Color_64[nWidth*nHeight];

				for (int y = 0; y < nHeight; y++)
					bmap->GetLinearPixels(0, y, nWidth, p + y * nWidth);
			
				if(texEle->pTex)
				{
					D3DSURFACE_DESC stLD;
					texEle->pTex->GetLevelDesc(0, &stLD);
					if (stLD.Width != nWidth || stLD.Height != nHeight)
					{
						SAFE_RELEASE(texEle->pTex);
					}

				}
				if(!texEle->pTex)
					pd3dDevice->CreateTexture(nWidth,nHeight, 0,D3DUSAGE_AUTOGENMIPMAP,	D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&texEle->pTex, NULL);

				if(texEle->pTex)
				{
					PIXELFMT *pT;
					D3DLOCKED_RECT stLR;
					texEle->pTex->LockRect(0, &stLR, 0, 0);
					pT = (PIXELFMT *)stLR.pBits;

					for (int i = 0; i < nWidth * nHeight; i++)
					{
						pT[i].r = p[i].r >> 8;
						pT[i].g = p[i].g >> 8;
						pT[i].b = p[i].b >> 8;
						pT[i].a = p[i].a >> 8;
					}
					texEle->pTex->UnlockRect(0);
				
					if(bBump && texmap->ClassID() != GNORMAL_CLASS_ID)
					{
//						LPDIRECT3DTEXTURE9 normalTex = texEle->GetD3DBumpTexture();
						
						if(texEle->pBumpTex)
						{
							D3DSURFACE_DESC stLD;
							texEle->pBumpTex->GetLevelDesc(0, &stLD);
							if (stLD.Width != nWidth || stLD.Height != nHeight)
							{
								SAFE_RELEASE(texEle->pBumpTex);
							}
						}
						if(!texEle->pBumpTex)
							pd3dDevice->CreateTexture(nWidth,nHeight, 0,D3DUSAGE_AUTOGENMIPMAP,	D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&texEle->pBumpTex, NULL);

						D3DXComputeNormalMap(texEle->pBumpTex,texEle->pTex,NULL, NULL, D3DX_CHANNEL_RED,30.0f);

						if(texEle->GetParamHandle())
						{
							pEffectParser->LoadTexture(texEle->pBumpTex, texEle->GetParameterName());
//							pEffect->SetTexture(texEle->GetParamHandle(),texEle->pBumpTex);
//							D3DXSaveTextureToFile("c:\\temp\\normal_notgnormal.dds", D3DXIFF_DDS, texEle->pBumpTex, NULL);
							SAFE_RELEASE(texEle->pBumpTex);
						}
					}
					else
					{
						if(texEle->GetParamHandle())
						{
							pEffectParser->LoadTexture(texEle->pTex, texEle->GetParameterName());
//							pEffect->SetTexture(texEle->GetParamHandle(),texEle->pTex);
//							D3DXSaveTextureToFile("c:\\temp\\normal_gnormal.dds", D3DXIFF_DDS, texEle->pTex, NULL);
							SAFE_RELEASE(texEle->pTex);
						}

					}
				}
				bmap->DeleteThis();

			}
			delete p;
		}
		else
		{