Beispiel #1
0
	static Program make(void)
	{
		Program result;

		VertexShader vs;
		vs.Source(
			"#version 330\n"
			"#define side 128\n"

			"uniform mat4 ProjectionMatrix, CameraMatrix, LightProjMatrix, LightMatrix;"
			"uniform vec3 CameraPos, LightPos;"
			"uniform float Fade;"
			"uniform sampler2D Offsets;"
			"uniform sampler2D Heights;"

			"in vec4 Position;"
			"in vec3 Normal;"

			"out vec4 vertShadowCoord;"
			"out vec3 vertViewDir;"
			"out vec3 vertLightDir;"
			"out vec3 vertNormal;"
			"out float vertLight;"

			"void main(void)"
			"{"
			"	ivec2 Coord = ivec2(gl_InstanceID%side, gl_InstanceID/side);"
			"	vec2 Offs = texelFetch(Offsets, Coord, 0).xy;"
			"	float Depth = texelFetch(Heights, Coord, 0).r;"
			"	float Height = 1.0-Depth;"
			"	gl_Position = Position;"
			"	gl_Position.xz += Offs;"
			"	float l = (1.0-dot(Normal, vec3(0,1,0))*0.5)*0.8;"
			"	vertLight = (1.0-gl_Position.y*l)*sign(Height)*Fade;"
			"	gl_Position.y  *= max(Height*Fade*side/2, 0.5);"
			"	vertViewDir = CameraPos - gl_Position.xyz;"
			"	vertLightDir = LightPos - gl_Position.xyz;"
			"	vertShadowCoord = LightProjMatrix * LightMatrix * gl_Position;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"	vertNormal = Normal;"
			"}"
		).Compile();

		FragmentShader fs;
		fs.Source(
			"#version 330\n"
			"uniform sampler2DShadow Shadows;"

			"const vec3 LightDir = normalize(vec3(1, 0.3, 1));"
			"const vec3 BarColor = vec3(0.4, 0.4, 0.4);"

			"in vec4 vertShadowCoord;"
			"in vec3 vertViewDir;"
			"in vec3 vertLightDir;"
			"in vec3 vertNormal;"
			"in float vertLight;"

			"out vec3 fragColor;"

			"void main(void)"
			"{"
			"	vec3 Normal = normalize(vertNormal);"
			"	vec3 ViewDir = normalize(vertViewDir);"
			"	vec3 LightDir = normalize(vertLightDir);"
			"	vec3 LightRefl = reflect(-LightDir, Normal);"
			"	vec3 ShadowCoord = (vertShadowCoord.xyz/vertShadowCoord.w)*0.5 + 0.5;"
			"	float shdw = texture(Shadows, ShadowCoord);"
			"	float ambi = 0.15;"
			"	float diff = pow(max(dot(Normal, LightDir)+0.1, 0.0),2.0)*0.9;"
			"	float spec = pow(max(dot(ViewDir, LightRefl), 0.0), 32.0)*0.4;"
			"	float emis = pow(vertLight, 2.0)*0.7;"
			"	fragColor = "
			"		BarColor * (diff*shdw+ambi)+"
			"		vec3(1.0, 1.0, 1.0)*spec*shdw+"
			"		vec3(0.1, 1.0, 0.3)*emis;"
			"}"
		).Compile();

		result.AttachShader(vs).AttachShader(fs);
		result.Link().Validate().Use();
		return std::move(result);
	}
//-----------------------------------------------------------------------
bool FFPTexturing::resolveUniformParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet)
{
	Program* vsProgram = programSet->getCpuVertexProgram();
	Program* psProgram = programSet->getCpuFragmentProgram();
	
	
	// Resolve texture sampler parameter.		
	textureUnitParams->mTextureSampler = psProgram->resolveParameter(textureUnitParams->mTextureSamplerType, textureUnitParams->mTextureSamplerIndex, (uint16)GPV_GLOBAL, "gTextureSampler");
	if (textureUnitParams->mTextureSampler.get() == NULL)
		return false;
	
		
	// Resolve texture matrix parameter.
	if (needsTextureMatrix(textureUnitParams->mTextureUnitState))
	{				
		textureUnitParams->mTextureMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_TEXTURE_MATRIX, textureUnitParams->mTextureSamplerIndex);
		if (textureUnitParams->mTextureMatrix.get() == NULL)
			return false;
	}

	switch (textureUnitParams->mTexCoordCalcMethod)
	{
	case TEXCALC_NONE:								
		break;

	// Resolve World + View matrices.
	case TEXCALC_ENVIRONMENT_MAP:
	case TEXCALC_ENVIRONMENT_MAP_PLANAR:	
	case TEXCALC_ENVIRONMENT_MAP_NORMAL:
		
		mWorldITMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX, 0);
		if (mWorldITMatrix.get() == NULL)		
			return false;	
		
		mViewMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_VIEW_MATRIX, 0);
		if (mViewMatrix.get() == NULL)		
			return false;				
		
		break;

	case TEXCALC_ENVIRONMENT_MAP_REFLECTION:
		mWorldMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_WORLD_MATRIX, 0);
		if (mWorldMatrix.get() == NULL)		
			return false;	

		mWorldITMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX, 0);
		if (mWorldITMatrix.get() == NULL)		
			return false;	

		mViewMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_VIEW_MATRIX, 0);
		if (mViewMatrix.get() == NULL)		
			return false;	

		break;


	case TEXCALC_PROJECTIVE_TEXTURE:

		mWorldMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_WORLD_MATRIX, 0);
		if (mWorldMatrix.get() == NULL)		
			return false;	

		textureUnitParams->mTextureViewProjImageMatrix = vsProgram->resolveParameter(GCT_MATRIX_4X4, -1, (uint16)GPV_LIGHTS, "gTexViewProjImageMatrix");
		if (textureUnitParams->mTextureViewProjImageMatrix.get() == NULL)		
			return false;	

		const TextureUnitState::EffectMap&		effectMap = textureUnitParams->mTextureUnitState->getEffects();	
		TextureUnitState::EffectMap::const_iterator	effi;

		for (effi = effectMap.begin(); effi != effectMap.end(); ++effi)
		{
			if (effi->second.type == TextureUnitState::ET_PROJECTIVE_TEXTURE)
			{
				textureUnitParams->mTextureProjector = effi->second.frustum;
				break;
			}
		}

		

		if (textureUnitParams->mTextureProjector == NULL)		
			return false;	

		break;
	}

	return true;
}
Beispiel #3
0
	bool Execute(const AnyString& commandLine, uint timeout)
	{
		Program program;
		program.commandLine(commandLine);
		return (program.execute(timeout)) ? (0 == program.wait()) : false;
	}
    PoolTilesExample()
      : make_plane(
          Vec3f(), Vec3f(7.0f, 0.0f, 0.0f), Vec3f(0.0f, 0.0f, -7.0f), 48, 48)
      , plane_instr(make_plane.Instructions())
      , plane_indices(make_plane.Indices())
      , make_shape()
      , shape_instr(make_shape.Instructions())
      , shape_indices(make_shape.Indices())
      , plane_vs(ObjectDesc("Plane vertex"))
      , shape_vs(ObjectDesc("Shape vertex"))
      , plane_fs(ObjectDesc("Plane fragment"))
      , shape_fs(ObjectDesc("Shape fragment"))
      , plane_camera_matrix(plane_prog, "CameraMatrix")
      , shape_camera_matrix(shape_prog, "CameraMatrix")
      , plane_camera_position(plane_prog, "CameraPosition")
      , width(800)
      , height(600)
      , refl_tex_side(width > height ? height : width)
      , tile_tex_side(64) {
        gl.RequireAtLeast(LimitQuery::MaxCombinedTextureImageUnits, 5);

        plane_vs.Source(
          "#version 140\n"
          "uniform vec3 LightPosition;"
          "uniform vec3 CameraPosition;"
          "uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
          "in vec4 Position;"
          "in vec2 TexCoord;"
          "out vec3 vertLightDir;"
          "out vec3 vertViewDir;"
          "out vec4 vertReflTexCoord;"
          "out vec2 vertTileTexCoord;"
          "void main()"
          "{"
          "	gl_Position = ModelMatrix* Position;"
          "	vertLightDir = normalize(LightPosition - gl_Position.xyz);"
          "	vertViewDir = normalize(CameraPosition - gl_Position.xyz);"
          "	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
          "	vertReflTexCoord = gl_Position;"
          "	vertTileTexCoord = TexCoord;"
          "}");
        plane_vs.Compile();

        plane_fs.Source(
          "#version 140\n"
          "uniform sampler2D RandTex, PictTex, TileTex, NormTex;"
          "uniform sampler2D ReflectTex;"
          "uniform uint TileCount;"
          "uniform float Aspect;"
          "in vec3 vertLightDir;"
          "in vec3 vertViewDir;"
          "in vec4 vertReflTexCoord;"
          "in vec2 vertTileTexCoord;"
          "out vec4 fragColor;"
          "void main()"
          "{"
          "	vec3 Normal = texture("
          "		NormTex, "
          "		vertTileTexCoord * TileCount"
          "	).rgb;"
          "	vec3 LightRefl = reflect("
          "		-normalize(vertLightDir),"
          "		normalize(Normal)"
          "	);"
          "	float Diffuse = max(dot("
          "		Normal, "
          "		vertLightDir"
          "	), 0.0);"
          "	float Specular = max(dot("
          "		LightRefl,"
          "		vertViewDir"
          "	), 0.0);"
          "	float PlasterLight = 0.3 + max(Diffuse, 0.0);"
          "	float TileLight = 0.3 + pow(Diffuse, 2.0)*0.9 + pow(Specular, "
          "4.0)*2.5;"
          "	vec2 ReflCoord = vertReflTexCoord.xy;"
          "	ReflCoord /= vertReflTexCoord.w;"
          "	ReflCoord *= 0.5;"
          "	ReflCoord += vec2(Aspect*0.5, 0.5);"
          "	ReflCoord += vec2(Normal.x, Normal.z)*0.5;"
          "	vec3 ReflColor = texture("
          "		ReflectTex, "
          "		ReflCoord"
          "	).rgb;"
          "	vec3 TileProps = texture("
          "		TileTex, "
          "		vertTileTexCoord * TileCount"
          "	).rgb;"
          "	float Pict = texture(PictTex, vertTileTexCoord).r;"
          "	float Rand = texture(RandTex, vertTileTexCoord).r;"
          "	float LightVsDark = "
          "		mix( 0.1, 0.9, Pict)+"
          "		mix(-0.1, 0.1, Rand);"
          "	vec3 TileColor = mix("
          "		vec3(0.1, 0.1, 0.5),"
          "		vec3(0.4, 0.4, 0.9),"
          "		LightVsDark "
          "	);"
          "	vec3 PlasterColor = vec3(0.9, 0.9, 0.9);"
          "	fragColor = vec4("
          "		mix("
          "			PlasterColor * PlasterLight,"
          "			TileColor * TileLight, "
          "			TileProps.b"
          "		) +"
          "		ReflColor * TileProps.g * 0.6,"
          "		1.0"
          "	);"
          "}");
        plane_fs.Compile();

        plane_prog.AttachShader(plane_vs);
        plane_prog.AttachShader(plane_fs);
        plane_prog.Link();
        plane_prog.Use();

        Vec3f lightPos(3.0f, 2.5f, 2.0f);
        Uniform<Vec3f>(plane_prog, "LightPosition").Set(lightPos);
        Uniform<GLuint>(plane_prog, "TileCount").Set(tile_tex_side);
        Uniform<Mat4f>(plane_prog, "ModelMatrix")
          .Set(ModelMatrixf::Translation(0.0f, -0.5f, 0.0f));

        std::vector<GLfloat> data;
        GLuint n_per_vertex;

        n_per_vertex = make_plane.Positions(data);
        plane_verts.Data(data);
        DSAVertexArrayAttribEXT(plane, plane_prog, "Position")
          .Setup<GLfloat>(plane_verts, n_per_vertex)
          .Enable();

        n_per_vertex = make_plane.TexCoordinates(data);
        plane_texcoords.Data(data);
        DSAVertexArrayAttribEXT(plane, plane_prog, "TexCoord")
          .Setup<GLfloat>(plane_texcoords, n_per_vertex)
          .Enable();

        //
        rand_tex.target = Texture::Target::_2D;
        rand_tex.Image2D(images::RandomRedUByte(tile_tex_side, tile_tex_side));
        rand_tex.Filter(TextureFilter::Nearest);
        rand_tex.Wrap(TextureWrap::Repeat);
        Texture::Active(0);
        UniformSampler(plane_prog, "RandTex").Set(0);
        rand_tex.Bind();

        //
        pict_tex.target = Texture::Target::_2D;
        pict_tex.Image2D(images::LoadTexture("pool_pictogram"));
        pict_tex.Filter(TextureFilter::Linear);
        pict_tex.Wrap(TextureWrap::Repeat);
        Texture::Active(1);
        UniformSampler(plane_prog, "PictTex").Set(1);
        pict_tex.Bind();
        //
        auto tile_image = images::LoadTexture("small_tile");
        //
        tile_tex.target = Texture::Target::_2D;
        tile_tex.Image2D(tile_image);
        tile_tex.MinFilter(TextureMinFilter::LinearMipmapLinear);
        tile_tex.MagFilter(TextureMagFilter::Linear);
        tile_tex.Wrap(TextureWrap::Repeat);
        tile_tex.GenerateMipmap();
        Texture::Active(2);
        UniformSampler(plane_prog, "TileTex").Set(2);
        tile_tex.Bind();
        //
        norm_tex.target = Texture::Target::_2D;
        norm_tex.Image2D(images::TransformComponents<GLfloat, 3>(
          images::NormalMap(tile_image),
          Mat4d(
            Vec4d(1.0, 0.0, 0.0, 0.0),
            Vec4d(0.0, 0.0, 1.0, 0.0),
            Vec4d(0.0, -1.0, 0.0, 0.0),
            Vec4d(0.0, 0.0, 0.0, 1.0))));
        norm_tex.MinFilter(TextureMinFilter::LinearMipmapLinear);
        norm_tex.MagFilter(TextureMagFilter::Linear);
        norm_tex.Wrap(TextureWrap::Repeat);
        norm_tex.GenerateMipmap();
        Texture::Active(3);
        UniformSampler(plane_prog, "NormTex").Set(3);
        norm_tex.Bind();
        //
        reflect_tex.target = Texture::Target::_2D;
        reflect_tex.Image2D(
          0,
          PixelDataInternalFormat::RGB,
          refl_tex_side,
          refl_tex_side,
          0,
          PixelDataFormat::RGB,
          PixelDataType::UnsignedByte,
          nullptr);
        reflect_tex.Filter(TextureFilter::Linear);
        reflect_tex.Wrap(TextureWrap::ClampToEdge);
        Texture::Active(4);
        UniformSampler(plane_prog, "ReflectTex").Set(4);
        reflect_tex.Bind();

        rbo.Storage(
          PixelDataInternalFormat::DepthComponent,
          refl_tex_side,
          refl_tex_side);
        fbo.target = Framebuffer::Target::Draw;
        fbo.AttachTexture(FramebufferAttachment::Color, reflect_tex, 0);
        fbo.AttachRenderbuffer(FramebufferAttachment::Depth, rbo);

        shape_vs.Source(
          "#version 140\n"
          "uniform vec3 LightPosition;"
          "uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;"
          "in vec4 Position;"
          "in vec3 Normal;"
          "out vec3 vertNormal;"
          "out vec3 vertLightDir;"
          "out vec3 vertLightRefl;"
          "out vec3 vertViewDir;"
          "out vec3 vertViewRefl;"
          "out vec3 vertColor;"
          "void main()"
          "{"
          "	gl_Position = "
          "		ModelMatrix *"
          "		Position;"
          "	vertLightDir = LightPosition - gl_Position.xyz;"
          "	vertNormal = mat3(ModelMatrix)*Normal;"
          "	vertLightRefl = reflect("
          "		-normalize(vertLightDir),"
          "		normalize(vertNormal)"
          "	);"
          "	vertViewDir = ("
          "		vec4(0.0, 0.0, 1.0, 1.0)*"
          "		CameraMatrix"
          "	).xyz;"
          "	vertViewRefl = reflect("
          "		-normalize(vertViewDir),"
          "		normalize(vertNormal)"
          "	);"
          "	vertColor = vec3(0.3, 0.3, 0.7);"
          "	gl_Position = "
          "		ProjectionMatrix *"
          "		CameraMatrix *"
          "		gl_Position;"
          "}");
        shape_vs.Compile();

        shape_fs.Source(
          "#version 140\n"
          "uniform sampler2D PictTex, TileTex;"
          "uniform uint TileCount;"
          "in vec3 vertNormal;"
          "in vec3 vertLightDir;"
          "in vec3 vertLightRefl;"
          "in vec3 vertViewDir;"
          "in vec3 vertViewRefl;"
          "in vec3 vertColor;"
          "out vec4 fragColor;"

          "void main()"
          "{"
          "	float LtDist = length(vertLightDir);"
          "	float Diffuse = dot("
          "		normalize(vertNormal), "
          "		normalize(vertLightDir)"
          "	) / LtDist;"
          "	float Specular = dot("
          "		normalize(vertLightRefl),"
          "		normalize(vertViewDir)"
          "	);"
          "	vec3 LightColor = vec3(1.0, 1.0, 1.0);"
          "	vec2 ReflTexCoord = -vec2("
          "		vertViewRefl.x,"
          "		vertViewRefl.z "
          "	);"
          "	ReflTexCoord *= 0.25;"
          "	ReflTexCoord += vec2(0.5, 0.5);"
          "	float Pict = texture(PictTex, ReflTexCoord).r;"
          "	float LightVsDark = mix( 0.1, 0.9, Pict);"
          "	vec3 TileColor = mix("
          "		vec3(0.2, 0.2, 0.6),"
          "		vec3(0.5, 0.5, 0.9),"
          "		LightVsDark"
          "	);"
          "	vec3 PlasterColor = vec3(0.7, 0.7, 0.7);"
          "	vec3 FloorColor = mix("
          "		PlasterColor, "
          "		TileColor, "
          "		texture(TileTex, ReflTexCoord*TileCount).b"
          "	);"
          "	vec3 ReflColor = mix("
          "		vec3(0.5, 0.5, 0.4), "
          "		FloorColor, "
          "		pow(max((-vertViewRefl.y-0.5)*2.0, 0.0), 2.0)"
          "	);"
          "	fragColor = vec4("
          "		vertColor * 0.4 + "
          "		ReflColor * 0.3 + "
          "		(LightColor + vertColor)*pow(max(2.5*Diffuse, 0.0), 3) + "
          "		LightColor * pow(max(Specular, 0.0), 64), "
          "		1.0"
          "	);"
          "}");
        shape_fs.Compile();

        shape_prog.AttachShader(shape_vs);
        shape_prog.AttachShader(shape_fs);
        shape_prog.Link();
        shape_prog.Use();

        Uniform<Vec3f>(shape_prog, "LightPosition").Set(lightPos);
        Uniform<Mat4f>(shape_prog, "ModelMatrix")
          .Set(ModelMatrixf::Translation(0.0f, 0.6f, 0.0f));
        UniformSampler(shape_prog, "PictTex").Set(0);
        UniformSampler(shape_prog, "TileTex").Set(1);
        Uniform<GLuint>(shape_prog, "TileCount").Set(tile_tex_side);

        n_per_vertex = make_shape.Positions(data);
        shape_verts.Data(data);
        DSAVertexArrayAttribEXT(shape, shape_prog, "Position")
          .Setup<GLfloat>(shape_verts, n_per_vertex)
          .Enable();

        n_per_vertex = make_shape.Normals(data);
        shape_normals.Data(data);
        DSAVertexArrayAttribEXT(shape, shape_prog, "Normal")
          .Setup<GLfloat>(shape_normals, n_per_vertex)
          .Enable();
        //
        gl.ClearColor(0.5f, 0.5f, 0.4f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.Enable(Capability::DepthTest);
    }
    TessellationExample(void)
        : prog()
        , projection_matrix(prog, "ProjectionMatrix")
        , camera_matrix(prog, "CameraMatrix")
    {
        VertexShader vert(ObjectDesc("Vertex"));
        vert.Source(StrLit(
                        "#version 330\n"
                        "uniform mat4 CameraMatrix;"

                        "in vec4 Position;"
                        "out vec4 vertPosition;"

                        "void main(void)"
                        "{"
                        "	vertPosition = CameraMatrix * Position;"
                        "}"
                    ));
        vert.Compile();
        prog << vert;

        TessControlShader teco(ObjectDesc("TessControl"));
        teco.Source(StrLit(
                        "#version 330\n"
                        "#extension ARB_tessellation_shader: enable\n"
                        "layout(vertices = 16) out;"

                        "in vec4 vertPosition[];"
                        "patch out vec3 tecoPosition[16];"

                        "void main(void)"
                        "{"
                        "	if(gl_InvocationID == 0)"
                        "	{"
                        "		int tl = 1-int(100.0 / vertPosition[gl_InvocationID].z);"
                        "		gl_TessLevelInner[0] = tl;"
                        "		gl_TessLevelInner[1] = tl;"
                        "		gl_TessLevelOuter[0] = tl;"
                        "		gl_TessLevelOuter[1] = tl;"
                        "		gl_TessLevelOuter[2] = tl;"
                        "		gl_TessLevelOuter[3] = tl;"
                        "	}"
                        "	tecoPosition[gl_InvocationID] = "
                        "		vertPosition[gl_InvocationID].xyz;"
                        "}"
                    ));
        teco.Compile();
        prog << teco;

        TessEvaluationShader teev(ObjectDesc("TessEvaluation"));
        teev.Source(StrLit(
                        "#version 330\n"
                        "#extension ARB_tessellation_shader: enable\n"
                        "layout(quads, equal_spacing, ccw) in;"
                        "uniform mat4 ProjectionMatrix;"
                        "patch in vec3 tecoPosition[16];"

                        "const mat4 B = mat4("
                        "	-1, 3,-3, 1,"
                        "	 3,-6, 3, 0,"
                        "	-3, 3, 0, 0,"
                        "	 1, 0, 0, 0 "
                        ");"

                        "mat4 Px, Py, Pz;"

                        "void main(void)"
                        "{"
                        "	float u = gl_TessCoord.x, v = gl_TessCoord.y;"

                        "	for(int j=0; j!=4; ++j)"
                        "	for(int i=0; i!=4; ++i)"
                        "	{"
                        "		int k = j*4+i;"
                        "		Px[j][i] = tecoPosition[k].x;"
                        "		Py[j][i] = tecoPosition[k].y;"
                        "		Pz[j][i] = tecoPosition[k].z;"
                        "	}"

                        "	mat4 Cx = B * Px * B;"
                        "	mat4 Cy = B * Py * B;"
                        "	mat4 Cz = B * Pz * B;"

                        "	vec4 up = vec4(u*u*u, u*u, u, 1);"
                        "	vec4 vp = vec4(v*v*v, v*v, v, 1);"

                        "	vec4 tempPosition = vec4(dot(Cx * vp, up), dot(Cy * vp, up), dot(Cz * vp, up), 1.0);"

                        "	gl_Position = ProjectionMatrix * tempPosition;"
                        "}"
                    ));
        teev.Compile();
        prog << teev;

        FragmentShader frag(ObjectDesc("Fragment"));
        frag.Source(StrLit(
                        "#version 330\n"
                        "out vec3 fragColor;"
                        "void main(void)"
                        "{"
                        "	fragColor = vec3(0.1, 0.1, 0.1);"
                        "}"
                    ));
        frag.Compile();
        prog << frag;

        prog.Link();
        prog.Use();

        vao.Bind();

        GLfloat patch_cp_pos[16*3] = {
            -2.0f,  0.0f, -2.0f,
            -1.0f,  0.0f, -3.0f,
            1.0f,  0.0f, -5.0f,
            2.0f,  0.0f, -2.0f,
            -1.0f,  0.0f, -1.0f,
            0.0f,  4.0f, -1.0f,
            1.0f,  4.0f, -1.0f,
            3.0f,  0.0f, -1.0f,
            -1.0f,  0.0f,  1.0f,
            -1.0f,  4.0f,  1.0f,
            0.0f,  4.0f,  1.0f,
            1.0f,  0.0f,  1.0f,
            -2.0f,  0.0f,  2.0f,
            -1.0f,  0.0f,  5.0f,
            1.0f,  0.0f,  3.0f,
            2.0f,  0.0f,  2.0f
        };
        positions.Bind(Buffer::Target::Array);
        Buffer::Data(Buffer::Target::Array, 16*3, patch_cp_pos);
        VertexAttribArray position_attr(prog, "Position");
        position_attr.Setup<Vec3f>();
        position_attr.Enable();

        gl.ClearColor(0.9f, 0.9f, 0.9f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.PolygonMode(PolygonMode::Line);
        gl.PatchParameter(PatchParameter::PatchVertices, 16);
    }
Beispiel #6
0
	TessellationExample(void)
	 : shape_instr(make_shape.Instructions(PrimitiveType::Patches))
	 , shape_indices(make_shape.Indices())
	 , vs(ObjectDesc("Vertex"))
	 , cs(ObjectDesc("Tessellation Control"))
	 , es(ObjectDesc("Tessellation Evaluation"))
	 , gs(ObjectDesc("Geometry"))
	 , fs(ObjectDesc("Fragment"))
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	 , model_matrix(prog, "ModelMatrix")
	 , offset(prog, "Offset")
	 , view_position(prog, "ViewPosition")
	 , viewport_dimensions(prog, "ViewportDimensions")
	{
		vs.Source(
			"#version 410\n"

			"uniform vec3 ViewPosition;"

			"in vec3 Position;"

			"out vec3 vertPosition;"
			"out float vertDistance;"

			"void main(void)"
			"{"
			"	vertPosition = Position;"
			"	vertDistance = length(ViewPosition - vertPosition);"
			"}"
		);
		vs.Compile();

		cs.Source(
			"#version 410\n"

			"layout(vertices = 3) out;"

			"in vec3 vertPosition[];"
			"in float vertDistance[];"

			"out vec3 tecoPosition[];"

			"int tessLevel(float dist)"
			"{"
			"	return int(9.0 / sqrt(dist+0.1));"
			"}"

			"void main(void)"
			"{"
			"	tecoPosition[gl_InvocationID] ="
			"		vertPosition[gl_InvocationID];"

			"	if(gl_InvocationID == 0)"
			"	{"
			"		gl_TessLevelInner[0] = tessLevel(("
			"			vertDistance[0]+"
			"			vertDistance[1]+"
			"			vertDistance[2] "
			"		)*0.333);"
			"		gl_TessLevelOuter[0] = tessLevel(("
			"			vertDistance[1]+"
			"			vertDistance[2] "
			"		)*0.5);"
			"		gl_TessLevelOuter[1] = tessLevel(("
			"			vertDistance[2]+"
			"			vertDistance[0] "
			"		)*0.5);"
			"		gl_TessLevelOuter[2] = tessLevel(("
			"			vertDistance[0]+"
			"			vertDistance[1] "
			"		)*0.5);"
			"	}"
			"}"
		);
		cs.Compile();

		es.Source(
			"#version 410\n"

			"layout(triangles, equal_spacing, ccw) in;"

			"const vec3 LightPosition = vec3(12.0, 10.0, 7.0);"

			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"

			"in vec3 tecoPosition[];"

			"out vec3 teevNormal;"
			"out vec3 teevLightDir;"

			"void main(void)"
			"{"
			"	vec3 p0 = gl_TessCoord.x * tecoPosition[0];"
			"	vec3 p1 = gl_TessCoord.y * tecoPosition[1];"
			"	vec3 p2 = gl_TessCoord.z * tecoPosition[2];"

			"	vec4 tempPosition = vec4(normalize(p0+p1+p2), 0.0);"
			"	teevNormal = (ModelMatrix * tempPosition).xyz;"
			"	tempPosition.w = 1.0;"
			"	tempPosition = ModelMatrix * tempPosition;"
			"	teevLightDir = LightPosition - tempPosition.xyz;"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		tempPosition;"
			"}"
		);
		es.Compile();

		gs.Source(
			"#version 410\n"
			"layout (triangles) in;"
			"layout (triangle_strip, max_vertices = 3) out;"

			"uniform vec3 Offset;"
			"uniform vec2 ViewportDimensions;"

			"in vec3 teevNormal[], teevLightDir[];"

			"noperspective out vec3 geomDist;"
			"flat out vec3 geomNormal;"
			"out vec3 geomColor;"
			"out vec3 geomLightDir;"

			"void main(void)"
			"{"
			"	geomNormal = normalize("
			"		teevNormal[0]+"
			"		teevNormal[1]+"
			"		teevNormal[2]"
			"	);"

			"	vec2 ScreenPos[3];"
			"	for(int i=0; i!=3; ++i)"
			"	{"
			"		ScreenPos[i] = "
			"			ViewportDimensions*"
			"			gl_in[i].gl_Position.xy/"
			"			gl_in[i].gl_Position.w;"
			"	}"

			"	vec2 TmpVect[3];"
			"	for(int i=0; i!=3; ++i)"
			"	{"
			"		TmpVect[i] = "
			"			ScreenPos[(i+2)%3]-"
			"			ScreenPos[(i+1)%3];"
			"	}"

			"	const vec3 EdgeMask[3] = vec3[3]("
			"		vec3(1.0, 0.0, 0.0),"
			"		vec3(0.0, 1.0, 0.0),"
			"		vec3(0.0, 0.0, 1.0) "
			"	);"

			"	for(int i=0; i!=3; ++i)"
			"	{"
			"		float Dist = abs("
			"			TmpVect[(i+1)%3].x*TmpVect[(i+2)%3].y-"
			"			TmpVect[(i+1)%3].y*TmpVect[(i+2)%3].x "
			"		) / length(TmpVect[i]);"
			"		vec3 DistVect = vec3(Dist, Dist, Dist);"

			"		gl_Position = gl_in[i].gl_Position;"
			"		geomColor = normalize(abs("
			"			vec3(2.0, 2.0, 2.0)-"
			"			teevNormal[i]-"
			"			Offset"
			"		));"
			"		geomLightDir = teevLightDir[i];"
			"		geomDist = EdgeMask[i] * DistVect;"
			"		EmitVertex();"
			"	}"
			"	EndPrimitive();"
			"}"
		);
		gs.Compile();

		fs.Source(
			"#version 410\n"

			"noperspective in vec3 geomDist;"
			"flat in vec3 geomNormal;"
			"in vec3 geomColor;"
			"in vec3 geomLightDir;"

			"out vec3 fragColor;"

			"void main(void)"
			"{"
			"	float MinDist = min(min(geomDist.x,geomDist.y),geomDist.z);"
			"	float EdgeAlpha = exp2(-pow(MinDist, 2.0));"

			"	const float Ambient = 0.8;"
			"	float Diffuse = max(dot("
			"		normalize(geomNormal),"
			"		normalize(geomLightDir)"
			"	), 0.0);"

			"	vec3 FaceColor = geomColor * (Diffuse + Ambient);"
			"	const vec3 EdgeColor = vec3(0.0, 0.0, 0.0);"

			"	fragColor = mix(FaceColor, EdgeColor, EdgeAlpha);"
			"}"
		);
		fs.Compile();

		prog.AttachShader(vs);
		prog.AttachShader(cs);
		prog.AttachShader(es);
		prog.AttachShader(gs);
		prog.AttachShader(fs);
		prog.Link();
		prog.Use();

		shape.Bind();

		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Position");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();

			indices.Bind(Buffer::Target::ElementArray);
			Buffer::Data(Buffer::Target::ElementArray, shape_indices);
			shape_indices.clear();
		}

		//
		gl.ClearColor(0.8f, 0.8f, 0.8f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);

		prog.Use();
	}
Beispiel #7
0
    TorusExample(void)
        : make_torus(1.0, 0.5, 18, 36)
        , torus_instr(make_torus.Instructions())
        , torus_indices(make_torus.Indices())
        , vs(ObjectDesc("Vertex"))
        , gs(ObjectDesc("Geometry"))
        , face_fs(ObjectDesc("Face fragment"))
        , frame_fs(ObjectDesc("Frame fragment"))
        , transf_prog(ObjectDesc("Transformation"))
        , face_prog(ObjectDesc("Face"))
        , frame_prog(ObjectDesc("Frame"))
        , projection_matrix(transf_prog, "ProjectionMatrix")
        , camera_matrix(transf_prog, "CameraMatrix")
        , model_matrix(transf_prog, "ModelMatrix")
        , transf_time(transf_prog, "Time")
    {
        vs.Source(
            "#version 330\n"
            "uniform mat4 ModelMatrix;"
            "in vec4 Position;"
            "in vec3 Normal;"
            "in vec2 TexCoord;"
            "out gl_PerVertex {"
            "	vec4 gl_Position;"
            "};"
            "out vec3 vertNormal;"
            "out vec2 vertTexCoord;"
            "void main(void)"
            "{"
            "	gl_Position = ModelMatrix * Position;"
            "	vertNormal = (ModelMatrix*vec4(Normal,0.0)).xyz;"
            "	vertTexCoord = TexCoord;"
            "}"
        );
        vs.Compile();

        gs.Source(
            "#version 330\n"
            "layout(triangles) in;"
            "layout(triangle_strip, max_vertices = 15) out;"
            "uniform mat4 CameraMatrix, ProjectionMatrix;"
            "uniform vec3 LightPos;"
            "uniform float Time;"
            "in gl_PerVertex {"
            "	vec4 gl_Position;"
            "} gl_in[];"
            "in vec3 vertNormal[];"
            "in vec2 vertTexCoord[];"
            "out gl_PerVertex {"
            "	vec4 gl_Position;"
            "};"
            "out vec3 geomNormal;"
            "out vec3 geomLight;"
            "out float geomGlow;"
            "flat out int geomTop;"
            "void main(void)"
            "{"
            "	vec3 FaceNormal = normalize("
            "		vertNormal[0]+"
            "		vertNormal[1]+"
            "		vertNormal[2] "
            "	);"
            "	vec2 FaceCoord = 0.33333 * ("
            "		vertTexCoord[0]+"
            "		vertTexCoord[1]+"
            "		vertTexCoord[2] "
            "	);"
            "	float Offs = (sin((FaceCoord.s + Time/10.0)* 3.14 * 2.0 * 10)*0.5 + 0.5)*0.4;"
            "	Offs *= cos(FaceCoord.t * 3.1415 * 2.0)*0.5 + 0.51;"

            "	vec3 pos[3], norm[3];"
            "	for(int i=0; i!=3; ++i)"
            "		pos[i] = gl_in[i].gl_Position.xyz;"
            "	for(int i=0; i!=3; ++i)"
            "		norm[i] = cross("
            "			FaceNormal, "
            "			normalize(pos[(i+1)%3] - pos[i])"
            "		);"
            "	vec3 pofs = FaceNormal * Offs;"

            "	geomTop = 0;"
            "	for(int i=0; i!=3; ++i)"
            "	{"
            "		geomNormal = norm[i];"
            "		for(int j=0; j!=2; ++j)"
            "		{"
            "			vec3 tpos = pos[(i+j)%3];"
            "			geomLight = LightPos-tpos;"
            "			geomGlow = 1.0;"
            "			gl_Position = "
            "				ProjectionMatrix *"
            "				CameraMatrix *"
            "				vec4(tpos, 1.0);"
            "			EmitVertex();"
            "			geomGlow = 0.7;"
            "			geomLight = LightPos-tpos+pofs;"
            "			gl_Position = "
            "				ProjectionMatrix *"
            "				CameraMatrix *"
            "				vec4(tpos + pofs, 1.0);"
            "			EmitVertex();"
            "		}"
            "		EndPrimitive();"
            "	}"

            "	geomGlow = 0.0;"
            "	geomTop = 1;"
            "	for(int i=0; i!=3; ++i)"
            "	{"
            "		geomLight = LightPos - (pos[i]+pofs);"
            "		geomNormal = vertNormal[i];"
            "		gl_Position = "
            "			ProjectionMatrix *"
            "			CameraMatrix *"
            "			vec4(pos[i] + pofs, 1.0);"
            "		EmitVertex();"
            "	}"
            "	EndPrimitive();"
            "}"
        );
        gs.Compile();

        transf_prog.AttachShader(vs);
        transf_prog.AttachShader(gs);
        transf_prog.MakeSeparable();
        transf_prog.Link();
        transf_prog.Use();

        ProgramUniform<Vec3f>(transf_prog, "LightPos").Set(4, 4, -8);

        torus.Bind();
        verts.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_torus.Positions(data);
            Buffer::Data(Buffer::Target::Array, data);

            VertexAttribArray attr(transf_prog, "Position");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        normals.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_torus.Normals(data);
            Buffer::Data(Buffer::Target::Array, data);

            VertexAttribArray attr(transf_prog, "Normal");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        texcoords.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_torus.TexCoordinates(data);
            Buffer::Data(Buffer::Target::Array, data);

            VertexAttribArray attr(transf_prog, "TexCoord");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        face_fs.Source(
            "#version 330\n"
            "in vec3 geomNormal;"
            "in vec3 geomLight;"
            "in float geomGlow;"
            "flat in int geomTop;"
            "uniform vec3 TopColor, SideColor;"
            "const vec3 LightColor = vec3(1.0, 1.0, 1.0);"
            "out vec4 fragColor;"
            "void main(void)"
            "{"
            "	float d = max(dot("
            "		normalize(geomLight),"
            "		normalize(geomNormal)"
            "	), 0.0);"
            "	vec3 color;"
            "	if(geomTop != 0)"
            "	{"
            "		color = TopColor * d +"
            "			LightColor * pow(d, 8.0);"
            "	}"
            "	else"
            "	{"
            "		color = SideColor * geomGlow +"
            "			LightColor *"
            "			pow(d, 2.0) * 0.2;"
            "	}"
            "	fragColor = vec4(color, 1.0);"
            "}"
        );
        face_fs.Compile();

        face_prog.AttachShader(face_fs);
        face_prog.MakeSeparable();
        face_prog.Link();

        ProgramUniform<Vec3f>(face_prog, "TopColor").Set(0.2f, 0.2f, 0.2f);
        ProgramUniform<Vec3f>(face_prog, "SideColor").Set(0.9f, 0.9f, 0.2f);

        face_pp.Bind();
        face_prog.Use();
        face_pp.UseStages(transf_prog).Vertex().Geometry();
        face_pp.UseStages(face_prog).Fragment();


        frame_fs.Source(
            "#version 330\n"
            "out vec4 fragColor;"
            "void main(void)"
            "{"
            "	fragColor = vec4(0.2, 0.1, 0.0, 1.0);"
            "}"
        );
        frame_fs.Compile();

        frame_prog.AttachShader(frame_fs);
        frame_prog.MakeSeparable();
        frame_prog.Link();

        frame_pp.Bind();
        frame_prog.Use();
        frame_pp.UseStages(transf_prog).Vertex().Geometry();
        frame_pp.UseStages(frame_prog).Fragment();

        ProgramPipeline::Unbind();
        Program::UseNone();

        gl.ClearColor(0.7f, 0.6f, 0.5f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.Enable(Capability::DepthTest);
        gl.DepthFunc(CompareFn::Less);
        gl.FrontFace(make_torus.FaceWinding());
    }
Beispiel #8
0
void Computer::executeInstruction()
{
	const auto& i = program[programCounter];
	switch (i.op)
	{
	case Opcode::cpy:
	{
		auto v = evalOperand(i.x);
		if(i.y.value < 0 || i.y.value>=registers.registerCount())
			throw runtime_error("Invalid register");
		registers.registerValues[i.y.value] = v;
		programCounter++;
		break;
	}
	case Opcode::inc:
	{
		if(i.x.value<0||i.x.value>=registers.registerCount())
			throw runtime_error("Invalid register");
		registers.registerValues[i.x.value]++;
		programCounter++;
		break;
	}
	case Opcode::dec:
	{
		if(i.x.value<0||i.x.value>=registers.registerCount())
			throw runtime_error("Invalid register");
		registers.registerValues[i.x.value]--;
		programCounter++;
		break;
	}
	case Opcode::jnz:
	{
		auto vx = evalOperand(i.x);
		auto vy = evalOperand(i.y);
		programCounter += (vx != 0 ? vy : 1);
		break;
	}
	case Opcode::tgl:
	{
		auto v = evalOperand(i.x);
		auto tglAddr = programCounter + v;
		if(tglAddr>=0&&tglAddr<program.size())
		{
			auto& tglInstr = program[tglAddr];
			switch(tglInstr.op)
			{
				case Opcode::cpy:
					tglInstr.op = Opcode::jnz;
					break;
				case Opcode::inc:
					tglInstr.op = Opcode::dec;
					break;
				case Opcode::dec:
					tglInstr.op = Opcode::inc;
					break;
				case Opcode::jnz:
					tglInstr.op = Opcode::cpy;
					break;
				case Opcode::tgl:
					tglInstr.op = Opcode::inc;
					break;
			}
		}
		programCounter++;
		break;
	}
	case Opcode::out:
	{
		auto v = evalOperand(i.x);
		if(outFn)
		{
			outFn(v);
		}
		programCounter++;
		break;
	}
	}
}
Beispiel #9
0
Program parseInstructions(const vector<string>& instructionsInText)
{
	regex cpyRgx("cpy ([a-d]|[+-]?\\d+) ([a-d])");
	regex incRgx("inc ([a-d])");
	regex decRgx("dec ([a-d])");
	regex jnzRgx("jnz ([a-d]|[+-]?\\d+) ([a-d]|[+-]?\\d+)");
	regex tglRgx("tgl ([a-z])");
	regex tglOut("out ([a-z])");

	Program p;
	for (const auto& i : instructionsInText)
	{
		Instruction instr;

		smatch m;
		if (regex_match(i, m, cpyRgx))
		{
			auto m1 = m[1].str();
			auto m2 = m[2].str();
			instr.op = Opcode::cpy;
			instr.x = parseOperand(m1);
			instr.y = parseOperand(m2);
		} else if (regex_match(i, m, incRgx))
		{
			auto m1 = m[1].str();
			instr.op = Opcode::inc;
			instr.x = parseOperand(m1);
		} else if (regex_match(i, m, decRgx))
		{
			auto m1 = m[1].str();
			instr.op = Opcode::dec;
			instr.x = parseOperand(m1);
		}
		else if (regex_match(i, m, jnzRgx))
		{
			auto m1 = m[1].str();
			auto m2 = m[2].str();
			instr.op = Opcode::jnz;
			instr.x = parseOperand(m1);
			instr.y = parseOperand(m2);
		}
		else if(regex_match(i, m, tglRgx))
		{
			auto m1 = m[1].str();
			instr.op = Opcode::tgl;
			instr.x = parseOperand(m1);
		}
		else if(regex_match(i, m, tglOut))
		{
			auto m1 = m[1].str();
			instr.op = Opcode::out;
			instr.x = parseOperand(m1);
		}
		else
		{
			assert(0);
			throw runtime_error("Invalid instruction");
		}
		p.push_back(move(instr));
	}
	return p;
}
Beispiel #10
0
extern void ImportSoftware::importData()
{
    QStringList args;
    args << "-listsoftware";
    Program process;
    process.setArguments(args);
    QXmlStreamReader xml;
    xml.setDevice(&process);
    if(process.open(QIODevice::ReadOnly)){
        QMap<QString,QString> map;
        QString machine;
        while(!process.state()==QProcess::NotRunning){
            if (process.atEnd())
                process.waitForReadyRead();
            xml.readNextStartElement();
            if(xml.isStartElement()){
                if(xml.name()=="softwarelist")
                    machine=xml.attributes().value("name").toString();
                else if(xml.name()=="software"){
                    map.insert("machine",machine);
                    QXmlStreamAttributes attributes=xml.attributes();
                    foreach(QXmlStreamAttribute attribute,attributes.toList())
                        map.insert(attribute.name().toString(),attribute.value().toString());
                }
                else if(xml.name()=="description"){
                    QString description=xml.readElementText();
                    if(description.contains("(")){
                        int index=description.indexOf("(");
                        map.insert("version",description.mid(index+1,description.size()-index-2));
                        description.truncate(index-1);
                    }
                    if(description.contains(" / ")){
                        int index=description.indexOf(" / ");
                        description.truncate(index);
                    }
                    if(description.contains(" - ")){
                        int index=description.indexOf(" - ");
                        map.insert("subtitle",description.mid(index+3));
                        description.truncate(index);
                    }
                    else if(description.contains(": ")){
                        int index=description.indexOf(": ");
                        map.insert("subtitle",description.mid(index+2));
                        description.truncate(index);
                    }
                    map.insert("title",description);
                }
                else if(xml.name()=="year"){
                    map.insert("year",xml.readElementText());
                }
                else if(xml.name()=="publisher"){
                    map.insert("developer",xml.readElementText());
                }
            }
            else if(xml.isEndElement() && xml.name()=="software"){
                dataTable.append(map);
                map.clear();
            }
        }
    }
}
Beispiel #11
0
int main(void)
{
    GLFWwindow* window;

    // Initialize the library
    if (!glfwInit())
        return -1;

    // Activate supersampling
    glfwWindowHint(GLFW_SAMPLES, 8);

    // Ensure that we get at least a 3.2 context
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);

    // On apple we have to load a core profile with forward compatibility
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

    // Create a windowed mode window and its OpenGL context
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    // Make the window's context current
    glfwMakeContextCurrent(window);

    #ifndef __APPLE__
      glewExperimental = true;
      GLenum err = glewInit();
      if(GLEW_OK != err)
      {
        /* Problem: glewInit failed, something is seriously wrong. */
       fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
      }
      glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM
      fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    #endif

    int major, minor, rev;
    major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
    minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
    rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
    printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
    printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
    printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));

    // Initialize the VAO
    // A Vertex Array Object (or VAO) is an object that describes how the vertex
    // attributes are stored in a Vertex Buffer Object (or VBO). This means that
    // the VAO is not the actual object storing the vertex data,
    // but the descriptor of the vertex data.
    VertexArrayObject VAO;
    VAO.init();
    VAO.bind();

    // Initialize the VBO with the vertices data
    // A VBO is a data container that lives in the GPU memory
    VBO.init();

    V.resize(2,6);
    V <<
    0,  0.5, -0.5, 0.1,  0.6, -0.4,
    0.5, -0.5, -0.5, 0.6, -0.4, -0.4;
    VBO.update(V);

    // Initialize the OpenGL Program
    // A program controls the OpenGL pipeline and it must contains
    // at least a vertex shader and a fragment shader to be valid
    Program program;
    const GLchar* vertex_shader =
            "#version 150 core\n"
                    "in vec2 position;"
                    "void main()"
                    "{"
                    "    gl_Position = vec4(position, 0.0, 1.0);"
                    "}";
    const GLchar* fragment_shader =
            "#version 150 core\n"
                    "out vec4 outColor;"
                    "uniform vec4 triangleColor;"
                    "void main()"
                    "{"
                    "    outColor = vec4(triangleColor);"
                    "}";

    // Compile the two shaders and upload the binary to the GPU
    // Note that we have to explicitly specify that the output "slot" called outColor
    // is the one that we want in the fragment buffer (and thus on screen)
    program.init(vertex_shader,fragment_shader,"outColor");
    program.bind();

    // The vertex shader wants the position of the vertices as an input.
    // The following line connects the VBO we defined above with the position "slot"
    // in the vertex shader
    program.bindVertexAttribArray("position",VBO);

    // Register the keyboard callback
    glfwSetKeyCallback(window, key_callback);

    // Register the mouse callback
    glfwSetMouseButtonCallback(window, mouse_button_callback);

    // Update viewport
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // Loop until the user closes the window
    while (!glfwWindowShouldClose(window))
    {
        // Bind your VAO (not necessary if you have only one)
        VAO.bind();

        // Bind your program
        program.bind();

        // Clear the framebuffer
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Enable blending test
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        // Draw a triangle (red)
        glUniform4f(program.uniform("triangleColor"), 1.0f, 0.0f, 0.0f, 1.0f);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // Draw a triangle (green)
        glUniform4f(program.uniform("triangleColor"), 0.0f, 1.0f, 0.0f, 0.5f);
        glDrawArrays(GL_TRIANGLES, 3, 3);

        // Swap front and back buffers
        glfwSwapBuffers(window);

        // Poll for and process events
        glfwPollEvents();
    }

    // Deallocate opengl memory
    program.free();
    VAO.free();
    VBO.free();

    // Deallocate glfw internals
    glfwTerminate();
    return 0;
}
Beispiel #12
0
	CubeExample(void)
	 : cube_instr(make_cube.Instructions())
	 , cube_indices(make_cube.Indices())
	 , projection_matrix(prog)
	 , camera_matrix(prog)
	{
		// Set the vertex shader source and compile it
		vs.Source(
			"#version 330\n"
			"in vec4 Position;"
			"void main(void)"
			"{"
			"	gl_Position = Position;"
			"}"
		).Compile();

		// Set the geometry shader source and compile it
		gs.Source(
			"#version 330\n"
			"layout(triangles) in;"
			"layout(triangle_strip, max_vertices = 108) out;"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"out vec3 vertColor;"
			"void main(void)"
			"{"
			"	for(int c=0; c!=36; ++c)"
			"	{"
			"		float angle = c * 10 * 2 * 3.14159 / 360.0;"
			"		float cx = cos(angle);"
			"		float sx = sin(angle);"
			"		mat4 ModelMatrix = mat4("
			"			 cx, 0.0,  sx, 0.0,"
			"			0.0, 1.0, 0.0, 0.0,"
			"			-sx, 0.0,  cx, 0.0,"
			"			0.0, 0.0, 0.0, 1.0 "
			"		) * mat4("
			"			 1.0, 0.0, 0.0, 0.0,"
			"			 0.0, 1.0, 0.0, 0.0,"
			"			 0.0, 0.0, 1.0, 0.0,"
			"			12.0, 0.0, 0.0, 1.0 "
			"		);"
			"		for(int v=0; v!=gl_in.length(); ++v)"
			"		{"
			"			vec4 vert = gl_in[v].gl_Position;"
			"			gl_Position = "
			"				ProjectionMatrix *"
			"				CameraMatrix *"
			"				ModelMatrix *"
			"				vert;"
			"			vertColor = abs(normalize(ModelMatrix*vert)).xzy;"
			"			EmitVertex();"
			"		}"
			"		EndPrimitive();"
			"	}"
			"}"
		).Compile();

		// set the fragment shader source and compile it
		fs.Source(
			"#version 330\n"
			"in vec3 vertColor;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4(vertColor, 1.0);"
			"}"
		).Compile();

		// attach the shaders to the program
		prog << vs << gs << fs;
		// link and use it
		prog.Link().Use();

		projection_matrix.BindTo("ProjectionMatrix");
		camera_matrix.BindTo("CameraMatrix");

		// bind the VAO for the cube
		cube.Bind();

		// bind the VBO for the cube vertices
		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex).Enable();
		}

		gl.ClearColor(0.9f, 0.9f, 0.9f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
	}
Beispiel #13
0
PVR_ERROR DVBLinkClient::GetEPGForChannel(ADDON_HANDLE handle, const PVR_CHANNEL& channel, time_t iStart, time_t iEnd)
{
  PVR_ERROR result = PVR_ERROR_FAILED;
  PLATFORM::CLockObject critsec(m_mutex);
  Channel * c = m_channelMap[channel.iUniqueId];
  EpgSearchResult epgSearchResult;

  if (DoEPGSearch(epgSearchResult,c->GetID(), iStart, iEnd))
  {
    for (std::vector<ChannelEpgData*>::iterator it = epgSearchResult.begin(); it < epgSearchResult.end(); it++) 
    {
      ChannelEpgData* channelEpgData = (ChannelEpgData*)*it;
      EpgData& epgData = channelEpgData->GetEpgData();
      for (std::vector<Program*>::iterator pIt = epgData.begin(); pIt < epgData.end(); pIt++) 
      {
        Program* p = (Program*)*pIt;
        EPG_TAG broadcast;
        memset(&broadcast, 0, sizeof(EPG_TAG));

        broadcast.iUniqueBroadcastId = p->GetStartTime();
        broadcast.strTitle = p->GetTitle().c_str();
        broadcast.iChannelNumber      = channel.iChannelNumber;
        broadcast.startTime           = p->GetStartTime();
        broadcast.endTime             = p->GetStartTime() + p->GetDuration();
        broadcast.strPlot             = p->ShortDescription.c_str();
        broadcast.strCast             = p->Actors.c_str();
        broadcast.strDirector         = p->Directors.c_str();
        broadcast.strWriter           = p->Writers.c_str();
        broadcast.iYear               = p->Year;
        broadcast.strIconPath         = p->Image.c_str();
        broadcast.iGenreType          = 0;
        broadcast.iGenreSubType       = 0;
        broadcast.strGenreDescription = "";
        broadcast.firstAired          = 0;
        broadcast.iParentalRating     = 0;
        broadcast.iStarRating         = p->Rating;
        broadcast.bNotify             = false;
        broadcast.iSeriesNumber       = p->SeasonNumber;
        broadcast.iEpisodeNumber      = p->EpisodeNumber;
        broadcast.iEpisodePartNumber  = 0;
        broadcast.strEpisodeName      = p->SubTitle.c_str();
        broadcast.strIMDBNumber       = NULL; // unused
        broadcast.strOriginalTitle    = NULL; // unused
        broadcast.strPlotOutline      = NULL;

        int genre_type, genre_subtype;
        SetEPGGenre(*p, genre_type, genre_subtype);
        broadcast.iGenreType = genre_type;
        if (genre_type == EPG_GENRE_USE_STRING)
          broadcast.strGenreDescription = p->Keywords.c_str();
        else
          broadcast.iGenreSubType = genre_subtype;

        broadcast.iFlags              = EPG_TAG_FLAG_UNDEFINED;
        
        PVR->TransferEpgEntry(handle, &broadcast);
      }
    }
    result = PVR_ERROR_NO_ERROR;
  }
  else
  {
    XBMC->Log(LOG_NOTICE, "Not EPG data found for channel : %s with id : %i", channel.strChannelName, channel.iUniqueId);
  }
  return result;
}
Beispiel #14
0
	TorusExample(void)
	 : make_torus(1.0, 0.5, 72, 48)
	 , torus_instr(make_torus.Instructions())
	 , torus_indices(make_torus.Indices())
	{
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 vertNormal;"
			"out vec3 vertViewDir;"
			"void main(void)"
			"{"
			"	vertNormal = Normal;"
			"	vertViewDir = ("
			"		vec4(0.0, 0.0, 1.0, 1.0)*"
			"		CameraMatrix"
			"	).xyz;"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"in vec3 vertNormal;"
			"in vec3 vertViewDir;"
			"out vec4 fragColor;"
			"uniform vec3 LightPos[3];"
			"void main(void)"
			"{"
			"	float amb = 0.2;"
			"	float diff = 0.0;"
			"	float spec = 0.0;"
			"	for(int i=0;i!=3;++i)"
			"	{"
			"		diff += max("
			"			dot(vertNormal,  LightPos[i])/"
			"			dot(LightPos[i], LightPos[i]),"
			"			0.0"
			"		);"
			"		float k = dot(vertNormal, LightPos[i]);"
			"		vec3 r = 2.0*k*vertNormal - LightPos[i];"
			"		spec += pow(max("
			"			dot(normalize(r), vertViewDir),"
			"			0.0"
			"		), 32.0 * dot(r, r));"
			"	}"
			"	fragColor = "
			"		vec4(1.0, 0.1, 0.3, 1.0)*(amb+diff)+"
			"		vec4(1.0, 1.0, 1.0, 1.0)*spec;"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the torus
		torus.Bind();

		// bind the VBO for the torus vertices
		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexAttribArray attr(prog, "Position");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();
		}

		// bind the VBO for the torus normals
		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Normals(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexAttribArray attr(prog, "Normal");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();
		}

		// set the light positions
		Uniform<Vec3f> light_pos(prog, "LightPos");
		light_pos[0].Set(Vec3f(2.0f,-1.0f, 0.0f));
		light_pos[1].Set(Vec3f(0.0f, 3.0f, 0.0f));
		light_pos[2].Set(Vec3f(0.0f,-1.0f, 4.0f));
		//
		gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_torus.FaceWinding());
		gl.CullFace(Face::Back);
	}
Beispiel #15
0
//Está un poco fuzzy, habrá que estructurarlo y tal, pero correcto
void SVMachine::quadraticSolution() {
	int n = C_trainingSet.size();
	int m = 1; // Entiendo que es el numero de restricciones
	Program qp (CGAL::EQUAL);

	// Obtengo la X
//	Utils::scalation(C_trainingSet); // Escalado de parámetros

	std::cout << "n vale: " << n << std::endl;
	std::cout << "nFeatures vale: " << C_nFeatures << std::endl;
	C_X = arma::mat(n, C_nFeatures);

	for(int i = 0; i < n; i++){
		for(int j = 0; j < C_nFeatures; j++){
			C_X(i,j) = C_trainingSet[i].getInput()[j];
		}
	}
	std::cout << "X vale: " << std::endl << C_X;

	// Obtengo la Y
	C_y = arma::mat(n, 1);

	std::cout << "n vale: " << n << std::endl;
	for(int i = 0; i < n; i++){
		C_y(i) = C_trainingSet[i].getResult()[0];
	}

	std::cout << "Y vale: " << std::endl << C_y;
	// Seteo la restriccion
	for(int i = 0; i < n; i++){
		qp.set_a(i,0,ET(C_y.at(i)));
		qp.set_l(i,true,ET(0));
		qp.set_u(i,false);
		qp.set_c(i,ET(-1));
//		std::cout << "y(" << i << "): " << y.at(i) << std::endl;
	}

	qp.set_b(0,ET(0));
	qp.set_r(0,CGAL::EQUAL);
	qp.set_c0(ET(0));

	// Seteo la symmetric positive-semidefinite matrix
	for(int i = 0; i < n; i++){
		for(int j = 0; j<=i; j++){
			ET ip = C_kernel->K(C_X.row(i).t(),C_X.row(j).t());
//			std::cout << "El kernel para " << i << "," << j << " nos dice que el innerproduct es: " << ip << std::endl;
			ET daux = ip*ET(C_y.at(i))*ET(C_y.at(j));
			std::cout << "El producto de " << i << "," << j << ": " << daux << std::endl;
			qp.set_d(i,j,daux);
//			std::cout << "La matriz auxiliar vale:" <<  daux << std::endl;
		}
	}

	 // solve the program, using ET as the exact type
	Solution s = CGAL::solve_quadratic_program(qp, ET());
	// print basic constraint indices (we know that there is only one: 1)
	std::cout << "Y la solución es: " << s << std::endl;
//	arma::mat W = arma::mat(n,1);

	C_SupportVectors = arma::mat(n,1);

	ET sumaB(0.0);

	if(s.is_optimal()) { // we know that, don't we?
		int i = 0;
		for (Solution::Variable_value_iterator it = s.variable_values_begin(); it != s.variable_values_end(); ++it){
			C_SupportVectors(i) = CGAL::to_double(*it);
			if(C_SupportVectors.at(i) != 0.0){
				C_m = i; // Esto lo hago para obtener un sv que me resuelva la b
			}
			i++;
		}
		// Calculo la b
		for(int i=0; i<n; i++)
			if(C_SupportVectors.at(i) != 0.0)
				sumaB += ET(C_SupportVectors.at(i))*ET(C_y.at(i))*C_kernel->K(C_X.row(i).t(), C_X.row(C_m).t());
		C_b = ET(C_y(C_m)) - sumaB;
		std::cout << "Y el valor de b es: "<< C_b << std::endl;
	} else std::cout << "No es optima, vete tu a saber por qué...\n";

//	int pausa; std::cin >> pausa;
}
Beispiel #16
0
	SphereExample(void)
	 : sphere_instr(make_sphere.Instructions())
	 , sphere_indices(make_sphere.Indices())
	 , hole_count(50)
	 , hole_diameter(0.30f)
	{
		// This shader will be used in transform fedback mode
		// to transform the vertices used to "cut out the holes"
		// the same way the sphere is transformed
		vs_tfb.Source(
			"#version 330\n"
			"uniform mat4 CameraMatrix, ModelMatrix;"
			"uniform float Diameter;"
			"in vec3 Hole;"
			"out vec3 vertTransfHole;"
			"void main(void)"
			"{"
			"	vertTransfHole = ("
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		vec4(Hole * (1.0 + 0.5 * Diameter), 0.0)"
			"	).xyz;"
			"}"
		);
		// compile, setup transform feedback output variables
		// link and use the program
		vs_tfb.Compile();
		prog_tfb.AttachShader(vs_tfb);

		const GLchar* var_name = "vertTransfHole";
		prog_tfb.TransformFeedbackVaryings(
			1, &var_name,
			TransformFeedbackMode::InterleavedAttribs
		);
		prog_tfb.Link();
		prog_tfb.Use();

		Uniform<GLfloat> diameter(prog_tfb, "Diameter");
		diameter.Set(hole_diameter);

		// bind the VAO for the holes
		holes.Bind();

		// bind the VBO for the hole vertices
		hole_verts.Bind(Buffer::Target::Array);
		// and the VBO for the transformed hole vertices captured by tfb
		transf_hole_verts.Bind(Buffer::Target::TransformFeedback);
		{
			std::vector<GLfloat> data;
			make_hole_data(data, hole_count);
			Buffer::Data(Buffer::Target::TransformFeedback, data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(prog_tfb, "Hole");
			attr.Setup<Vec3f>();
			attr.Enable();
		}
		transf_hole_verts.BindBase(
			Buffer::IndexedTarget::TransformFeedback,
			0
		);

		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 vertNormal;"
			"out vec3 vertLight;"
			"const vec3 LightPos = vec3(2.0, 3.0, 3.0);"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertLight = LightPos-gl_Position.xyz;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"in vec3 vertNormal;"
			"in vec3 vertLight;"
			"out vec4 fragColor;"
			"const int HoleCount = 50;"
			"uniform vec3 TransfHole[50];"
			"uniform float Diameter;"
			"void main(void)"
			"{"
			"	int imax = 0;"
			"	float dmax = -1.0;"
			"	for(int i=0; i!=HoleCount; ++i)"
			"	{"
			"		float d = dot(vertNormal, TransfHole[i]);"
			"		if(dmax < d)"
			"		{"
			"			dmax = d;"
			"			imax = i;"
			"		}"
			"	}"
			"	float l = length(vertLight);"
			"	vec3 FragDiff = TransfHole[imax] - vertNormal;"
			"	vec3 FinalNormal = "
			"		length(FragDiff) > Diameter?"
			"		vertNormal:"
			"		normalize(FragDiff+vertNormal*Diameter);"
			"	float i = (l > 0.0) ? dot("
			"		FinalNormal, "
			"		normalize(vertLight)"
			"	) / l : 0.0;"
			"	i = 0.2+max(i*2.5, 0.0);"
			"	fragColor = vec4(i, i, i, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		diameter.Set(hole_diameter);

		// bind the VAO for the sphere
		sphere.Bind();

		// bind the VBO for the sphere vertices
		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_sphere.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the sphere normals
		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_sphere.Normals(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
	}
/***************************************************************
* Function: ANIMCreateVirtualSphere()
*
***************************************************************/
void ANIMCreateVirtualSphere(osg::PositionAttitudeTransform** xformScaleFwd, 
			     osg::PositionAttitudeTransform** xformScaleBwd)
{
    // create sphere geometry
    *xformScaleFwd = new PositionAttitudeTransform;
    *xformScaleBwd = new PositionAttitudeTransform;
    Geode* sphereGeode = new Geode();
    Sphere* virtualSphere = new Sphere();
    Drawable* sphereDrawable = new ShapeDrawable(virtualSphere);

    virtualSphere->setRadius(ANIM_VIRTUAL_SPHERE_RADIUS);
    sphereGeode->addDrawable(sphereDrawable);
    (*xformScaleFwd)->addChild(sphereGeode);
    (*xformScaleBwd)->addChild(sphereGeode);

    osg::StateSet* stateset;   

    // highlights
/*    Sphere* highlightSphere = new Sphere();
    ShapeDrawable* highlightDrawable = new ShapeDrawable(highlightSphere);
    Geode* highlightGeode = new Geode();
    highlightSphere->setRadius(ANIM_VIRTUAL_SPHERE_RADIUS * 1.3);
    highlightDrawable->setColor(osg::Vec4(0,0,1,0.3));
    highlightGeode->addDrawable(highlightDrawable);
    (*xformScaleFwd)->addChild(highlightGeode);
    (*xformScaleBwd)->addChild(highlightGeode);

    stateset = highlightDrawable->getOrCreateStateSet();
    stateset->setMode(GL_BLEND, StateAttribute::ON);
    stateset->setMode(GL_CULL_FACE, StateAttribute::ON);
    stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);
*/

    // set up the forward / backward scale animation path
    AnimationPath* animationPathScaleFwd = new AnimationPath;
    AnimationPath* animationPathScaleBwd = new AnimationPath;
    animationPathScaleFwd->setLoopMode(AnimationPath::NO_LOOPING);
    animationPathScaleBwd->setLoopMode(AnimationPath::NO_LOOPING);

    osg::Vec3 pos(-1.5, 0, 0);

    Vec3 scaleFwd, scaleBwd;
    float step = 1.f / ANIM_VIRTUAL_SPHERE_NUM_SAMPS;
    for (int i = 0; i < ANIM_VIRTUAL_SPHERE_NUM_SAMPS + 1; i++)
    {
        float val = i * step;
        scaleFwd = Vec3(val, val, val);
        scaleBwd = Vec3(1-val, 1-val, 1-val);
        animationPathScaleFwd->insert(val, AnimationPath::ControlPoint(pos, Quat(), scaleFwd));
        animationPathScaleBwd->insert(val, AnimationPath::ControlPoint(pos, Quat(), scaleBwd));
    }

    AnimationPathCallback *animCallbackFwd = new AnimationPathCallback(animationPathScaleFwd,
						0.0, 1.f / ANIM_VIRTUAL_SPHERE_LAPSE_TIME);
    AnimationPathCallback *animCallbackBwd = new AnimationPathCallback(animationPathScaleBwd,
						0.0, 1.f / ANIM_VIRTUAL_SPHERE_LAPSE_TIME);
    (*xformScaleFwd)->setUpdateCallback(animCallbackFwd);
    (*xformScaleBwd)->setUpdateCallback(animCallbackBwd);

    /* apply shaders to geode stateset */
    stateset = new StateSet();
    stateset->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
    stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);
    //sphereGeode->setStateSet(stateset);
    sphereDrawable->setStateSet(stateset);

    Program* shaderProg = new Program;
    stateset->setAttribute(shaderProg);
    shaderProg->addShader(Shader::readShaderFile(Shader::VERTEX, ANIMDataDir() + "Shaders/VirtualSphere.vert"));
    shaderProg->addShader(Shader::readShaderFile(Shader::FRAGMENT, ANIMDataDir() + "Shaders/VirtualSphere.frag"));

    Image* envMap = osgDB::readImageFile(ANIMDataDir() + "Textures/EnvMap.JPG");
    Texture2D* envTex = new Texture2D(envMap);
    stateset->setTextureAttributeAndModes(0, envTex, StateAttribute::ON);

    Uniform* envMapSampler = new Uniform("EnvMap", 0);
    stateset->addUniform(envMapSampler);

    Uniform* baseColorUniform = new Uniform("BaseColor", Vec3(0.2, 1.0, 0.2));
    stateset->addUniform(baseColorUniform);

    Uniform* lightPosUniform = new Uniform("LightPos", Vec4(1.0, 0.0, 0.2, 0.0));
    stateset->addUniform(lightPosUniform);

}
Program* ProgramManager::CreateFromDescriptor( ProgramDescriptor* descriptor )
{
	int id;
	string name;
	string description;

	DescriptorsUtil::GetIntProperty( descriptor->Properties, "Id", &id );
	DescriptorsUtil::GetStringProperty( descriptor->Properties, "Name", &name );
	DescriptorsUtil::GetStringProperty( descriptor->Properties, "Description",
			&description );

	Program* program = new Program( id, name, description );
	string deviceType;
	// ------ Initialize Devices:
	list<DeviceDescriptor>::iterator deviceIt;
	for ( deviceIt = descriptor->Devices.begin(); deviceIt
			!= descriptor->Devices.end(); deviceIt++ )
	{
		BaseDevice* device = DeviceManager::Instance()->CreateFromDescriptor(
				*deviceIt );

		if( device == NULL )
			return NULL;

		program->AddDevice( device );
	}
	// ------- Initialize Wires:
	list<WireDescriptor>::iterator wireIt;
	list<WireConnectionPointDescriptor>::iterator cpIt; //connectionPointsIt

	for ( wireIt = descriptor->Wires.begin(); wireIt != descriptor->Wires.end(); wireIt++ )
	{
		Wire* wire = new Wire();

		for ( cpIt = ( *wireIt ).WireConnectionPoints.begin(); cpIt
				!= ( *wireIt ).WireConnectionPoints.end(); cpIt++ )
		{
			BaseDevice* device = program->GetDevice(
					( *cpIt ).DeviceDescriptorId );
			ConnectionPoint* cp = device->GetConnectionPoint(
					( *cpIt ).ConnectionPointDescriptorId );

			wire->Attach( cp );
		}

		program->AddWire( wire );
	}

	// ------ Initialize the program's Power Wire:
	list<WireConnectionPointDescriptor>* stratupPoints =
			&descriptor->PowerWire.WireConnectionPoints;
	for ( cpIt = stratupPoints->begin(); cpIt != stratupPoints->end(); cpIt++ )
	{
		int* startUpValue = new int( 1 );

		BaseDevice* device = program->GetDevice( ( *cpIt ).DeviceDescriptorId );
		ConnectionPoint* cp = device->GetConnectionPoint(
				( *cpIt ).ConnectionPointDescriptorId );

		InConnectionPoint* inConnectionPoint = (InConnectionPoint*) cp;
		inConnectionPoint->SetValue( startUpValue );

		program->PowerWire()->Attach( inConnectionPoint );
	}

	return program;
}
Beispiel #19
0
int FullTree::breed(System* system, Population* src, vector<Program>* newpop, int index)
{
	Program* newp;
	newpop->push_back(Program(system));
	newp=&newpop->back();

	newp->functions.assign(system->adf.begin(), system->adf.end());

	newp->branch.push_back(vector<TreeNode>());

	// Push the main program branch on
	fulltree(system, system->returntype, TreeNodeIter(&newp->branch[0], 0), (maxdepth<=mindepth?0:(rand()%(maxdepth-mindepth+1)))+mindepth);

	// Need to add ADF branches
	for (int i=0;i<system->adf.size();++i)
		newp->branch.push_back(vector<TreeNode>());

	ADF* curfunc;
	for (int i=system->adf.size()-1;i>=0;--i)
	{
		curfunc = (ADF*)(system->adf[i]);

		// Remove current function from list
		if (system->recursiveDepth<=0)
		{
#ifdef DEBUG
			if (system->functions[curfunc->arg_type[0]].back()!=curfunc)
				throw runtime_error("Function being popped off of system does not match last adf entry");
#endif
			system->functions[curfunc->arg_type[0]].pop_back();
		}
		// Push function arguments
		for (int j=1;j<curfunc->arg_type.size();++j)
			system->functions[curfunc->arg_type[j]].push_back(curfunc->args[j-1]);

		// Generate tree
		fulltree(system, curfunc->arg_type[0], TreeNodeIter(&newp->branch[i+1], 0), (maxdepth<=mindepth?0:(rand()%(maxdepth-mindepth+1)))+mindepth);

		// Pop function arguments
		for (int j=curfunc->arg_type.size()-1;j>=1;--j)
		{
			system->functions[curfunc->arg_type[j]].pop_back();
		}
	}
	
	if (system->recursiveDepth<=0)
	{
		for (int i=0;i<system->adf.size();++i)
		{
			curfunc = (ADF*)system->adf[i];
			system->functions[curfunc->arg_type[0]].push_back(curfunc);
		}
	}

#ifdef DEBUG
	if (!newp->checkConsistency())
	{
		throw runtime_error("Invalid produced program");
	}
#endif

	return 1;
}
Beispiel #20
0
void program_2(int a, int b) {
    Program qp (CGAL::SMALLER, false, 0, true, 0);
    const int X = 0;
    const int Y = 1;
    const int Z = 2;
    
    qp.set_l(Z, 0);
    qp.set_u(Z, false);

    // minimize a*x^2 + b*y + z^4
    qp.set_d(X, X, 2*a);
    qp.set_d(Z, Z, 2*1);        // by convention: we multiply value by 2.

    qp.set_c(Y, b);

    qp.set_a(X, 0, 1);
    qp.set_a(Y, 0, 1);
    qp.set_b(0, -4);
    qp.set_r(0, CGAL::LARGER);

    qp.set_a(X, 1, 4);
    qp.set_a(Y, 1, 2);
    qp.set_a(Z, 1, 1);
    qp.set_b(1, -1*a*b);
    qp.set_r(1, CGAL::LARGER);

    qp.set_a(X, 2, -1);
    qp.set_a(Y, 2, 1);
    qp.set_b(2, -1);
    qp.set_r(2, CGAL::LARGER);

    qp.set_a(Z, 3, 1);
    qp.set_b(3, 0);
    qp.set_r(3, CGAL::LARGER);

    Solution s = CGAL::solve_quadratic_program(qp, ET());
    assert(s.solves_quadratic_program(qp));
    
    if(s.is_optimal()) {
        double result = ceil(CGAL::to_double(s.objective_value()));        
        cout << result << "\n";
    }
    else if(s.is_unbounded()) 
        cout << "unbounded\n";
    else if(s.is_infeasible()) 
        cout << "no\n";
}
Beispiel #21
0
	RectangleExample(void)
	 : vs(ShaderType::Vertex)
	 , fs(ShaderType::Fragment)
	{
		// this could be any istream
		std::stringstream vs_source(
			"#version 330\n"
			"in vec2 Position;"
			"in vec3 Color;"
			"out vec3 vertColor;"
			"void main(void)"
			"{"
			"	vertColor = Color;"
			"	gl_Position = vec4(Position, 0.0, 1.0);"
			"}"
		);
		// set the vertex shader source
		vs.Source(GLSLSource::FromStream(vs_source));
		// compile it
		vs.Compile();

		std::stringstream fs_source(
			"#version 330\n"
			"in vec3 vertColor;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4(vertColor, 1.0);"
			"}"
		);
		// set the fragment shader source
		fs.Source(GLSLSource::FromStream(fs_source));
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the rectangle
		rectangle.Bind();

		GLfloat rectangle_verts[8] = {
			-1.0f, -1.0f,
			-1.0f,  1.0f,
			 1.0f, -1.0f,
			 1.0f,  1.0f
		};
		// bind the VBO for the rectangle vertices
		verts.Bind(Buffer::Target::Array);
		// upload the data
		Buffer::Data(Buffer::Target::Array, 8, rectangle_verts);
		// setup the vertex attribs array for the vertices
		VertexAttribArray vert_attr(prog, "Position");
		vert_attr.Setup<Vec2f>().Enable();

		GLfloat rectangle_colors[12] = {
			1.0f, 1.0f, 1.0f,
			1.0f, 0.0f, 0.0f,
			0.0f, 1.0f, 0.0f,
			0.0f, 0.0f, 1.0f,
		};
		// bind the VBO for the rectangle colors
		colors.Bind(Buffer::Target::Array);
		// upload the data
		Buffer::Data(Buffer::Target::Array, 12, rectangle_colors);
		// setup the vertex attribs array for the vertices
		VertexAttribArray color_attr(prog, "Color");
		color_attr.Setup<Vec3f>().Enable();
		//
		gl.Disable(Capability::DepthTest);
	}
Beispiel #22
0
	CubeMapExample(void)
	 : shape_instr(make_shape.Instructions())
	 , shape_indices(make_shape.Indices())
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	 , model_matrix(prog, "ModelMatrix")
	{
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"in vec2 TexCoord;"
			"out vec3 vertNormal;"
			"out vec3 vertLightDir;"
			"out vec3 vertLightRefl;"
			"out vec3 vertViewDir;"
			"out vec3 vertViewRefl;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertLightDir = LightPos - gl_Position.xyz;"
			"	vertLightRefl = reflect("
			"		-normalize(vertLightDir),"
			"		normalize(vertNormal)"
			"	);"
			"	vertViewDir = ("
			"		vec4(0.0, 0.0, 1.0, 1.0)*"
			"		CameraMatrix"
			"	).xyz;"
			"	vertViewRefl = reflect("
			"		normalize(vertViewDir),"
			"		normalize(vertNormal)"
			"	);"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"uniform samplerCube TexUnit;"
			"in vec3 vertNormal;"
			"in vec3 vertLightDir;"
			"in vec3 vertLightRefl;"
			"in vec3 vertViewDir;"
			"in vec3 vertViewRefl;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(vertLightDir);"
			"	float d = dot("
			"		normalize(vertNormal), "
			"		normalize(vertLightDir)"
			"	) / l;"
			"	float s = dot("
			"		normalize(vertLightRefl),"
			"		normalize(vertViewDir)"
			"	);"
			"	vec3 lt = vec3(1.0, 1.0, 1.0);"
			"	vec3 env = texture(TexUnit, vertViewRefl).rgb;"
			"	fragColor = vec4("
			"		env * 0.4 + "
			"		(lt + env) * 1.5 * max(d, 0.0) + "
			"		lt * pow(max(s, 0.0), 64), "
			"		1.0"
			"	);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the shape
		shape.Bind();

		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// setup the texture
		{
			GLuint tex_side = 256;
			auto image = images::NewtonFractal(
				tex_side, tex_side,
				Vec3f(0.3f, 0.1f, 0.2f),
				Vec3f(1.0f, 0.8f, 0.9f),
				Vec2f(-1.0f, -1.0f),
				Vec2f( 1.0f,  1.0f),
				images::NewtonFractal::X4Minus1(),
				images::NewtonFractal::DefaultMixer()
			);
			auto tex_target = Texture::Target::CubeMap;
			// texture syntax sugar
			tex << tex_target;
			tex_target << TextureMinFilter::Linear;
			tex_target << TextureMagFilter::Linear;
			tex_target << TextureWrap::ClampToEdge;

			for(int i=0; i!=6; ++i)
			{
				Texture::CubeMapFace(i) << image;
			}
		}
		// typechecked uniform with the exact sampler type
		// on compilers supporting strongly typed enums
		// you can use:
		//Typechecked<Uniform<SLtoCpp<SLDataType::SamplerCube>>>(prog, "TexUnit").Set(0);
		// without strongly typed enums you need to do:
		typedef SLtoCpp<OGLPLUS_CONST_ENUM_VALUE(SLDataType::SamplerCube)> GLSLsamplerCube;
		Typechecked<Uniform<GLSLsamplerCube>>(prog, "TexUnit").Set(0);

		//
		Uniform<Vec3f>(prog, "LightPos").Set(Vec3f(3.0f, 5.0f, 4.0f));
		//
		gl.ClearColor(0.2f, 0.05f, 0.1f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);

		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_shape.FaceWinding());
		gl.CullFace(Face::Back);
	}
Beispiel #23
0
	CubeExample(void)
	 : cube_instr(make_cube.Instructions())
	 , cube_indices(make_cube.Indices())
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	{
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"in vec4 Position;"
			"out vec3 vertColor;"
			"void main(void)"
			"{"
			"	float angle = gl_InstanceID * 10 * 2 * 3.14159 / 360.0;"
			"	float cx = cos(angle);"
			"	float sx = sin(angle);"
			"	mat4 ModelMatrix = mat4("
			"		 cx, 0.0,  sx, 0.0,"
			"		0.0, 1.0, 0.0, 0.0,"
			"		-sx, 0.0,  cx, 0.0,"
			"		0.0, 0.0, 0.0, 1.0 "
			"	) * mat4("
			"		 1.0, 0.0, 0.0, 0.0,"
			"		 0.0, 1.0, 0.0, 0.0,"
			"		 0.0, 0.0, 1.0, 0.0,"
			"		12.0, 0.0, 0.0, 1.0 "
			"	);"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		Position;"
			"	vertColor = abs(normalize((ModelMatrix*Position).xyz));"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"in vec3 vertColor;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4(vertColor, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the cube
		cube.Bind();

		// bind the VBO for the cube vertices
		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexAttribArray attr(prog, "Position");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();
		}

		//
		gl.ClearColor(0.9f, 0.9f, 0.9f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
	}
Beispiel #24
0
void rsi_ProgramBindConstants(Context *rsc, RsProgram vp, uint32_t slot, RsAllocation constants) {
    Program *p = static_cast<Program *>(vp);
    p->bindAllocation(rsc, static_cast<Allocation *>(constants), slot);
}
//-----------------------------------------------------------------------
bool FFPTexturing::resolveFunctionsParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet)
{
	Program* vsProgram = programSet->getCpuVertexProgram();
	Program* psProgram = programSet->getCpuFragmentProgram();
	Function* vsMain   = vsProgram->getEntryPointFunction();
	Function* psMain   = psProgram->getEntryPointFunction();
	Parameter::Content texCoordContent = Parameter::SPC_UNKNOWN;
	
	switch (textureUnitParams->mTexCoordCalcMethod)
	{
		case TEXCALC_NONE:					
			// Resolve explicit vs input texture coordinates.
			
			if (textureUnitParams->mTextureMatrix.get() == NULL)
				texCoordContent = Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + textureUnitParams->mTextureUnitState->getTextureCoordSet());

			textureUnitParams->mVSInputTexCoord = vsMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES, 
				textureUnitParams->mTextureUnitState->getTextureCoordSet(), 
				Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + textureUnitParams->mTextureUnitState->getTextureCoordSet()),
				textureUnitParams->mVSInTextureCoordinateType);	
			if (textureUnitParams->mVSInputTexCoord.get() == NULL)			
				return false;		
			break;

		case TEXCALC_ENVIRONMENT_MAP:
		case TEXCALC_ENVIRONMENT_MAP_PLANAR:		
		case TEXCALC_ENVIRONMENT_MAP_NORMAL:
			// Resolve vertex normal.
			mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPS_NORMAL, 0, Parameter::SPC_NORMAL_OBJECT_SPACE, GCT_FLOAT3);
			if (mVSInputNormal.get() == NULL)			
				return false;									
			break;	

		case TEXCALC_ENVIRONMENT_MAP_REFLECTION:

			// Resolve vertex normal.
			mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPS_NORMAL, 0, Parameter::SPC_NORMAL_OBJECT_SPACE, GCT_FLOAT3);
			if (mVSInputNormal.get() == NULL)			
				return false;		

			// Resolve vertex position.
			mVSInputPos = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);
			if (mVSInputPos.get() == NULL)			
				return false;		
			break;

		case TEXCALC_PROJECTIVE_TEXTURE:
			// Resolve vertex position.
			mVSInputPos = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);
			if (mVSInputPos.get() == NULL)			
				return false;		
			break;
	}

	// Resolve vs output texture coordinates.
	textureUnitParams->mVSOutputTexCoord = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, 
		-1,
		texCoordContent,
		textureUnitParams->mVSOutTextureCoordinateType);

	if (textureUnitParams->mVSOutputTexCoord.get() == NULL)
		return false;
		

	// Resolve ps input texture coordinates.
	textureUnitParams->mPSInputTexCoord = psMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES, 
		textureUnitParams->mVSOutputTexCoord->getIndex(),
		textureUnitParams->mVSOutputTexCoord->getContent(),
		textureUnitParams->mVSOutTextureCoordinateType);

	if (textureUnitParams->mPSInputTexCoord.get() == NULL)
		return false;

	const ShaderParameterList& inputParams = psMain->getInputParameters();
	const ShaderParameterList& localParams = psMain->getLocalParameters();

	mPSDiffuse = psMain->getParameterByContent(inputParams, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);
	if (mPSDiffuse.get() == NULL)
	{
		mPSDiffuse = psMain->getParameterByContent(localParams, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);
		if (mPSDiffuse.get() == NULL)
			return false;
	}

	mPSSpecular = psMain->getParameterByContent(inputParams, Parameter::SPC_COLOR_SPECULAR, GCT_FLOAT4);
	if (mPSSpecular.get() == NULL)
	{
		mPSSpecular = psMain->getParameterByContent(localParams, Parameter::SPC_COLOR_SPECULAR, GCT_FLOAT4);
		if (mPSSpecular.get() == NULL)
			return false;
	}

	mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);
	if (mPSOutDiffuse.get() == NULL)	
		return false;

	
	return true;
}
Beispiel #26
0
void rsi_ProgramBindTexture(Context *rsc, RsProgram vpf, uint32_t slot, RsAllocation a) {
    Program *p = static_cast<Program *>(vpf);
    p->bindTexture(rsc, slot, static_cast<Allocation *>(a));
}
Beispiel #27
0
	void SetProjection(const Mat4f& projection)
	{
		prog.Use();
		projection_matrix.Set(projection);
	}
Beispiel #28
0
void rsi_ProgramBindSampler(Context *rsc, RsProgram vpf, uint32_t slot, RsSampler s) {
    Program *p = static_cast<Program *>(vpf);
    p->bindSampler(rsc, slot, static_cast<Sampler *>(s));
}
Beispiel #29
0
void ocl_main(UArg arg0, UArg arg1)
{
   int    argc = (int)     arg0;
   char **argv = (char **) arg1;
#else
#define RETURN(x) return x
int main(int argc, char *argv[])
{
#endif
   cl_int err     = CL_SUCCESS;
   int    bufsize = sizeof(Golden);
   int    num_errors = 0;
   const int    print_nerrors = 12;

   for (int i=0; i < NumElements; ++i) 
   {
       srcA[i] = i * 1.0; 
       srcB[i] = ((i+7) % 257 )* 1.0; 
       Golden[i]   =   srcA[i] + srcB[i];
   }

   try 
   {
     Context context(CL_DEVICE_TYPE_ACCELERATOR);

     std::vector<Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
      
     int d = 0;
     std::string str;
     devices[d].getInfo(CL_DEVICE_NAME, &str);
     cout << "DEVICE: " << str << endl << endl;

     Buffer bufA   (context, CL_MEM_READ_ONLY,  bufsize);
     Buffer bufB   (context, CL_MEM_READ_ONLY,  bufsize);
     Buffer bufDst (context, CL_MEM_WRITE_ONLY, bufsize);

#ifndef _TI_RTOS
     ifstream t("vadd_wrapper.cl");
     if (!t)
     {
         std::cout << "Could not open Kernel Source file ([file].cl)\n";
         exit(-1);
     }

     std::string kSrc((istreambuf_iterator<char>(t)),
                      istreambuf_iterator<char>());
     Program::Sources    source(1, make_pair(kSrc.c_str(), kSrc.length()));
     Program             program = Program(context, source);
     program.build(devices, "vadd_openmp.obj"); 
#else
     Program::Binaries binary(1, make_pair(vadd_wrapper_dsp_bin,
                                              sizeof(vadd_wrapper_dsp_bin)));
     Program           program = Program(context, devices, binary);
     program.build(devices);
#endif

     Kernel kernel(program, "vadd_wrapper");
     kernel.setArg(0, bufA);
     kernel.setArg(1, bufB);
     kernel.setArg(2, bufDst);
     kernel.setArg(3, NumChunks);
     kernel.setArg(4, ChunkSize);

     Event ev1,ev2,ev3,ev4, ev5,  ev6,ev7,ev8;

     // In Order Command Queue, only one kernel pushed to device at a time
     // OpenMP c code should use: In Order Command Queue + Task
     CommandQueue InO_Q(context, devices[d], CL_QUEUE_PROFILING_ENABLE);

     InO_Q.enqueueWriteBuffer(bufA, CL_FALSE, 0, bufsize, srcA, NULL, &ev1);
     InO_Q.enqueueWriteBuffer(bufB, CL_FALSE, 0, bufsize, srcB, NULL, &ev2);

     std::vector<Event> vec_ev5(1);
     InO_Q.enqueueTask(kernel, NULL, &vec_ev5[0]);

     InO_Q.enqueueReadBuffer(bufDst, CL_TRUE, 0, bufsize, dst, &vec_ev5, &ev6);

     for (int i=0; i < NumElements; ++i)
     {
       if (Golden[i] - dst[i] < -EPISILON || Golden[i] - dst[i] > EPISILON) 
       { 
           if((num_errors += 1) < print_nerrors)
               printf("Error %d: %f <==> %f\n", i, Golden[i], dst[i]);
       }
     }

     ocl_event_times(ev1, "Write   BufA ");
     ocl_event_times(ev2, "Write   BufB ");
     ocl_event_times(vec_ev5[0], "Kernel       ");
     ocl_event_times(ev6, "Read   BufDst");
   }
   catch (Error err) 
   { cerr << "ERROR: " << err.what() << "(" << err.err() << ")" << endl; }

   if (num_errors > 0)
   { 
      cout << "FAIL with " << num_errors << " errors!\n";
      RETURN (-1);
   }
   else cout << "PASS!" << endl; 

   RETURN (0);
}
Beispiel #30
0
//-----------------------------------------------------------------------
bool FFPFog::addFunctionInvocations(ProgramSet* programSet)
{
    if (mFogMode == FOG_NONE)
        return true;

    Program* vsProgram = programSet->getCpuVertexProgram();
    Program* psProgram = programSet->getCpuFragmentProgram();
    Function* vsMain = vsProgram->getEntryPointFunction();
    Function* psMain = psProgram->getEntryPointFunction();
    FunctionInvocation* curFuncInvocation = NULL;   
    int internalCounter;


    // Per pixel fog.
    if (mCalcMode == CM_PER_PIXEL)
    {
        internalCounter = 0;
        curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_PIXELFOG_DEPTH, FFP_VS_FOG, internalCounter++);
        curFuncInvocation->pushOperand(mWorldViewProjMatrix, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mVSInPos, Operand::OPS_IN);  
        curFuncInvocation->pushOperand(mVSOutDepth, Operand::OPS_OUT);  
        vsMain->addAtomInstance(curFuncInvocation);     

        internalCounter = 0;
        switch (mFogMode)
        {
        case FOG_LINEAR:
            curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_PIXELFOG_LINEAR, FFP_PS_FOG, internalCounter++);
            break;
        case FOG_EXP:
            curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_PIXELFOG_EXP, FFP_PS_FOG, internalCounter++);
            break;
        case FOG_EXP2:
            curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_PIXELFOG_EXP2, FFP_PS_FOG, internalCounter++);
            break;
        case FOG_NONE:
        default:
            break;
        }

        curFuncInvocation->pushOperand(mPSInDepth, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mFogParams, Operand::OPS_IN);    
        curFuncInvocation->pushOperand(mFogColour, Operand::OPS_IN);        
        curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT);
        psMain->addAtomInstance(curFuncInvocation); 
        
    }

    // Per vertex fog.
    else
    {
        internalCounter = 0;

        switch (mFogMode)
        {
        case FOG_LINEAR:
            curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_VERTEXFOG_LINEAR, FFP_VS_FOG, internalCounter++);
            break;
        case FOG_EXP:
            curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_VERTEXFOG_EXP, FFP_VS_FOG, internalCounter++);
            break;
        case FOG_EXP2:
            curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_VERTEXFOG_EXP2, FFP_VS_FOG, internalCounter++);
            break;
        case FOG_NONE:
        default:
            break;
        }
            
        curFuncInvocation->pushOperand(mWorldViewProjMatrix, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mVSInPos, Operand::OPS_IN);      
        curFuncInvocation->pushOperand(mFogParams, Operand::OPS_IN);        
        curFuncInvocation->pushOperand(mVSOutFogFactor, Operand::OPS_OUT);
        vsMain->addAtomInstance(curFuncInvocation);     


        internalCounter = 0;

        curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_LERP, FFP_PS_FOG, internalCounter++);
        curFuncInvocation->pushOperand(mFogColour, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSInFogFactor, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT);
        psMain->addAtomInstance(curFuncInvocation); 
    }



    return true;
}