Example #1
0
		/// <summary>
		/// Apply this TransformStateBase.
		/// </summary>
		/// <param name="ctx">
		/// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
		/// </param>
		/// <param name="shaderProgram">
		/// The <see cref="ShaderProgram"/> which has the state set.
		/// </param>
		public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram)
		{
			GraphicsResource.CheckCurrentContext(ctx);

			#region Shadow Map 2D (Dummy)

			// Dummy shadow map: Texture2d
			// Note: necessary to avoid undefined behavior on glo_ShadowMap2D samplers
			string resourceClassId = "OpenGL.Objects.ShadowMap.DummyTexture2d";

			Texture2d dummyShadowMap = (Texture2d)ctx.GetSharedResource(resourceClassId);

			if (dummyShadowMap == null) {
				dummyShadowMap = new Texture2d(1, 1, PixelLayout.Depth16);
				dummyShadowMap.SamplerParams.CompareMode = true;
				dummyShadowMap.SamplerParams.CompareFunc = DepthFunction.Never;
				dummyShadowMap.Create(ctx);

				ctx.SetSharedResource(resourceClassId, dummyShadowMap);
			}

			#endregion

			ctx.Bind(shaderProgram);

			shaderProgram.SetUniform(ctx, "glo_ShadowMap2D_Count", _ShadowMap2D.Count);
			for (int i = 0; i < 4; i++) {
				if (i < _ShadowMap2D.Count) {
					shaderProgram.SetUniform(ctx, "glo_ShadowMap2D_MVP[" + i + "]", _ShadowMap2D[i].ModelViewProjectionBias);
					shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + i + "]", _ShadowMap2D[i].ShadowMap);
				} else
					shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + i + "]", dummyShadowMap);
			}
		}
Example #2
0
            /// <summary>
            /// Actually create resources associated to the type.
            /// </summary>
            /// <param name="instance">
            /// A <see cref="Object"/> that specifies the underlying instance.
            /// </param>
            /// <param name="ctx">
            /// A <see cref="GraphicsContext"/> used for creating the resources.
            /// </param>
            public override void Create(object instance, GraphicsContext ctx)
            {
                Texture2d texture = instance as Texture2d;

                if (texture == null)
                {
                    throw new InvalidOperationException("not implementing TextureRectangle");
                }

                texture.Create(ctx, 16, 16, PixelLayout.RGB24);
            }
Example #3
0
        public void TestCreate()
        {
            Texture2d texture = null;

            // Create(uint, uint, PixelLayout)
            try {
                texture = new Texture2d();
                Assert.IsFalse(texture.Exists(_Context));

                texture.Create(16, 16, PixelLayout.RGB24);
                Assert.IsFalse(texture.Exists(_Context));

                texture.Create(_Context);
                Assert.IsTrue(texture.Exists(_Context));
            } finally {
                if (texture != null)
                {
                    texture.Dispose(_Context);
                }
                texture = null;
            }

            // Create(GraphicsContext, uint, uint, PixelLayout)
            try {
                texture = new Texture2d();
                Assert.IsFalse(texture.Exists(_Context));

                texture.Create(_Context, 16, 32, PixelLayout.RGB24);
                Assert.IsTrue(texture.Exists(_Context));

                Assert.AreEqual(16, texture.Width);
                Assert.AreEqual(32, texture.Height);
                Assert.AreEqual(PixelLayout.RGB24, texture.PixelLayout);
            } finally {
                if (texture != null)
                {
                    texture.Dispose(_Context);
                }
                texture = null;
            }
        }
Example #4
0
        public static void Initialize(ResourceManager resourceManager, int width, int height)
        {
            retrieveRendererInfo();
            setupDebugOutput();

            GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
            SetCapability(EnableCap.Lighting, false);

            if (UseSrgb && HasCapabilities(3, 0, "GL_ARB_framebuffer_object"))
            {
                int defaultFramebufferColorEncoding;
                GL.GetFramebufferAttachmentParameter(FramebufferTarget.Framebuffer, FramebufferAttachment.BackLeft, FramebufferParameterName.FramebufferAttachmentColorEncoding, out defaultFramebufferColorEncoding);
                if (defaultFramebufferColorEncoding == (int)0x8C40)
                {
                    SetCapability(EnableCap.FramebufferSrgb, true);
                    colorCorrected = true;
                }
                else
                {
                    Trace.WriteLine("Warning: The default framebuffer isn't sRgb");
                }
            }

            // glActiveTexture requires opengl 1.3
            maxFpTextureUnits            = HasCapabilities(1, 3) ? GL.GetInteger(GetPName.MaxTextureUnits) : 1;
            maxTextureImageUnits         = GL.GetInteger(GetPName.MaxTextureImageUnits);
            maxVertexTextureImageUnits   = GL.GetInteger(GetPName.MaxVertexTextureImageUnits);
            maxGeometryTextureImageUnits = HasCapabilities(3, 2, "GL_ARB_geometry_shader4") ? GL.GetInteger(GetPName.MaxGeometryTextureImageUnits) : 0;
            maxCombinedTextureImageUnits = GL.GetInteger(GetPName.MaxCombinedTextureImageUnits);
            maxTextureCoords             = GL.GetInteger(GetPName.MaxTextureCoords);

            // glDrawBuffers requires opengl 2.0
            maxDrawBuffers = HasCapabilities(2, 0) ? GL.GetInteger(GetPName.MaxDrawBuffers) : 1;

            Trace.WriteLine($"texture units available: fp:{maxFpTextureUnits} ps:{maxTextureImageUnits} vs:{maxVertexTextureImageUnits} gs:{maxGeometryTextureImageUnits} combined:{maxCombinedTextureImageUnits} coords:{maxTextureCoords}");

            samplerTextureIds     = new int[maxTextureImageUnits];
            samplerTexturingModes = new TexturingModes[maxTextureImageUnits];

            CheckError("initializing openGL context");

            whitePixel  = Texture2d.Create(Color4.White, "whitepixel");
            normalPixel = Texture2d.Create(new Color4(0.5f, 0.5f, 1, 1), "normalpixel", 1, 1, new TextureOptions()
            {
                Srgb = false,
            });
            textGenerator   = new TextGenerator(resourceManager);
            textFontManager = new TextFontManager();

            Viewport = new Rectangle(0, 0, width, height);
        }
Example #5
0
        public void TestCreate2()
        {
            using (Texture2d texture = new Texture2d()) {
                texture.Create(_Context, 16, 16, PixelLayout.RGB24, 1);
                texture.MipmapBaseLevel = 1;

                Assert.AreEqual(16, texture.Width);
                Assert.AreEqual(16, texture.Height);

                Assert.AreEqual(32, texture.BaseSize.x);
                Assert.AreEqual(32, texture.BaseSize.y);
                Assert.AreEqual(1, texture.BaseSize.z);
            }
        }
Example #6
0
		public void TestCreate()
		{
			Texture2d texture = null;

			// Create(uint, uint, PixelLayout)
			try {
				texture = new Texture2d();
				Assert.IsFalse(texture.Exists(_Context));

				texture.Create(16, 16, PixelLayout.RGB24);
				Assert.IsFalse(texture.Exists(_Context));

				texture.Create(_Context);
				Assert.IsTrue(texture.Exists(_Context));
			} finally {
				if (texture != null)
					texture.Dispose(_Context);
				texture = null;
			}

			// Create(GraphicsContext, uint, uint, PixelLayout)
			try {
				texture = new Texture2d();
				Assert.IsFalse(texture.Exists(_Context));

				texture.Create(_Context, 16, 32, PixelLayout.RGB24);
				Assert.IsTrue(texture.Exists(_Context));

				Assert.AreEqual(16, texture.Width);
				Assert.AreEqual(32, texture.Height);
				Assert.AreEqual(PixelLayout.RGB24, texture.PixelLayout);
			} finally {
				if (texture != null)
					texture.Dispose(_Context);
				texture = null;
			}
		}
Example #7
0
        private static Texture2d ParseMaterialTexture(ObjContext objContext, ObjMaterial objMaterial, string[] commandTokens)
        {
            string textureFileName = commandTokens[commandTokens.Length - 1];
            string textureFilePath = Path.Combine(Path.GetDirectoryName(objContext.Path), textureFileName);

            try {
                Image     textureImage = ImageCodec.Instance.Load(textureFilePath);
                Texture2d texture      = new Texture2d();

                texture.Create(textureImage);
                texture.GenerateMipmaps();

                return(texture);
            } catch (Exception exception) {
                throw new InvalidOperationException(String.Format("unable to load texture {0}", textureFileName), exception);
            }
        }
Example #8
0
        private void SetSphereMaterial(SceneObjectGeometry sphere, string material)
        {
            MaterialState sphereMaterial = new MaterialState();

            sphereMaterial.FrontMaterial           = new MaterialState.Material(ColorRGBAF.ColorWhite);
            sphereMaterial.FrontMaterial.Ambient   = ColorRGBAF.ColorWhite * 0.2f;
            sphereMaterial.FrontMaterial.Diffuse   = ColorRGBAF.ColorWhite * 0.8f;
            sphereMaterial.FrontMaterial.Specular  = ColorRGBAF.ColorWhite * 1.0f;
            sphereMaterial.FrontMaterial.Shininess = 32.0f;

            sphere.ObjectState.DefineState(sphereMaterial);

            if (material == null)
            {
                return;
            }

            string basePath = Path.Combine("Data", "PhotosculptTextures");
            string textureFilename, texturePath;

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "diffuse");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialDiffuseTexture  = texture;
                    sphereMaterial.FrontMaterialDiffuseTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "normal");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialNormalTexture  = texture;
                    sphereMaterial.FrontMaterialNormalTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "specular");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialSpecularTexture  = texture;
                    sphereMaterial.FrontMaterialSpecularTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "ambientocclusion");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialAmbientTexture  = texture;
                    sphereMaterial.FrontMaterialAmbientTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "displace");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    // texture.RequestMipmapsCreation();
                    texture.WrapCoordR     = Texture.Wrap.Repeat;
                    texture.WrapCoordS     = Texture.Wrap.Repeat;
                    texture.MinFilter      = Texture.Filter.Nearest;
                    texture.MagFilter      = Texture.Filter.Nearest;
                    texture.MipmapMaxLevel = 0;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialDisplacementTexture = texture;
                    // sphereMaterial.FrontMaterialDisplacementTexCoord = 0;
                    sphereMaterial.FrontMaterialDisplacementFactor = 0.2f;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }
        }
Example #9
0
        private void VisionControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
        {
            // Create GL context abstraction
            _GraphicsContext = new GraphicsContext(e.DeviceContext, e.RenderContext);

            // Create texture
            _FramebufferTexture = new Texture2d(1024, 1024, PixelLayout.RGB24);
            _FramebufferTexture.SamplerParams.MagFilter = TextureMagFilter.Linear;
            _FramebufferTexture.SamplerParams.MinFilter = TextureMinFilter.Linear;
            _FramebufferTexture.Create(_GraphicsContext);

            // Create framebuffer
            _Framebuffer = new Framebuffer();
            _Framebuffer.AttachColor(0, _FramebufferTexture);
            _Framebuffer.Create(_GraphicsContext);

            // Create shader (standard)
            _ProgramStd = _GraphicsContext.CreateProgram("OpenGL.Standard");
            _ProgramStd.Create(_GraphicsContext);

            // Create program (standard + texture)
            _ProgramStdTex = _GraphicsContext.CreateProgram("OpenGL.Standard+Texture");
            _ProgramStdTex.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> quadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            quadBuffer.Create(new Vertex2f[] {
                new Vertex2f(-0.5f, +0.5f),
                new Vertex2f(-0.5f, -0.5f),
                new Vertex2f(+0.5f, +0.5f),
                new Vertex2f(+0.5f, -0.5f),
            });

            _ArraysQuad = new VertexArrays();
            _ArraysQuad.SetArray(quadBuffer, VertexArraySemantic.Position);
            _ArraysQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysQuad.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> postquadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            postquadBuffer.Create(new Vertex2f[] {
                new Vertex2f(0.0f, 1.0f),
                new Vertex2f(0.0f, 0.0f),
                new Vertex2f(1.0f, 1.0f),
                new Vertex2f(1.0f, 0.0f),
            });

            _ArraysPostQuad = new VertexArrays();
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.Position);
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.TexCoord);
            _ArraysPostQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysPostQuad.Create(_GraphicsContext);

            // Create vertex arrays (optical markers)
            _BufferOpticalMarkers = new ArrayBuffer <Vertex2f>(BufferUsage.DynamicDraw);
            _BufferOpticalMarkers.Create(10000 * 2);

            _ArraysOpticalMarkers = new VertexArrays();
            _ArraysOpticalMarkers.SetArray(_BufferOpticalMarkers, VertexArraySemantic.Position);
            _ArraysOpticalMarkers.SetElementArray(PrimitiveType.Lines);
            _ArraysOpticalMarkers.Create(_GraphicsContext);
        }
Example #10
0
        /// <summary>
        /// Apply this TransformStateBase.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
        /// </param>
        /// <param name="shaderProgram">
        /// The <see cref="ShaderProgram"/> which has the state set.
        /// </param>
        public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram)
        {
            GraphicsResource.CheckCurrentContext(ctx);

            if (!ctx.Extensions.UniformBufferObject_ARB)
            {
                if (shaderProgram == null)
                {
                    // Fixed pipeline rendering requires server state
                    throw new NotImplementedException();
                }
                else
                {
                    // Custom implementation
                    ctx.Bind(shaderProgram);

                    if (shaderProgram.IsActiveUniform("glo_LightModel"))
                    {
                        LightModel.ApplyState(ctx, shaderProgram, "glo_LightModel");
                    }

                    for (int i = 0; i < Lights.Count; i++)
                    {
                        string uniformName = "glo_Light[" + i + "]";

                        if (shaderProgram.IsActiveUniform(uniformName) == false)
                        {
                            break;
                        }

                        Lights[i].ApplyState(ctx, shaderProgram, uniformName);
                    }

                    shaderProgram.SetUniform(ctx, "glo_LightsCount", LightsCount);
                }
            }
            else
            {
                base.Apply(ctx, shaderProgram);                         // Uniform block
            }
            // Dummy shadow map: Texture2d
            // Note: necessary to avoid undefined behavior on glo_ShadowMap2D samplers
            string resourceClassId = "OpenGL.Objects.ShadowMap.DummyTexture2d";

            Texture2d dummyShadowMap = (Texture2d)ctx.GetSharedResource(resourceClassId);

            if (dummyShadowMap == null)
            {
                dummyShadowMap = new Texture2d(1, 1, PixelLayout.Depth16);
                dummyShadowMap.SamplerParams.CompareMode = true;
                dummyShadowMap.SamplerParams.CompareFunc = DepthFunction.Never;
                dummyShadowMap.Create(ctx);

                ctx.SetSharedResource(resourceClassId, dummyShadowMap);
            }

            // Dummy shadow map: TextureCube

            // Apply depth maps
            bool[] tex2dSet = new bool[4];

            for (int i = 0; i < tex2dSet.Length; i++)
            {
                if (i >= Lights.Count || Lights[i].ShadowMap2D == null)
                {
                    continue;
                }

                int shadowMapIndex = Lights[i].ShadowMapIndex;

                shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + shadowMapIndex + "]", Lights[i].ShadowMap2D);
                tex2dSet[shadowMapIndex] = true;
            }

            // Avoid undefined behavior
            for (int i = 0; i < tex2dSet.Length; i++)
            {
                if (tex2dSet[i] == false)
                {
                    shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + i + "]", dummyShadowMap);
                }
            }
        }