Beispiel #1
0
 public __Uint16Array(params ushort[] array)
 {
     InternalFloatArray = array;
     InternalBuffer     = ShortBuffer.wrap(
         (short[])(object)array
         );
 }
        /// <summary>
        /// Read and parse the Wavefront file(.obj) that in Assets folder.
        /// </summary>
        /// <param name="context">Context.</param>
        /// <returns></returns>
        private Optional ReadObject(Context context)
        {
            LoadResult   obj    = null;
            AssetManager assets = context.Assets;

            using (StreamReader sr = new StreamReader(assets.Open(objFileName)))
            {
                obj = Load(sr.ReadToEnd());
            }

            int       numVerticesPerFace = 3;
            IntBuffer objectIndices      = ObjDataBufferHelper.GetFaceVerticesIntBuffer(obj.Groups, numVerticesPerFace);

            FloatBuffer objectVertices = ObjDataBufferHelper.GetVerticesFloatBuffer(obj.Vertices);

            CalculateBoundingBox(objectVertices);

            // Size of the allocated buffer.
            ShortBuffer indices = ByteBuffer.AllocateDirect(2 * objectIndices.Limit())
                                  .Order(ByteOrder.NativeOrder()).AsShortBuffer();

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

            int         dimensionOfTextures = 2;
            FloatBuffer texCoordinates      = ObjDataBufferHelper.GetTexturesFloatBuffer(obj.Textures, dimensionOfTextures);
            FloatBuffer normals             = ObjDataBufferHelper.GetNormalsFloatBuffer(obj.Normals);

            return(Optional.Of(new ObjectData(objectIndices, objectVertices, indices, texCoordinates, normals)));
        }
Beispiel #3
0
 public override ShortBuffer Put(ShortBuffer src)
 {
     if (src is HeapShortBuffer)
     {
         if (src == this)
         {
             throw new IllegalArgumentException();
         }
         HeapShortBuffer sb = (HeapShortBuffer)src;
         int             n  = sb.Remaining();
         if (n > Remaining())
         {
             throw new BufferOverflowException();
         }
         System.Array.Copy(sb.Hb, sb.Ix(sb.Position()), Hb, Ix(Position()), n);
         sb.Position(sb.Position() + n);
         Position(Position() + n);
     }
     else if (src.Direct)
     {
         int n = src.Remaining();
         if (n > Remaining())
         {
             throw new BufferOverflowException();
         }
         src.Get(Hb, Ix(Position()), n);
         Position(Position() + n);
     }
     else
     {
         base.Put(src);
     }
     return(this);
 }
Beispiel #4
0
            private void initTriangle()
            {
                // float has 4 bytes
                ByteBuffer vbb = ByteBuffer.allocateDirect(_nrOfVertices * 3 * 4);

                vbb.order(ByteOrder.nativeOrder());
                _vertexBuffer = vbb.asFloatBuffer();

                // short has 2 bytes
                ByteBuffer ibb = ByteBuffer.allocateDirect(_nrOfVertices * 2);

                ibb.order(ByteOrder.nativeOrder());
                _indexBuffer = ibb.asShortBuffer();

                float[] coords =
                {
                    -0.5f, -0.5f, 0f, // (x1, y1, z1)
                    0.5f,  -0.5f, 0f, // (x2, y2, z2)
                    0f,     0.5f, 0f  // (x3, y3, z3)
                };

                _vertexBuffer.put(coords);
                _indexBuffer.put(_indicesArray);

                _vertexBuffer.position(0);
                _indexBuffer.position(0);
            }
Beispiel #5
0
        public Square()
        {
            // initialize vertex byte buffer for shape coordinates
            ByteBuffer bb = ByteBuffer.AllocateDirect(
                // (# of coordinate values * 4 bytes per float)
                squareCoords.Length * 4);

            bb.Order(ByteOrder.NativeOrder());
            vertexBuffer = bb.AsFloatBuffer();
            vertexBuffer.Put(squareCoords);
            vertexBuffer.Position(0);

            // initialize byte buffer for the draw list
            ByteBuffer dlb = ByteBuffer.AllocateDirect(
                // (# of coordinate values * 2 bytes per short)
                drawOrder.Length * 2);

            dlb.Order(ByteOrder.NativeOrder());
            drawListBuffer = dlb.AsShortBuffer();
            drawListBuffer.Put(drawOrder);
            drawListBuffer.Position(0);

            // prepare shaders and OpenGL program
            int vertexShader = MyGLRenderer.LoadShader(GLES20.GlVertexShader,
                                                       vertexShaderCode);
            int fragmentShader = MyGLRenderer.LoadShader(GLES20.GlFragmentShader,
                                                         fragmentShaderCode);

            mProgram = GLES20.GlCreateProgram();                          // create empty OpenGL Program
            GLES20.GlAttachShader(mProgram, vertexShader);                // add the vertex shader to program
            GLES20.GlAttachShader(mProgram, fragmentShader);              // add the fragment shader to program
            GLES20.GlLinkProgram(mProgram);                               // create OpenGL program executables
        }
Beispiel #6
0
        public static ShortBuffer GetIndices(int size)
        {
            if (size > indexSize)
            {
                // TODO: Optimize it!

                indexSize = size;
                var localSize = size * SIZE * sizeof(short);
                indices = ByteBuffer.AllocateDirect(localSize).Order(ByteOrder.NativeOrder()).AsShortBuffer();

                var values = new short[size * 6];
                var pos    = 0;
                var limit  = size * 4;
                for (var ofs = 0; ofs < limit; ofs += 4)
                {
                    values[pos++] = (short)(ofs + 0);
                    values[pos++] = (short)(ofs + 1);
                    values[pos++] = (short)(ofs + 2);
                    values[pos++] = (short)(ofs + 0);
                    values[pos++] = (short)(ofs + 2);
                    values[pos++] = (short)(ofs + 3);
                }

                indices.Put(values);
                indices.Position(0);
            }

            return(indices);
        }
Beispiel #7
0
            public MyRenderer(BasicCustomVideoRenderer parent)
            {
                this.mCustomVideoRenderer = parent;

                ByteBuffer bb = ByteBuffer.allocateDirect(mXYZCoords.Length * 4);

                bb.order(ByteOrder.nativeOrder());
                mVertexBuffer = bb.asFloatBuffer();
                mVertexBuffer.put(mXYZCoords);
                mVertexBuffer.position(0);

                ByteBuffer tb = ByteBuffer.allocateDirect(mUVCoords.Length * 4);

                tb.order(ByteOrder.nativeOrder());
                mTextureBuffer = tb.asFloatBuffer();
                mTextureBuffer.put(mUVCoords);
                mTextureBuffer.position(0);

                ByteBuffer dlb = ByteBuffer.allocateDirect(mVertexIndex.Length * 2);

                dlb.order(ByteOrder.nativeOrder());
                mDrawListBuffer = dlb.asShortBuffer();
                mDrawListBuffer.put(mVertexIndex);
                mDrawListBuffer.position(0);
            }
Beispiel #8
0
        /**
         * Returns a copy of the specified buffer, with the specified new size. The new size must be greater than or equal
         * to the specified buffer's size. If the new size is greater than the specified buffer's size, this returns a new
         * buffer which is partially filled with the contents of the specified buffer. The returned buffer is a backed by a
         * direct ByteBuffer if and only if the specified buffer is direct.
         *
         * @param buffer  the buffer to copy.
         * @param newSize the new buffer's size, in shorts.
         *
         * @return the new buffer, with the specified size.
         *
         * @throws ArgumentException if the buffer is null, if the new size is negative, or if the new size is less
         *                                  than the buffer's remaing elements.
         */
        public static ShortBuffer copyOf(ShortBuffer buffer, int newSize)
        {
            if (newSize < 0 || newSize < buffer.remaining())
            {
                String message = Logging.getMessage("generic.SizeOutOfRange", newSize);
                Logging.logger().severe(message);
                throw new ArgumentException(message);
            }

            ShortBuffer newBuffer = newShortBuffer(newSize, buffer.isDirect());

            int pos = buffer.position(); // Save the input buffer's current position.

            try
            {
                newBuffer.put(buffer);
                newBuffer.rewind();
            }
            finally
            {
                buffer.position(pos); // Restore the input buffer's original position.
            }

            return(newBuffer);
        }
		public Square ()
		{
			// initialize vertex byte buffer for shape coordinates
			ByteBuffer bb = ByteBuffer.AllocateDirect (
			// (# of coordinate values * 4 bytes per float)
			        squareCoords.Length * 4);
			bb.Order (ByteOrder.NativeOrder ());
			vertexBuffer = bb.AsFloatBuffer ();
			vertexBuffer.Put (squareCoords);
			vertexBuffer.Position (0);

			// initialize byte buffer for the draw list
			ByteBuffer dlb = ByteBuffer.AllocateDirect (
			// (# of coordinate values * 2 bytes per short)
			        drawOrder.Length * 2);
			dlb.Order (ByteOrder.NativeOrder ());
			drawListBuffer = dlb.AsShortBuffer ();
			drawListBuffer.Put (drawOrder);
			drawListBuffer.Position (0);

			// prepare shaders and OpenGL program
			int vertexShader = MyGLRenderer.LoadShader (GLES20.GlVertexShader,
			                                           vertexShaderCode);
			int fragmentShader = MyGLRenderer.LoadShader (GLES20.GlFragmentShader,
			                                             fragmentShaderCode);

			mProgram = GLES20.GlCreateProgram ();             // create empty OpenGL Program
			GLES20.GlAttachShader (mProgram, vertexShader);   // add the vertex shader to program
			GLES20.GlAttachShader (mProgram, fragmentShader); // add the fragment shader to program
			GLES20.GlLinkProgram (mProgram);                  // create OpenGL program executables
		}
Beispiel #10
0
        public static ShortBuffer Wrap(short[] data)
        {
            ShortBuffer buf = new ShortBuffer(new byte[data.Length * 2], 0, data.Length * 2);

            buf.Put(data);
            return(buf);
        }
Beispiel #11
0
            protected int replaceNaN(ShortBuffer shortBuffer, short value)
            {
                int length    = shortBuffer.remaining();
                int numValues = 0;

                if (this.tmpBuffer == null || this.tmpBuffer.length < shortBuffer.remaining())
                {
                    this.tmpBuffer = new short[length];
                }

                shortBuffer.get(this.tmpBuffer, 0, length);
                shortBuffer.flip();

                for (int i = 0; i < length; i++)
                {
                    if (isNoValueShort(this.tmpBuffer[i]))
                    {
                        this.tmpBuffer[i] = value;
                    }
                    else
                    {
                        numValues++;
                    }
                }

                shortBuffer.put(this.tmpBuffer, 0, length);
                shortBuffer.flip();

                return(numValues);
            }
Beispiel #12
0
 public static void copyBuffer(ShortBuffer dstBuffer, ShortBuffer srcBuffer)
 {
     if (dstBuffer != srcBuffer)
     {
         srcBuffer.rewind();
         dstBuffer.put(srcBuffer);
     }
 }
Beispiel #13
0
        public static ShortBuffer allocateDirectBuffer(ShortBuffer buffer)
        {
            if (buffer.Direct)
            {
                return(buffer);
            }

            return(allocateDirectBuffer(buffer.remaining() << 1).asShortBuffer());
        }
Beispiel #14
0
        /// <summary>
        /// Convert Int buffer to ShortBuffer.
        /// </summary>
        /// <param name="intBuffer">source buffer</param>
        /// <returns>ShortBuffer</returns>
        public static ShortBuffer ConvertToShortBuffer(IntBuffer intBuffer)
        {
            ShortBuffer shortBuffer = CreateDirectShortBuffer(intBuffer.Capacity());

            for (int i = 0; i < intBuffer.Capacity(); i++)
            {
                shortBuffer.Put(i, (short)intBuffer.Get());
            }
            return(shortBuffer);
        }
Beispiel #15
0
        public virtual void DrawElements(FloatBuffer vertices, ShortBuffer indices, int size)
        {
            vertices.Position(0);
            AXy.VertexPointer(2, 4, vertices);

            vertices.Position(2);
            AUv.VertexPointer(2, 4, vertices);

            GLES20.GlDrawElements(GLES20.GlTriangles, size, GLES20.GlUnsignedShort, indices);
        }
Beispiel #16
0
        /// <summary>
        /// Since the given buffer may not have an array, this will automatically perform necessary edits to get a <see cref="ushort"/> array (this uses ushort because of how java handles datatypes)
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private static ushort[] GetFromShortBuffer(ShortBuffer buffer)
        {
            List <ushort> data = new List <ushort>();

            while (buffer.hasRemaining())
            {
                short v = buffer.get();
                // This is kinda expensive ngl
                data.Add(BitConverter.ToUInt16(BitConverter.GetBytes(v), 0));
            }
            return(data.ToArray());
        }
 public ObjectData(IntBuffer objectIndices,
                   FloatBuffer objectVertices,
                   ShortBuffer indices,
                   FloatBuffer texCoords,
                   FloatBuffer normals)
 {
     this.objectIndices  = objectIndices;
     this.objectVertices = objectVertices;
     this.indices        = indices;
     this.texCoords      = texCoords;
     this.normals        = normals;
 }
Beispiel #18
0
        public Flare(int nRays, float radius)
            : base(0, 0, 0, 0)
        {
            // FIXME
            // Texture is incorrectly created every time we need
            // to show the effect, it must be refactored

            var gradient = new[] {
                Android.Graphics.Color.Argb(0xFF, 0xFF, 0xFF, 0xFF),
                Android.Graphics.Color.Argb(0x00, 0xFF, 0xFF, 0xFF)
            };

            _texture = new Gradient(gradient);

            _nRays = nRays;

            Angle        = 45;
            AngularSpeed = 180;

            _vertices = ByteBuffer.AllocateDirect((nRays * 2 + 1) * 4 * (sizeof(float))).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            _indices = ByteBuffer.AllocateDirect(nRays * 3 * sizeof(short)).Order(ByteOrder.NativeOrder()).AsShortBuffer();

            var v = new float[4];

            v[0] = 0;
            v[1] = 0;
            v[2] = 0.25f;
            v[3] = 0;
            _vertices.Put(v);

            v[2] = 0.75f;
            v[3] = 0;

            for (var i = 0; i < nRays; i++)
            {
                var a = i * 3.1415926f * 2 / nRays;
                v[0] = FloatMath.Cos(a) * radius;
                v[1] = FloatMath.Sin(a) * radius;
                _vertices.Put(v);

                a   += 3.1415926f * 2 / nRays / 2;
                v[0] = FloatMath.Cos(a) * radius;
                v[1] = FloatMath.Sin(a) * radius;
                _vertices.Put(v);

                _indices.Put(0);
                _indices.Put((short)(1 + i * 2));
                _indices.Put((short)(2 + i * 2));
            }

            _indices.Position(0);
        }
Beispiel #19
0
            private void initTriangle()
            {
                float[] coords =
                {
                    -0.5f, -0.5f, 0.5f,  // 0
                    0.5f,  -0.5f, 0.5f,  // 1
                    0f,    -0.5f, -0.5f, // 2
                    0f,     0.5f, 0f,    // 3
                };
                _nrOfVertices = coords.Length;

                float[] colors =
                {
                    1f, 0f, 0f, 1f,     // point 0 red
                    0f, 1f, 0f, 1f,     // point 1 green
                    0f, 0f, 1f, 1f,     // point 2 blue
                    1f, 1f, 1f, 1f,     // point 3 white
                };

                short[] indices = new short[] {
                    0, 1, 3,     // rwg
                    0, 2, 1,     // rbg
                    0, 3, 2,     // rbw
                    1, 2, 3,     // bwg
                };

                // float has 4 bytes, coordinate * 4 bytes
                ByteBuffer vbb = ByteBuffer.allocateDirect(coords.Length * 4);

                vbb.order(ByteOrder.nativeOrder());
                _vertexBuffer = vbb.asFloatBuffer();

                // short has 2 bytes, indices * 2 bytes
                ByteBuffer ibb = ByteBuffer.allocateDirect(indices.Length * 2);

                ibb.order(ByteOrder.nativeOrder());
                _indexBuffer = ibb.asShortBuffer();

                // float has 4 bytes, colors (RGBA) * 4 bytes
                ByteBuffer cbb = ByteBuffer.allocateDirect(colors.Length * 4);

                cbb.order(ByteOrder.nativeOrder());
                _colorBuffer = cbb.asFloatBuffer();

                _vertexBuffer.put(coords);
                _indexBuffer.put(indices);
                _colorBuffer.put(colors);

                _vertexBuffer.position(0);
                _indexBuffer.position(0);
                _colorBuffer.position(0);
            }
Beispiel #20
0
        /**
         * Allocates a new {@link BufferWrapper} of the specified size, in shorts. The BufferWrapper is backed by a Buffer
         * of shorts.
         *
         * @param size           the new BufferWrapper's size.
         * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct
         *                       buffer.
         *
         * @return the new BufferWrapper.
         *
         * @throws ArgumentException if size is negative.
         */
        public static BufferWrapper newShortBufferWrapper(int size, bool allocateDirect)
        {
            if (size < 0)
            {
                String message = Logging.getMessage("generic.SizeOutOfRange", size);
                Logging.logger().severe(message);
                throw new ArgumentException(message);
            }

            ShortBuffer buffer = newShortBuffer(size, allocateDirect);

            return(new BufferWrapper.ShortBufferWrapper(buffer));
        }
        private void DrawLabel(float[] cameraViews, float[] cameraProjection)
        {
            ShaderUtil.CheckGlError(TAG, "Draw label start.");
            Matrix.MultiplyMM(modelViewMatrix, 0, cameraViews, 0, modelMatrix, 0);
            Matrix.MultiplyMM(modelViewProjectionMatrix, 0, cameraProjection, 0, modelViewMatrix, 0);

            float halfWidth  = LABEL_WIDTH / 2.0f;
            float halfHeight = LABEL_HEIGHT / 2.0f;

            float[] vertices =
            {
                -halfWidth, -halfHeight, 1,
                -halfWidth, halfHeight,  1,
                halfWidth,  halfHeight,  1,
                halfWidth,  -halfHeight, 1,
            };

            // The size of each floating point is 4 bits.
            FloatBuffer vetBuffer = ByteBuffer.AllocateDirect(4 * vertices.Length)
                                    .Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            vetBuffer.Rewind();
            for (int i = 0; i < vertices.Length; ++i)
            {
                vetBuffer.Put(vertices[i]);
            }
            vetBuffer.Rewind();

            // The size of each floating point is 4 bits.
            GLES20.GlVertexAttribPointer(glPositionParameter, COORDS_PER_VERTEX, GLES20.GlFloat,
                                         false, 4 * COORDS_PER_VERTEX, vetBuffer);

            // Set the sequence of OpenGL drawing points to generate two triangles that form a plane.
            short[] indices = { 0, 1, 2, 0, 2, 3 };

            // Size of the allocated buffer.
            ShortBuffer idxBuffer = ByteBuffer.AllocateDirect(2 * indices.Length)
                                    .Order(ByteOrder.NativeOrder()).AsShortBuffer();

            idxBuffer.Rewind();
            for (int i = 0; i < indices.Length; ++i)
            {
                idxBuffer.Put(indices[i]);
            }
            idxBuffer.Rewind();

            GLES20.GlUniformMatrix4fv(glModelViewProjectionMatrix, 1, false, modelViewProjectionMatrix, 0);

            GLES20.GlDrawElements(GLES20.GlTriangleStrip, idxBuffer.Limit(), GLES20.GlUnsignedShort, idxBuffer);
            ShaderUtil.CheckGlError(TAG, "Draw label end.");
        }
Beispiel #22
0
            protected BufferWrapper doRead(ByteBuffer byteBuffer)
            {
                ShortBuffer shortBuffer = byteBuffer.asShortBuffer();

                // Replace null (NaN) values in partially null coordinates with 0. Because these vector coordinate buffers
                // are passed directly to GL, we avoid compatability problems with some graphics drivers by removing any
                // NaN coordinate in the vectors. We must also detect when a vector is completely null, and enter an empty
                // sub-buffer in this case. This is necessary because we are eliminating the NaN signal which the data
                // consumer would ordinarily use to detect null coordinates.
                if (this.replaceNaN(shortBuffer, (short)0) <= 0)
                {
                    return(null);
                }

                return(new BufferWrapper.ShortBufferWrapper(shortBuffer));
            }
        public ShortBuffer AsShortBuffer()
        {
            ShortBuffer buf = new ShortBuffer();

            buf.buffer = new byte[this.buffer.Length];
            this.buffer.CopyTo(buf.buffer, 0);

            buf.c        = this.c;
            buf.capacity = this.capacity;
            buf.index    = this.index;
            buf.limit    = this.limit;
            buf.mark     = this.mark;
            buf.offset   = this.offset;
            buf.order    = this.order;
            return(buf);
        }
        private void SetupTriangle()
        {
            rect = new RectF(10, 200, 100, 10);

            /*rect.Left = 10;
            *  rect.Right = 100;
            *  rect.Bottom = 100;
            *  rect.Top = 200;*/

            // We have to create the vertices.

            /*vertices = new float[]
             * {
             *  10.0f, 200f, 0.0f,
             *  10.0f, 100f, 0.0f,
             *  100f, 100f, 0.0f,
             *  100f, 200f, 0.0f,
             * };*/
            vertices = new float[]
            {
                rect.Left, rect.Top, 0.0f,
                rect.Left, rect.Bottom, 0.0f,
                rect.Right, rect.Bottom, 0.0f,
                rect.Right, rect.Top, 0.0f,
            };


            indices = new short[] { 0, 1, 2, 0, 2, 3 }; // The order of vertexrendering.

            // The vertex buffer.
            ByteBuffer byteBuffer = ByteBuffer.AllocateDirect(vertices.Length * 4);

            byteBuffer.Order(ByteOrder.NativeOrder());
            vertexBuffer = byteBuffer.AsFloatBuffer();
            vertexBuffer.Put(vertices);
            vertexBuffer.Position(0);

            // initialize byte buffer for the draw list
            ByteBuffer byteBuffer2 = ByteBuffer.AllocateDirect(indices.Length * 2);

            byteBuffer2.Order(ByteOrder.NativeOrder());
            drawListBuffer = byteBuffer2.AsShortBuffer();
            drawListBuffer.Put(indices);
            drawListBuffer.Position(0);
        }
        public IndexedVerticesScreen(IGame g) : base(g)
        {
            _glGraphics = ((AndroidGLGame)g).GLGraphics;
            ByteBuffer bb = ByteBuffer.AllocateDirect(_vertexSize * 4);

            bb.Order(ByteOrder.NativeOrder());
            _vertices = bb.AsFloatBuffer();
            _vertices.Put(new float[] { 100f, 100f, 0f, 1f, 428f, 100f, 1f, 1f, 428f, 428f, 1f, 0f, 100f, 428f, 0f, 0f });
            _vertices.Flip();

            bb = ByteBuffer.AllocateDirect(6 * 2);
            bb.Order(ByteOrder.NativeOrder());
            _indices = bb.AsShortBuffer();
            _indices.Put(new short[] { 0, 1, 2, 2, 3, 0 });
            _indices.Flip();

            _texture = new AndroidTexture((AndroidGLGame)g, "bobrgb888.png");
        }
Beispiel #26
0
        public AndroidVertices(AndroidGLGraphics glGraphics, int maxVertices, int maxIndices, bool color, bool tecCoords)
        {
            _glGraphics = glGraphics;

            _hasColor     = color;
            _hasTexCoords = tecCoords;
            _vertexSize   = (2 + (_hasColor ? 4 : 0) + (_hasTexCoords ? 2 : 0)) * 4;

            ByteBuffer buffer = ByteBuffer.AllocateDirect(maxVertices * _vertexSize);

            buffer.Order(ByteOrder.NativeOrder());
            _vertices = buffer.AsFloatBuffer();
            if (maxVertices > 0)
            {
                buffer = ByteBuffer.AllocateDirect(maxIndices * 2);
                buffer.Order(ByteOrder.NativeOrder());
                _indices = buffer.AsShortBuffer();
            }
        }
Beispiel #27
0
        public override bool allocate()
        {
            try
            {
                byteBuffer  = ByteBuffer.allocateDirect(MemoryMap.END_RAM + 1).order(ByteOrder.LITTLE_ENDIAN);
                intBuffer   = byteBuffer.asIntBuffer();
                shortBuffer = byteBuffer.asShortBuffer();
                clearBuffer = ByteBuffer.allocateDirect(clearBufferSize).order(byteBuffer.order());
            }
            catch (System.OutOfMemoryException)
            {
                // Not enough memory provided for this VM, cannot use FastMemory model
                Memory.Console.WriteLine("Cannot allocate DirectBufferMemory: add the option '-Xmx256m' to the Java Virtual Machine startup command to improve Performance");
                Memory.Console.WriteLine("The current Java Virtual Machine has been started using '-Xmx" + (Runtime.Runtime.maxMemory() / (1024 * 1024)) + "m'");
                return(false);
            }

            return(base.allocate());
        }
            private void initTriangle()
            {
                // float has 4 bytes
                ByteBuffer vbb = ByteBuffer.allocateDirect(_nrOfVertices * 3 * 4);

                vbb.order(ByteOrder.nativeOrder());
                _vertexBuffer = vbb.asFloatBuffer();

                // short has 4 bytes
                ByteBuffer ibb = ByteBuffer.allocateDirect(_nrOfVertices * 2);

                ibb.order(ByteOrder.nativeOrder());
                _indexBuffer = ibb.asShortBuffer();

                // float has 4 bytes, 4 colors (RGBA) * number of vertices * 4 bytes
                ByteBuffer cbb = ByteBuffer.allocateDirect(4 * _nrOfVertices * 4);

                cbb.order(ByteOrder.nativeOrder());
                _colorBuffer = cbb.asFloatBuffer();

                float[] coords =
                {
                    -0.5f, -0.5f, 0f, // (x1, y1, z1)
                    0.5f,  -0.5f, 0f, // (x2, y2, z2)
                    0.5f,   0.5f, 0f  // (x3, y3, z3)
                };

                float[] colors =
                {
                    1f, 0f, 0f, 1f, // point 1
                    0f, 1f, 0f, 1f, // point 2
                    0f, 0f, 1f, 1f, // point 3
                };

                _vertexBuffer.put(coords);
                _indexBuffer.put(_indicesArray);
                _colorBuffer.put(colors);

                _vertexBuffer.position(0);
                _indexBuffer.position(0);
                _colorBuffer.position(0);
            }
			public MyRenderer()
			{
				ByteBuffer bb = ByteBuffer.allocateDirect(mXYZCoords.Length * 4);
				bb.order(ByteOrder.nativeOrder());
				mVertexBuffer = bb.asFloatBuffer();
				mVertexBuffer.put(mXYZCoords);
				mVertexBuffer.position(0);

				ByteBuffer tb = ByteBuffer.allocateDirect(mUVCoords.Length * 4);
				tb.order(ByteOrder.nativeOrder());
				mTextureBuffer = tb.asFloatBuffer();
				mTextureBuffer.put(mUVCoords);
				mTextureBuffer.position(0);

				ByteBuffer dlb = ByteBuffer.allocateDirect(mVertexIndex.Length * 2);
				dlb.order(ByteOrder.nativeOrder());
				mDrawListBuffer = dlb.asShortBuffer();
				mDrawListBuffer.put(mVertexIndex);
				mDrawListBuffer.position(0);
			}
Beispiel #30
0
        private int getInt32(Buffer buffer)
        {
            if (buffer is IntBuffer)
            {
                return(((IntBuffer)buffer).get());
            }
            else if (buffer is ShortBuffer)
            {
                ShortBuffer shortBuffer = (ShortBuffer)buffer;
                int         n0          = shortBuffer.get() & 0xFFFF;
                int         n1          = shortBuffer.get() & 0xFFFF;
                return((n1 << 16) | n0);
            }
            else if (buffer is ByteBuffer)
            {
                return(((ByteBuffer)buffer).Int);
            }

            return(0);
        }
Beispiel #31
0
        public static ShortBuffer getDirectBuffer(int size, ShortBuffer buffer)
        {
            if (buffer == null)
            {
                return(buffer);
            }

            size = Round2(size);

            if (buffer.Direct)
            {
                buffer.limit((size >> 1) + buffer.position());
                return(buffer);
            }

            ShortBuffer directBuffer = allocateDirectBuffer(size).asShortBuffer();

            directBuffer.put((ShortBuffer)((ShortBuffer)buffer).slice().limit(size >> 1));
            directBuffer.rewind();

            return(directBuffer);
        }
        /**
         * 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);
        }