예제 #1
0
        public virtual void Bitmap(Bitmap bitmap)
        {
            Bind();
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);

            Premultiplied = true;
        }
            /// <summary>
            /// 加载位图生成纹理
            /// </summary>
            /// <param name="gl"></param>
            private void loadTexture(IGL10 gl)
            {
                Bitmap bitmap = null;

                try
                {
                    // 加载位图
                    bitmap = BitmapFactory.DecodeResource(ma.Resources, Resource.Drawable.sand);
                    int[] textures = new int[1];
                    // 指定生成N个纹理(第一个参数指定生成一个纹理)
                    // textures数组将负责存储所有纹理的代号
                    gl.GlGenTextures(1, textures, 0);
                    // 获取textures纹理数组中的第一个纹理
                    texture = textures[0];
                    // 通知OpenGL将texture纹理绑定到GL10.GL_TEXTURE_2D目标中
                    gl.GlBindTexture(GL10.GlTexture2d, texture);
                    // 设置纹理被缩小(距离视点很远时被缩小)时的滤波方式
                    gl.GlTexParameterf(GL10.GlTexture2d, GL10.GlTextureMinFilter, GL10.GlNearest);
                    // 设置纹理被放大(距离视点很近时被方法)时的滤波方式
                    gl.GlTexParameterf(GL10.GlTexture2d, GL10.GlTextureMagFilter, GL10.GlLinear);
                    // 设置在横向、纵向上都是平铺纹理
                    gl.GlTexParameterf(GL10.GlTexture2d, GL10.GlTextureWrapS, GL10.GlRepeat);
                    gl.GlTexParameterf(GL10.GlTexture2d, GL10.GlTextureWrapT, GL10.GlRepeat);
                    // 加载位图生成纹理
                    GLUtils.TexImage2D(GL10.GlTexture2d, 0, bitmap, 0);
                }
                finally
                {
                    // 生成纹理之后,回收位图
                    if (bitmap != null)
                    {
                        bitmap.Recycle();
                    }
                }
            }
        /// <summary>
        /// Create the shader program for label display in the openGL thread.
        /// This method will be called when WorldRenderManager's OnSurfaceCreated.
        /// </summary>
        /// <param name="labelBitmaps">View data indicating the plane type.</param>
        public void Init(List <Bitmap> labelBitmaps)
        {
            ShaderUtil.CheckGlError(TAG, "Init start.");
            if (labelBitmaps.Count == 0)
            {
                Log.Debug(TAG, "No bitmap.");
            }
            CreateProgram();
            int idx = 0;

            GLES20.GlGenTextures(textures.Length, textures, 0);
            foreach (Bitmap labelBitmap in labelBitmaps)
            {
                // for semantic label plane
                GLES20.GlActiveTexture(GLES20.GlTexture0 + idx);
                GLES20.GlBindTexture(GLES20.GlTexture2d, textures[idx]);

                GLES20.GlTexParameteri(
                    GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
                GLES20.GlTexParameteri(
                    GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear);
                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, labelBitmap, 0);
                GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
                GLES20.GlBindTexture(GLES20.GlTexture2d, 0);
                idx++;
                ShaderUtil.CheckGlError(TAG, "Texture loading");
            }
            ShaderUtil.CheckGlError(TAG, "Init end.");
        }
        public void LoadTextures()
        {
            try
            {
                // Generate textures
                GLES20.GlGenTextures(2, MTextures, 0);

                // Load input bitmap
                if (MSourceBitmap != null)
                {
                    MImageWidth  = MSourceBitmap.Width;
                    MImageHeight = MSourceBitmap.Height;
                    MTexRenderer.UpdateTextureSize(MImageWidth, MImageHeight);

                    // Upload to texture
                    GLES20.GlBindTexture(GLES20.GlTexture2d, MTextures[0]);
                    GLUtils.TexImage2D(GLES20.GlTexture2d, 0, MSourceBitmap, 0);

                    // Set texture parameters
                    GlToolbox.InitTexParams();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
예제 #5
0
        public static int loadTexture(Context context, int resourceId)
        {
            if (resourceId == -1)
            {
                return(resourceId);
            }

            System.GC.Collect();

            int[] textureHandle = new int[1];

            GLES20.GlGenTextures(1, textureHandle, 0);

            if (textureHandle[0] != 0)
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.InScaled = false; // No pre-scaling
                Bitmap bitmap = BitmapFactory.DecodeResource(context.Resources, resourceId, options);
                GLES20.GlBindTexture(GLES20.GlTexture2d, textureHandle[0]);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);
                bitmap.Recycle();
            }

            if (textureHandle[0] == 0)
            {
                throw new RuntimeException("Error loading texture.");
            }

            return(textureHandle[0]);
        }
예제 #6
0
        private static TexInfo CreateTexInfoFromBitmap(Bitmap bitmap)
        {
            TexInfo ret = null;

            if (bitmap != null)
            {
                ret = new TexInfo();

                ret.has_alpha        = bitmap.HasAlpha;
                ret.needs_alpha_test = false;                   // ad-hock

                GLES20.GlPixelStorei(GLES20.GlUnpackAlignment, 1);
                int[] tex = new int[1];
                GLES20.GlGenTextures(1, tex, 0);
                ret.tex = tex [0];

                GLES20.GlBindTexture(GLES20.GlTexture2d, ret.tex);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinear);

                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);
                bitmap.Recycle();
            }

            return(ret);
        }
예제 #7
0
        public Texture(Context context, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }
            GLES20.GlGenTextures(1, textureHandle, 0); //init 1 texture storage handle
            if (textureHandle[0] != 0)
            {
                //Android.Graphics cose class Matrix exists at both Android.Graphics and Android.OpenGL and this is only sample of using
                Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options();
                options.InScaled = false; // No pre-scaling
                int id = context.Resources.GetIdentifier(fileName, "drawable", context.PackageName);
                Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeResource(context.Resources, id, options);
                GLES20.GlBindTexture(GLES20.GlTexture2d, textureHandle[0]);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);
                bitmap.Recycle();

                handle = textureHandle[0];
            }
        }
예제 #8
0
파일: Circle.cs 프로젝트: KirinDenis/SeaBan
        public override void initShader()
        {
            base.initShader();


            //make texture ----------------------------------------------------
            //draw texture
            if (LevelCanvas.b != null)
            {
                LevelCanvas.b.Recycle();
            }
            int    width  = steps * textureStep;
            int    height = steps * textureStep;
            Bitmap bitmap = Bitmap.CreateBitmap(width, height, Config.Argb8888);
            Canvas canvas = new Canvas(bitmap);

            Paint paint = new Paint();

            paint.Color = Android.Graphics.Color.Green;
            paint.SetStyle(Paint.Style.Fill);
            canvas.DrawPaint(paint);

            paint.Color     = Android.Graphics.Color.White;
            paint.AntiAlias = true;
            paint.TextSize  = textureStep;
            paint.TextAlign = Paint.Align.Center;


            for (int i = 0; i < steps; i++)
            {
                paint.Color = Android.Graphics.Color.Rgb(i * 0xF, i * 0xF, i * 0xF);
                canvas.DrawText((steps - i).ToString(), textureStep + textureStep / 2, i * textureStep + textureStep - textureStep / 6, paint);
            }
            //load texture

            int[] textureHandle = new int[1];
            GLES20.GlGenTextures(1, textureHandle, 0);

            if (textureHandle[0] != 0)
            {
                GLES20.GlBindTexture(GLES20.GlTexture2d, textureHandle[0]);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);

                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);
                //    bitmap.Recycle();
                LevelCanvas.b = bitmap;
            }

            textureResID = textureHandle[0];
            TextureManager.addTextureHandle(textureResID, textureHandle[0]);
        }
예제 #9
0
        private Texture(String filename)
        {
#if __ANDROID__
            AssetManager assets = GameActivity.Instance.Assets;
            Bitmap       bitmap = null;
            using (Stream stream = assets.Open(filename))
            {
                bitmap = BitmapFactory.DecodeStream(stream);
                Width  = bitmap.Width;
                Height = bitmap.Height;
            }
            GL.GenTextures(1, out _GLID);
            GL.BindTexture(All.Texture2D, _GLID);

            GL.TexParameter(All.Texture2D, All.TextureWrapS, (Int32)All.Repeat);
            GL.TexParameter(All.Texture2D, All.TextureWrapT, (Int32)All.Repeat);
            GL.TexParameter(All.Texture2D, All.TextureMinFilter, (Int32)All.Linear);
            GL.TexParameter(All.Texture2D, All.TextureMagFilter, (Int32)All.Linear);
            GLUtils.TexImage2D((Int32)All.Texture2D, 0, bitmap, 0);
            GL.GenerateMipmap(All.Texture2D);
            GL.BindTexture(All.Texture2D, 0);
            bitmap.Recycle();
#elif __IOS__
            UIImage image    = UIImage.FromFile(filename);
            nint    cgWidth  = image.CGImage.Width;
            nint    cgHeight = image.CGImage.Height;
            Width  = (Int32)cgWidth;
            Height = (Int32)cgHeight;
            CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
            Byte[]       data       = new Byte[Width * Height * 4];
            CGContext    context    = new CGBitmapContext(data, cgWidth, cgHeight, 8, 4 * Width, colorSpace, CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrderDefault);
            colorSpace.Dispose();
            context.ClearRect(new CGRect(0, 0, cgWidth, cgHeight));
            context.DrawImage(new CGRect(0, 0, cgWidth, cgHeight), image.CGImage);

            GL.GenTextures(1, out _GLID);
            GL.BindTexture(TextureTarget.Texture2D, _GLID);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (Int32)All.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (Int32)All.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (Int32)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (Int32)TextureMagFilter.Linear);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, Width, Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, data);
            context.Dispose();
            GL.GenerateMipmap(TextureTarget.Texture2D);
            GL.BindTexture(TextureTarget.Texture2D, 0);
#endif
            LoadedTextures.Add(filename, this);
            _Filename = filename;
        }
        /// <summary>
        /// Initialize the OpenGL ES rendering related to face geometry,
        /// including creating the shader program.
        /// This method is called when FaceRenderManager's OnSurfaceCreated method calling.
        /// </summary>
        /// <param name="context">Context.</param>
        public void Init(Context context)
        {
            ShaderUtil.CheckGlError(TAG, "Init start.");
            int[] texNames = new int[1];
            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(1, texNames, 0);
            mTextureName = texNames[0];

            int[] buffers = new int[BUFFER_OBJECT_NUMBER];
            GLES20.GlGenBuffers(BUFFER_OBJECT_NUMBER, buffers, 0);
            mVerticeId  = buffers[0];
            mTriangleId = buffers[1];

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVerticeId);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mVerticeBufferSize * BYTES_PER_POINT, null, GLES20.GlDynamicDraw);
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, mTriangleId);

            // Each floating-point number occupies 4 bytes.
            GLES20.GlBufferData(GLES20.GlElementArrayBuffer, mTriangleBufferSize * 4, null,
                                GLES20.GlDynamicDraw);
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextureName);

            CreateProgram();

            //Add texture to facegeometry.
            Bitmap       textureBitmap = null;
            AssetManager assets        = context.Assets;

            try
            {
                Stream sr = assets.Open("face_geometry.png");
                textureBitmap = BitmapFactory.DecodeStream(sr);
            }
            catch (Exception e)
            {
                Log.Debug(TAG, " Open bitmap error!");
            }


            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);
            ShaderUtil.CheckGlError(TAG, "Init end.");
        }
예제 #11
0
        protected override int CreateTexture(Bitmap bmp, bool filter)
        {
            var id = new int[1];

            GLES11.GlGenTextures(1, id, 0);
            GLES11.GlBindTexture(GLES11.GlTexture2d, id[0]);
            GLUtils.TexImage2D(GLES11.GlTexture2d, 0, bmp, 0);
            GLES11.GlTexParameterx(GLES11.GlTexture2d, GLES11.GlTextureMinFilter, filter ? GLES11.GlLinear : GLES11.GlNearest);
            GLES11.GlTexParameterx(GLES11.GlTexture2d, GLES11.GlTextureMagFilter, filter ? GLES11.GlLinear : GLES11.GlNearest);
            GLES11.GlTexParameterx(GLES11.GlTexture2d, GLES11.GlTextureWrapS, GLES11.GlClampToEdge);
            GLES11.GlTexParameterx(GLES11.GlTexture2d, GLES11.GlTextureWrapT, GLES11.GlClampToEdge);
            bmp.Recycle();

            return(id[0]);
        }
예제 #12
0
        /// <summary>
        /// Allocates and initializes OpenGL resources needed by the plane renderer.  Must be
        /// called on the OpenGL thread, typically in
        /// <see cref="GLSurfaceView.IRenderer.OnSurfaceCreated(IGL10, Javax.Microedition.Khronos.Egl.EGLConfig)"/>
        /// </summary>
        /// <param name="context">Needed to access shader source and texture PNG.</param>
        /// <param name="gridDistanceTextureName">Name of the PNG file containing the grid texture.</param>
        public void CreateOnGlThread(Context context, String gridDistanceTextureName)
        {
            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.plane_vertex);
            int passthroughShader = ShaderUtil.LoadGLShader(TAG, context,
                                                            GLES20.GlFragmentShader, Resource.Raw.plane_fragment);

            mPlaneProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mPlaneProgram, vertexShader);
            GLES20.GlAttachShader(mPlaneProgram, passthroughShader);
            GLES20.GlLinkProgram(mPlaneProgram);
            GLES20.GlUseProgram(mPlaneProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            // Read the texture.
            var textureBitmap = Android.Graphics.BitmapFactory.DecodeStream(
                context.Assets.Open(gridDistanceTextureName));

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(mTextures.Length, mTextures, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]);

            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);

            ShaderUtil.CheckGLError(TAG, "Texture loading");

            mPlaneXZPositionAlphaAttribute = GLES20.GlGetAttribLocation(mPlaneProgram,
                                                                        "a_XZPositionAlpha");

            mPlaneModelUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_Model");
            mPlaneModelViewProjectionUniform =
                GLES20.GlGetUniformLocation(mPlaneProgram, "u_ModelViewProjection");
            mTextureUniform       = GLES20.GlGetUniformLocation(mPlaneProgram, "u_Texture");
            mLineColorUniform     = GLES20.GlGetUniformLocation(mPlaneProgram, "u_lineColor");
            mDotColorUniform      = GLES20.GlGetUniformLocation(mPlaneProgram, "u_dotColor");
            mGridControlUniform   = GLES20.GlGetUniformLocation(mPlaneProgram, "u_gridControl");
            mPlaneUvMatrixUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix");

            ShaderUtil.CheckGLError(TAG, "Program parameters");
        }
예제 #13
0
        public Texture(Bitmap bitmap)
        {
            bitmap = ReverseBitmap(bitmap);
            Width  = bitmap.Width;
            Height = bitmap.Height;
            GL.GenTextures(1, out int code);
            TextureCode = code;
            Bind();

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);

            GLUtils.TexImage2D((int)TextureTarget.Texture2D, 0, bitmap, 0);
            GL.GenerateMipmap(TextureTarget.Texture2D);
        }
예제 #14
0
파일: Assets.cs 프로젝트: tipfom/timetitan
        public static Texture2D GetTexture(InterpolationMode interpolation, params string[] path)
        {
            int pathhash = path.GetHashCode( );

            if (!textureCache.ContainsKey(pathhash) || textureCache[pathhash].Disposed)
            {
                int width, height, id = GL.GenTexture( );
                GL.BindTexture(TextureTarget.Texture2D, id);
#if __ANDROID__
                using (BitmapFactory.Options options = new BitmapFactory.Options( )
                {
                    InScaled = false
                })
                    using (Stream stream = GetStream(path))
                        using (Bitmap bitmap = BitmapFactory.DecodeStream(stream, null, options)) {
                            GLUtils.TexImage2D((int)TextureTarget.Texture2D, 0, bitmap, 0);
                            width  = bitmap.Width;
                            height = bitmap.Height;
                        }
#endif

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)interpolation);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)interpolation);

                if (!textureCache.ContainsKey(pathhash))
                {
                    textureCache.Add(pathhash, new Texture2D(id, new Size(width, height), path[path.Length - 1]));
                }
                else
                {
                    textureCache[pathhash] = new Texture2D(id, new Size(width, height), path[path.Length - 1]);
                }
#if DEBUG
                if (id == 0 || Debug.CheckGL(typeof(Assets)))
                {
                    Debug.Print(typeof(Assets), "failed loading image " + path[path.Length - 1]);
                }
                else
                {
                    Debug.Print(typeof(Assets), "loaded image " + path[path.Length - 1]);
                }
#endif
            }
            return(textureCache[pathhash]);
        }
        private void SetupImage()
        {
            // Create our UV coordinates.
            uvs = new float[] {
                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 1.0f,
                1.0f, 0.0f
            };

            // The texture buffer
            ByteBuffer byteBuffer = ByteBuffer.AllocateDirect(uvs.Length * 4);

            byteBuffer.Order(ByteOrder.NativeOrder());
            uvBuffer = byteBuffer.AsFloatBuffer();
            uvBuffer.Put(uvs);
            uvBuffer.Position(0);

            // Generate Textures, if more needed, alter these numbers.
            int[] textureIds = new int[1];
            GLES20.GlGenTextures(1, textureIds, 0);

            // Retrieve our image from resources.
            Bitmap bitmap = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.plant07);

            // Bind texture to texturename
            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, textureIds[0]);

            // Set filtering
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear);

            // Set wrapping mode
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);

            // Load the bitmap into the bound texture.
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);

            // We are done using the bitmap so we should recycle it.
            bitmap.Recycle();
            bitmap.Dispose();
        }
예제 #16
0
        void LoadTextures()
        {
            // Generate textures
            GLES20.GlGenTextures(2, _textures, 0);

            // Load input bitmap
            var bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Lenna);

            _imageWidth  = bitmap.Width;
            _imageHeight = bitmap.Height;
            Renderer.UpdateTextureSize(_imageWidth, _imageHeight);

            // Upload to texture
            GLES20.GlBindTexture(GLES20.GlTexture2d, _textures [0]);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);

            // Set texture parameters
            GLToolbox.InitTexParams();
        }
예제 #17
0
        public int GetTexture(string path, InterpolationMode interpolation, out int width, out int height)
        {
            int id = GL.GenTexture();

            GL.BindTexture(TextureTarget.Texture2D, id);
            using (BitmapFactory.Options options = new BitmapFactory.Options()
            {
                InScaled = false
            })
                using (Stream stream = GetStream(path))
                    using (Bitmap bitmap = BitmapFactory.DecodeStream(stream, null, options)) {
                        GLUtils.TexImage2D((int)TextureTarget.Texture2D, 0, bitmap, 0);
                        width  = bitmap.Width;
                        height = bitmap.Height;
                    }

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)interpolation);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)interpolation);

            return(id);
        }
예제 #18
0
        public static int LoadGlTexture(Resources res, int resId)
        {
            var texture = new int[1];

            GLES20.GlGenTextures(1, texture, 0);
            if (texture [0] == 0)
            {
                throw new InvalidOperationException("Can't create texture");
            }
            var options = new Android.Graphics.BitmapFactory.Options {
                InScaled = false
            };
            var bmp = Android.Graphics.BitmapFactory.DecodeResource(res, resId, options);

            GLES20.GlBindTexture(GLES20.GlTexture2d, texture [0]);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlNearest);
            GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlNearest);

            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bmp, 0);
            bmp.Recycle();

            return(texture [0]);
        }
예제 #19
0
        private void HandleSetupImageTexture(uint texName, out Size size)
        {
            // create bitmap
            Bitmap bitmap;

            if (!bitmapFile.Equals(global::Android.Net.Uri.Empty))
            {
                var f = new Java.IO.File(bitmapFile.Path);
                bitmap = BitmapFactory.DecodeFile(f.Path);
            }
            else
            {
                bitmap = BitmapFactory.DecodeResource(context.Resources, bitmapResource);
            }

            // set context image texture with bitmap
            GLHelper.GetError();
            GL.BindTexture(TextureTarget.Texture2D, ccContext.ImageTexName);
            GLHelper.GetError();
            GLUtils.TexImage2D(GLES30.GlTexture2d, 0, GLES30.GlRgba, bitmap, 0);
            GLHelper.GetError();
            GL.BindTexture(TextureTarget.Texture2D, 0);
            GLHelper.GetError();

            // Set size
            size = new Size(bitmap.Width, bitmap.Height);

            float radius = Math.Min(size.Width, size.Height) * 0.5f * 0.8f;

            ccContext.CountLayerContext.SetROI(new Vector2(size.Width * 0.5f, size.Height * 0.5f), radius);

            // Trigger center view
            ccContext.CenterView(viewSize);

            // recycle bitmap
            bitmap.Recycle();
        }
        private void InitGlTextureData(Context context)
        {
            ShaderUtil.CheckGlError(TAG, "Init gl texture data start.");
            Bitmap       textureBitmap = null;
            AssetManager assets        = context.Assets;

            try
            {
                var sr = assets.Open("AR_logo.png");
                textureBitmap = BitmapFactory.DecodeStream(sr);
            }
            catch (Exception e)
            {
                Log.Debug(TAG, " Open Bitmap Error! ");
                return;
            }

            ShaderUtil.CheckGlError(TAG, "bitmap error.");
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);
            textureBitmap.Recycle();
            ShaderUtil.CheckGlError(TAG, "Init gl texture data end.");
        }
예제 #21
0
        public void OnDrawFrame(IGL10 gl)
        {
            // First allocate texture if there is not one yet.
            if (DRAW_TEXTURE && mTextureIds == null)
            {
                // Generate texture.
                mTextureIds = new int[2];
                gl.GlGenTextures(2, mTextureIds, 0);
                foreach (int textureId in mTextureIds)
                {
                    // Set texture attributes.
                    gl.GlBindTexture(GL10.GlTexture2d, textureId);
                    gl.GlTexParameterf(GL10.GlTexture2d,
                                       GL10.GlTextureMinFilter, GL10.GlNearest);
                    gl.GlTexParameterf(GL10.GlTexture2d,
                                       GL10.GlTextureMagFilter, GL10.GlNearest);
                    gl.GlTexParameterf(GL10.GlTexture2d, GL10.GlTextureWrapS,
                                       GL10.GlClampToEdge);
                    gl.GlTexParameterf(GL10.GlTexture2d, GL10.GlTextureWrapT,
                                       GL10.GlClampToEdge);
                }
            }

            if (DRAW_TEXTURE && mTexturePage.TexturesChanged)
            {
                gl.GlBindTexture(GL10.GlTexture2d, mTextureIds[0]);
                Bitmap texture = mTexturePage.GetTexture(mTextureRectFront,
                                                         CurlPage.SIDE_FRONT);
                GLUtils.TexImage2D(GL10.GlTexture2d, 0, texture, 0);
                texture.Recycle();

                mTextureBack = mTexturePage.HasBackTexture;
                if (mTextureBack)
                {
                    gl.GlBindTexture(GL10.GlTexture2d, mTextureIds[1]);
                    texture = mTexturePage.GetTexture(mTextureRectBack,
                                                      CurlPage.SIDE_BACK);
                    GLUtils.TexImage2D(GL10.GlTexture2d, 0, texture, 0);
                    texture.Recycle();
                }
                else
                {
                    mTextureRectBack.Set(mTextureRectFront);
                }

                mTexturePage.Recycle();
                Reset();
            }

            // Some 'global' settings.
            gl.GlEnableClientState(GL10.GlVertexArray);

            // TODO: Drop shadow drawing is done temporarily here to hide some
            // problems with its calculation.
            if (DRAW_SHADOW)
            {
                gl.GlDisable(GL10.GlTexture2d);
                gl.GlEnable(GL10.GlBlend);
                gl.GlBlendFunc(GL10.GlSrcAlpha, GL10.GlOneMinusSrcAlpha);
                gl.GlEnableClientState(GL10.GlColorArray);
                gl.GlColorPointer(4, GL10.GlFloat, 0, mBufShadowColors);
                gl.GlVertexPointer(3, GL10.GlFloat, 0, mBufShadowVertices);
                gl.GlDrawArrays(GL10.GlTriangleStrip, 0, mDropShadowCount);
                gl.GlDisableClientState(GL10.GlColorArray);
                gl.GlDisable(GL10.GlBlend);
            }

            if (DRAW_TEXTURE)
            {
                gl.GlEnableClientState(GL10.GlTextureCoordArray);
                gl.GlTexCoordPointer(2, GL10.GlFloat, 0, mBufTexCoords);
            }
            gl.GlVertexPointer(3, GL10.GlFloat, 0, mBufVertices);
            // Enable color array.
            gl.GlEnableClientState(GL10.GlColorArray);
            gl.GlColorPointer(4, GL10.GlFloat, 0, mBufColors);

            // Draw front facing blank vertices.
            gl.GlDisable(GL10.GlTexture2d);
            gl.GlDrawArrays(GL10.GlTriangleStrip, 0, mVerticesCountFront);

            // Draw front facing texture.
            if (DRAW_TEXTURE)
            {
                gl.GlEnable(GL10.GlBlend);
                gl.GlEnable(GL10.GlTexture2d);

                if (!mFlipTexture || !mTextureBack)
                {
                    gl.GlBindTexture(GL10.GlTexture2d, mTextureIds[0]);
                }
                else
                {
                    gl.GlBindTexture(GL10.GlTexture2d, mTextureIds[1]);
                }

                gl.GlBlendFunc(GL10.GlSrcAlpha, GL10.GlOneMinusSrcAlpha);
                gl.GlDrawArrays(GL10.GlTriangleStrip, 0, mVerticesCountFront);

                gl.GlDisable(GL10.GlBlend);
                gl.GlDisable(GL10.GlTexture2d);
            }

            int backStartIdx = Math.Max(0, mVerticesCountFront - 2);
            int backCount    = mVerticesCountFront + mVerticesCountBack - backStartIdx;

            // Draw back facing blank vertices.
            gl.GlDrawArrays(GL10.GlTriangleStrip, backStartIdx, backCount);

            // Draw back facing texture.
            if (DRAW_TEXTURE)
            {
                gl.GlEnable(GL10.GlBlend);
                gl.GlEnable(GL10.GlTexture2d);

                if (mFlipTexture || !mTextureBack)
                {
                    gl.GlBindTexture(GL10.GlTexture2d, mTextureIds[0]);
                }
                else
                {
                    gl.GlBindTexture(GL10.GlTexture2d, mTextureIds[1]);
                }

                gl.GlBlendFunc(GL10.GlSrcAlpha, GL10.GlOneMinusSrcAlpha);
                gl.GlDrawArrays(GL10.GlTriangleStrip, backStartIdx, backCount);

                gl.GlDisable(GL10.GlBlend);
                gl.GlDisable(GL10.GlTexture2d);
            }

            // Disable textures and color array.
            gl.GlDisableClientState(GL10.GlTextureCoordArray);
            gl.GlDisableClientState(GL10.GlColorArray);

            if (DRAW_POLYGON_OUTLINES)
            {
                gl.GlEnable(GL10.GlBlend);
                gl.GlBlendFunc(GL10.GlSrcAlpha, GL10.GlOneMinusSrcAlpha);
                gl.GlLineWidth(1.0f);
                gl.GlColor4f(0.5f, 0.5f, 1.0f, 1.0f);
                gl.GlVertexPointer(3, GL10.GlFloat, 0, mBufVertices);
                gl.GlDrawArrays(GL10.GlLineStrip, 0, mVerticesCountFront);
                gl.GlDisable(GL10.GlBlend);
            }

            if (DRAW_CURL_POSITION)
            {
                gl.GlEnable(GL10.GlBlend);
                gl.GlBlendFunc(GL10.GlSrcAlpha, GL10.GlOneMinusSrcAlpha);
                gl.GlLineWidth(1.0f);
                gl.GlColor4f(1.0f, 0.5f, 0.5f, 1.0f);
                gl.GlVertexPointer(2, GL10.GlFloat, 0, mBufCurlPositionLines);
                gl.GlDrawArrays(GL10.GlLines, 0, mCurlPositionLinesCount * 2);
                gl.GlDisable(GL10.GlBlend);
            }

            if (DRAW_SHADOW)
            {
                gl.GlEnable(GL10.GlBlend);
                gl.GlBlendFunc(GL10.GlSrcAlpha, GL10.GlOneMinusSrcAlpha);
                gl.GlEnableClientState(GL10.GlColorArray);
                gl.GlColorPointer(4, GL10.GlFloat, 0, mBufShadowColors);
                gl.GlVertexPointer(3, GL10.GlFloat, 0, mBufShadowVertices);
                gl.GlDrawArrays(GL10.GlTriangleStrip, mDropShadowCount,
                                mSelfShadowCount);
                gl.GlDisableClientState(GL10.GlColorArray);
                gl.GlDisable(GL10.GlBlend);
            }

            gl.GlDisableClientState(GL10.GlVertexArray);
        }
예제 #22
0
        /**
         * Creates and initializes OpenGL resources needed for rendering the model.
         *
         * @param context Context for loading the shader and below-named model and texture assets.
         * @param objAssetName  Name of the OBJ file containing the model geometry.
         * @param diffuseTextureAssetName  Name of the PNG file containing the diffuse texture map.
         */
        public void CreateOnGlThread(Context context, string objAssetName, string diffuseTextureAssetName)
        {
            // Read the texture.
            var textureBitmap = BitmapFactory.DecodeStream(context.Assets.Open(diffuseTextureAssetName));

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(mTextures.Length, mTextures, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]);

            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);

            textureBitmap.Recycle();

            ShaderUtil.CheckGLError(TAG, "Texture loading");

            // Read the obj file.
            var objInputStream = context.Assets.Open(objAssetName);
            var obj            = ObjReader.Read(objInputStream);

            // Prepare the Obj so that its structure is suitable for
            // rendering with OpenGL:
            // 1. Triangulate it
            // 2. Make sure that texture coordinates are not ambiguous
            // 3. Make sure that normals are not ambiguous
            // 4. Convert it to single-indexed data
            obj = ObjUtils.ConvertToRenderable(obj);

            // OpenGL does not use Java arrays. ByteBuffers are used instead to provide data in a format
            // that OpenGL understands.

            // Obtain the data from the OBJ, as direct buffers:
            IntBuffer   wideIndices = ObjData.GetFaceVertexIndices(obj, 3);
            FloatBuffer vertices    = ObjData.GetVertices(obj);
            FloatBuffer texCoords   = ObjData.GetTexCoords(obj, 2);
            FloatBuffer normals     = ObjData.GetNormals(obj);

            // Convert int indices to shorts for GL ES 2.0 compatibility
            ShortBuffer indices = ByteBuffer.AllocateDirect(2 * wideIndices.Limit())
                                  .Order(ByteOrder.NativeOrder()).AsShortBuffer();

            while (wideIndices.HasRemaining)
            {
                indices.Put((short)wideIndices.Get());
            }
            indices.Rewind();

            var buffers = new int[2];

            GLES20.GlGenBuffers(2, buffers, 0);
            mVertexBufferId = buffers[0];
            mIndexBufferId  = buffers[1];

            // Load vertex buffer
            mVerticesBaseAddress  = 0;
            mTexCoordsBaseAddress = mVerticesBaseAddress + 4 * vertices.Limit();
            mNormalsBaseAddress   = mTexCoordsBaseAddress + 4 * texCoords.Limit();
            int totalBytes = mNormalsBaseAddress + 4 * normals.Limit();

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVertexBufferId);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, totalBytes, null, GLES20.GlStaticDraw);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mVerticesBaseAddress, 4 * vertices.Limit(), vertices);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mTexCoordsBaseAddress, 4 * texCoords.Limit(), texCoords);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mNormalsBaseAddress, 4 * normals.Limit(), normals);
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            // Load index buffer
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, mIndexBufferId);
            mIndexCount = indices.Limit();
            GLES20.GlBufferData(
                GLES20.GlElementArrayBuffer, 2 * mIndexCount, indices, GLES20.GlStaticDraw);
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, 0);

            ShaderUtil.CheckGLError(TAG, "OBJ buffer load");

            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.object_vertex);
            int fragmentShader = ShaderUtil.LoadGLShader(TAG, context,
                                                         GLES20.GlFragmentShader, Resource.Raw.object_fragment);

            mProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mProgram, vertexShader);
            GLES20.GlAttachShader(mProgram, fragmentShader);
            GLES20.GlLinkProgram(mProgram);
            GLES20.GlUseProgram(mProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            mModelViewUniform           = GLES20.GlGetUniformLocation(mProgram, "u_ModelView");
            mModelViewProjectionUniform =
                GLES20.GlGetUniformLocation(mProgram, "u_ModelViewProjection");

            mPositionAttribute = GLES20.GlGetAttribLocation(mProgram, "a_Position");
            mNormalAttribute   = GLES20.GlGetAttribLocation(mProgram, "a_Normal");
            mTexCoordAttribute = GLES20.GlGetAttribLocation(mProgram, "a_TexCoord");

            mTextureUniform = GLES20.GlGetUniformLocation(mProgram, "u_Texture");

            mLightingParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_LightingParameters");
            mMaterialParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_MaterialParameters");

            ShaderUtil.CheckGLError(TAG, "Program parameters");

            Android.Opengl.Matrix.SetIdentityM(mModelMatrix, 0);
        }
예제 #23
0
        public void OnSurfaceCreated(IGL10 gl, Javax.Microedition.Khronos.Egl.EGLConfig config)
        {
            const float coord = 1.0f;

            // Cube coords
            // X, Y, Z = 1 vertex * 3 = 1 face * 12 = 1 cube
            float[] triangleVerticesData =
            {
                -coord, -coord, -coord,
                -coord, -coord, coord,
                -coord, coord,  coord,

                coord,  coord,  -coord,
                -coord, -coord, -coord,
                -coord, coord,  -coord,

                coord,  -coord, coord,
                -coord, -coord, -coord,
                coord,  -coord, -coord,

                coord,  coord,  -coord,
                coord,  -coord, -coord,
                -coord, -coord, -coord,

                -coord, -coord, -coord,
                -coord, coord,  coord,
                -coord, coord,  -coord,

                coord,  -coord, coord,
                -coord, -coord, coord,
                -coord, -coord, -coord,

                -coord, coord,  coord,
                -coord, -coord, coord,
                coord,  -coord, coord,

                coord,  coord,  coord,
                coord,  -coord, -coord,
                coord,  coord,  -coord,

                coord,  -coord, -coord,
                coord,  coord,  coord,
                coord,  -coord, coord,

                coord,  coord,  coord,
                coord,  coord,  -coord,
                -coord, coord,  -coord,

                coord,  coord,  coord,
                -coord, coord,  -coord,
                -coord, coord,  coord,

                coord,  coord,  coord,
                -coord, coord,  coord,
                coord,  -coord, coord
            };

            FloatBuffer mTriangleVertices = ByteBuffer.AllocateDirect(triangleVerticesData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleVertices.Put(triangleVerticesData).Flip();

            // Cube colors
            // R, G, B, A
            float[] triangleColorsData =
            {
                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f
            };

            FloatBuffer mTriangleColors = ByteBuffer.AllocateDirect(triangleColorsData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleColors.Put(triangleColorsData).Flip();

            //Cube texture UV Map
            float[] triangleTextureUVMapData =
            {
                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f,

                0.0f, 0.0f,
                0.0f, 1.0f,
                1.0f, 0.0f
            };

            FloatBuffer mTriangleTextureUVMap = ByteBuffer.AllocateDirect(triangleTextureUVMapData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleTextureUVMap.Put(triangleTextureUVMapData).Flip();

            //triagles normals
            //This normal array is not right, it is spacialy DO FOR demonstrate how normals work with faces when light is calculated at shader program
            float[] triangleNormalData =
            {
                // Front face
                0.0f,   0.0f,  1.0f,
                0.0f,   0.0f,  1.0f,
                0.0f,   0.0f,  1.0f,
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,

                // Right face
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,
                1.0f,   0.0f,  0.0f,

                // Back face
                0.0f,   0.0f, -1.0f,
                0.0f,   0.0f, -1.0f,
                0.0f,   0.0f, -1.0f,
                0.0f,   0.0f, -1.0f,
                0.0f,   0.0f, -1.0f,
                0.0f,   0.0f, -1.0f,

                // Left face
                -1.0f,  0.0f,  0.0f,
                -1.0f,  0.0f,  0.0f,
                -1.0f,  0.0f,  0.0f,
                -1.0f,  0.0f,  0.0f,
                -1.0f,  0.0f,  0.0f,
                -1.0f,  0.0f,  0.0f,

                // Top face
                0.0f,   1.0f,  0.0f,
                0.0f,   1.0f,  0.0f,
                0.0f,   1.0f,  0.0f,
                0.0f,   1.0f,  0.0f,
                0.0f,   1.0f,  0.0f,
                0.0f,   1.0f,  0.0f,

                // Bottom face
                0.0f,  -1.0f,  0.0f,
                0.0f,  -1.0f,  0.0f,
                0.0f,  -1.0f,  0.0f,
                0.0f,  -1.0f,  0.0f,
                0.0f,  -1.0f,  0.0f,
                0.0f,  -1.0f, 0.0f
            };

            FloatBuffer mTriangleNormal = ByteBuffer.AllocateDirect(triangleNormalData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleNormal.Put(triangleNormalData).Flip();

            //Data buffers to VBO
            GLES20.GlGenBuffers(4, VBOBuffers, 0); //2 buffers for vertices, texture and colors

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[0]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleVertices.Capacity() * mBytesPerFloat, mTriangleVertices, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[1]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleColors.Capacity() * mBytesPerFloat, mTriangleColors, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[2]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleTextureUVMap.Capacity() * mBytesPerFloat, mTriangleTextureUVMap, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[3]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleNormal.Capacity() * mBytesPerFloat, mTriangleNormal, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            //Load and setup texture

            GLES20.GlGenTextures(1, textureHandle, 0); //init 1 texture storage handle
            if (textureHandle[0] != 0)
            {
                //Android.Graphics cose class Matrix exists at both Android.Graphics and Android.OpenGL and this is only sample of using
                Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options();
                options.InScaled = false; // No pre-scaling
                Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.texture1, options);
                GLES20.GlBindTexture(GLES20.GlTexture2d, textureHandle[0]);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);
                bitmap.Recycle();
            }

            //Ask android to run RAM garbage cleaner
            System.GC.Collect();

            //Setup OpenGL ES
            GLES20.GlClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            // GLES20.GlEnable(GLES20.GlDepthTest); //uncoment if needs enabled dpeth test
            GLES20.GlEnable(2884); // GlCullFace == 2884 see OpenGL documentation to this constant value
            GLES20.GlCullFace(GLES20.GlBack);


            // Position the eye behind the origin.
            float eyeX = 0.0f;
            float eyeY = 0.0f;
            float eyeZ = 4.5f;

            // We are looking toward the distance
            float lookX = 0.0f;
            float lookY = 0.0f;
            float lookZ = -5.0f;

            // Set our up vector. This is where our head would be pointing were we holding the camera.
            float upX = 0.0f;
            float upY = coord;
            float upZ = 0.0f;

            // Set the view matrix. This matrix can be said to represent the camera position.
            // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and
            // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.
            Matrix.SetLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

            //all "attribute" variables is "triagles" VBO (arrays) items representation
            //a_Possition[0] <=> a_Color[0] <=> a_TextureCoord[0] <=> a_Normal[0]
            //a_Possition[1] <=> a_Color[1] <=> a_TextureCoord[1] <=> a_Normal[1]
            //...
            //a_Possition[n] <=> a_Color[n] <=> a_TextureCoord[n] <=> a_Normal[n] -- where "n" is object buffers length
            //-> HOW MANY faces in your object (model) in VBO -> how many times the vertex shader will be called by OpenGL
            string vertexShader =
                "uniform mat4 u_MVPMatrix;      \n"         // A constant representing the combined model/view/projection matrix.
                + "uniform vec3 u_LightPos;       \n"       // A constant representing the light source position
                + "attribute vec4 a_Position;     \n"       // Per-vertex position information we will pass in. (it means vec4[x,y,z,w] but we put only x,y,z at this sample
                + "attribute vec4 a_Color;        \n"       // Per-vertex color information we will pass in.
                + "varying vec4 v_Color;          \n"       // This will be passed into the fragment shader.
                + "attribute vec2 a_TextureCoord; \n"       // Per-vertex texture UVMap information we will pass in.
                + "varying vec2 v_TextureCoord;   \n"       // This will be passed into the fragment shader.
                + "attribute vec3 a_Normal;       \n"       // Per-vertex normals information we will pass in.
                + "void main()                    \n"       // The entry point for our vertex shader.
                + "{                              \n"
                //light calculation section for fragment shader
                + "   vec3 modelViewVertex = vec3(u_MVPMatrix * a_Position);\n"
                + "   vec3 modelViewNormal = vec3(u_MVPMatrix * vec4(a_Normal, 0.0));\n"
                + "   float distance = length(u_LightPos - modelViewVertex);\n"
                + "   vec3 lightVector = normalize(u_LightPos - modelViewVertex);\n"
                + "   float diffuse = max(dot(modelViewNormal, lightVector), 0.1);\n"
                + "   diffuse = diffuse * (1.0 / (1.0 + (0.25 * distance * distance)));\n"
                + "   v_Color = a_Color * vec4(diffuse);\n" //Pass the color with light aspect to fragment shader
                + "   v_TextureCoord = a_TextureCoord; \n"  // Pass the texture coordinate through to the fragment shader. It will be interpolated across the triangle.
                + "   gl_Position = u_MVPMatrix   \n"       // gl_Position is a special variable used to store the final position.
                + "                 * a_Position; \n"       // Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
                + "}                              \n";

            string fragmentShader =
                "precision mediump float;       \n"                                       // Set the default precision to medium. We don't need as high of a
                                                                                          // precision in the fragment shader.
                + "varying vec4 v_Color;          \n"                                     // This is the color from the vertex shader interpolated across the triangle per fragment.
                + "varying vec2 v_TextureCoord;   \n"                                     // This is the texture coordinate from the vertex shader interpolated across the triangle per fragment.
                + "uniform sampler2D u_Texture;   \n"                                     // This is the texture image handler
                + "void main()                    \n"                                     // The entry point for our fragment shader.
                + "{                              \n"
                + "   gl_FragColor = texture2D(u_Texture, v_TextureCoord) * v_Color;  \n" // Pass the color directly through the pipeline.
                + "}                              \n";

            int vertexShaderHandle = GLES20.GlCreateShader(GLES20.GlVertexShader);

            if (vertexShaderHandle != 0)
            {
                // Pass in the shader source.
                GLES20.GlShaderSource(vertexShaderHandle, vertexShader);

                // Compile the shader.
                GLES20.GlCompileShader(vertexShaderHandle);

                // Get the compilation status.
                int[] compileStatus = new int[1];
                GLES20.GlGetShaderiv(vertexShaderHandle, GLES20.GlCompileStatus, compileStatus, 0);

                // If the compilation failed, delete the shader.
                if (compileStatus[0] == 0)
                {
                    GLES20.GlDeleteShader(vertexShaderHandle);
                    vertexShaderHandle = 0;
                }
            }

            if (vertexShaderHandle == 0)
            {
                throw new Exception("Error creating vertex shader.");
            }

            // Load in the fragment shader shader.
            int fragmentShaderHandle = GLES20.GlCreateShader(GLES20.GlFragmentShader);

            if (fragmentShaderHandle != 0)
            {
                // Pass in the shader source.
                GLES20.GlShaderSource(fragmentShaderHandle, fragmentShader);

                // Compile the shader.
                GLES20.GlCompileShader(fragmentShaderHandle);

                // Get the compilation status.
                int[] compileStatus = new int[1];
                GLES20.GlGetShaderiv(fragmentShaderHandle, GLES20.GlCompileStatus, compileStatus, 0);

                // If the compilation failed, delete the shader.
                if (compileStatus[0] == 0)
                {
                    GLES20.GlDeleteShader(fragmentShaderHandle);
                    fragmentShaderHandle = 0;
                }
            }

            if (fragmentShaderHandle == 0)
            {
                throw new Exception("Error creating fragment shader.");
            }

            // Create a program object and store the handle to it.
            int programHandle = GLES20.GlCreateProgram();

            if (programHandle != 0)
            {
                // Bind the vertex shader to the program.
                GLES20.GlAttachShader(programHandle, vertexShaderHandle);

                // Bind the fragment shader to the program.
                GLES20.GlAttachShader(programHandle, fragmentShaderHandle);

                // Bind attributes
                GLES20.GlBindAttribLocation(programHandle, 0, "a_Position");
                GLES20.GlBindAttribLocation(programHandle, 1, "a_Color");
                GLES20.GlBindAttribLocation(programHandle, 2, "a_TextureCoord");
                GLES20.GlBindAttribLocation(programHandle, 3, "a_Normal");

                // Link the two shaders together into a program.
                GLES20.GlLinkProgram(programHandle);

                // Get the link status.
                int[] linkStatus = new int[1];
                GLES20.GlGetProgramiv(programHandle, GLES20.GlLinkStatus, linkStatus, 0);

                // If the link failed, delete the program.
                if (linkStatus[0] == 0)
                {
                    GLES20.GlDeleteProgram(programHandle);
                    programHandle = 0;
                }
            }

            if (programHandle == 0)
            {
                throw new Exception("Error creating program.");
            }

            // Set program handles. These will later be used to pass in values to the program.
            mMVPMatrixHandle    = GLES20.GlGetUniformLocation(programHandle, "u_MVPMatrix");
            mLightPos           = GLES20.GlGetUniformLocation(programHandle, "u_LightPos");
            mPositionHandle     = GLES20.GlGetAttribLocation(programHandle, "a_Position");
            mColorHandle        = GLES20.GlGetAttribLocation(programHandle, "a_Color");
            mTextureCoordHandle = GLES20.GlGetAttribLocation(programHandle, "a_TextureCoord");
            mNormalHandle       = GLES20.GlGetAttribLocation(programHandle, "a_Normal");
            mTextureHandle      = GLES20.GlGetUniformLocation(programHandle, "u_Texture");


            // Tell OpenGL to use this program when rendering.
            GLES20.GlUseProgram(programHandle);
        }
예제 #24
0
        public void OnSurfaceCreated(IGL10 gl, Javax.Microedition.Khronos.Egl.EGLConfig config)
        {
            const float coord = 1.0f;

            ObjParser model3D = new ObjParser();

            List <byte[]> test1 = model3D.ParsedObject(context, "buggy");

            float[] vertexArray = new float[test1[0].Length / 4];
            System.Buffer.BlockCopy(test1[0], 0, vertexArray, 0, (int)test1[0].Length);

            modelVerticesData = vertexArray;

            FloatBuffer mTriangleVertices = ByteBuffer.AllocateDirect(modelVerticesData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleVertices.Put(modelVerticesData).Flip();

            // Cube colors
            // R, G, B, A
            float[] modelColorsData =
            {
                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,

                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f
            };

            FloatBuffer mTriangleColors = ByteBuffer.AllocateDirect(modelColorsData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleColors.Put(modelColorsData).Flip();


            float[] textureUVMapArray = new float[test1[1].Length / 4];
            System.Buffer.BlockCopy(test1[1], 0, textureUVMapArray, 0, (int)test1[1].Length);

            modelTextureUVMapData = textureUVMapArray;

            FloatBuffer mTriangleTextureUVMap = ByteBuffer.AllocateDirect(modelTextureUVMapData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleTextureUVMap.Put(modelTextureUVMapData).Flip();



            //Data buffers to VBO
            GLES20.GlGenBuffers(3, VBOBuffers, 0); //2 buffers for vertices, texture and colors

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[0]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleVertices.Capacity() * mBytesPerFloat, mTriangleVertices, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[1]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleColors.Capacity() * mBytesPerFloat, mTriangleColors, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[2]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleTextureUVMap.Capacity() * mBytesPerFloat, mTriangleTextureUVMap, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            //Load and setup texture

            GLES20.GlGenTextures(1, textureHandle, 0); //init 1 texture storage handle
            if (textureHandle[0] != 0)
            {
                //Android.Graphics cose class Matrix exists at both Android.Graphics and Android.OpenGL and this is only sample of using
                Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options();
                options.InScaled = false; // No pre-scaling
                Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.iam, options);
                GLES20.GlBindTexture(GLES20.GlTexture2d, textureHandle[0]);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlNearest);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
                GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
                GLUtils.TexImage2D(GLES20.GlTexture2d, 0, bitmap, 0);
                bitmap.Recycle();
            }

            //Ask android to run RAM garbage cleaner
            System.GC.Collect();

            //Setup OpenGL ES
            GLES20.GlClearColor(coord, coord, coord, coord);
            // GLES20.GlEnable(GLES20.GlDepthTest); //uncoment if needs enabled dpeth test
            GLES20.GlEnable(2884); // GlCullFace == 2884 see OpenGL documentation to this constant value
            GLES20.GlCullFace(GLES20.GlBack);


            // Position the eye behind the origin.
            float eyeX = 0.0f;
            float eyeY = 0.0f;
            float eyeZ = 4.5f;

            // We are looking toward the distance
            float lookX = 0.0f;
            float lookY = 0.0f;
            float lookZ = -5.0f;

            // Set our up vector. This is where our head would be pointing were we holding the camera.
            float upX = 0.0f;
            float upY = coord;
            float upZ = 0.0f;

            // Set the view matrix. This matrix can be said to represent the camera position.
            // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and
            // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.
            Matrix.SetLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

            string vertexShader =
                "uniform mat4 u_MVPMatrix;      \n"         // A constant representing the combined model/view/projection matrix.
                + "attribute vec4 a_Position;     \n"       // Per-vertex position information we will pass in.
                + "attribute vec4 a_Color;        \n"       // Per-vertex color information we will pass in.
                + "varying vec4 v_Color;          \n"       // This will be passed into the fragment shader.
                + "attribute vec2 a_TextureCoord; \n"
                + "varying vec2 v_TextureCoord;   \n"
                + "void main()                    \n"       // The entry point for our vertex shader.
                + "{                              \n"
                + "   v_TextureCoord = a_TextureCoord; \n"  // Pass the color through to the fragment shader. It will be interpolated across the triangle.
                + "   v_Color = a_Color;          \n"       // Pass the color through to the fragment shader. It will be interpolated across the triangle.
                + "   gl_Position = u_MVPMatrix   \n"       // gl_Position is a special variable used to store the final position.
                + "                 * a_Position; \n"       // Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
                + "}                              \n";

            string fragmentShader =
                "precision mediump float;       \n"     // Set the default precision to medium. We don't need as high of a
                                                        // precision in the fragment shader.
                + "varying vec4 v_Color;          \n"   // This is the color from the vertex shader interpolated across the triangle per fragment.
                + "varying vec2 v_TextureCoord;   \n"
                + "uniform sampler2D u_Texture;   \n"
                + "void main()                    \n"                           // The entry point for our fragment shader.
                + "{                              \n"
                + "   gl_FragColor = texture2D(u_Texture, v_TextureCoord);  \n" // Pass the color directly through the pipeline.
                + "}                              \n";


            vertexShader   = string.Empty;
            fragmentShader = string.Empty;

            int          resourceId   = context.Resources.GetIdentifier("vertexshadervladimir1", "raw", context.PackageName);
            Stream       fileStream   = context.Resources.OpenRawResource(resourceId);
            StreamReader streamReader = new StreamReader(fileStream);

            string line = string.Empty;

            while ((line = streamReader.ReadLine()) != null)
            {
                vertexShader += line + "\n";
            }

            resourceId   = context.Resources.GetIdentifier("fragmentshadervladimir1", "raw", context.PackageName);
            fileStream   = context.Resources.OpenRawResource(resourceId);
            streamReader = new StreamReader(fileStream);
            while ((line = streamReader.ReadLine()) != null)
            {
                fragmentShader += line + "\n";
            }

            int vertexShaderHandle = GLES20.GlCreateShader(GLES20.GlVertexShader);

            if (vertexShaderHandle != 0)
            {
                // Pass in the shader source.
                GLES20.GlShaderSource(vertexShaderHandle, vertexShader);

                // Compile the shader.
                GLES20.GlCompileShader(vertexShaderHandle);

                // Get the compilation status.
                int[] compileStatus = new int[1];
                GLES20.GlGetShaderiv(vertexShaderHandle, GLES20.GlCompileStatus, compileStatus, 0);

                // If the compilation failed, delete the shader.
                if (compileStatus[0] == 0)
                {
                    GLES20.GlDeleteShader(vertexShaderHandle);
                    vertexShaderHandle = 0;
                }
            }

            if (vertexShaderHandle == 0)
            {
                throw new Exception("Error creating vertex shader.");
            }

            // Load in the fragment shader shader.
            int fragmentShaderHandle = GLES20.GlCreateShader(GLES20.GlFragmentShader);

            if (fragmentShaderHandle != 0)
            {
                // Pass in the shader source.
                GLES20.GlShaderSource(fragmentShaderHandle, fragmentShader);

                // Compile the shader.
                GLES20.GlCompileShader(fragmentShaderHandle);

                // Get the compilation status.
                int[] compileStatus = new int[1];
                GLES20.GlGetShaderiv(fragmentShaderHandle, GLES20.GlCompileStatus, compileStatus, 0);

                // If the compilation failed, delete the shader.
                if (compileStatus[0] == 0)
                {
                    GLES20.GlDeleteShader(fragmentShaderHandle);
                    fragmentShaderHandle = 0;
                }
            }

            if (fragmentShaderHandle == 0)
            {
                throw new Exception("Error creating fragment shader.");
            }

            // Create a program object and store the handle to it.
            int programHandle = GLES20.GlCreateProgram();

            if (programHandle != 0)
            {
                // Bind the vertex shader to the program.
                GLES20.GlAttachShader(programHandle, vertexShaderHandle);

                // Bind the fragment shader to the program.
                GLES20.GlAttachShader(programHandle, fragmentShaderHandle);

                // Bind attributes
                GLES20.GlBindAttribLocation(programHandle, 0, "a_Position");
                GLES20.GlBindAttribLocation(programHandle, 1, "a_Color");
                GLES20.GlBindAttribLocation(programHandle, 2, "a_TextureCoord");

                // Link the two shaders together into a program.
                GLES20.GlLinkProgram(programHandle);

                // Get the link status.
                int[] linkStatus = new int[1];
                GLES20.GlGetProgramiv(programHandle, GLES20.GlLinkStatus, linkStatus, 0);

                // If the link failed, delete the program.
                if (linkStatus[0] == 0)
                {
                    GLES20.GlDeleteProgram(programHandle);
                    programHandle = 0;
                }
            }

            if (programHandle == 0)
            {
                throw new Exception("Error creating program.");
            }

            // Set program handles. These will later be used to pass in values to the program.
            mMVPMatrixHandle    = GLES20.GlGetUniformLocation(programHandle, "u_MVPMatrix");
            mPositionHandle     = GLES20.GlGetAttribLocation(programHandle, "a_Position");
            mColorHandle        = GLES20.GlGetAttribLocation(programHandle, "a_Color");
            mTextureCoordHandle = GLES20.GlGetAttribLocation(programHandle, "a_TextureCoord");
            mTextureHandle      = GLES20.GlGetUniformLocation(programHandle, "u_Texture");


            // Tell OpenGL to use this program when rendering.
            GLES20.GlUseProgram(programHandle);
        }
예제 #25
0
        public void CreateOnGlThread(Context context, string objAssetName, string diffuseTextureAssetName)
        {
            // Read the texture.
            var textureBitmap = BitmapFactory.DecodeStream(context.Assets.Open(diffuseTextureAssetName));

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(mTextures.Length, mTextures, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]);

            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);

            textureBitmap.Recycle();

            ShaderUtil.CheckGLError(TAG, "Texture loading");

            // Read the obj file.
            var objInputStream = context.Assets.Open(objAssetName);
            var obj            = JavaGl.Obj.ObjReader.Read(objInputStream);

            obj = JavaGl.Obj.ObjUtils.ConvertToRenderable(obj);

            IntBuffer   wideIndices = JavaGl.Obj.ObjData.GetFaceVertexIndices(obj, 3);
            FloatBuffer vertices    = JavaGl.Obj.ObjData.GetVertices(obj);
            FloatBuffer texCoords   = JavaGl.Obj.ObjData.GetTexCoords(obj, 2);
            FloatBuffer normals     = JavaGl.Obj.ObjData.GetNormals(obj);

            ShortBuffer indices = ByteBuffer.AllocateDirect(2 * wideIndices.Limit())
                                  .Order(ByteOrder.NativeOrder()).AsShortBuffer();

            while (wideIndices.HasRemaining)
            {
                indices.Put((short)wideIndices.Get());
            }
            indices.Rewind();

            var buffers = new int[2];

            GLES20.GlGenBuffers(2, buffers, 0);
            mVertexBufferId = buffers[0];
            mIndexBufferId  = buffers[1];

            mVerticesBaseAddress  = 0;
            mTexCoordsBaseAddress = mVerticesBaseAddress + 4 * vertices.Limit();
            mNormalsBaseAddress   = mTexCoordsBaseAddress + 4 * texCoords.Limit();
            int totalBytes = mNormalsBaseAddress + 4 * normals.Limit();

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVertexBufferId);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, totalBytes, null, GLES20.GlStaticDraw);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mVerticesBaseAddress, 4 * vertices.Limit(), vertices);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mTexCoordsBaseAddress, 4 * texCoords.Limit(), texCoords);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mNormalsBaseAddress, 4 * normals.Limit(), normals);
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, mIndexBufferId);
            mIndexCount = indices.Limit();
            GLES20.GlBufferData(
                GLES20.GlElementArrayBuffer, 2 * mIndexCount, indices, GLES20.GlStaticDraw);
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, 0);

            ShaderUtil.CheckGLError(TAG, "OBJ buffer load");

            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.object_vertex);
            int fragmentShader = ShaderUtil.LoadGLShader(TAG, context,
                                                         GLES20.GlFragmentShader, Resource.Raw.object_fragment);

            mProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mProgram, vertexShader);
            GLES20.GlAttachShader(mProgram, fragmentShader);
            GLES20.GlLinkProgram(mProgram);
            GLES20.GlUseProgram(mProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            mModelViewUniform           = GLES20.GlGetUniformLocation(mProgram, "u_ModelView");
            mModelViewProjectionUniform =
                GLES20.GlGetUniformLocation(mProgram, "u_ModelViewProjection");

            mPositionAttribute = GLES20.GlGetAttribLocation(mProgram, "a_Position");
            mNormalAttribute   = GLES20.GlGetAttribLocation(mProgram, "a_Normal");
            mTexCoordAttribute = GLES20.GlGetAttribLocation(mProgram, "a_TexCoord");

            mTextureUniform = GLES20.GlGetUniformLocation(mProgram, "u_Texture");

            mLightingParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_LightingParameters");
            mMaterialParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_MaterialParameters");

            ShaderUtil.CheckGLError(TAG, "Program parameters");

            Android.Opengl.Matrix.SetIdentityM(mModelMatrix, 0);
        }
예제 #26
0
        // see http://deathbyalgorithm.blogspot.fr/2013/05/opentk-textures.html
        public static int LoadTexture(string name, int quality, bool repeat, bool flip_y)
        {
            string prefix;

                        #if __IOS__
            prefix = "OpenGLDemo.iOS.";
                        #endif
                        #if __ANDROID__
            prefix = "OpenGLDemo.Droid.";
                        #endif

            var assembly = typeof(App2).GetTypeInfo().Assembly;

//			foreach (var res in assembly.GetManifestResourceNames())
//				System.Diagnostics.Debug.WriteLine("found resource: " + res);

            Stream stream = assembly.GetManifestResourceStream(prefix + name + ".png");
            byte[] imageData;

            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                imageData = ms.ToArray();
            }

                        #if __ANDROID__
            Bitmap b = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
                        #elif __IOS__
            UIImage image  = ImageFromByteArray(imageData);
            int     width  = (int)image.CGImage.Width;
            int     height = (int)image.CGImage.Height;

            CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
            byte[]       imageData2 = new byte[height * width * 4];
            CGContext    context    = new CGBitmapContext(imageData2, width, height, 8, 4 * width, colorSpace,
                                                          CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big);

            colorSpace.Dispose();
            context.ClearRect(new RectangleF(0, 0, width, height));
            context.DrawImage(new RectangleF(0, 0, width, height), image.CGImage);
                        #endif

            int [] textures = new int[1];

            //Generate a new texture target in gl
            GL.GenTextures(1, textures);

            //Will bind the texture newly/empty created with GL.GenTexture
            //All gl texture methods targeting Texture2D will relate to this texture
            GL.BindTexture(TextureTarget.Texture2D, textures[0]);

            //The reason why your texture will show up glColor without setting these parameters is actually
            //TextureMinFilters fault as its default is NearestMipmapLinear but we have not established mipmapping
            //We are only using one texture at the moment since mipmapping is a collection of textures pre filtered
            //I'm assuming it stops after not having a collection to check.
            switch (quality)
            {
            case 1:            //High quality
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
                break;

            //case 0:
            default:            //Low quality
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Nearest);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Nearest);
                break;
            }

            if (repeat)
            {
                //This will repeat the texture past its bounds set by TexImage2D
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.Repeat);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.Repeat);
            }
            else
            {
                //This will clamp the texture to the edge, so manipulation will result in skewing
                //It can also be useful for getting rid of repeating texture bits at the borders
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge);
            }

                        #if __ANDROID__
            GLUtils.TexImage2D((int)All.Texture2D, 0, b, 0);
            b.Recycle();
                        #elif __IOS__
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, imageData2);
                        #endif

            GL.BindTexture(TextureTarget.Texture2D, 0);

            return(textures[0]);
        }