void SnowTerrain::initBlendMaps(Terrain* terrain) { TextureLayerFileList blendImages = mSnowConfig->terrainSettings.textureBlendFileList; // load those blendmaps into the layers for(int j = 0;j < terrain->getLayerCount();j++) { // skip first layer if(j==0) continue; // no blend map for this layer if(blendImages.size() >= j && blendImages[j].length() == 0) continue; Ogre::TerrainLayerBlendMap *blendmap = terrain->getLayerBlendMap(j); Ogre::Image img; img.load(blendImages[j],"General"); int blendmapsize = terrain->getLayerBlendMapSize(); if(img.getWidth() != blendmapsize) img.resize(blendmapsize, blendmapsize); float *ptr = blendmap->getBlendPointer(); Ogre::uint8 *data = static_cast<Ogre::uint8*>(img.getPixelBox().data); for(int bp = 0;bp < blendmapsize * blendmapsize;bp++) ptr[bp] = static_cast<float>(data[bp]) / 255.0f; blendmap->dirty(); blendmap->update(); } }
//----------------------------------------------------------------------------------------- void CTerrainGroupEditor::setBrushName(const std::string& brush) { mBrushName = brush; if(!mDecalTexture.isNull()) { Ogre::Image img; img.load(brush,"Brushes"); unsigned char *dataptr = OGRE_ALLOC_T(unsigned char, img.getWidth() * img.getHeight() * 3, Ogre::MEMCATEGORY_GEOMETRY); Ogre::PixelBox resultbox(img.getWidth(),img.getHeight(),1,Ogre::PF_B8G8R8,dataptr); Ogre::PixelUtil::bulkPixelConversion(img.getPixelBox(), resultbox); resultbox.setConsecutive(); int pos = 0; Ogre::ColourValue colval; for(unsigned int x = 0;x < img.getHeight() * img.getWidth();x++) { dataptr[pos] = 0; dataptr[pos + 1] = 0; dataptr[pos + 2] *= 0.8f; pos += 3; } mDecalTexture->setHeight(img.getHeight()); mDecalTexture->setWidth(img.getWidth()); Ogre::HardwarePixelBufferSharedPtr ptr = mDecalTexture->getBuffer(); ptr->blitFromMemory(resultbox); OGRE_FREE(dataptr, Ogre::MEMCATEGORY_GEOMETRY); img.resize(mBrushSize, mBrushSize); img.resize(BRUSH_DATA_SIZE, BRUSH_DATA_SIZE); pos = 0; Ogre::ColourValue cval; for(unsigned int y = 0;y < BRUSH_DATA_SIZE ;y++) { pos = ((BRUSH_DATA_SIZE - 1) - y) * BRUSH_DATA_SIZE; for(unsigned int x = 0;x < BRUSH_DATA_SIZE ;x++) { cval = img.getColourAt(x,y,0); mBrushData[pos] = cval.r; pos++; } } }
/**************************************************************************** ** ** Copyright (C) 2016 - 2017 ** ** This file is part of the Magus toolkit ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ****************************************************************************/ #include "constants.h" #include "texturelayer.h" #include "OgreHlmsPbs.h" #include "OgreHlmsManager.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include <fstream> #include <ctime> //****************************************************************************/ TextureLayer::TextureLayer(void) : mTextureOnWhichIsPaintedWidth(0), mTextureOnWhichIsPaintedHeight(0), mTextureOnWhichIsPaintedHasAlpha(false), mNumMipMaps(0), mTextureTypeDefined(false), mMaxSequence(0) { mTextureType = Ogre::PBSM_DIFFUSE; mDatablockId = ""; mTextureFileName = ""; } //****************************************************************************/ TextureLayer::~TextureLayer(void) { } //****************************************************************************/ void TextureLayer::setDatablockIdAndTexture (const Ogre::IdString& datablockId, Ogre::PbsTextureTypes textureType, const Ogre::String& textureFileName) { mDatablockId = datablockId; mTextureType = textureType; mTextureFileName = textureFileName; mTextureTypeDefined = true; // Load the texture as image; assume it can be loaded, because it was already loaded as part of the material setFirstTextureGeneration(); // Create the pixelbox of the original texture; this MUST be a separate image mOriginalTexture.load(textureFileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mPixelboxOriginalTexture = mOriginalTexture.getPixelBox(0, 0); // Debug texture //Ogre::LogManager::getSingleton().logMessage("Debug texture: " + textureFileName); //Ogre::LogManager::getSingleton().logMessage("Depth: " + Ogre::StringConverter::toString(mOriginalTexture.getDepth())); //Ogre::LogManager::getSingleton().logMessage("Pixel format: " + Ogre::StringConverter::toString(mOriginalTexture.getFormat())); //Ogre::LogManager::getSingleton().logMessage("Alpha: " + Ogre::StringConverter::toString(mOriginalTexture.getHasAlpha())); //Ogre::LogManager::getSingleton().logMessage("Height: " + Ogre::StringConverter::toString(mOriginalTexture.getHeight())); //Ogre::LogManager::getSingleton().logMessage("Number of faces: " + Ogre::StringConverter::toString(mOriginalTexture.getNumFaces())); //Ogre::LogManager::getSingleton().logMessage("Number of mipmaps: " + Ogre::StringConverter::toString(mOriginalTexture.getNumMipmaps())); //Ogre::LogManager::getSingleton().logMessage("Width: " + Ogre::StringConverter::toString(mOriginalTexture.getWidth())); } //****************************************************************************/ void TextureLayer::blitTexture (void) { /* Always get the actual pointers, because they may change. That is the reason why the datablock pointer cannot be cached. * The same seems to apply to the texture pointer. */ Ogre::HlmsDatablock* datablock; Ogre::HlmsPbsDatablock* datablockPbs; Ogre::TexturePtr texture; Ogre::HlmsManager* hlmsManager = Ogre::Root::getSingletonPtr()->getHlmsManager(); Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>(hlmsManager->getHlms(Ogre::HLMS_PBS)); datablock = hlmsPbs->getDatablock(mDatablockId); if (!datablock) return; datablockPbs = static_cast<Ogre::HlmsPbsDatablock*>(datablock); try { // Get texture on GPU if (!datablockPbs->getTexture(mTextureType).isNull()) { texture = datablockPbs->getTexture(mTextureType); // TextureType MUST exist, otherwise the application crashes mNumMipMaps = texture->getNumMipmaps(); } } catch (Ogre::Exception e){} if (texture.isNull()) return; Ogre::uint8 maxMipMaps = mNumMipMaps + 1; // Increase with one, because there is always one image to blit maxMipMaps = maxMipMaps > PAINT_MAX_MIP_MAPS ? PAINT_MAX_MIP_MAPS : maxMipMaps; // Just paint a few mipmaps (not all) Ogre::Image textureOnWhichIsPaintedScaled = mTextureOnWhichIsPainted; // Temporary image must be used, otherwise painting doesn't work size_t w = mTextureOnWhichIsPaintedWidth; size_t h = mTextureOnWhichIsPaintedHeight; Ogre::v1::HardwarePixelBuffer* buffer; for (Ogre::uint8 i = 0; i < maxMipMaps; ++i) { buffer = texture->getBuffer(0, i).getPointer(); buffer->blitFromMemory(textureOnWhichIsPaintedScaled.getPixelBox(0, 0), Ogre::Box(0, 0, 0, w, h, 1)); w*=0.5f; // Mipmaps always are half of the previous one h*=0.5f; if (w < 1.0f || h < 1.0f) break; // Stop when the mipmaps are too small textureOnWhichIsPaintedScaled.resize(w, h); } textureOnWhichIsPaintedScaled.freeMemory(); }
void DotSceneLoader::processBlendmaps(rapidxml::xml_node<>* XMLNode) { int pageX = Ogre::StringConverter::parseInt(XMLNode->first_attribute("pageX")->value()); int pageY = Ogre::StringConverter::parseInt(XMLNode->first_attribute("pageY")->value()); Ogre::String filename = mTerrainGroup->generateFilename(pageX, pageY); // skip this is terrain page has been saved already if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(mTerrainGroup->getResourceGroup(), filename)) { rapidxml::xml_node<>* pElement; // Process blendmaps (*) std::vector<Ogre::String> blendMaps; rapidxml::xml_node<>* pBlendmap; pElement = XMLNode->first_node("blendMaps"); pBlendmap = pElement->first_node("blendMap"); while(pBlendmap) { blendMaps.push_back(getAttrib(pBlendmap, "texture","")); pBlendmap = pBlendmap->next_sibling("blendMap"); } for(int j = 1;j < mTerrainGroup->getTerrain(pageX, pageY)->getLayerCount();j++) { Ogre::TerrainLayerBlendMap *blendmap = mTerrainGroup->getTerrain(pageX, pageY)->getLayerBlendMap(j); Ogre::Image img; img.load(blendMaps[j-1],"General"); int blendmapsize = mTerrainGroup->getTerrain(pageX, pageY)->getLayerBlendMapSize(); if(img.getWidth() != blendmapsize) img.resize(blendmapsize, blendmapsize); float *ptr = blendmap->getBlendPointer(); Ogre::uint8 *data = static_cast<Ogre::uint8*>(img.getPixelBox().data); for(int bp = 0;bp < blendmapsize * blendmapsize;bp++) ptr[bp] = static_cast<float>(data[bp]) / 255.0f; blendmap->dirty(); blendmap->update(); } } }
void TerrainGeometryManager::initBlendMaps(int x, int z, Ogre::Terrain* terrain ) { bool debugBlendMaps = BOPT("DebugBlendMaps", false); int layerCount = terrain->getLayerCount(); for (int i = 1; i < layerCount; i++) { blendLayerInfo_t &bi = blendInfo[i]; if(bi.blendMapTextureFilename.empty()) continue; Ogre::Image img; //std::pair<uint8,uint8> textureIndex = terrain->getLayerBlendTextureIndex(i); //uint8 bti = terrain->getBlendTextureIndex(i); try { img.load(bi.blendMapTextureFilename, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); } catch(Exception &e) { LOG("Error loading blendmap: " + bi.blendMapTextureFilename + " : " + e.getFullDescription()); continue; } TerrainLayerBlendMap *blendmap = terrain->getLayerBlendMap(i); // resize that blending map so it will fit Ogre::uint32 blendmapSize = terrain->getLayerBlendMapSize(); if (img.getWidth() != blendmapSize) img.resize(blendmapSize, blendmapSize); // now to the ugly part float* ptr = blendmap->getBlendPointer(); for (Ogre::uint32 z = 0; z != blendmapSize; z++) { for (Ogre::uint32 x = 0; x != blendmapSize; x++) { Ogre::ColourValue c = img.getColourAt(x, z, 0); float alpha = bi.alpha; if (bi.blendMode == 'R') *ptr++ = c.r * alpha; else if (bi.blendMode == 'G') *ptr++ = c.g * alpha; else if (bi.blendMode == 'B') *ptr++ = c.b * alpha; else if (bi.blendMode == 'A') *ptr++ = c.a * alpha; } } blendmap->dirty(); blendmap->update(); } if (debugBlendMaps) { for (int i = 1; i < layerCount; i++) { Ogre::TerrainLayerBlendMap* blendMap = terrain->getLayerBlendMap(i); Ogre::uint32 blendmapSize = terrain->getLayerBlendMapSize(); Ogre::Image img; unsigned short *idata = OGRE_ALLOC_T(unsigned short, blendmapSize * blendmapSize, Ogre::MEMCATEGORY_RESOURCE); float scale = 65535.0f; for (unsigned int x = 0; x < blendmapSize; x++) for (unsigned int z = 0; z < blendmapSize; z++) idata[x + z * blendmapSize] = (unsigned short)(blendMap->getBlendValue(x, blendmapSize - z) * scale); img.loadDynamicImage((Ogre::uchar*)(idata), blendmapSize, blendmapSize, Ogre::PF_L16); std::string fileName = "blendmap_layer_" + Ogre::StringConverter::toString(i) + ".png"; img.save(fileName); OGRE_FREE(idata, Ogre::MEMCATEGORY_RESOURCE); } } }
void MapDisplay::showMap() { if (current_map_.data.empty()) { return; } if( !validateFloats( current_map_ )) { setStatus( StatusProperty::Error, "Map", "Message contained invalid floating point values (nans or infs)" ); return; } if( current_map_.info.width * current_map_.info.height == 0 ) { std::stringstream ss; ss << "Map is zero-sized (" << current_map_.info.width << "x" << current_map_.info.height << ")"; setStatus( StatusProperty::Error, "Map", QString::fromStdString( ss.str() )); return; } setStatus( StatusProperty::Ok, "Message", "Map received" ); ROS_DEBUG( "Received a %d X %d map @ %.3f m/pix\n", current_map_.info.width, current_map_.info.height, current_map_.info.resolution ); float resolution = current_map_.info.resolution; int width = current_map_.info.width; int height = current_map_.info.height; Ogre::Vector3 position( current_map_.info.origin.position.x, current_map_.info.origin.position.y, current_map_.info.origin.position.z ); Ogre::Quaternion orientation( current_map_.info.origin.orientation.w, current_map_.info.origin.orientation.x, current_map_.info.origin.orientation.y, current_map_.info.origin.orientation.z ); frame_ = current_map_.header.frame_id; if (frame_.empty()) { frame_ = "/map"; } unsigned int pixels_size = width * height; unsigned char* pixels = new unsigned char[pixels_size]; memset(pixels, 255, pixels_size); bool map_status_set = false; unsigned int num_pixels_to_copy = pixels_size; if( pixels_size != current_map_.data.size() ) { std::stringstream ss; ss << "Data size doesn't match width*height: width = " << width << ", height = " << height << ", data size = " << current_map_.data.size(); setStatus( StatusProperty::Error, "Map", QString::fromStdString( ss.str() )); map_status_set = true; // Keep going, but don't read past the end of the data. if( current_map_.data.size() < pixels_size ) { num_pixels_to_copy = current_map_.data.size(); } } memcpy( pixels, ¤t_map_.data[0], num_pixels_to_copy ); Ogre::DataStreamPtr pixel_stream; pixel_stream.bind( new Ogre::MemoryDataStream( pixels, pixels_size )); if( !texture_.isNull() ) { Ogre::TextureManager::getSingleton().remove( texture_->getName() ); texture_.setNull(); } static int tex_count = 0; std::stringstream ss; ss << "MapTexture" << tex_count++; try { texture_ = Ogre::TextureManager::getSingleton().loadRawData( ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, pixel_stream, width, height, Ogre::PF_L8, Ogre::TEX_TYPE_2D, 0); if( !map_status_set ) { setStatus( StatusProperty::Ok, "Map", "Map OK" ); } } catch(Ogre::RenderingAPIException&) { Ogre::Image image; pixel_stream->seek(0); float fwidth = width; float fheight = height; if( width > height ) { float aspect = fheight / fwidth; fwidth = 2048; fheight = fwidth * aspect; } else { float aspect = fwidth / fheight; fheight = 2048; fwidth = fheight * aspect; } { std::stringstream ss; ss << "Map is larger than your graphics card supports. Downsampled from [" << width << "x" << height << "] to [" << fwidth << "x" << fheight << "]"; setStatus(StatusProperty::Ok, "Map", QString::fromStdString( ss.str() )); } ROS_WARN("Failed to create full-size map texture, likely because your graphics card does not support textures of size > 2048. Downsampling to [%d x %d]...", (int)fwidth, (int)fheight); //ROS_INFO("Stream size [%d], width [%f], height [%f], w * h [%f]", pixel_stream->size(), width, height, width * height); image.loadRawData(pixel_stream, width, height, Ogre::PF_L8); image.resize(fwidth, fheight, Ogre::Image::FILTER_NEAREST); ss << "Downsampled"; texture_ = Ogre::TextureManager::getSingleton().loadImage(ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, image); } delete [] pixels; Ogre::Pass* pass = material_->getTechnique(0)->getPass(0); Ogre::TextureUnitState* tex_unit = NULL; if (pass->getNumTextureUnitStates() > 0) { tex_unit = pass->getTextureUnitState(0); } else { tex_unit = pass->createTextureUnitState(); } tex_unit->setTextureName(texture_->getName()); tex_unit->setTextureFiltering( Ogre::TFO_NONE ); updatePalette(); resolution_property_->setValue( resolution ); width_property_->setValue( width ); height_property_->setValue( height ); position_property_->setVector( position ); orientation_property_->setQuaternion( orientation ); transformMap(); manual_object_->setVisible( true ); scene_node_->setScale( resolution * width, resolution * height, 1.0 ); context_->queueRender(); }
Vector4* SnowTerrain::getTerrainNormalData() { PixelBox* terrainNormals; // load from normals file if(mSnowConfig->terrainSettings.normalsDataFile.length() > 0) { // get terrain normal data using image Ogre::Image img; img.load(mSnowConfig->terrainSettings.normalsDataFile, "General"); //img.flipAroundY(); //img.flipAroundX(); size_t size = img.getWidth(); assert(img.getWidth() == img.getHeight()); if (img.getWidth() != mTerrainSize || img.getHeight() != mTerrainSize) img.resize(mTerrainSize, mTerrainSize); terrainNormals = &img.getPixelBox(); Vector4* floats = convertNormalsToFloats(terrainNormals, true); //OGRE_FREE(terrainNormals->data, Ogre::MEMCATEGORY_GENERAL); // need to swap z and y vector due to different vertical axis in normal map and world space! for(size_t i = 0;i<mTerrainSize*mTerrainSize;i++) { Vector4 v = floats[i]; floats[i].z = v.y; floats[i].y = v.z; } return floats; } else { // need to wait until terrain is loaded while (getTerrain()->isDerivedDataUpdateInProgress()) { // we need to wait for this to finish OGRE_THREAD_SLEEP(50); Root::getSingleton().getWorkQueue()->processResponses(); } // Get terrain normal data using official method //terrainNormals = getTerrain()->calculateNormals(Ogre::Rect(0,0,mTerrainSize,mTerrainSize),Rect(0,0,mTerrainSize,mTerrainSize)); Ogre::Image img; getTerrain()->getTerrainNormalMap()->convertToImage(img); //img.flipAroundY(); img.flipAroundX(); //img.save("test_normals.bmp"); terrainNormals = &img.getPixelBox(); Vector4* floats = convertNormalsToFloats(terrainNormals, true); //OGRE_FREE(terrainNormals->data, Ogre::MEMCATEGORY_GENERAL); return floats; } }
void BrushSelector::buildPreviewBitmap( const Fairy::TextureInfo texInfo ) { const Ogre::uchar BytePerPixel = 8; // 读取原始image Ogre::Image *oriImage = GetSceneManipulator()->getPreviewImage(texInfo.ownerTextureName); // 源大纹理的大小 size_t oriImageHeight = oriImage->getHeight(); size_t oriImageWidth = oriImage->getWidth(); Ogre::uchar *oriImageData = oriImage->getData(); // 所选纹理的大小 size_t newImageWidth = texInfo.width*TexTileSize; size_t newImageHeight = texInfo.height*TexTileSize; // 分配一个足够大的空间来保存新建的image的数据 size_t newImagegetRowSpan = newImageWidth*oriImage->getBPP()/BytePerPixel; // 新建的image的行宽(单位为字节) Ogre::uchar *newImageData = OGRE_ALLOC_T(Ogre::uchar, oriImageHeight*newImagegetRowSpan, Ogre::MEMCATEGORY_GENERAL);//new Ogre::uchar[newImageHeight*newImagegetRowSpan]; Ogre::uchar *newImageDataPointer = newImageData; // 得知起始像素点 size_t startPoint = ( oriImageWidth * texInfo.topCorner + texInfo.leftCorner ) * TexTileSize * oriImage->getBPP()/BytePerPixel; Ogre::uchar *oriImagedataPointer = oriImageData + startPoint; // 把所选的纹理的数据提取出来,并创建一个新的image for ( Ogre::uint i=0; i<newImageHeight; ++i ) { memcpy(newImageDataPointer, oriImagedataPointer, newImagegetRowSpan); newImageDataPointer += newImagegetRowSpan; oriImagedataPointer += oriImage->getRowSpan(); } Ogre::Image newImage; newImage.loadDynamicImage(newImageData,newImageWidth,newImageHeight,1,oriImage->getFormat(),true); // 如果所选纹理大于64*64,就先resize if ( texInfo.width > 1 || texInfo.height > 1 ) newImage.resize(mPreviewImageWidth, mPreviewImageHeight); // 如果有alpha,要与黑白图进行混合 if ( newImage.getHasAlpha() ) { Ogre::ColourValue col; for ( int i=0; i<mPreviewImageWidth; ++i ) { for ( int j=0; j<mPreviewImageWidth; ++j ) { col = newImage.getColourAt(j,i,0); float alphaValue = col.a; unsigned char r = col.r*255 * alphaValue + mBlackWhitePreviewImage.GetRed(i,j) * ( 1.0f - alphaValue); unsigned char g = col.g*255 * alphaValue + mBlackWhitePreviewImage.GetGreen(i,j) * ( 1.0f - alphaValue); unsigned char b = col.b*255 * alphaValue + mBlackWhitePreviewImage.GetBlue(i,j) * ( 1.0f - alphaValue); // 设置到image中 mCurrentPreviewImage.SetRGB(j,i,r,g,b); } } // 设置到缩略图控件中 mBrushesPreview->SetBitmap(mCurrentPreviewImage); } // 没有alpha,就直接拷贝数据 else { Ogre::ColourValue col; for ( int i=0; i<mPreviewImageWidth; ++i ) { for ( int j=0; j<mPreviewImageWidth; ++j ) { col = newImage.getColourAt(j,i,0); unsigned char r = col.r*255; unsigned char g = col.g*255; unsigned char b = col.b*255; // 设置到image中 mCurrentPreviewImage.SetRGB(j,i,r,g,b); } } mBrushesPreview->SetBitmap(mCurrentPreviewImage); } }
void NavViewPanel::displayMap(const nav_msgs::OccupancyGrid& map) { boost::mutex::scoped_lock lock(map_lock_); map_resolution_ = map.info.resolution; // Pad dimensions to power of 2 map_width_ = map.info.width;//(int)pow(2,ceil(log2(map.info.width))); map_height_ = map.info.height;//(int)pow(2,ceil(log2(map.info.height))); map_origin_x_ = map.info.origin.position.x; map_origin_y_ = map.info.origin.position.y; //ROS_INFO("Padded dimensions to %d X %d\n", map_width_, map_height_); // Expand it to be RGB data int pixels_size = map_width_ * map_height_ * 3; unsigned char* pixels = new unsigned char[pixels_size]; memset(pixels, 255, pixels_size); for(unsigned int j=0;j<map.info.height;j++) { for(unsigned int i=0;i<map.info.width;i++) { unsigned char val; if(map.data[j*map.info.width+i] == 100) val = 0; else if(map.data[j*map.info.width+i] == 0) val = 255; else val = 127; int pidx = 3*(j*map_width_ + i); pixels[pidx+0] = val; pixels[pidx+1] = val; pixels[pidx+2] = val; } } Ogre::DataStreamPtr pixel_stream; pixel_stream.bind(new Ogre::MemoryDataStream( pixels, pixels_size )); static int tex_count = 0; std::stringstream ss; ss << "NavViewMapTexture" << tex_count++; try { map_texture_ = Ogre::TextureManager::getSingleton().loadRawData( ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, pixel_stream, map_width_, map_height_, Ogre::PF_BYTE_RGB, Ogre::TEX_TYPE_2D, 0); } catch(Ogre::RenderingAPIException&) { Ogre::Image image; pixel_stream->seek(0); float width = map_width_; float height = map_height_; if (map_width_ > map_height_) { float aspect = height / width; width = 2048; height = width * aspect; } else { float aspect = width / height; height = 2048; width = height * aspect; } ROS_WARN("Failed to create full-size map texture, likely because your graphics card does not support textures of size > 2048. Downsampling to [%d x %d]...", (int)width, (int)height); image.loadRawData(pixel_stream, map_width_, map_height_, Ogre::PF_BYTE_RGB); image.resize(width, height, Ogre::Image::FILTER_NEAREST); ss << "Downsampled"; map_texture_ = Ogre::TextureManager::getSingleton().loadImage(ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, image); } delete [] pixels; Ogre::SceneNode* map_node = NULL; if ( !map_object_ ) { static int map_count = 0; std::stringstream ss; ss << "NavViewMapObject" << map_count++; map_object_ = scene_manager_->createManualObject( ss.str() ); map_node = root_node_->createChildSceneNode(); map_node->attachObject( map_object_ ); ss << "Material"; map_material_ = Ogre::MaterialManager::getSingleton().create( ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME ); map_material_->setReceiveShadows(false); map_material_->getTechnique(0)->setLightingEnabled(false); } else { map_node = map_object_->getParentSceneNode(); } Ogre::Pass* pass = map_material_->getTechnique(0)->getPass(0); Ogre::TextureUnitState* tex_unit = NULL; if (pass->getNumTextureUnitStates() > 0) { tex_unit = pass->getTextureUnitState(0); } else { tex_unit = pass->createTextureUnitState(); } tex_unit->setTextureName(map_texture_->getName()); tex_unit->setTextureFiltering( Ogre::TFO_NONE ); map_object_->clear(); map_object_->begin(map_material_->getName(), Ogre::RenderOperation::OT_TRIANGLE_LIST); { // First triangle { // Top left map_object_->position( 0.0f, 0.0f, 0.0f ); map_object_->textureCoord(0.0f, 0.0f); map_object_->normal( 0.0f, 0.0f, 1.0f ); // Bottom right map_object_->position( map_resolution_*map_width_, map_resolution_*map_height_, 0.0f ); map_object_->textureCoord(1.0f, 1.0f); map_object_->normal( 0.0f, 0.0f, 1.0f ); // Bottom left map_object_->position( 0.0f, map_resolution_*map_height_, 0.0f ); map_object_->textureCoord(0.0f, 1.0f); map_object_->normal( 0.0f, 0.0f, 1.0f ); } // Second triangle { // Top left map_object_->position( 0.0f, 0.0f, 0.0f ); map_object_->textureCoord(0.0f, 0.0f); map_object_->normal( 0.0f, 0.0f, 1.0f ); // Top right map_object_->position( map_resolution_*map_width_, 0.0f, 0.0f ); map_object_->textureCoord(1.0f, 0.0f); map_object_->normal( 0.0f, 0.0f, 1.0f ); // Bottom right map_object_->position( map_resolution_*map_width_, map_resolution_*map_height_, 0.0f ); map_object_->textureCoord(1.0f, 1.0f); map_object_->normal( 0.0f, 0.0f, 1.0f ); } } map_object_->end(); //only center the position of the map if its the first received if(first_map_){ root_node_->setPosition(Ogre::Vector3(-map_width_*map_resolution_/2, -map_height_*map_resolution_/2, 0.0f)); first_map_ = false; } map_node->setPosition(Ogre::Vector3(0.0f, 0.0f, MAP_DEPTH)); queueRender(); }
void MaterialPreviewDialog::buildPreviewBitmap( const Ogre::String &texName ) { const Ogre::uchar BytePerPixel = 8; // 读取原始image Ogre::Image *oriImage = getPreviewImage(texName); // 源大纹理的大小 size_t oriImageHeight = oriImage->getHeight(); size_t oriImageWidth = oriImage->getWidth(); Ogre::uchar *oriImageData = oriImage->getData(); // 分配一个足够大的空间来保存新建的image的数据 size_t newImagegetRowSpan = oriImageWidth*oriImage->getBPP()/BytePerPixel; // 新建的image的行宽(单位为字节) Ogre::uchar *newImageData = new Ogre::uchar[oriImageHeight*newImagegetRowSpan]; Ogre::uchar *newImageDataPointer = newImageData; Ogre::uchar *oriImagedataPointer = oriImageData; // 把所选的纹理的数据提取出来,并创建一个新的image for ( Ogre::uint i=0; i<oriImageHeight; ++i ) { memcpy(newImageDataPointer, oriImagedataPointer, newImagegetRowSpan); newImageDataPointer += newImagegetRowSpan; oriImagedataPointer += oriImage->getRowSpan(); } Ogre::Image newImage; newImage.loadDynamicImage(newImageData,oriImageWidth,oriImageHeight,1,oriImage->getFormat(),true); // 如果所选纹理大于64*64,就先resize if ( oriImageWidth > mPreviewImageWidth || oriImageHeight > mPreviewImageHeight ) newImage.resize(mPreviewImageWidth, mPreviewImageHeight); // 如果有alpha,要与黑白图进行混合 if ( newImage.getHasAlpha() ) { Ogre::uchar *tempPtr = newImage.getData(); assert (tempPtr); for ( size_t i=0; i<mPreviewImageHeight; ++i ) for ( size_t j=0; j<mPreviewImageWidth; ++j ) { // 取出alpha值 float alphaValue = (float)tempPtr[3] / 255.0f; // 计算出经过alpha混合后的颜色值 unsigned char r = tempPtr[2] * alphaValue; unsigned char g = tempPtr[1] * alphaValue; unsigned char b = tempPtr[0] * alphaValue; // 设置到image中 mCurrentPreviewImage.SetRGB(j,i,r,g,b); tempPtr += 4; } // 要把指针移回到图片数据的 tempPtr -= mPreviewImageHeight * mPreviewImageWidth * 4; // 设置到缩略图控件中 } // 没有alpha,就直接拷贝数据 else { memcpy ( mCurrentPreviewImage.GetData(), newImage.getData(), newImage.getSize() ); } }
int _tmain(int argc, _TCHAR* argv[]) { // ------------------------- Check for command line argument ------------------------------------------- if (! argv[1]) { printf("\n"); printf("Missing argument.\nExample: \"Converter.exe job1.cfg\""); return 0; } // ------------------------- Basic Ogre Engine initialization ------------------------------------------- Ogre::Root* root = new Ogre::Root; Ogre::RenderSystem* rendersys = root->getRenderSystemByName("Direct3D9 Rendering Subsystem"); rendersys->setConfigOption("Full Screen", "No"); rendersys->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour"); root->setRenderSystem(rendersys); Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General"); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); root->initialise(false); Ogre::RenderWindow* window = root->createRenderWindow("RAW2OGT", 800, 600, false); Ogre::SceneManager* scenemgr = root->createSceneManager(Ogre::SceneType::ST_GENERIC); Ogre::Camera* camera = scenemgr->createCamera("camera"); Ogre::Viewport* viewport = window->addViewport(camera); /*Ogre::Vector3 lightdir(0, -0.3, 0.75); lightdir.normalise(); Ogre::Light* l = scenemgr->createLight("tstLight"); l->setType(Ogre::Light::LT_DIRECTIONAL); l->setDirection(lightdir); l->setDiffuseColour(Ogre::ColourValue(1.0, 1.0, 1.0)); l->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));*/ scenemgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7)); // --------------------------------- Start convert ---------------------------------------------------- // Load job config Ogre::ConfigFile* terrainconfig = OGRE_NEW Ogre::ConfigFile(); terrainconfig->loadDirect(argv[1]); // Load info from [general] block Ogre::String heightmapfile = terrainconfig->getSetting("heightmap", "general"); Ogre::Real heightmapscale = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapscale", "general")); Ogre::Real heightmapoffset = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapoffset", "general")); Ogre::uint16 terrainsize = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("terrainsize", "general")); Ogre::Real worldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", "general")); Ogre::uint16 layercount = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("layercount", "general")); // initialise stream to heightmapfile Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(heightmapfile, "General"); size_t size = stream.get()->size(); // verify size if(size != terrainsize * terrainsize * 4) OGRE_EXCEPT( Ogre::Exception::ERR_INTERNAL_ERROR, "Size of stream does not match terrainsize!", "TerrainPage" ); // load to buffer float* buffer = OGRE_ALLOC_T(float, size, Ogre::MEMCATEGORY_GENERAL); stream->read(buffer, size); // apply scale and offset for(int i=0;i<terrainsize*terrainsize;i++) { buffer[i] = (buffer[i] + heightmapoffset) * heightmapscale; } // Terrain initialization Ogre::TerrainGlobalOptions* terrainglobals = OGRE_NEW Ogre::TerrainGlobalOptions(); terrainglobals->setMaxPixelError(1); //terrainglobals->setCompositeMapDistance(30000); //terrainglobals->setLightMapDirection(lightdir); //terrainglobals->setCompositeMapAmbient(scenemgr->getAmbientLight()); //terrainglobals->setCompositeMapDiffuse(l->getDiffuseColour()); Ogre::TerrainMaterialGeneratorA::SM2Profile* pMatProfile = static_cast<Ogre::TerrainMaterialGeneratorA::SM2Profile*>(terrainglobals->getDefaultMaterialGenerator()->getActiveProfile()); pMatProfile->setLightmapEnabled(false); pMatProfile->setCompositeMapEnabled(false); Ogre::TerrainGroup* terraingroup = OGRE_NEW Ogre::TerrainGroup(scenemgr, Ogre::Terrain::ALIGN_X_Z, terrainsize, worldsize); terraingroup->setFilenameConvention(Ogre::String("terrain"), Ogre::String("ogt")); terraingroup->setOrigin(Ogre::Vector3::ZERO); Ogre::Terrain* terrain = OGRE_NEW Ogre::Terrain(scenemgr); // terrainsettings Ogre::Terrain::ImportData& imp = terraingroup->getDefaultImportSettings(); imp.terrainSize = terrainsize; imp.worldSize = worldsize; imp.minBatchSize = 33; imp.maxBatchSize = 65; // use float RAW heightmap as input imp.inputFloat = buffer; // process texture layers imp.layerList.resize(layercount); Ogre::StringVector blendmaps(layercount); for(int i=0;i<layercount;i++) { // load layer info Ogre::String sectionStr = Ogre::StringConverter::toString(i); Ogre::Real layerworldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", sectionStr)); if (i==0) { // no blendmap at layer 0 (baselayer) Ogre::String specular = terrainconfig->getSetting("specular", sectionStr); Ogre::String normal = terrainconfig->getSetting("normal", sectionStr); // add layer imp.layerList[i].textureNames.push_back(specular); imp.layerList[i].textureNames.push_back(normal); imp.layerList[i].worldSize = layerworldsize; } else { Ogre::String specular = terrainconfig->getSetting("specular", sectionStr); Ogre::String normal = terrainconfig->getSetting("normal", sectionStr); Ogre::String blend = terrainconfig->getSetting("blend", sectionStr); // add layer imp.layerList[i].textureNames.push_back(specular); imp.layerList[i].textureNames.push_back(normal); imp.layerList[i].worldSize = layerworldsize; blendmaps[i] = blend; } } // load the terrain terrain->prepare(imp); terrain->load(); // load those blendmaps into the layers for(int j = 1;j < terrain->getLayerCount();j++) { Ogre::TerrainLayerBlendMap *blendmap = terrain->getLayerBlendMap(j); Ogre::Image img; img.load(blendmaps[j],"General"); int blendmapsize = terrain->getLayerBlendMapSize(); if(img.getWidth() != blendmapsize) img.resize(blendmapsize, blendmapsize); float *ptr = blendmap->getBlendPointer(); Ogre::uint8 *data = static_cast<Ogre::uint8*>(img.getPixelBox().data); for(int bp = 0;bp < blendmapsize * blendmapsize;bp++) ptr[bp] = static_cast<float>(data[bp]) / 255.0f; blendmap->dirty(); blendmap->update(); } // create filename for writing int pos = heightmapfile.find_last_of('.'); if (pos < 0) heightmapfile = heightmapfile + ".ogt"; else heightmapfile = heightmapfile.substr(0, pos) + ".ogt"; // save as Ogre .OGT terrain->save(heightmapfile); Ogre::LogManager::getSingletonPtr()->logMessage(Ogre::LogMessageLevel::LML_NORMAL, heightmapfile + " successfully written."); // debug viewing (exit with CTRL+C) camera->setPosition(-terrainsize, 7000, -terrainsize); camera->lookAt(terrainsize/2,0,terrainsize/2); root->startRendering(); return 0; }
void MaterialPreviewDialog::buildPreviewBitmap( const Ogre::String &texName ) { const Ogre::uchar BytePerPixel = 8; // 读取原始image Ogre::Image *oriImage = getPreviewImage(texName); // 源大纹理的大小 size_t oriImageHeight = oriImage->getHeight(); size_t oriImageWidth = oriImage->getWidth(); Ogre::uchar *oriImageData = oriImage->getData(); // 分配一个足够大的空间来保存新建的image的数据 size_t newImagegetRowSpan = oriImageWidth*oriImage->getBPP()/BytePerPixel; // 新建的image的行宽(单位为字节) Ogre::uchar *newImageData = OGRE_ALLOC_T(Ogre::uchar, oriImageHeight*newImagegetRowSpan, Ogre::MEMCATEGORY_GENERAL);//new Ogre::uchar[oriImageHeight*newImagegetRowSpan]; Ogre::uchar *newImageDataPointer = newImageData; Ogre::uchar *oriImagedataPointer = oriImageData; // 把所选的纹理的数据提取出来,并创建一个新的image for ( Ogre::uint i=0; i<oriImageHeight; ++i ) { memcpy(newImageDataPointer, oriImagedataPointer, newImagegetRowSpan); newImageDataPointer += newImagegetRowSpan; oriImagedataPointer += oriImage->getRowSpan(); } Ogre::Image newImage; newImage.loadDynamicImage(newImageData,oriImageWidth,oriImageHeight,1,oriImage->getFormat(),true); // 如果所选纹理大于64*64,就先resize if ( oriImageWidth > mPreviewImageWidth || oriImageHeight > mPreviewImageHeight ) newImage.resize(mPreviewImageWidth, mPreviewImageHeight); // 如果有alpha,要与黑白图进行混合 if ( newImage.getHasAlpha() ) { Ogre::ColourValue col; for ( int i=0; i<mPreviewImageWidth; ++i ) { for ( int j=0; j<mPreviewImageWidth; ++j ) { col = newImage.getColourAt(j,i,0); float alphaValue = col.a; unsigned char r = col.r*255 * alphaValue; unsigned char g = col.g*255 * alphaValue; unsigned char b = col.b*255 * alphaValue; // 设置到image中 mCurrentPreviewImage.SetRGB(j,i,r,g,b); } } } // 没有alpha,就直接拷贝数据 else { Ogre::ColourValue col; for ( int i=0; i<mPreviewImageWidth; ++i ) { for ( int j=0; j<mPreviewImageWidth; ++j ) { col = newImage.getColourAt(j,i,0); unsigned char r = col.r*255; unsigned char g = col.g*255; unsigned char b = col.b*255; // 设置到image中 mCurrentPreviewImage.SetRGB(j,i,r,g,b); } } } }
/* ----------------------------------------------------------------------- | build bullet height field shape and generate ogre mesh from grayscale image | | @param in : | @param out: raw data of height field terrain | ToDo: adjest grid scale, grid height, local scale, max/min height ----------------------------------------------------------------------- */ bool buildHeightFieldTerrainFromImage(const Ogre::String& filename, btDynamicsWorld* dynamicsWorld, btAlignedObjectArray<btCollisionShape*>& collisionShapes, void* &data) { Ogre::Image img; try { img.load(filename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); } catch(Ogre::Exception err) { LOG(err.what()); return false; } size_t grid_w = 65, grid_h = 65; // must be (2^N) + 1 size_t grid_max_w = 129, grid_max_h = 129; // must be (2^N) + 1 size_t img_w = img.getWidth(); size_t img_h = img.getHeight(); // validate image size is (2^N) + 1 if ((img_w-1) & (img_w-2)) img_w = grid_w; if ((img_h-1) & (img_h-2)) img_h = grid_h; //if (img_w > grid_max_w) img_w = grid_max_w; //if (img_h > grid_max_h) img_h = grid_max_h; LOG("LoadImage name=%s, width=%d, height=%d, width^2+1=%d, height^2+1=%d", filename.c_str(), img.getWidth(), img.getHeight(), img_w, img_h); img.resize(img_w, img_h); size_t pixelSize = Ogre::PixelUtil::getNumElemBytes(img.getFormat()); size_t bufSize = img.getSize() / pixelSize; data = new Ogre::Real[ bufSize ]; Ogre::Real* dest = static_cast<Ogre::Real*>(data); memset(dest, 0, bufSize); /* | @ Notice the alignment problem | - uchar to float alignment | - pixel format in bytes as rawdata type, also affects alignment */ Ogre::uchar* src = img.getData(); for (size_t i=0;i<bufSize;++i) { dest[i] = ((Ogre::Real)src[i * pixelSize] - 127.0f)/16.0f; } // parameter int upAxis = 1; btScalar gridSpacing = 5.0f; btScalar gridHeightScale = 0.2f; btScalar minHeight = -10.0f; btScalar maxHeight = 10.0f; btScalar defaultContactProcessingThreshold = BT_LARGE_FLOAT; btHeightfieldTerrainShape *heightfieldShape = new btHeightfieldTerrainShape(img_w, img_h, dest, gridHeightScale, minHeight, maxHeight, upAxis, PHY_FLOAT, false); btAssert(heightfieldShape && "null heightfield"); // shape btVector3 localScaling(1.0f, 1.0f, 1.0f); heightfieldShape->setLocalScaling(localScaling); collisionShapes.push_back(heightfieldShape); // rigidBody btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0))); btRigidBody::btRigidBodyConstructionInfo cInfo(0, motionState, heightfieldShape, btVector3(0,0,0)); btRigidBody* rigidBody = new btRigidBody(cInfo); rigidBody->setContactProcessingThreshold(defaultContactProcessingThreshold); int flags = rigidBody->getCollisionFlags(); rigidBody->setCollisionFlags(flags | btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT); dynamicsWorld->addRigidBody(rigidBody); // add ogre height field mesh Ogre::SceneManager* sceneMgr = Ogre::Root::getSingletonPtr()->getSceneManager("DefaultSceneManager"); btAssert(sceneMgr); Ogre::ManualObject* obj = sceneMgr->createManualObject("btHeightFieldEntity"); btVector3 aabbMin, aabbMax; heightfieldShape->getAabb(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), aabbMin, aabbMax); btHeightFieldProcessor callback(obj, "DefaultPlane"); heightfieldShape->processAllTriangles(&callback, aabbMin, aabbMax); sceneMgr->getRootSceneNode()->attachObject(obj); return true; }