// Called by Rocket when a texture is required to be built from an internally-generated sequence of pixels. bool GuiRenderer::GenerateTexture(Rocket::Core::TextureHandle& textureHandle, const unsigned char* source, const Rocket::Core::Vector2i& sourceDimensions) { // Create a Direct3DTexture9, which will be set as the texture handle. Note that we only create one surface for // this texture; because we're rendering in a 2D context, mip-maps are not required. IDirect3DTexture9* texture; guiManager->getGraphicsDevice().resource->CreateTexture(sourceDimensions.x, sourceDimensions.y, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &texture, NULL); // Lock the top surface and write the pixel data onto it. D3DLOCKED_RECT lockedRect; texture->LockRect(0, &lockedRect, 0, 0); for (int y = 0; y < sourceDimensions.y; ++y) { for (int x = 0; x < sourceDimensions.x; ++x) { const unsigned char* sourcePixel = source + (sourceDimensions.x * 4 * y) + (x * 4); unsigned char* destinationPixel = ((unsigned char*) lockedRect.pBits) + lockedRect.Pitch * y + x * 4; destinationPixel[0] = sourcePixel[2]; destinationPixel[1] = sourcePixel[1]; destinationPixel[2] = sourcePixel[0]; destinationPixel[3] = sourcePixel[3]; } } texture->UnlockRect(0); // Set the handle on the Rocket texture structure. textureHandle = (Rocket::Core::TextureHandle)texture; return true; }
void D3D9Blit(const IntRect& dstRect, unsigned char* src, unsigned srcStride, bool discard = false) { RECT d3dRect; d3dRect.left = dstRect.left_; d3dRect.top = dstRect.top_; d3dRect.right = dstRect.right_; d3dRect.bottom = dstRect.bottom_; int level = 0; DWORD flags = discard ? D3DLOCK_DISCARD : 0; D3DLOCKED_RECT d3dLockedRect; IDirect3DTexture9* object = (IDirect3DTexture9*) webTexture2D_->GetTexture2D()->GetGPUObject(); if (FAILED(object->LockRect(level, &d3dLockedRect, (flags & D3DLOCK_DISCARD) ? 0 : &d3dRect, flags))) { LOGERROR("WebTexture2D - Could not lock texture"); return; } int width = dstRect.Width(); int height = dstRect.Height(); for (int j = 0; j < height; ++j) { unsigned char* dst = (unsigned char*) d3dLockedRect.pBits + j * d3dLockedRect.Pitch; memcpy(dst, src, width * 4); src += srcStride; } object->UnlockRect(level); }
// interface functions void MFTexture_CreatePlatformSpecific(MFTexture *pTexture, bool generateMipChain) { MFCALLSTACK; HRESULT hr; MFTextureTemplateData *pTemplate = pTexture->pTemplateData; // create texture D3DFORMAT platformFormat = (D3DFORMAT)MFTexture_GetPlatformFormatID(pTemplate->imageFormat, MFDD_D3D9); hr = D3DXCreateTexture(pd3dDevice, pTemplate->pSurfaces[0].width, pTemplate->pSurfaces[0].height, generateMipChain ? 0 : 1, 0, platformFormat, D3DPOOL_MANAGED, (IDirect3DTexture9**)&pTexture->pInternalData); MFDebug_Assert(hr != D3DERR_NOTAVAILABLE, MFStr("LoadTexture failed: D3DERR_NOTAVAILABLE, 0x%08X", hr)); MFDebug_Assert(hr != D3DERR_OUTOFVIDEOMEMORY, MFStr("LoadTexture failed: D3DERR_OUTOFVIDEOMEMORY, 0x%08X", hr)); MFDebug_Assert(hr != D3DERR_INVALIDCALL, MFStr("LoadTexture failed: D3DERR_INVALIDCALL, 0x%08X", hr)); MFDebug_Assert(hr != D3DXERR_INVALIDDATA, MFStr("LoadTexture failed: D3DXERR_INVALIDDATA, 0x%08X", hr)); MFDebug_Assert(hr == D3D_OK, MFStr("Failed to create texture '%s'.", pTexture->name)); IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData; // copy image data D3DLOCKED_RECT rect; pTex->LockRect(0, &rect, NULL, 0); MFCopyMemory(rect.pBits, pTemplate->pSurfaces[0].pImageData, pTemplate->pSurfaces[0].bufferLength); pTex->UnlockRect(0); // filter mip levels if(generateMipChain) D3DXFilterTexture(pTex, NULL, 0, D3DX_DEFAULT); }
static IDirect3DTexture9 *BindFont(IDirect3DDevice9 *_Dev, const CTexFont *_Font) { assert(_Font!=NULL); IDirect3DTexture9 *Tex = NULL; IDirect3DDevice9Ex *D3DDev9Ex = NULL; bool IsD3DDev9Ex = SUCCEEDED(_Dev->QueryInterface(__uuidof(IDirect3DDevice9Ex), (void **)&D3DDev9Ex)) && D3DDev9Ex != NULL; HRESULT hr; if (IsD3DDev9Ex) { hr = _Dev->CreateTexture(_Font->m_TexWidth, _Font->m_TexHeight, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &Tex, NULL); D3DDev9Ex->Release(); } else hr = _Dev->CreateTexture(_Font->m_TexWidth, _Font->m_TexHeight, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &Tex, NULL); if( FAILED(hr) ) return NULL; D3DLOCKED_RECT r; hr = Tex->LockRect(0, &r, NULL, 0); if( SUCCEEDED(hr) ) { color32 *p = static_cast<color32 *>(r.pBits); for( int i=0; i<_Font->m_TexWidth*_Font->m_TexHeight; ++i, ++p ) *p = 0x00ffffff | (((color32)(_Font->m_TexBytes[i]))<<24); Tex->UnlockRect(0); } return Tex; }
void LoadImage(char *buf, int sizeBuf, int &width, int &height, uint8 ** ppBuffer, bool bAlpha) { #ifdef USE_DIRECTX_RENDERER HRESULT hr; D3DSURFACE_DESC desc; IDirect3DTexture9* pTexture = NULL; D3DFORMAT d3dFormat; if (bAlpha) d3dFormat = D3DFMT_A8R8G8B8; else d3dFormat = D3DFMT_R8G8B8; // read from file hr = D3DXCreateTextureFromFileInMemoryEx( CGlobals::GetRenderDevice(), buf, sizeBuf, 0, 0, 1, 0, d3dFormat, D3DPOOL_SCRATCH, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, NULL, NULL, &pTexture ); if( FAILED(hr) ) return; pTexture->GetLevelDesc( 0, &desc ); // set size width = desc.Width; height = desc.Height; uint8 *pBufferTemp; int nSize; if (bAlpha) nSize = width * height * 4; else nSize = width * height * 3; pBufferTemp = new uint8[nSize]; D3DLOCKED_RECT lockedRect; hr = pTexture->LockRect( 0, &lockedRect, NULL, D3DLOCK_READONLY ); if( SUCCEEDED(hr) ) { uint8 *pImagePixels = (uint8 *) lockedRect.pBits; memcpy(pBufferTemp, pImagePixels, nSize); // *ppBuffer = pBufferTemp; pTexture->UnlockRect( 0 ); } else { width = 0; height = 0; *ppBuffer = NULL; } SAFE_RELEASE( pTexture ); #endif }
void Console::initialize(IDirect3DDevice9* device, int w, int h) { SDLOG(0, "Initializing Console on device %p\n", device); width = w; height = h; this->device = device; // Create font SDLOG(2, " - creating console font\n"); SAFERELEASE(fontTex); FILE* ff = fopen(getAssetFileName("font.ttf").c_str(), "rb"); unsigned char* ttf_buffer = new unsigned char[1<<20]; unsigned char* temp_bitmap = new unsigned char[BMPSIZE*BMPSIZE]; fread(ttf_buffer, 1, 1<<20, ff); fclose(ff); stbtt_BakeFontBitmap(ttf_buffer, 0, 40.0, temp_bitmap, BMPSIZE, BMPSIZE, 32, 96, cdata); // no guarantee this fits! device->CreateTexture(BMPSIZE, BMPSIZE, 0, D3DUSAGE_AUTOGENMIPMAP, D3DFMT_A8, D3DPOOL_DEFAULT, &fontTex, NULL); IDirect3DTexture9 *tempTex; device->CreateTexture(BMPSIZE, BMPSIZE, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_SYSTEMMEM, &tempTex, NULL); D3DLOCKED_RECT rect; tempTex->LockRect(0, &rect, NULL, 0); memcpy(rect.pBits, temp_bitmap, BMPSIZE*BMPSIZE); tempTex->UnlockRect(0); device->UpdateTexture(tempTex, fontTex); tempTex->Release(); delete ttf_buffer; delete temp_bitmap; // Create vertex decl SDLOG(2, " - creating console vertex decl\n"); SAFERELEASE(vertexDeclaration); device->CreateVertexDeclaration(vertexElements , &vertexDeclaration); // Load effect from file SDLOG(2, " - loading console effect file\n"); SAFERELEASE(effect); vector<D3DXMACRO> defines; std::stringstream s; D3DXMACRO null = { NULL, NULL }; defines.push_back(null); DWORD flags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_OPTIMIZATION_LEVEL3; SDLOG(2, " - actually load effect\n"); ID3DXBuffer* errors; HRESULT hr = D3DXCreateEffectFromFile(device, getAssetFileName("console.fx").c_str(), &defines.front(), NULL, flags, NULL, &effect, &errors); if(hr != D3D_OK) SDLOG(0, "ERRORS:\n %s\n", errors->GetBufferPointer()); // get handles rectColorHandle = effect->GetParameterByName(NULL, "rectColor"); textTex2DHandle = effect->GetParameterByName(NULL, "textTex2D"); SDLOG(0, " - done\n"); }
void RageDisplay_D3D::UpdateTexture( unsigned uTexHandle, RageSurface* img, int xoffset, int yoffset, int width, int height ) { IDirect3DTexture9* pTex = (IDirect3DTexture9*)uTexHandle; ASSERT( pTex != NULL ); RECT rect; rect.left = xoffset; rect.top = yoffset; rect.right = width - xoffset; rect.bottom = height - yoffset; D3DLOCKED_RECT lr; pTex->LockRect( 0, &lr, &rect, 0 ); D3DSURFACE_DESC desc; pTex->GetLevelDesc(0, &desc); ASSERT( xoffset+width <= int(desc.Width) ); ASSERT( yoffset+height <= int(desc.Height) ); // // Copy bits // #if defined(XBOX) // Xbox textures need to be swizzled XGSwizzleRect( img->pixels, // pSource, img->pitch, // Pitch, NULL, // pRect, lr.pBits, // pDest, img->w, // Width, img->h, // Height, NULL, // pPoint, img->format->BytesPerPixel ); //BytesPerPixel #else int texpixfmt; for(texpixfmt = 0; texpixfmt < NUM_PIX_FORMATS; ++texpixfmt) if(D3DFORMATS[texpixfmt] == desc.Format) break; ASSERT( texpixfmt != NUM_PIX_FORMATS ); RageSurface *Texture = CreateSurfaceFromPixfmt(RagePixelFormat(texpixfmt), lr.pBits, width, height, lr.Pitch); ASSERT( Texture ); RageSurfaceUtils::Blit( img, Texture, width, height ); delete Texture; #endif pTex->UnlockRect( 0 ); }
void COverlayRenderer::DrawARGBBitmap(OSDTexture* pOsdTexture, const BD_ARGB_OVERLAY* pOv) { CAutoLock lock(&m_csRenderLock); if (!pOsdTexture || !m_pD3DDevice || !pOv) return; if (pOv->argb) { IDirect3DTexture9* texture = NULL; if (m_pD3DDevice) { AdjustDirtyRect(pOv->plane, pOv->x, pOv->y, pOv->w, pOv->h); D3DLOCKED_RECT lockedRect; HRESULT hr = m_pD3DDevice->CreateTexture(pOv->w, pOv->h, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &texture, NULL); if (SUCCEEDED(hr)) { hr = texture->LockRect(0, &lockedRect, NULL, 0); if (SUCCEEDED(hr)) { if (pOv->argb) { for(INT i = 0; i < pOv->h; i++) { DWORD *pDst = (DWORD*)lockedRect.pBits + (lockedRect.Pitch / 4) * i; DWORD *pSrc = (DWORD*)pOv->argb + i * pOv->stride; memcpy(pDst, pSrc, pOv->w * 4); } } else LogDebug("ovr: DrawBitmap - pOv->argb is NULL"); texture->UnlockRect(0); } else LogDebug("ovr: DrawBitmap LockRect 0x%08x", hr); DrawToTexture(pOsdTexture, texture, pOv->x, pOv->y, pOv->w, pOv->h); } else LogDebug("ovr: DrawBitmap - CreateTexture2 0x%08x", hr); } } }
HRESULT HEIGHTMAP::LoadFromFile(IDirect3DDevice9* Device, char fileName[]) { try { //Reset the heightMap to 0.0f memset(m_pHeightMap, 0, sizeof(float) * m_size.x * m_size.y); //Initiate the texture variables IDirect3DTexture9 *heightMapTexture = NULL; D3DXIMAGE_INFO info; //Load the texture (and scale it to our heightMap m_size) if(FAILED(D3DXCreateTextureFromFileEx(Device, fileName, m_size.x, m_size.y, 1, D3DUSAGE_DYNAMIC, D3DFMT_L8, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, NULL, &info, NULL, &heightMapTexture)))return E_FAIL; //Lock the texture D3DLOCKED_RECT sRect; heightMapTexture->LockRect(0, &sRect, NULL, NULL); BYTE *bytes = (BYTE*)sRect.pBits; //Extract height values from the texture for(int y=0;y<m_size.y;y++) for(int x=0;x<m_size.x;x++) { BYTE *b = bytes + y * sRect.Pitch + x; m_pHeightMap[x + y * m_size.x] = (*b / 255.0f) * m_maxHeight; } //Unlock the texture heightMapTexture->UnlockRect(0); //Release texture heightMapTexture->Release(); } catch(...) { debug.Print("Error in HEIGHTMAP::LoadFromFile()"); } return S_OK; }
static IDirect3DTexture9 *BindFont(IDirect3DDevice9 *_Dev, const CTexFont *_Font) { assert(_Font!=NULL); IDirect3DTexture9 *Tex = NULL; HRESULT hr = _Dev->CreateTexture(_Font->m_TexWidth, _Font->m_TexHeight, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &Tex, NULL); if( FAILED(hr) ) return NULL; D3DLOCKED_RECT r; hr = Tex->LockRect(0, &r, NULL, 0); if( SUCCEEDED(hr) ) { color32 *p = static_cast<color32 *>(r.pBits); for( int i=0; i<_Font->m_TexWidth*_Font->m_TexHeight; ++i, ++p ) *p = 0x00ffffff | (((color32)(_Font->m_TexBytes[i]))<<24); Tex->UnlockRect(0); } return Tex; }
IDirect3DTexture9 * DXRender::createTextureFromData(unsigned int width, unsigned int height, const unsigned char * data, unsigned int sourcePitch, bool flip, unsigned int mipmapLevels) { IDirect3DTexture9 * texture = NULL; if (!isDeviceReady()) return texture; if (caps.TextureCaps & D3DPTEXTURECAPS_POW2) VASSERT(isPowerOfTwo(width) && isPowerOfTwo(height), QString_NT("Texture not POW2: %1, %2").arg(width).arg(height)); HRESULT hr = dxr->device->CreateTexture(width, height, mipmapLevels, D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &texture, NULL); if (hr != D3D_OK) { VASSERT(D3D_OK == hr, QString_NT("Failed to create texture: hr = %1, width = %2, height = %3, mipmapLevels = %4").arg(hr).arg(width).arg(height).arg(mipmapLevels)); return NULL; } D3DLOCKED_RECT lockedRect = {0}; hr = texture->LockRect(0, &lockedRect, NULL, 0); VASSERT(D3D_OK == hr, QString_NT("Could not lock texture: hr = %1").arg(hr)); if (width * 4 == lockedRect.Pitch && lockedRect.Pitch == sourcePitch && !flip) memcpy(lockedRect.pBits, data, width * height * 4); else if (flip) { for (unsigned int i = 0; i < height; i++) memcpy((char *)lockedRect.pBits + (height - 1 - i) * lockedRect.Pitch, data + sourcePitch * i, sourcePitch); } else { for (unsigned int i = 0; i < height; i++) memcpy((char *)lockedRect.pBits + i * lockedRect.Pitch, data + sourcePitch * i, sourcePitch); } hr = texture->UnlockRect(0); VASSERT(D3D_OK == hr, QString_NT("Could not unlock texture: hr = %1").arg(hr)); return texture; }
IDirect3DTexture9 * Texture_DX9::build_from_Image(const Image &image) { Video_DX9 &vdx = dynamic_cast<Video_DX9 &>(get_Video()); IDirect3DTexture9 * ppTexture; D3DFORMAT format; switch(image.color_space()) { case Image::Luminance: format = D3DFMT_L8; break; case Image::Luminance_Alpha: format = D3DFMT_A8B8G8R8; break; case Image::RGB: format = D3DFMT_A8B8G8R8; break; case Image::RGBA: format = D3DFMT_A8B8G8R8; break; default: format = D3DFMT_UNKNOWN; abort(); } set_sampler_states(); if(FAILED(Video_DX9::D3DXCreateTexture()(vdx.get_d3d_device(), UINT(image.width()), UINT(image.height()), D3DX_DEFAULT, 0, format, D3DPOOL_MANAGED, &ppTexture))) throw Texture_Init_Failure(); D3DLOCKED_RECT rect; if(FAILED(ppTexture->LockRect(0, &rect, 0, 0))) { ppTexture->Release(); throw Texture_Init_Failure(); } if(image.color_space() == Image::Luminance) { memcpy(rect.pBits, image.get_data(), image.width() * image.height()); } else if(image.color_space() == Image::Luminance_Alpha) { Uint8 * dest = reinterpret_cast<Uint8 *>(rect.pBits); const Uint8 * src = image.get_data(); for(Uint8 * const dest_end = dest + image.width() * image.height() * 4; dest != dest_end; dest += 4, src += 2) { dest[0] = src[0]; dest[1] = src[0]; dest[2] = src[0]; dest[3] = src[1]; } } else if(image.color_space() == Image::RGB) { Uint8 * dest = reinterpret_cast<Uint8 *>(rect.pBits); const Uint8 * src = image.get_data(); for(Uint8 * const dest_end = dest + image.width() * image.height() * 4; dest != dest_end; dest += 4, src += 3) { dest[0] = src[2]; dest[1] = src[1]; dest[2] = src[0]; dest[3] = 0xFF; } } else /*if(image.color_space() == Image::RGBA)*/ { Uint8 * dest = reinterpret_cast<Uint8 *>(rect.pBits); const Uint8 * src = image.get_data(); for(Uint8 * const dest_end = dest + image.width() * image.height() * 4; dest != dest_end; dest += 4, src += 4) { dest[0] = src[2]; dest[1] = src[1]; dest[2] = src[0]; dest[3] = src[3]; } } if(FAILED(ppTexture->UnlockRect(0))) { ppTexture->Release(); throw Texture_Init_Failure(); } if(FAILED(Video_DX9::D3DXFilterTexture()(ppTexture, 0, D3DX_DEFAULT, D3DX_DEFAULT))) { ppTexture->Release(); throw Texture_Init_Failure(); } return ppTexture; }
MF_API bool MFTexture_Update(MFTexture *pTexture, int element, int mipLevel, const void *pData, size_t lineStride, size_t sliceStride) { int numFaces = pTexture->type == MFTexType_Cubemap ? 6 : 1; MFDebug_Assert(element < numFaces, "Array textures not supported in D3D9!"); int s = mipLevel*pTexture->numElements + (element > -1 ? element : 0); MFTextureSurface &surface = pTexture->pSurfaces[s]; DWORD lockFlags = (pTexture->createFlags & MFTCF_TypeMask) == MFTCF_Scratch ? D3DLOCK_DISCARD : 0; size_t lineBytes = (surface.bitsPerPixel * surface.width) / 8; if(lineStride == 0) lineStride = lineBytes; if(sliceStride == 0) sliceStride = lineStride * surface.width; switch(pTexture->type) { case MFTexType_1D: { IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DSURFACE_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_RECT rect; pTex->LockRect(mipLevel, &rect, NULL, lockFlags); MFCopyMemory(rect.pBits, pData, lineBytes); pTex->UnlockRect(mipLevel); break; } case MFTexType_2D: { IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DSURFACE_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_RECT rect; pTex->LockRect(mipLevel, &rect, NULL, lockFlags); const char *pSrc = (const char*)pData; char *pDest = (char*)rect.pBits; for(int i=0; i<surface.height; ++i) { MFCopyMemory(pDest, pSrc, lineBytes); pDest += rect.Pitch; pSrc += lineStride; } pTex->UnlockRect(mipLevel); break; } case MFTexType_3D: { IDirect3DVolumeTexture9 *pTex = (IDirect3DVolumeTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DVOLUME_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height && (int)desc.Depth == surface.depth, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_BOX box; pTex->LockBox(mipLevel, &box, NULL, lockFlags); MFCopyMemory(box.pBits, pData, surface.bufferLength); const char *pSrcSlice = (const char*)pData; char *pDestSlice = (char*)box.pBits; for(int d=0; d<surface.depth; ++d) { const char *pSrcLine = pSrcSlice; char *pDestLine = pDestSlice; for(int i=0; i<surface.height; ++i) { MFCopyMemory(pDestLine, pSrcLine, lineBytes); pDestLine += box.RowPitch; pSrcLine += lineStride; } pSrcSlice += sliceStride; pDestSlice += box.SlicePitch; } pTex->UnlockBox(mipLevel); break; } case MFTexType_Cubemap: { MFDebug_Assert(element != -1, "TODO: must handle setting all surfaces at once..."); IDirect3DCubeTexture9 *pTex = (IDirect3DCubeTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DSURFACE_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_RECT rect; pTex->LockRect(gD3DCubeFaces[element], mipLevel, &rect, NULL, lockFlags); const char *pSrc = (const char*)pData; char *pDest = (char*)rect.pBits; for(int i=0; i<surface.height; ++i) { MFCopyMemory(pDest, pSrc, lineBytes); pDest += rect.Pitch; pSrc += lineStride; } pTex->UnlockRect(gD3DCubeFaces[element], mipLevel); break; } } return true; }
void ConvertImageFileToBMPBuffer(string szSrcFileName, LPBYTE * bytes, long* len) { if(!FileExists(szSrcFileName)) return; ATG::Timer m_Timer; double timeA = m_Timer.GetAbsoluteTime(); IDirect3DTexture9 * pTexture; HRESULT retVal = D3DXCreateTextureFromFileEx( CFreestyleApp::getInstance().m_pd3dDevice, szSrcFileName.c_str(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 1, D3DUSAGE_CPU_CACHED_MEMORY, D3DFMT_LIN_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, NULL, NULL, &pTexture ); float timeB = m_Timer.GetAbsoluteTime(); DebugMsg("Test", "Texture Creation: %4.2f", (timeB- timeA)); if(retVal == S_OK) { timeA = m_Timer.GetAbsoluteTime(); // Get our level desc D3DSURFACE_DESC desc; pTexture->GetLevelDesc(0, &desc); // Now lock our data D3DLOCKED_RECT lock; RECT rect = {0, 0, desc.Width, desc.Height}; pTexture->LockRect(0, &lock, &rect, D3DLOCK_READONLY); //Read our data DWORD headerSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); DWORD dataLen = lock.Pitch * desc.Height; DWORD * dataBuffer = (DWORD*)malloc( dataLen + headerSize ); DWORD * address = (DWORD*)lock.pBits; // Create file our header BITMAPFILEHEADER* fHead = (BITMAPFILEHEADER*)dataBuffer; fHead->bfType = 0x424D; // "BM" fHead->bfSize = SwapDWORD(dataLen + headerSize); fHead->bfReserved1 = 0; fHead->bfReserved2 = 0; fHead->bfOffBits = SwapDWORD(headerSize); // Create our info header BITMAPINFOHEADER* iHead = (BITMAPINFOHEADER*)(fHead + 1); ZeroMemory(iHead, sizeof(BITMAPINFOHEADER)); iHead->biSize = SwapDWORD(sizeof(BITMAPINFOHEADER)); iHead->biWidth = SwapDWORD(desc.Width); iHead->biHeight = SwapDWORD(desc.Height); iHead->biPlanes = SwapWORD(1); iHead->biBitCount = SwapWORD(32); iHead->biSizeImage = SwapDWORD(dataLen); // Copy over our raw (BGRA) DWORD* rawPtr = (DWORD*)(iHead + 1); for(int y = desc.Height - 1; y >= 0; y--) { for(DWORD x = 0; x < desc.Width; x++) { DWORD cp = (y * lock.Pitch) + (x * 4); DWORD * temp = (DWORD*)(address + (cp / 4)); *rawPtr = SwapDWORD(*temp); rawPtr++; } } // Unlock our texture pTexture->UnlockRect(0); timeB = m_Timer.GetAbsoluteTime(); DebugMsg("Test", "Texture Lock Time: %4.2f", (timeB- timeA)); *len = (headerSize + dataLen); *bytes = (BYTE*)dataBuffer; }else { DebugMsg("ConvertImageInMemoryToBMPBuffer", "Conversion To BMP From Memory Failed. [%X]", retVal); } // Release our Texture if(pTexture != NULL) pTexture->Release(); }
void RenderState::init(IDirect3DDevice9* dev) { _dev = dev; D3DDEVICE_CREATION_PARAMETERS params; HRESULT hr = dev->GetCreationParameters(¶ms); if (FAILED(hr)) { MM_LOG_INFO(format("Failed to obtain device creation parameters")); } else { _focusWindow = params.hFocusWindow; } // create "selected" texture WCHAR* dataPath = NULL; if (Interop::OK()) { IDirect3DTexture9 * tex; int width = 256; int height = 256; HRESULT hr = dev->CreateTexture(width, height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, 0); if (FAILED(hr)) { MM_LOG_INFO("Failed to create 'selection' texture"); } else { _selectionTexture = tex; D3DLOCKED_RECT rect; hr = tex->LockRect(0, &rect, 0, D3DLOCK_DISCARD); if (FAILED(hr)) { MM_LOG_INFO("Failed to lock 'selection' texture"); } else { unsigned char* dest = static_cast<unsigned char*>(rect.pBits); // fill it with a lovely shade of green Uint32 numEls = width * height; for (Uint32 i = 0; i < numEls; ++i) { Uint32* d = (Uint32*)(dest + (i*sizeof(Uint32))); *d = 0xFF00FF00; } //MM_LOG_INFO("filled selection texture"); tex->UnlockRect(0); } } } // Set key bindings. Input also assumes that CONTROL modifier is required for these as well. // TODO: should push this out to conf file eventually so that they can be customized without rebuild // If you change these, be sure to change LocStrings/ProfileText in MMLaunch! _punctKeyMap[DIK_BACKSLASH] = [&]() { this->loadMods(); }; _punctKeyMap[DIK_RBRACKET] = [&]() { this->toggleShowModMesh(); }; _punctKeyMap[DIK_SEMICOLON] = [&]() { this->clearTextureLists(); }; _punctKeyMap[DIK_COMMA] = [&]() { this->selectNextTexture(); }; _punctKeyMap[DIK_PERIOD] = [&]() { this->selectPrevTexture(); }; _punctKeyMap[DIK_SLASH] = [&]() { this->requestSnap(); }; _punctKeyMap[DIK_MINUS] = [&]() { this->loadEverything(); }; // If you change these, be sure to change LocStrings/ProfileText in MMLaunch! _fKeyMap[DIK_F1] = [&]() { this->loadMods(); }; _fKeyMap[DIK_F2] = [&]() { this->toggleShowModMesh(); }; _fKeyMap[DIK_F6] = [&]() { this->clearTextureLists(); }; _fKeyMap[DIK_F3] = [&]() { this->selectNextTexture(); }; _fKeyMap[DIK_F4] = [&]() { this->selectPrevTexture(); }; _fKeyMap[DIK_F7] = [&]() { this->requestSnap(); }; _fKeyMap[DIK_F10] = [&]() { this->loadEverything(); }; _pCurrentKeyMap = &_fKeyMap; if (Interop::OK()) { if (Interop::Conf().LoadModsOnStart) { loadEverything(); toggleShowModMesh(); } else { loadManagedAssembly(); } } _initted = true; }
void DeprecatedTextureHostSystemMemD3D9::UpdateImpl(const SurfaceDescriptor& aImage, nsIntRegion *aRegion, nsIntPoint *aOffset) { MOZ_ASSERT(aImage.type() == SurfaceDescriptor::TSurfaceDescriptorD3D9); MOZ_ASSERT(mCompositor, "Must have compositor to update."); if (!mCompositor->device()) { return; } IDirect3DTexture9* texture = reinterpret_cast<IDirect3DTexture9*>(aImage.get_SurfaceDescriptorD3D9().texture()); if (!texture) { Reset(); return; } D3DSURFACE_DESC desc; texture->GetLevelDesc(0, &desc); HRESULT hr = texture->GetLevelDesc(0, &desc); if (FAILED(hr)) { Reset(); return; } mSize.width = desc.Width; mSize.height = desc.Height; _D3DFORMAT format = desc.Format; uint32_t bpp = 0; switch (format) { case D3DFMT_X8R8G8B8: mFormat = SurfaceFormat::B8G8R8X8; bpp = 4; break; case D3DFMT_A8R8G8B8: mFormat = SurfaceFormat::B8G8R8A8; bpp = 4; break; case D3DFMT_A8: mFormat = SurfaceFormat::A8; bpp = 1; break; default: NS_ERROR("Bad image format"); } int32_t maxSize = mCompositor->GetMaxTextureSize(); if (mSize.width <= maxSize && mSize.height <= maxSize) { mIsTiled = false; mTexture = TextureToTexture(gfxWindowsPlatform::GetPlatform()->GetD3D9DeviceManager(), texture, mSize, format); if (!mTexture) { NS_WARNING("Could not upload texture"); Reset(); return; } } else { mIsTiled = true; uint32_t tileCount = GetRequiredTilesD3D9(mSize.width, maxSize) * GetRequiredTilesD3D9(mSize.height, maxSize); mTileTextures.resize(tileCount); for (uint32_t i = 0; i < tileCount; i++) { IntRect tileRect = GetTileRect(i); RECT d3dTileRect; d3dTileRect.left = tileRect.x; d3dTileRect.top = tileRect.y; d3dTileRect.right = tileRect.XMost(); d3dTileRect.bottom = tileRect.YMost(); D3DLOCKED_RECT lockedRect; texture->LockRect(0, &lockedRect, &d3dTileRect, 0); mTileTextures[i] = DataToTexture(gfxWindowsPlatform::GetPlatform()->GetD3D9DeviceManager(), reinterpret_cast<unsigned char*>(lockedRect.pBits), lockedRect.Pitch, tileRect.Size(), format, bpp); texture->UnlockRect(0); if (!mTileTextures[i]) { NS_WARNING("Could not upload texture"); Reset(); return; } } } }
HRESULT ConvertMemoryBufferToBMPBuffer( MemoryBuffer &image_in, MemoryBuffer &image_out) { // Check to ensure that our data has a valid length before proceeding if( image_in.GetDataLength() == 0 ) return S_FALSE; // Set up a timer class to profile our code ATG::Timer m_Timer; double timeStart, timeStop; // Begin Profiling our Texture Creation Code timeStart = m_Timer.GetAbsoluteTime(); IDirect3DTexture9 * pTexture; HRESULT retVal = D3DXCreateTextureFromFileInMemoryEx( CFreestyleApp::getInstance().m_pd3dDevice, image_in.GetData(), image_in.GetDataLength(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 1, D3DUSAGE_CPU_CACHED_MEMORY, D3DFMT_LIN_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, NULL, NULL, &pTexture ); // End Profiling our Texture Creation Code timeStop = m_Timer.GetAbsoluteTime(); DebugMsg("ConvertImageToBMP", "Texture Creation took %4.2f seconds to complete", (float)(timeStop - timeStart)); // If our texture was created successfully, if(retVal = D3D_OK) { //Begin Profiling our Data Manipulation Code timeStart = m_Timer.GetAbsoluteTime(); // Get our level desc D3DSURFACE_DESC desc; pTexture->GetLevelDesc(0, &desc); // Now lock our data D3DLOCKED_RECT lock; RECT rect = {0, 0, desc.Width, desc.Height}; pTexture->LockRect(0, &lock, &rect, D3DLOCK_READONLY); //Read our data DWORD headerSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); DWORD dataLen = lock.Pitch * desc.Height; DWORD * dataBuffer = (DWORD*)malloc( dataLen + headerSize ); DWORD * address = (DWORD*)lock.pBits; // Create file our header BITMAPFILEHEADER* fHead = (BITMAPFILEHEADER*)dataBuffer; fHead->bfType = 0x424D; // "BM" fHead->bfSize = SwapDWORD(dataLen + headerSize); fHead->bfReserved1 = 0; fHead->bfReserved2 = 0; fHead->bfOffBits = SwapDWORD(headerSize); // Create our info header BITMAPINFOHEADER* iHead = (BITMAPINFOHEADER*)(fHead + 1); ZeroMemory(iHead, sizeof(BITMAPINFOHEADER)); iHead->biSize = SwapDWORD(sizeof(BITMAPINFOHEADER)); iHead->biWidth = SwapDWORD(desc.Width); iHead->biHeight = SwapDWORD(desc.Height); iHead->biPlanes = SwapWORD(1); iHead->biBitCount = SwapWORD(32); iHead->biSizeImage = SwapDWORD(dataLen); // Copy over our raw (BGRA) DWORD* rawPtr = (DWORD*)(iHead + 1); for(int y = desc.Height - 1; y >= 0; y--) { for(DWORD x = 0; x < desc.Width; x++) { DWORD cp = (y * lock.Pitch) + (x * 4); DWORD * temp = (DWORD*)(address + (cp / 4)); *rawPtr = SwapDWORD(*temp); rawPtr++; } } // Unlock our texture pTexture->UnlockRect(0); // End Profiling our Data Modification Code timeStop = m_Timer.GetAbsoluteTime(); DebugMsg("ConvertImageToBMP", "Data Modification took %4.2f seconds to complete", (float)(timeStop - timeStart)); // Begin Profiling our Memory Copy Code timeStart = m_Timer.GetAbsoluteTime(); // Copy our completed data to our new buffer image_out.Add(dataBuffer, (headerSize + dataLen)); // End Profiling our Memory Copy Code timeStop = m_Timer.GetAbsoluteTime(); DebugMsg("ConvertImageToBMP", "Image Memory Copy took %4.2f seconds to complete", (float)(timeStop - timeStart)); } else { DebugMsg("ConvertImageInMemoryToBMPBuffer", "Conversion To BMP From Memory Failed. [%X]", retVal); } return retVal; }
bool CreateFontTexture ( IDirect3DDevice9* pDev, DWORD usage, D3DPOOL pool, UINT ch, Font* pFont ) { HDC hdc = GetDC(NULL); HFONT hFont = ::CreateFont(0, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, _T("MS UI Gothic")); HFONT hOldFont = (HFONT)::SelectObject(hdc, hFont); HRESULT hr; int gm_w, gm_h; int fnt_x, fnt_y; BYTE *bmp_p = NULL; int bmp_w, bmp_h; //bmp_p { TEXTMETRIC tm; GLYPHMETRICS gm; MAT2 mat2 = { {0,1}, {0,0}, {0,0}, {0,1} }; GetTextMetrics(hdc, &tm); DWORD bufsize = GetGlyphOutline( hdc, ch, GGO_GRAY4_BITMAP, &gm, 0, NULL, &mat2); if (bufsize == GDI_ERROR) { bufsize = GetLastError(); goto fin; } bmp_p = (BYTE*)malloc(bufsize); DWORD r = GetGlyphOutline( hdc, ch, GGO_GRAY4_BITMAP, &gm, bufsize, bmp_p, &mat2); pFont->tm_max_w = tm.tmMaxCharWidth; pFont->tm_ave_w = tm.tmAveCharWidth; gm_w = gm.gmCellIncX; gm_h = tm.tmHeight; bmp_w = ((gm.gmBlackBoxX + 3) / 4) * 4; //4-align bmp_h = gm.gmBlackBoxY; fnt_x = gm.gmptGlyphOrigin.x; fnt_y = tm.tmAscent - gm.gmptGlyphOrigin.y; } IDirect3DTexture9* pTex; hr = pDev->CreateTexture(gm_w, gm_h, 1, usage, D3DFMT_A8R8G8B8, pool, &pTex, NULL); { D3DLOCKED_RECT rect; pTex->LockRect(0, &rect, NULL, D3DLOCK_DISCARD); FillMemory(rect.pBits, rect.Pitch * gm_h, 0); for (int y=0; y<bmp_h; ++y) { BYTE* p = ((BYTE*)rect.pBits) + rect.Pitch * (fnt_y + y) + fnt_x * 4; for (int x=0; x<bmp_w; ++x) { DWORD trans = ((255 * bmp_p[x+y*bmp_w]) /16)&0xFF; DWORD color = 0x00FFFFFF | (trans << 24); memcpy(p, &color, 4); p += 4; } } pTex->UnlockRect(0); } pFont->pTex = pTex; pFont->gm_w = gm_w; pFont->gm_h = gm_h; pFont->fnt_x = fnt_x; pFont->fnt_y = fnt_y; fin: if (bmp_p) { free(bmp_p); } SelectObject(hdc, hOldFont); return true; }
bool parseCodeImage(const char* pszPath) { D3DXIMAGE_INFO info; HRESULT re = D3DXGetImageInfoFromFileA(pszPath, &info); if(re != S_OK) return false; IDirect3DTexture9 *pText = NULL; //D3DXCreateTextureFromFileA(g_pDevice, pszPath, &pText); //用没有 EX 的函数, 创建的纹理长宽会变成 2的 n次方 re = D3DXCreateTextureFromFileExA(g_pDevice, pszPath, info.Width, info.Height, info.MipLevels, 0/*D3DUSAGE_RENDERTARGET*/, info.Format, D3DPOOL_SYSTEMMEM, D3DX_FILTER_TRIANGLE,D3DX_FILTER_TRIANGLE,D3DCOLOR_ARGB(255,0,0,0), NULL, NULL, &pText); FILE* pFile = fopen("D:/hehe.txt", "w"); D3DLOCKED_RECT rc; pText->LockRect(0, &rc, NULL, 0); BYTE bR = 0, bG = 0, bB = 0; DWORD* pSrc = (DWORD*)rc.pBits; for (int i = 0; i < info.Height ; i++) { for (int j = 0; j < info.Width; j++) { bR = (*pSrc) >> 16; bG = (*pSrc) << 16 >> 24; bB = (*pSrc) & 0x000000ff; if (bR >= 205 && bG >= 205 && bB >= 205) { fprintf(pFile, "1"); } else { fprintf(pFile, "8"); } BYTE t = max( max(bR, bG), bB); *pSrc = t | t << 8 | t << 16; ++pSrc; } fprintf(pFile, "\r\n"); } pText->UnlockRect(0); // 保存灰度图 re = D3DXSaveTextureToFileA("D:/hehe.jpg", D3DXIFF_BMP, pText, NULL); pText->Release(); fclose(pFile); }
bool D3D9DebugManager::InitFontRendering() { HRESULT hr = S_OK; int width = FONT_TEX_WIDTH; int height = FONT_TEX_HEIGHT; string font = GetEmbeddedResource(sourcecodepro_ttf); byte *ttfdata = (byte *)font.c_str(); const int firstChar = int(' ') + 1; const int lastChar = 127; const int numChars = lastChar - firstChar; byte *buf = new byte[width * height]; const float pixelHeight = 20.0f; stbtt_BakeFontBitmap(ttfdata, 0, pixelHeight, buf, width, height, firstChar, numChars, m_Font.charData); stbtt_fontinfo f = {0}; stbtt_InitFont(&f, ttfdata, 0); int ascent = 0; stbtt_GetFontVMetrics(&f, &ascent, NULL, NULL); m_Font.maxHeight = float(ascent) * stbtt_ScaleForPixelHeight(&f, pixelHeight); IDirect3DTexture9 *fontTex = NULL; hr = m_WrappedDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &fontTex, NULL); if(FAILED(hr)) { RDCERR("Failed to create font texture %08x", hr); } D3DLOCKED_RECT lockedRegion; hr = fontTex->LockRect(0, &lockedRegion, NULL, D3DLOCK_DISCARD); if(FAILED(hr)) { RDCERR("Failed to lock font texture %08x", hr); } else { BYTE *texBase = (BYTE *)lockedRegion.pBits; for(int y = 0; y < height; y++) { byte *curRow = (texBase + (y * lockedRegion.Pitch)); for(int x = 0; x < width; x++) { curRow[x * 4 + 0] = buf[(y * width) + x]; curRow[x * 4 + 1] = buf[(y * width) + x]; curRow[x * 4 + 2] = buf[(y * width) + x]; curRow[x * 4 + 3] = buf[(y * width) + x]; } } hr = fontTex->UnlockRect(0); if(hr != S_OK) { RDCERR("Failed to unlock font texture %08x", hr); } } m_Font.Tex = fontTex; delete[] buf; return true; }
void COverlayRenderer::DrawBitmap(OSDTexture* pOsdTexture, const BD_OVERLAY* pOv) { CAutoLock lock(&m_csRenderLock); if (!pOsdTexture || !m_pD3DDevice) return; if (pOv->palette) DecodePalette(pOv); if (pOv->img) { IDirect3DTexture9* texture = NULL; if (m_pD3DDevice) { AdjustDirtyRect(pOv->plane, pOv->x, pOv->y, pOv->w, pOv->h); D3DLOCKED_RECT lockedRect; HRESULT hr = m_pD3DDevice->CreateTexture(pOv->w, pOv->h, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &texture, NULL); if (SUCCEEDED(hr)) { hr = texture->LockRect(0, &lockedRect, NULL, 0); if (SUCCEEDED(hr)) { UINT32* dst = (UINT32*)lockedRect.pBits; const BD_PG_RLE_ELEM* rlep = pOv->img; unsigned pixels = pOv->w * pOv->h; // Copy image data to the texture if (pOv->img) { for (unsigned int i = 0; i < pixels; rlep++) { for (unsigned int j = rlep->len; j > 0; j--) { if (i > 0 && i % pOv->w == 0) dst += lockedRect.Pitch / 4 - pOv->w; *dst = m_palette[rlep->color]; dst++; i++; } } } else LogDebug("ovr: DrawBitmap - pOv->img is NULL"); texture->UnlockRect(0); } else LogDebug("ovr: DrawBitmap LockRect 0x%08x", hr); DrawToTexture(pOsdTexture, texture, pOv->x, pOv->y, pOv->w, pOv->h); } else LogDebug("ovr: DrawBitmap - CreateTexture2 0x%08x", hr); } } }
bool CSprite::_CreateTexture(const CBitmap& _bitmap) { HRESULT hr; CGraphicsManager *pGraphicsManager = CGraphicsManager::GetInstance(); IDirect3DDevice9 *pD3Device = pGraphicsManager->GetDevice(); int iWidth = _bitmap.GetWidth(); int iHeight = _bitmap.GetHeight(); IDirect3DTexture9 *pSystemTexture = NULL; hr = pD3Device->CreateTexture((UINT)iWidth, (UINT)iHeight, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &pSystemTexture, NULL); if(FAILED(hr)) { LogError("Failed to create system texture"); return false; } D3DLOCKED_RECT lockedRect; memset(&lockedRect, 0, sizeof(lockedRect)); hr = pSystemTexture->LockRect(0, &lockedRect, NULL, 0); if(FAILED(hr)) { LogErrorHr("Failed to lock system texture rect", hr); return false; } DWORD *pTexLocation = (DWORD *)lockedRect.pBits; for(int iRowIndex = 0; iRowIndex < iHeight; iRowIndex++) { memcpy(pTexLocation, _bitmap.GetRow(iRowIndex), sizeof(DWORD) * iWidth); for(int iColumnIndex = 0; iColumnIndex < iWidth; iColumnIndex++) { DWORD dwPixel = pTexLocation[iColumnIndex]; if(dwPixel != g_dwBackgroundColor) { dwPixel |= 0xff000000l; pTexLocation[iColumnIndex] = dwPixel; } } BYTE *pTextureByteLocation = (BYTE *)pTexLocation; pTextureByteLocation += lockedRect.Pitch; pTexLocation = (DWORD *)pTextureByteLocation; } hr = pSystemTexture->UnlockRect(0); if(FAILED(hr)) { LogErrorHr("Failed to unlock system texture rect", hr); return false; } hr = pD3Device->CreateTexture(iWidth, iHeight, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pTexture, NULL); if(FAILED(hr)) { LogErrorHr("Failed to create video texture", hr); return false; } hr = pD3Device->UpdateTexture(pSystemTexture, m_pTexture); if(FAILED(hr)) { LogErrorHr("Failed to update video texture", hr); return false; } pSystemTexture->Release(); return true; }
MF_API bool MFTexture_Map(MFTexture *pTexture, int element, int mipLevel, MFLockedTexture *pLock) { int numFaces = pTexture->type == MFTexType_Cubemap ? 6 : 1; MFDebug_Assert(element < numFaces, "Array textures not supported in D3D9!"); int s = mipLevel*pTexture->numElements + (element ? element : 0); MFTextureSurface &surface = pTexture->pSurfaces[s]; DWORD lockFlags = (pTexture->createFlags & MFTCF_TypeMask) == MFTCF_Scratch ? D3DLOCK_DISCARD : 0; switch(pTexture->type) { case MFTexType_1D: { IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DSURFACE_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_RECT rect; pTex->LockRect(mipLevel, &rect, NULL, lockFlags); pLock->pData = rect.pBits; pLock->width = surface.width; pLock->height = surface.height; pLock->depth = surface.depth; pLock->strideInBytes = rect.Pitch; pLock->sliceInBytes = rect.Pitch * surface.height; break; } case MFTexType_2D: { IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DSURFACE_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_RECT rect; pTex->LockRect(mipLevel, &rect, NULL, lockFlags); pLock->pData = rect.pBits; pLock->width = surface.width; pLock->height = surface.height; pLock->depth = surface.depth; pLock->strideInBytes = rect.Pitch; pLock->sliceInBytes = rect.Pitch * surface.height; break; } case MFTexType_3D: { IDirect3DVolumeTexture9 *pTex = (IDirect3DVolumeTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DVOLUME_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height && (int)desc.Depth == surface.depth, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_BOX box; pTex->LockBox(mipLevel, &box, NULL, lockFlags); pLock->pData = box.pBits; pLock->width = surface.width; pLock->height = surface.height; pLock->depth = surface.depth; pLock->strideInBytes = box.RowPitch; pLock->sliceInBytes = box.SlicePitch; break; } case MFTexType_Cubemap: { IDirect3DCubeTexture9 *pTex = (IDirect3DCubeTexture9*)pTexture->pInternalData; #if defined(MF_DEBUG) D3DSURFACE_DESC desc; pTex->GetLevelDesc(mipLevel, &desc); MFDebug_Assert((int)desc.Width == surface.width && (int)desc.Height == surface.height, "D3D9 mip dimensions don't match the texture template data..."); #endif D3DLOCKED_RECT rect; pTex->LockRect(gD3DCubeFaces[element], mipLevel, &rect, NULL, lockFlags); pLock->pData = rect.pBits; pLock->width = surface.width; pLock->height = surface.height; pLock->depth = surface.depth; pLock->strideInBytes = rect.Pitch; pLock->sliceInBytes = rect.Pitch * surface.height; break; } } return true; }
HRESULT Loader::LoadElevations( float **ppImageData, int* nSize, const char * szFilename, bool swapVertical /*= true*/) { float* pImageData = NULL; CParaFile cFile; cFile.OpenAssetFile(szFilename, true, ParaTerrain::Settings::GetInstance()->GetMediaPath()); if(cFile.isEof()) return E_FAIL; int elevWidth=0; int elevHeight=0; if(strcmp(szFilename+strlen(szFilename)-4, ".raw") == 0) { /// Load from raw elevation elevWidth = (int)sqrt((float)(((int)cFile.getSize()/4))); elevHeight = elevWidth; /// just use the file buffer as the image buffer pImageData = (float*)cFile.getBuffer(); cFile.GiveupBufferOwnership(); } else { #ifdef USE_DIRECTX_RENDERER D3DSURFACE_DESC desc; IDirect3DTexture9* pTexture = NULL; HRESULT hr; /// Create a D3DFMT_X8R8G8B8 texture -- use D3DPOOL_SCRATCH to // ensure that this will succeeded independent of the device hr = D3DXCreateTextureFromFileInMemoryEx( CGlobals::GetRenderDevice(), cFile.getBuffer(), (int)cFile.getSize(), 0, 0, 1, 0, D3DFMT_X8R8G8B8, D3DPOOL_SCRATCH, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, NULL, NULL, &pTexture ); if( FAILED(hr) ) return hr; pTexture->GetLevelDesc( 0, &desc ); elevWidth = desc.Width; elevHeight = desc.Height; // create an array of floats to store the values of the bmp pImageData = new float[elevWidth * elevHeight]; if( pImageData == NULL ) { SAFE_RELEASE( pTexture ); return E_OUTOFMEMORY; } //ZeroMemory( pImageData, elevWidth * elevHeight * sizeof(FLOAT) ); D3DLOCKED_RECT lockedRect; hr = pTexture->LockRect( 0, &lockedRect, NULL, D3DLOCK_READONLY ); float fMin=1.0f,fMax=-1.0f; if( SUCCEEDED(hr) ) { DWORD* pBuffer = (DWORD*) lockedRect.pBits; for( DWORD iY=0; iY<desc.Height; iY++ ) { pBuffer = (DWORD*)((BYTE*)lockedRect.pBits + lockedRect.Pitch * iY); for( DWORD iX=0; iX<desc.Width; iX++ ) { LinearColor color((DWORD)(*pBuffer)); float fValue = (color.r+color.g+color.b)/3.0f-0.5f; if (fValue<fMin) fMin = fValue; if (fValue>fMax) fMax = fValue; if (swapVertical) { // Invert Y, so it appears the same as the bmp pImageData[ (desc.Height-1-iY)*elevWidth + iX] = fValue; } else { pImageData[ iY*elevWidth + iX] = fValue; } pBuffer++; } } pTexture->UnlockRect( 0 ); /// Normalize all values between 0.0f and 1.0f /*float fHeight = (fMax-fMin); for( DWORD iY=0; iY<desc.Height; iY++ ) { for( DWORD iX=0; iX<desc.Width; iX++ ) { pImageData[ iY*elevWidth + iX] = (pImageData[ iY*elevWidth + iX]-fMin)/fHeight; } }*/ } SAFE_RELEASE( pTexture ); #else return E_FAIL; #endif } // TODO: re-enable this when you are ready. const bool FORCE_256_mesh = false; if(elevWidth == 129 && FORCE_256_mesh) { // make it 257. int elevWidthDest = 257; float * pImageDataDest = new float[elevWidthDest * elevWidthDest]; for (int i=0; i<elevWidthDest; i++) { for (int j=0; j<elevWidthDest; j++) { int rI = i%2; int ltX = i/2; int rJ = j%2; int ltY = j/2; if(rI == 0) { if(rJ == 0) { pImageDataDest[i*elevWidthDest+j] = pImageData[ltX*elevWidth+ltY]; } else { pImageDataDest[i*elevWidthDest+j] = (pImageData[ltX*elevWidth+ltY+1] + pImageData[ltX*elevWidth+ltY]) * 0.5f; } } else { if(rJ == 0) { pImageDataDest[i*elevWidthDest+j] = (pImageData[(ltX+1)*elevWidth+ltY] + pImageData[ltX*elevWidth+ltY])*0.5f; } else { pImageDataDest[i*elevWidthDest+j] = (pImageData[(ltX+1)*elevWidth+ltY]+pImageData[ltX*elevWidth+ltY]+pImageData[ltX*elevWidth+ltY+1]+pImageData[(ltX+1)*elevWidth+ltY+1])*0.25f; } } } } SAFE_DELETE(pImageData); pImageData = pImageDataDest; elevWidth = elevWidthDest; } *nSize = elevWidth; *ppImageData = pImageData; return S_OK; }
HRESULT KG3DGraphicsEngine::ScreenShotImpl() { HRESULT hResult = E_FAIL; HRESULT hRetCode = E_FAIL; IDirect3DSurface9* pFrameSurface = NULL; IDirect3DTexture9* pTextureSys = NULL; ID3DXBuffer* pBuffer = NULL; D3DVIEWPORT9 ViewPort; RECT RectView; ASSERT(m_eShotImageType != D3DXIFF_FORCE_DWORD); hRetCode = g_pd3dDevice->GetRenderTarget(0, &pFrameSurface); KG_COM_PROCESS_ERROR(hRetCode); g_pd3dDevice->GetViewport(&ViewPort); SetRect(&RectView, ViewPort.X, ViewPort.Y, ViewPort.X + ViewPort.Width, ViewPort.Y + ViewPort.Height); if (m_eShotImageType == D3DXIFF_JPG) { D3DSURFACE_DESC SurfaceDesc; D3DLOCKED_RECT LockRect; hRetCode = D3DXSaveSurfaceToFileInMemory(&pBuffer, D3DXIFF_BMP, pFrameSurface, NULL, &RectView); KG_COM_PROCESS_ERROR(hRetCode); hRetCode = D3DXCreateTextureFromFileInMemoryEx(g_pd3dDevice, pBuffer->GetBufferPointer(), pBuffer->GetBufferSize(), ViewPort.Width, ViewPort.Height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &pTextureSys); KG_COM_PROCESS_ERROR(hRetCode); /* hRetCode = D3DXSaveSurfaceToFile(TEXT("__temp_shot.bmp"), D3DXIFF_BMP, pFrameSurface, NULL, &RectView); KG_COM_PROCESS_ERROR(hRetCode); hRetCode = D3DXCreateTextureFromFileEx(g_pd3dDevice, TEXT("__temp_shot.bmp"), ViewPort.Width, ViewPort.Height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &pTextureSys); KG_COM_PROCESS_ERROR(hRetCode); */ pTextureSys->GetLevelDesc(0, &SurfaceDesc); if (SUCCEEDED(pTextureSys->LockRect(0, &LockRect, NULL, D3DLOCK_NOSYSLOCK))) { struct _Rgba { BYTE r; BYTE g; BYTE b; BYTE a;}; struct _Rgb { BYTE b; BYTE g; BYTE r; }; _Rgb* pRgb = new _Rgb[SurfaceDesc.Height * SurfaceDesc.Width]; for (UINT v = 0; v < SurfaceDesc.Height; ++v) { _Rgba* pRgba = (_Rgba*)((BYTE*)LockRect.pBits + LockRect.Pitch * v); for (UINT u = 0; u < SurfaceDesc.Width; ++u) { pRgb[v * SurfaceDesc.Width + u].r = pRgba[u].r; pRgb[v * SurfaceDesc.Width + u].g = pRgba[u].g; pRgb[v * SurfaceDesc.Width + u].b = pRgba[u].b; } } JpegFile::RGBToJpegFile(m_szShotPath, (BYTE*)pRgb, SurfaceDesc.Width, SurfaceDesc.Height, TRUE, m_nShotImageQuty); delete[] pRgb; pTextureSys->UnlockRect(0); } else { KG_PROCESS_ERROR(FALSE); } } else { hRetCode = D3DXSaveSurfaceToFile(m_szShotPath, m_eShotImageType, pFrameSurface, NULL, &RectView); KG_COM_PROCESS_ERROR(hRetCode); } hResult = S_OK; Exit0 : SAFE_RELEASE(pBuffer); SAFE_RELEASE(pTextureSys); SAFE_RELEASE(pFrameSurface); return hResult; }
HRESULT D3DBufImgOps_EnableLookupOp(D3DContext *d3dc, jboolean nonPremult, jboolean shortData, jint numBands, jint bandLength, jint offset, void *tableValues) { HRESULT res; IDirect3DDevice9 *pd3dDevice; D3DResource *pLutTexRes; IDirect3DTexture9 *pLutTex; int bytesPerElem = (shortData ? 2 : 1); jfloat foffsets[4]; void *bands[4]; int i; jint flags = 0; J2dTraceLn4(J2D_TRACE_INFO, "D3DBufImgOps_EnableLookupOp: short=%d num=%d len=%d off=%d", shortData, numBands, bandLength, offset); RETURN_STATUS_IF_NULL(d3dc, E_FAIL); d3dc->UpdateState(STATE_CHANGE); // choose the appropriate shader, depending on the source image // and the number of bands involved if (numBands != 4) { flags |= LOOKUP_USE_SRC_ALPHA; } if (nonPremult) { flags |= LOOKUP_NON_PREMULT; } // locate/enable the shader program for the given flags res = d3dc->EnableLookupProgram(flags); RETURN_STATUS_IF_FAILED(res); // update the "uniform" offset value for (i = 0; i < 4; i++) { foffsets[i] = offset / 255.0f; } pd3dDevice = d3dc->Get3DDevice(); pd3dDevice->SetPixelShaderConstantF(0, foffsets, 1); res = d3dc->GetResourceManager()->GetLookupOpLutTexture(&pLutTexRes); RETURN_STATUS_IF_FAILED(res); pLutTex = pLutTexRes->GetTexture(); // update the lookup table with the user-provided values if (numBands == 1) { // replicate the single band for R/G/B; alpha band is unused for (i = 0; i < 3; i++) { bands[i] = tableValues; } bands[3] = NULL; } else if (numBands == 3) { // user supplied band for each of R/G/B; alpha band is unused for (i = 0; i < 3; i++) { bands[i] = PtrAddBytes(tableValues, i*bandLength*bytesPerElem); } bands[3] = NULL; } else if (numBands == 4) { // user supplied band for each of R/G/B/A for (i = 0; i < 4; i++) { bands[i] = PtrAddBytes(tableValues, i*bandLength*bytesPerElem); } } // upload the bands one row at a time into our lookup table texture D3DLOCKED_RECT lockedRect; res = pLutTex->LockRect(0, &lockedRect, NULL, D3DLOCK_NOSYSLOCK); RETURN_STATUS_IF_FAILED(res); jushort *pBase = (jushort*)lockedRect.pBits; for (i = 0; i < 4; i++) { jushort *pDst; if (bands[i] == NULL) { continue; } pDst = pBase + (i * 256); if (shortData) { memcpy(pDst, bands[i], bandLength*sizeof(jushort)); } else { int j; jubyte *pSrc = (jubyte *)bands[i]; for (j = 0; j < bandLength; j++) { pDst[j] = (jushort)(pSrc[j] << 8); } } } pLutTex->UnlockRect(0); // bind the lookup table to texture unit 1 and enable texturing res = d3dc->SetTexture(pLutTex, 1); pd3dDevice->SetSamplerState(1, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); pd3dDevice->SetSamplerState(1, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); pd3dDevice->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); pd3dDevice->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); return res; }