Example #1
0
/**
 * Load shader module from file.
 */
VkResult VkcPipeline::createShader(VkShaderModule &shader, QString fileName, const VkcDevice *device)
{
    // Open shader file in binary.
    QFile shaderFile("data/shaders/" + fileName);

    if(!shaderFile.exists())
    {
        qDebug() << "ERROR:   [@qDebug]              - Shader \"" << fileName << "\" not found.";
        return VK_ERROR_INITIALIZATION_FAILED;
    }

    shaderFile.open(QIODevice::ReadOnly);

    // Read shader data.
    QByteArray shaderData = shaderFile.readAll();

    // Fill shader module info.
    VkShaderModuleCreateInfo shaderInfo =
    {
        VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,    // VkStructureType              sType;
        nullptr,                                        // const void*                  pNext;
        0,                                              // VkShaderModuleCreateFlags    flags;

        (size_t)shaderData.size(),                      // size_t                       codeSize;
        (const uint32_t*)shaderData.data()              // const uint32_t*              pCode;
    };

    // Create shader module.
    mgAssert(vkCreateShaderModule(device->logical, &shaderInfo, nullptr, &shader));

    return VK_SUCCESS;
}
ID3DBlob* D3DApp::GenerateShader(const std::string& filename, const std::string& function,
	const std::string& model, const D3D_SHADER_MACRO* pDefines)
{
	HRESULT hr = S_OK;

	ID3DBlob* pCompiledShader = nullptr;
	ID3DBlob* pErrorMessages = nullptr;

	UINT flags = D3DCOMPILE_PACK_MATRIX_ROW_MAJOR;
#ifdef _DEBUG
	flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; // | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#endif

	std::ifstream shaderFile(filename);
	std::string hlslCode((std::istreambuf_iterator<char>(shaderFile)),
		std::istreambuf_iterator<char>());

	HR(D3DCompile(
		hlslCode.c_str(),
		hlslCode.size(),
		nullptr,
		pDefines,
		nullptr,
		function.c_str(),
		model.c_str(),
		flags,
		0,
		&pCompiledShader,
		&pErrorMessages));

	ReleaseCOM(pErrorMessages);

	return(pCompiledShader);
}
std::string CShader::FileToString(std::string pShaderPath)
{
    std::string ret;


    //load the file

    std::string line;
    std::ifstream shaderFile(pShaderPath);
    if (shaderFile.is_open())
    {
        while (getline(shaderFile, line))
        {
            ret.append(line);
        }
        shaderFile.close();
    }
    else
    {
        //TODO: add error to logging system
    };

    return ret;

}
void GLSLprogram::compileShader(const std::string& filePath, GLuint shaderID) {
	std::ifstream shaderFile(filePath);
	if (shaderFile.fail()) {
		std::cout << "Fil fel: " + filePath;
	}
	std::string fileContent = "";
	std::string line;

	while (std::getline(shaderFile, line)) {
		fileContent += line + "\n";
	}
	shaderFile.close();

	const char* contentsPtr = fileContent.c_str();
	glShaderSource(shaderID, 1, &contentsPtr, nullptr);
	glCompileShader(shaderID);

	GLint success = 0;
	glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success);

	if (success == GL_FALSE) {
		GLint maxLength = 0;
		glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &maxLength);

		std::vector<char> errorLog(maxLength);
		glGetShaderInfoLog(shaderID, maxLength, &maxLength, &errorLog[0]);

		glDeleteShader(shaderID);
		std::printf("%s\n", &(errorLog[0]));
	}
}
void
ShaderProgram::getShaderInformation (const std::string& filename, GLuint shader, bool ism_vertexShader)
{
  char* shaderInformation;
  int sizeOfBuffer;
  std::ifstream shaderFile (filename, std::ios::in | std::ios::binary | std::ios::ate); 
  if (shaderFile.is_open())
  {
    sizeOfBuffer = shaderFile.tellg ();
    shaderInformation = new char[sizeOfBuffer + 1];
    shaderFile.seekg (0, std::ios::beg);
    shaderFile.read (shaderInformation, sizeOfBuffer);
    shaderFile.close ();
    shaderInformation[sizeOfBuffer] = '\0';
  }
  if (ism_vertexShader)
  {
    glShaderSource (shader, 1, &shaderInformation, 0);
  }
  else if (!ism_vertexShader)
  {
    glShaderSource (shader, 1, &shaderInformation, 0);
  }
  delete[] shaderInformation;
}
Example #6
0
void Shader::loadShaderFile(const GLchar * filepath, std::string & str)
{
        std::ifstream shaderFile(filepath);
        std::stringstream shaderStream;
        shaderStream << shaderFile.rdbuf();
        shaderFile.close();
        str = shaderStream.str();
}
Example #7
0
	void GLSLProgram::compileShader(const std::string& filePath, GLuint id)
	{
	 //Open the file
        std::ifstream shaderFile(filePath);
        if (shaderFile.fail()) {
            perror(filePath.c_str());
            fatalError("Failed to open " + filePath);
        }

        //File contents stores all the text in the file
        std::string fileContents = "";
        //line is used to grab each line of the file
        std::string line;

        //Get all the lines in the file and add it to the contents
        while (std::getline(shaderFile, line)) {
            fileContents += line + "\n";
        }

        shaderFile.close();

        //get a pointer to our file contents c string;
        const char* contentsPtr = fileContents.c_str();
        //tell opengl that we want to use fileContents as the contents of the shader file
        glShaderSource(id, 1, &contentsPtr, nullptr);

        //compile the shader
        glCompileShader(id);

        //check for errors
        GLint success = 0;
        glGetShaderiv(id, GL_COMPILE_STATUS, &success);

        if (success == GL_FALSE)
        {
            GLint maxLength = 0;
            glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength);

            //The maxLength includes the NULL character
            std::vector<char> errorLog(maxLength);
            glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]);

            //Provide the infolog in whatever manor you deem best.
            //Exit with failure.
            glDeleteShader(id); //Don't leak the shader.

            //Print error log and quit
            std::printf("%s\n", &(errorLog[0]));
            fatalError("Shader " + filePath + " failed to compile");
		}
		
	}
Example #8
0
  std::string Shader::Read_Shader(const char* sFile)
  {
    std::ifstream shaderFile (sFile);

    if (!shaderFile.good ())
    {
      std::cout << "File cannot be loaded...  " << sFile;
      return NULL;
    }

    return std::string (std::istreambuf_iterator<char> (shaderFile),
      std::istreambuf_iterator<char> ());
  }
/*-----------------------------------------------------------------------------------------------
Description:
    Encapsulates the creation of an OpenGL GPU program, including the compilation and linking of
    shaders.  It tries to cover all the basics and the error reporting and is as self-contained
    as possible, only returning a program ID when it is finished.

    In particular, this one loads the compute.
Parameters: None
Returns:
    The OpenGL ID of the GPU program.
Exception:  Safe
Creator:    John Cox (7-30-2016)
-----------------------------------------------------------------------------------------------*/
unsigned int GenerateComputeShaderProgram()
{
    // hard-coded ignoring possible errors like a boss

    std::ifstream shaderFile("shaderParticle.comp");
    std::stringstream shaderData;
    shaderData << shaderFile.rdbuf();
    shaderFile.close();
    std::string tempFileContents = shaderData.str();
    GLuint compShaderId = glCreateShader(GL_COMPUTE_SHADER);
    const GLchar *bytes[] = { tempFileContents.c_str() };
    const GLint strLengths[] = { (int)tempFileContents.length() };
    glShaderSource(compShaderId, 1, bytes, strLengths);
    glCompileShader(compShaderId);

    GLint isCompiled = 0;
    glGetShaderiv(compShaderId, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE)
    {
        GLchar errLog[128];
        GLsizei *logLen = 0;
        glGetShaderInfoLog(compShaderId, 128, logLen, errLog);
        printf("compute shader failed: '%s'\n", errLog);
        glDeleteShader(compShaderId);
        return 0;
    }

    GLuint programId = glCreateProgram();
    glAttachShader(programId, compShaderId);
    glLinkProgram(programId);

    // the program contains binary, linked versions of the shaders, so clean up the compile 
    // objects
    // Note: Shader objects need to be un-linked before they can be deleted.  This is ok because
    // the program safely contains the shaders in binary form.
    glDetachShader(programId, compShaderId);
    glDeleteShader(compShaderId);

    // check if the program was built ok
    GLint isLinked = 0;
    glGetProgramiv(programId, GL_LINK_STATUS, &isLinked);
    if (isLinked == GL_FALSE)
    {
        printf("compute program didn't compile\n");
        glDeleteProgram(programId);
        return 0;
    }

    // done here
    return programId;
}
Example #10
0
	const char* SShaderInfo::getShaderProgram(const char *filePath,string &shaderProgramText)
	{
		fstream shaderFile(filePath,ios::in);
		string shader;
		string line;
		if(shaderFile.is_open()){
			while(getline(shaderFile,line)){
				shader += line + '\n';
			}
		}
		shaderFile.close();

		return shader.c_str();
	}
bool VShadingPass::Compile(const VFileList &vertexShaders, const VFileList &fragmShaders)
{
	VString bigSourceStr;

	for( VFileList::const_iterator i = vertexShaders.begin(); i != vertexShaders.end(); ++i ) {
		const VString &fileName = *i;
		CPVRTResourceFile shaderFile(fileName.c_str());
		if( !shaderFile.IsOpen() )
			return false;

		VString fileContent((const char*) shaderFile.DataPtr(), shaderFile.Size());
		bigSourceStr += fileContent;
	}

	if( !mVertexShader.Create(GL_VERTEX_SHADER, bigSourceStr.c_str(), &mErrorLog ) ) {
		return false;
	}

	bigSourceStr.clear();

	for( VFileList::const_iterator i = fragmShaders.begin(); i != fragmShaders.end(); ++i ) {
		const VString &fileName = *i;
		CPVRTResourceFile shaderFile(fileName.c_str());
		if( !shaderFile.IsOpen() )
			return false;

		VString fileContent((const char*) shaderFile.DataPtr(), shaderFile.Size());
		bigSourceStr += fileContent;
	}

	if( !mFragmentShader.Create(GL_FRAGMENT_SHADER, bigSourceStr.c_str(), &mErrorLog ) ) {
		return false;
	}

	return true;
}
const char* getShaderProgram( const char *filePath, string &shader )
{
	fstream shaderFile( filePath, ios::in );

	if ( shaderFile.is_open() )
	{
		std::stringstream buffer;
		buffer << shaderFile.rdbuf();
		shader = buffer.str();
		buffer.clear();
	}
	shaderFile.close();

	return shader.c_str();
}
Example #13
0
GLuint ShaderState::loadShader(GLenum eShaderType, std::string& strShaderFilename)
{
    std::string filePath = Utils::getFilePath(strShaderFilename);

    std::ifstream shaderFile(filePath.c_str());
    if(!shaderFile.is_open())
    {
        fprintf(stderr, "Cannot load the shader file \"%s\" for the %s shader.\n",
                filePath.c_str(), getShaderName(eShaderType));
        return 0;
    }
    std::stringstream shaderData;
    shaderData << shaderFile.rdbuf();
    shaderFile.close();

    return createShader(eShaderType, shaderData.str(), strShaderFilename);
}
	GLuint LoadShader(GLenum eShaderType, const std::string &strShaderFilename)
	{
		std::string strFilename = FindFileOrThrow(strShaderFilename);
		std::ifstream shaderFile(strFilename.c_str());
		std::stringstream shaderData;
		shaderData << shaderFile.rdbuf();
		shaderFile.close();

		try
		{
			return glutil::CompileShader(eShaderType, shaderData.str());
		}
		catch(std::exception &e)
		{
			fprintf(stderr, "%s\n", e.what());
			throw;
		}
	}
Example #15
0
	//Reads in file and compiles/creates a shader from it
	GLuint LoadShader(GLenum shaderType, const std::string &shaderFilename)
	{
		std::ifstream shaderFile(shaderFilename.c_str());
		std::stringstream shaderData;
		shaderData << shaderFile.rdbuf();
		shaderFile.close();

		try
		{
			return glutil::CompileShader(shaderType, shaderData.str());
		}
		catch(std::exception &e)
		{
			std::cout << "Shader Load Error\n";
			fprintf(stderr, "%s\n", e.what());
			throw;
		}
	}
void PointViewerMainWindow::openShaderFile(const QString& shaderFileName)
{
    QFile shaderFile(shaderFileName);
    if (!shaderFile.open(QIODevice::ReadOnly))
    {
        shaderFile.setFileName("shaders:" + shaderFileName);
        if (!shaderFile.open(QIODevice::ReadOnly))
        {
            g_logger.error("Couldn't open shader file \"%s\": %s",
                        shaderFileName, shaderFile.errorString());
            return;
        }
    }
    m_currShaderFileName = shaderFile.fileName();
    QByteArray src = shaderFile.readAll();
    m_shaderEditor->setPlainText(src);
    m_pointView->shaderProgram().setShader(src);
}
Example #17
0
Shader::Shader(const std::string& path, const GLenum type)
    : handle(0), type(type)
{
    // Load the shader source code
    std::ifstream shaderFile(path.c_str());
    if(!shaderFile.is_open())
    {
        std::cerr << "[FATAL] [SHADER \"" << path << "\" ==> undetermined] Unable to open specified path" << std::endl;
        throw std::runtime_error("Unable to open specified path");
    }
    
    shaderFile.seekg ( 0, std::ios::end );
    size_t shaderSourceSize = shaderFile.tellg();
    shaderFile.seekg ( 0, std::ios::beg );
    
    std::string shaderSource;
    shaderSource.resize(shaderSourceSize);
    shaderFile.read ( &shaderSource[0], shaderSourceSize );
    shaderFile.close();
    
    const char *sourceData = shaderSource.data();
    const GLint sourceLength = (const GLint) shaderSourceSize;
    
    // Compile the shader
    handle = glCreateShader(type);
    glShaderSource(handle, 1, &sourceData, &sourceLength);
    glCompileShader(handle);
    
    // Check compilation status
    GLint r;
    glGetShaderiv(handle, GL_COMPILE_STATUS, &r);
    if(r == GL_FALSE)
    {
        GLchar messages[256];
        glGetShaderInfoLog(handle, sizeof(messages), 0, &messages[0]);
        glDeleteShader(handle);
        handle = 0;
        
        std::cerr << "[FATAL] [SHADER \"" << path << "\" ==> " << handle << "] Compilation failed with error: " << messages << std::endl;
        throw std::runtime_error("Shader failed to compile");
    }
    
    std::cout << "[INFO] [SHADER \"" << path << "\" ==> " << handle << "] Compilation successful" << std::endl;
}
bool VShadingPass::CompileShader(const char *fileName, VShader &src, GLuint type)
{
	CPVRTResourceFile shaderFile(fileName);
	if( !shaderFile.IsOpen() )
		return false;

	VString log;
	VString bigString((const char*) shaderFile.DataPtr(), shaderFile.Size());
	if( !src.Create(type, bigString.c_str(), &log ) ) {
		mErrorLog = "Error in ";
		mErrorLog += fileName;
		mErrorLog += ":\n";
		mErrorLog += log;

		return false;
	}

	return true;
}
Example #19
0
	GLchar* loadFile(char* fileName) {
		std::string fileLine, result;
		std::ifstream shaderFile(fileName);
		char* shaderContents;
		int size;

		if (shaderFile.is_open()) {
			while (getline(shaderFile, fileLine)) {
				result += fileLine + "\n";
			}
			shaderFile.close();
		}
		size = result.size();
		shaderContents = new char[size];
		memcpy(shaderContents, result.c_str(), size);
		shaderContents[size - 1] = '\0';

		return shaderContents;
	}
Example #20
0
//-----------------------------------------------------------------------------
//! SLGLShader::load loads a shader file into string _shaderSource
void SLGLShader::load(SLstring filename)
{  
    fstream shaderFile(filename.c_str(), ios::in);
    
    if (!shaderFile.is_open())
    {   SL_LOG("File open failed: %s\n", filename.c_str());
        exit(1);
    }
   
    std::stringstream buffer;
    buffer << shaderFile.rdbuf(); 

    // remove comments because some stupid ARM compiler can't handle GLSL comments
    #ifdef SL_OS_MACIOS
    _code = buffer.str();
    #else
    _code = SLUtils::removeComments(buffer.str());
    #endif
}
Example #21
0
CShader::shaderInst::shaderInst(const char *fName, int shaderType){
	if (!inst().enableShaders)
		return;

	std::fstream shaderFile(fName);
	fileName = fName;
	
	if(!shaderFile.good()) std::logic_error("Can't load shader's file");
	
	shaderSize = fileSize(shaderFile);
	
	shaderContent = new char[shaderSize + 32];
	memset(shaderContent, 0, shaderSize + 32);
	shaderFile.read(shaderContent, shaderSize);
	//*(short*)&shaderContent[shaderSize] = 0;
	
	type = shaderType? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER;
	
	compile();
}
  GLuint LoadShaderGL(GLenum eShaderType, const std::string &strFilename)
  {
    std::ifstream shaderFile(strFilename.c_str());
    if (!shaderFile.is_open())
      throw std::runtime_error("Cannot find file: " + strFilename);
   
    std::stringstream shaderData;
    shaderData << shaderFile.rdbuf();
    shaderFile.close();
    
    try
      {
	return CreateShaderGL(eShaderType, shaderData.str());
      }
    catch(std::exception &e)
      {
	std::cerr<<e.what()<<std::endl;
	throw;
      }
  }
const GLchar *ShaderManipulator::readShaderFromFile(std::string path){
	std::string vertexCode;
	std::string fragmentCode;
	try
	{
		// Open files
		std::ifstream shaderFile(path);
		std::stringstream vShaderStream;
		// Read file's buffer contents into streams
		vShaderStream << shaderFile.rdbuf();
		// close file handlers
		shaderFile.close();
		// Convert stream into GLchar array
		vertexCode = vShaderStream.str();
	}
	catch (std::exception e)
	{
		std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
	}
	
	return vertexCode.c_str();
}
hkgShaderCollection* HardwareSkinningDemo::compileShader()
{
	hkgShaderCollection* ret  = HK_NULL;

	hkgDisplayContext* ctx = m_env->m_window->getContext();
	hkgShader* vertexShader = hkgShader::createVertexShader( ctx );
	hkgShader* pixelShader = hkgShader::createPixelShader( ctx );

	hkString shaderFile("./Resources/Animation/Shaders/SimpleSkinningShader"); 
	shaderFile += hkString(vertexShader->getDefaultFileNameExtension());

	vertexShader->realizeCompileFromFile( shaderFile.cString(), "mainVS", HK_NULL, HK_NULL, HK_NULL);
	pixelShader->realizeCompileFromFile( shaderFile.cString(), "mainPS", HK_NULL, HK_NULL, HK_NULL);

	ret = hkgShaderCollection::create();
	ret->addShaderGrouping(vertexShader, pixelShader);	

	pixelShader->removeReference();
	vertexShader->removeReference();

	return ret;
}
void PointViewerMainWindow::saveShaderFile()
{
    QString shaderFileName = QFileDialog::getSaveFileName(
        this,
        tr("Save current OpenGL shader"),
        m_currShaderFileName,
        tr("OpenGL shader files (*.glsl);;All files(*)")
    );
    if (shaderFileName.isNull())
        return;
    QFile shaderFile(shaderFileName);
    if (shaderFile.open(QIODevice::WriteOnly))
    {
        QTextStream stream(&shaderFile);
        stream << m_shaderEditor->toPlainText();
        m_currShaderFileName = shaderFileName;
    }
    else
    {
        g_logger.error("Couldn't open shader file \"%s\": %s",
                       shaderFileName, shaderFile.errorString());
    }
}
Example #26
0
	GLuint LoadShader(GLenum eShaderType, const std::string& strShaderFile) {
		std::ifstream shaderFile(strShaderFile.c_str());
		std::stringstream shaderData;
		shaderData << shaderFile.rdbuf();
		shaderFile.close();

		std::string shaderDataString = shaderData.str();

		GLuint shader = glCreateShader(eShaderType);
		const char *strFileData = shaderDataString.c_str();
		glShaderSource(shader, 1, &strFileData, NULL);

		glCompileShader(shader);

		GLint status;
		glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
		if (status == GL_FALSE) {
			GLint infoLogLength;
			glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);

			GLchar *strInfoLog = new GLchar[infoLogLength + 1];
			glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);

			const char *strShaderType = NULL;
			switch (eShaderType) {
			case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
			case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
			case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
			}

			fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
			delete[] strInfoLog;
		}

		return shader;

	}
Example #27
0
void Shader::compile() {
	std::ifstream shaderFile(_shaderFileName.c_str());
	std::string shaderCode;
	const int MAX_LINE_SIZE = 300;
	char line[MAX_LINE_SIZE];
	const int MAX_LOG_SIZE = 1000;
	int log_size;
	char compiler_log[MAX_LOG_SIZE];

	// read shader code from file
	if(shaderFile.is_open()) {
		do {
			shaderFile.getline(line, MAX_LINE_SIZE);
			shaderCode.append(line);
			shaderCode.append("\n");
		} while( !shaderFile.eof() );
		shaderFile.close();
	} else {
		std::cerr << "Unable to open shader file " << _shaderFileName << "." << std::endl;
	}

	// compile shader
	GLint compileSatus;
	const char* codePointer = shaderCode.c_str();
	int codeLength = shaderCode.length() + 1;
	glShaderSource(_shaderId, 1, &codePointer, &codeLength);
	glCompileShader(_shaderId);
	glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &compileSatus);
	if( compileSatus == GL_FALSE ) {
		glGetShaderInfoLog(_shaderId, MAX_LOG_SIZE, &log_size, compiler_log);
		compiler_log[log_size] = '\0';
		std::cerr << "Compiling " << _shaderFileName << std::endl 
		          << "Shader code: " << std::endl << shaderCode
		          << compiler_log;
	}
}
Example #28
0
std::string Shader::loadSourceCode() {
  std::ifstream shaderFile(file);
  std::stringstream buffer;
  buffer << shaderFile.rdbuf();
  return buffer.str();
}
/*-----------------------------------------------------------------------------------------------
Description:
    Encapsulates the creation of an OpenGL GPU program, including the compilation and linking of
    shaders.  It tries to cover all the basics and the error reporting and is as self-contained
    as possible, only returning a program ID when it is finished.

    In particular, this one loads the vertex and fragment parts of the shader program.
Parameters: None
Returns:
    The OpenGL ID of the GPU program.
Exception:  Safe
Creator:    John Cox (2-13-2016)
-----------------------------------------------------------------------------------------------*/
unsigned int GenerateVertexShaderProgram()
{
    // hard-coded ignoring possible errors like a boss

    // load up the vertex shader and compile it
    // Note: After retrieving the file's contents, dump the stringstream's contents into a 
    // single std::string.  Do this because, in order to provide the data for shader 
    // compilation, pointers are needed.  The std::string that the stringstream::str() function 
    // returns is a copy of the data, not a reference or pointer to it, so it will go bad as 
    // soon as the std::string object disappears.  To deal with it, copy the data into a 
    // temporary string.
    //std::ifstream shaderFile("shaderGeometry.vert");
    std::ifstream shaderFile("shaderParticle.vert");
    std::stringstream shaderData;
    shaderData << shaderFile.rdbuf();
    shaderFile.close();
    std::string tempFileContents = shaderData.str();
    GLuint vertShaderId = glCreateShader(GL_VERTEX_SHADER);
    const GLchar *vertBytes[] = { tempFileContents.c_str() };
    const GLint vertStrLengths[] = { (int)tempFileContents.length() };
    glShaderSource(vertShaderId, 1, vertBytes, vertStrLengths);
    glCompileShader(vertShaderId);
    // alternately (if you are willing to include and link in glutil, boost, and glm), call 
    // glutil::CompileShader(GL_VERTEX_SHADER, shaderData.str());

    GLint isCompiled = 0;
    glGetShaderiv(vertShaderId, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE)
    {
        GLchar errLog[128];
        GLsizei *logLen = 0;
        glGetShaderInfoLog(vertShaderId, 128, logLen, errLog);
        printf("vertex shader failed: '%s'\n", errLog);
        glDeleteShader(vertShaderId);
        return 0;
    }

    // load up the fragment shader and compiler it
    //shaderFile.open("shaderGeometry.frag");
    shaderFile.open("shaderParticle.frag");
    shaderData.str(std::string());      // because stringstream::clear() only clears error flags
    shaderData.clear();                 // clear any error flags that may have popped up
    shaderData << shaderFile.rdbuf();
    shaderFile.close();
    tempFileContents = shaderData.str();
    GLuint fragShaderId = glCreateShader(GL_FRAGMENT_SHADER);
    const GLchar *fragBytes[] = { tempFileContents.c_str() };
    const GLint fragStrLengths[] = { (int)tempFileContents.length() };
    glShaderSource(fragShaderId, 1, fragBytes, fragStrLengths);
    glCompileShader(fragShaderId);

    glGetShaderiv(fragShaderId, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE)
    {
        GLchar errLog[128];
        GLsizei *logLen = 0;
        glGetShaderInfoLog(fragShaderId, 128, logLen, errLog);
        printf("fragment shader failed: '%s'\n", errLog);
        glDeleteShader(vertShaderId);
        glDeleteShader(fragShaderId);
        return 0;
    }

    GLuint programId = glCreateProgram();
    glAttachShader(programId, vertShaderId);
    glAttachShader(programId, fragShaderId);
    glLinkProgram(programId);

    // the program contains binary, linked versions of the shaders, so clean up the compile 
    // objects
    // Note: Shader objects need to be un-linked before they can be deleted.  This is ok because
    // the program safely contains the shaders in binary form.
    glDetachShader(programId, vertShaderId);
    glDetachShader(programId, fragShaderId);
    glDeleteShader(vertShaderId);
    glDeleteShader(fragShaderId);

    // check if the program was built ok
    GLint isLinked = 0;
    glGetProgramiv(programId, GL_LINK_STATUS, &isLinked);
    if (isLinked == GL_FALSE)
    {
        printf("program didn't compile\n");
        glDeleteProgram(programId);
        return 0;
    }

    // done here
    return programId;
}
Example #30
0
void ShaderDefinitions::readShaderDefinitions()
{

	ShadingNode sn;
	std::vector<ShadingNode> snodes;
	snodes.push_back(sn);
	this->shadingNodes.push_back(sn);

	logger.feature(MString("home dir: ") + getRendererHome());
	logger.feature(MString("shader defs file: ") + getRendererHome() + "ressources/shaderDefinitions.txt");
	
	std::string shaderDefFile = (getRendererHome() + "ressources/shaderDefinitions.txt").asChar();

	std::ifstream shaderFile(shaderDefFile.c_str());
	if( !shaderFile.good())
	{
		logger.error(MString("Unable to open shaderInfoFile ") + MString(shaderDefFile.c_str()));
		shaderFile.close();
		return;
	}
	std::string line;

	ShadingNode node;

	do{
		std::getline(shaderFile, line);
		//logger.debug(line.c_str());
		if(validString(line))
		{
			std::vector<std::string> stringArray;
			pystring::split(line, stringArray, ":");

			if(pystring::startswith(line, "shader_end"))
			{
				// these nodes are automatically valid because they are supported
				node.nodeState = ShadingNode::VALID;

				this->shadingNodes.push_back(node);
				// clean up old node
				node = ShadingNode();
			}

			if(pystring::startswith(line, "shader_start"))
			{
				node.typeName = stringArray[1].c_str();
			}
			//inatt:blender:float
			if(pystring::startswith(line, "inatt"))
			{
				if( stringArray.size() > 2 )
				{
					ShaderAttribute att;
					att.name = stringArray[1];
					att.type = stringArray[2];
					node.inputAttributes.push_back(att);
				}
			}
			if(pystring::startswith(line, "outatt"))
			{
				if( stringArray.size() > 2 )
				{
					ShaderAttribute att;
					att.name = stringArray[1];
					att.type = stringArray[2];
					node.outputAttributes.push_back(att);
				}
			}
		}

	}while(!shaderFile.eof());

	//logger.debug("Reading of shader def file done.");
	shaderFile.close();
	readDone = true;
}