void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) { const char *pszPath = CCFileUtils::fullPathFromRelativePath(pszPlist); CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFile(pszPath); string texturePath(""); CCDictionary<std::string, CCObject*>* metadataDict = (CCDictionary<std::string, CCObject*>*)dict->objectForKey(string("metadata")); if (metadataDict) { // try to read texture file name from meta data texturePath = string(valueForKey("textureFileName", metadataDict)); } if (! texturePath.empty()) { // build texture path relative to plist file // stringByDeletingLastPathComponent string textureBase(pszPath); int indexOfLastSeperator = textureBase.find_last_of('/'); if (indexOfLastSeperator == textureBase.length() - 1) { textureBase.erase(indexOfLastSeperator, 1); indexOfLastSeperator = textureBase.find_last_of('/'); } textureBase.erase(indexOfLastSeperator); // stringByAppendingPathComponent if (! textureBase.empty()) { texturePath = textureBase + "/" + texturePath; } } else { // build texture path by replacing file extension texturePath = pszPath; // remove .xxx size_t startPos = texturePath.find_last_of("."); texturePath = texturePath.erase(startPos); // append .png texturePath = texturePath.append(".png"); CCLOG("cocos2d: CCSpriteFrameCache: Trying to use file %s as texture", texturePath); } CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage(texturePath.c_str()); if (pTexture) { addSpriteFramesWithDictionary(dict, pTexture); } else { CCLOG("cocos2d: CCSpriteFrameCache: Couldn't load texture"); } }
void MapLoader::extractButtons() { TiXmlElement *textureElement = rootHandle.FirstChild("texture").ToElement(); string texturePath("none"); string surfaceType("none"); Vector2f position; Vector2f size; if (textureElement) { do { textureElement->QueryStringAttribute("source", &texturePath); textureElement->QueryStringAttribute("type", &surfaceType); TiXmlElement *buttonElement = textureElement->FirstChildElement("GUIbutton"); if (buttonElement) { do { scene->buttons.emplace_back(); GUIButton &button = scene->buttons.back(); buttonElement->QueryFloatAttribute("x", &position.x); buttonElement->QueryFloatAttribute("y", &position.y); buttonElement->QueryFloatAttribute("w", &size.x); buttonElement->QueryFloatAttribute("h", &size.y); button.texture = TextureLoader::getTexture(texturePath); button.texture.xTiling = 0.5f; button.texture.yTiling = 0.5f; } while ((buttonElement = buttonElement->NextSiblingElement("GUIbutton")) != nullptr); } texturePath = "none"; } while ((textureElement = textureElement->NextSiblingElement("texture")) != nullptr); } }
void MapLoader::extractWalls() { TiXmlElement *textureElement = rootHandle.FirstChild("texture").ToElement(); string texturePath("none"); string surfaceType("none"); if (textureElement) { do { textureElement->QueryStringAttribute("source", &texturePath); textureElement->QueryStringAttribute("type", &surfaceType); TiXmlElement *wallBoxElement = textureElement->FirstChildElement("wall"); if (wallBoxElement) { do { scene->walls.emplace_back(); PhysicsEntity &wall = scene->walls.back(); XmlHelper::extractPosition(wallBoxElement, wall.position); XmlHelper::extractRotation(wallBoxElement, wall.rotation); XmlHelper::extractScale(wallBoxElement, wall.scale); wall.texture = TextureLoader::getTexture(texturePath); wall.texture.xTiling = 0.5f; wall.texture.yTiling = 0.5f; wall.mesh = MeshLoader::getPortalBox(wall); wall.physBody = BoxCollider::generateCage(wall); } while ((wallBoxElement = wallBoxElement->NextSiblingElement("wall")) != nullptr); } texturePath = "none"; } while ((textureElement = textureElement->NextSiblingElement("texture")) != nullptr); } }
Prism::Font::Font(const std::string& aFilePath, const CU::Vector2<int>& aTextureSize) : myFilePath(aFilePath) , myTextureSize(aTextureSize) { ParseFontFile(myChars, myFilePath, myTextureSize.x, myTextureSize.y); std::string texturePath(aFilePath.begin(), aFilePath.end() - 4); texturePath += ".dds"; myTexture = Engine::GetInstance()->GetTextureContainer()->GetTexture(texturePath); }
Material *MaterialPrecache::ParseMaterial(const char *path) { QDomElement root; if (!OpenXMLFile(path, root)) { return nullptr; } QImage *texture = new QImage(); QString texturePath(PATH_MATERIAL_ROOT); texturePath += root.firstChildElement("texture").text(); if (!texture->load(OSLocalPath(texturePath))) { delete texture; DBGWARNING("!! Error precaching texture:" << path << ", for material:" << path); return nullptr; } QPainter::CompositionMode mode = StringToCompositionMode( root.firstChildElement("blendmode").text()); QDomElement eOpacity = root.firstChildElement("opacity"); QDomElement eTint = root.firstChildElement("tint"); QDomElement eNoFilter = root.firstChildElement("nofilter"); float opacity = eOpacity.isNull() ? 1.0f : eOpacity.text().toFloat(); int flags = Material::MF_NONE; if (XMLParseBoolean(eNoFilter)) { flags |= Material::MF_NEVER_FILTER; } if (eTint.isNull()) { return new Material(texture, opacity, mode, flags); } else { QColor tint = XMLParseColor(eTint); return new Material(texture, opacity, mode, tint, flags); } }
//----------------------------------------------------------------------------- /// Copy a texture from a KMZ to a cache. Note that the texture filename is modified void copySketchupTexture(const Torque::Path &path, String &textureFilename) { if (textureFilename.isEmpty()) return; Torque::Path texturePath(textureFilename); texturePath.setExtension(findTextureExtension(texturePath)); String cachedTexFilename = String::ToString("%s_%s.cached", TSShapeLoader::getShapePath().getFileName().c_str(), texturePath.getFileName().c_str()); Torque::Path cachedTexPath; cachedTexPath.setRoot(path.getRoot()); cachedTexPath.setPath(path.getPath()); cachedTexPath.setFileName(cachedTexFilename); cachedTexPath.setExtension(texturePath.getExtension()); FileStream *source; FileStream *dest; if ((source = FileStream::createAndOpen(texturePath.getFullPath(), Torque::FS::File::Read)) == NULL) return; if ((dest = FileStream::createAndOpen(cachedTexPath.getFullPath(), Torque::FS::File::Write)) == NULL) { delete source; return; } dest->copyFrom(source); delete dest; delete source; // Update the filename in the material cachedTexPath.setExtension(""); textureFilename = cachedTexPath.getFullPath(); }
void MapLoader::extractButtons() { // FIXME #if 0 XMLElement *textureElement = rootHandle.FirstChild("texture").ToElement(); string texturePath("none"); string surfaceType("none"); Vector2f position; Vector2f size; if (textureElement) { do { textureElement->QueryStringAttribute("source", &texturePath); textureElement->QueryStringAttribute("type", &surfaceType); XMLElement *buttonElement = textureElement->FirstChildElement("GUIbutton"); if (buttonElement) { do { scene->buttons.emplace_back(); GUIButton &button = scene->buttons.back(); buttonElement->QueryFloatAttribute("x", &position.x); buttonElement->QueryFloatAttribute("y", &position.y); buttonElement->QueryFloatAttribute("w", &size.x); buttonElement->QueryFloatAttribute("h", &size.y); button.material = MaterialLoader::fromTexture(texturePath); button.material.scaleU = button.material.scaleV = 2.f; } while ((buttonElement = buttonElement->NextSiblingElement("GUIbutton")) != nullptr); } texturePath = "none"; } while ((textureElement = textureElement->NextSiblingElement("texture")) != nullptr); } #endif }
int Renderer::preview( const std::string& fileName, const liqPreviewShaderOptions& options ) { CM_TRACE_FUNC("Renderer::preview("<<fileName<<","<<options.shaderNodeName<<")"); std::string shaderFileName; liqShader currentShader; MObject shaderObj; MString shader_type_TempForRefactoring;// [2/14/2012 yaoyansi] if ( options.fullShaderPath ) { // a full shader path was specified //cout <<"[liquid] got full path for preview !"<<endl; //shaderFileName = const_cast<char*>(options.shaderNodeName); std::string tmp( options.shaderNodeName ); currentShader.setShaderFileName(tmp.substr( 0, tmp.length() - 4 ) ); if ( options.type == "surface" ){ assert(0&&"we should use currentShader.shader_type_ex = \"surface\""); //currentShader.shader_type = SHADER_TYPE_SURFACE;// [2/14/2012 yaoyansi] shader_type_TempForRefactoring = "surface"; }else if ( options.type == "displacement" ){ assert(0&&"we should use currentShader.shader_type_ex = \"displacement\""); //currentShader.shader_type = SHADER_TYPE_DISPLACEMENT;// [2/14/2012 yaoyansi] shader_type_TempForRefactoring = "displacement"; } //cout <<"[liquid] options.shaderNodeName = " << options.shaderNodeName << endl; //cout <<"[liquid] options.type = "<<options.type<<endl; } else { // a shader node was specified MSelectionList shaderNameList; shaderNameList.add( options.shaderNodeName.c_str() ); shaderNameList.getDependNode( 0, shaderObj ); if( shaderObj == MObject::kNullObj ) { MGlobal::displayError( std::string( "Can't find node for " + options.shaderNodeName ).c_str() ); RiEnd(); return 0; } currentShader = liqShader( shaderObj ); shader_type_TempForRefactoring = currentShader.shader_type_ex; shaderFileName = currentShader.getShaderFileName(); } MFnDependencyNode assignedShader( shaderObj ); // Get the Pathes in globals node MObject globalObjNode; MString liquidShaderPath = "",liquidTexturePath = "",liquidProceduralPath = ""; MStatus status; MSelectionList globalList; // get the current project directory MString MELCommand = "workspace -q -rd"; MString MELReturn; MGlobal::executeCommand( MELCommand, MELReturn ); MString liquidProjectDir = MELReturn; status = globalList.add( "liquidGlobals" ); if ( globalList.length() > 0 ) { status.clear(); status = globalList.getDependNode( 0, globalObjNode ); MFnDependencyNode globalNode( globalObjNode ); liquidGetPlugValue( globalNode, "shaderPath", liquidShaderPath, status); liquidGetPlugValue( globalNode, "texturePath", liquidTexturePath, status); liquidGetPlugValue( globalNode, "proceduralPath", liquidProceduralPath, status); } if( fileName.empty() ) { RiBegin_liq( NULL ); #ifdef DELIGHT //RtPointer callBack( progressCallBack ); //RiOption( "statistics", "progresscallback", &callBack, RI_NULL ); #endif } else { liquidMessage2(messageInfo,"preview rib file: [%s]", fileName.c_str()); RiBegin_liq( (RtToken)fileName.c_str() ); } std::string liquidHomeDir = liquidSanitizeSearchPath( getEnvironment( "LIQUIDHOME" ) ); std::string shaderPath( "&:@:.:~:" + liquidHomeDir + "/lib/shaders" ); std::string texturePath( "&:@:.:~:" + liquidHomeDir + "/lib/textures" ); std::string proceduralPath( "&:@:.:~:" + liquidHomeDir + "/lib/shaders" ); std::string projectDir = std::string( liquidSanitizeSearchPath( liquidProjectDir ).asChar() ); if ( liquidProjectDir != "") { shaderPath += ":" + projectDir; texturePath += ":" + projectDir; proceduralPath += ":" + projectDir; } if ( liquidShaderPath != "" ) shaderPath += ":" + std::string( liquidSanitizeSearchPath( parseString( liquidShaderPath, false ) ).asChar()); if ( liquidTexturePath != "" ) texturePath += ":" + std::string( liquidSanitizeSearchPath( parseString( liquidTexturePath, false) ).asChar()); if ( liquidProceduralPath != "" ) proceduralPath += ":" + std::string( liquidSanitizeSearchPath( parseString( liquidProceduralPath, false) ).asChar()); RtString list( const_cast< RtString >( shaderPath.c_str() ) ); RiOption( "searchpath", "shader", &list, RI_NULL ); RtString texPath( const_cast< RtString >( texturePath.c_str() ) ); if( texPath[ 0 ] ) RiOption( "searchpath","texture", &texPath, RI_NULL ); RtString procPath( const_cast< RtString >( proceduralPath.c_str() ) ); if( procPath[ 0 ] ) RiOption( "searchpath","procedural", &procPath, RI_NULL ); RiShadingRate( ( RtFloat )options.shadingRate ); RiPixelSamples( options.pixelSamples, options.pixelSamples ); #ifdef PRMAN if ( MString( "PRMan" ) == liqglo.liquidRenderer.renderName ) RiPixelFilter( RiCatmullRomFilter, 4., 4. ); #elif defined( DELIGHT ) if ( MString( "3Delight" ) == liqglo.liquidRenderer.renderName ) RiPixelFilter( RiSeparableCatmullRomFilter, 4., 4. ); // RiPixelFilter( RiMitchellFilter, 4., 4.); #else RiPixelFilter( RiCatmullRomFilter, 4., 4. ); #endif RiFormat( ( RtInt )options.displaySize, ( RtInt )options.displaySize, 1.0 ); if( options.backPlane ) { RiDisplay( const_cast< RtString >( options.displayName.c_str() ), const_cast< RtString >( options.displayDriver.c_str() ), RI_RGB, RI_NULL ); } else { // Alpha might be useful RiDisplay( const_cast< RtString >( options.displayName.c_str() ), const_cast< RtString >( options.displayDriver.c_str() ), RI_RGBA, RI_NULL ); } RtFloat fov( 22.5 ); RiProjection( "perspective", "fov", &fov, RI_NULL ); RiTranslate( 0, 0, 2.75 ); RiExposure(1, currentShader.m_previewGamma); RtInt visible = 1; RtString transmission = "transparent"; RiAttribute( "visibility", ( RtToken ) "camera", &visible, RI_NULL ); RiAttribute( "visibility", ( RtToken ) "trace", &visible, RI_NULL ); // RiAttribute( "visibility", ( RtToken ) "transmission", ( RtPointer ) &transmission, RI_NULL ); RiWorldBegin(); RiReverseOrientation(); RiTransformBegin(); RiRotate( -90., 1., 0., 0. ); RiCoordinateSystem( "_environment" ); RiTransformEnd(); RtLightHandle ambientLightH, directionalLightH; RtFloat intensity; intensity = 0.05 * (RtFloat)options.previewIntensity; ambientLightH = RiLightSource( "ambientlight", "intensity", &intensity, RI_NULL ); intensity = 0.9 * (RtFloat)options.previewIntensity; RtPoint from; RtPoint to; from[0] = -1.; from[1] = 1.5; from[2] = -1.; to[0] = 0.; to[1] = 0.; to[2] = 0.; RiTransformBegin(); RiRotate( 55., 1, 0, 0 ); RiRotate( 30., 0, 1, 0 ); directionalLightH = RiLightSource( "liquiddistant", "intensity", &intensity, RI_NULL ); RiTransformEnd(); intensity = 0.2f * (RtFloat)options.previewIntensity; from[0] = 1.3f; from[1] = -1.2f; from[2] = -1.; RiTransformBegin(); RiRotate( -50., 1, 0, 0 ); RiRotate( -40., 0, 1, 0 ); directionalLightH = RiLightSource( "liquiddistant", "intensity", &intensity, RI_NULL ); RiTransformEnd(); RiAttributeBegin(); //ymesh omit this section, because liqShader::writeRibAttributes() do this work in that branch //I don't use liqShader::writeRibAttributes(), so I use this section. -yayansi float displacementBounds = 0.; liquidGetPlugValue( assignedShader, "displacementBound", displacementBounds, status); if ( displacementBounds > 0. ) { RtString coordsys = "shader"; RiArchiveRecord( RI_COMMENT, "ymesh omit this section, because liqShader::writeRibAttributes do this work in that branch" ); RiAttribute( "displacementbound", "coordinatesystem", &coordsys, RI_NULL ); RiAttribute( "displacementbound", "sphere", &displacementBounds, "coordinatesystem", &coordsys, RI_NULL ); } //LIQ_GET_SHADER_FILE_NAME( shaderFileName, options.shortShaderName, currentShader ); // output shader space MString shadingSpace; liquidGetPlugValue( assignedShader, "shaderSpace", shadingSpace, status); if ( shadingSpace != "" ) { RiTransformBegin(); RiCoordSysTransform( (char*) shadingSpace.asChar() ); } RiTransformBegin(); // Rotate shader space to make the preview more interesting RiRotate( 60., 1., 0., 0. ); RiRotate( 60., 0., 1., 0. ); RtFloat scale( 1.f / ( RtFloat )options.objectScale ); RiScale( scale, scale, scale ); if ( shader_type_TempForRefactoring=="surface" || shader_type_TempForRefactoring=="shader"/*currentShader.shader_type == SHADER_TYPE_SURFACE || currentShader.shader_type == SHADER_TYPE_SHADER */ ) // [2/14/2012 yaoyansi] { RiColor( currentShader.rmColor ); RiOpacity( currentShader.rmOpacity ); //cout << "Shader: " << shaderFileName << endl; if ( options.fullShaderPath ) RiSurface( (RtToken)shaderFileName.c_str(), RI_NULL ); else { liqShader liqAssignedShader( shaderObj ); liqAssignedShader.forceAs = SHADER_TYPE_SURFACE; liqAssignedShader.write(); } } else if ( shader_type_TempForRefactoring=="displacement"/*currentShader.shader_type == SHADER_TYPE_DISPLACEMENT*/ ) // [2/14/2012 yaoyansi] { RtToken Kd( "Kd" ); RtFloat KdValue( 1. ); #ifdef GENERIC_RIBLIB // !!! current ribLib has wrong interpretation of RiSurface parameters RiSurface( "plastic", Kd, &KdValue, RI_NULL ); #else RiSurface( "plastic", &Kd, &KdValue, RI_NULL ); #endif if ( options.fullShaderPath ) RiDisplacement( (RtToken)shaderFileName.c_str(), RI_NULL ); else { liqShader liqAssignedShader( shaderObj ); liqAssignedShader.forceAs = SHADER_TYPE_DISPLACEMENT; liqAssignedShader.write(); } } RiTransformEnd(); if ( shadingSpace != "" ) RiTransformEnd(); switch( options.primitiveType ) { case CYLINDER: { RiReverseOrientation(); RiScale( 0.95, 0.95, 0.95 ); RiRotate( 60., 1., 0., 0. ); RiTranslate( 0., 0., -0.05 ); RiCylinder( 0.5, -0.3, 0.3, 360., RI_NULL ); RiTranslate( 0., 0., 0.3f ); RiTorus( 0.485, 0.015, 0., 90., 360., RI_NULL ); RiDisk( 0.015, 0.485, 360., RI_NULL ); RiTranslate( 0., 0., -0.6 ); RiTorus( 0.485, 0.015, 270., 360., 360., RI_NULL ); RiReverseOrientation(); RiDisk( -0.015, 0.485, 360., RI_NULL ); break; } case TORUS: { RiRotate( 45., 1., 0., 0. ); RiTranslate( 0., 0., -0.05 ); RiReverseOrientation(); RiTorus( 0.3f, 0.2f, 0., 360., 360., RI_NULL ); break; } case PLANE: { RiScale( 0.5, 0.5, 0.5 ); RiReverseOrientation(); static RtPoint plane[4] = { { -1., 1., 0. }, { 1., 1., 0. }, { -1., -1., 0. }, { 1., -1., 0. } }; RiPatch( RI_BILINEAR, RI_P, (RtPointer) plane, RI_NULL ); break; } case TEAPOT: { RiTranslate( 0.06f, -0.18f, 0. ); RiRotate( -120., 1., 0., 0. ); RiRotate( 130., 0., 0., 1. ); RiScale( 0.2f, 0.2f, 0.2f ); RiArchiveRecord( RI_VERBATIM, "Geometry \"teapot\"" ); break; } case CUBE: { /* Lovely cube with rounded corners and edges */ RiScale( 0.35f, 0.35f, 0.35f ); RiRotate( 60., 1., 0., 0. ); RiRotate( 60., 0., 0., 1. ); RiTranslate( 0.11f, 0., -0.08f ); RiReverseOrientation(); static RtPoint top[ 4 ] = { { -0.95, 0.95, -1. }, { 0.95, 0.95, -1. }, { -0.95, -0.95, -1. }, { 0.95, -0.95, -1. } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) top, RI_NULL ); static RtPoint bottom[ 4 ] = { { 0.95, 0.95, 1. }, { -0.95, 0.95, 1. }, { 0.95, -0.95, 1. }, { -0.95, -0.95, 1. } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) bottom, RI_NULL ); static RtPoint right[ 4 ] = { { -0.95, -1., -0.95 }, { 0.95, -1., -0.95 }, { -0.95, -1., 0.95 }, { 0.95, -1., 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) right, RI_NULL ); static RtPoint left[ 4 ] = { { 0.95, 1., -0.95 }, { -0.95, 1., -0.95 }, { 0.95, 1., 0.95 }, { -0.95, 1., 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) left, RI_NULL ); static RtPoint front[ 4 ] = { {-1., 0.95, -0.95 }, { -1., -0.95, -0.95 }, { -1., 0.95, 0.95 }, { -1., -0.95, 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) front, RI_NULL ); static RtPoint back[ 4 ] = { { 1., -0.95, -0.95 }, { 1., 0.95, -0.95 }, { 1., -0.95, 0.95 }, { 1., 0.95, 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) back, RI_NULL ); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0.95, 0. ); RiRotate( 90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, -0.95, 0. ); RiRotate( 180., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0., 0., 0.95 ); RiTransformBegin(); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiRotate( 180., 0., 0., 1. ); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); RiRotate( 90., 1., 0., 0. ); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiRotate( 90., 0., 1., 0. ); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0., 0., -0.95 ); RiTransformBegin(); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiRotate( 180., 0., 0., 1. ); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); RiRotate( 90., 1., 0., 0. ); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 180., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiRotate( -90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiRotate( 90., 0., 1., 0. ); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiRotate( -90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 180., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); break; } case CUSTOM: { //cout <<"custom : "<<options.customRibFile<<endl; if ( fileExists( options.customRibFile.c_str() ) ) { RiReadArchive( const_cast< RtToken >( options.customRibFile.c_str() ), NULL, RI_NULL ); } break; } case SPHERE: default: { RiRotate( 60., 1., 0., 0. ); RiReverseOrientation(); RiSphere( 0.5, -0.5, 0.5, 360., RI_NULL ); break; } } RiAttributeEnd(); /* * Backplane */ if( options.backPlane ) { if ( options.customBackplane.empty() ) { RiAttributeBegin(); RiScale( 0.91, 0.91, 0.91 ); if( MString("displacement")==shader_type_TempForRefactoring/*SHADER_TYPE_DISPLACEMENT == currentShader.shader_type*/ ) // [2/14/2012 yaoyansi] { RtColor bg = { 0.698, 0.698, 0. }; RiColor( bg ); } else RiSurface( const_cast< RtToken >( options.backPlaneShader.c_str() ), RI_NULL ); static RtPoint backplane[4] = { { -1., 1., 2. }, { 1., 1., 2. }, { -1., -1., 2. }, { 1., -1., 2. } }; RiPatch( RI_BILINEAR, RI_P, (RtPointer) backplane, RI_NULL ); RiAttributeEnd(); } else { if ( fileExists( options.customBackplane.c_str() ) ) { RiAttributeBegin(); RiScale( 1., 1., -1. ); RiReadArchive( const_cast< RtString >( options.customBackplane.c_str() ), NULL, RI_NULL ); RiAttributeEnd(); } } } RiWorldEnd(); /* this caused maya to hang up under windoof - Alf #ifdef _WIN32 // Wait until the renderer is done while( !fileFullyAccessible( options.displayName.c_str() ) ); #endif */ RiEnd(); if(liqglo.m_logMsgFlush) { fflush( NULL ); } }
void Model::LoadMaterials(const aiScene* assimpScene, std::string directoryPath) { // Get the number of materials in the model. const unsigned int numMaterials = assimpScene->mNumMaterials; // Resize the materials lost so that we don't waste time dynamically // resizing the vector. m_materials.resize(numMaterials); // For each material... for (unsigned int m = 0; m < numMaterials; ++m) { // Get the ASSIMP material. const aiMaterial* assimpMaterial = assimpScene->mMaterials[m]; // Create our own new material. std::shared_ptr<Material> material = std::make_shared<Material>(); // Populate the material's name. aiString name; if (assimpMaterial->Get(AI_MATKEY_NAME, name) == AI_SUCCESS) { material->SetName(std::string(name.data)); } // Populate the material's diffuse color. aiColor3D diffuseColor; if (assimpMaterial->Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor) == AI_SUCCESS) { material->SetDiffuseColor(glm::vec3( diffuseColor.r, diffuseColor.g, diffuseColor.b )); } // Populate the material's specular color. aiColor3D specularColor; if (assimpMaterial->Get(AI_MATKEY_COLOR_SPECULAR, specularColor) == AI_SUCCESS) { material->SetSpecularColor(glm::vec3( specularColor.r, specularColor.g, specularColor.b )); } // Populate the material's ambient color. aiColor3D ambientColor; if (assimpMaterial->Get(AI_MATKEY_COLOR_AMBIENT, ambientColor) == AI_SUCCESS) { material->SetAmbientColor(glm::vec3( ambientColor.r, ambientColor.g, ambientColor.b )); } // Populate the material's emissive color. aiColor3D emissiveColor; if (assimpMaterial->Get(AI_MATKEY_COLOR_AMBIENT, emissiveColor) == AI_SUCCESS) { material->SetEmissiveColor(glm::vec3( emissiveColor.r, emissiveColor.g, emissiveColor.b )); } // Populate the material's shininess. float shininess; if (assimpMaterial->Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) { material->SetShininess(shininess); } // Populate the material's diffuse texture path. // Note: Other textures (specular, emissive, etc) are ignored. aiString diffuseTexturePath; if (assimpMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &diffuseTexturePath) == AI_SUCCESS) { std::string texturePath(diffuseTexturePath.data); if (texturePath.at(0) != '/') { texturePath = "/" + texturePath; } material->SetDiffuseTexturePath(directoryPath + texturePath); } // Add the material to the list. m_materials[m] = material; } }
State::stateResult_t VisibilitySubdivisionRenderer::doEnableState( FrameContext & context, Node *, const RenderParam & rp) { if (rp.getFlag(SKIP_RENDERER)) { return State::STATE_SKIPPED; } if (viSu == nullptr) { // Invalid information. => Fall back to standard rendering. return State::STATE_SKIPPED; } // [AccumRendering] if(accumRenderingEnabled){ // camera moved? -> start new frame const Geometry::Matrix4x4 & newCamMat=context.getCamera()->getWorldTransformationMatrix(); if(newCamMat!=lastCamMatrix){ lastCamMatrix = newCamMat; startRuntime=0; } }else{ startRuntime=0; } // ---- uint32_t renderedTriangles = 0; if (hold) { for (const auto & object : holdObjects) { if (debugOutput) { debugDisplay(renderedTriangles, object, context, rp); } else { context.displayNode(object, rp); } } return State::STATE_SKIP_RENDERING; } Geometry::Vec3 pos = context.getCamera()->getWorldOrigin(); bool refreshCache = false; // Check if cached cell can be used. if (currentCell == nullptr || !currentCell->getBB().contains(pos)) { currentCell = viSu->getNodeAtPosition(pos); refreshCache = true; } if (currentCell == nullptr || !currentCell->isLeaf()) { // Invalid information. => Fall back to standard rendering. return State::STATE_SKIPPED; } if (refreshCache) { try { const auto & vv = getVV(currentCell); const uint32_t maxIndex = vv.getIndexCount(); objects.clear(); objects.reserve(maxIndex); for(uint_fast32_t index = 0; index < maxIndex; ++index) { if(vv.getBenefits(index) == 0) { continue; } const VisibilityVector::costs_t costs = vv.getCosts(index); const VisibilityVector::benefits_t benefits = vv.getBenefits(index); const float score = static_cast<float>(costs) / static_cast<float>(benefits); objects.emplace_back(score, vv.getNode(index)); } } catch(...) { // Invalid information. => Fall back to standard rendering. return State::STATE_SKIPPED; } if (displayTexturedDepthMeshes) { #ifdef MINSG_EXT_OUTOFCORE for (const auto & depthMesh : depthMeshes) { OutOfCore::getCacheManager().setUserPriority(depthMesh.get(), 0); } #endif /* MINSG_EXT_OUTOFCORE */ depthMeshes.clear(); depthMeshes.reserve(6); textures.clear(); textures.reserve(6); const std::string dmDirectionStrings[6] = { "-dir_x1_y0_z0", "-dir_x-1_y0_z0", "-dir_x0_y1_z0", "-dir_x0_y-1_z0", "-dir_x0_y0_z1", "-dir_x0_y0_z-1" }; for (auto & dmDirectionString : dmDirectionStrings) { Util::GenericAttribute * attrib = currentCell->getAttribute("DepthMesh" + dmDirectionString); if (attrib == nullptr) { continue; } Util::FileName dmMeshPath(attrib->toString()); Util::Reference<Rendering::Mesh> dmMesh; #ifdef MINSG_EXT_OUTOFCORE Util::GenericAttribute * bbAttrib = currentCell->getAttribute("DepthMesh" + dmDirectionString + "-bounds"); if (bbAttrib == nullptr) { WARN("Found depth mesh with no bounding box."); continue; } std::vector<float> bbValues = Util::StringUtils::toFloats(bbAttrib->toString()); FAIL_IF(bbValues.size() != 6); const Geometry::Box meshBB(Geometry::Vec3(bbValues[0], bbValues[1], bbValues[2]), bbValues[3], bbValues[4], bbValues[5]); dmMesh = OutOfCore::addMesh(dmMeshPath, meshBB); #else /* MINSG_EXT_OUTOFCORE */ dmMesh = Rendering::Serialization::loadMesh(dmMeshPath); #endif /* MINSG_EXT_OUTOFCORE */ depthMeshes.emplace_back(dmMesh); // Count the depth mesh here already. renderedTriangles += dmMesh->getPrimitiveCount(); Util::GenericAttribute * texAttrib = currentCell->getAttribute("Texture" + dmDirectionString); if (texAttrib == nullptr) { continue; } Util::FileName texturePath(texAttrib->toString()); Util::Reference<Rendering::Texture> texture = Rendering::Serialization::loadTexture(texturePath); if (texture.isNull()) { WARN("Loading texture for depth mesh failed."); continue; } textures.emplace_back(texture); } } } const Geometry::Frustum & frustum = context.getCamera()->getFrustum(); holdObjects.clear(); holdObjects.reserve(objects.size()); std::sort(objects.begin(), objects.end()); for(const auto & ratioObjectPair : objects) { object_ptr o = ratioObjectPair.second; #ifdef MINSG_EXT_OUTOFCORE OutOfCore::getCacheManager().setUserPriority(o->getMesh(), 5); #endif /* MINSG_EXT_OUTOFCORE */ if (conditionalFrustumTest(frustum, o->getWorldBB(), rp)) { // [AccumRendering] // skip geometry rendered in the last frame if(renderedTriangles<startRuntime){ renderedTriangles += o->getTriangleCount(); continue; } // ---- if (debugOutput) { debugDisplay(renderedTriangles, o, context, rp); } else { context.displayNode(o, rp); renderedTriangles += o->getTriangleCount(); } holdObjects.push_back(o); } if (maxRuntime != 0 && renderedTriangles >= startRuntime+maxRuntime) { break; } } // Draw the textured depth meshes at the end. if (displayTexturedDepthMeshes) { context.getRenderingContext().pushAndSetPolygonOffset(Rendering::PolygonOffsetParameters(polygonOffsetFactor, polygonOffsetUnits)); auto texIt = textures.cbegin(); for (const auto & depthMesh : depthMeshes) { context.getRenderingContext().pushAndSetShader(getTDMShader()); context.getRenderingContext().pushAndSetTexture(0,texIt->get()); if (conditionalFrustumTest(frustum, depthMesh->getBoundingBox(), rp)) { context.displayMesh(depthMesh.get()); } context.getRenderingContext().popTexture(0); context.getRenderingContext().popShader(); #ifdef MINSG_EXT_OUTOFCORE OutOfCore::getCacheManager().setUserPriority(depthMesh.get(), 2); #endif /* MINSG_EXT_OUTOFCORE */ ++texIt; } context.getRenderingContext().popPolygonOffset(); } // [AccumRendering] startRuntime=renderedTriangles; // ---- return State::STATE_SKIP_RENDERING; }
/** * \brief callback called when a mesh data is encountered during the .x file load * \param Name - name of the Mesh (const char*) * \param meshData - the mesh data * \param materials - material array * \param effectInstances - effect files / settings for the mesh * \param numMaterials - number of materials in the mesh * \param adjacency - adjacency array * \param pSkinInfo - skin info. * \param retNewMeshContainer - output pointer to assign our newly created mesh container * \return success code * \author Keith Ditchburn \date 17 July 2005 */ HRESULT CMeshHierarchy::CreateMeshContainer( LPCSTR Name, CONST D3DXMESHDATA *meshData, CONST D3DXMATERIAL *materials, CONST D3DXEFFECTINSTANCE *effectInstances, DWORD numMaterials, CONST DWORD *adjacency, LPD3DXSKININFO pSkinInfo, LPD3DXMESHCONTAINER* retNewMeshContainer) { // Create a mesh container structure to fill and initilaise to zero values // Note: I use my extended version of the structure (D3DXMESHCONTAINER_EXTENDED) defined in MeshStructures.h D3DXMESHCONTAINER_EXTENDED *newMeshContainer=new D3DXMESHCONTAINER_EXTENDED; ZeroMemory(newMeshContainer, sizeof(D3DXMESHCONTAINER_EXTENDED)); // Always a good idea to initialise return pointer before proceeding *retNewMeshContainer = 0; // The mesh name (may be 0) needs copying over if (Name && strlen(Name)) { newMeshContainer->Name=CUtility::DuplicateCharString(Name); CUtility::DebugString("Added mesh: "+ToString(Name)+"\n"); } else { CUtility::DebugString("Added Mesh: no name given\n"); } // The mesh type (D3DXMESHTYPE_MESH, D3DXMESHTYPE_PMESH or D3DXMESHTYPE_PATCHMESH) if (meshData->Type!=D3DXMESHTYPE_MESH) { // This demo does not handle mesh types other than the standard // Other types are D3DXMESHTYPE_PMESH (progressive mesh) and D3DXMESHTYPE_PATCHMESH (patch mesh) DestroyMeshContainer(newMeshContainer); return E_FAIL; } newMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH; // Adjacency data - holds information about triangle adjacency, required by the ID3DMESH object DWORD dwFaces = meshData->pMesh->GetNumFaces(); newMeshContainer->pAdjacency = new DWORD[dwFaces*3]; memcpy(newMeshContainer->pAdjacency, adjacency, sizeof(DWORD) * dwFaces*3); // Get the Direct3D device, luckily this is held in the mesh itself (Note: must release it when done with it) LPDIRECT3DDEVICE9 pd3dDevice = 0; meshData->pMesh->GetDevice(&pd3dDevice); D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; meshData->pMesh->GetDeclaration(decl); HRESULT res; DWORD dwVertexStride = meshData->pMesh->GetNumBytesPerVertex (); DWORD dwNumDeclarations = 0; bool haveNormals = false; for (int i=0; (i < MAX_FVF_DECL_SIZE) && (decl[i].Stream != 0xFF); i++) { if (decl[dwNumDeclarations].Usage == D3DDECLUSAGE_NORMAL) haveNormals = true; if (decl[dwNumDeclarations].Usage == D3DDECLUSAGE_TANGENT) { dwNumDeclarations = 0; break; } dwNumDeclarations++; } if (dwNumDeclarations) { if (!haveNormals) { // normals decl[dwNumDeclarations].Stream = 0; decl[dwNumDeclarations].Offset = (WORD)dwVertexStride; decl[dwNumDeclarations].Type = D3DDECLTYPE_FLOAT3; decl[dwNumDeclarations].Method = D3DDECLMETHOD_DEFAULT; decl[dwNumDeclarations].Usage = D3DDECLUSAGE_NORMAL; decl[dwNumDeclarations].UsageIndex = 0; dwVertexStride += sizeof(float)*3; dwNumDeclarations++; } // tangent decl[dwNumDeclarations].Stream = 0; decl[dwNumDeclarations].Offset = (WORD)dwVertexStride; decl[dwNumDeclarations].Type = D3DDECLTYPE_FLOAT3; decl[dwNumDeclarations].Method = D3DDECLMETHOD_DEFAULT; decl[dwNumDeclarations].Usage = D3DDECLUSAGE_TANGENT; decl[dwNumDeclarations].UsageIndex = 0; dwNumDeclarations++; // ending element memset (&decl[dwNumDeclarations], 0, sizeof(D3DVERTEXELEMENT9)); decl[dwNumDeclarations].Stream = 0xFF; decl[dwNumDeclarations].Type = D3DDECLTYPE_UNUSED; } res = meshData->pMesh->CloneMesh(meshData->pMesh->GetOptions(),decl,pd3dDevice,&newMeshContainer->MeshData.pMesh); assert(res == D3D_OK); if (!haveNormals) { res = D3DXComputeNormals(newMeshContainer->MeshData.pMesh,newMeshContainer->pAdjacency); // compute normals assert(res == D3D_OK); } res = D3DXComputeTangent(newMeshContainer->MeshData.pMesh,0,0,1,TRUE,NULL); // compute tangent(u) assert(res == D3D_OK); //newMeshContainer->MeshData.pMesh=meshData->pMesh; newMeshContainer->MeshData.pMesh->AddRef(); // Create material and texture arrays. Note that I always want to have at least one newMeshContainer->NumMaterials = max(numMaterials,1); newMeshContainer->exMaterials = new D3DMATERIAL9[newMeshContainer->NumMaterials]; newMeshContainer->exTextures = new LPDIRECT3DTEXTURE9[newMeshContainer->NumMaterials]; ZeroMemory(newMeshContainer->exTextures, sizeof(LPDIRECT3DTEXTURE9) * newMeshContainer->NumMaterials); if (numMaterials>0) { // Load all the textures and copy the materials over for(DWORD i = 0; i < numMaterials; ++i) { newMeshContainer->exTextures[i] = 0; newMeshContainer->exMaterials[i]=materials[i].MatD3D; if(materials[i].pTextureFilename) { std::string texturePath(materials[i].pTextureFilename); if (CUtility::FindFile(&texturePath)) { // Use the D3DX function to load the texture if(FAILED(D3DXCreateTextureFromFile(pd3dDevice, texturePath.c_str(), &newMeshContainer->exTextures[i]))) { CUtility::DebugString("Could not load texture: "+texturePath+"\n"); } } else { CUtility::DebugString("Could not find texture: "+ToString(materials[i].pTextureFilename)+"\n"); } } } } else // make a default material in the case where the mesh did not provide one { ZeroMemory(&newMeshContainer->exMaterials[0], sizeof( D3DMATERIAL9 ) ); newMeshContainer->exMaterials[0].Diffuse.r = 0.5f; newMeshContainer->exMaterials[0].Diffuse.g = 0.5f; newMeshContainer->exMaterials[0].Diffuse.b = 0.5f; newMeshContainer->exMaterials[0].Specular = newMeshContainer->exMaterials[0].Diffuse; newMeshContainer->exTextures[0]=0; } // If there is skin data associated with the mesh copy it over if (pSkinInfo) { // save off the SkinInfo newMeshContainer->pSkinInfo = pSkinInfo; pSkinInfo->AddRef(); // Need an array of offset matrices to move the vertices from the figure space to the bone's space UINT numBones = pSkinInfo->GetNumBones(); newMeshContainer->exBoneOffsets = new D3DXMATRIX[numBones]; // Create the arrays for the bones and the frame matrices newMeshContainer->exFrameCombinedMatrixPointer = new D3DXMATRIX*[numBones]; // get each of the bone offset matrices so that we don't need to get them later for (UINT i = 0; i < numBones; i++) newMeshContainer->exBoneOffsets[i] = *(newMeshContainer->pSkinInfo->GetBoneOffsetMatrix(i)); CUtility::DebugString("Mesh has skinning info.\n Number of bones is: "+ToString(numBones)+"\n"); // Note: in the Microsoft samples a GenerateSkinnedMesh function is called here in order to prepare // the skinned mesh data for optimial hardware acceleration. As mentioned in the notes this sample // does not do hardware skinning but instead uses software skinning. } else { // No skin info so 0 all the pointers newMeshContainer->pSkinInfo = 0; newMeshContainer->exBoneOffsets = 0; newMeshContainer->exSkinMesh = 0; newMeshContainer->exFrameCombinedMatrixPointer = 0; } // When we got the device we caused an internal reference count to be incremented // So we now need to release it pd3dDevice->Release(); // The mesh may contain a reference to an effect file if (effectInstances) { if (effectInstances->pEffectFilename) CUtility::DebugString("This .x file references an effect file. Effect files are not handled by this demo\n"); } // Set the output mesh container pointer to our newly created one *retNewMeshContainer = newMeshContainer; return S_OK; }
void AsyncLoadPlist::loadPlistAsync(const char *pszPlist, cocos2d::CCObject *target, SEL_CallFuncO selector) { CCAssert(pszPlist, "plist filename should not be NULL"); // 读取plist数据,获得图片路径 const char *pszPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pszPlist).c_str(); CCDictionary *dict = CCDictionary::createWithContentsOfFileThreadSafe(pszPath); std::string texturePath(""); CCDictionary* metadataDict = (CCDictionary*)dict->objectForKey("metadata"); if (metadataDict) { // try to read texture file name from meta data texturePath = metadataDict->valueForKey("textureFileName")->getCString(); } // CCDictionary::createWithContentsOfFileThreadSafe 需要释放dict dict->release(); if (! texturePath.empty()) { // build texture path relative to plist file texturePath = CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile(texturePath.c_str(), pszPath); } else { CCAssert(0, "在plist文件中没有找到图片文件"); return; } // 从texturePath中取文件名 如/../../filename.png 则filename.png std::string textureFileName = texturePath.substr(texturePath.rfind('/') + 1); // 从TextureCache中找到纹理就直接返回 CCTexture2D *texture = CCTextureCache::sharedTextureCache()->textureForKey(textureFileName.c_str()); if (texture != NULL) { if (target && selector) { (target->*selector)(CCString::create(pszPlist)); } return; } // lazy init if (s_pSem == NULL) { #if CC_ASYNC_TEXTURE_CACHE_USE_NAMED_SEMAPHORE s_pSem = sem_open(CC_ASYNC_TEXTURE_CACHE_SEMAPHORE, O_CREAT, 0644, 0); if( s_pSem == SEM_FAILED ) { CCLOG( "CCTextureCache async thread semaphore init error: %s\n", strerror( errno ) ); s_pSem = NULL; return; } #else int semInitRet = sem_init(&s_sem, 0, 0); if( semInitRet < 0 ) { CCLOG( "CCTextureCache async thread semaphore init error: %s\n", strerror( errno ) ); return; } s_pSem = &s_sem; #endif s_pLoadStructQueue = new std::queue<LoadStruct*>(); s_pImageQueue = new std::queue<ImageInfo*>(); pthread_mutex_init(&s_loadStructQueueMutex, NULL); pthread_mutex_init(&s_ImageInfoMutex, NULL); pthread_create(&s_loadingThread, NULL, loadImage, NULL); need_quit = false; } if (0 == s_nAsyncRefCount) { CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(AsyncLoadPlist::loadPlistAsyncCallBack), this, 0, false); } ++s_nAsyncRefCount; if (target) { target->retain(); } // generate async struct LoadStruct *data = new LoadStruct(); data->texturePath = texturePath.c_str(); data->plistFileName = pszPlist; data->target = target; data->selector = selector; // add async struct into queue pthread_mutex_lock(&s_loadStructQueueMutex); s_pLoadStructQueue->push(data); pthread_mutex_unlock(&s_loadStructQueueMutex); sem_post(s_pSem); }