Exemplo n.º 1
0
        private void SetupGrahpicsResources(GraphicsDevice device)
        {
            this.vertexBuffer.Generate();

            this.layout = device.CreateVertexLayout();

            var attribute = new VertexAttribute();

            attribute.Index  = 0;
            attribute.Offset = 0;
            attribute.Stride = Marshal.SizeOf <Vertex>();
            attribute.Format = VertexAttributeFormat.Vector2f;
            attribute.Usage  = VertexAttributeUsage.Position;
            this.layout.SetAttribute(attribute);

            attribute.Index  = 1;
            attribute.Offset = Marshal.SizeOf <Vector2>();
            attribute.Stride = Marshal.SizeOf <Vertex>();
            attribute.Format = VertexAttributeFormat.Vector4f;
            attribute.Usage  = VertexAttributeUsage.Colour;
            this.layout.SetAttribute(attribute);

            var asm      = typeof(GLShapeRenderer).Assembly;
            var vertpath = $"{nameof(GLShapeRenderer)}.vert.glsl";
            var fragpath = $"{nameof(GLShapeRenderer)}.frag.glsl";

            this.program = (GLShader)device.CreateShader(ShaderFormat.GLSL, asm.GetManifestResourceStream(vertpath), asm.GetManifestResourceStream(fragpath));

            this.program.SetVertexData(this.vertexBuffer, this.layout);
        }
Exemplo n.º 2
0
        private void SetupLayout(GraphicsDevice device)
        {
            var layout = device.CreateVertexLayout();

            var attribute = new VertexAttribute();

            attribute.Index  = 0;
            attribute.Offset = 0;
            attribute.Stride = Marshal.SizeOf <Vertex2>();
            attribute.Format = VertexAttributeFormat.Vector2f;
            attribute.Usage  = VertexAttributeUsage.Position;
            layout.SetAttribute(attribute);


            attribute.Index  = 1;
            attribute.Offset = Marshal.SizeOf <Vector2>();
            attribute.Stride = Marshal.SizeOf <Vertex2>();
            attribute.Format = VertexAttributeFormat.Vector2f;
            attribute.Usage  = VertexAttributeUsage.TextureCoordinate;
            layout.SetAttribute(attribute);

            attribute.Index  = 2;
            attribute.Offset = Marshal.SizeOf <Vector2>() * 2;
            attribute.Stride = Marshal.SizeOf <Vertex2>();
            attribute.Format = VertexAttributeFormat.Vector4f;
            attribute.Usage  = VertexAttributeUsage.Colour;
            layout.SetAttribute(attribute);

            this.layout = layout;
        }
Exemplo n.º 3
0
        public VertexArrayBuilder AddVertexAttribute(int location, IEnumerable <byte> data, int size, bool normalize = false, bool interleave = true)
        {
            var attribute = new VertexAttribute(location, data.ToArray(), VertexAttribType.UnsignedByte, size, normalize, interleave);

            staticVertexAttributes.Add(attribute);
            return(this);
        }
Exemplo n.º 4
0
 public void OnAfterDeserialize()
 {
     if (!System.Enum.TryParse <VertexAttribute>(attributeTypeString, out attributeType))
     {
         attributeType = VertexAttribute.Position;
     }
 }
Exemplo n.º 5
0
        private static Type GetOutputType(VertexAttribute attribute)
        {
            switch (attribute)
            {
            case VertexAttribute.Position: return(typeof(Vector3));

            case VertexAttribute.Normal: return(typeof(Vector3));

            case VertexAttribute.Tangent: return(typeof(Vector4));

            case VertexAttribute.Color: return(typeof(Vector4));

            case VertexAttribute.TexCoord0:
            case VertexAttribute.TexCoord1:
            case VertexAttribute.TexCoord2:
            case VertexAttribute.TexCoord3:
            case VertexAttribute.TexCoord4:
            case VertexAttribute.TexCoord5:
            case VertexAttribute.TexCoord6:
            case VertexAttribute.TexCoord7: return(typeof(Vector4));

            case VertexAttribute.BlendWeight: return(typeof(Vector4));

            case VertexAttribute.BlendIndices: return(typeof(Vector4));

            default: throw new InvalidOperationException("Unexpected attribute : " + attribute);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Конструктор
 /// </summary>
 public MorphMeshShader() : base()
 {
     if (firstVertexAttrib == null)
     {
         firstVertexAttrib = new VertexAttribute("inFirstPosition");
         attribs.Add(firstVertexAttrib);
     }
     if (secondVertexAttrib == null)
     {
         secondVertexAttrib = new VertexAttribute("inSecondPosition");
         attribs.Add(secondVertexAttrib);
     }
     if (firstNormalAttrib == null)
     {
         firstNormalAttrib = new VertexAttribute("inFirstNormal");
         attribs.Add(firstNormalAttrib);
     }
     if (secondNormalAttrib == null)
     {
         secondNormalAttrib = new VertexAttribute("inSecondNormal");
         attribs.Add(secondNormalAttrib);
     }
     if (deltaUniform == null)
     {
         deltaUniform = new FloatUniform("delta");
         uniforms.Add(deltaUniform);
     }
 }
Exemplo n.º 7
0
        private static SpriteChannelInfo GetChannelInfo(Sprite sprite, VertexAttribute channel)
        {
            SpriteChannelInfo result;

            SpriteDataAccessExtensions.GetChannelInfo_Injected(sprite, channel, out result);
            return(result);
        }
Exemplo n.º 8
0
        static void ParseValues(ref VertexAttribute buffer, string[] values)
        {
            if (buffer == null)
            {
                buffer             = new VertexAttribute();
                buffer.ElementSize = values.Length - 1;
            }
            else if (buffer.ElementSize != values.Length - 1)
            {
                throw new InvalidOperationException("Invalid vertex specification. Vertex attributes must all have the same size.");
            }

            for (int i = 1; i < values.Length; i++)
            {
                float value;
                if (!float.TryParse(values[i], NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                {
                    throw new InvalidOperationException(string.Format(
                                                            "Invalid vertex specification: {0}.",
                                                            values[i]));
                }

                buffer.Add(value);
            }
        }
Exemplo n.º 9
0
        public void onEnter()
        {
            this.camera = new PerspecitveCamera(MathHelper.PiOver4, Game.shared.width, Game.shared.height);
            this.shader = Game.assets.shader("test");
            VertexAttributes attrs = new VertexAttributes(VertexAttribute.Position(), VertexAttribute.Color());

            this.rawMesh     = new VertexBufferObject(true, 3, 7, attrs);
            this.rawIndicies = new IndexBufferObject(true);

            float[] data = new float[] {
                -0.8f, -0.8f, 0f, 1f, 0f, 0f, 1.0f,
                0.8f, -0.8f, 0f, 0f, 1f, 0f, 1.0f,
                0f, 0.8f, 0f, 0f, 0f, 1f, 1.0f,
                0.8f, 0.8f, 0f, 1f, 0f, 1f, 1.0f
            };

            uint[] indicies = new uint[] {
                0, 1, 2,
                1, 2, 3
            };

            this.rawIndicies.setIndicies(ref indicies);
            this.rawMesh.setVerticies(ref data);

            this.mviewdata = Matrix4.Translation(0f, 0f, 0f);
            Vector3 cameraPosition = new Vector3(5f, 5f, 5f);

            this.camera.translate(ref cameraPosition);

            Vector3 target = new Vector3(0f, 0f, 0f);

            this.camera.lookAt(ref target);
        }
Exemplo n.º 10
0
 private void SetSizedArrayForChannel(VertexAttribute channel, InternalVertexChannelType format, int dim, System.Array values, int valuesArrayLength, int valuesStart, int valuesCount)
 {
     if (canAccess)
     {
         if (valuesStart < 0)
         {
             throw new ArgumentOutOfRangeException(nameof(valuesStart), valuesStart, "Mesh data array start index can't be negative.");
         }
         if (valuesCount < 0)
         {
             throw new ArgumentOutOfRangeException(nameof(valuesCount), valuesCount, "Mesh data array length can't be negative.");
         }
         if (valuesStart >= valuesArrayLength && valuesCount != 0)
         {
             throw new ArgumentOutOfRangeException(nameof(valuesStart), valuesStart, "Mesh data array start is outside of array size.");
         }
         if (valuesStart + valuesCount > valuesArrayLength)
         {
             throw new ArgumentOutOfRangeException(nameof(valuesCount), valuesStart + valuesCount, "Mesh data array start+count is outside of array size.");
         }
         if (values == null)
         {
             valuesStart = 0;
         }
         SetArrayForChannelImpl(channel, format, dim, values, valuesArrayLength, valuesStart, valuesCount);
     }
     else
     {
         PrintErrorCantAccessChannel(channel);
     }
 }
Exemplo n.º 11
0
        private SpriteChannelInfo GetChannelInfo(VertexAttribute channel)
        {
            SpriteChannelInfo result;

            this.GetChannelInfo_Injected(channel, out result);
            return(result);
        }
Exemplo n.º 12
0
        public override void Setup()
        {
            GL.Enable(EnableCap.DepthTest);
            GL.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            var vertexAttributes = new VertexAttribute[] {
                new VertexAttribute("aPosition", 3, VertexAttribPointerType.Float, ColoredTexturedVertex.Size, 0)
            };
            var vbo = VertexBuffer.CreateVertexBuffer();

            vbo.LoadData(CubeVertices());
            _modelVao = VertexArray.CreateVertexArray();
            _modelVao.Bind();

            _modelShader = ShaderProgram.CreateShaderProgram("./Assets/Shaders/vertex.vert", "./Assets/Shaders/fragment.frag", vertexAttributes);
            _modelShader.Use();
            _modelShader.SetVertexAttributes();

            var lamp = Light.CreateLight();

            lamp.Bind();
            var lampShader = ShaderProgram.CreateShaderProgram("./Assets/Shaders/vertex.vert", "./Assets/Shaders/lighting.frag", vertexAttributes);

            lampShader.Use();
            lampShader.SetVertexAttributes();
            lamp.BindBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer, vbo.Id);
            lamp.Position     = new Vector3(1.2f, 1.0f, 2.0f);
            lamp.Shader       = lampShader;
            lamp.VertexBuffer = vbo;
            Lamp = lamp;
        }
        private static void CheckAttributeTypeMatchesAndThrow <T>(VertexAttribute channel)
        {
            var channelTypeMatches = false;

            switch (channel)
            {
            case VertexAttribute.Position:
            case VertexAttribute.Normal:
                channelTypeMatches = typeof(T) == typeof(Vector3); break;

            case VertexAttribute.Tangent:
                channelTypeMatches = typeof(T) == typeof(Vector4); break;

            case VertexAttribute.Color:
                channelTypeMatches = typeof(T) == typeof(Color32); break;

            case VertexAttribute.TexCoord0:
            case VertexAttribute.TexCoord1:
            case VertexAttribute.TexCoord2:
            case VertexAttribute.TexCoord3:
            case VertexAttribute.TexCoord4:
            case VertexAttribute.TexCoord5:
            case VertexAttribute.TexCoord6:
                channelTypeMatches = typeof(T) == typeof(Vector2); break;

            default:
                throw new InvalidOperationException(String.Format("The requested channel '{0}' is unknown.", channel));
            }

            if (!channelTypeMatches)
            {
                throw new InvalidOperationException(String.Format("The requested channel '{0}' does not match the return type {1}.", channel, typeof(T).Name));
            }
        }
Exemplo n.º 14
0
 // Конструктор
 protected SkyboxShader() : base()
 {
     if (vertexAttrib == null)
     {
         vertexAttrib = new VertexAttribute("inPosition");
         attribs.Add(vertexAttrib);
     }
     if (texCoordAttrib == null)
     {
         texCoordAttrib = new VertexAttribute("inTexCoord");
         attribs.Add(texCoordAttrib);
     }
     if (textureUniform == null)
     {
         textureUniform = new TextureUniform("texture");
         uniforms.Add(textureUniform);
     }
     if (diffuseColor == null)
     {
         diffuseColor = new ColorUniform("diffuseColor");
         uniforms.Add(diffuseColor);
     }
     if (textureMatrix == null)
     {
         textureMatrix = new MatrixUniform("textureMatrix");
         uniforms.Add(textureMatrix);
     }
 }
Exemplo n.º 15
0
        public override VertexAttribute[] GetAttributes(int bufferHandle)
        {
            var attributes = new VertexAttribute[2];

            var in_position = new VertexAttribute();
            in_position.VertexBuffer = bufferHandle;
            in_position.Size = 2;
            in_position.PointerType = VertexAttribPointerType.Float;
            in_position.Normalized = false;
            in_position.Stride = Vertex.SizeInBytes;
            in_position.Offset = Vertex.PositionOffset;
            in_position.ShaderHandle = Handle;
            in_position.ShaderAttribName = "in_position";
            attributes[0] = in_position;

            var in_texcoord = new VertexAttribute();
            in_texcoord.VertexBuffer = bufferHandle;
            in_texcoord.Size = 2;
            in_texcoord.PointerType = VertexAttribPointerType.Float;
            in_texcoord.Stride = Vertex.SizeInBytes;
            in_texcoord.Offset = Vertex.TextureOffset;
            in_texcoord.Normalized = false;
            in_texcoord.ShaderHandle = Handle;
            in_texcoord.ShaderAttribName = "in_texcoord";
            attributes[1] = in_texcoord;

            return attributes;
        }
Exemplo n.º 16
0
        static AttributeType GetAttributeType(VertexAttribute attribute)
        {
            switch (attribute)
            {
            case VertexAttribute.Position:
                return(AttributeType.POSITION);

            case VertexAttribute.Normal:
                return(AttributeType.NORMAL);

            case VertexAttribute.Color:
                return(AttributeType.COLOR);

            case VertexAttribute.TexCoord0:
            case VertexAttribute.TexCoord1:
            case VertexAttribute.TexCoord2:
            case VertexAttribute.TexCoord3:
            case VertexAttribute.TexCoord4:
            case VertexAttribute.TexCoord5:
            case VertexAttribute.TexCoord6:
            case VertexAttribute.TexCoord7:
                return(AttributeType.TEX_COORD);

            case VertexAttribute.Tangent:
            case VertexAttribute.BlendWeight:
            case VertexAttribute.BlendIndices:
                return(AttributeType.GENERIC);

            default:
                throw new ArgumentOutOfRangeException(nameof(attribute), attribute, null);
            }
        }
Exemplo n.º 17
0
 public AttributeMapBase(VertexAttribute attribute, VertexAttributeFormat format)
 {
     this.attribute = attribute;
     this.format    = format;
     offset         = 0;
     stream         = 0;
 }
Exemplo n.º 18
0
 public override void SetAttribute(VertexAttribute attribute)
 {
     if (!this.attributes.TryAdd(attribute.Index, attribute))
     {
         this.attributes[attribute.Index] = attribute;
     }
 }
Exemplo n.º 19
0
        private async Task LoadModel(string name, VertexAttribute attributes, bool textured)
        {
            var model = await Resource.LoadModel(name, textured);

            model.Attributes = attributes;
            shape            = model;
        }
Exemplo n.º 20
0
        public VertexArrayBuilder AddVertexAttribute(int location, IEnumerable <double> data, int size, bool interleave = true)
        {
            var bytes     = ToByteArray(data);
            var attribute = new VertexAttribute(location, bytes, VertexAttribType.Double, size, false, interleave);

            staticVertexAttributes.Add(attribute);
            return(this);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Sets whether a given attribute should be normalized. By default attributes are not normalized. A normalized
        /// attribute is mapped between 0 and 1 in the shader. This applies only to integer types.
        /// </summary>
        /// <param name="attribute">Enum of the attribute to set the normalization flag to.</param>
        /// <param name="normalized">True to automatically normalize the given attribute.</param>
        /// <returns>This Builder for chaining calls.</returns>
        public VertexBufferBuilder WithNormalized(VertexAttribute attribute, bool normalized = true)
        {
            ThrowExceptionIfDisposed();

            Native.VertexBufferBuilder.Normalized(NativePtr, (int)attribute, normalized);

            return(this);
        }
Exemplo n.º 22
0
        public VertexArrayBuilder AddVertexAttribute(int location, IEnumerable <uint> data, int size, bool normalize = false, bool interleave = true)
        {
            var bytes     = ToByteArray(data);
            var attribute = new VertexAttribute(location, bytes, VertexAttribType.UnsignedInt, size, normalize, interleave);

            staticVertexAttributes.Add(attribute);
            return(this);
        }
Exemplo n.º 23
0
        /// <summary>
        /// <para>Sets up an attribute for this vertex buffer set.</para>
        /// <para>Using <param name="byteOffset"/> and <param name="byteStride"/>, attributes can be interleaved in the
        /// same buffer.</para>
        /// <para>Warning: <see cref="VertexAttribute.Tangents"/> must be specified as a quaternion and is how normals
        /// are specified.</para>
        /// </summary>
        /// <param name="attribute">The attribute to set up.</param>
        /// <param name="bufferIndex">The index of the buffer containing the data for this attribute. Must  be between
        /// 0 and bufferCount() - 1.</param>
        /// <param name="attributeType">The type of the attribute data (e.g. byte, float3, etc...).</param>
        /// <param name="byteOffset">Offset in *bytes* into the buffer <param name="bufferIndex"/>.</param>
        /// <param name="byteStride">Stride in *bytes* to the next element of this attribute. When set to  zero the
        /// attribute size, as defined by \p attributeType is used.</param>
        /// <returns>This Builder for chaining calls.</returns>
        public VertexBufferBuilder WithAttribute(VertexAttribute attribute, int bufferIndex, ElementType attributeType, int byteOffset = 0, int byteStride = 0)
        {
            ThrowExceptionIfDisposed();

            Native.VertexBufferBuilder.Attribute(NativePtr, (int)attribute, bufferIndex, (uint)attributeType, byteOffset, byteStride);

            return(this);
        }
Exemplo n.º 24
0
        public void SetVertexAttribute(VertexAttribute attribute)
        {
            int index = GetAttributeLocation(attribute.Name);

            // enable and set attribute
            GL.EnableVertexAttribArray(index);
            GL.VertexAttribPointer(index, attribute.Size, attribute.Type, attribute.Normalize, attribute.Stride, attribute.Offset);
        }
Exemplo n.º 25
0
        public static NativeSlice <T> GetVertexAttribute <T>(this Sprite sprite, VertexAttribute channel) where T : struct
        {
            SpriteDataAccessExtensions.CheckAttributeTypeMatchesAndThrow <T>(channel);
            SpriteChannelInfo channelInfo = SpriteDataAccessExtensions.GetChannelInfo(sprite, channel);
            NativeSlice <T>   result      = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <T>(channelInfo.buffer, channelInfo.offset, channelInfo.count, channelInfo.stride);

            NativeSliceUnsafeUtility.SetAtomicSafetyHandle <T>(ref result, sprite.GetSafetyHandle());
            return(result);
        }
Exemplo n.º 26
0
        public int GetOffset(int usage)
        {
            VertexAttribute vertexAttribute = FindByUsage(usage);

            if (vertexAttribute == null)
            {
                return(0);
            }
            return(vertexAttribute.offset / 4);
        }
Exemplo n.º 27
0
 public static PICAAttribute GetPICAAttribute(VertexAttribute vertexAttribute)
 {
     return(new PICAAttribute
     {
         Name = vertexAttribute.AttrName,
         Format = vertexAttribute.Format.ToPICAAttributeFormat(),
         Elements = vertexAttribute.Elements,
         Scale = vertexAttribute.Scale
     });
 }
Exemplo n.º 28
0
        public void onEnter()
        {
            this.shader         = Game.assets.shader("test");
            this.camera         = new PerspecitveCamera();
            this.cameraPosition = new Vector3(0f, 5f, -20f);
            this.camera.translate(ref cameraPosition);

            Vector3 target = new Vector3(0f, 0f, 0f);

            this.camera.lookAt(ref target);

            float[] vertData = new float[] {
                -1f, -1f, -1f, 0.0f, 1.0f, 1.0f, 1.0f,
                1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
                -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
                1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
                -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f
            };

            uint[] indicedata = new uint[] {
                //front
                0, 7, 3,
                0, 4, 7,
                //back
                1, 2, 6,
                6, 5, 1,
                //left
                0, 2, 1,
                0, 3, 2,
                //right
                4, 5, 6,
                6, 7, 4,
                //top
                2, 3, 6,
                6, 3, 7,
                //bottom
                0, 1, 5,
                0, 5, 4
            };

            VertexAttributes attrs = new VertexAttributes(VertexAttribute.Position(), VertexAttribute.Color());

            this.mesh = new Mesh(true, 8, 7, attrs);

            this.mesh.setVerticies(ref vertData);
            this.mesh.setIndicies(ref indicedata);

            this.posVector      = Vector3.Zero;
            this.mviewdata      = Matrix4.CreateTranslation(Vector3.Zero);
            this.rotationMatrix = Matrix4.CreateRotationX(0f);
            this.finalMatrix    = new Matrix4();
        }
Exemplo n.º 29
0
 private void SetSizedArrayForChannel(VertexAttribute channel, InternalVertexChannelType format, int dim, System.Array values, int valuesCount)
 {
     if (canAccess)
     {
         SetArrayForChannelImpl(channel, format, dim, values, valuesCount);
     }
     else
     {
         PrintErrorCantAccessChannel(channel);
     }
 }
Exemplo n.º 30
0
        public VertexFormat(VertexAttribute[] attributes)
        {
            /* Convert the enum type */
            Toolkit.utVertexAttribute[] uta = new Toolkit.utVertexAttribute[attributes.Length];
            for (int i = 0; i < attributes.Length; ++i)
                uta[i] = (Toolkit.utVertexAttribute)attributes[i];

            _handle = Toolkit.utCreateVertexFormat(uta, uta.Length);
            if (_handle == IntPtr.Zero)
                throw new FrameworkException();
        }
Exemplo n.º 31
0
        public List <VertexAttributeDependancies> vertexDependancies = new List <VertexAttributeDependancies>(); // vertex inputs for this shader

        public VertexAttributeDependancies GetVertexDependanciesForAttributeType(VertexAttribute attributeType)
        {
            foreach (VertexAttributeDependancies input in vertexDependancies)
            {
                if (input.attributeType == attributeType)
                {
                    return(input);
                }
            }
            return(null);
        }
Exemplo n.º 32
0
            public override bool Equals(object obj)
            {
                if (!(obj is VertexAttribute))
                {
                    return(false);
                }
                VertexAttribute other = (VertexAttribute)obj;

                return(this.usage == other.usage &&
                       this.numComponents == other.numComponents &&
                       this.alias.Equals(other.alias));
            }
Exemplo n.º 33
0
		public RegisterAsAttribute (VertexAttribute Format, VertexType Type)
		{
			format = Format;

			switch (format) {
			case VertexAttribute.POSITION:
				shaderLocation=0;
				break;
			case VertexAttribute.COLOR:
				shaderLocation=1;
				break;
			case VertexAttribute.UV:
				shaderLocation=2;
				break;
			case VertexAttribute.NORMAL:
				shaderLocation=3;
				break;
			}
			type = Type;
		}
Exemplo n.º 34
0
		public OpenGLDevice(
			PresentationParameters presentationParameters
		) {
			// Create OpenGL context
			glContext = SDL.SDL_GL_CreateContext(
				presentationParameters.DeviceWindowHandle
			);

			// Check for a possible ES context
			int flags;
			int es2Flag = (int) SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_ES;
			SDL.SDL_GL_GetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, out flags);
			useES2 = (flags & es2Flag) == es2Flag;

			// Check for a possible Core context
			int coreFlag = (int) SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE;
			useCoreProfile = (flags & coreFlag) == coreFlag;

			// Init threaded GL crap where applicable
			InitThreadedGL(
				presentationParameters.DeviceWindowHandle
			);

			// Initialize entry points
			LoadGLEntryPoints();

			shaderProfile = MojoShader.MOJOSHADER_glBestProfile(
				GLGetProcAddress,
				IntPtr.Zero,
				null,
				null,
				IntPtr.Zero
			);
			shaderContext = MojoShader.MOJOSHADER_glCreateContext(
				shaderProfile,
				GLGetProcAddress,
				IntPtr.Zero,
				null,
				null,
				IntPtr.Zero
			);
			MojoShader.MOJOSHADER_glMakeContextCurrent(shaderContext);

			// Print GL information
			FNAPlatform.Log("OpenGL Device: " + glGetString(GLenum.GL_RENDERER));
			FNAPlatform.Log("OpenGL Driver: " + glGetString(GLenum.GL_VERSION));
			FNAPlatform.Log("OpenGL Vendor: " + glGetString(GLenum.GL_VENDOR));
			FNAPlatform.Log("MojoShader Profile: " + shaderProfile);

			// Load the extension list, initialize extension-dependent components
			string extensions;
			if (useCoreProfile)
			{
				extensions = string.Empty;
				int numExtensions;
				glGetIntegerv(GLenum.GL_NUM_EXTENSIONS, out numExtensions);
				for (uint i = 0; i < numExtensions; i += 1)
				{
					extensions += glGetStringi(GLenum.GL_EXTENSIONS, i) + " ";
				}
			}
			else
			{
				extensions = glGetString(GLenum.GL_EXTENSIONS);
			}
			SupportsS3tc = (
				extensions.Contains("GL_EXT_texture_compression_s3tc") ||
				extensions.Contains("GL_OES_texture_compression_S3TC") ||
				extensions.Contains("GL_EXT_texture_compression_dxt3") ||
				extensions.Contains("GL_EXT_texture_compression_dxt5")
			);
			SupportsDxt1 = (
				SupportsS3tc ||
				extensions.Contains("GL_EXT_texture_compression_dxt1")
			);

			/* Check the max multisample count, override parameters if necessary */
			int maxSamples = 0;
			if (supportsMultisampling)
			{
				glGetIntegerv(GLenum.GL_MAX_SAMPLES, out maxSamples);
			}
			MaxMultiSampleCount = maxSamples;
			presentationParameters.MultiSampleCount = Math.Min(
				presentationParameters.MultiSampleCount,
				MaxMultiSampleCount
			);

			// Initialize the faux-backbuffer
			int winWidth, winHeight;
			GetWindowDimensions(
				presentationParameters,
				out winWidth,
				out winHeight
			);
			if (	winWidth != presentationParameters.BackBufferWidth ||
				winHeight != presentationParameters.BackBufferHeight ||
				presentationParameters.MultiSampleCount > 0	)
			{
				if (!supportsFauxBackbuffer)
				{
					throw new NoSuitableGraphicsDeviceException(
						"Your hardware does not support the faux-backbuffer!" +
						"\n\nKeep the window/backbuffer resolution the same."
					);
				}
				Backbuffer = new OpenGLBackbuffer(
					this,
					presentationParameters.BackBufferWidth,
					presentationParameters.BackBufferHeight,
					presentationParameters.DepthStencilFormat,
					presentationParameters.MultiSampleCount
				);
			}
			else
			{
				Backbuffer = new NullBackbuffer(
					presentationParameters.BackBufferWidth,
					presentationParameters.BackBufferHeight
				);
			}

			// Initialize texture collection array
			int numSamplers;
			glGetIntegerv(GLenum.GL_MAX_TEXTURE_IMAGE_UNITS, out numSamplers);
			Textures = new OpenGLTexture[numSamplers];
			for (int i = 0; i < numSamplers; i += 1)
			{
				Textures[i] = OpenGLTexture.NullTexture;
			}
			MaxTextureSlots = numSamplers;

			// Initialize vertex attribute state arrays
			int numAttributes;
			glGetIntegerv(GLenum.GL_MAX_VERTEX_ATTRIBS, out numAttributes);
			attributes = new VertexAttribute[numAttributes];
			attributeEnabled = new bool[numAttributes];
			previousAttributeEnabled = new bool[numAttributes];
			attributeDivisor = new int[numAttributes];
			previousAttributeDivisor = new int[numAttributes];
			for (int i = 0; i < numAttributes; i += 1)
			{
				attributes[i] = new VertexAttribute();
				attributeEnabled[i] = false;
				previousAttributeEnabled[i] = false;
				attributeDivisor[i] = 0;
				previousAttributeDivisor[i] = 0;
			}

			// Initialize render target FBO and state arrays
			int numAttachments;
			glGetIntegerv(GLenum.GL_MAX_DRAW_BUFFERS, out numAttachments);
			currentAttachments = new uint[numAttachments];
			currentAttachmentTypes = new GLenum[numAttachments];
			drawBuffersArray = new GLenum[numAttachments];
			for (int i = 0; i < numAttachments; i += 1)
			{
				currentAttachments[i] = 0;
				currentAttachmentTypes[i] = GLenum.GL_TEXTURE_2D;
				drawBuffersArray[i] = GLenum.GL_COLOR_ATTACHMENT0 + i;
			}
			currentDrawBuffers = 0;
			currentRenderbuffer = 0;
			currentDepthStencilFormat = DepthFormat.None;
			glGenFramebuffers(1, out targetFramebuffer);
			glGenFramebuffers(1, out resolveFramebufferRead);
			glGenFramebuffers(1, out resolveFramebufferDraw);

			// Generate and bind a VAO, to shut Core up
			if (useCoreProfile)
			{
				glGenVertexArrays(1, out vao);
				glBindVertexArray(vao);
			}
		}
Exemplo n.º 35
0
        public ModernGLDevice(
			PresentationParameters presentationParameters
		)
        {
            // Create OpenGL context
            glContext = SDL.SDL_GL_CreateContext(
                presentationParameters.DeviceWindowHandle
            );

            // Check for a possible Core context
            int flags;
            int coreFlag = (int) SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE;
            SDL.SDL_GL_GetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, out flags);
            useCoreProfile = (flags & coreFlag) == coreFlag;

            // Init threaded GL crap where applicable
            InitThreadedGL(
                presentationParameters.DeviceWindowHandle
            );

            // Initialize entry points
            LoadGLEntryPoints();

            shaderProfile = MojoShader.MOJOSHADER_glBestProfile(
                GLGetProcAddress,
                IntPtr.Zero,
                null,
                null,
                IntPtr.Zero
            );
            shaderContext = MojoShader.MOJOSHADER_glCreateContext(
                shaderProfile,
                GLGetProcAddress,
                IntPtr.Zero,
                null,
                null,
                IntPtr.Zero
            );
            MojoShader.MOJOSHADER_glMakeContextCurrent(shaderContext);

            // Print GL information
            FNALoggerEXT.LogInfo("IGLDevice: ModernGLDevice");
            FNALoggerEXT.LogInfo("OpenGL Device: " + glGetString(GLenum.GL_RENDERER));
            FNALoggerEXT.LogInfo("OpenGL Driver: " + glGetString(GLenum.GL_VERSION));
            FNALoggerEXT.LogInfo("OpenGL Vendor: " + glGetString(GLenum.GL_VENDOR));
            FNALoggerEXT.LogInfo("MojoShader Profile: " + shaderProfile);

            // Load the extension list, initialize extension-dependent components
            string extensions;
            if (useCoreProfile)
            {
                extensions = string.Empty;
                int numExtensions;
                glGetIntegerv(GLenum.GL_NUM_EXTENSIONS, out numExtensions);
                for (uint i = 0; i < numExtensions; i += 1)
                {
                    extensions += glGetStringi(GLenum.GL_EXTENSIONS, i) + " ";
                }
            }
            else
            {
                extensions = glGetString(GLenum.GL_EXTENSIONS);
            }
            SupportsS3tc = (
                extensions.Contains("GL_EXT_texture_compression_s3tc") ||
                extensions.Contains("GL_OES_texture_compression_S3TC") ||
                extensions.Contains("GL_EXT_texture_compression_dxt3") ||
                extensions.Contains("GL_EXT_texture_compression_dxt5")
            );
            SupportsDxt1 = (
                SupportsS3tc ||
                extensions.Contains("GL_EXT_texture_compression_dxt1")
            );
            SupportsHardwareInstancing = true;

            /* Check the max multisample count, override parameters if necessary */
            int maxSamples = 0;
            glGetIntegerv(GLenum.GL_MAX_SAMPLES, out maxSamples);
            MaxMultiSampleCount = maxSamples;
            presentationParameters.MultiSampleCount = Math.Min(
                presentationParameters.MultiSampleCount,
                MaxMultiSampleCount
            );

            // Initialize the faux-backbuffer
            Rectangle bounds = FNAPlatform.GetWindowBounds(presentationParameters.DeviceWindowHandle);
            if (	bounds.Width != presentationParameters.BackBufferWidth ||
                bounds.Height != presentationParameters.BackBufferHeight ||
                presentationParameters.MultiSampleCount > 0	)
            {
                Backbuffer = new OpenGLBackbuffer(
                    this,
                    presentationParameters.BackBufferWidth,
                    presentationParameters.BackBufferHeight,
                    presentationParameters.DepthStencilFormat,
                    presentationParameters.MultiSampleCount
                );
            }
            else
            {
                Backbuffer = new NullBackbuffer(
                    presentationParameters.BackBufferWidth,
                    presentationParameters.BackBufferHeight
                );
            }

            // Initialize texture collection array
            int numSamplers;
            glGetIntegerv(GLenum.GL_MAX_TEXTURE_IMAGE_UNITS, out numSamplers);
            Textures = new OpenGLTexture[numSamplers];
            Samplers = new uint[numSamplers];
            SamplersU = new TextureAddressMode[numSamplers];
            SamplersV = new TextureAddressMode[numSamplers];
            SamplersW = new TextureAddressMode[numSamplers];
            SamplersFilter = new TextureFilter[numSamplers];
            SamplersAnisotropy = new float[numSamplers];
            SamplersMaxLevel = new int[numSamplers];
            SamplersLODBias = new float[numSamplers];
            SamplersMipped = new bool[numSamplers];
            glCreateSamplers(numSamplers, Samplers);
            for (int i = 0; i < numSamplers; i += 1)
            {
                Textures[i] = OpenGLTexture.NullTexture;
                SamplersU[i] = TextureAddressMode.Wrap;
                SamplersV[i] = TextureAddressMode.Wrap;
                SamplersW[i] = TextureAddressMode.Wrap;
                SamplersFilter[i] = TextureFilter.Linear;
                SamplersAnisotropy[i] = 4.0f;
                SamplersMaxLevel[i] = 0;
                SamplersLODBias[i] = 0.0f;
                SamplersMipped[i] = false;
                glBindSampler(i, Samplers[i]);
            }
            MaxTextureSlots = numSamplers;

            // Initialize vertex attribute state arrays
            int numAttributes;
            glGetIntegerv(GLenum.GL_MAX_VERTEX_ATTRIBS, out numAttributes);
            attributes = new VertexAttribute[numAttributes];
            attributeEnabled = new bool[numAttributes];
            previousAttributeEnabled = new bool[numAttributes];
            attributeDivisor = new int[numAttributes];
            previousAttributeDivisor = new int[numAttributes];
            for (int i = 0; i < numAttributes; i += 1)
            {
                attributes[i] = new VertexAttribute();
                attributeEnabled[i] = false;
                previousAttributeEnabled[i] = false;
                attributeDivisor[i] = 0;
                previousAttributeDivisor[i] = 0;
            }

            // Initialize render target FBO and state arrays
            int numAttachments;
            glGetIntegerv(GLenum.GL_MAX_DRAW_BUFFERS, out numAttachments);
            currentAttachments = new uint[numAttachments];
            currentAttachmentTypes = new GLenum[numAttachments];
            drawBuffersArray = new GLenum[numAttachments];
            for (int i = 0; i < numAttachments; i += 1)
            {
                currentAttachments[i] = 0;
                currentAttachmentTypes[i] = GLenum.GL_TEXTURE_2D;
                drawBuffersArray[i] = GLenum.GL_COLOR_ATTACHMENT0 + i;
            }
            currentDrawBuffers = 0;
            currentRenderbuffer = 0;
            currentDepthStencilFormat = DepthFormat.None;
            glCreateFramebuffers(1, out targetFramebuffer);
            glCreateFramebuffers(1, out resolveFramebufferRead);
            glCreateFramebuffers(1, out resolveFramebufferDraw);

            // Generate and bind a VAO, to shut Core up
            if (useCoreProfile)
            {
                glGenVertexArrays(1, out vao);
                glBindVertexArray(vao);
            }
        }
 public override void AddFields(VertexAttribute a)
 {
     a.normalized = n;
 }
 public override void AddFields(VertexAttribute a)
 {
     a.nComponents = n;
 }