Exemple #1
0
        public BasicEntity(ModelDefinition modelbb, MaterialEffect material, Vector3 position, double angleZ, double angleX, double angleY, Vector3 scale, MeshMaterialLibrary library = null, Entity physicsObject = null)
        {
            Id                  = IdGenerator.GetNewId();
            Name                = GetType().Name + " " + Id;
            WorldTransform      = new TransformMatrix(Matrix.Identity, Id);
            ModelDefinition     = modelbb;
            Model               = modelbb.Model;
            BoundingBox         = modelbb.BoundingBox;
            BoundingBoxOffset   = modelbb.BoundingBoxOffset;
            SignedDistanceField = modelbb.SDF;

            Material = material;
            Position = position;
            Scale    = scale;

            RotationMatrix = Matrix.CreateRotationX((float)angleX) * Matrix.CreateRotationY((float)angleY) *
                             Matrix.CreateRotationZ((float)angleZ);

            if (library != null)
            {
                RegisterInLibrary(library);
            }

            if (physicsObject != null)
            {
                RegisterPhysics(physicsObject);
            }

            WorldTransform.World        = Matrix.CreateScale(Scale) * RotationMatrix * Matrix.CreateTranslation(Position);
            WorldTransform.Scale        = Scale;
            WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));
        }
Exemple #2
0
    public void RefreshMaterial()
    {
        if (m_Render == null)
        {
            m_Render = GetComponent <Renderer>();
            if (m_Render == null)
            {
                return;
            }
        }
        int i = 0;

        for (i = 0; i < m_Render.sharedMaterials.Length; i++)
        {
            if (m_MaterialEffects.Count <= i)
            {
                MaterialEffect matEffect = new MaterialEffect(m_Render.sharedMaterials[i]);
                m_MaterialEffects.Add(matEffect);
            }
            else
            {
                m_MaterialEffects[i].ReInitMaterial(m_Render.sharedMaterials[i]);
            }
        }
        for (int j = m_MaterialEffects.Count - 1; i <= j; j--)
        {
            m_MaterialEffects.RemoveAt(j);
        }
        UpdateRenderLayer();
    }
Exemple #3
0
        public BasicEntity(Model model, MaterialEffect material, Vector3 position, double angleZ, double angleX, double angleY, Vector3 scale, MeshMaterialLibrary library = null, Entity physicsObject = null)
        {
            Id             = IdGenerator.GetNewId();
            WorldTransform = new TransformMatrix(Matrix.Identity, Id);

            Position = position;
            AngleZ   = angleZ;
            AngleX   = angleX;
            AngleY   = angleY;
            Scale    = scale;

            RotationMatrix = Matrix.CreateRotationX((float)AngleX) * Matrix.CreateRotationY((float)AngleY) *
                             Matrix.CreateRotationZ((float)AngleZ);

            Material = material;
            Model    = model;

            if (library != null)
            {
                RegisterInLibrary(library);
            }

            if (physicsObject != null)
            {
                RegisterPhysics(physicsObject);
            }
        }
 public bool HasMaterial(MaterialEffect mat)
 {
     if (!GameSettings.g_BatchByMaterial)
     {
         return(false);
     }
     return(mat.Equals(_material));
 }
        public void Register(MaterialEffect mat, ModelMeshPart mesh, TransformMatrix worldMatrix, BoundingSphere boundingSphere) //These should be ordered by likeness, so I don't get opaque -> transparent -> opaque
        {
            bool found = false;

            if (mat == null)
            {
                var effect = mesh.Effect as MaterialEffect;
                if (effect != null)
                {
                    mat = effect;
                }
                else
                {
                    mat = new MaterialEffect(mesh.Effect);
                }
            }

            //Check if we already have a material like that, if yes put it in there!
            for (var i = 0; i < Index; i++)
            {
                MaterialLibrary matLib = MaterialLib[i];
                if (matLib.HasMaterial(mat))
                {
                    matLib.Register(mesh, worldMatrix, boundingSphere);
                    found = true;
                    break;
                }
            }

            //We have no MatLib for that specific Material yet. Make a new one.
            if (!found)
            {
                MaterialLib[Index] = new MaterialLibrary();
                MaterialLib[Index].SetMaterial(ref mat);
                MaterialLib[Index].Register(mesh, worldMatrix, boundingSphere);
                Index++;
            }

            //If we exceeded our array length, make the array bigger.
            if (Index >= MaterialLib.Length)
            {
                MaterialLibrary[] tempLib = new MaterialLibrary[Index + 1];
                MaterialLib.CopyTo(tempLib, 0);
                MaterialLib = tempLib;

                MaterialLibPointer = new int[Index + 1];
                //sort from 0 to Index
                for (int j = 0; j < MaterialLibPointer.Length; j++)
                {
                    MaterialLibPointer[j] = j;
                }
                SortByDistance();
            }
        }
        public int GetMaterialInfoIndex(string name, MaterialEffect effect)
        {
            for (int i = 0; i < materials.Count; i++)
            {
                if (materials[i].Name == name && materials[i].Effect == effect)
                {
                    return(i);
                }
            }

            return(-1);
        }
        public static void SetMaterialEffect(MaterialEffect value,
                                             Graphic graphic, VertexMaterialData materialProperties, ref MaterialEffect effect, ref string materialType)
        {
            if (effect == value && graphic.material != null)
            {
                return;
            }

            UpdateMaterial(graphic, materialProperties, ref effect, ref materialType);

            effect = value;
        }
 public BasicEntity(Model model, MaterialEffect material, Vector3 position, Matrix rotationMatrix, Vector3 scale)
 {
     Id             = IdGenerator.GetNewId();
     Name           = GetType().Name + " " + Id;
     WorldTransform = new TransformMatrix(Matrix.Identity, Id);
     Model          = model;
     Material       = material;
     Position       = position;
     RotationMatrix = rotationMatrix;
     Scale          = scale;
     RotationMatrix = rotationMatrix;
 }
Exemple #9
0
 public void SetMaterialSettings(MaterialEffect material, MeshMaterialLibrary.RenderType renderType)
 {
     if (renderType == MeshMaterialLibrary.RenderType.ShadowOmnidirectional)
     {
         //Check if we have a mask texture
         if (material.HasMask)
         {
             _pass = Passes.OmnidirectionalAlpha;
             _MaskTexture.SetValue(material.Mask);
         }
         else
         {
             _pass = Passes.Omnidirectional;
         }
     }
 }
        private static void UpdateMaterial(
            Graphic graphic, VertexMaterialData materialProperties, ref MaterialEffect effect, ref string materialType)
        {
            var info = Materials.Instance.GetMaterialInfo(materialType, effect);

            materialProperties.Clear();
            if (info != null)
            {
                graphic.material = info.Material;
                info.Properties.CopyTo(materialProperties);
            }
            else
            {
                graphic.material = null;
            }
        }
Exemple #11
0
 private void PerMaterialSettings(RenderType renderType, MaterialEffect material, IRenderModule renderModule)
 {
     if (material.RenderCClockwise)
     {
         graphicsDevice.RasterizerState = RasterizerState.CullClockwise;
     }
     else if (renderType == RenderType.ShadowOmnidirectional)
     {
         ((ShadowMapRenderModule)renderModule).SetMaterialSettings(material, renderType);
     }
     //if (renderType == RenderType.IdRender || renderType == RenderType.IdOutline)
     //{
     //    Shaders.IdRenderEffectParameterColorId.SetValue(Color.Transparent.ToVector4());
     //}
     //todo: We only need textures for non shadow mapping, right? Not quite actually, for alpha textures we need materials
     else if (renderType == RenderType.Opaque)
     {
         ((GBufferRenderModule)renderModule).SetMaterialSettings(material);
     }
 }
        private void DeleteFromRegistry(MaterialEffect mat, ModelMeshPart mesh, TransformMatrix worldMatrix)
        {
            for (var i = 0; i < Index; i++)
            {
                MaterialLibrary matLib = MaterialLib[i];
                //if (matLib.HasMaterial(mat))
                //{
                if (matLib.DeleteFromRegistry(mesh, worldMatrix))
                {
                    for (var j = i; j < Index - 1; j++)
                    {
                        //slide down one
                        MaterialLib[j] = MaterialLib[j + 1];
                    }
                    Index--;

                    break;
                }
                //}
            }
        }
Exemple #13
0
        public BasicEntity(ModelDefinition modelbb, MaterialEffect material, Vector3 position, Matrix rotationMatrix, Vector3 scale)
        {
            Id                  = IdGenerator.GetNewId();
            Name                = GetType().Name + " " + Id;
            WorldTransform      = new TransformMatrix(Matrix.Identity, Id);
            Model               = modelbb.Model;
            ModelDefinition     = modelbb;
            BoundingBox         = modelbb.BoundingBox;
            BoundingBoxOffset   = modelbb.BoundingBoxOffset;
            SignedDistanceField = modelbb.SDF;

            Material       = material;
            Position       = position;
            RotationMatrix = rotationMatrix;
            Scale          = scale;
            RotationMatrix = rotationMatrix;

            WorldTransform.World        = Matrix.CreateScale(Scale) * RotationMatrix * Matrix.CreateTranslation(Position);
            WorldTransform.Scale        = Scale;
            WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));
        }
Exemple #14
0
        /// <summary>
        /// Create a basic rendered model with custom material
        /// </summary>
        /// <param name="model"></param>
        /// <param name="materialEffect">custom material</param>
        /// <param name="position"></param>
        /// <param name="angleX"></param>
        /// <param name="angleY"></param>
        /// <param name="angleZ"></param>
        /// <param name="scale"></param>
        /// <param name="PhysicsEntity">attached physical object</param>
        /// <param name="hasStaticPhysics">if "true" a static mesh will be computed based on the model mesh. Other physical objects can collide with the entity</param>
        /// <returns>returns the basicEntity we created</returns>
        private BasicEntity AddEntity(Model model, MaterialEffect materialEffect, Vector3 position, double angleX, double angleY, double angleZ, float scale, Entity PhysicsEntity = null, bool hasStaticPhysics = false)
        {
            BasicEntity entity = new BasicEntity(model,
                                                 materialEffect,
                                                 position: position,
                                                 angleZ: angleZ,
                                                 angleX: angleX,
                                                 angleY: angleY,
                                                 scale: Vector3.One * scale,
                                                 library: MeshMaterialLibrary,
                                                 physicsObject: PhysicsEntity);

            BasicEntities.Add(entity);

            if (hasStaticPhysics)
            {
                AddStaticPhysics(entity);
            }

            return(entity);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="mat">if "null" it will be taken from the model!</param>
        /// <param name="model"></param>
        /// <param name="worldMatrix"></param>
        public void Register(MaterialEffect mat, Model model, TransformMatrix worldMatrix)
        {
            if (model == null)
            {
                return;
            }

            //if (mat == null)
            //{
            //    throw new NotImplementedException();
            //}

            for (int index = 0; index < model.Meshes.Count; index++)
            {
                var mesh = model.Meshes[index];
                for (int i = 0; i < mesh.MeshParts.Count; i++)
                {
                    ModelMeshPart meshPart = mesh.MeshParts[i];
                    Register(mat, meshPart, worldMatrix, mesh.BoundingSphere);
                }
            }
        }
Exemple #16
0
        //public override void preparePerFrame(Renderable r) { }
        //public override void preparePerViewBegin(View v) { }
        //public override void preparePerView(Renderable r, View v) { }
        //public override void preparePerViewFinalize(View v) { }
        //public override void preparePerPassBegin(Pass p) { }

        public override void preparePerPass(Renderable r, Pass p)
        {
            TerrainRenderable tr = r as TerrainRenderable;
            Chunk             c  = tr.myChunk;

            if (myRenderManager.isLoaded(c, bufferChunk) == false)
            {
                myRenderManager.loadChunk(c, bufferChunk);
                return;
            }

            //DebugRenderer.addOffsetCube(c.myLocation, c.mySize, Color4.Blue, Fill.WIREFRAME, false, 0.0f);

            DrawChunk dc = myRenderManager.findDrawChunk(c);

            if (dc != null)
            {
                Matrix4 m = Matrix4.CreateTranslation(c.myLocation);

                //add solid render info
                if (dc.solidCount > 0)
                {
                    MaterialEffect effect              = getEffect(p.technique, 1);
                    PipelineState  pipeline            = effect.createPipeline(MaterialManager.visualMaterial);
                    RenderQueue <TerrainRenderInfo> rq = p.findRenderQueue(pipeline.id) as RenderQueue <TerrainRenderInfo>;
                    if (rq == null)
                    {
                        rq            = Renderer.device.createRenderQueue <TerrainRenderInfo>(effect.createPipeline(MaterialManager.visualMaterial));
                        rq.name       = rq.myPipeline.shaderState.shaderProgram.name + "-" + "opaque";
                        rq.visualizer = this;
                        p.registerQueue(rq);
                    }

                    TerrainRenderInfo info = rq.nextInfo();
                    info.distToCamera = (p.view.camera.position - c.myLocation).Length;
                    info.model        = m;
                    info.myType       = TerrainRenderInfo.Type.SOLID;
                    info.count        = dc.solidCount;
                    info.offset       = dc.solidOffset;
                    info.sortId       = getSortId(info);
                    effect.updateRenderState(MaterialManager.visualMaterial, info.renderState);

                    addDraw(info.offset, info.count, info.model);
                }

                //add transparent render info
                if (dc.transCount > 0)
                {
                    MaterialEffect effect              = getEffect(p.technique, 2);
                    PipelineState  pipeline            = effect.createPipeline(MaterialManager.visualMaterial);
                    RenderQueue <TerrainRenderInfo> rq = p.findRenderQueue(pipeline.id) as RenderQueue <TerrainRenderInfo>;
                    if (rq == null)
                    {
                        rq            = Renderer.device.createRenderQueue <TerrainRenderInfo>(effect.createPipeline(MaterialManager.visualMaterial));
                        rq.name       = rq.myPipeline.shaderState.shaderProgram.name + "-" + "transparent";
                        rq.visualizer = this;
                        p.registerQueue(rq);
                    }

                    TerrainRenderInfo info = rq.nextInfo();
                    info.distToCamera = (p.view.camera.position - c.myLocation).Length;
                    info.model        = m;
                    info.myType       = TerrainRenderInfo.Type.TRANS;
                    info.count        = dc.transCount;
                    info.offset       = dc.transOffset;
                    info.sortId       = getSortId(info);
                    effect.updateRenderState(MaterialManager.visualMaterial, info.renderState);

                    addDraw(info.offset, info.count, info.model);
                }

                //add water renderinfo
                if (dc.waterCount > 0)
                {
                    MaterialEffect effect              = getEffect(p.technique, 3);
                    PipelineState  pipeline            = effect.createPipeline(MaterialManager.visualMaterial);
                    RenderQueue <TerrainRenderInfo> rq = p.findRenderQueue(pipeline.id) as RenderQueue <TerrainRenderInfo>;
                    if (rq == null)
                    {
                        rq            = Renderer.device.createRenderQueue <TerrainRenderInfo>(effect.createPipeline(MaterialManager.visualMaterial));
                        rq.name       = rq.myPipeline.shaderState.shaderProgram.name + "-" + "water";
                        rq.visualizer = this;
                        p.registerQueue(rq);
                    }

                    TerrainRenderInfo info = rq.nextInfo();
                    info.distToCamera = (p.view.camera.position - c.myLocation).Length;
                    info.model        = m;
                    info.myType       = TerrainRenderInfo.Type.WATER;
                    info.count        = dc.waterCount;
                    info.offset       = dc.waterOffset;
                    info.sortId       = getSortId(info);
                    effect.updateRenderState(MaterialManager.visualMaterial, info.renderState);

                    addDraw(info.offset, info.count, info.model);
                }
            }
        }
Exemple #17
0
        public void Draw(RenderType renderType, Matrix viewProjection, bool lightViewPointChanged = false, bool hasAnyObjectMoved = false, bool outlined = false, int outlineId = 0, Matrix?view = null, IRenderModule renderModule = null)
        {
            SetBlendAndRasterizerState(renderType);

            if (renderType == RenderType.ShadowLinear || renderType == RenderType.ShadowOmnidirectional)
            {
                //For shadowmaps we need to find out whether any object has moved and if so if it is rendered. If yes, redraw the whole frame, if no don't do anything
                if (!CheckShadowMapUpdateNeeds(lightViewPointChanged, hasAnyObjectMoved))
                {
                    return;
                }
            }

            for (int index1 = 0; index1 < Index; index1++)
            {
                MaterialLibrary matLib = MaterialLib[index1];

                if (matLib.Index < 1)
                {
                    continue;
                }

                //if none of this materialtype is drawn continue too!
                bool isUsed = false;

                for (int i = 0; i < matLib.Index; i++)
                {
                    MeshLibrary meshLib = matLib.GetMeshLibrary()[i];

                    //If it's set to "not rendered" skip
                    for (int j = 0; j < meshLib.Rendered.Length; j++)
                    {
                        if (meshLib.Rendered[j])
                        {
                            isUsed = true;
                            //if (meshLib.GetWorldMatrices()[j].HasChanged)
                            //    hasAnyObjectMoved = true;
                        }

                        if (isUsed)    // && hasAnyObjectMoved)
                        {
                            break;
                        }
                    }
                }

                if (!isUsed)
                {
                    continue;
                }

                //Count the draws of different materials!

                MaterialEffect material = matLib.GetMaterial();

                //Check if alpha or opaque!
                if (renderType == RenderType.Opaque && material.IsTransparent || renderType == RenderType.Opaque && material.Type == MaterialEffect.MaterialTypes.ForwardShaded)
                {
                    continue;
                }
                if (renderType == RenderType.Hologram && material.Type != MaterialEffect.MaterialTypes.Hologram)
                {
                    continue;
                }
                if (renderType != RenderType.Hologram && material.Type == MaterialEffect.MaterialTypes.Hologram)
                {
                    continue;
                }

                if (renderType == RenderType.SubsurfaceScattering &&
                    material.Type != MaterialEffect.MaterialTypes.SubsurfaceScattering)
                {
                    continue;
                }

                if (renderType == RenderType.Forward &&
                    material.Type != MaterialEffect.MaterialTypes.ForwardShaded)
                {
                    continue;
                }

                //Set the appropriate Shader for the material
                if (renderType == RenderType.ShadowOmnidirectional || renderType == RenderType.ShadowLinear)
                {
                    if (!material.HasShadow)
                    {
                        continue;
                    }
                }

                if (renderType != RenderType.IdRender && renderType != RenderType.IdOutline)
                {
                    GameStats.MaterialDraws++;
                }

                PerMaterialSettings(renderType, material, renderModule);

                for (int i = 0; i < matLib.Index; i++)
                {
                    MeshLibrary meshLib = matLib.GetMeshLibrary()[i];

                    //Initialize the mesh VB and IB
                    graphicsDevice.SetVertexBuffer(meshLib.GetMesh().VertexBuffer);
                    graphicsDevice.Indices = (meshLib.GetMesh().IndexBuffer);
                    int primitiveCount = meshLib.GetMesh().PrimitiveCount;
                    int vertexOffset   = meshLib.GetMesh().VertexOffset;
                    //int vCount = meshLib.GetMesh().NumVertices;
                    int startIndex = meshLib.GetMesh().StartIndex;

                    //Now draw the local meshes!
                    for (int index = 0; index < meshLib.Index; index++)
                    {
                        //If it's set to "not rendered" skip
                        //if (!meshLib.GetWorldMatrices()[index].Rendered) continue;
                        if (!meshLib.Rendered[index])
                        {
                            continue;
                        }

                        Matrix localWorldMatrix = meshLib.GetWorldMatrices()[index].World;

                        if (!ApplyShaders(renderType, renderModule, localWorldMatrix, view, viewProjection, meshLib, index,
                                          outlineId, outlined))
                        {
                            continue;
                        }
                        GameStats.MeshDraws++;

                        graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, vertexOffset, startIndex,
                                                             primitiveCount);
                    }
                }

                //Reset to
                if (material.RenderCClockwise)
                {
                    graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
                }
            }
        }
        public MaterialInfo GetMaterialInfo(string name, MaterialEffect e)
        {
            MaterialInfo result = materials.FirstOrDefault((o) => o.Name == name && o.Effect == e);

            return(result);
        }
        public void Draw(RenderType renderType, GraphicsDevice graphicsDevice, Matrix viewProjection, bool lightViewPointChanged = false, bool hasAnyObjectMoved = false, bool outlined = false, int outlineId = 0, Matrix?view = null)
        {
            //if (renderType != RenderType.Alpha)
            //{
            graphicsDevice.BlendState = BlendState.Opaque;
            //    graphicsDevice.RasterizerState = RasterizerState.CullNone;
            //}

            //For shadowmaps we need to find out whether any object has moved and if so if it is rendered. If yes, redraw the whole frame, if no don't do anything
            if (!lightViewPointChanged && hasAnyObjectMoved)
            {
                bool discardFrame = true;

                for (int index1 = 0; index1 < Index; index1++)
                {
                    MaterialLibrary matLib = MaterialLib[index1];

                    //We determined beforehand whether something changed this frame
                    if (matLib.HasChangedThisFrame)
                    {
                        for (int i = 0; i < matLib.Index; i++)
                        {
                            //Now we have to check whether we have a rendered thing in here
                            MeshLibrary meshLib = matLib.GetMeshLibrary()[i];
                            for (int index = 0; index < meshLib.Index; index++)
                            {
                                //If it's set to "not rendered" skip
                                for (int j = 0; j < meshLib.Rendered.Length; j++)
                                {
                                    if (meshLib.Rendered[j])
                                    {
                                        discardFrame = false;
                                        break;
                                    }
                                }

                                if (!discardFrame)
                                {
                                    break;
                                }
                            }
                        }
                        if (!discardFrame)
                        {
                            break;
                        }
                    }
                }

                if (discardFrame)
                {
                    return;
                }

                //graphicsDevice.Clear(new Color(0.51f, 0.501f, 0, 0));
                graphicsDevice.Clear(Color.TransparentBlack);
            }

            for (int index1 = 0; index1 < Index; index1++)
            {
                MaterialLibrary matLib = MaterialLib[index1];

                if (matLib.Index < 1)
                {
                    continue;
                }

                //if none of this materialtype is drawn continue too!
                bool isUsed = false;

                for (int i = 0; i < matLib.Index; i++)
                {
                    MeshLibrary meshLib = matLib.GetMeshLibrary()[i];
                    for (int index = 0; index < meshLib.Index; index++)
                    {
                        //If it's set to "not rendered" skip
                        for (int j = 0; j < meshLib.Rendered.Length; j++)
                        {
                            if (meshLib.Rendered[j])
                            {
                                isUsed = true;
                                //if (meshLib.GetWorldMatrices()[j].HasChanged)
                                //    hasAnyObjectMoved = true;
                            }

                            if (isUsed)// && hasAnyObjectMoved)
                            {
                                break;
                            }
                        }

                        if (isUsed)// && hasAnyObjectMoved)
                        {
                            break;
                        }
                    }
                }

                if (!isUsed)
                {
                    continue;
                }

                //Count the draws of different materials!

                MaterialEffect material = /*GameSettings.DebugDrawUntextured==2 ? Art.DefaultMaterial :*/ matLib.GetMaterial();

                //Check if alpha or opaque!

                Effect shader = null;

                //todo: We only need textures for non shadow mapping, right? Not quite actually, for alpha textures we need materials
                if (renderType == RenderType.TextureBuffer)
                {
                    shader = Shaders.GBufferEffect;

                    if (GameSettings.d_defaultMaterial)
                    {
                        Shaders.GBufferEffectParameter_Material_DiffuseColor.SetValue(Color.Gray.ToVector3());
                        Shaders.GBufferEffectParameter_Material_Roughness.SetValue(GameSettings.m_defaultRoughness > 0
                                ? GameSettings.m_defaultRoughness
                                : 0.3f);
                        Shaders.GBufferEffectParameter_Material_Metallic.SetValue(0.0f);
                        Shaders.GBufferEffectParameter_Material_MaterialType.SetValue(0);
                        Shaders.GBufferEffect.CurrentTechnique = Shaders.GBufferEffectTechniques_DrawBasic;
                    }
                    else
                    {
                        if (material.HasDisplacement)
                        {
                            Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                            Shaders.GBufferEffectParameter_Material_NormalMap.SetValue(material.NormalMap);
                            Shaders.GBufferEffectParameter_Material_DisplacementMap.SetValue(material.DisplacementMap);
                            Shaders.GBufferEffect.CurrentTechnique =
                                Shaders.GBufferEffectTechniques_DrawTextureDisplacement;
                        }
                        else if (material.HasMask) //Has diffuse for sure then
                        {
                            if (material.HasNormalMap && material.HasRoughnessMap)
                            {
                                Shaders.GBufferEffectParameter_Material_MaskMap.SetValue(material.Mask);
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_NormalMap.SetValue(material.NormalMap);
                                Shaders.GBufferEffectParameter_Material_RoughnessMap.SetValue(material.RoughnessMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecularNormalMask;
                            }

                            else if (material.HasNormalMap)
                            {
                                Shaders.GBufferEffectParameter_Material_MaskMap.SetValue(material.Mask);
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_NormalMap.SetValue(material.NormalMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureNormalMask;
                            }

                            else if (material.HasRoughnessMap)
                            {
                                Shaders.GBufferEffectParameter_Material_MaskMap.SetValue(material.Mask);
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_RoughnessMap.SetValue(material.RoughnessMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecularMask;
                            }
                            else
                            {
                                Shaders.GBufferEffectParameter_Material_MaskMap.SetValue(material.Mask);
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecularMask;
                            }
                        }
                        else
                        {
                            if (material.HasNormalMap && material.HasRoughnessMap && material.HasDiffuse &&
                                material.HasMetallic)
                            {
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_NormalMap.SetValue(material.NormalMap);
                                Shaders.GBufferEffectParameter_Material_RoughnessMap.SetValue(material.RoughnessMap);
                                Shaders.GBufferEffectParameter_Material_MetallicMap.SetValue(material.MetallicMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecularNormalMetallic;
                            }

                            else if (material.HasNormalMap && material.HasRoughnessMap && material.HasDiffuse)
                            {
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_NormalMap.SetValue(material.NormalMap);
                                Shaders.GBufferEffectParameter_Material_RoughnessMap.SetValue(material.RoughnessMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecularNormal;
                            }

                            else if (material.HasNormalMap && material.HasDiffuse)
                            {
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_NormalMap.SetValue(material.NormalMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureNormal;
                            }

                            else if (material.HasMetallic && material.HasRoughnessMap && material.HasDiffuse)
                            {
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_RoughnessMap.SetValue(material.RoughnessMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecularMetallic;
                            }

                            else if (material.HasRoughnessMap && material.HasDiffuse)
                            {
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffectParameter_Material_RoughnessMap.SetValue(material.RoughnessMap);
                                Shaders.GBufferEffect.CurrentTechnique =
                                    Shaders.GBufferEffectTechniques_DrawTextureSpecular;
                            }

                            else if (material.HasDiffuse)
                            {
                                Shaders.GBufferEffectParameter_Material_Texture.SetValue(material.AlbedoMap);
                                Shaders.GBufferEffect.CurrentTechnique = Shaders.GBufferEffectTechniques_DrawTexture;
                            }

                            else
                            {
                                Shaders.GBufferEffect.CurrentTechnique = Shaders.GBufferEffectTechniques_DrawBasic;
                            }
                        }


                        if (!material.HasDiffuse)
                        {
                            if (material.Type == MaterialEffect.MaterialTypes.Emissive && material.EmissiveStrength > 0)
                            {
                                //{
                                Shaders.GBufferEffectParameter_Material_DiffuseColor.SetValue(material.DiffuseColor *
                                                                                              material.EmissiveStrength);
                            }
                            //* Math.Max(material.EmissiveStrength,1));
                            //}
                            else
                            {
                                //{
                                Shaders.GBufferEffectParameter_Material_DiffuseColor.SetValue(material.DiffuseColor);
                            }
                            //}
                        }

                        if (!material.HasRoughnessMap)
                        {
                            Shaders.GBufferEffectParameter_Material_Roughness.SetValue(GameSettings.m_defaultRoughness >
                                                                                       0
                                ? GameSettings.m_defaultRoughness
                                : material.Roughness);
                        }
                        Shaders.GBufferEffectParameter_Material_Metallic.SetValue(material.Metallic);
                        Shaders.GBufferEffectParameter_Material_MaterialType.SetValue(material.MaterialTypeNumber);
                    }
                }

                for (int i = 0; i < matLib.Index; i++)
                {
                    MeshLibrary meshLib = matLib.GetMeshLibrary()[i];

                    //Initialize the mesh VB and IB
                    graphicsDevice.SetVertexBuffer(meshLib.GetMesh().VertexBuffer);
                    graphicsDevice.Indices = (meshLib.GetMesh().IndexBuffer);
                    int primitiveCount = meshLib.GetMesh().PrimitiveCount;
                    int vertexOffset   = meshLib.GetMesh().VertexOffset;
                    //int vCount = meshLib.GetMesh().NumVertices;
                    int startIndex = meshLib.GetMesh().StartIndex;

                    //Now draw the local meshes!
                    for (int index = 0; index < meshLib.Index; index++)
                    {
                        //If it's set to "not rendered" skip
                        //if (!meshLib.GetWorldMatrices()[index].Rendered) continue;
                        if (!meshLib.Rendered[index])
                        {
                            continue;
                        }


                        Matrix localWorldMatrix = meshLib.GetWorldMatrices()[index].World;
                        if (renderType == RenderType.TextureBuffer)
                        {
                            Shaders.GBufferEffectParameter_World.SetValue(localWorldMatrix);
                            Shaders.GBufferEffectParameter_WorldViewProj.SetValue(localWorldMatrix * viewProjection);

                            Matrix world = Matrix.Transpose(Matrix.Invert(localWorldMatrix));
                            Shaders.GBufferEffectParameter_WorldIT.SetValue(world);

                            shader.CurrentTechnique.Passes[0].Apply();
                        }
                        else if (renderType == RenderType.FinalMesh)
                        {
                            Shaders.GBufferEffectParameter_WorldViewProj.SetValue(localWorldMatrix * viewProjection);

                            Shaders.GBufferEffectTechniques_DrawBasicMesh.Passes[0].Apply();
                        }

                        if (material.RenderCClockwise)
                        {
                            graphicsDevice.RasterizerState = RasterizerState.CullClockwise;
                        }

                        GameStats.MeshDraws++;

                        try
                        {
                            graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, vertexOffset, startIndex, primitiveCount);
                        }
                        catch (Exception)
                        {
                            // do nothing
                        }

                        if (material.RenderCClockwise)
                        {
                            graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
                        }

                        //only once
                        if (renderType == RenderType.TextureBuffer)
                        {
                            return;
                        }
                    }
                }
            }

            //Update the drawcalls in our stats
        }
        public void SetMaterialSettings(MaterialEffect material)
        {
            if (GameSettings.d_defaultmaterial)
            {
                _Material_DiffuseColor.SetValue(Color.Gray.ToVector3());
                _Material_Roughness.SetValue(GameSettings.m_defaultroughness > 0
                        ? GameSettings.m_defaultroughness
                        : 0.3f);
                _Material_Metallic.SetValue(0.0f);
                _Material_MaterialType.SetValue(0);
                _gbufferShader.CurrentTechnique = _DrawBasic;
            }
            else
            {
                if (material.HasDisplacement)
                {
                    _Material_Texture.SetValue(material.AlbedoMap);
                    _Material_NormalMap.SetValue(material.NormalMap);
                    _Material_DisplacementMap.SetValue(material.DisplacementMap);
                    _gbufferShader.CurrentTechnique =
                        _DrawTextureDisplacement;
                }
                else if (material.HasMask) //Has diffuse for sure then
                {
                    if (material.HasNormalMap && material.HasRoughnessMap)
                    {
                        _Material_MaskMap.SetValue(material.Mask);
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_NormalMap.SetValue(material.NormalMap);
                        _Material_RoughnessMap.SetValue(material.RoughnessMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecularNormalMask;
                    }

                    else if (material.HasNormalMap)
                    {
                        _Material_MaskMap.SetValue(material.Mask);
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_NormalMap.SetValue(material.NormalMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureNormalMask;
                    }

                    else if (material.HasRoughnessMap)
                    {
                        _Material_MaskMap.SetValue(material.Mask);
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_RoughnessMap.SetValue(material.RoughnessMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecularMask;
                    }
                    else
                    {
                        _Material_MaskMap.SetValue(material.Mask);
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecularMask;
                    }
                }
                else
                {
                    if (material.HasNormalMap && material.HasRoughnessMap && material.HasDiffuse &&
                        material.HasMetallic)
                    {
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_NormalMap.SetValue(material.NormalMap);
                        _Material_RoughnessMap.SetValue(material.RoughnessMap);
                        _Material_MetallicMap.SetValue(material.MetallicMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecularNormalMetallic;
                    }

                    else if (material.HasNormalMap && material.HasRoughnessMap && material.HasDiffuse)
                    {
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_NormalMap.SetValue(material.NormalMap);
                        _Material_RoughnessMap.SetValue(material.RoughnessMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecularNormal;
                    }

                    else if (material.HasNormalMap && material.HasDiffuse)
                    {
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_NormalMap.SetValue(material.NormalMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureNormal;
                    }

                    else if (material.HasMetallic && material.HasRoughnessMap && material.HasDiffuse)
                    {
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_RoughnessMap.SetValue(material.RoughnessMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecularMetallic;
                    }

                    else if (material.HasRoughnessMap && material.HasDiffuse)
                    {
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _Material_RoughnessMap.SetValue(material.RoughnessMap);
                        _gbufferShader.CurrentTechnique =
                            _DrawTextureSpecular;
                    }

                    else if (material.HasNormalMap && !material.HasDiffuse)
                    {
                        _Material_NormalMap.SetValue(material.NormalMap);
                        _gbufferShader.CurrentTechnique = _DrawNormal;
                    }

                    else if (material.HasDiffuse)
                    {
                        _Material_Texture.SetValue(material.AlbedoMap);
                        _gbufferShader.CurrentTechnique = _DrawTexture;
                    }

                    else
                    {
                        _gbufferShader.CurrentTechnique = _DrawBasic;
                    }
                }


                if (!material.HasDiffuse)
                {
                    if (material.Type == MaterialEffect.MaterialTypes.Emissive && material.EmissiveStrength > 0)
                    {
                        _Material_DiffuseColor.SetValue(material.DiffuseColor);
                        _Material_Metallic.SetValue(material.EmissiveStrength / 8);
                    }
                    //* Math.Max(material.EmissiveStrength,1));
                    //}
                    else
                    {
                        //{
                        _Material_DiffuseColor.SetValue(material.DiffuseColor);
                    }
                    //}
                }

                if (!material.HasRoughnessMap)
                {
                    _Material_Roughness.SetValue(GameSettings.m_defaultroughness >
                                                 0
                        ? GameSettings.m_defaultroughness
                        : material.Roughness);
                }
                _Material_Metallic.SetValue(material.Metallic);

                if (material.Type == MaterialEffect.MaterialTypes.SubsurfaceScattering)
                {
                    if (GameSettings.sdf_subsurface)
                    {
                        _Material_MaterialType.SetValue(material.MaterialTypeNumber);
                    }
                    else
                    {
                        _Material_MaterialType.SetValue(0);
                    }
                }
                else
                {
                    _Material_MaterialType.SetValue(material.MaterialTypeNumber);
                }
            }
        }
 public void SetMaterial(ref MaterialEffect mat)
 {
     _material = mat;
 }
Exemple #22
0
        //Load our default setup!
        private void SetUpEditorScene(GraphicsDevice graphics)
        {
            ////////////////////////////////////////////////////////////////////////
            // Camera

            //Set up our starting camera position

            // NOTE: Coordinate system depends on Camera.up,
            //       Right now z is going up, it's not depth!

            Camera = new Camera(position: new Vector3(-88, -11f, 4), lookat: new Vector3(38, 8, 32));

            EnvironmentSample = new EnvironmentSample(new Vector3(-45, -5, 5));

            VolumeTexture = new VolumeTextureEntity("Content/Sponza/sponza_sdf.sdff", graphics, new Vector3(-7, 0, 63), new Vector3(200, 100, 100))
            {
                NeedsUpdate = true
            };

            _sdfGenerator = new SDFGenerator();

            ////////////////////////////////////////////////////////////////////////
            // GUI

            ////////////////////////////////////////////////////////////////////////
            // Static geometry

            // NOTE: If you don't pass a materialEffect it will use the default material from the object

            BasicEntity testEntity = AddEntity(model: _assets.SponzaModel,
                                               position: Vector3.Zero,
                                               angleX: Math.PI / 2,
                                               angleY: 0,
                                               angleZ: 0,
                                               scale: 0.1f,
                                               hasStaticPhysics: false);//CHANGE BACK


            //AddEntity(model: _assets.CloneTrooper,
            //    position: new Vector3(20, 0, 10),
            //    angleX: Math.PI / 2,
            //    angleY: 0,
            //    angleZ: 0,
            //    scale: 10.4f);

            for (int x = -5; x <= 5; x++)
            {
                for (int y = -5; y <= 5; y++)
                {
                    AddEntity(model: _assets.Plane,
                              materialEffect: ((x + 5 + y + 5) % 2 == 1) ? _assets.MirrorMaterial : _assets.MetalRough03Material,
                              position: new Vector3(30 + x * 4, y * 4 + 4, 0),
                              angleX: 0,
                              angleY: 0,
                              angleZ: 0,
                              scale: 2);
                }
            }

            AddEntity(model: _assets.StanfordDragon,
                      materialEffect: _assets.BaseMaterial,
                      position: new Vector3(40, -10, 0),
                      angleX: Math.PI / 2,
                      angleY: 0,
                      angleZ: 0,
                      scale: 10);

            ////////////////////////////////////////////////////////////////////////
            // Dynamic geometry

            // NOTE: We first have to create a physics object and then apply said object to a rendered model
            // BEPU could use non-default meshes, but that is much much more expensive so I am using just default ones right now
            // ... so -> spheres, boxes etc.
            // For dynamic meshes I could use the same way i have static meshes, but use - MobileMesh - instead

            // NOTE: Our physics entity's position will be overwritten, so it doesn't matter
            // NOTE: If a physics object has mass it will move, otherwise it is static

            Entity physicsEntity;

            //Just a ground box where nothing should fall through
            //_physicsSpace.Add(new Box(new BEPUutilities.Vector3(0, 0, -0.5f), 1000, 1000, 1));

            _physicsSpace.Add(physicsEntity = new Sphere(position: BEPUutilities.Vector3.Zero, radius: 5, mass: 50));
            AddEntity(model: _assets.IsoSphere,
                      materialEffect: _assets.AlphaBlendRim,
                      position: new Vector3(20, 0, 10),
                      angleX: Math.PI / 2,
                      angleY: 0,
                      angleZ: 0,
                      scale: 5,
                      PhysicsEntity: physicsEntity);

            testEntity.ApplyTransformation();
            _sdfGenerator.Generate(testEntity);

            for (int i = 0; i < 10; i++)
            {
                MaterialEffect test = _assets.SilverMaterial.Clone();
                test.Roughness = i / 9.0f + 0.1f;
                test.Metallic  = 1;
                _physicsSpace.Add(physicsEntity = new Sphere(position: BEPUutilities.Vector3.Zero, radius: 5, mass: 50));
                AddEntity(model: _assets.IsoSphere,
                          materialEffect: test,
                          position: new Vector3(30 + i * 10, 0, 10),
                          angleX: Math.PI / 2,
                          angleY: 0,
                          angleZ: 0,
                          scale: 5,
                          PhysicsEntity: physicsEntity);
            }

            ////////////////////////////////////////////////////////////////////////
            // Decals

            Decals.Add(new Decal(_assets.IconDecal, new Vector3(-6, 22, 15), 0, -Math.PI / 2, 0, Vector3.One * 10));

            ////////////////////////////////////////////////////////////////////////
            // Dynamic lights

            AddPointLight(position: new Vector3(-61, 0, 107),
                          radius: 150,
                          color: new Color(104, 163, 223),
                          intensity: 20,
                          castShadows: false,
                          shadowResolution: 1024,
                          staticShadow: false,
                          isVolumetric: true);

            AddPointLight(position: new Vector3(15, 0, 107),
                          radius: 150,
                          color: new Color(104, 163, 223),
                          intensity: 30,
                          castShadows: false,
                          shadowResolution: 1024,
                          staticShadow: false,
                          isVolumetric: true);

            AddPointLight(position: new Vector3(66, 0, 40),
                          radius: 120,
                          color: new Color(255, 248, 232),
                          intensity: 120,
                          castShadows: true,
                          shadowResolution: 1024,
                          softShadowBlurAmount: 0,
                          staticShadow: false,
                          isVolumetric: false);

            //volumetric light!
            //AddPointLight(position: new Vector3(-4, 40, 66),
            //    radius: 80,
            //    color: Color.White,
            //    intensity: 50,
            //    castShadows: true,
            //    shadowResolution: 1024,
            //    staticShadow: false,
            //    isVolumetric: true,
            //    volumetricDensity: 3);


            // Spawn a lot of lights to test performance

            //int sides = 4;
            //float distance = 20;
            //Vector3 startPosition = new Vector3(-30, 30, 1);

            ////amount of lights is sides*sides* sides*2

            //for (int x = 0; x < sides * 2; x++)
            //    for (int y = 0; y < sides; y++)
            //        for (int z = 0; z < sides; z++)
            //        {
            //            Vector3 position = new Vector3(x, -y, z) * distance + startPosition;
            //            AddPointLight(position, distance, FastRand.NextColor(), 50, false, false, 0.9f);
            //        }


            //AddDirectionalLight(direction: new Vector3(0.2f, 0.2f, -1),
            //    intensity: 100,
            //    color: Color.White,
            //    position: Vector3.UnitZ * 2,
            //    drawShadows: true,
            //    shadowWorldSize: 450,
            //    shadowDepth: 180,
            //    shadowResolution: 1024,
            //    shadowFilteringFiltering: DirectionalLightSource.ShadowFilteringTypes.SoftPCF3x,
            //    screenspaceShadowBlur: false);
        }
Exemple #23
0
 public void AddEffect(MaterialEffect newEffect)
 {
     effects.Add(newEffect);
 }