Example #1
0
        public void Set(Context context, Mesh mesh)
        {
            Verify.ThrowIfNull(context);

            if (mesh == null)
            {
                throw new ArgumentNullException("mesh");
            }

            if (mesh.PrimitiveType != PrimitiveType.Lines &&
                mesh.PrimitiveType != PrimitiveType.LineLoop &&
                mesh.PrimitiveType != PrimitiveType.LineStrip)
            {
                throw new ArgumentException("mesh.PrimitiveType must be Lines, LineLoop, or LineStrip.", "mesh");
            }

            if (!mesh.Attributes.Contains("position") &&
                !mesh.Attributes.Contains("color"))
            {
                throw new ArgumentException("mesh.Attributes should contain attributes named \"position\" and \"color\".", "mesh");
            }

            if (_drawState.ShaderProgram == null)
            {
                _drawState.ShaderProgram = Device.CreateShaderProgram(
                    EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Polyline.Polyline.PolylineVS.glsl"),
                    EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Polyline.Polyline.PolylineGS.glsl"),
                    EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Polyline.Polyline.PolylineFS.glsl"));
                _fillDistance = (Uniform<float>)_drawState.ShaderProgram.Uniforms["u_fillDistance"];
            }
            
            ///////////////////////////////////////////////////////////////////
            _drawState.VertexArray = context.CreateVertexArray(mesh, _drawState.ShaderProgram.VertexAttributes, BufferHint.StaticDraw);
            _primitiveType = mesh.PrimitiveType;
        }
Example #2
0
        private void Clean(Context context)
        {
            if (_dirty)
            {
                if (_va != null)
                {
                    _va.Dispose();
                    _va = null;
                    _drawState.VertexArray = null;
                    _drawStateSolid.VertexArray = null;
                }

                Mesh mesh = BoxTessellator.Compute(2 * _shape.Radii);
                _va = context.CreateVertexArray(mesh, _drawState.ShaderProgram.VertexAttributes, BufferHint.StaticDraw);
                _drawState.VertexArray = _va;
                _drawStateSolid.VertexArray = _va;
                _primitiveType = mesh.PrimitiveType;

                _renderState.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;

                ((Uniform<Vector3F>)_drawState.ShaderProgram.Uniforms["u_globeOneOverRadiiSquared"]).Value = _shape.OneOverRadiiSquared.ToVector3F();
                ((Uniform<Vector3F>)_drawStateSolid.ShaderProgram.Uniforms["u_globeOneOverRadiiSquared"]).Value = _shape.OneOverRadiiSquared.ToVector3F();

                if (_wireframe != null)
                {
                    _wireframe.Dispose();
                    _wireframe = null;
                }
                _wireframe = new Wireframe(context, mesh);
                _wireframe.FacetCullingFace = CullFace.Front;
                _wireframe.Width = 3;

                _dirty = false;
            }
        }
        private void Update(Context context, SceneState sceneState)
        {
            if (_meshBuffers != null)
            {
                if (_drawState.VertexArray != null)
                {
                    _drawState.VertexArray.Dispose();
                    _drawState.VertexArray = null;
                }

                _drawState.VertexArray = context.CreateVertexArray(_meshBuffers);
                _meshBuffers = null;
            }

            ///////////////////////////////////////////////////////////////////

            int width = (int)Math.Ceiling(Width * sceneState.HighResolutionSnapScale);
            int outlineWidth = (int)Math.Ceiling(OutlineWidth * sceneState.HighResolutionSnapScale);

            int textureWidth = width + outlineWidth + outlineWidth + 2;

            if ((_texture == null) || (_texture.Description.Width != textureWidth))
            {
                int textureResolution = textureWidth * 2;

                float[] texels = new float[textureResolution];

                int k = 3;
                for (int i = 1; i < textureWidth - 1; ++i)
                {
                    texels[k] = 1;                  // Alpha (stored in Green channel)
                    k += 2;
                }

                int j = (outlineWidth + 1) * 2;
                for (int i = 0; i < width; ++i)
                {
                    texels[j] = 1;                  // Fill/Outline (stored in Red channel)
                    j += 2;
                }

                WritePixelBuffer pixelBuffer = Device.CreateWritePixelBuffer(PixelBufferHint.Stream,
                    sizeof(float) * textureResolution);
                pixelBuffer.CopyFromSystemMemory(texels);

                if (_texture != null)
                {
                    _texture.Dispose();
                    _texture = null;
                }

                // TODO:  Why does only Float or HalfFloat work here?
                _texture = Device.CreateTexture2D(new Texture2DDescription(textureWidth, 1, TextureFormat.RedGreen8));
                _texture.CopyFromBuffer(pixelBuffer, ImageFormat.RedGreen, ImageDatatype.Float);
            }
        }
Example #4
0
        private void CreateVertexArray(Context context)
        {
            // TODO:  Buffer hint.
            _positionBuffer = Device.CreateVertexBuffer(BufferHint.StaticDraw, SizeInBytes<Vector2F>.Value);

            VertexBufferAttribute positionAttribute = new VertexBufferAttribute(
                _positionBuffer, ComponentDatatype.Float, 2);

            _drawState.VertexArray = context.CreateVertexArray();
            _drawState.VertexArray.Attributes[_drawState.ShaderProgram.VertexAttributes["position"].Location] = positionAttribute;
         }
Example #5
0
        public ClipmapUpdater(Context context, ClipmapLevel[] clipmapLevels)
        {
            ShaderVertexAttributeCollection vertexAttributes = new ShaderVertexAttributeCollection();
            vertexAttributes.Add(new ShaderVertexAttribute("position", VertexLocations.Position, ShaderVertexAttributeType.FloatVector2, 1));

            Mesh unitQuad = RectangleTessellator.Compute(new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(1.0, 1.0)), 1, 1);
            _unitQuad = context.CreateVertexArray(unitQuad, vertexAttributes, BufferHint.StaticDraw);
            _unitQuadPrimitiveType = unitQuad.PrimitiveType;
            _sceneState = new SceneState();
            _framebuffer = context.CreateFramebuffer();

            _updateShader = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.ClipmapUpdateVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.ClipmapUpdateFS.glsl"));
            _updateTexelOutput = _updateShader.FragmentOutputs["texelOutput"];
            _updateDrawState = new DrawState(new RenderState(), _updateShader, _unitQuad);
            _updateDrawState.RenderState.FacetCulling.FrontFaceWindingOrder = unitQuad.FrontFaceWindingOrder;
            _updateDrawState.RenderState.DepthTest.Enabled = false;
            _updateDestinationOffset = (Uniform<Vector2F>)_updateShader.Uniforms["u_destinationOffset"];
            _updateUpdateSize = (Uniform<Vector2F>)_updateShader.Uniforms["u_updateSize"];
            _updateSourceOrigin = (Uniform<Vector2F>)_updateShader.Uniforms["u_sourceOrigin"];

            _upsampleShader = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.ClipmapUpsampleVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.ClipmapUpsampleFS.glsl"));
            _upsampleTexelOutput = _upsampleShader.FragmentOutputs["texelOutput"];
            _upsampleDrawState = new DrawState(new RenderState(), _upsampleShader, _unitQuad);
            _upsampleDrawState.RenderState.FacetCulling.FrontFaceWindingOrder = unitQuad.FrontFaceWindingOrder;
            _upsampleDrawState.RenderState.DepthTest.Enabled = false;
            _upsampleSourceOrigin = (Uniform<Vector2F>)_upsampleShader.Uniforms["u_sourceOrigin"];
            _upsampleUpdateSize = (Uniform<Vector2F>)_upsampleShader.Uniforms["u_updateSize"];
            _upsampleDestinationOffset = (Uniform<Vector2F>)_upsampleShader.Uniforms["u_destinationOffset"];
            _upsampleOneOverTextureSize = (Uniform<Vector2F>)_upsampleShader.Uniforms["u_oneOverTextureSize"];

            _computeNormalsShader = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.ClipmapComputeNormalsVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.ClipmapComputeNormalsFS.glsl"));
            _normalOutput = _computeNormalsShader.FragmentOutputs["normalOutput"];
            _computeNormalsDrawState = new DrawState(new RenderState(), _computeNormalsShader, _unitQuad);
            _computeNormalsDrawState.RenderState.FacetCulling.FrontFaceWindingOrder = unitQuad.FrontFaceWindingOrder;
            _computeNormalsDrawState.RenderState.DepthTest.Enabled = false;
            _computeNormalsOrigin = (Uniform<Vector2F>)_computeNormalsShader.Uniforms["u_origin"];
            _computeNormalsUpdateSize = (Uniform<Vector2F>)_computeNormalsShader.Uniforms["u_updateSize"];
            _computeNormalsOneOverHeightMapSize = (Uniform<Vector2F>)_computeNormalsShader.Uniforms["u_oneOverHeightMapSize"];
            _heightExaggeration = (Uniform<float>)_computeNormalsShader.Uniforms["u_heightExaggeration"];
            _postDelta = (Uniform<float>)_computeNormalsShader.Uniforms["u_postDelta"];

            HeightExaggeration = 1.0f;

            ClipmapLevel levelZero = clipmapLevels[0];
            InitializeRequestThreads(context, _terrain, levelZero, levelZero.Terrain);
            InitializeRequestThreads(context, _imagery, levelZero, levelZero.Imagery);
        }
Example #6
0
        public static VertexArray CreateVertexArray(Context context, int positionLocation)
        {
            Vector4F[] positions = new[] { new Vector4F(0, 0, 0, 1) };
            VertexBuffer positionsBuffer = Device.CreateVertexBuffer(BufferHint.StaticDraw, ArraySizeInBytes.Size(positions));
            positionsBuffer.CopyFromSystemMemory(positions);
            
            VertexArray va = context.CreateVertexArray();
            va.Attributes[positionLocation] = new VertexBufferAttribute(positionsBuffer, ComponentDatatype.Float, 4);
            va.DisposeBuffers = true;

            return va;
        }
        public GPURelativeToEye(Context context, Vector3D[] positions, byte[] colors)
        {
            _sp = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Examples.GPURelativeToEye.Shaders.VS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Examples.Shaders.FS.glsl"));
            _cameraEyeHigh = (Uniform<Vector3F>)_sp.Uniforms["u_cameraEyeHigh"];
            _cameraEyeLow = (Uniform<Vector3F>)_sp.Uniforms["u_cameraEyeLow"];
            _modelViewPerspectiveMatrixRelativeToEye = (Uniform<Matrix4F>)(_sp.Uniforms["u_modelViewPerspectiveMatrixRelativeToEye"]);
            _pointSize = (Uniform<float>)_sp.Uniforms["u_pointSize"];

            ///////////////////////////////////////////////////////////////////

            Mesh mesh = new Mesh();
            VertexAttributeFloatVector3 positionsHighAttribute = new VertexAttributeFloatVector3("positionHigh", positions.Length);
            VertexAttributeFloatVector3 positionsLowAttribute = new VertexAttributeFloatVector3("positionLow", positions.Length);
            VertexAttributeRGB colorAttribute = new VertexAttributeRGB("color", positions.Length);
            mesh.Attributes.Add(positionsHighAttribute);
            mesh.Attributes.Add(positionsLowAttribute);
            mesh.Attributes.Add(colorAttribute);

            for (int i = 0; i < positions.Length; ++i)
            {
                Vector3F positionHigh;
                Vector3F positionLow;
                Vector3DToTwoVector3F(positions[i], out positionHigh, out positionLow);

                positionsHighAttribute.Values.Add(positionHigh);
                positionsLowAttribute.Values.Add(positionLow);
            }

            for (int i = 0; i < colors.Length; ++i)
            {
                colorAttribute.Values.Add(colors[i]);
            }

            _va = context.CreateVertexArray(mesh, _sp.VertexAttributes, BufferHint.StaticDraw);

            ///////////////////////////////////////////////////////////////////

            RenderState renderState = new RenderState();
            renderState.FacetCulling.Enabled = false;
            renderState.DepthTest.Enabled = false;
            renderState.ProgramPointSize = ProgramPointSize.Enabled;

            _drawState = new DrawState(renderState, _sp, _va);
        }
        internal void Update(Context context, ShaderProgram sp)
        {
            if (_va == null)
            {
                VertexBufferAttribute positionAttribute = new VertexBufferAttribute(
                    _positionBuffer, ComponentDatatype.Float, 2);
                VertexBufferAttribute textureCoordinatesAttribute = new VertexBufferAttribute(
                    _textureCoordinatesBuffer, ComponentDatatype.HalfFloat, 2);

                _va = context.CreateVertexArray();
                _va.Attributes[sp.VertexAttributes["position"].Location] = positionAttribute;
                _va.Attributes[sp.VertexAttributes["textureCoordinates"].Location] = textureCoordinatesAttribute;
            }

            if (_viewport != context.Viewport)
            {
                //
                // Bottom and top swapped:  MS -> OpenGL
                //
                float left = context.Viewport.Left;
                float bottom = context.Viewport.Top;
                float right = context.Viewport.Right;
                float top = context.Viewport.Bottom;

                Vector2F[] positions = new Vector2F[] 
                { 
                    new Vector2F(left, bottom), 
                    new Vector2F(right, bottom), 
                    new Vector2F(left, top), 
                    new Vector2F(right, top)
                };
                _positionBuffer.CopyFromSystemMemory(positions);

                Vector2H[] textureCoordinates = new Vector2H[] 
                { 
                    new Vector2H(0, 0), 
                    new Vector2H(1, 0), 
                    new Vector2H(0, 1), 
                    new Vector2H(1, 1)
                };
                _textureCoordinatesBuffer.CopyFromSystemMemory(textureCoordinates);

                _viewport = context.Viewport;
            }
        }
        private void Clean(Context context)
        {
            if (_dirty)
            {
                if (_drawState.VertexArray != null)
                {
                    _drawState.VertexArray.Dispose();
                    _drawState.VertexArray = null;
                }

                Mesh mesh = GeographicGridEllipsoidTessellator.Compute(Shape,
                    _numberOfSlicePartitions, _numberOfStackPartitions, GeographicGridEllipsoidVertexAttributes.Position);
                _drawState.VertexArray = context.CreateVertexArray(mesh, _drawState.ShaderProgram.VertexAttributes, BufferHint.StaticDraw);
                _primitiveType = mesh.PrimitiveType;
                _numberOfTriangles = (((IndicesUnsignedInt)mesh.Indices).Values.Count / 3);

                _drawState.RenderState.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;

                _dirty = false;
            }
        }
Example #10
0
        public Wireframe(Context context, Mesh mesh)
        {
            RenderState renderState = new RenderState();
            renderState.Blending.Enabled = true;
            renderState.Blending.SourceRGBFactor = SourceBlendingFactor.SourceAlpha;
            renderState.Blending.SourceAlphaFactor = SourceBlendingFactor.SourceAlpha;
            renderState.Blending.DestinationRGBFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            renderState.Blending.DestinationAlphaFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            renderState.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;
            renderState.DepthTest.Function = DepthTestFunction.LessThanOrEqual;

            //
            // This implementation is based on the 2006 SIGGRAPH Sketch:
            //
            //    Single-pass Wireframe Rendering
            //    http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/4884/pdf/imm4884.pdf
            //
            // NVIDIA published a white paper with some enhancements we can consider:
            //
            //    Solid Wireframe
            //    http://developer.download.nvidia.com/SDK/10.5/direct3d/Source/SolidWireframe/Doc/SolidWireframe.pdf
            //
            // More recent work, which I was not aware of at the time, is:
            //
            //    Two Methods for Antialiased Wireframe Drawing with Hidden Line Removal
            //    http://orbit.dtu.dk/getResource?recordId=219956&objectId=1&versionId=1
            //
            ShaderProgram sp = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Wireframe.Shaders.WireframeVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Wireframe.Shaders.WireframeGS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Wireframe.Shaders.WireframeFS.glsl"));
            _lineWidth = (Uniform<float>)sp.Uniforms["u_halfLineWidth"];
            Width = 1;

            _colorUniform = (Uniform<Vector3F>)sp.Uniforms["u_color"];
            Color = Color.Black;

            _drawState = new DrawState(renderState, sp, context.CreateVertexArray(mesh, sp.VertexAttributes, BufferHint.StaticDraw));
            _primitiveType = mesh.PrimitiveType;
        }
Example #11
0
        public CPURelativeToEye(Context context, Vector3D[] positions, byte[] colors)
        {
            _sp = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Examples.CPURelativeToEye.Shaders.VS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Examples.Shaders.FS.glsl"));
            _modelViewPerspectiveMatrixRelativeToEye = (Uniform<Matrix4F>)(_sp.Uniforms["u_modelViewPerspectiveMatrixRelativeToEye"]);
            _pointSize = (Uniform<float>)_sp.Uniforms["u_pointSize"];

            ///////////////////////////////////////////////////////////////////

            _positions = new Vector3D[positions.Length];
            positions.CopyTo(_positions, 0);
            _positionsRelativeToEye = new Vector3F[_positions.Length];
            _eye = Vector3D.Zero;

            //
            // _positionBuffer is dynamic, and is written to when the camera moves.
            //
            _positionBuffer = Device.CreateVertexBuffer(BufferHint.DynamicDraw, ArraySizeInBytes.Size(_positionsRelativeToEye));

            _colorBuffer = Device.CreateVertexBuffer(BufferHint.StaticDraw, colors.Length);
            _colorBuffer.CopyFromSystemMemory(colors);

            _va = context.CreateVertexArray();
            _va.Attributes[_sp.VertexAttributes["position"].Location] =
                new VertexBufferAttribute(_positionBuffer, ComponentDatatype.Float, 3);
            _va.Attributes[_sp.VertexAttributes["color"].Location] =
                new VertexBufferAttribute(_colorBuffer, ComponentDatatype.UnsignedByte, 3, true, 0, 0);

            ///////////////////////////////////////////////////////////////////

            RenderState renderState = new RenderState();
            renderState.FacetCulling.Enabled = false;
            renderState.DepthTest.Enabled = false;
            renderState.ProgramPointSize = ProgramPointSize.Enabled;

            _drawState = new DrawState(renderState, _sp, _va);
        }
Example #12
0
        public RelativeToCenter(Context context, Vector3D[] positions, byte[] colors)
        {
            _sp = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Examples.RelativeToCenter.Shaders.VS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Examples.Shaders.FS.glsl"));
            _modelViewPerspectiveMatrixRelativeToCenter = (Uniform<Matrix4F>)(_sp.Uniforms["u_modelViewPerspectiveMatrixRelativeToCenter"]);
            _pointSize = (Uniform<float>)_sp.Uniforms["u_pointSize"];

            ///////////////////////////////////////////////////////////////////

            Mesh mesh = new Mesh();
            VertexAttributeFloatVector3 positionsAttribute = new VertexAttributeFloatVector3("position", positions.Length);
            VertexAttributeRGB colorAttribute = new VertexAttributeRGB("color", positions.Length);
            mesh.Attributes.Add(positionsAttribute);
            mesh.Attributes.Add(colorAttribute);

            _center = new AxisAlignedBoundingBox(positions).Center;
            for (int i = 0; i < positions.Length; ++i)
            {
                positionsAttribute.Values.Add((positions[i] - _center).ToVector3F());
            }

            for (int i = 0; i < colors.Length; ++i)
            {
                colorAttribute.Values.Add(colors[i]);
            }

            _va = context.CreateVertexArray(mesh, _sp.VertexAttributes, BufferHint.StaticDraw);

            ///////////////////////////////////////////////////////////////////

            RenderState renderState = new RenderState();
            renderState.FacetCulling.Enabled = false;
            renderState.DepthTest.Enabled = false;
            renderState.ProgramPointSize = ProgramPointSize.Enabled;

            _drawState = new DrawState(renderState, _sp, _va);
        }
        public TriangleMeshTerrainTile(Context context, TerrainTile tile)
        {
            ShaderProgram silhouetteSP = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.SilhouetteVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.SilhouetteGS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.SilhouetteFS.glsl"));

            Uniform<float> fillDistance = (Uniform<float>)silhouetteSP.Uniforms["u_fillDistance"];
            fillDistance.Value = 1.5f;
            _silhouetteHeightExaggeration = (Uniform<float>)silhouetteSP.Uniforms["u_heightExaggeration"];

            ShaderProgram sp = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.TerrainVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.TerrainFS.glsl"));

            _tileMinimumHeight = tile.MinimumHeight;
            _tileMaximumHeight = tile.MaximumHeight;

            _heightExaggeration = (Uniform<float>)sp.Uniforms["u_heightExaggeration"];
            _minimumHeight = (Uniform<float>)sp.Uniforms["u_minimumHeight"];
            _maximumHeight = (Uniform<float>)sp.Uniforms["u_maximumHeight"];
            HeightExaggeration = 1;

            ///////////////////////////////////////////////////////////////////

            Mesh mesh = new Mesh();
            mesh.PrimitiveType = PrimitiveType.Triangles;
            mesh.FrontFaceWindingOrder = WindingOrder.Counterclockwise;

            int numberOfPositions = tile.Resolution.X * tile.Resolution.Y;
            VertexAttributeDoubleVector3 positionsAttribute = new VertexAttributeDoubleVector3("position", numberOfPositions);
            IList<Vector3D> positions = positionsAttribute.Values;
            mesh.Attributes.Add(positionsAttribute);

            int numberOfPartitionsX = tile.Resolution.X - 1;
            int numberOfPartitionsY = tile.Resolution.Y - 1;
            int numberOfIndices = (numberOfPartitionsX * numberOfPartitionsY) * 6;
            IndicesUnsignedInt indices = new IndicesUnsignedInt(numberOfIndices);
            mesh.Indices = indices;

            //
            // Positions
            //
            Vector2D lowerLeft = tile.Extent.LowerLeft;
            Vector2D toUpperRight = tile.Extent.UpperRight - lowerLeft;

            int heightIndex = 0;
            for (int y = 0; y <= numberOfPartitionsY; ++y)
            {
                double deltaY = y / (double)numberOfPartitionsY;
                double currentY = lowerLeft.Y + (deltaY * toUpperRight.Y);

                for (int x = 0; x <= numberOfPartitionsX; ++x)
                {
                    double deltaX = x / (double)numberOfPartitionsX;
                    double currentX = lowerLeft.X + (deltaX * toUpperRight.X);
                    positions.Add(new Vector3D(currentX, currentY, tile.Heights[heightIndex++]));
                }
            }

            //
            // Indices
            //
            int rowDelta = numberOfPartitionsX + 1;
            int i = 0;
            for (int y = 0; y < numberOfPartitionsY; ++y)
            {
                for (int x = 0; x < numberOfPartitionsX; ++x)
                {
                    indices.AddTriangle(new TriangleIndicesUnsignedInt(i, i + 1, rowDelta + (i + 1)));
                    indices.AddTriangle(new TriangleIndicesUnsignedInt(i, rowDelta + (i + 1), rowDelta + i));
                    i += 1;
                }
                i += 1;
            }

            _drawState = new DrawState();
            _drawState.RenderState.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;
            _drawState.ShaderProgram = sp;
            _drawState.VertexArray = context.CreateVertexArray(mesh, sp.VertexAttributes, BufferHint.StaticDraw);

            _silhouetteDrawState = new DrawState();
            _silhouetteDrawState.RenderState.FacetCulling.Enabled = false;
            _silhouetteDrawState.RenderState.DepthMask = false;
            _silhouetteDrawState.VertexArray = _drawState.VertexArray;
            _silhouetteDrawState.ShaderProgram = silhouetteSP;

            _primitiveType = mesh.PrimitiveType;

            _clearColor = new ClearState();
            _clearColor.Buffers = ClearBuffers.ColorBuffer;
            
            //
            // Only depth needs to be cleared but include stencil for speed.
            //
            _clearDepthStencil = new ClearState();
            _clearDepthStencil.Buffers = ClearBuffers.DepthBuffer | ClearBuffers.StencilBuffer;
        }
Example #14
0
        public GlobeClipmapTerrain(Context context, RasterSource terrainSource, EsriRestImagery imagery, Ellipsoid ellipsoid, int clipmapPosts)
        {
            _terrainSource = terrainSource;
            _ellipsoid = ellipsoid;

            _clipmapPosts = clipmapPosts;
            _clipmapSegments = _clipmapPosts - 1;

            int clipmapLevels = _terrainSource.Levels.Count;
            _clipmapLevels = new ClipmapLevel[clipmapLevels];

            for (int i = 0; i < _clipmapLevels.Length; ++i)
            {
                _clipmapLevels[i] = new ClipmapLevel();
            }

            for (int i = 0; i < _clipmapLevels.Length; ++i)
            {
                RasterLevel terrainLevel = _terrainSource.Levels[i];
                _clipmapLevels[i].Terrain = terrainLevel;
                _clipmapLevels[i].HeightTexture = Device.CreateTexture2D(new Texture2DDescription(_clipmapPosts, _clipmapPosts, TextureFormat.Red32f));
                _clipmapLevels[i].NormalTexture = Device.CreateTexture2D(new Texture2DDescription(_clipmapPosts, _clipmapPosts, TextureFormat.RedGreenBlue32f));
                _clipmapLevels[i].CoarserLevel = i == 0 ? null : _clipmapLevels[i - 1];
                _clipmapLevels[i].FinerLevel = i == _clipmapLevels.Length - 1 ? null : _clipmapLevels[i + 1];

                // Aim for roughly one imagery texel per geometry texel.
                // Find the first imagery level that meets our resolution needs.
                double longitudeResRequired = terrainLevel.PostDeltaLongitude;
                double latitudeResRequired = terrainLevel.PostDeltaLatitude;
                RasterLevel imageryLevel = null;
                for (int j = 0; j < imagery.Levels.Count; ++j)
                {
                    imageryLevel = imagery.Levels[j];
                    if (imageryLevel.PostDeltaLongitude <= longitudeResRequired &&
                        imageryLevel.PostDeltaLatitude <= latitudeResRequired)
                    {
                        break;
                    }
                }

                _clipmapLevels[i].Imagery = imageryLevel;
                _clipmapLevels[i].ImageryWidth = (int)Math.Ceiling(_clipmapPosts * terrainLevel.PostDeltaLongitude / imageryLevel.PostDeltaLongitude);
                _clipmapLevels[i].ImageryHeight = (int)Math.Ceiling(_clipmapPosts * terrainLevel.PostDeltaLatitude / imageryLevel.PostDeltaLatitude);
                _clipmapLevels[i].ImageryTexture = Device.CreateTexture2D(new Texture2DDescription(_clipmapLevels[i].ImageryWidth, _clipmapLevels[i].ImageryHeight, TextureFormat.RedGreenBlue8, false));
            }

            _shaderProgram = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.GlobeClipmapVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.ClipmapTerrain.GlobeClipmapFS.glsl"));

            _fillPatchPosts = (clipmapPosts + 1) / 4; // M
            _fillPatchSegments = _fillPatchPosts - 1;

            // Create the MxM block used to fill the ring and the field.
            Mesh fieldBlockMesh = RectangleTessellator.Compute(
                new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(_fillPatchSegments, _fillPatchSegments)),
                _fillPatchSegments, _fillPatchSegments);
            _fillPatch = context.CreateVertexArray(fieldBlockMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            // Create the Mx3 block used to fill the space between the MxM blocks in the ring
            Mesh ringFixupHorizontalMesh = RectangleTessellator.Compute(
                new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(_fillPatchSegments, 2.0)),
                _fillPatchSegments, 2);
            _horizontalFixupPatch = context.CreateVertexArray(ringFixupHorizontalMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            // Create the 3xM block used to fill the space between the MxM blocks in the ring
            Mesh ringFixupVerticalMesh = RectangleTessellator.Compute(
                new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(2.0, _fillPatchSegments)),
                2, _fillPatchSegments);
            _verticalFixupPatch = context.CreateVertexArray(ringFixupVerticalMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            Mesh offsetStripHorizontalMesh = RectangleTessellator.Compute(
                new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(2 * _fillPatchPosts, 1.0)),
                2 * _fillPatchPosts, 1);
            _horizontalOffsetPatch = context.CreateVertexArray(offsetStripHorizontalMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            Mesh offsetStripVerticalMesh = RectangleTessellator.Compute(
                new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(1.0, 2 * _fillPatchPosts - 1)),
                1, 2 * _fillPatchPosts - 1);
            _verticalOffsetPatch = context.CreateVertexArray(offsetStripVerticalMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            Mesh centerMesh = RectangleTessellator.Compute(new RectangleD(new Vector2D(0.0, 0.0), new Vector2D(2.0, 2.0)), 2, 2);
            _centerPatch = context.CreateVertexArray(centerMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            Mesh degenerateTriangleMesh = CreateDegenerateTriangleMesh();
            _degenerateTrianglePatch = context.CreateVertexArray(degenerateTriangleMesh, _shaderProgram.VertexAttributes, BufferHint.StaticDraw);

            _patchOriginInClippedLevel = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_patchOriginInClippedLevel"];
            _levelScaleFactor = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_levelScaleFactor"];
            _levelZeroWorldScaleFactor = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_levelZeroWorldScaleFactor"];
            _levelOffsetFromWorldOrigin = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_levelOffsetFromWorldOrigin"];
            _heightExaggeration = (Uniform<float>)_shaderProgram.Uniforms["u_heightExaggeration"];
            _viewPosInClippedLevel = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_viewPosInClippedLevel"];
            _fineLevelOriginInCoarse = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_fineLevelOriginInCoarse"];
            _unblendedRegionSize = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_unblendedRegionSize"];
            _oneOverBlendedRegionSize = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_oneOverBlendedRegionSize"];
            _fineTextureOrigin = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_fineTextureOrigin"];
            _showBlendRegions = (Uniform<bool>)_shaderProgram.Uniforms["u_showBlendRegions"];
            _useBlendRegions = (Uniform<bool>)_shaderProgram.Uniforms["u_useBlendRegions"];
            _oneOverClipmapSize = (Uniform<float>)_shaderProgram.Uniforms["u_oneOverClipmapSize"];
            _color = (Uniform<Vector3F>)_shaderProgram.Uniforms["u_color"];
            _blendRegionColor = (Uniform<Vector3F>)_shaderProgram.Uniforms["u_blendRegionColor"];
            _terrainToImageryResolutionRatio = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_terrainToImageryResolutionRatio"];
            _terrainOffsetInImagery = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_terrainOffsetInImagery"];
            _oneOverImagerySize = (Uniform<Vector2F>)_shaderProgram.Uniforms["u_oneOverImagerySize"];
            _showImagery = (Uniform<bool>)_shaderProgram.Uniforms["u_showImagery"];
            _lighting = (Uniform<bool>)_shaderProgram.Uniforms["u_shade"];

            ((Uniform<Vector3F>)_shaderProgram.Uniforms["u_globeRadiiSquared"]).Value =
                ellipsoid.RadiiSquared.ToVector3F();
            
            _renderState = new RenderState();
            _renderState.FacetCulling.FrontFaceWindingOrder = fieldBlockMesh.FrontFaceWindingOrder;
            _primitiveType = fieldBlockMesh.PrimitiveType;

            float oneOverBlendedRegionSize = (float)(10.0 / _clipmapPosts);
            _oneOverBlendedRegionSize.Value = new Vector2F(oneOverBlendedRegionSize, oneOverBlendedRegionSize);

            float unblendedRegionSize = (float)(_clipmapSegments / 2 - _clipmapPosts / 10.0 - 1);
            _unblendedRegionSize.Value = new Vector2F(unblendedRegionSize, unblendedRegionSize);

            _useBlendRegions.Value = true;
            _showImagery.Value = true;

            _oneOverClipmapSize.Value = 1.0f / clipmapPosts;

            _updater = new ClipmapUpdater(context, _clipmapLevels);

            HeightExaggeration = 0.00001f;
        }
        public SceneGPURelativeToEyeLOD(Context context, Vector3D[] positions, byte[] colors)
        {
            _spHigh = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Examples.GPURelativeToEyeLOD.Shaders.HighPrecisionVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Examples.Shaders.FS.glsl"));
            _cameraEyeHigh = (Uniform<Vector3F>)_spHigh.Uniforms["u_cameraEyeHigh"];
            _cameraEyeLow = (Uniform<Vector3F>)_spHigh.Uniforms["u_cameraEyeLow"];
            _modelViewPerspectiveMatrixRelativeToEye = (Uniform<Matrix4F>)(_spHigh.Uniforms["u_modelViewPerspectiveMatrixRelativeToEye"]);
            _pointSizeHigh = (Uniform<float>)_spHigh.Uniforms["u_pointSize"];

            ///////////////////////////////////////////////////////////////////

            Vector3F[] positionsHigh = new Vector3F[positions.Length];
            Vector3F[] positionsLow = new Vector3F[positions.Length];

            for (int i = 0; i < positions.Length; ++i)
            {
                Vector3DToTwoVector3F(positions[i], out positionsHigh[i], out positionsLow[i]);
            }
            _center = positions[6];

            _positionBufferHigh = Device.CreateVertexBuffer(BufferHint.StaticDraw, ArraySizeInBytes.Size(positions));
            _positionBufferLow = Device.CreateVertexBuffer(BufferHint.StaticDraw, ArraySizeInBytes.Size(positions));
            _colorBuffer = Device.CreateVertexBuffer(BufferHint.StaticDraw, colors.Length);

            _positionBufferHigh.CopyFromSystemMemory(positionsHigh);
            _positionBufferLow.CopyFromSystemMemory(positionsLow);
            _colorBuffer.CopyFromSystemMemory(colors);

            _vaHigh = context.CreateVertexArray();
            _vaHigh.Attributes[_spHigh.VertexAttributes["positionHigh"].Location] =
                new VertexBufferAttribute(_positionBufferHigh, ComponentDatatype.Float, 3);
            _vaHigh.Attributes[_spHigh.VertexAttributes["positionLow"].Location] =
                new VertexBufferAttribute(_positionBufferLow, ComponentDatatype.Float, 3);
            _vaHigh.Attributes[_spHigh.VertexAttributes["color"].Location] =
                new VertexBufferAttribute(_colorBuffer, ComponentDatatype.UnsignedByte, 3, true, 0, 0);

            ///////////////////////////////////////////////////////////////////

            RenderState renderState = new RenderState();
            renderState.FacetCulling.Enabled = false;
            renderState.DepthTest.Enabled = false;
            renderState.ProgramPointSize = ProgramPointSize.Enabled;

            _drawStateHigh = new DrawState(renderState, _spHigh, _vaHigh);

            ///////////////////////////////////////////////////////////////////
            // Low Precision

            _spLow = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Examples.GPURelativeToEyeLOD.Shaders.LowPrecisionVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Examples.Shaders.FS.glsl"));
            _pointSizeLow = (Uniform<float>)_spLow.Uniforms["u_pointSize"];

            _vaLow = context.CreateVertexArray();
            _vaLow.Attributes[_spLow.VertexAttributes["position"].Location] =
                new VertexBufferAttribute(_positionBufferHigh, ComponentDatatype.Float, 3);
            _vaLow.Attributes[_spLow.VertexAttributes["color"].Location] =
                new VertexBufferAttribute(_colorBuffer, ComponentDatatype.UnsignedByte, 3, true, 0, 0);

            _drawStateLow = new DrawState(renderState, _spLow, _vaLow);
        }
        public VertexDisplacementMapTerrainTile(Context context, TerrainTile tile)
        {
            //
            // Upload height map as a one channel floating point texture
            //
            WritePixelBuffer pixelBuffer = Device.CreateWritePixelBuffer(PixelBufferHint.Stream,
                sizeof(float) * tile.Heights.Length);
            pixelBuffer.CopyFromSystemMemory(tile.Heights);

            _texture = Device.CreateTexture2DRectangle(new Texture2DDescription(
                tile.Resolution.X, tile.Resolution.Y, TextureFormat.Red32f));
            _texture.CopyFromBuffer(pixelBuffer, ImageFormat.Red, ImageDatatype.Float);
            
            ///////////////////////////////////////////////////////////////////

            ShaderProgram spTerrain = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.TerrainVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.TerrainFS.glsl"));
            _heightExaggerationUniform = (Uniform<float>)spTerrain.Uniforms["u_heightExaggeration"];
            ((Uniform<Vector2F>)spTerrain.Uniforms["u_positionToTextureCoordinate"]).Value = new Vector2F(
                (float)(1.0 / (double)(tile.Resolution.X)), 
                (float)( 1.0 / (double)(tile.Resolution.Y)));
            ((Uniform<Vector2F>)spTerrain.Uniforms["u_positionToRepeatTextureCoordinate"]).Value = new Vector2F(
                (float)(4.0 / (double)tile.Resolution.X),
                (float)(4.0 / (double)tile.Resolution.Y));
            
            ///////////////////////////////////////////////////////////////////

            ShaderProgram spNormals = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.NormalsVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.NormalsGS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.NormalsFS.glsl"));
            _heightExaggerationNormals = (Uniform<float>)spNormals.Uniforms["u_heightExaggeration"];
            _fillDistanceNormals = (Uniform<float>)spNormals.Uniforms["u_fillDistance"];
            ((Uniform<Vector3F>)spNormals.Uniforms["u_color"]).Value = Vector3F.Zero;

            ///////////////////////////////////////////////////////////////////

            ShaderProgram spWireframe = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.WireframeVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.WireframeGS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.VertexDisplacementMapTerrainTile.WireframeFS.glsl"));
            _lineWidthWireframe = (Uniform<float>)spWireframe.Uniforms["u_halfLineWidth"];
            _heightExaggerationWireframe = (Uniform<float>)spWireframe.Uniforms["u_heightExaggeration"];
            ((Uniform<Vector3F>)spWireframe.Uniforms["u_color"]).Value = Vector3F.Zero;
            
            ///////////////////////////////////////////////////////////////////

            Mesh mesh = RectangleTessellator.Compute(new RectangleD(new Vector2D(0.5, 0.5),
                new Vector2D((double)tile.Resolution.X - 0.5, (double)tile.Resolution.Y - 0.5)),
                tile.Resolution.X - 1, tile.Resolution.Y - 1);
            _va = context.CreateVertexArray(mesh, spWireframe.VertexAttributes, BufferHint.StaticDraw);
            _primitiveType = mesh.PrimitiveType;

            ///////////////////////////////////////////////////////////////////

            RenderState rsTerrain = new RenderState();
            rsTerrain.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;

            RenderState rsWireframe = new RenderState();
            rsWireframe.Blending.Enabled = true;
            rsWireframe.Blending.SourceRGBFactor = SourceBlendingFactor.SourceAlpha;
            rsWireframe.Blending.SourceAlphaFactor = SourceBlendingFactor.SourceAlpha;
            rsWireframe.Blending.DestinationRGBFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            rsWireframe.Blending.DestinationAlphaFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            rsWireframe.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;
            rsWireframe.DepthTest.Function = DepthTestFunction.LessThanOrEqual;

            RenderState rsNormals = new RenderState();
            rsNormals.FacetCulling.Enabled = false;
            rsNormals.Blending.Enabled = true;
            rsNormals.Blending.SourceRGBFactor = SourceBlendingFactor.SourceAlpha;
            rsNormals.Blending.SourceAlphaFactor = SourceBlendingFactor.SourceAlpha;
            rsNormals.Blending.DestinationRGBFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            rsNormals.Blending.DestinationAlphaFactor = DestinationBlendingFactor.OneMinusSourceAlpha;

            ///////////////////////////////////////////////////////////////////

            _drawStateTerrain = new DrawState(rsTerrain, spTerrain, _va);
            _drawStateWireframe = new DrawState(rsWireframe, spWireframe, _va);
            _drawStateNormals = new DrawState(rsNormals, spNormals, _va);

            _tileMinimumHeight = tile.MinimumHeight;
            _tileMaximumHeight = tile.MaximumHeight;

            _heightExaggeration = 1;
            _normalsAlgorithm = TerrainNormalsAlgorithm.ForwardDifference;
            _showTerrain = true;
            _dirty = true;
        }
Example #17
0
        public Plane(Context context)
        {
            Verify.ThrowIfNull(context);

            RenderState lineRS = new RenderState();
            lineRS.FacetCulling.Enabled = false;

            ShaderProgram lineSP = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Plane.Shaders.LineVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Plane.Shaders.LineGS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Plane.Shaders.LineFS.glsl"));
            _lineLogarithmicDepth = (Uniform<bool>)lineSP.Uniforms["u_logarithmicDepth"];
            _lineLogarithmicDepthConstant = (Uniform<float>)lineSP.Uniforms["u_logarithmicDepthConstant"];
            _lineFillDistance = (Uniform<float>)lineSP.Uniforms["u_fillDistance"];
            _lineColorUniform = (Uniform<Vector3F>)lineSP.Uniforms["u_color"];

            OutlineWidth = 1;
            OutlineColor = Color.Gray;

            ///////////////////////////////////////////////////////////////////

            RenderState fillRS = new RenderState();
            fillRS.FacetCulling.Enabled = false;
            fillRS.Blending.Enabled = true;
            fillRS.Blending.SourceRGBFactor = SourceBlendingFactor.SourceAlpha;
            fillRS.Blending.SourceAlphaFactor = SourceBlendingFactor.SourceAlpha;
            fillRS.Blending.DestinationRGBFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            fillRS.Blending.DestinationAlphaFactor = DestinationBlendingFactor.OneMinusSourceAlpha;
            
            ShaderProgram fillSP = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Plane.Shaders.FillVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Renderables.Plane.Shaders.FillFS.glsl"));
            _fillLogarithmicDepth = (Uniform<bool>)fillSP.Uniforms["u_logarithmicDepth"];
            _fillLogarithmicDepthConstant = (Uniform<float>)fillSP.Uniforms["u_logarithmicDepthConstant"];
            _fillColorUniform = (Uniform<Vector3F>)fillSP.Uniforms["u_color"];
            _fillAlphaUniform = (Uniform<float>)fillSP.Uniforms["u_alpha"];

            LogarithmicDepthConstant = 1;
            FillColor = Color.Gray;
            FillTranslucency = 0.5f;

            ///////////////////////////////////////////////////////////////////

            _positionBuffer = Device.CreateVertexBuffer(BufferHint.StaticDraw, 2 * 4 * SizeInBytes<Vector3F>.Value);

            ushort[] indices = new ushort[] 
            { 
                0, 1, 2, 3,                             // Line loop
                0, 1, 2, 0, 2, 3                        // Triangles
            };
            IndexBuffer indexBuffer = Device.CreateIndexBuffer(BufferHint.StaticDraw, indices.Length * sizeof(ushort));
            indexBuffer.CopyFromSystemMemory(indices);

            int stride = 2 * SizeInBytes<Vector3F>.Value;
            _va = context.CreateVertexArray();
            _va.Attributes[VertexLocations.PositionHigh] =
                new VertexBufferAttribute(_positionBuffer, ComponentDatatype.Float, 3, false, 0, stride);
            _va.Attributes[VertexLocations.PositionLow] =
                new VertexBufferAttribute(_positionBuffer, ComponentDatatype.Float, 3, false, SizeInBytes<Vector3F>.Value, stride);
            _va.IndexBuffer = indexBuffer;

            Show = true;
            ShowOutline = true;
            ShowFill = true;

            ///////////////////////////////////////////////////////////////////

            _drawStateLine = new DrawState(lineRS, lineSP, _va);
            _drawStateFill = new DrawState(fillRS, fillSP, _va);

            Origin = Vector3D.Zero;
            XAxis = Vector3D.UnitX;
            YAxis = Vector3D.UnitY;
        }
        public void Set(Context context, IList<Vector3D> positions)
        {
            //
            // This method expects that the positions are ordered in a repeated pattern of 
            // below terrain, above terrain pairs.
            //
            // Wall mesh
            //
            Mesh wallMesh = new Mesh();
            wallMesh.PrimitiveType = PrimitiveType.TriangleStrip;

            //
            // Positions
            //
            int numberOfLineSegments = (positions.Count / 2) - 1;
            int numberOfVertices = 2 + numberOfLineSegments + numberOfLineSegments;
            VertexAttributeDoubleVector3 positionsAttribute = new VertexAttributeDoubleVector3("position", numberOfVertices);
            IList<Vector3D> tempPositions = positionsAttribute.Values;
            wallMesh.Attributes.Add(positionsAttribute);
            foreach (Vector3D v in positions)
            {
                tempPositions.Add(v);
            }

            //
            // Vertex array
            //
            _wallVA = context.CreateVertexArray(wallMesh, _wallSP.VertexAttributes, BufferHint.StaticDraw);

            //
            // Line mesh
            //
            Mesh lineMesh = new Mesh();
            lineMesh.PrimitiveType = PrimitiveType.LineStrip;

            //
            // Positions
            //
            positionsAttribute = new VertexAttributeDoubleVector3("position", numberOfVertices);
            tempPositions = positionsAttribute.Values;
            lineMesh.Attributes.Add(positionsAttribute);
            foreach (Vector3D v in positions)
            {
                tempPositions.Add(v);
            }

            //
            // Indices
            //
            int numIndices = 4 * numberOfLineSegments;
            ushort[] indices = new ushort[numIndices];
            int baseIndex = 1;
            for (int i = 0; i < numIndices; i += 4, baseIndex += 2)
            {
                indices[i] = (ushort)baseIndex;
                indices[i + 1] = (ushort)(baseIndex - 1);
                indices[i + 2] = (ushort)(baseIndex + 1);
                indices[i + 3] = (ushort)(baseIndex + 2);
            }
            IndexBuffer indexBuffer = Device.CreateIndexBuffer(BufferHint.StaticDraw, numIndices * sizeof(ushort));
            indexBuffer.CopyFromSystemMemory(indices);

            //
            // Vertex array
            //
            _lineVA = context.CreateVertexArray(lineMesh, _wallSP.VertexAttributes, BufferHint.StaticDraw);
            _lineVA.IndexBuffer = indexBuffer;

            //
            // State
            //
            _wallDrawState = new DrawState();
            _wallDrawState.RenderState.FacetCulling.Enabled = false;
            _wallDrawState.RenderState.DepthTest.Enabled = false;
            _wallDrawState.RenderState.DepthMask = false;
            _wallDrawState.VertexArray = _lineVA;
            _wallDrawState.ShaderProgram = _wallSP;

            _shadowVolumePassOne = new DrawState();
            _shadowVolumePassOne.VertexArray = _lineVA;
            _shadowVolumePassOne.ShaderProgram = _shadowVolumeSP;
            _shadowVolumePassOne.RenderState.FacetCulling.Enabled = false;
            _shadowVolumePassOne.RenderState.DepthMask = false;
            _shadowVolumePassOne.RenderState.ColorMask = new ColorMask(false, false, false, false);
            StencilTest stOne = _shadowVolumePassOne.RenderState.StencilTest;
            stOne.Enabled = true;
            stOne.FrontFace.DepthFailStencilPassOperation = StencilOperation.Decrement;
            stOne.BackFace.DepthFailStencilPassOperation = StencilOperation.Increment;

            _shadowVolumePassTwo = new DrawState();
            _shadowVolumePassTwo.VertexArray = _lineVA;
            _shadowVolumePassTwo.ShaderProgram = _shadowVolumeSP;
            _shadowVolumePassTwo.RenderState.DepthMask = false;
            StencilTest stTwo = _shadowVolumePassTwo.RenderState.StencilTest;
            stTwo.Enabled = true;
            stTwo.FrontFace.DepthFailStencilPassOperation = StencilOperation.Zero;
            stTwo.FrontFace.DepthPassStencilPassOperation = StencilOperation.Zero;
            stTwo.FrontFace.Function = StencilTestFunction.NotEqual;
            stTwo.BackFace.DepthFailStencilPassOperation = StencilOperation.Zero;
            stTwo.BackFace.DepthPassStencilPassOperation = StencilOperation.Zero;
            stTwo.BackFace.Function = StencilTestFunction.NotEqual;
        }
        private void Update(Context context)
        {
            if (_dirtyVA)
            {
                Vector3D radii = new Vector3D(_tileResolution.X, _tileResolution.Y,
                    (_tileMaximumHeight - _tileMinimumHeight) * _heightExaggeration.Value);
                Vector3D halfRadii = 0.5 * radii;

                Mesh mesh = BoxTessellator.Compute(radii);

                //
                // TEXEL_SPACE_TODO:  Translate box so it is not centered at 
                // the origin - world space and texel space will match up.
                //
                IList<Vector3D> positions = ((VertexAttributeDoubleVector3)mesh.Attributes["position"]).Values;
                for (int i = 0; i < positions.Count; ++i)
                {
                    positions[i] = positions[i] + halfRadii;
                }

                if (_drawState.VertexArray != null)
                {
                    _drawState.VertexArray.Dispose();
                    _drawState.VertexArray = null;
                }
                _drawState.VertexArray = context.CreateVertexArray(mesh, _drawState.ShaderProgram.VertexAttributes, BufferHint.StaticDraw);
                _primitiveType = mesh.PrimitiveType;
                _drawState.RenderState.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;

                if (_wireframe != null)
                {
                    _wireframe.Dispose();
                }
                _wireframe = new Wireframe(context, mesh);
                _wireframe.FacetCullingFace = CullFace.Front;
                _wireframe.Width = 3;

                _dirtyVA = false;
            }
        }
Example #20
0
        private void Update(Context context)
        {
            if (_meshBuffers != null)
            {
                if (_drawState.VertexArray != null)
                {
                    _drawState.VertexArray.Dispose();
                    _drawState.VertexArray = null;
                }

                _drawState.VertexArray = context.CreateVertexArray(_meshBuffers);
                _meshBuffers = null;
            }
        }