예제 #1
0
        protected void RenderToDepthMap(RenderTexture rt, ShaderUniqueParameter sp, Dictionary <Shader, Dictionary <Material, List <SubMeshData> > > sm)
        {
            // レンダーターゲットをセット
            rt.Bind(Color4.White);

            depthShader.UseShader();
            //depthShader.SetUniqueParameter(sp, true);

            foreach (var sh in sm)
            {
                foreach (var mat in sh.Value)
                {
                    foreach (var sub in mat.Value)
                    {
                        if (!sub.Visible || !sub.CastShadow)
                        {
                            continue;
                        }
                        sp.world = sub.WorldTransform;
                        depthShader.SetUniqueParameter(sp, false);

                        if (sub.Animator != null)
                        {
                            sub.Animator.BindMotion(1);
                            depthShader.SetParameter(depthShader.loc_skin, 1);
                        }
                        else
                        {
                            depthShader.SetParameter(depthShader.loc_skin, 0);
                        }
                        Drawer.DrawSubMesh(sub.SubMesh);
                    }
                }
            }
        }
예제 #2
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            renderTexture.Bind(Color4.White);
            sobelShader.UseShader();
            sobelShader.SetParameter(sobelShader.loc_resolution, MMW.RenderResolution.ToVector2().Inverse());
            sobelShader.SetParameter(sobelShader.loc_mvp, ref orthoMatrix, false);
            sobelShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            Drawer.DrawTextureMesh();
            sobelShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #3
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = DstRenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            renderTexture.Bind(Color4.White);
            fxaaShader.UseShader();
            fxaaShader.SetParameterByName("resolutionInverse", renderTexture.Size.ToVector2().Inverse());
            fxaaShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            fxaaShader.SetParameterByName("MVP", ref orthoMatrix, false);
            Drawer.DrawTextureMesh();
            fxaaShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0);
        }
예제 #4
0
        /// <summary>
        /// 複数のテクスチャを1つのビットマップにまとめる
        /// </summary>
        /// <param name="textures"></param>
        /// <param name="gridNum"></param>
        /// <param name="gridSize"></param>
        /// <returns></returns>
        public static Texture2D CombineBitmaps(Texture2D[] textures, int gridNum, int gridSize = 256)
        {
            RenderTexture rt = new RenderTexture(gridNum * gridSize, gridNum * gridSize);

            rt.ColorFormat0 = MMW.Configuration.DefaultPixelFormat;
            rt.Load();

            rt.Bind(Color4.White);

            for (var y = 0; y < gridNum; y++)
            {
                for (var x = 0; x < gridNum; x++)
                {
                    var index = y * gridNum + x;
                    if (index >= textures.Length)
                    {
                        continue;
                    }

                    Drawer.DrawTexture(
                        textures[index],
                        new RectangleF(0.0f, 0.0f, 1.0f, 1.0f),
                        new RectangleF(x / (float)gridNum, y / (float)gridNum, 1.0f / (float)gridNum, 1.0f / (float)gridNum));
                }
            }

            //var res = (Bitmap)rt.ColorDst0.SrcBitmap.Clone();
            return(rt.ColorDst0);
        }
예제 #5
0
        public override void Draw(double deltaTime)
        {
            if (DepthMap == null)
            {
                return;
            }
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            renderTexture.Bind(Color4.White);
            ssaoShader.UseShader();
            ssaoShader.SetParameter(ssaoShader.loc_resolution, renderTexture.Size.ToVector2());
            ssaoShader.SetParameter(ssaoShader.loc_resolutionIV, renderTexture.Size.ToVector2().Inverse());
            ssaoShader.SetParameter(ssaoShader.loc_mxlength, MxLength);
            ssaoShader.SetParameter(ssaoShader.loc_radius, Radius);
            ssaoShader.SetParameter(ssaoShader.loc_raylength, RayLength);
            ssaoShader.SetParameter(ssaoShader.loc_aoscatter, AOScatter);
            ssaoShader.SetParameter(ssaoShader.loc_cdm, CDM);
            ssaoShader.SetParameter(ssaoShader.loc_strength, Strength);
            ssaoShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            ssaoShader.SetParameter(TextureUnit.Texture1, DepthMap);
            ssaoShader.SetParameter(TextureUnit.Texture2, PositionMap);
            ssaoShader.SetParameter(TextureUnit.Texture3, NormalMap);
            ssaoShader.SetParameter(ssaoShader.loc_v, Camera.View, false);
            ssaoShader.SetParameter(ssaoShader.loc_mvp, ref orthoMatrix, false);
            ssaoShader.SetParameter(ssaoShader.loc_nearFar, new Vector2(Camera.Near, Camera.Far));
            Drawer.DrawTextureMesh();
            ssaoShader.UnuseShader();

            renderTexture2.Bind(Color4.White);
            blurShader.UseShader();
            blurShader.SetParameter(blurShader.loc_resolution, MMW.RenderResolution.ToVector2().Inverse());
            blurShader.SetParameter(blurShader.loc_mvp, ref orthoMatrix, false);
            blurShader.SetParameter(blurShader.loc_strength, 8.0f);
            blurShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            blurShader.SetParameter(TextureUnit.Texture1, renderTexture.ColorDst0);
            Drawer.DrawTextureMesh();
            blurShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture2.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #6
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }
            if (Radius <= 0.0f)
            {
                return;
            }

            renderTextureV.Bind(Color4.Black);
            blurVShader.UseShader();
            blurVShader.SetParameter(blurVShader.loc_resolution, renderTextureV.Size.ToVector2().Inverse());
            blurVShader.SetParameter(blurVShader.loc_radius, Radius / Reduct);
            if (SrcTexture == null)
            {
                blurVShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            }
            else
            {
                blurVShader.SetParameter(TextureUnit.Texture0, SrcTexture);
            }
            blurVShader.SetParameter(blurVShader.loc_mvp, ref orthoMatrix, false);
            Drawer.DrawTextureMesh();

            renderTextureH.Bind(Color4.Black);
            blurHShader.UseShader();
            blurHShader.SetParameter(blurHShader.loc_resolution, renderTextureH.Size.ToVector2().Inverse());
            blurHShader.SetParameter(blurHShader.loc_radius, Radius / Reduct);
            blurHShader.SetParameter(TextureUnit.Texture0, renderTextureV.ColorDst0);
            blurHShader.SetParameter(blurHShader.loc_mvp, ref orthoMatrix, false);
            Drawer.DrawTextureMesh();
            blurHShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTextureH.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #7
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }
            if (Length <= 0.0f)
            {
                return;
            }
            if (VelocityMap == null)
            {
                return;
            }

            renderTexture.Bind(Color4.Black);

            blurShader.UseShader();
            blurShader.SetParameter(blurShader.loc_resolution, renderTexture.Size.ToVector2().Inverse());
            blurShader.SetParameter(blurShader.loc_length, Length);
            blurShader.SetParameter(blurShader.loc_mvp, ref orthoMatrix, false);
            if (SrcTexture == null)
            {
                blurShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            }
            else
            {
                blurShader.SetParameter(TextureUnit.Texture0, SrcTexture);
            }
            blurShader.SetParameter(TextureUnit.Texture1, VelocityMap);
            blurShader.SetParameter(TextureUnit.Texture2, DepthMap);
            Drawer.DrawTextureMesh();
            blurShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #8
0
        public override void Draw(double deltaTime)
        {
            if (DepthTexture == null)
            {
                return;
            }
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            if (BlurTexture == null)
            {
                blurRT.Bind(Color4.White);
                Drawer.DrawTexture(rt.ColorDst0);
                blur.Draw(deltaTime);
            }

            renderTexture.Bind(Color4.White);
            dofShader.UseShader();
            dofShader.SetParameter(dofShader.loc_resolution, MMW.RenderResolution.ToVector2().Inverse());
            dofShader.SetParameter(dofShader.loc_mvp, ref orthoMatrix, false);
            dofShader.SetParameter(dofShader.loc_nearFar, new Vector2(Camera.Near, Camera.Far));
            dofShader.SetParameter(dofShader.loc_baseDepth, BaseDepth);
            dofShader.SetParameter(dofShader.loc_startDist, StartDist);
            dofShader.SetParameter(dofShader.loc_transDist, TransDist);
            dofShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            dofShader.SetParameter(TextureUnit.Texture1, blurRT.ColorDst0);
            dofShader.SetParameter(TextureUnit.Texture2, DepthTexture);
            Drawer.DrawTextureMesh();
            dofShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #9
0
        internal static void Draw(double deltaTime)
        {
            fpsDelta += deltaTime;
            fpsCount++;
            if (fpsDelta >= 1.0)
            {
                fps       = fpsCount;
                fpsDelta -= 1.0;
                fpsCount  = 0;
            }

            // 深度の浅いカメラから描画

            if (HMDCamera.Connected)
            {
                HMDCamera.CameraType = HMDCameraType.Default;
                var cameras = FindGameComponents <Camera>((cam) => cam.Enabled && cam != MainCamera);
                Array.Sort(cameras, (cam1, cam2) => { return(cam1.Depth - cam2.Depth); });
                for (var i = 0; i < cameras.Length; i++)
                {
                    cameras[i].Draw(deltaTime);
                }

                HMDCamera.CameraType     = HMDCameraType.Right;
                MainCamera.TargetTexture = renderTargetRight;
                MainCamera.Draw(deltaTime);

                HMDCamera.CameraType     = HMDCameraType.Left;
                MainCamera.TargetTexture = renderTargetLeft;
                MainCamera.Draw(deltaTime);

                RenderTexture.Bind(0, ClientSize, Color4.Black);
                Drawer.DrawTexture(renderTargetRight.ColorDst0, new RectangleF(0, 0, 1, 1), new RectangleF(0.5f, 0, 0.5f, 1));
                Drawer.DrawTexture(renderTargetLeft.ColorDst0, new RectangleF(0, 0, 1, 1), new RectangleF(0, 0, 0.5f, 1));
            }
            else
            {
                var cameras = FindGameComponents <Camera>((cam) => cam.Enabled);
                Array.Sort(cameras, (cam1, cam2) => { return(cam1.Depth - cam2.Depth); });
                for (var i = 0; i < cameras.Length; i++)
                {
                    cameras[i].Draw(deltaTime);
                }
                RenderTexture.Bind(0, ClientSize, Color4.Black);
                Drawer.DrawTexture(defaultRenderTarget.ColorDst0);
            }
        }
예제 #10
0
        public override void Draw(double deltaTime)
        {
            if (DepthMap == null)
            {
                return;
            }
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }
            if (Radius <= 0.0f)
            {
                return;
            }

            renderTexture.Bind(Color4.White);
            ssaoShader.UseShader();
            ssaoShader.SetParameter(ssaoShader.loc_resolution, renderTexture.Size.ToVector2().Inverse());
            ssaoShader.SetParameter(ssaoShader.loc_radius, Radius);
            ssaoShader.SetParameter(ssaoShader.loc_depthBias, DepthBias);
            ssaoShader.SetParameter(ssaoShader.loc_strength, Strength);
            ssaoShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            ssaoShader.SetParameter(TextureUnit.Texture1, DepthMap);
            ssaoShader.SetParameter(ssaoShader.loc_mvp, ref orthoMatrix, false);
            ssaoShader.SetParameter(ssaoShader.loc_nearFar, new Vector2(Camera.Near, Camera.Far));
            Drawer.DrawTextureMesh();
            ssaoShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #11
0
        protected void RenderToColorMap(RenderTexture rt, ShaderUniqueParameter sp, Dictionary <Shader, Dictionary <Material, List <SubMeshData> > > sm)
        {
            // レンダーターゲットをセット
            rt.Bind(Color4.Black);

            colorShader.UseShader();
            colorShader.SetUniqueParameter(sp, true);

            ushort index = 0;

            foreach (var sh in sm)
            {
                foreach (var mat in sh.Value)
                {
                    foreach (var sub in mat.Value)
                    {
                        if (!sub.Visible)
                        {
                            continue;
                        }
                        sp.world = sub.WorldTransform;
                        colorShader.SetUniqueParameter(sp, false);
                        colorShader.SetParameter(colorShader.loc_color, ref randColors[index++]);

                        if (sub.Animator != null)
                        {
                            sub.Animator.BindMotion(1);
                        }
                        else
                        {
                            Animator.BindIdentity(1);
                        }
                        Drawer.DrawSubMesh(sub.SubMesh);
                        if (sub.Animator != null)
                        {
                            sub.Animator.UnbindMotion(1);
                        }
                        else
                        {
                            Animator.UnbindIdentity(1);
                        }
                    }
                }
            }
        }
예제 #12
0
        public override void Draw(double deltaTime)
        {
            if (DepthMap == null)
            {
                return;
            }
            if (NearBias <= 0.0f && FarBias <= 0.0f)
            {
                return;
            }
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            renderTexture.Bind(Color4.White);
            dofShader.UseShader();
            dofShader.SetParameter(dofShader.loc_resolution, MMW.RenderResolution.ToVector2().Inverse());
            dofShader.SetParameter(dofShader.loc_mvp, ref orthoMatrix, false);
            dofShader.SetParameter(dofShader.loc_focus, Focus);
            dofShader.SetParameter(dofShader.loc_bias, new Vector2(NearBias, FarBias));
            dofShader.SetParameter(dofShader.loc_blurMax, new Vector2(NearRadiusMax, FarRadiusMax));
            dofShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            dofShader.SetParameter(TextureUnit.Texture1, DepthMap);
            Drawer.DrawTextureMesh();
            dofShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #13
0
        protected void RenderToVelocityMap(RenderTexture rt, ShaderUniqueParameter sp, Dictionary <Shader, Dictionary <Material, List <SubMeshData> > > sm)
        {
            // レンダーターゲットをセット
            rt.Bind(Color4.Black);

            velocityShader.UseShader();
            velocityShader.SetUniqueParameter(sp, true);

            foreach (var sh in sm)
            {
                foreach (var mat in sh.Value)
                {
                    foreach (var sub in mat.Value)
                    {
                        if (!sub.Visible)
                        {
                            continue;
                        }
                        sp.world    = sub.WorldTransform;
                        sp.oldWorld = sub.OldWorldTransform;
                        velocityShader.SetUniqueParameter(sp, false);

                        if (sub.Animator != null)
                        {
                            sub.Animator.BindMotion(1, 2);
                        }
                        else
                        {
                            Animator.BindIdentity(1, 2);
                        }
                        Drawer.DrawSubMesh(sub.SubMesh);
                        if (sub.Animator != null)
                        {
                            sub.Animator.UnbindMotion(1, 2);
                        }
                        else
                        {
                            Animator.UnbindIdentity(1, 2);
                        }
                    }
                }
            }
        }
예제 #14
0
        public override void Draw(double deltaTime)
        {
            if (Camera == null || MulTexture == null)
            {
                return;
            }
            if (!Camera.TargetTexture.Loaded)
            {
                return;
            }

            renderTexture.Bind(Color4.White);
            mulShader.UseShader();
            mulShader.SetParameterByName("resolutionInverse", new Vector2(1.0f / MMW.RenderResolution.Width, 1.0f / MMW.RenderResolution.Height));
            mulShader.SetParameter(TextureUnit.Texture0, Camera.TargetTexture.ColorDst0);
            mulShader.SetParameter(TextureUnit.Texture1, MulTexture);
            mulShader.SetParameterByName("MVP", orthoMatrix, false);
            Drawer.DrawTextureMesh();
            mulShader.UnuseShader();

            Camera.TargetTexture.Bind();
            Drawer.DrawTexture(renderTexture.ColorDst0, new RectangleF(0, 0, 1, 1), new RectangleF(0, 0, 1, 1));
        }
예제 #15
0
        public static void Render(float Dt)
        {
            if (!IsOpen)
            {
                return;
            }

            if (RT == null)
            {
                InitGraphics();
            }

            RT.Bind();
            RT.Clear(ClearColor);
            RenderContent(Dt);
            RT.Unbind();

            float Y = (0 - RT.Height) + (NanoVG.Height * ConsoleHeightRatio) + ScrollAmt;

            NanoVG.BeginFrame();
            NanoVG.DrawTexturedRect(RT_NVG, 0, (int)Y, RT.Width, RT.Height);
            NanoVG.EndFrame();
        }
예제 #16
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }
            if (Radius <= 0.0f)
            {
                return;
            }

            glareRT.Bind(Color4.Black);
            if (Glare == GlareType.Line)
            {
                glareLineShader.UseShader();
                glareLineShader.SetParameter(glareLineShader.loc_resolution, glareRT.Size.ToVector2().Inverse());
                glareLineShader.SetParameter(glareLineShader.loc_radius, Radius / Reduct);
                glareLineShader.SetParameter(glareLineShader.loc_direction, Direction);
                glareLineShader.SetParameter(glareLineShader.loc_mvp, ref orthoMatrix, false);
                if (SrcTexture == null)
                {
                    glareLineShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
                }
                else
                {
                    glareLineShader.SetParameter(TextureUnit.Texture0, SrcTexture);
                }
            }
            else if (Glare == GlareType.Plus)
            {
                glarePlusShader.UseShader();
                glarePlusShader.SetParameter(glarePlusShader.loc_resolution, glareRT.Size.ToVector2().Inverse());
                glarePlusShader.SetParameter(glarePlusShader.loc_radius, Radius / Reduct);
                glarePlusShader.SetParameter(glarePlusShader.loc_direction, Direction);
                glarePlusShader.SetParameter(glarePlusShader.loc_mvp, ref orthoMatrix, false);
                if (SrcTexture == null)
                {
                    glarePlusShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
                }
                else
                {
                    glarePlusShader.SetParameter(TextureUnit.Texture0, SrcTexture);
                }
            }
            else if (Glare == GlareType.Star)
            {
                glareStarShader.UseShader();
                glareStarShader.SetParameter(glareStarShader.loc_resolution, glareRT.Size.ToVector2().Inverse());
                glareStarShader.SetParameter(glareStarShader.loc_radius, Radius / Reduct);
                glareStarShader.SetParameter(glareStarShader.loc_direction, Direction);
                glareStarShader.SetParameter(glareStarShader.loc_mvp, ref orthoMatrix, false);
                if (SrcTexture == null)
                {
                    glareStarShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
                }
                else
                {
                    glareStarShader.SetParameter(TextureUnit.Texture0, SrcTexture);
                }
            }
            Drawer.DrawTextureMesh();
            glareLineShader.UnuseShader();

            rt.Bind();
            Drawer.DrawTexture(glareRT.ColorDst0);
            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #17
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            // HDR抽出
            hdrRT.Bind(Color4.Black);
            hdrShader.UseShader();
            hdrShader.SetParameter(hdrShader.loc_resolution, hdrRT.Size.ToVector2().Inverse());
            hdrShader.SetParameter(hdrShader.loc_threshold, HDRThreshold);
            hdrShader.SetParameter(hdrShader.loc_mvp, ref orthoMatrix, false);
            hdrShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            Drawer.DrawTextureMesh();
            hdrShader.UnuseShader();

            // HDR画像のぼかし画像を生成
            // line
            for (var i = 0; i < BlurNum; i++)
            {
                blurs[i].Direction     = Direction;
                blurs[i].RenderTexture = blurRT1s[i];
                if (i == 0)
                {
                    blurs[i].SrcTexture = hdrRT.ColorDst0;
                }
                else
                {
                    blurs[i].SrcTexture = blurRT1s[i - 1].ColorDst0;
                }
                blurs[i].Draw(deltaTime);
            }
            if (GlareType == GlareBlur.GlareType.Plus)
            {
                var dir = new Vector2(-Direction.Y, Direction.X);
                for (var i = 0; i < BlurNum; i++)
                {
                    blurs[i].Direction     = dir;
                    blurs[i].RenderTexture = blurRT2s[i];
                    if (i == 0)
                    {
                        blurs[i].SrcTexture = hdrRT.ColorDst0;
                    }
                    else
                    {
                        blurs[i].SrcTexture = blurRT2s[i - 1].ColorDst0;
                    }
                    blurs[i].Draw(deltaTime);
                }
            }
            else if (GlareType == GlareBlur.GlareType.Star)
            {
                var dir1 = new Vector2((Direction.X * cos60) - (Direction.Y * sin60), (Direction.X * sin60) + (Direction.Y * cos60));
                var dir2 = new Vector2((Direction.X * cos120) - (Direction.Y * sin120), (Direction.X * sin120) + (Direction.Y * cos120));
                for (var i = 0; i < BlurNum; i++)
                {
                    blurs[i].Direction     = dir1;
                    blurs[i].RenderTexture = blurRT2s[i];
                    if (i == 0)
                    {
                        blurs[i].SrcTexture = hdrRT.ColorDst0;
                    }
                    else
                    {
                        blurs[i].SrcTexture = blurRT2s[i - 1].ColorDst0;
                    }
                    blurs[i].Draw(deltaTime);
                }
                for (var i = 0; i < BlurNum; i++)
                {
                    blurs[i].Direction     = dir2;
                    blurs[i].RenderTexture = blurRT3s[i];
                    if (i == 0)
                    {
                        blurs[i].SrcTexture = hdrRT.ColorDst0;
                    }
                    else
                    {
                        blurs[i].SrcTexture = blurRT3s[i - 1].ColorDst0;
                    }
                    blurs[i].Draw(deltaTime);
                }
            }

            // Glare処理
            glareRT.Bind(Color4.Black);
            glareShader.UseShader();
            glareShader.SetParameter(glareShader.loc_resolution, glareRT.Size.ToVector2().Inverse());
            glareShader.SetParameter(glareShader.loc_mvp, ref orthoMatrix, false);
            glareShader.SetParameter(glareShader.loc_intensity, Intensity);
            glareShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            var units = new TextureUnit[][]
            {
                new TextureUnit[]
                {
                    TextureUnit.Texture1,
                    TextureUnit.Texture2,
                    TextureUnit.Texture3,
                },
                new TextureUnit[]
                {
                    TextureUnit.Texture4,
                    TextureUnit.Texture5,
                    TextureUnit.Texture6,
                },
                new TextureUnit[]
                {
                    TextureUnit.Texture7,
                    TextureUnit.Texture8,
                    TextureUnit.Texture9,
                },
            };

            // line
            for (var i = 0; i < 3; i++)
            {
                if (i < BlurNum)
                {
                    glareShader.SetParameter(units[0][i], blurRT1s[i].ColorDst0);
                }
                else
                {
                    glareShader.SetParameter(units[0][i], glareShader.black);
                }
            }
            // plus
            for (var i = 0; i < 3; i++)
            {
                if (i < BlurNum && GlareType > GlareBlur.GlareType.Line)
                {
                    glareShader.SetParameter(units[1][i], blurRT2s[i].ColorDst0);
                }
                else
                {
                    glareShader.SetParameter(units[1][i], glareShader.black);
                }
            }
            // star
            for (var i = 0; i < 3; i++)
            {
                if (i < BlurNum && GlareType > GlareBlur.GlareType.Plus)
                {
                    glareShader.SetParameter(units[2][i], blurRT3s[i].ColorDst0);
                }
                else
                {
                    glareShader.SetParameter(units[2][i], glareShader.black);
                }
            }
            Drawer.DrawTextureMesh();
            glareShader.UnuseShader();

            // 書き出し
            rt.Bind();
            Drawer.DrawTexture(glareRT.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #18
0
        protected internal override void Draw(double deltaTime)
        {
            var objects     = MMW.FindGameObjects((obj) => obj.Enabled && !obj.Destroyed /*&& obj.Layer < GameObject.LayerUI && layerMask.Get(obj.Layer)*/);
            var drawMeshDic = new Dictionary <Shader, Dictionary <Material, List <SubMeshData> > >();

            var animList  = new List <AAnimator>();
            var morphList = new List <AMorpher>();

            var wp = Transform.WorldPosition;

            var distDic  = new Dictionary <GameObject, float>();
            var distTask = Task.Factory.StartNew(() =>
            {
                foreach (var obj in objects)
                {
                    var dist = (wp - obj.Transform.WorldPosition).Length;
                    distDic.Add(obj, dist);
                }
            });

            // オブジェクトレイヤ抽出
            //DrawableGameComponent[] meshComs = null;
            DrawableGameComponent[] beforeComs = null;
            DrawableGameComponent[] afterComs  = null;
            //DrawableGameComponent[] uiMeshComs = null;
            DrawableGameComponent[] uiComs = null;
            var layerSortTask = Task.Factory.StartNew(() =>
            {
                var draws = MMW.FindGameComponents <DrawableGameComponent>(c => c.Enabled && !c.Destroyed && !(c is MeshRenderer));

                //var meshList = new List<DrawableGameComponent>();
                var beforeList = new List <DrawableGameComponent>();
                var afterList  = new List <DrawableGameComponent>();
                var uiList     = new List <DrawableGameComponent>();
                //var uiMeshList = new List<DrawableGameComponent>();

                foreach (var d in draws)
                {
                    if (d.Layer < LayerAfterMeshRender)
                    {
                        beforeList.Add(d);
                    }
                    else if (d.Layer < LayerUI)
                    {
                        afterList.Add(d);
                    }
                    else
                    {
                        uiList.Add(d);
                    }

                    //if (d.Layer < LayerUI) meshList.Add(d);
                    //else uiMeshList.Add(d);
                }

                beforeList.Sort((a, b) => a.Layer - b.Layer);
                afterList.Sort((a, b) => a.Layer - b.Layer);
                uiList.Sort((a, b) => a.Layer - b.Layer);
                //meshList.Sort((a, b) => a.Layer - b.Layer);
                //uiMeshList.Sort((a, b) => a.Layer - b.Layer);

                //var meshObjs = objects.ToArray();
                //var beforeObjs = Array.FindAll(objects, (o) => o.Layer >= 0 && o.Layer < GameObject.LayerAfterRender);
                //var afterObjs = Array.FindAll(objects, (o) => o.Layer >= GameObject.LayerAfterRender);
                //var uiObjs = MMW.FindGameObjects((obj) => obj.Layer >= GameObject.LayerUI && layerMask.Get(obj.Layer));

                //Array.Sort(meshObjs, (a, b) => a.Layer - b.Layer);
                //Array.Sort(beforeObjs, (a, b) => a.Layer - b.Layer);
                //Array.Sort(afterObjs, (a, b) => a.Layer - b.Layer);
                //Array.Sort(uiObjs, (a, b) => a.Layer - b.Layer);

                /*
                 * foreach (var obj in meshObjs)
                 * {
                 *  var coms = obj.GetComponents<DrawableGameComponent>((c) => c.Enabled && !(c is MeshRenderer));
                 *  meshList.AddRange(coms);
                 * }
                 * foreach (var obj in beforeObjs)
                 * {
                 *  var coms = obj.GetComponents<DrawableGameComponent>((c) => c.Enabled && !(c is MeshRenderer));
                 *  beforeList.AddRange(coms);
                 * }
                 * foreach (var obj in afterObjs)
                 * {
                 *  var coms = obj.GetComponents<DrawableGameComponent>((c) => c.Enabled && !(c is MeshRenderer));
                 *  afterList.AddRange(coms);
                 * }
                 * foreach (var obj in uiObjs)
                 * {
                 *  var coms = obj.GetComponents<DrawableGameComponent>((c) => c.Enabled && !(c is MeshRenderer));
                 *  uiList.AddRange(coms);
                 * }
                 */

                //meshComs = meshList.ToArray();
                beforeComs = beforeList.ToArray();
                afterComs  = afterList.ToArray();
                uiComs     = uiList.ToArray();
                //uiMeshComs = uiMeshList.ToArray();
            });

            // ライト情報を抽出
            var lights           = new List <BufferLight>();
            var lightExtractTask = Task.Factory.StartNew(() =>
            {
                foreach (var obj in objects)
                {
                    var pls = obj.GetComponents <PointLight>();
                    foreach (var pl in pls)
                    {
                        var l = new BufferLight()
                        {
                            color     = pl.Color.ToVector4(),
                            pos       = new Vector4(pl.Transform.WorldPosition),
                            dir       = -Vector4.UnitY,
                            intensity = pl.Intensity,
                            radius    = pl.Radius,
                            specCoeff = pl.SpecularCoeff,
                            innerDot  = -1.0f,
                            outerDot  = -1.0f,
                        };
                        lights.Add(l);
                    }

                    var sls = obj.GetComponents <SpotLight>();
                    foreach (var sl in sls)
                    {
                        var l = new BufferLight()
                        {
                            color     = sl.Color.ToVector4(),
                            pos       = new Vector4(sl.Transform.WorldPosition),
                            dir       = new Vector4(sl.WorldDirection, 0.0f),
                            intensity = sl.Intensity,
                            radius    = sl.Radius,
                            specCoeff = sl.SpecularCoeff,
                            innerDot  = sl.InnerDot,
                            outerDot  = sl.OuterDot,
                        };
                        lights.Add(l);
                    }
                }
                lights = lights.Take(2048).ToList();
            });

            var clipDic  = new Dictionary <GameObject, bool>();
            var clipTask = Task.Factory.StartNew(() =>
            {
                distTask.Wait();
                foreach (var obj in objects)
                {
                    var mr = obj.GetComponent <MeshRenderer>();
                    if (mr == null || !mr.Enabled)
                    {
                        clipDic.Add(obj, true);
                        continue;
                    }

                    if (mr.ForceRendering)
                    {
                        clipDic.Add(obj, false);
                        continue;
                    }

                    if (distDic[obj] < ForceRenderDistance)
                    {
                        clipDic.Add(obj, false);
                        continue;
                    }

                    var clip = true;
                    var b    = mr.Mesh.Bounds;

                    var mvp  = obj.Transform.WorldTransform * ViewProjection;
                    var mint = new Vector4(b.Min, 1.0f) * mvp;
                    var maxt = new Vector4(b.Max, 1.0f) * mvp;
                    var min  = mint.Xyz / mint.W;
                    var max  = maxt.Xyz / maxt.W;

                    var xx = new float[] { min.X, max.X };
                    var yy = new float[] { min.Y, max.Y };
                    var zz = new float[] { min.Z, max.Z };

                    foreach (var x in xx)
                    {
                        foreach (var y in yy)
                        {
                            foreach (var z in zz)
                            {
                                if (
                                    x > -1.5f && x < 1.5f &&
                                    y > -1.5f && y < 1.5f &&
                                    z > -1.0f && z < 1.0f)
                                {
                                    clip = false;
                                    break;
                                }
                            }
                            if (!clip)
                            {
                                break;
                            }
                        }
                        if (!clip)
                        {
                            break;
                        }
                    }

                    clipDic.Add(obj, clip);
                }
            });

            var animTasks    = new List <Task>();
            var findAnimTask = Task.Factory.StartNew(() =>
            {
                clipTask.Wait();
                distTask.Wait();
                foreach (var obj in objects)
                {
                    if (!obj.Enabled)
                    {
                        continue;
                    }
                    if (clipDic[obj])
                    {
                        continue;
                    }

                    var animator = obj.GetComponent <AAnimator>();
                    var morpher  = obj.GetComponent <AMorpher>();

                    if (animator != null && animator.Enabled)
                    {
                        if (animator.EnableAsyncCalc)
                        {
                            animTasks.Add(Task.Run(() => animator.CalcTransform()));
                        }
                        animList.Add(animator);
                    }

                    if (morpher != null && morpher.Enabled && distDic[obj] < 10.0f)
                    {
                        if (morpher.EnableAsyncCalc)
                        {
                            animTasks.Add(Task.Run(() => morpher.CalcMorph()));
                        }
                        morphList.Add(morpher);
                    }
                }
            });

            List <MeshRenderer> renderers = new List <MeshRenderer>();

            if (MeshDraw)
            {
                Matrix4 proj;
                if (Orthographic)
                {
                    proj = Matrix4.CreateOrthographic(TargetTexture.Size.Width, TargetTexture.Size.Height, Near, Far);
                }
                proj = Matrix4.CreatePerspectiveFieldOfView(FoV, Aspect, Near, Far);

                sp.pointLights = null;
                sp.spotLights  = null;
                sp.camera      = this;
                sp.resolution  = new Vector2(TargetTexture.Size.Width, TargetTexture.Size.Height);
                sp.deltaTime   = deltaTime;
                sp.oldViewProj = sp.viewProj;
                sp.view        = View;
                sp.proj        = proj;
                sp.cameraPos   = wp;
                sp.cameraDir   = WorldDirection;
                sp.dirLight    = MMW.DirectionalLight;
                var viewproj = sp.view * sp.proj;
                sp.viewProj        = viewproj;
                sp.viewInverse     = sp.view.Inverted();
                sp.projInverse     = sp.proj.Inverted();
                sp.viewProjInverse = sp.viewProj.Inverted();
                sp.environmentMap  = EnvironmentMap;

                // 描画準備
                clipTask.Wait();

                var query = 0;
                foreach (var obj in objects)
                {
                    if (!obj.Enabled)
                    {
                        continue;
                    }
                    if (clipDic[obj])
                    {
                        continue;
                    }

                    var rds = obj.GetComponents <MeshRenderer>();
                    renderers.AddRange(rds);

                    foreach (var r in rds)
                    {
                        r.query = queries[query++];
                    }
                }



                foreach (var obj in objects)
                {
                    if (!obj.Enabled)
                    {
                        continue;
                    }
                    if (clipDic[obj])
                    {
                        continue;
                    }

                    var rds      = obj.GetComponents <MeshRenderer>();
                    var animator = obj.GetComponent <AAnimator>();
                    var morpher  = obj.GetComponent <AMorpher>();

                    var world    = obj.Transform.WorldTransform;
                    var oldWorld = obj.Transform.OldWorldTransfom;
                    foreach (var r in rds)
                    {
                        for (var i = 0; i < r.MaterialCount; i++)
                        {
                            var mat = r.GetMaterialAt(i);
                            if (!drawMeshDic.ContainsKey(mat.Shader))
                            {
                                drawMeshDic.Add(mat.Shader, new Dictionary <Material, List <SubMeshData> >());
                            }
                            if (!drawMeshDic[mat.Shader].ContainsKey(mat))
                            {
                                drawMeshDic[mat.Shader].Add(mat, new List <SubMeshData>());
                            }
                        }
                        foreach (var sm in r.Mesh.subMeshes)
                        {
                            var mat = r.GetMaterial(sm.materialIndex);
                            var smd = new SubMeshData()
                            {
                                SubMesh           = sm,
                                WorldTransform    = world,
                                WorldTransformInv = world.Inverted(),
                                OldWorldTransform = oldWorld,
                                Visible           = r.Visible,
                                CastShadow        = r.CastShadow,
                                GameObject        = obj,
                                Morpher           = morpher,
                                Animator          = animator,
                                OcclusionQuery    = r.query,
                                MeshRenderer      = r,
                            };
                            drawMeshDic[mat.Shader][mat].Add(smd);
                        }
                    }
                }

                findAnimTask.Wait();
                foreach (var task in animTasks)
                {
                    task.Wait();
                }
                foreach (var a in animList)
                {
                    if (!a.EnableAsyncCalc)
                    {
                        a.CalcTransform();
                    }
                    a.UpdateData();
                }
                foreach (var m in morphList)
                {
                    if (!m.EnableAsyncCalc)
                    {
                        m.CalcMorph();
                    }
                    m.UpdateData();
                }

                // 影の準備
                if (ShadowMapping && MMW.Configuration.ShadowQuality != MMWConfiguration.ShadowQualityType.NoShadow)
                {
                    Vector3 lightDir = MMW.DirectionalLight.WorldDirection;
                    Vector3 center   = wp;
                    Matrix4 view     = Matrix4.Identity;
                    Matrix4 projo    = Matrix4.Identity;

                    // render to far shadow depth map

                    /*
                     * {
                     *  view = Matrix4.LookAt(Vector3.Zero, lightDir, Vector3.UnitY);
                     *  projo = Matrix4.CreateOrthographic(240, 240, -150, 150);
                     *  sp.viewProj = view * projo;
                     *  if (prevLightDir != lightDir)
                     *  {
                     *      RenderToDepthMap(shadowDepthRT1, sp, drawMeshDic);
                     *  }
                     *  sp.shadowDepthBias1 = sp.viewProj * shadowDepthBias;
                     *  sp.shadowDepthMap1 = shadowDepthRT1.ColorDst0;
                     * }*/

                    //  render to middle shadow depth map
                    {
                        view        = Matrix4.LookAt(center, center + lightDir, Vector3.UnitY);
                        projo       = Matrix4.CreateOrthographic(40, 40, -150, 150);
                        sp.viewProj = view * projo;
                        RenderToDepthMap(shadowDepthRT2, sp, drawMeshDic);
                        sp.shadowDepthBias2 = sp.viewProj * shadowDepthBias;
                        sp.shadowDepthMap2  = shadowDepthRT2.ColorDst0;
                    }

                    //  render to near shadow depth map
                    {
                        view        = Matrix4.LookAt(center, center + lightDir, Vector3.UnitY);
                        projo       = Matrix4.CreateOrthographic(10, 10, -80, 80);
                        sp.viewProj = view * projo;
                        RenderToDepthMap(shadowDepthRT3, sp, drawMeshDic);
                        sp.shadowDepthBias3 = sp.viewProj * shadowDepthBias;
                        sp.shadowDepthMap3  = shadowDepthRT3.ColorDst0;
                    }

                    sp.viewProj   = viewproj;
                    prevLightDir  = lightDir;
                    prevCameraPos = center;
                }
            }

            // 遅延描画
            deferredRT.Bind(new Color4(0, 0, 0, 0));

            // スカイボックス
            if (ClearFlag == ClearFlag.SkyBox)
            {
                var dir = GameObject.Transform.WorldDirectionZ;
                if (ForceTarget)
                {
                    dir = (Target - wp).Normalized();
                }

                var mat    = Matrix4.LookAt(Vector3.Zero, dir, Up) * Projection;
                var oldMat = Matrix4.LookAt(Vector3.Zero, prevCameraDir, Up) * Projection;

                GL.Disable(EnableCap.DepthTest);
                backShader.UseShader();
                backShader.SetParameter(backShader.loc_mvp, ref mat, false);
                backShader.SetParameter(backShader.loc_oldmvp, ref oldMat, false);
                backShader.SetParameter(backShader.loc_albedo, SkyBoxColor);
                backShader.SetParameter(backShader.loc_fog, MMW.FogIntensity);
                backShader.SetParameter(backShader.loc_fogcolor, MMW.MainCamera.ClearColor);
                backShader.SetParameter(TextureUnit.Texture0, EnvironmentMap);
                Drawer.DrawSubMesh(cubeMesh.subMeshes[0]);
                backShader.UnuseShader();
                GL.Enable(EnableCap.DepthTest);

                prevCameraDir = dir;
            }

            // その他スクリプトの描画(メッシュ描画前)
            if (ScriptDraw)
            {
                layerSortTask.Wait();
                DrawScripts(beforeComs, (float)deltaTime);
                DrawMeshScripts(beforeComs, (float)deltaTime);
            }

            if (MeshDraw)
            {
                // オクルージョン描画
                //DrawOcclusionBox(renderers);
                DrawDeferredMeshes(sp, drawMeshDic);
                //DrawMeshScripts(meshComs, (float)deltaTime);
            }

            // その他スクリプトの描画
            if (ScriptDraw)
            {
                DrawScripts(afterComs, (float)deltaTime);
                DrawMeshScripts(afterComs, (float)deltaTime);
            }

            // ライトカリング
            lightExtractTask.Wait();
            lightRT.Bind(new Color4(0, 0, 0, 0));
            GL.BindBuffer(BufferTarget.ShaderStorageBuffer, ssbo_light);
            GL.BufferSubData(BufferTarget.ShaderStorageBuffer, (IntPtr)0, lights.Count * 20 * 4, lights.ToArray());
            GL.BindBuffer(BufferTarget.ShaderStorageBuffer, ssbo_count);
            GL.BufferSubData(BufferTarget.ShaderStorageBuffer, (IntPtr)0, initCounts.Length * 4, initCounts);
            GL.BindBuffer(BufferTarget.ShaderStorageBuffer, 0);

            lightCullingShader.UseShader();
            AAnimator.BindIdentity(1, 2);
            GL.CullFace(CullFaceMode.Back);
            GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 3, ssbo_count);
            GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 4, ssbo_index);
            lightCullingShader.SetParameter(lightCullingShader.loc_resolution, lightRT.Size.ToVector2());
            var syncList = new List <IntPtr>();

            for (var i = 0; i < lights.Count; i++)
            {
                lightCullingShader.SetParameter(lightCullingShader.loc_index, i);
                var mvp = MatrixHelper.CreateTransform(lights[i].pos.Xyz, Vector3.Zero, new Vector3(lights[i].radius * 1.2f)) * sp.viewProj;
                lightCullingShader.SetParameter(lightCullingShader.loc_mvp, ref mvp, false);
                syncList.Add(GL.FenceSync(SyncCondition.SyncGpuCommandsComplete, WaitSyncFlags.None));
                Drawer.DrawSubMesh(plMesh.subMeshes[0]);
            }
            GL.CullFace(CullFaceMode.Front);
            lightCullingShader.UnuseShader();

            foreach (var sync in syncList)
            {
                GL.DeleteSync(sync);
            }

            // レンダーターゲットをセット
            TargetTexture.Bind();
            GL.ClearColor(ClearColor);
            if (ClearFlag == ClearFlag.SolidColor)
            {
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
            }
            else if (ClearFlag == ClearFlag.DepthOnly)
            {
                GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
            }
            else if (ClearFlag == ClearFlag.SkyBox)
            {
                GL.ClearColor(Color4.White);
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
            }

            // メッシュ描画
            if (MeshDraw)
            {
                /*
                 * var srcRect = new RectangleF(0, 0, 1.0f, 1.0f);
                 * var dstRect1 = new RectangleF(0, 0, 0.25f, 0.5f);
                 * var dstRect2 = new RectangleF(0, 0.5f, 0.25f, 0.5f);
                 * var dstRect3 = new RectangleF(0.25f, 0, 0.25f, 0.5f);
                 * var dstRect4 = new RectangleF(0.25f, 0.5f, 0.25f, 0.5f);
                 * var dstRect5 = new RectangleF(0.5f, 0, 0.25f, 0.5f);
                 * var dstRect6 = new RectangleF(0.5f, 0.5f, 0.25f, 0.5f);
                 * var dstRect7 = new RectangleF(0.75f, 0, 0.25f, 0.5f);
                 * var dstRect8 = new RectangleF(0.75f, 0.5f, 0.25f, 0.5f);
                 * Drawer.DrawTexture(sp.shadowDepthMap2, srcRect, dstRect1);
                 * Drawer.DrawTexture(sp.shadowDepthMap3, srcRect, dstRect2);
                 * Drawer.DrawTexture(deferredRT.ColorDst2, srcRect, dstRect3);
                 * Drawer.DrawTexture(deferredRT.ColorDst3, srcRect, dstRect4);
                 * Drawer.DrawTexture(deferredRT.ColorDst4, srcRect, dstRect5);
                 * Drawer.DrawTexture(deferredRT.ColorDst5, srcRect, dstRect6);
                 * Drawer.DrawTexture(deferredRT.ColorDst6, srcRect, dstRect7);
                 * Drawer.DrawTexture(deferredRT.ColorDst7, srcRect, dstRect8);
                 */
                //Drawer.DrawTexture(lightRT.ColorDst0);

                sp.ortho                     = orthoMat;
                sp.deferredAlbedoMap         = deferredRT.ColorDst0;
                sp.deferredWorldPosMap       = deferredRT.ColorDst1;
                sp.deferredWorldNormalMap    = deferredRT.ColorDst2;
                sp.deferredPhysicalParamsMap = deferredRT.ColorDst3;
                sp.deferredF0Map             = deferredRT.ColorDst4;
                sp.deferredDepthMap          = deferredRT.ColorDst5;
                sp.deferredShadowMap         = deferredRT.ColorDst6;
                sp.deferredVelocityMap       = deferredRT.ColorDst7;

                deferredShader.UseShader();
                deferredShader.SetUniqueParameter(sp, true);
                GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 5, ssbo_light);
                Drawer.DrawTextureMesh();
                deferredShader.UnuseShader();

                GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 3, 0);
                GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 4, 0);
                GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 5, 0);
            }

            // イメージエフェクトをかける
            var effects = GameObject.GetComponents <ImageEffect>();

            if (effects != null)
            {
                for (var i = 0; i < effects.Length; i++)
                {
                    if (!effects[i].Enabled)
                    {
                        continue;
                    }
                    if (effects[i].RequireMaps.Contains(RequireMap.Depth))
                    {
                        effects[i].DepthMap = sp.deferredDepthMap;
                    }
                    if (effects[i].RequireMaps.Contains(RequireMap.Position))
                    {
                        effects[i].PositionMap = sp.deferredWorldPosMap;
                    }
                    if (effects[i].RequireMaps.Contains(RequireMap.Normal))
                    {
                        effects[i].NormalMap = sp.deferredWorldNormalMap;
                    }
                    if (effects[i].RequireMaps.Contains(RequireMap.Velocity))
                    {
                        effects[i].VelocityMap = sp.deferredVelocityMap;
                    }
                    effects[i].Draw(deltaTime);
                }
            }

            GL.Clear(ClearBufferMask.DepthBufferBit);

            // UI層のゲームオブジェクトを描画
            if (UIDraw && layerMask.Get(GameObject.LayerUI))
            {
                DrawScripts(uiComs, (float)deltaTime);
                DrawMeshScripts(uiComs, (float)deltaTime);
            }
        }
예제 #19
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            // HDR抽出
            hdrRT.Bind(Color4.Black);
            hdrShader.UseShader();
            hdrShader.SetParameter(hdrShader.loc_resolution, hdrRT.Size.ToVector2().Inverse());
            hdrShader.SetParameter(hdrShader.loc_mvp, ref orthoMatrix, false);
            hdrShader.SetParameter(hdrShader.loc_threshold, Threshold);
            hdrShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            Drawer.DrawTextureMesh();
            hdrShader.UnuseShader();

            // HDR画像のぼかし画像を生成
            for (var i = 0; i < BlurNum; i++)
            {
                if (i == 0)
                {
                    blurs[i].SrcTexture = hdrRT.ColorDst0;
                }
                else
                {
                    blurs[i].SrcTexture = blurRTs[i - 1].ColorDst0;
                }
                blurs[i].Draw(deltaTime);
            }

            // Bloom処理
            bloomRT.Bind(Color4.Black);
            bloomShader.UseShader();
            bloomShader.SetParameter(bloomShader.loc_resolution, bloomRT.Size.ToVector2().Inverse());
            bloomShader.SetParameter(bloomShader.loc_mvp, ref orthoMatrix, false);
            bloomShader.SetParameter(bloomShader.loc_intensity, Intensity);
            bloomShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            var units = new TextureUnit[]
            {
                TextureUnit.Texture1,
                TextureUnit.Texture2,
                TextureUnit.Texture3,
                TextureUnit.Texture4,
                TextureUnit.Texture5,
            };

            for (var i = 0; i < 5; i++)
            {
                if (i < BlurNum)
                {
                    bloomShader.SetParameter(units[i], blurRTs[i].ColorDst0);
                }
                else
                {
                    bloomShader.SetParameter(units[i], bloomShader.black);
                }
            }
            Drawer.DrawTextureMesh();
            bloomShader.UnuseShader();

            // 書き出し
            rt.Bind();
            Drawer.DrawTexture(bloomRT.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #20
0
        public override void Draw(double deltaTime)
        {
            RenderTexture rt = RenderTexture;

            if (rt == null)
            {
                if (Camera == null)
                {
                    return;
                }
                else
                {
                    rt = Camera.TargetTexture;
                }
            }
            if (!rt.Loaded)
            {
                return;
            }

            totalTime += deltaTime;
            if (totalTime > ExtractBrightInterval)
            {
                totalTime -= ExtractBrightInterval;
                // 平均輝度抽出
                var reso = aveRT.Size.ToVector2().Inverse();
                aveRT.Bind(Color4.Black);
                aveShader.UseShader();
                aveShader.SetParameter(aveShader.loc_resolution, ref reso);
                aveShader.SetParameter(aveShader.loc_mvp, ref orthoMatrix, false);
                aveShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
                Drawer.DrawTextureMesh();
                aveShader.UnuseShader();

                // 縮小
                shrinkShader.UseShader();
                for (var i = 0; i < shrinkRTs.Length; i++)
                {
                    shrinkRTs[i].Bind(Color4.Black);
                    if (i == 0)
                    {
                        shrinkShader.SetParameter(TextureUnit.Texture0, aveRT.ColorDst0);
                    }
                    else
                    {
                        shrinkShader.SetParameter(TextureUnit.Texture0, shrinkRTs[i - 1].ColorDst0);
                    }
                    shrinkShader.SetParameter(shrinkShader.loc_mvp, ref orthoMatrix, false);
                    shrinkShader.SetParameter(shrinkShader.loc_offset, ref reso);
                    reso = shrinkRTs[i].Size.ToVector2().Inverse();
                    shrinkShader.SetParameter(shrinkShader.loc_resolution, ref reso);

                    if (i == shrinkRTs.Length - 1)
                    {
                        GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 6, ssbo_lum);
                    }
                    Drawer.DrawTextureMesh();
                }
                shrinkShader.UnuseShader();
            }

            // トーンマッピング
            toneRT.Bind(Color4.Black);
            toneShader.UseShader();
            toneShader.SetParameter(toneShader.loc_resolution, toneRT.Size.ToVector2().Inverse());
            toneShader.SetParameter(toneShader.loc_mvp, ref orthoMatrix, false);
            toneShader.SetParameter(toneShader.loc_intensity, Intensity);
            toneShader.SetParameter(toneShader.loc_rate, (float)(totalTime / ExtractBrightInterval));
            toneShader.SetParameter(TextureUnit.Texture0, rt.ColorDst0);
            toneShader.SetParameter(TextureUnit.Texture1, shrinkRTs.Last().ColorDst0);
            GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 6, ssbo_lum);
            Drawer.DrawTextureMesh();
            GL.BindBufferBase(BufferRangeTarget.ShaderStorageBuffer, 6, 0);
            toneShader.UnuseShader();

            // 書き出し
            rt.Bind();
            Drawer.DrawTexture(toneRT.ColorDst0);

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
예제 #21
0
        public void Render()
        {
            // Bind OpenGL
            m_window.MakeCurrent();

            // ----------
            // DRAW WORLD
            // ----------

            // Clear world render texture
            m_worldRenderTexture.Bind();
            var clearColor = (m_sky != null) ? m_sky.BackgroundColour : Vector3.Zero;

            GL.ClearColor(clearColor.X, clearColor.Y, clearColor.Z, 1.0f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            App.CheckOpenGLError();

            // Draw the skybox
            if (m_sky != null)
            {
                var backgroundImage = m_sky.Sky.BackgroundImage;
                if (backgroundImage != null)
                {
                    // Draw background image
                    GL.DepthMask(false);
                    var backgroundTexture = Texture.Get(backgroundImage, true);
                    m_backgroundEffect.Texture = backgroundTexture;
                    m_backgroundEffect.Bind();
                    m_fullScreenQuad.Draw();
                    GL.DepthMask(true);
                }

                m_sky.DrawBackground(m_camera);
                GL.Clear(ClearBufferMask.DepthBufferBit);
            }

            // Draw states
            if (m_transition != null)
            {
                m_currentState.PostDraw();
                m_pendingState.PreDraw();
            }
            else
            {
                m_currentState.Draw();
            }

            // Draw the camera marker
            if (UseDebugCamera && m_debugMenu.Visible)
            {
                m_cameraAxisMarker.Draw(m_camera);
            }

            m_worldRenderTexture.Unbind();

            // -----------------
            // POSTPROCESS WORLD
            // -----------------

            // Clear screen
            m_upscaleRenderTexture.Bind();
            GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // Draw texture to screen
            m_postEffect.Texture = m_worldRenderTexture;
            m_postEffect.Bind();
            m_fullScreenQuad.Draw();

            // --------
            // DRAW GUI
            // --------

            if (RenderUI)
            {
                // Draw GUI
                m_screen.DrawExcept(m_debugMenu, m_cursor);
                m_screen.DrawOnly(m_cursor);
            }

            // Draw debug GUI
            m_screen.DrawOnly(m_debugMenu);

            if (RenderUI)
            {
                // -----------
                // DRAW 3D GUI
                // -----------

                // Clear world render texture
                m_worldRenderTexture.Bind();
                GL.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                App.CheckOpenGLError();

                // Draw 3D GUI to offscreen buffer
                m_screen.Draw3D();

                // ------------------
                // POSTPROCESS 3D GUI
                // ------------------

                // Clear screen
                m_upscaleRenderTexture.Bind();

                // Draw texture to screen
                m_postEffect.Texture = m_worldRenderTexture;
                m_postEffect.Bind();
                m_fullScreenQuad.Draw();
            }

            // -----------------
            // UPSCALE TO SCREEN
            // -----------------

            // Clear screen
            m_upscaleRenderTexture.Unbind();
            GL.Viewport(0, 0, Window.Width, Window.Height);
            GL.Clear(ClearBufferMask.DepthBufferBit);

            // Draw texture to screen
            m_upscaleEffect.Texture = m_upscaleRenderTexture;
            m_upscaleEffect.Bind();
            m_fullScreenQuad.Draw();

            // ------
            // FINISH
            // ------

            if (m_pendingScreenshot != null)
            {
                // Take screenshot
                GL.Finish();
                TakeScreenshot();
            }

            // Flip OpenGL
            m_window.SwapBuffers();
        }
예제 #22
0
        public static void Render()
        {
            //Render Scene
            if (ppEffects.Count > 0)
            {
                grabPass1.Bind();
            }
            else
            {
                screenBuffer.Bind();
            }
            GL.ClearColor(Color4.Black);
            GL.ClearStencil(0);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.StencilTest);
            GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);
            GL.CullFace(CullFaceMode.Back);
            UpdateMatrices();
            foreach (Renderer r in registeredRenderers)
            {
                if (r.enabled)
                {
                    if (r.transform.entity != null)
                    {
                        r.transform.entity.WriteToStencilBuffer();
                    }
                    r.Render();
                }
            }
            HoveredID = RenderTexture.ReadStencil((int)Input.MousePosition.X, window.Height - (int)Input.MousePosition.Y);
            screenBuffer.Bind();

            //Do Post Processing
            currentGrabPass = false;
            for (int i = 0; i < ppEffects.Count; i++)
            {
                if (i < ppEffects.Count - 1)
                {
                    if (!currentGrabPass)
                    {
                        grabPass2.Bind();
                    }
                    else
                    {
                        grabPass1.Bind();
                    }
                }
                else
                {
                    screenBuffer.Bind();
                }
                PostProcess(i);
                if (i < ppEffects.Count - 1)
                {
                    screenBuffer.Bind();
                }
                currentGrabPass = !currentGrabPass;
            }
            GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);

            //Draw final screenbuffer
            GL.ClearColor(Color4.Black);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
            GL.Enable(EnableCap.DepthTest);
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, screenBuffer.Handle);
            screenBufferShader.Use();
            GL.Uniform1(screenBufferShader.GetUniformLocation("a_screen"), 0);
            ppQuad.subMeshes[0].vao.Bind();
            GL.DrawElements(BeginMode.Triangles, 6, DrawElementsType.UnsignedInt, 0);
        }
예제 #23
0
        //static OpenGLDevice NuklearDev;

        static void Main(string[] args)
        {
            /*IBWFile F = IBWLoader.Load("dataset/ibw/Image0018.ibw");
             *
             * for (int i = 0; i < F.Depth; i++) {
             *      Bitmap Bmp = new Bitmap(F.Width, F.Height);
             *
             *      int D_Dim = i;
             *
             *      float Min = float.MaxValue;
             *      float Max = float.MinValue;
             *
             *      for (int y = 0; y < F.Height; y++) {
             *              for (int x = 0; x < F.Width; x++) {
             *                      float Flt = (float)F.GetData(x, y, D_Dim) * 1000000000;
             *
             *                      Min = Math.Min(Min, Flt);
             *                      Max = Math.Max(Max, Flt);
             *              }
             *      }
             *
             *      float Offset = -Min;
             *      float OffsetMax = Max + Offset;
             *      float ScaleVal = 255.0f / OffsetMax;
             *
             *      Min = float.MaxValue;
             *      Max = float.MinValue;
             *
             *      for (int y = 0; y < F.Height; y++) {
             *              for (int x = 0; x < F.Width; x++) {
             *                      float Flt = ((float)F.GetData(x, y, D_Dim) * 1000000000 + Offset) * ScaleVal;
             *
             *                      int Clr = (int)Flt;
             *                      Bmp.SetPixel(x, F.Height - y - 1, System.Drawing.Color.FromArgb(255, Clr, Clr, Clr));
             *              }
             *      }
             *
             *      Bmp.Save("test_" + i + ".png");
             * }
             *
             *
             * File.WriteAllText("text_data.txt", F.NoteData);
             *
             *
             * Console.WriteLine("Done!");
             * Console.ReadLine();
             * return;//*/



            const float Scale = 0.9f;

            ClearColor = new FishGfx.Color(60, 80, 100);

            RenderAPI.GetDesktopResolution(out int W, out int H);
            RWind = new RenderWindow((int)(W * Scale), (int)(H * Scale), "Vector PFM");

            Console.WriteLine("OpenGL {0}", RenderAPI.Version);
            Console.WriteLine("Running on {0}", RenderAPI.Renderer);

            // Load shader programs
            Shader_DrawRayCast = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default3d.vert"),
                                                   new ShaderStage(ShaderType.FragmentShader, "data/defaultRayCast.frag"));
            Shader_DrawRayCast.Uniforms.Camera.SetPerspective(RWind.GetWindowSizeVec());
            Shader_DrawRayCast.Uniforms.Camera.Position   = new Vector3(0, 300, 0);
            Shader_DrawRayCast.Uniforms.Camera.PitchClamp = new Vector2(-80, 80);

            Shader_DrawFlat = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default3d.vert"),
                                                new ShaderStage(ShaderType.FragmentShader, "data/defaultFlatColor.frag"));
            Shader_DrawFlat.Uniforms.Camera = Shader_DrawRayCast.Uniforms.Camera;

            Shader_Screen = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default.vert"),
                                              new ShaderStage(ShaderType.FragmentShader, "data/default.frag"));
            Shader_Screen.Uniforms.Camera.SetOrthogonal(0, 0, 1, 1);

            Shader_Textured = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default3d.vert"),
                                                new ShaderStage(ShaderType.FragmentShader, "data/default.frag"));
            Shader_Textured.Uniforms.Camera = Shader_DrawRayCast.Uniforms.Camera;

            //NuklearDev = new OpenGLDevice(RWind.GetWindowSizeVec());
            //NuklearAPI.Init(NuklearDev);

            RWind.OnMouseMoveDelta += (Wnd, X, Y) => Shader_DrawRayCast.Uniforms.Camera.Update(new Vector2(-X, -Y));
            RWind.OnKey            += OnKey;
            //RWind.OnMouseMove += (Wnd, X, Y) => NuklearDev.OnMouseMove((int)X, (int)Y);

            RWind.OnMouseMoveDelta += (Wnd, X, Y) => {
                if (LeftMouse)
                {
                    const float MoveSpeed = 1.0f;

                    if (X != 0 || Y != 0)
                    {
                        Camera Cam = Shader_DrawRayCast.Uniforms.Camera;

                        if (X != 0)
                        {
                            Cam.Position -= Cam.WorldRightNormal * MoveSpeed * -X;
                        }

                        if (Y != 0)
                        {
                            Cam.Position += Cam.WorldUpNormal * MoveSpeed * -Y;
                        }

                        RecalcCamera();
                    }
                }
                else if (RightMouse)
                {
                    DesiredPivotDistance += Y;
                    RecalcCamera();
                }
            };

            HMap = new Terrain();
            HMap.LoadFromImage(Image.FromFile("dataset/data2/heightmap.png"), 100);
            //HMap.LoadFromImage(Image.FromFile("dataset/height_test.png"), 10);
            //HMap.LoadFromImage(Image.FromFile("dataset/owl.png"), 100);


            DesiredPivotDistance = float.PositiveInfinity;
            CameraPivot          = new Vector3(HMap.Width / 2, HMap.GetHeight(HMap.Width / 2, HMap.Height / 2), HMap.Height / 2);
            RecalcCamera();

            PinMesh = new Mesh3D {
                PrimitiveType = PrimitiveType.Triangles
            };
            PinMesh.SetVertices(GfxUtils.LoadObj("data/models/pin/pin.obj"));

            PinTexture = Texture.FromFile("data/models/pin/pin_mat.png");

            Mesh3D Vectors = new Mesh3D {
                PrimitiveType = PrimitiveType.Lines
            };

            {
                //Vertex3[] Verts = new Vertex3[HMap.Width * HMap.Height * 2];
                List <Vertex3> Verts = new List <Vertex3>();

                for (int i = 0; i < HMap.Width * HMap.Height * 2; i += 2)
                {
                    int X = (i / 2) % HMap.Width;
                    int Y = (i / 2) / HMap.Width;

                    const int Density = 2;
                    if (X % Density != 0 || Y % Density != 0)
                    {
                        continue;
                    }

                    float Height = HMap.GetHeight(X, Y);

                    Verts.Add(new Vertex3(new Vector3(X, Height - 0.5f, Y), FishGfx.Color.Black));
                    Verts.Add(new Vertex3(new Vector3(X, Height + 20, Y), FishGfx.Color.White));
                }

                Vectors.SetVertices(Verts.ToArray());
            }

            RWind.GetWindowSize(out int WindowWidth, out int WindowHeight);
            RenderTexture Screen = new RenderTexture(WindowWidth, WindowHeight);

            RayCastingTexture = Screen.CreateNewColorAttachment(1);

            Background = Texture.FromFile("data/background.png");

            Mesh2D ScreenQuad = new Mesh2D();

            ScreenQuad.SetVertices(new Vertex2[] {
                new Vertex2(new Vector2(0, 0), new Vector2(0, 0)),
                new Vertex2(new Vector2(0, 1), new Vector2(0, 1)),
                new Vertex2(new Vector2(1, 1), new Vector2(1, 1)),
                new Vertex2(new Vector2(1, 0), new Vector2(1, 0))
            });
            ScreenQuad.SetElements(new uint[] { 0, 1, 2, 0, 2, 3 }.Reverse().ToArray());

            Stopwatch SWatch = Stopwatch.StartNew();
            float     Dt     = 0;

            while (!RWind.ShouldClose)
            {
                Update(Dt);

                // Draw the world onto a render texture including the ray casting buffer
                Screen.Bind(0, 1);
                {
                    Shader_DrawRayCast.Bind();
                    Gfx.Clear(FishGfx.Color.Transparent);

                    /*Gfx.EnableCullFace(false);
                     * HMap.Draw();
                     * Gfx.EnableCullFace(true);*/

                    // Draw back face
                    Gfx.CullFront();
                    Texture Orig = HMap.OverlayTexture;
                    HMap.OverlayTexture = Background;
                    HMap.Draw();

                    // Draw front face
                    Gfx.CullBack();
                    HMap.OverlayTexture = Orig;
                    HMap.Draw();

                    Shader_DrawRayCast.Unbind();
                }
                Screen.Unbind();

                // Draw other stuff
                Screen.Bind(0);
                {
                    Shader_DrawFlat.Bind();
                    Vectors.Draw();
                    Shader_DrawFlat.Unbind();

                    Shader_Textured.Bind();
                    Shader_Textured.SetModelMatrix(Matrix4x4.CreateScale(2) * Matrix4x4.CreateTranslation(CameraPivot));
                    PinTexture.BindTextureUnit();
                    PinMesh.Draw();
                    PinTexture.UnbindTextureUnit();
                    Shader_Textured.Unbind();
                }
                Screen.Unbind();

                // Draw render texture and GUI to screen
                Shader_Screen.Bind();
                {
                    Gfx.Clear(ClearColor);
                    Gfx.EnableDepthDest(false);

                    if (FunctionMode == 1)
                    {
                        Screen.Color.BindTextureUnit();
                    }
                    else if (FunctionMode == 2)
                    {
                        RayCastingTexture.BindTextureUnit();
                    }

                    ScreenQuad.Draw();
                    //NuklearAPI.Frame(DrawGUI);
                    Gfx.EnableDepthDest(true);
                }
                Shader_Screen.Unbind();

                // Swap buffers, do magic
                RWind.SwapBuffers();
                Events.Poll();

                while (SWatch.ElapsedMilliseconds / 1000.0f < 1.0f / 60.0f)
                {
                    ;
                }
                Dt = SWatch.ElapsedMilliseconds / 1000.0f;
                SWatch.Restart();
            }
        }