public void ApplyMaterials(ComposedShader shader)
        {
            List <Material> materials;
            Appearance      appearance;

            materials  = new List <Material>();
            appearance = this.ItemsByType <Appearance>().FirstOrDefault();

            if (appearance != null)
            {
                materials = appearance.ItemsByType <Material>();
            }

            shader.SetFieldValue("materialsEnabled", materials.Any() ? 1 : 0);

            if (materials.Any())
            {
            }
            else
            {
                //shaderMaterials.Add(new ShaderMaterial()
                //{
                //     ambientIntensity = 0.1f,
                //     diffuseColor = new Vector4(0,0,0,0),
                //     emissiveColor = new Vector4(0,0,0,0),
                //    specularColor = new Vector4(1, 1, 1, 1),
                //    transparency = 1.0f,
                //    shininess = 0.2f
                //});
            }

            shader.SetFieldValue("materialsCount", shaderMaterials.Count);

            Buffering.BufferMaterials(shader, shaderMaterials, "materials");
        }
Beispiel #2
0
        public void EnableRendering(Vector3 origin)
        {
            Vector3[] lineColors;
            int[]     lineIndicies;

            bboxShader = ShaderCompiler.BuildDefaultShader();
            bboxShader.Link();

            lineColors   = null;
            lineIndicies = null;

            lines(LineColor, 12, out lineColors, out lineIndicies);

            _geo                 = new Box.BoxGeometry();
            _pack                = new PackedGeometry();
            _pack.Coloring       = true;
            _pack._indices       = _geo.Indices;
            _pack._coords        = _geo.Vertices;
            _pack.color          = X3DTypeConverters.Vec3ToFloatArray(lineColors);
            _pack._colorIndicies = lineIndicies;
            _pack.restartIndex   = -1;
            _pack.Interleave();
            _handle = _pack.CreateHandle();

            renderingEnabled = _handle.HasGeometry;

            InitBoundaryPoints(origin);
        }
        public override void Load()
        {
            base.Load();

            parentShader         = GetParent <ComposedShader>();
            parentProtoInterface = GetParent <ProtoInterface>();

            if (parentShader != null)
            {
                parentShader.Fields.Add(this);
            }
        }
        public void IncludeTesselationShaders(string tessControlShaderSource, string tessEvalShaderSource,
                                              string geometryShaderSource)
        {
            CurrentShader = ShaderCompiler.ApplyShader(DefaultShader.vertexShaderSource,
                                                       DefaultShader.fragmentShaderSource,
                                                       tessControlShaderSource,
                                                       tessEvalShaderSource,
                                                       geometryShaderSource);



            //IncludeComposedShader(CurrentShader);
        }
        public void IncludeComposedShader(ComposedShader shader)
        {
            shader.Link();
            shader.Use();

            CurrentShader = shader;

            RefreshDefaultUniforms(shader);

            if (shader.IsTessellator)
            {
                RefreshTessUniforms(shader);
            }

            ComposedShaders.Add(shader);
        }
        public void RefreshDefaultUniforms(ComposedShader shader = null)
        {
            if (shader == null)
            {
                shader = CurrentShader;
            }
            if (shader.HasErrors)
            {
                return;
            }

            //uniforms.a_position = GL.GetAttribLocation(shader.ShaderHandle, "position");
            //uniforms.a_normal = GL.GetAttribLocation(shader.ShaderHandle, "normal");
            //uniforms.a_color = GL.GetAttribLocation(shader.ShaderHandle, "color");
            //uniforms.a_texcoord = GL.GetAttribLocation(shader.ShaderHandle, "texcoord");

            uniforms.a_coloringEnabled  = GL.GetUniformLocation(shader.ShaderHandle, "coloringEnabled");
            uniforms.a_texturingEnabled = GL.GetUniformLocation(shader.ShaderHandle, "texturingEnabled");
            uniforms.sampler            = GL.GetUniformLocation(shader.ShaderHandle, "_MainTex");
        }
        public void RefreshTessUniforms(ComposedShader shader = null)
        {
            if (shader == null)
            {
                shader = CurrentShader;
            }
            if (shader.HasErrors)
            {
                return;
            }

            Uniforms.Modelview       = GL.GetUniformLocation(shader.ShaderHandle, "modelview");
            Uniforms.Projection      = GL.GetUniformLocation(shader.ShaderHandle, "projection");
            Uniforms.NormalMatrix    = GL.GetUniformLocation(shader.ShaderHandle, "normalmatrix");
            Uniforms.LightPosition   = GL.GetUniformLocation(shader.ShaderHandle, "LightPosition");
            Uniforms.AmbientMaterial = GL.GetUniformLocation(shader.ShaderHandle, "AmbientMaterial");
            Uniforms.DiffuseMaterial = GL.GetUniformLocation(shader.ShaderHandle, "DiffuseMaterial");
            //Uniforms.TessLevelInner = GL.GetUniformLocation(shader.ShaderHandle, "TessLevelInner");
            //Uniforms.TessLevelOuter = GL.GetUniformLocation(shader.ShaderHandle, "TessLevelOuter");
        }
        public override void PreRenderOnce(RenderingContext rc)
        {
            base.PreRenderOnce(rc);

            if (typeof(Text).IsInstanceOfType(geometry))
            {
                // 2D Text Shader, used to apply transparancy. Since alpha blending didnt work transparent background
                IncludeDefaultShader(ColorReplaceShader.vertexShaderSource,
                                     ColorReplaceShader.fragmentShaderSource);
            }
            else if (typeof(Sphere).IsInstanceOfType(geometry))
            {
                // TESSELLATION
                IncludeTesselationShaders(TriangleTessShader.tessControlShader,
                                          TriangleTessShader.tessEvalShader,
                                          TriangleTessShader.geometryShaderSource);

                //CurrentShader.SetFieldValue("spherical", 1);
            }
            else
            {
                CurrentShader = ShaderCompiler.BuildDefaultShader();
            }

            if (ComposedShaders.Any())
            {
                CurrentShader = ComposedShaders.First();
            }

            CurrentShader.Link();
            CurrentShader.Use();

            CollectMaterials();
            RefreshDefaultUniforms();

            Geometry(rc);
        }
        private void Geometry(RenderingContext rc)
        {
            if (geometry == null)
            {
                geometry = (X3DGeometryNode)this.Children.First(n => (typeof(X3DGeometryNode)).IsInstanceOfType(n));
            }

            if (geometry != null)
            {
                //TODO: refactor geometry interleaving code and make it callable here

                //TODO: should then be able to calculate bounding boxes of arbitrary geometry here

                geometry.CollectGeometry(rc, out _handle, out bbox, out coloring, out texturing);


                // BUFFER GEOMETRY
                if (_handle.NumVerticies3 > 0)
                {
                    // use CurrentShader
                }


                if (_handle.NumVerticies4 > 0)
                {
                    quadShader = ShaderCompiler.CreateNewInstance(CurrentShader, true);
                }

                loadedGeometry = _handle.HasGeometry;

                if (drawBoundingBox && bbox != null)
                {
                    bbox.EnableRendering(GetPosition(rc));
                }
            }
        }
        //[XmlIgnore]
        //public string ShaderSource;

        #region Rendering Methods

        public override void Load()
        {
            base.Load();

            parentShape  = GetParent <Shape>();
            parentShader = GetParent <ComposedShader>();

            string file;

            string[] mf_urls;

            if (!string.IsNullOrEmpty(ShaderSource))
            {
                LinkShaderSource(ShaderSource);
            }
            else if (Urls != null)
            {
                file = Urls.FirstOrDefault();

                if (!string.IsNullOrEmpty(file))
                {
                    _url = _url.TrimStart();

                    if (_url.StartsWith(X3DTypeConverters.DATA_TEXT_PLAIN))
                    {
                        ShaderSource = _url.Remove(0, X3DTypeConverters.DATA_TEXT_PLAIN.Length).TrimStart();

                        LinkShaderSource(ShaderSource);
                    }
                    else
                    {
                        file = file.Replace("\"", "");
                        file = SceneManager.CurrentLocation + "\\" + file;

                        if (X3DTypeConverters.IsMFString(file))
                        {
                            object resource;

                            mf_urls = X3DTypeConverters.GetMFString(file);

                            foreach (string url in mf_urls)
                            {
                                if (SceneManager.FetchSingle(url, out resource))
                                {
                                    Stream s;

                                    s = (Stream)resource;

                                    StreamReader sr = new StreamReader(s);
                                    ShaderSource = sr.ReadToEnd();

                                    s.Close();

                                    break;
                                }
                            }
                        }
                        else
                        {
                            ShaderSource = File.ReadAllText(file);

                            LinkShaderSource(ShaderSource);
                        }
                    }
                }
            }
        }
Beispiel #11
0
        public override void Load()
        {
            base.Load();

            int            i;
            int            a, b;
            PackedGeometry _pack;

            cubeHandle  = GeometryHandle.Zero;
            innerHandle = GeometryHandle.Zero;
            outerHandle = GeometryHandle.Zero;

            generateCube = !(string.IsNullOrEmpty(frontUrl) || string.IsNullOrEmpty(backUrl) ||
                             string.IsNullOrEmpty(topUrl) || string.IsNullOrEmpty(bottomUrl) ||
                             string.IsNullOrEmpty(leftUrl) || string.IsNullOrEmpty(rightUrl));

            //TODO: replace cube sides that arent available with transparent sides

            generateSkyAndGround = !(string.IsNullOrEmpty(groundColor) || string.IsNullOrEmpty(skyColor) ||
                                     string.IsNullOrEmpty(groundAngle) || string.IsNullOrEmpty(skyAngle));


            // TODO: later render both skydome and skybox together
            // Alpha values in skybox should provide a way to see through to skydome.
            // Skycolor sphere should be slightly larger than groundcolor hemisphere
            // and finally skybox should fit and be smaller than groundcolor hemisphere.

            if (generateSkyAndGround)
            {
                // Sphere
                // interpolate colors from groundColor and skyColor over hemispheres using specified sky and ground angles
                this.groundColors = X3DTypeConverters.MFVec3f(groundColor);
                this.groundAngles = X3DTypeConverters.Floats(groundAngle);
                this.skyColors    = X3DTypeConverters.MFVec3f(skyColor);
                this.skyAngles    = X3DTypeConverters.Floats(skyAngle);

                // Assign colors with matching angles
                colors = new Vector3[groundColors.Length + skyColors.Length];
                for (i = 0; i < skyColors.Length; i++)
                {
                    colors[i] = skyColors[i];
                }
                for (i = skyColors.Length; i < skyColors.Length + groundColors.Length; i++)
                {
                    colors[i] = groundColors[i - skyColors.Length];
                }
                angles    = new float[groundAngles.Length + skyAngles.Length + 2];
                angles[0] = 0;
                for (i = 0; i < skyAngles.Length; i++)
                {
                    angles[i + 1] = skyAngles[i];
                }
                angles[skyAngles.Length + 1] = 0;
                for (i = 0; i < groundAngles.Length; i++)
                {
                    angles[i + skyAngles.Length + 2] = 1.5f + groundAngles[i];
                }



                groundDivisor = (1.0f / groundColors.Length) * (float)Math.PI; // how many colors divided over 90 degrees (lower hemisphere)
                skyDivisor    = (1.0f / groundColors.Length) * (float)Math.PI; // how many colors divided over 90 degrees (upper hemisphere)

                // SKYDOME
                // outer sphere (sky)

                scaleSky     = Vector3.One * 6.0f;                                             // slightly bigger than ground hemisphere
                _shaderOuter = ShaderCompiler.ApplyShader(BackgroundShader.vertexShaderSource, // Make use of the BackgroundShader for Skydome Linear Interpolation
                                                          BackgroundShader.fragmentShaderSource);
                _shaderOuter.Link();

                List <Vertex> geometryOuterSphere = BuildSphereGeometryQuads(60, Vector3.Zero, 1.0f);
                Buffering.BufferShaderGeometry(geometryOuterSphere, out outerHandle.vbo4, out outerHandle.NumVerticies4);

                min = Vector3.Zero;
                max = Vector3.Zero;
                BoundingBox.CalculateBoundingBox(geometryOuterSphere, out max, out min);
                bboxOuter = max - min;

                // inner hemisphere (ground)

                //scaleGround = Vector3.One * 5.6f;
                //_shaderInner = ShaderCompiler.ApplyShader(BackgroundShader.vertexShaderSource,
                //                                 BackgroundShader.fragmentShaderSource);
                //_shaderInner.Link();

                //List<Vertex> geometryInnerHemisphere = BuildHemisphereGeometryQuads(60, new Vector3(0, 0.0f,0), 1.0f, false);
                //Buffering.BufferShaderGeometry(geometryInnerHemisphere, out innerHandle.vbo4, out innerHandle.NumVerticies4);

                //min = Vector3.Zero;
                //max = Vector3.Zero;
                //BoundingBox.CalculateBoundingBox(geometryInnerHemisphere, out max, out min);
                //bboxInner = max - min;


                skydomeTexture = MakeSkydomeTexture();
            }

            if (generateCube)
            {
                tex_cube = createCubeMapFromURIs();

                // SKYBOX
                // innermost skybox

                scaleCube = Vector3.One * 3.1f;

                _shaderInnerCube = ShaderCompiler.ApplyShader(CubeMapBackgroundShader.vertexShaderSource,
                                                              CubeMapBackgroundShader.fragmentShaderSource);
                _shaderInnerCube.Link();

                _pack           = new PackedGeometry();
                _pack._indices  = _cube.Indices;
                _pack._coords   = _cube.Vertices;
                _pack.Texturing = true;
                //_pack._colorIndicies = _boxGeometry.Colors;
                _pack._texCoords   = _cube.Texcoords;
                _pack.restartIndex = -1;

                _pack.Interleave();

                // BUFFER GEOMETRY
                cubeHandle = _pack.CreateHandle();
            }
        }
        //TODO: refactor Shader code
        public void IncludeDefaultShader(string vertexShaderSource, string fragmentShaderSource)
        {
            CurrentShader = ShaderCompiler.ApplyShader(vertexShaderSource, fragmentShaderSource);

            //IncludeComposedShader(CurrentShader);
        }
        public Matrix4 ApplyGeometricTransformations(RenderingContext rc, ComposedShader shader, SceneGraphNode context)
        {
            RefreshDefaultUniforms(shader);
            //RefreshMaterialUniforms();

            if (shader.IsTessellator)
            {
                RefreshTessUniforms(shader);
            }


            Matrix4 view = Matrix4.LookAt(new Vector3(4, 3, 3), // Camera is at (4,3,3), in World Space
                                          new Vector3(0, 0, 0), // and looks at the origin
                                          new Vector3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
                                          );

            Matrix4 model; // applied transformation hierarchy

            SceneGraphNode transform_context = context == null ? this : context;

            List <Transform> transformationHierarchy = transform_context
                                                       .AscendantByType <Transform>()
                                                       .Select(t => (Transform)t)
                                                       .Where(t => t.Hidden == false)
                                                       .ToList();

            Matrix4 modelview = Matrix4.Identity;// * rc.matricies.worldview;

            // using Def_Use/Figure02.1Hut.x3d Cone and Cylinder
            Vector3 x3dScale = new Vector3(0.06f, 0.06f, 0.06f); // scaling down to conform with X3D standard (note this was done manually and might need tweaking)

            //x3dScale = Vector3.One;

            Quaternion modelrotation      = Quaternion.Identity;
            Matrix4    modelLocalRotation = Matrix4.Identity;


            //if (rc.cam.OrbitLocalOrientation != Vector2.Zero)
            //{
            //    // Center of Rotation based on center of bounding box
            //    Quaternion qLocal = QuaternionExtensions.EulerToQuat(0, -rc.cam.OrbitLocalOrientation.X, -rc.cam.OrbitLocalOrientation.Y);
            //    Quaternion qAdjust = QuaternionExtensions.EulerToQuat(MathHelpers.PIOver2, 0.0f, 0.0f);

            //    Matrix4 mat4CenterOfRotation = Matrix4.CreateTranslation(centerOfRotation);
            //    Matrix4 origin = Matrix4.CreateTranslation(new Vector3(0, 0, 0));

            //    modelLocalRotation = mat4CenterOfRotation * Matrix4.CreateFromQuaternion(qLocal) * Matrix4.CreateFromQuaternion(qAdjust);
            //}

            //const float bbscale = 0.0329999961f;

            Vector3 centerOffset = Vector3.Zero;

            foreach (Transform transform in transformationHierarchy)
            {
                modelview = SceneEntity.ApplyX3DTransform(centerOffset,
                                                          Vector3.Zero,
                                                          transform.Scale,
                                                          Vector3.Zero,
                                                          transform.Translation, // * x3dScale,
                                                          modelview);

                //modelview *= Matrix4.CreateTranslation(transform.Translation * x3dScale);

                //modelrotation = new Quaternion(transform.Rotation.X, transform.Rotation.Y, transform.Rotation.Z, transform.Rotation.W);
                //modelrotations *= Matrix4.CreateFromQuaternion(modelrotation);

                //modelrotations *= MathHelpers.CreateRotation(ref modelrotation);
            }

            //Vector3 center = modelview.ExtractTranslation();
            //Vector3 centerOffsetVector = center + (bbox.Maximum - bbox.Minimum);
            //Matrix4 centerOffset = Matrix4.CreateTranslation(centerOffsetVector);



            model = modelview;

            Matrix4 cameraTransl = Matrix4.CreateTranslation(rc.cam.Position);

            Quaternion q = rc.cam.Orientation;

            Matrix4 cameraRot;

            cameraRot = Matrix4.CreateFromQuaternion(q); // cameraRot = MathHelpers.CreateRotation(ref q);


            Matrix4 MVP = ((modelLocalRotation * model) * cameraTransl) * cameraRot; // position and orient the Shape relative to the world and camera



            //shader.SetFieldValue("size", new Vector3(bbox.Width, bbox.Height, bbox.Depth) * bbscale);
            shader.SetFieldValue("modelview", ref MVP);                              //GL.UniformMatrix4(uniformModelview, false, ref rc.matricies.modelview);
            shader.SetFieldValue("projection", ref rc.matricies.projection);
            shader.SetFieldValue("camscale", rc.cam.Scale.X);                        //GL.Uniform1(uniformCameraScale, rc.cam.Scale.X);
            shader.SetFieldValue("X3DScale", rc.matricies.Scale);                    //GL.Uniform3(uniformX3DScale, rc.matricies.Scale);
            shader.SetFieldValue("coloringEnabled", this.coloring ? 1 : 0);          //GL.Uniform1(uniforms.a_coloringEnabled, 0);
            shader.SetFieldValue("texturingEnabled", this.texturingEnabled ? 1 : 0); //GL.Uniform1(uniforms.a_texturingEnabled, this.texturingEnabled ? 1 : 0);
            shader.SetFieldValue("lightingEnabled", 1);

            if (shader.IsBuiltIn == false)
            {
                shader.ApplyFieldsAsUniforms(rc);
            }

            return(MVP);
        }