Example #1
0
        private void TestToStringWithCulture(CultureInfo culture)
        {
            CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = culture;
            try
            {
                string listSeparator = culture.TextInfo.ListSeparator;
                string decimalSeparator = culture.NumberFormat.NumberDecimalSeparator;
                var o = new Matrix4F(
                    1.1f, 2.2f, 3.3f, 4.4f,
                    5.5f, 6.6f, 7.7f, 8.8f,
                    9.9f, 10.10f, 11.11f, 12.12f,
                    13.13f, 14.14f, 15.15f, 16.16f);

                string s = o.ToString(null, null);
                TestToStringResults(o, s, listSeparator, decimalSeparator);

                s = o.ToString();
                Assert.True(s.Contains(listSeparator));

                s = o.ToString("G", culture);
                TestToStringResults(o, s, listSeparator, decimalSeparator);

                s = o.ToString("R", culture);
                TestToStringResults(o, s, listSeparator, decimalSeparator);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = originalCulture;
            }
        }
Example #2
0
        /// <summary>
        /// Renders the control</summary>
        /// <param name="action">Render action</param>
        /// <param name="camera">Camera</param>
        /// <param name="state">Render state</param>
        /// <param name="transform">Transform</param>
        public void Render(IRenderAction action, Camera camera, RenderState state, Matrix4F transform)
        {
            float s1, s2, s3;

            // apply xform
            Gl.glPushMatrix();
            Util3D.glMultMatrixf(transform);

            CalcAxisLengths(camera, transform, out s1, out s2, out s3);

            bool drawX, drawY, drawZ;
            DecideArrowDrawing(transform, camera, out drawX, out drawY, out drawZ);

            if (drawX)
            {
                RenderXArrow(s1);
                RenderXAxis(s1);
            }
            if (drawY)
            {
                RenderYArrow(s2);
                RenderYAxis(s2);
            }
            if (drawZ)
            {
                RenderZArrow(s3);
                RenderZAxis(s3);
            }

            RenderXYSquare(s1 * SquareLength, s2 * SquareLength, true);
            RenderYZSquare(s2 * SquareLength, s3 * SquareLength, true);
            RenderXZSquare(s1 * SquareLength, s3 * SquareLength, true);
            
            Gl.glPopMatrix();
        }
Example #3
0
 /// <summary>
 /// Constructor</summary>
 /// <param name="renderObject">RenderObject. A reference is held to this, so that IRenderObject.Dispatch
 /// can be called.</param>
 /// <param name="transform">Transform to use when dispatching the RenderObject; a reference is held</param>
 /// <param name="graphPath">Graph path leading to RenderObject; a reference is held</param>
 /// <param name="renderState">RenderState to use for RenderObject; is copied</param>
 public TraverseNode(
     IRenderObject renderObject,
     Matrix4F transform,
     Stack<SceneNode> graphPath,
     RenderState renderState)
 {
     Init(renderObject, transform, graphPath, renderState);
 }
Example #4
0
 /// <summary>
 /// Decomposes the given matrix to translation, scale, 
 /// and rotation and set them to given Transformable node.        
 /// </summary>        
 public static void SetTransform(ITransformable xform, Matrix4F mtrx)
 {
     xform.Translation = mtrx.Translation;
     xform.Scale = mtrx.GetScale();
     Vec3F rot = new Vec3F();
     mtrx.GetEulerAngles(out rot.X, out rot.Y, out rot.Z);
     xform.Rotation = rot;
     xform.UpdateTransform();
 }
Example #5
0
 public static void DrawUnitSquare(GUILayer.SimpleRenderingContext context, Matrix4F xform, Color color)
 {
     GameEngine.DrawPrimitive(context, PrimitiveType.LineList,
         s_linesVertId,
         s_unitSquareStartVertex,
         s_unitSquareVertexCount,
         color,
         xform);
 }
Example #6
0
 public static void DrawCircle(GUILayer.SimpleRenderingContext context, Matrix4F xform, Color color)
 {
     GameEngine.DrawPrimitive(context, PrimitiveType.LineStrip,
        s_circleVerts,
        0,
        s_circleVertexCount,
        color,
        xform);
 }
Example #7
0
 public static void DrawPivot(GUILayer.SimpleRenderingContext context, Matrix4F xform, Color c)
 {
     GameEngine.DrawPrimitive(context, PrimitiveType.LineStrip,
       s_pivotVerts,
       0,
       s_pivotVertexCount,
       c,
       xform);            
 }
Example #8
0
 /// <summary>
 /// Initializes instance</summary>
 /// <param name="renderObject">RenderObject. A reference is held to this, so that IRenderObject.Dispatch
 /// can be called.</param>
 /// <param name="transform">Transform to use when dispatching the RenderObject; a reference is held</param>
 /// <param name="graphPath">Graph path leading to RenderObject; a reference is held</param>
 /// <param name="renderState">RenderState to use for RenderObject; is copied</param>
 public void Init(
     IRenderObject renderObject,
     Matrix4F transform,
     Stack<SceneNode> graphPath,
     RenderState renderState)
 {
     m_renderObject = renderObject;
     m_transform = transform;
     m_renderState.Init(renderState);
     m_graphPath = graphPath.ToArray();//faster to create every time than to cache!
 }
Example #9
0
 public static void DrawUnitSquare(Matrix4F xform, Color color)
 {
     GameEngine.DrawPrimitive(PrimitiveType.LineList,
         s_linesVertId,
         s_unitSquareStartVertex,
         s_unitSquareVertexCount,
         color,
         xform,
         RenderFlag
         );
 }
Example #10
0
 public static void DrawCircle(Matrix4F xform, Color color)
 {            
     GameEngine.DrawPrimitive(PrimitiveType.LineStrip,
        s_circleVerts,
        0,
        s_circleVertexCount,
        color,
        xform,
        RenderFlag
        );
 }
Example #11
0
 public static void DrawPivot(Matrix4F xform, Color c)
 {
     GameEngine.DrawPrimitive(PrimitiveType.LineStrip,
       s_pivotVerts,
       0,
       s_pivotVertexCount,
       c,
       xform,
       RenderFlag
       );            
 }
Example #12
0
 private void TestToStringResults(Matrix4F o, string s, string listSeparator, string decimalSeparator)
 {
     string[] results = s.Split(new[] { listSeparator }, StringSplitOptions.RemoveEmptyEntries);
     Assert.AreEqual(results.Length, 16);
     for (int i = 0; i < 16; i++)
     {
         Assert.True(results[i].Contains(decimalSeparator));
         float result = float.Parse(results[i]);
         Assert.AreEqual(result, o[i]);
     }
 }
Example #13
0
        public override void OnBeginDrag()
        {
            if (m_hitRegion == HitRegion.None || !CanManipulate(m_node))
                return;
            var transactionContext = DesignView.Context.As<ITransactionContext>();
            transactionContext.Begin("Move".Localize());
            m_originalPivot = m_node.Pivot;

            Path<DomNode> path = new Path<DomNode>(m_node.Cast<DomNode>().GetPath());
            Matrix4F localToWorld = TransformUtils.CalcPathTransform(path, path.Count - 1);
            m_worldToLocal = new Matrix4F();
            m_worldToLocal.Invert(localToWorld);
        }
Example #14
0
 /// <summary>
 /// Computes world transformation matrix for the given 
 /// Transformable node.</summary>        
 public static Matrix4F ComputeWorldTransform(ITransformable xform)
 {
     Matrix4F world = new Matrix4F();
     DomNode node = xform.As<DomNode>();
     foreach (DomNode n in node.Lineage)
     {
         ITransformable xformNode = n.As<ITransformable>();
         if (xformNode != null)
         {
             world.Mul(world, xformNode.Transform);
         }
     }
     return world;
 }
Example #15
0
        /// <summary>
        /// Calculates the world space matrix of the given path</summary>
        /// <param name="path">The path</param>
        /// <param name="start">Starting index</param>
        /// <param name="M">the world matrix</param>        
        public static void CalcPathTransform(Matrix4F M, Path<DomNode> path, int start)
        {
            for (int i = start; i >= 0; i--)
            {
                if (path[i] != null)
                {
                    ITransformable renderable =
                        path[i].As<ITransformable>();

                    if (renderable != null)
                    {
                        M.Mul(M, renderable.Transform);
                    }
                }
            }
        }
Example #16
0
        /// <summary>
        /// Calculates the world space matrix of the given path
        /// </summary>
        /// <param name="path">The path</param>
        /// <param name="start">Starting index</param>
        /// <returns>The world space matrix</returns>
        public static Matrix4F CalcPathTransform(Path<DomNode> path, int start)
        {
            Matrix4F M = new Matrix4F();

            for (int i = start; i >= 0; i--)
            {
                if (path[i] != null)
                {
                    ITransformable renderable =
                        path[i].As<ITransformable>();

                    if (renderable != null)
                    {
                        M.Mul(M, renderable.Transform);
                    }
                }
            }

            return M;
        }
Example #17
0
        /// <summary>
        /// Calculates the world space matrix of the given SceneNode path, starting from a given index</summary>
        /// <param name="path">The SceneNode path</param>
        /// <param name="start">Starting index within the path</param>
        /// <returns>The world space matrix</returns>
        public static Matrix4F CalcPathTransform(SceneNode[] path, int start)
        {
            Matrix4F M = new Matrix4F();

            for (int i = start; i < path.Length; i++)
            {
                if (path[i].Source != null)
                {
                    ITransformable renderable =
                        path[i].Source.As<ITransformable>();

                    if (renderable != null)
                    {
                        M.Mul(M, renderable.Transform);
                    }
                }
            }

            return M;
        }
Example #18
0
        public IControlPoint InsertPoint(uint index, float x, float y, float z)
        {            
            IControlPoint cpt = CreateControlPoint();
            int numSteps = GetAttribute<int>(Schema.curveType.stepsAttribute);
            int interpolationType = GetAttribute<int>(Schema.curveType.interpolationTypeAttribute);            
            if (interpolationType != 0 && numSteps > 0)
            {
                index = index / (uint)numSteps;
            }


            Path<DomNode> path = new Path<DomNode>(DomNode.GetPath());
            Matrix4F toworld = TransformUtils.CalcPathTransform(path, path.Count - 1);
            Matrix4F worldToLocal = new Matrix4F();
            worldToLocal.Invert(toworld);
            Vec3F pos = new Vec3F(x, y, z);
            worldToLocal.Transform(ref pos);
            cpt.Translation = pos;
            ControlPoints.Insert((int)index + 1, cpt);
            return cpt;
        }
        public override void Render(ViewControl vc)
        {
            Matrix4F normWorld = GetManipulatorMatrix();
            if (normWorld == null) return;

            Camera camera = vc.Camera;
            float s;
            Util.CalcAxisLengths(camera, normWorld.Translation, out s);
            m_translatorControl.Render(normWorld, s);        
            
            Matrix4F sc = new Matrix4F();
            Vec3F pos = normWorld.Translation;            
            s /= 12.0f;
            sc.Scale(s);

            Matrix4F bl = new Matrix4F();
            Util.CreateBillboard(bl, pos, camera.WorldEye, camera.Up, camera.LookAt);

            Matrix4F recXform = new Matrix4F();
            Matrix4F.Multiply(sc, bl, recXform);

            Util3D.DrawPivot(recXform, Color.Yellow);
        }
        public override bool Pick(ViewControl vc, Point scrPt)
        {
            m_hitRegion = HitRegion.None;
            if (base.Pick(vc, scrPt) == false)
                return false;

            Camera camera = vc.Camera;
            
            Matrix4F view = camera.ViewMatrix;
            Matrix4F vp = view  * camera.ProjectionMatrix;
            Matrix4F wvp = HitMatrix * vp;
            
            Ray3F rayL = vc.GetRay(scrPt,wvp);

            float s = Util.CalcAxisScale(vc.Camera, HitMatrix.Translation, AxisLength, vc.Height);

                // There's only one hot-spot for this manipulator:
                //      a square at the manipulator origin.
            Vec3F min = new Vec3F(-0.5f, -0.5f, -0.5f);
            Vec3F max = new Vec3F(0.5f, 0.5f, 0.5f);
            AABB box = new AABB(min, max);

            float centerCubeScale = s * CenterCubeSize;
            Matrix4F centerCubeXform = new Matrix4F();
            centerCubeXform.Scale(centerCubeScale);
            centerCubeXform.Invert(centerCubeXform);
            Ray3F ray = rayL;
            ray.Transform(centerCubeXform);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.XYSquare;
                return true;
            }

            m_hitRegion = HitRegion.None;
            return false;
        }
Example #21
0
 public BoneGlobalTransformItem(bool hasValue, ref Matrix4F value)
 {
     HasValue = hasValue;
     Value    = value;
 }
Example #22
0
        protected override void OnRender(ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData, ref Component_Image actualTexture)
        {
            base.OnRender(context, frameData, ref actualTexture);

            var pipeline = context.RenderingPipeline as Component_RenderingPipeline_Basic;

            if (pipeline == null)
            {
                return;
            }
            var frameData2 = frameData as Component_RenderingPipeline_Basic.FrameData;

            if (frameData2 == null)
            {
                return;
            }
            if (Intensity.Value == 0)
            {
                return;
            }

            bool skip = true;

            foreach (var lightIndex in frameData2.LightsInFrustumSorted)
            {
                var lightItem = frameData2.Lights[lightIndex];

                if (lightItem.data.children != null)
                {
                    foreach (var child in lightItem.data.children)
                    {
                        var lensFlares = child as Component_LensFlares;
                        if (lensFlares != null)
                        {
                            skip = false;
                            break;
                        }
                    }
                }
            }
            if (skip)
            {
                return;
            }

            //init context data
            ViewportRenderingContextData contextData;

            if (context.anyData.TryGetValue("LensEffects", out var contextData2))
            {
                contextData = (ViewportRenderingContextData)contextData2;
            }
            else
            {
                contextData = new ViewportRenderingContextData();
                context.anyData["LensEffects"] = contextData;
            }

            //update context data light items
            contextData.Update(context.Owner.LastUpdateTimeStep, Intensity, FadeSpeed);

            //create copy
            var newTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, actualTexture.Result.ResultFormat, createSimple3DRenderer: true, createCanvasRenderer: true);

            var viewport = newTexture.Result.GetRenderTarget().Viewports[0];
            //!!!!double precision
            Matrix4F viewMatrix       = context.Owner.CameraSettings.ViewMatrix.ToMatrix4F();
            Matrix4F projectionMatrix = context.Owner.CameraSettings.ProjectionMatrix.ToMatrix4F();

            context.SetViewport(viewport, viewMatrix, projectionMatrix);

            pipeline.CopyToCurrentViewport(context, actualTexture);

            var simple3DRenderer = viewport.Simple3DRenderer;
            var canvasRenderer   = viewport.CanvasRenderer;

            //render
            foreach (var lightIndex in frameData2.LightsInFrustumSorted)
            {
                var lightItem = frameData2.Lights[lightIndex];

                if (lightItem.data.children != null)
                {
                    foreach (var child in lightItem.data.children)
                    {
                        var lensFlares = child as Component_LensFlares;
                        if (lensFlares != null)
                        {
                            var light = lightItem.data.Creator as Component_Light;
                            if (light != null)
                            {
                                CheckVisibilityScreenPosition(context, lightItem.data.Position, out var gotScreenPosition, out var insideScreen);

                                if (gotScreenPosition)
                                {
                                    //update
                                    {
                                        switch (CheckVisibilityMethod.Value)
                                        {
                                        case CheckVisibilityMethodEnum.OcclusionQuery:
                                        {
                                            var parameter = (contextData, light);
                                            if (RenderingSystem.TryCreateOcclusionQuery(OcclusionQueryCallback, parameter, out var query))
                                            {
                                                var thickness = context.Owner.Simple3DRenderer.GetThicknessByPixelSize(lightItem.data.Position, 5);
                                                var bounds    = new Bounds(lightItem.data.Position);
                                                bounds.Expand(thickness * 0.5);

                                                simple3DRenderer.SetColor(new ColorValue(1, 0, 0));
                                                simple3DRenderer.SetOcclusionQuery(query);
                                                simple3DRenderer.AddBounds(bounds, true);
                                                //simple3DRenderer.AddSphere( new Sphere( lightItem.data.Position, 0.5 ), 4, true );
                                                simple3DRenderer.SetOcclusionQuery(null);
                                            }
                                        }
                                        break;

                                        case CheckVisibilityMethodEnum.PhysicsRayCast:
                                            if (CheckVisibilityPhysics(context, lightItem.data.Position))
                                            {
                                                contextData.UpdateLastTimeVisible(light);
                                            }
                                            break;
                                        }
                                    }

                                    //render
                                    var intensity = contextData.GetIntensity(light);
                                    if (intensity > 0)
                                    {
                                        //simple3DRenderer.SetColor( new ColorValue( 1, 0, 0 ) );
                                        //simple3DRenderer.AddSphere( new Sphere( lightItem.data.Position, 0.5 ), 10, true );

                                        lensFlares.RenderUI(canvasRenderer, lightItem.data, context.Owner, intensity);
                                    }
                                }
                                else
                                {
                                    contextData.Remove(light);
                                }
                            }
                        }
                    }
                }
            }

            //render
            if (simple3DRenderer._ViewportRendering_PrepareRenderables())
            {
                simple3DRenderer._ViewportRendering_RenderToCurrentViewport(context);
                simple3DRenderer._Clear();
            }
            canvasRenderer._ViewportRendering_RenderToCurrentViewport(context, true, context.Owner.LastUpdateTime);


            //free old textures
            context.DynamicTexture_Free(actualTexture);

            //update actual texture
            actualTexture = newTexture;
        }
Example #23
0
        public override ManipulatorPickResult Pick(ViewControl vc, Point scrPt)
        {
            m_hitRegion = HitRegion.None;
            if (base.Pick(vc, scrPt) == ManipulatorPickResult.Miss)
            {
                return(ManipulatorPickResult.Miss);
            }

            Camera camera       = vc.Camera;
            float  RingDiameter = 2 * AxisLength;
            float  s            = Util.CalcAxisScale(vc.Camera, HitMatrix.Translation, RingDiameter, vc.Height);

            float rad       = s * Util3D.RingCenterRadias;
            float lrad      = rad * LookRingScale;
            float tolerance = s * Util3D.RingThickness;

            Matrix4F billboard
                = Util.CreateBillboard(HitMatrix.Translation, vc.Camera.WorldEye, vc.Camera.Up, vc.Camera.LookAt);

            m_lookAxisHitMtrx = billboard;
            // compute ray in object space  space.
            Matrix4F vp   = camera.ViewMatrix * camera.ProjectionMatrix;
            Matrix4F wvp  = HitMatrix * vp;
            Ray3F    rayL = vc.GetRay(scrPt, wvp);

            Matrix4F wvp2  = billboard * vp;
            Ray3F    rayL2 = vc.GetRay(scrPt, wvp2);

            Plane3F xplane = new Plane3F(Vec3F.XAxis, Vec3F.ZeroVector);
            Plane3F yplane = new Plane3F(Vec3F.YAxis, Vec3F.ZeroVector);
            Plane3F zplane = new Plane3F(Vec3F.ZAxis, Vec3F.ZeroVector);


            Vec3F pt;
            float xdelta    = float.MaxValue;
            float ydelta    = float.MaxValue;
            float zdelta    = float.MaxValue;
            float lookdelta = float.MaxValue;

            if (rayL.IntersectPlane(xplane, out pt))
            {
                xdelta = Math.Abs(pt.Length - rad);
            }

            if (rayL.IntersectPlane(yplane, out pt))
            {
                ydelta = Math.Abs(pt.Length - rad);
            }

            if (rayL.IntersectPlane(zplane, out pt))
            {
                zdelta = Math.Abs(pt.Length - rad);
            }

            if (rayL2.IntersectPlane(zplane, out pt))
            {
                lookdelta = Math.Abs(pt.Length - lrad);
            }

            if (xdelta < tolerance && xdelta < ydelta && xdelta < zdelta &&
                xdelta < lookdelta)
            {
                m_hitRegion = HitRegion.XAxis;
            }
            else if (ydelta < tolerance && ydelta < zdelta &&
                     ydelta < lookdelta)
            {
                m_hitRegion = HitRegion.YAxis;
            }
            else if (zdelta < tolerance && zdelta < lookdelta)
            {
                m_hitRegion = HitRegion.ZAxis;
            }
            else if (lookdelta < tolerance)
            {
                m_hitRegion = HitRegion.LookAxis;
            }

            if (m_hitRegion != HitRegion.None)
            {
                return(ManipulatorPickResult.DeferredBeginDrag);
            }

            return(ManipulatorPickResult.Miss);
        }
        unsafe public override void Render(Component_RenderingPipeline pipeline, ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData)
        {
            UpdateProcessedCubemaps();

            if (mesh != null)
            {
                ////!!!!
                //CreatedCubemapUpdate();

                //!!!!double
                Matrix4F worldMatrix = Matrix4.FromTranslate(context.Owner.CameraSettings.Position).ToMatrix4F();

                foreach (var item in mesh.Result.MeshData.RenderOperations)
                {
                    ParameterContainer generalContainer = new ParameterContainer();
                    generalContainer.Set("multiplier", Multiplier.Value.ToColorValue());
                    GetRotationMatrix(out var rotation);
                    generalContainer.Set("rotation", rotation);                      // Matrix3.FromRotateByZ( Rotation.Value.InRadians() ).ToMatrix3F() );
                    generalContainer.Set("stretch", (float)Stretch.Value);

                    Component_Image tex = null;
                    ////!!!!hack. by idea need mirror 6-sided loaded cubemaps
                    //bool flipCubemap = false;

                    if (AlwaysUseProcessedCubemap)
                    {
                        tex = processedEnvironmentCubemap;
                    }
                    if (tex == null)
                    {
                        tex = Cubemap;
                        //if( tex != null && tex.AnyCubemapSideIsSpecified() )
                        //	flipCubemap = true;
                    }
                    if (tex == null)
                    {
                        tex = processedEnvironmentCubemap;
                    }
                    if (tex == null)
                    {
                        tex = ResourceUtility.BlackTextureCube;
                    }

                    //generalContainer.Set( "flipCubemap", new Vector4F( flipCubemap ? -1 : 1, 0, 0, 0 ) );

                    ////!!!!сделать GetResultEnvironmentCubemap()?
                    ////!!!!!!где еще его использовать
                    //if( processedEnvironmentCubemap != null )
                    //	tex = processedEnvironmentCubemap;
                    ////else if( AnyCubemapSideIsSpecified() )
                    ////	tex = createdCubemap;
                    //else
                    //	tex = Cubemap;
                    //if( tex == null )
                    //	tex = ResourceUtility.BlackTextureCube;

                    if (tex.Result != null)
                    {
                        var cube = tex.Result.TextureType == Component_Image.TypeEnum.Cube;

                        var pass = GetMaterialPass(cube);
                        if (pass != null)
                        {
                            TextureAddressingMode addressingMode;
                            if (cube)
                            {
                                addressingMode = TextureAddressingMode.Wrap;
                            }
                            else
                            {
                                addressingMode = TextureAddressingMode.WrapU | TextureAddressingMode.ClampV;
                            }

                            context.BindTexture(new ViewportRenderingContext.BindTextureData(0 /*"skyboxTexture"*/, tex, addressingMode, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                            var containers = new List <ParameterContainer>();
                            containers.Add(generalContainer);

                            Bgfx.SetTransform((float *)&worldMatrix);
                            ((Component_RenderingPipeline_Basic)pipeline).RenderOperation(context, item, pass, containers);
                        }
                    }
                }
            }
        }
Example #25
0
        /// <summary>
        /// Renders control for picking</summary>
        /// <param name="action">Render action</param>
        /// <param name="camera">Camera</param>
        /// <param name="renderState">Render state</param>
        /// <param name="transform">Transform, local to world</param>
        public void RenderPick(IRenderAction action, Camera camera, RenderState renderState, Matrix4F transform)
        {
            action.RenderStateGuardian.Commit(renderState);

            // apply xform
            Gl.glPushMatrix();
            Util3D.glMultMatrixf(transform);

            float s1, s2, s3;

            CalcAxisLengths(camera, transform, out s1, out s2, out s3);
            float squareSideX = s1 * SquareLength;
            float squareSideY = s2 * SquareLength;
            float squareSideZ = s3 * SquareLength;

            bool drawX, drawY, drawZ;

            DecideArrowDrawing(transform, camera, out drawX, out drawY, out drawZ);

            // Mark each axis with a different name.
            // Since the OpenGl selection buffer does a bad job in detecting lines we'll use
            //  triangles instead.
            Gl.glPushName(m_nameBase);

            if (drawX)
            {
                Gl.glPushName((int)HitElement.X_ARROW);
                Gl.glBegin(Gl.GL_TRIANGLES);
                Gl.glVertex3f(squareSideX, 0, 0);
                Gl.glVertex3f(s1, 0, 0);
                Gl.glVertex3f(squareSideX, 0, 0);
                Gl.glEnd();
                RenderXArrow(s1);
                Gl.glPopName();
            }

            if (drawY)
            {
                Gl.glPushName((int)HitElement.Y_ARROW);
                Gl.glBegin(Gl.GL_TRIANGLES);
                Gl.glVertex3f(0, squareSideY, 0);
                Gl.glVertex3f(0, s2, 0);
                Gl.glVertex3f(0, squareSideY, 0);
                Gl.glEnd();
                RenderYArrow(s2);
                Gl.glPopName();
            }

            if (drawZ)
            {
                Gl.glPushName((int)HitElement.Z_ARROW);
                Gl.glBegin(Gl.GL_TRIANGLES);
                Gl.glVertex3f(0, 0, squareSideZ);
                Gl.glVertex3f(0, 0, s3);
                Gl.glVertex3f(0, 0, squareSideZ);
                Gl.glEnd();
                RenderZArrow(s3);
                Gl.glPopName();
            }

            if (drawX && drawY)
            {
                Gl.glPushName((int)HitElement.XY_SQUARE);
                RenderXYSquare(squareSideX, squareSideY, true);
                Gl.glPopName();
            }

            if (drawY && drawZ)
            {
                Gl.glPushName((int)HitElement.YZ_SQUARE);
                RenderYZSquare(squareSideY, squareSideZ, true);
                Gl.glPopName();
            }

            if (drawX && drawZ)
            {
                Gl.glPushName((int)HitElement.XZ_SQUARE);
                RenderXZSquare(squareSideX, squareSideZ, true);
                Gl.glPopName();
            }

            Gl.glPopMatrix();
            Gl.glPopName();
        }
Example #26
0
        private void RenderProperties(IEnumerable <object> objects, bool renderCaption, bool renderBound, bool renderPivot)
        {
            bool renderAny = renderCaption || renderBound || renderPivot;

            if (renderAny == false)
            {
                return;
            }

            Util3D.RenderFlag = BasicRendererFlags.WireFrame;
            Matrix4F vp = Camera.ViewMatrix * Camera.ProjectionMatrix;

            foreach (object obj in objects)
            {
                IBoundable bnode = obj.As <IBoundable>();
                if (bnode == null || bnode.BoundingBox.IsEmpty || obj.Is <IGameObjectFolder>())
                {
                    continue;
                }

                INameable      nnode = obj.As <INameable>();
                ITransformable trans = obj.As <ITransformable>();

                if (renderBound)
                {
                    Util3D.DrawAABB(bnode.BoundingBox);
                }
                if (renderCaption && nnode != null)
                {
                    Vec3F topCenter = bnode.BoundingBox.Center;
                    topCenter.Y = bnode.BoundingBox.Max.Y;
                    Point pt = Project(vp, topCenter);
                    GameEngine.DrawText2D(nnode.Name, Util3D.CaptionFont, pt.X, pt.Y, Color.White);
                }
            }

            if (renderPivot)
            {
                Util3D.RenderFlag = BasicRendererFlags.WireFrame
                                    | BasicRendererFlags.DisableDepthTest;

                // create few temp matrics to
                Matrix4F toWorld  = new Matrix4F();
                Matrix4F PV       = new Matrix4F();
                Matrix4F sc       = new Matrix4F();
                Matrix4F bl       = new Matrix4F();
                Matrix4F recXform = new Matrix4F();
                foreach (object obj in objects)
                {
                    ITransformable trans = obj.As <ITransformable>();
                    IBoundable     bnode = obj.As <IBoundable>();
                    if (trans == null || bnode == null || bnode.BoundingBox.IsEmpty || obj.Is <IGameObjectFolder>())
                    {
                        continue;
                    }

                    Path <DomNode> path = new Path <DomNode>(trans.Cast <DomNode>().GetPath());
                    toWorld.Set(Vec3F.ZeroVector);
                    TransformUtils.CalcPathTransform(toWorld, path, path.Count - 1);

                    // Offset by pivot
                    PV.Set(trans.Pivot);
                    toWorld.Mul(PV, toWorld);
                    Vec3F pos = toWorld.Translation;

                    float s;
                    Util.CalcAxisLengths(Camera, pos, out s);
                    s /= 12.0f;
                    sc.Scale(s);
                    Util.CreateBillboard(bl, pos, Camera.WorldEye, Camera.Up, Camera.LookAt);

                    Matrix4F.Multiply(sc, bl, recXform);

                    Util3D.DrawPivot(recXform, Color.Yellow);
                }
            }
        }
        unsafe protected override void OnRender(ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData, ref Component_Image actualTexture)
        {
            base.OnRender(context, frameData, ref actualTexture);

            //is not supported
            if (!context.RenderingPipeline.GetUseMultiRenderTargets())
            {
                return;
            }

            //downscale for SSAA
            var actualTextureSource = actualTexture;

            if (actualTexture.Result.ResultSize != context.Owner.SizeInPixels)
            {
                actualTexture = context.RenderTarget2D_Alloc(context.Owner.SizeInPixels, actualTextureSource.Result.ResultFormat);

                //copy to scene texture with downscale
                context.SetViewport(actualTexture.Result.GetRenderTarget().Viewports[0]);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                shader.FragmentProgramFileName = @"Base\Shaders\Effects\Downscale2_fs.sc";

                shader.Parameters.Set("sourceSizeInv", new Vector2F(1, 1) / actualTextureSource.Result.ResultSize.ToVector2F());

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0 /*"sourceTexture"*/,
                                                                                   actualTextureSource, TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));

                context.RenderQuadToCurrentViewport(shader);
            }

            // Setup Constants:

            Vector2F viewportPixelSize        = new Vector2F(1.0f / (float)actualTexture.Result.ResultSize.X, 1.0f / (float)actualTexture.Result.ResultSize.Y);
            Vector2F halfViewportPixelSize    = new Vector2F(1.0f / ((float)actualTexture.Result.ResultSize.X * 0.5f), 1.0f / ((float)actualTexture.Result.ResultSize.Y * 0.5f));
            Vector4F quarterViewportPixelSize = new Vector4F(1.0f / ((float)actualTexture.Result.ResultSize.X * 0.25f), 1.0f / ((float)actualTexture.Result.ResultSize.Y * 0.25f), (float)((actualTexture.Result.ResultSize.X / 4) * (actualTexture.Result.ResultSize.Y / 4)), 0.0f);
            Vector2F viewport2xPixelSize      = new Vector2F(viewportPixelSize.X * 2.0f, viewportPixelSize.Y * 2.0f);

            Matrix4F projectionMatrix = context.Owner.CameraSettings.ProjectionMatrix.ToMatrix4F();

            float depthLinearizeMul = -projectionMatrix[3][2];
            float depthLinearizeAdd = projectionMatrix[2][2];

            if (depthLinearizeMul * depthLinearizeAdd < 0.0f)
            {
                depthLinearizeAdd = -depthLinearizeAdd;
            }

            Vector2F depthUnpackConsts = new Vector2F(depthLinearizeMul, depthLinearizeAdd);

            float tanHalfFOVY = 1.0f / projectionMatrix[1][1];
            float tanHalfFOVX = 1.0F / projectionMatrix[0][0];

            Vector2F cameraTanHalfFOV = new Vector2F(tanHalfFOVX, tanHalfFOVY);

            Vector2F NDCToViewMul = new Vector2F(cameraTanHalfFOV.X * 2.0f, cameraTanHalfFOV.Y * -2.0f);
            Vector2F NDCToViewAdd = new Vector2F(cameraTanHalfFOV.X * -1.0f, cameraTanHalfFOV.Y * 1.0f);

            Matrix4F itViewMatrix = (context.Owner.CameraSettings.ViewMatrix.GetInverse().ToMatrix4F()).GetTranspose();

            // Effect Params:

            float effectSamplingRadiusNearLimit = (float)Radius * 1.2f;

            if (Quality.Value == QualityEnum.Low)
            {
                effectSamplingRadiusNearLimit *= 1.50f;
            }

            effectSamplingRadiusNearLimit /= tanHalfFOVY;

            float effectSamplingRadiusNearLimitRec = 1.0f / effectSamplingRadiusNearLimit;

            Vector4F effectRadiusParams = new Vector4F((float)Radius, -1.0f / (float)Radius, effectSamplingRadiusNearLimitRec, 0.0f);

            float effectFadeOutMul = -1.0f / ((float)FadeOutTo - (float)FadeOutFrom);
            float effectFadeOutAdd = (float)FadeOutFrom / ((float)FadeOutTo - (float)FadeOutFrom) + 1.0f;

            float detailAOStrength     = (float)DetailStrength;
            float effectShadowStrength = (float)Multiplier;
            float effectShadowClamp    = 1.0f;
            float effectShadowPow      = (float)Power;

            float invSharpness = 1.0f - (float)Sharpness;

            if (invSharpness < 0.0f)
            {
                invSharpness = 0.0f;
            }
            if (invSharpness > 1.0f)
            {
                invSharpness = 1.0f;
            }

            // First Pass: Prepare 4 Depth half-Buffers:

            Component_Image[] halfDepths = new Component_Image[4];
            for (int i = 0; i < 4; i++)
            {
                halfDepths[i] = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.Float16R);
            }

            var fourDepthsMRT = context.MultiRenderTarget_Create(new[] {
                new MultiRenderTarget.Item(halfDepths[0]),
                new MultiRenderTarget.Item(halfDepths[1]),
                new MultiRenderTarget.Item(halfDepths[2]),
                new MultiRenderTarget.Item(halfDepths[3])
            });

            {
                context.SetViewport(fourDepthsMRT.Viewports[0], Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PrepareDepths_fs.sc";

                context.objectsDuringUpdate.namedTextures.TryGetValue("depthTexture", out Component_Image depthTexture);

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, depthTexture,
                                                                                   TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                shader.Parameters.Set("depthUnpackConsts", depthUnpackConsts);
                //!!!!use actualTextureSource size?
                shader.Parameters.Set("viewportPixelSize", viewportPixelSize);

                context.RenderQuadToCurrentViewport(shader);
            }

            // Second Pass: prepare 4 Mip-Maps for each Half-Depth-Map:

            Component_Image[,] depthMipMaps = null;

            if (Quality.Value > QualityEnum.Medium)
            {
                Vector2I[] mipMapSizes = new Vector2I[4];                   // Setup Mip-Map sizes:

                mipMapSizes[0] = new Vector2I(actualTexture.Result.ResultSize / 2);
                for (int m = 1; m < 4; m++)
                {
                    mipMapSizes[m] = new Vector2I(mipMapSizes[m - 1] / 2);
                }

                // Prepare MipMaps textures:

                depthMipMaps = new Component_Image[4, 4];

                for (int d = 0; d < 4; d++)
                {
                    depthMipMaps[d, 0] = halfDepths[d];                         // MipMaps 0 is original halfDepthMaps
                    for (int m = 1; m < 4; m++)
                    {
                        depthMipMaps[d, m] = context.RenderTarget2D_Alloc(mipMapSizes[m], PixelFormat.Float16R);
                    }
                }

                for (int m = 1; m < 4; m++)                  // Mip-Maps loop
                {
                    var fourDepthsMipsMRT = context.MultiRenderTarget_Create(new[] {
                        new MultiRenderTarget.Item(depthMipMaps[0, m]),
                        new MultiRenderTarget.Item(depthMipMaps[1, m]),
                        new MultiRenderTarget.Item(depthMipMaps[2, m]),
                        new MultiRenderTarget.Item(depthMipMaps[3, m])
                    });

                    context.SetViewport(fourDepthsMipsMRT.Viewports[0], Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PrepareDepthMips_fs.sc";

                    // For current Mip-Map generation using previous Mip-Map:

                    float    prevMipLevel  = (float)(m - 1);
                    var      prevMipSize   = mipMapSizes[m - 1];
                    Vector4F prevMipParams = new Vector4F(1.0f / (float)prevMipSize.X, 1.0f / (float)prevMipSize.Y, prevMipLevel, 0.0f);

                    for (int i = 0; i < 4; i++)
                    {
                        // previous MipMap as input:
                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(i, depthMipMaps[i, m - 1],
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                    }
                    shader.Parameters.Set("prevMipParams", prevMipParams);
                    shader.Parameters.Set("effectRadiusParams", effectRadiusParams);

                    context.RenderQuadToCurrentViewport(shader);
                }
            }

            Component_Image SSAOTextureArray = new Component_Image();

            Component_Image SSAOBaseTextureArray = null;

            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                SSAOBaseTextureArray = new Component_Image();
                SSAOBaseTextureArray = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt, 0, false, /*0,*/ 4);
            }

            Component_Image importanceMap     = null;
            Component_Image averageImportance = null;

            // Generate Importance Map for Highest/Adaptive Quality mode:
            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                // 4 SSAO passes:

                for (int pass = 0; pass < 4; pass++)
                {
                    Vector4F[] patternRotScaleMatrices;
                    GeneratePatternRotScaleMatrices(pass, out patternRotScaleMatrices);

                    Vector2F perPassFullResCoordOffset = new Vector2F((float)(pass % 2), (float)(pass / 2));

                    {
                        context.SetViewport(SSAOBaseTextureArray.Result.GetRenderTarget(0, pass).Viewports[0],
                                            Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                        CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                        shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_AdaptiveBase_fs.sc";

                        context.objectsDuringUpdate.namedTextures.TryGetValue("normalTexture", out Component_Image normalTexture);

                        for (int m = 0; m < 4; m++)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(m, depthMipMaps[pass, m],
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                        }

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(4, halfDepths[pass],
                                                                                           TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(5, normalTexture,
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set("NDCToViewMul", NDCToViewMul);
                        shader.Parameters.Set("NDCToViewAdd", NDCToViewAdd);
                        shader.Parameters.Set("effectRadiusParams", effectRadiusParams);
                        shader.Parameters.Set("viewportPixelSize", viewportPixelSize);
                        shader.Parameters.Set("viewport2xPixelSize", viewport2xPixelSize);
                        shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                        shader.Parameters.Set("perPassFullResCoordOffset", perPassFullResCoordOffset);
                        shader.Parameters.Set("patternRotScaleMatrices", patternRotScaleMatrices);
                        shader.Parameters.Set("effectFadeOutMul", effectFadeOutMul);
                        shader.Parameters.Set("effectFadeOutAdd", effectFadeOutAdd);
                        shader.Parameters.Set("effectShadowStrength", effectShadowStrength);
                        shader.Parameters.Set("effectShadowClamp", effectShadowClamp);
                        shader.Parameters.Set("effectShadowPow", effectShadowPow);
                        shader.Parameters.Set("detailAOStrength", detailAOStrength);
                        shader.Parameters.Set("itViewMatrix", itViewMatrix);

                        context.RenderQuadToCurrentViewport(shader);
                    }
                }

                // Importance Map Generation:
                importanceMap = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 4, PixelFormat.L8);
                {
                    context.SetViewport(importanceMap.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateImportanceMap_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, SSAOBaseTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                    shader.Parameters.Set("effectShadowStrength", effectShadowStrength);
                    shader.Parameters.Set("effectShadowPow", effectShadowPow);

                    context.RenderQuadToCurrentViewport(shader);
                }

                // Importance Map Post-Process A:
                var importanceMapPong = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 4, PixelFormat.L8);
                {
                    context.SetViewport(importanceMapPong.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PostProcessImportanceMapA_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, importanceMap,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));

                    shader.Parameters.Set("quarterViewportPixelSize", quarterViewportPixelSize);

                    context.RenderQuadToCurrentViewport(shader);
                }

                // Importance Map Post-Process B:
                {
                    context.SetViewport(importanceMap.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PostProcessImportanceMapB_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, importanceMapPong,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));

                    shader.Parameters.Set("quarterViewportPixelSize", quarterViewportPixelSize);

                    context.RenderQuadToCurrentViewport(shader);
                }

                context.DynamicTexture_Free(importanceMapPong);

                // Get Average Importance Pass:
                averageImportance = context.RenderTarget2D_Alloc(new Vector2I(1, 1), PixelFormat.L8);
                {
                    context.SetViewport(averageImportance.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GetAverageImportance_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, importanceMap,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set("quarterViewportPixelSize", quarterViewportPixelSize);

                    context.RenderQuadToCurrentViewport(shader);
                }
            }

            // Third Pass: Generate 4 SSAO buffers:

            Component_Image blurPingTexture = null, blurPongTexture = null;

            if (BlurAmount.Value > 0)
            {
                blurPingTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt);
                blurPongTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt);
            }

            SSAOTextureArray = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt, 0, false, /*0,*/ 4);

            for (int pass = 0; pass < 4; pass++)
            {
                Vector4F[] patternRotScaleMatrices;
                GeneratePatternRotScaleMatrices(pass, out patternRotScaleMatrices);

                Vector2F perPassFullResCoordOffset = new Vector2F((float)(pass % 2), (float)(pass / 2));

                {
                    if (BlurAmount.Value == 0)
                    {
                        context.SetViewport(SSAOTextureArray.Result.GetRenderTarget(0, pass).Viewports[0],
                                            Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                    }
                    else
                    {
                        context.SetViewport(blurPingTexture.Result.GetRenderTarget().Viewports[0],
                                            Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                    }

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName = @"Base\Shaders\EffectsCommon_vs.sc";

                    if (Quality.Value == QualityEnum.Low)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_LQ_fs.sc";
                    }
                    else if (Quality.Value == QualityEnum.Medium)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_MQ_fs.sc";
                    }
                    else if (Quality.Value == QualityEnum.High)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_HQ_fs.sc";
                    }
                    else if (Quality.Value == QualityEnum.HighestAdaptive)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_HAQ_fs.sc";
                    }

                    context.objectsDuringUpdate.namedTextures.TryGetValue("normalTexture", out Component_Image normalTexture);

                    if (Quality.Value > QualityEnum.Medium)
                    {
                        for (int m = 0; m < 4; m++)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(m, depthMipMaps[pass, m],
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                        }

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(4, halfDepths[pass],
                                                                                           TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(5, normalTexture,
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        if (Quality.Value == QualityEnum.HighestAdaptive)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(6, importanceMap,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(7, averageImportance,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(8, SSAOBaseTextureArray,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                        }
                    }
                    else
                    {
                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, halfDepths[pass],
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, halfDepths[pass],
                                                                                           TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(2, normalTexture,
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                    }

                    shader.Parameters.Set("NDCToViewMul", NDCToViewMul);
                    shader.Parameters.Set("NDCToViewAdd", NDCToViewAdd);
                    shader.Parameters.Set("effectRadiusParams", effectRadiusParams);
                    shader.Parameters.Set("viewportPixelSize", viewportPixelSize);
                    shader.Parameters.Set("viewport2xPixelSize", viewport2xPixelSize);
                    shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                    shader.Parameters.Set("perPassFullResCoordOffset", perPassFullResCoordOffset);
                    shader.Parameters.Set("patternRotScaleMatrices", patternRotScaleMatrices);
                    shader.Parameters.Set("effectFadeOutMul", effectFadeOutMul);
                    shader.Parameters.Set("effectFadeOutAdd", effectFadeOutAdd);
                    shader.Parameters.Set("effectShadowStrength", effectShadowStrength);
                    shader.Parameters.Set("effectShadowClamp", effectShadowClamp);
                    shader.Parameters.Set("effectShadowPow", effectShadowPow);
                    shader.Parameters.Set("detailAOStrength", detailAOStrength);
                    shader.Parameters.Set("itViewMatrix", itViewMatrix);

                    if (Quality.Value == QualityEnum.HighestAdaptive)
                    {
                        shader.Parameters.Set("adaptiveSampleCountLimit", (float)AdaptiveQualityLimit);
                        shader.Parameters.Set("passNumber", (float)pass);
                    }

                    context.RenderQuadToCurrentViewport(shader);
                }

                if (Quality.Value > QualityEnum.Medium)
                {
                    // Free Mip-Maps Targets for this Pass:
                    for (int m = 0; m < 4; m++)
                    {
                        context.DynamicTexture_Free(depthMipMaps[pass, m]);
                    }
                }
                else
                {
                    context.DynamicTexture_Free(halfDepths[pass]);
                }

                // Blur SSAO Texture:

                if (BlurAmount.Value > 0)
                {
                    int wideBlursRemaining = Math.Max(0, BlurAmount.Value - 2);

                    for (int i = 0; i < BlurAmount.Value; i++)
                    {
                        if (i == (BlurAmount.Value - 1))
                        {
                            context.SetViewport(SSAOTextureArray.Result.GetRenderTarget(0, pass).Viewports[0],
                                                Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                        }
                        else
                        {
                            context.SetViewport(blurPongTexture.Result.GetRenderTarget().Viewports[0],
                                                Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                        }

                        CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                        shader.VertexProgramFileName = @"Base\Shaders\EffectsCommon_vs.sc";

                        if (Quality.Value > QualityEnum.Low)
                        {
                            if (wideBlursRemaining > 0)
                            {
                                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\SmartBlurWide_fs.sc";
                                wideBlursRemaining--;
                            }
                            else
                            {
                                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\SmartBlur_fs.sc";
                            }
                        }
                        else
                        {
                            shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\NonSmartBlur_fs.sc";
                        }

                        if (Quality.Value > QualityEnum.Low)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, blurPingTexture,
                                                                                               TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));
                            shader.Parameters.Set("invSharpness", invSharpness);
                        }
                        else
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, blurPingTexture,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                        }

                        shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);

                        context.RenderQuadToCurrentViewport(shader);

                        // Swap Ping-Pong Blur textures:
                        var tmp_tex = blurPingTexture;
                        blurPingTexture = blurPongTexture;
                        blurPongTexture = tmp_tex;
                    }
                }
            }

            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                context.DynamicTexture_Free(SSAOBaseTextureArray);
            }

            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                context.DynamicTexture_Free(importanceMap);
                context.DynamicTexture_Free(averageImportance);
            }

            if (BlurAmount.Value > 0)
            {
                // Free Blur ping/pong Targets:
                context.DynamicTexture_Free(blurPingTexture);
                context.DynamicTexture_Free(blurPongTexture);
            }

            // 4th Pass: Apply 4 SSAO Textures to Final SSAO Result:

            var FullSSAOTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, PixelFormat.R8G8_UInt);

            {
                context.SetViewport(FullSSAOTexture.Result.GetRenderTarget().Viewports[0],
                                    Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName = @"Base\Shaders\EffectsCommon_vs.sc";

                if (Quality.Value > QualityEnum.Low)
                {
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\Apply_fs.sc";
                }
                else
                {
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\Apply_noSmart_fs.sc";
                }

                if (Quality.Value > QualityEnum.Low)
                {
                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, SSAOTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, SSAOTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                }
                else
                {
                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, SSAOTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                }

                if (Quality.Value > QualityEnum.Low)
                {
                    shader.Parameters.Set("invSharpness", invSharpness);
                    shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                }

                context.RenderQuadToCurrentViewport(shader);
            }

            // Free SSAO Texture Array Target:
            context.DynamicTexture_Free(SSAOTextureArray);

            // 5th Final Pass:
            var finalTexture = context.RenderTarget2D_Alloc(actualTextureSource.Result.ResultSize, actualTextureSource.Result.ResultFormat);

            {
                context.SetViewport(finalTexture.Result.GetRenderTarget().Viewports[0]);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\Final_fs.sc";

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, actualTextureSource,
                                                                                   TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, FullSSAOTexture,
                                                                                   TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                shader.Parameters.Set("intensity", (float)Intensity);
                shader.Parameters.Set("showAO", ShowAO ? 1.0f : -1.0f);

                context.RenderQuadToCurrentViewport(shader);
            }

            // Free Targets:
            context.DynamicTexture_Free(actualTexture);
            if (actualTextureSource != actualTexture)
            {
                context.DynamicTexture_Free(actualTextureSource);
            }
            context.DynamicTexture_Free(FullSSAOTexture);

            // Update actual Texture:
            actualTexture = finalTexture;
        }
Example #28
0
        public override void Render(object opaqueContext, ViewControl vc)
        {                                                                           
            Matrix4F normWorld = GetManipulatorMatrix();
            if (normWorld == null) return;

            var context = opaqueContext as GUILayer.SimpleRenderingContext;
            if (context == null) return;

            float RingDiameter = 2 * AxisLength;
            Color xcolor = (m_hitRegion == HitRegion.XAxis) ? Color.Gold : XAxisColor;
            Color ycolor = (m_hitRegion == HitRegion.YAxis ) ? Color.Gold : YAxisColor;
            Color Zcolor = (m_hitRegion == HitRegion.ZAxis ) ? Color.Gold : ZAxisColor;
            Color lColor = (m_hitRegion == HitRegion.LookAxis) ? Color.Gold : Color.Cyan;

            float s = Util.CalcAxisScale(vc.Camera, normWorld.Translation, RingDiameter, vc.Height);
            Vec3F axScale = new Vec3F(s, s, s);

            Matrix4F rot = new Matrix4F();
            Matrix4F scale = new Matrix4F();
            scale.Scale(axScale);
            rot.RotX(MathHelper.PiOver2);            
            Matrix4F xform = scale * rot * normWorld;
            Util3D.DrawRing(context, xform, Zcolor);

            rot.RotZ(-MathHelper.PiOver2);
            xform = scale * rot * normWorld;
            Util3D.DrawRing(context, xform, xcolor);
            
            xform = scale * normWorld;
            Util3D.DrawRing(context, xform, ycolor);

            Matrix4F billboard
                = Util.CreateBillboard(normWorld.Translation, vc.Camera.WorldEye, vc.Camera.Up, vc.Camera.LookAt);
            rot.RotX(MathHelper.PiOver2);
            scale.Scale(s * LookRingScale);
            xform = scale * rot * billboard;
            Util3D.DrawRing(context, xform, lColor);
        }
Example #29
0
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_hitRegion == HitRegion.None || m_activeOp == null || m_activeOp.NodeList.Count == 0)
                return;
            Camera cam = vc.Camera;

            Matrix4F view = cam.ViewMatrix;
            Matrix4F proj = cam.ProjectionMatrix;

            Matrix4F axisMtrx = HitMatrix * view;
            Ray3F hitRay = HitRayV;
            Ray3F dragRay = vc.GetRay(scrPt, proj);
            
            Vec3F xAxis = axisMtrx.XAxis;
            Vec3F yAxis = axisMtrx.YAxis;
            Vec3F zAxis = axisMtrx.ZAxis;
            Vec3F origin = axisMtrx.Translation;
            
            Vec3F rotAxis = new Vec3F();            
            float theta = 0;

            float snapAngle = ((ISnapSettings)DesignView).SnapAngle;
            switch (m_hitRegion)
            {                
                case HitRegion.XAxis:
                    {
                        Plane3F xplane = new Plane3F(xAxis, origin);
                        theta = CalcAngle(origin, xplane, hitRay, dragRay, snapAngle);
                        rotAxis = HitMatrix.XAxis;                        
                    }
                    break;
                case HitRegion.YAxis:
                    {
                        Plane3F yplane = new Plane3F(yAxis, origin);
                        theta = CalcAngle(origin, yplane, hitRay, dragRay, snapAngle);
                        rotAxis = HitMatrix.YAxis;                        
                    }
                    break;
                case HitRegion.ZAxis:
                    {
                        Plane3F zplane = new Plane3F(zAxis, origin);
                        theta = CalcAngle(origin, zplane, hitRay, dragRay, snapAngle);
                        rotAxis = HitMatrix.ZAxis;
                    }
                    break;
                case HitRegion.LookAxis:
                    {                        
                        // for billboard objects the look vector is object's negative position in viewspace.
                        Vec3F lookAxis = Vec3F.Normalize(-origin);
                        Plane3F plane = new Plane3F(lookAxis, origin);
                        theta = CalcAngle(origin, plane, hitRay, dragRay, snapAngle);                        
                        rotAxis = m_lookAxisHitMtrx.ZAxis;
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            AngleAxisF axf = new AngleAxisF(-theta, rotAxis);
            Matrix4F deltaMtrx = new Matrix4F(axf);                                   
            Matrix4F rotMtrx = new Matrix4F();

            for (int i = 0; i < m_activeOp.NodeList.Count; i++)
            {
                ITransformable node = m_activeOp.NodeList[i];                              
                rotMtrx.Mul(m_rotations[i], deltaMtrx);                
                float ax, ay, az;
                rotMtrx.GetEulerAngles(out ax, out ay, out az);                                
                node.Rotation = new Vec3F(ax, ay, az);      
            }
        }
Example #30
0
 /// <summary>
 /// Sets up the view matrix given a Camera</summary>
 /// <param name="camera">Camera to get view matrix for</param>
 protected override void SetupView(Camera camera)
 {
     m_viewMatrix = new Matrix4F(camera.ViewMatrix);
     base.SetupView(camera);
 }
Example #31
0
        public override bool Pick(ViewControl vc, Point scrPt)
        {
            m_hitRegion = HitRegion.None;
            if (base.Pick(vc, scrPt) == false)
                return false;

            Camera camera = vc.Camera;
            float s = Util.CalcAxisScale(vc.Camera, HitMatrix.Translation, AxisLength, vc.Height);

            Matrix4F vp = camera.ViewMatrix * camera.ProjectionMatrix;
            Matrix4F wvp = HitMatrix * vp;

            // get ray in object space  space.
            Ray3F rayL = vc.GetRay(scrPt, wvp);

            m_scale = new Vec3F(1, 1, 1);
            m_hitScale = s;

            Vec3F min = new Vec3F(-0.5f, -0.5f, -0.5f);
            Vec3F max = new Vec3F(0.5f, 0.5f, 0.5f);
            AABB box = new AABB(min, max);
            Matrix4F boxScale = new Matrix4F();
            Matrix4F boxTrans = new Matrix4F();
            Matrix4F BoxMtrx = new Matrix4F();

            float handleScale = s * AxisHandle;

            // +X axis
            boxScale.Scale(new Vec3F(s, handleScale, handleScale));
            boxTrans.Translation = new Vec3F(s / 2, 0, 0);
            BoxMtrx = boxScale * boxTrans;

            Ray3F ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);

            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.XAxis;
                return true;
            }

            // -X
            boxTrans.Translation = new Vec3F(-s / 2, 0, 0);
            BoxMtrx = boxScale * boxTrans;

            ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);

            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.NegXAxis;
                return true;
            }

            // y axis
            boxScale.Scale(new Vec3F(handleScale, s, handleScale));
            boxTrans.Translation = new Vec3F(0, s / 2, 0);
            BoxMtrx = boxScale * boxTrans;

            ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.YAxis;
                return true;
            }

            // -Y
            boxTrans.Translation = new Vec3F(0, -s / 2, 0);
            BoxMtrx = boxScale * boxTrans;
            ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.NegYAxis;
                return true;
            }

            // z axis
            boxScale.Scale(new Vec3F(handleScale, handleScale, s));
            boxTrans.Translation = new Vec3F(0, 0, s / 2);
            BoxMtrx = boxScale * boxTrans;

            ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.ZAxis;
                return true;
            }

            // -Z
            boxTrans.Translation = new Vec3F(0, 0, -s / 2);
            BoxMtrx = boxScale * boxTrans;

            ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.NegZAxis;
                return true;
            }

            return false;
        }
Example #32
0
        public void Render(object opaqueContext, ViewControl vc, Matrix4F normWorld)
        {
            var context = opaqueContext as GUILayer.SimpleRenderingContext;

            if (context == null)
            {
                return;
            }

            float s      = Util.CalcAxisScale(vc.Camera, normWorld.Translation, Manipulator.AxisLength, vc.Height);
            Color xcolor = (m_hitRegion == HitRegion.XAxis || m_hitRegion == HitRegion.XYSquare || m_hitRegion == HitRegion.XZSquare) ? Color.Gold : Manipulator.XAxisColor;
            Color ycolor = (m_hitRegion == HitRegion.YAxis || m_hitRegion == HitRegion.XYSquare || m_hitRegion == HitRegion.YZSquare) ? Color.Gold : Manipulator.YAxisColor;
            Color Zcolor = (m_hitRegion == HitRegion.ZAxis || m_hitRegion == HitRegion.XZSquare || m_hitRegion == HitRegion.YZSquare) ? Color.Gold : Manipulator.ZAxisColor;

            Color XYx = m_hitRegion == HitRegion.XYSquare ? Color.Gold : Manipulator.XAxisColor;
            Color XYy = m_hitRegion == HitRegion.XYSquare ? Color.Gold : Manipulator.YAxisColor;


            Color XZx = m_hitRegion == HitRegion.XZSquare ? Color.Gold : Manipulator.XAxisColor;
            Color XZz = m_hitRegion == HitRegion.XZSquare ? Color.Gold : Manipulator.ZAxisColor;


            Color YZy = m_hitRegion == HitRegion.YZSquare ? Color.Gold : Manipulator.YAxisColor;
            Color YZz = m_hitRegion == HitRegion.YZSquare ? Color.Gold : Manipulator.ZAxisColor;


            var axisScale = new Matrix4F();

            axisScale.Scale(new Vec3F(s * Manipulator.AxisThickness, s * (1 - ConeHeight), s * Manipulator.AxisThickness));
            var axisrot = new Matrix4F();


            // Draw X axis
            axisrot.RotZ(-MathHelper.PiOver2);
            Matrix4F scaleRot  = axisScale * axisrot;
            Matrix4F axisXform = scaleRot * normWorld;

            Util3D.DrawCylinder(context, axisXform, xcolor);

            // draw y
            axisXform = axisScale * normWorld;
            Util3D.DrawCylinder(context, axisXform, ycolor);

            // draw z
            axisrot.RotX(MathHelper.PiOver2);
            scaleRot  = axisScale * axisrot;
            axisXform = scaleRot * normWorld;
            Util3D.DrawCylinder(context, axisXform, Zcolor);

            // draw center cube.
            Matrix4F cubeScale = new Matrix4F();

            cubeScale.Scale(CenterCube * s);
            var cubexform = cubeScale * normWorld;

            Util3D.DrawCube(context, cubexform, Color.White);


            Matrix4F arrowHead = ComputeXhead(normWorld, s);

            Util3D.DrawCone(context, arrowHead, xcolor);

            arrowHead = ComputeYhead(normWorld, s);
            Util3D.DrawCone(context, arrowHead, ycolor);

            arrowHead = ComputeZhead(normWorld, s);
            Util3D.DrawCone(context, arrowHead, Zcolor);

            // draw xy rect.
            Matrix4F scale = new Matrix4F();

            scale.Scale(s * Manipulator.AxisThickness, s * SquareLength, s * Manipulator.AxisThickness);
            Matrix4F trans = new Matrix4F();

            trans.Translation = new Vec3F(0, s * SquareLength, 0);
            Matrix4F rot = new Matrix4F();

            rot.RotZ(-MathHelper.PiOver2);
            Matrix4F squareXform = scale * rot * trans * normWorld;


            Util3D.DrawCylinder(context, squareXform, XYy);

            trans.Translation = new Vec3F(s * SquareLength, 0, 0);
            squareXform       = scale * trans * normWorld;
            Util3D.DrawCylinder(context, squareXform, XYx);


            // draw xz rect.
            trans.Translation = new Vec3F(0, 0, s * SquareLength);
            rot.RotZ(-MathHelper.PiOver2);
            squareXform = scale * rot * trans * normWorld;
            Util3D.DrawCylinder(context, squareXform, XZz);

            trans.Translation = new Vec3F(s * SquareLength, 0, 0);
            rot.RotX(MathHelper.PiOver2);
            squareXform = scale * rot * trans * normWorld;
            Util3D.DrawCylinder(context, squareXform, XZx);

            // draw yz
            trans.Translation = new Vec3F(0, s * SquareLength, 0);
            rot.RotX(MathHelper.PiOver2);
            squareXform = scale * rot * trans * normWorld;
            Util3D.DrawCylinder(context, squareXform, YZy);

            trans.Translation = new Vec3F(0, 0, s * SquareLength);
            squareXform       = scale * trans * normWorld;
            Util3D.DrawCylinder(context, squareXform, YZz);
        }
Example #33
0
        /// <summary>
        /// Performs actions during control drag</summary>
        /// <param name="hit">Hit record</param>
        /// <param name="x">Mouse x position</param>
        /// <param name="y">Mouse y position</param>
        /// <param name="action">Render action</param>
        /// <param name="camera">Camera</param>
        /// <param name="transform">Transform</param>
        /// <returns>Translation, in world coordinates</returns>
        public Vec3F OnDrag(HitRecord hit, float x, float y, IRenderAction action, Camera camera, Matrix4F transform)
        {
            float    a1, a2;
            Matrix4F W = new Matrix4F();

            W.Mul(transform, camera.ViewMatrix);

            // Setup rays, in view space. (-z goes into the screen.)
            Ray3F ray0 = camera.CreateRay(m_iX, m_iY);
            Ray3F ray  = camera.CreateRay(x, y);

            // Build axis and origin in view space
            Vec3F xAxis  = W.XAxis;
            Vec3F yAxis  = W.YAxis;
            Vec3F zAxis  = W.ZAxis;
            Vec3F origin = W.Translation;

            Vec3F trans = new Vec3F();

            // Choose the best projection plane according to the projection angle
            switch ((HitElement)hit.RenderObjectData[1])
            {
            case HitElement.X_ARROW:
            {
                a1 = Math.Abs(Vec3F.Dot(ray0.Direction, yAxis));
                a2 = Math.Abs(Vec3F.Dot(ray0.Direction, zAxis));
                Vec3F axis       = (a1 > a2 ? yAxis : zAxis);
                Vec3F p0         = ray0.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                Vec3F p1         = ray.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                float dragAmount = Vec3F.Dot(xAxis, p1 - p0);
                Vec3F xLocal     = transform.XAxis;
                trans = dragAmount * xLocal;
            }
            break;

            case HitElement.Y_ARROW:
            {
                a1 = Math.Abs(Vec3F.Dot(ray0.Direction, zAxis));
                a2 = Math.Abs(Vec3F.Dot(ray0.Direction, xAxis));
                Vec3F axis       = (a1 > a2 ? zAxis : xAxis);
                Vec3F p0         = ray0.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                Vec3F p1         = ray.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                float dragAmount = Vec3F.Dot(yAxis, p1 - p0);
                Vec3F yLocal     = transform.YAxis;
                trans = dragAmount * yLocal;
            }
            break;

            case HitElement.Z_ARROW:
            {
                a1 = Math.Abs(Vec3F.Dot(ray0.Direction, xAxis));
                a2 = Math.Abs(Vec3F.Dot(ray0.Direction, yAxis));
                Vec3F axis       = (a1 > a2 ? xAxis : yAxis);
                Vec3F p0         = ray0.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                Vec3F p1         = ray.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                float dragAmount = Vec3F.Dot(zAxis, p1 - p0);
                Vec3F zLocal     = transform.ZAxis;
                trans = dragAmount * zLocal;
            }
            break;

            case HitElement.XY_SQUARE:
            {
                Vec3F p0         = ray0.IntersectPlane(zAxis, -Vec3F.Dot(zAxis, origin));
                Vec3F p1         = ray.IntersectPlane(zAxis, -Vec3F.Dot(zAxis, origin));
                Vec3F deltaLocal = p1 - p0;
                float dragX      = Vec3F.Dot(xAxis, deltaLocal);
                float dragY      = Vec3F.Dot(yAxis, deltaLocal);
                Vec3F xLocal     = transform.XAxis;
                Vec3F yLocal     = transform.YAxis;
                trans = dragX * xLocal + dragY * yLocal;
            }
            break;

            case HitElement.YZ_SQUARE:
            {
                Vec3F p0         = ray0.IntersectPlane(xAxis, -Vec3F.Dot(xAxis, origin));
                Vec3F p1         = ray.IntersectPlane(xAxis, -Vec3F.Dot(xAxis, origin));
                Vec3F deltaLocal = p1 - p0;
                float dragY      = Vec3F.Dot(yAxis, deltaLocal);
                float dragZ      = Vec3F.Dot(zAxis, deltaLocal);
                Vec3F yLocal     = transform.YAxis;
                Vec3F zLocal     = transform.ZAxis;
                trans = dragY * yLocal + dragZ * zLocal;
            }
            break;

            case HitElement.XZ_SQUARE:
            {
                Vec3F p0         = ray0.IntersectPlane(yAxis, -Vec3F.Dot(yAxis, origin));
                Vec3F p1         = ray.IntersectPlane(yAxis, -Vec3F.Dot(yAxis, origin));
                Vec3F deltaLocal = p1 - p0;
                float dragX      = Vec3F.Dot(xAxis, deltaLocal);
                float dragZ      = Vec3F.Dot(zAxis, deltaLocal);
                Vec3F xLocal     = transform.XAxis;
                Vec3F zLocal     = transform.ZAxis;
                trans = dragX * xLocal + dragZ * zLocal;
            }
            break;
            }
            return(trans);
        }
Example #34
0
 /// <summary>
 /// Performs actions at the beginning of control drag</summary>
 /// <param name="hit">Hit record</param>
 /// <param name="x">Mouse x position</param>
 /// <param name="y">Mouse y position</param>
 /// <param name="action">Render action</param>
 /// <param name="camera">Camera</param>
 /// <param name="transform">Transform</param>
 /// <returns>Code for control element under mouse x, y</returns>
 public HitElement OnHit(HitRecord hit, float x, float y, IRenderAction action, Camera camera, Matrix4F transform)
 {
     // Store pick coords
     m_iX = x;
     m_iY = y;
     return((HitElement)hit.RenderObjectData[1]);
 }
Example #35
0
        void Update(Component_Skeleton skeleton, Component_SkeletonAnimationTrack animationTrack, double time)
        {
            if (time != calculatedForTime)
            {
                //update general data
                calculatedForTime = time;
                bones             = skeleton.GetBones();

                //calculate bone transforms
                if (boneTransforms == null || boneTransforms.Length != bones.Length)
                {
                    boneTransforms = new Component_SkeletonAnimationTrack.CalculateBoneTransformsItem[bones.Length];
                }
                animationTrack?.CalculateBoneTransforms(time, boneTransforms);
                CalculateBoneTransforms?.Invoke(this, boneTransforms);

                //calculate transformMatrixRelativeToSkin, transformRelativeToSkin, boneGlobalTransforms, hasScale

                if (transformMatrixRelativeToSkin == null || transformMatrixRelativeToSkin.Length != bones.Length)
                {
                    transformMatrixRelativeToSkin = new Matrix4F[bones.Length];
                }

                if (transformRelativeToSkin == null || transformRelativeToSkin.Length != bones.Length)
                {
                    transformRelativeToSkin = new Component_SkeletonAnimationTrack.CalculateBoneTransformsItem[bones.Length];
                }

                if (boneGlobalTransforms == null || boneGlobalTransforms.Length != bones.Length)
                {
                    boneGlobalTransforms = new BoneGlobalTransformItem[bones.Length];
                }
                var matrixZero = Matrix4F.Zero;
                for (int i = 0; i < bones.Length; i++)
                {
                    boneGlobalTransforms[i] = new BoneGlobalTransformItem(false, ref matrixZero);
                }

                foreach (var b in bones)
                {
                    GetBoneGlobalTransformRecursive(skeleton, b);
                }

                hasScale = false;

                for (int i = 0; i < bones.Length; i++)
                {
                    var bone = bones[i];

                    Matrix4F m;
                    if (bone != null)
                    {
                        Matrix4F.Multiply(ref GetBoneGlobalTransformRecursive(skeleton, bone), ref bone.GetTransformMatrixInverse(), out m);
                    }
                    else
                    {
                        m = Matrix4F.Identity;
                    }
                    transformMatrixRelativeToSkin[i] = m;

                    m.Decompose(out Vector3F t, out QuaternionF r, out Vector3F s);

                    transformRelativeToSkin[i] = new Component_SkeletonAnimationTrack.CalculateBoneTransformsItem {
                        Position = t, Rotation = r, Scale = s
                    };

                    //if the scale differs from 1.0 more than this value, then the scaling is present and DualQuaternionSkinning can not be used.
                    const float EpsilonForScale = 1e-3f;
                    if (Math.Abs(1.0f - s.X) > EpsilonForScale || Math.Abs(1.0f - s.Y) > EpsilonForScale || Math.Abs(1.0f - s.Y) > EpsilonForScale)
                    {
                        hasScale = true;
                    }
                }
            }
        }
        /// <summary>
        /// Synchronizes the camera to the controller's current state</summary>
        /// <param name="camera">Camera</param>
        protected override void ControllerToCamera(Camera camera)
        {
            Vec3F lookAt = Camera.LookAt;
            Vec3F up = Camera.Up;
            if (camera.ViewType == ViewTypes.Perspective)
            {
                
                QuatF rotation = m_rotation * m_currentRotation;
                rotation = rotation.Inverse;
                Matrix4F transform = new Matrix4F(rotation);

                lookAt = new Vec3F(0, 0, -1);
                up = new Vec3F(0, 1, 0);
                transform.Transform(ref lookAt);
                transform.Transform(ref up);
            }

            float eyeOffset = m_distanceFromLookAt;
            float lookAtOffset = 0;
            if (m_distanceFromLookAt < m_dollyThreshold) // do we need to start dollying?
            {
                eyeOffset = m_distanceFromLookAt;
                lookAtOffset = m_distanceFromLookAt - m_dollyThreshold;
            }

            Camera.Set(
                m_lookAtPoint - (eyeOffset * lookAt),       // eye
                m_lookAtPoint - (lookAtOffset * lookAt),    // lookAt
                up);                                        // up

            base.ControllerToCamera(camera);
        }
 /// <summary>
 /// Sets the view matrix for the alpha-sorted phase</summary>
 /// <param name="viewMatrix">View matrix for the alpha-sorted phase</param>
 public void SetViewMatrix(Matrix4F viewMatrix)
 {
     m_viewMatrix.Set(viewMatrix);
 }
        void ProcessVertex(ref Vector3F position, out Vector3F result)
        {
            Matrix4? nullable = new Matrix4?(PosCenter.Value.ToMatrix4());
            Matrix4  matrix4  = nullable ?? Matrix4.Identity;
            Matrix4F matrix4f = matrix4.ToMatrix4F();
            bool     inv      = matrix4f.Inverse();

            MatrixInv = inv;

            ResPosVec1 = matrix4f * Pos1n.Value.Position.ToVector3F();

            result = position;
            var sc        = new Vector3F(0.2f, 0.2f, 0.2f);
            var rposition = position * sc;

            var   l_r01   = (float)Pos01n.Value.Scale.X;
            var   relp01  = (Pos01n.Value.Position).ToVector3F();
            var   l_dist1 = (rposition - relp01);
            float l_l01   = l_dist1.Length();

            var   l_r02   = (float)Pos02n.Value.Scale.X;
            var   relp02  = (Pos02n.Value.Position).ToVector3F();
            var   l_dist2 = (rposition - relp02);
            float l_l02   = l_dist2.Length();

            var   l_r03   = (float)Pos03n.Value.Scale.X;
            var   relp03  = (Pos03n.Value.Position).ToVector3F();
            var   l_dist3 = (rposition - relp03);
            float l_l03   = l_dist3.Length();

            var   l_r04   = (float)Pos04n.Value.Scale.X;
            var   relp04  = (Pos04n.Value.Position).ToVector3F();
            var   l_dist4 = (rposition - relp04);
            float l_l04   = l_dist4.Length();

            var f = ((ResPos1.Value.Position - PosCenter.Value.Position) / sc).ToVector3F().GetNormalize();
            SphericalDirectionF sd = new SphericalDirectionF(f.X, f.Y);
            float       ax         = MathEx.Acos(f.X);
            float       ay         = MathEx.Asin(f.X);
            QuaternionF q          = new AnglesF().ToQuaternion();


            if (l_l01 <= l_r01)
            {
                var relp1 = matrix4f * Pos1n.Value.Position.ToVector3F();
                result = relp1;
            }
            if (l_l02 <= l_r02)
            {
                var relp2 = matrix4f * Pos2n.Value.Position.ToVector3F();;
                result = relp2;
            }
            if (l_l03 <= l_r03)
            {
                var relp3 = matrix4f * Pos3n.Value.Position.ToVector3F();;
                result = relp3;
            }
            if (l_l04 <= l_r04)
            {
                var relp4 = matrix4f * Pos4n.Value.Position.ToVector3F();;
                result = relp4;
            }
        }
Example #39
0
        //public static void Convert( ref OgreMatrix4 mat, out Mat4 result )
        //{
        //   result = new Mat4( mat.mat0, mat.mat1, mat.mat2, mat.mat3 );
        //   result.Transpose();
        //}

        public static unsafe void Convert(OgreMatrix4 *mat, out Matrix4F result)
        {
            result = new Matrix4F(mat->mat0, mat->mat1, mat->mat2, mat->mat3);
            result.Transpose();
        }
Example #40
0
        /// <summary>
        /// Computes transformation matrix from transformation related atrributes.</summary>
        public void ComputeTransform()
        {
            Matrix4F xform = TransformUtils.CalcTransform(m_transformable);

            SetAttribute(Schema.gameObjectType.transformAttribute, xform.ToArray());
        }
 protected Matrix4F mul(Matrix4F matrix1, Matrix4F matrix2)
 {
     return(matrix1 * matrix2);
 }
 /// <summary>
 /// Sets the DomNode attribute to the given Matrix4F</summary>
 /// <param name="domNode">DomNode holding attribute</param>
 /// <param name="attribute">Attribute of the DomNode that contains the data</param>
 /// <param name="m">Matrix4F value to be set</param>
 public static void SetMatrix(DomNode domNode, AttributeInfo attribute, Matrix4F m)
 {
     domNode.SetAttribute(attribute, m.ToArray());
 }
 protected Vector4F mul(Vector4F vector, Matrix4F transform)
 {
     return(Matrix4F.Transform(transform, vector));
     //return Vector4F.Transform(vector, transform);
 }
        //private void Pipeline_RenderBegin( Component_RenderingPipeline_Basic sender, ViewportRenderingContext context, Component_RenderingPipeline_Basic.FrameData frameData )
        //{
        //	if( EnabledInHierarchy && sender.UseRenderTargets )
        //	{
        //		//frameData.GenerateIBLSpecularTexture = true;
        //		//frameData.DeferredSpecularIBLItensity = 1.0 - Intensity;
        //	}
        //}

        private void Pipeline_RenderDeferredShadingEnd(Component_RenderingPipeline_Basic sender, ViewportRenderingContext context, Component_RenderingPipeline_Basic.FrameData frameData, ref Component_Image sceneTexture)
        {
            if (EnabledInHierarchy && sender.GetUseMultiRenderTargets())
            {
                var actualTexture = sceneTexture;

                var pipeline = (Component_RenderingPipeline_Basic)context.RenderingPipeline;

                Vector3 cameraPos = context.Owner.CameraSettings.Position;
                //!!!!double
                Vector3F cameraPosition = cameraPos.ToVector3F();

                //!!!!double
                Matrix4F projectionMatrix = context.Owner.CameraSettings.ProjectionMatrix.ToMatrix4F();
                Matrix4F viewMatrix       = context.Owner.CameraSettings.ViewMatrix.ToMatrix4F();

                Matrix4F viewProjMatrix    = projectionMatrix * viewMatrix;
                Matrix4F invViewProjMatrix = viewProjMatrix.GetInverse();

                float aspectRatio = (float)context.Owner.CameraSettings.AspectRatio;
                float fov         = (float)context.Owner.CameraSettings.FieldOfView;
                float zNear       = (float)context.Owner.CameraSettings.NearClipDistance;
                float zFar        = (float)context.Owner.CameraSettings.FarClipDistance;

                var ambientLight      = frameData.Lights[frameData.LightsInFrustumSorted[0]];
                var ambientLightPower = ambientLight.data.Power;

                var reflectionTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, actualTexture.Result.ResultFormat);
                {
                    context.SetViewport(reflectionTexture.Result.GetRenderTarget().Viewports[0]);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ScreenSpaceReflection\SSR_fs.sc";

                    int maxSteps = 50;
                    switch (Quality.Value)
                    {
                    case QualityEnum.Lowest: maxSteps = 15; break;

                    case QualityEnum.Low: maxSteps = 25; break;

                    case QualityEnum.Medium: maxSteps = 40; break;

                    case QualityEnum.High: maxSteps = 60; break;

                    case QualityEnum.Highest: maxSteps = 100; break;
                    }

                    //int maxSteps = 50;
                    //switch( Quality.Value )
                    //{
                    //case QualityEnum.Lowest: maxSteps = 20; break;
                    //case QualityEnum.Low: maxSteps = 50; break;
                    //case QualityEnum.Medium: maxSteps = 80; break;
                    //case QualityEnum.High: maxSteps = 120; break;
                    //case QualityEnum.Highest: maxSteps = 160; break;
                    //}

                    shader.Defines.Add(new CanvasRenderer.ShaderItem.DefineItem("MAX_STEPS", maxSteps.ToString()));

                    context.objectsDuringUpdate.namedTextures.TryGetValue("gBuffer0Texture", out var gBuffer0Texture);
                    context.objectsDuringUpdate.namedTextures.TryGetValue("depthTexture", out var depthTexture);
                    context.objectsDuringUpdate.namedTextures.TryGetValue("normalTexture", out var normalTexture);
                    context.objectsDuringUpdate.namedTextures.TryGetValue("gBuffer2Texture", out var gBuffer2Texture);

                    //!!!!reflection probes?
                    pipeline.GetBackgroundEnvironmentTextures(context, frameData, /*true, */ out var environmentTexture, out var environmentTextureIBL);

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, depthTexture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, actualTexture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(2, normalTexture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    //!!!!rotation, multiplier

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(3, environmentTexture.Value.texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(4, environmentTextureIBL.Value.texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(5, Component_RenderingPipeline_Basic.BrdfLUT,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(6, gBuffer2Texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(7, gBuffer0Texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point));

                    //!!!часть параметров есть UniformsGeneral.sh

                    shader.Parameters.Set("viewProj", viewProjMatrix);
                    shader.Parameters.Set("invViewProj", invViewProjMatrix);
                    shader.Parameters.Set("cameraPosition", cameraPosition);
                    shader.Parameters.Set("edgeFactorPower", (float)EdgeFactorPower);
                    shader.Parameters.Set("initialStepScale", (float)InitialStepScale.Value);
                    shader.Parameters.Set("worldThickness", (float)WorldThickness.Value);

                    shader.Parameters.Set("colorTextureSize", new Vector4F((float)actualTexture.Result.ResultSize.X, (float)actualTexture.Result.ResultSize.Y, 0.0f, 0.0f));
                    shader.Parameters.Set("zNear", zNear);
                    shader.Parameters.Set("zFar", zFar);
                    shader.Parameters.Set("fov", fov);
                    shader.Parameters.Set("aspectRatio", aspectRatio);

                    context.RenderQuadToCurrentViewport(shader);
                }

                var min = BlurRoughnessMin.Value;
                var max = BlurRoughnessMax.Value;
                if (min > max)
                {
                    min = max;
                }
                var blurRoughnessMin = pipeline.GaussianBlur(context, this, reflectionTexture, min, BlurDownscalingMode, BlurDownscalingValue);
                var blurRoughnessMax = pipeline.GaussianBlur(context, this, reflectionTexture, max, BlurDownscalingMode, BlurDownscalingValue);
                //// Blur Pass:
                //var bluredReflection = pipeline.GaussianBlur( context, this, reflectionTexture, BlurFactorOnMaxRoughness, BlurDownscalingMode, BlurDownscalingValue );

                // Final Pass:
                var finalTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, actualTexture.Result.ResultFormat);
                {
                    context.SetViewport(finalTexture.Result.GetRenderTarget().Viewports[0]);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ScreenSpaceReflection\SSR_Apply_fs.sc";

                    context.objectsDuringUpdate.namedTextures.TryGetValue("gBuffer0Texture", out var gBuffer0Texture);
                    context.objectsDuringUpdate.namedTextures.TryGetValue("depthTexture", out var depthTexture);
                    context.objectsDuringUpdate.namedTextures.TryGetValue("normalTexture", out var normalTexture);
                    context.objectsDuringUpdate.namedTextures.TryGetValue("gBuffer2Texture", out var gBuffer2Texture);

                    //!!!!reflection probes?
                    pipeline.GetBackgroundEnvironmentTextures(context, frameData, /*true, */ out var environmentTexture, out var environmentTextureIBL);

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, actualTexture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, blurRoughnessMin,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(2, blurRoughnessMax,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    //shader.Parameters.Set( "1", new GpuMaterialPass.TextureParameterValue( reflectionTexture,
                    //	TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None ) );

                    //shader.Parameters.Set( "2", new GpuMaterialPass.TextureParameterValue( bluredReflection,
                    //	TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None ) );

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(3, depthTexture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(4, normalTexture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    //!!!!rotation, multiplier

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(5, environmentTexture.Value.texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(6, environmentTextureIBL.Value.texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(7, Component_RenderingPipeline_Basic.BrdfLUT,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(8, gBuffer2Texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(9, gBuffer0Texture,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point));

                    shader.Parameters.Set("invViewProj", invViewProjMatrix);
                    shader.Parameters.Set("cameraPosition", cameraPosition);
                    shader.Parameters.Set("intensity", (float)Intensity);
                    shader.Parameters.Set("ambientLightPower", ambientLightPower);

                    context.RenderQuadToCurrentViewport(shader);
                }

                // Free Targets:
                context.DynamicTexture_Free(reflectionTexture);
                context.DynamicTexture_Free(blurRoughnessMin);
                context.DynamicTexture_Free(blurRoughnessMax);
                //context.RenderTarget_Free( bluredReflection );
                context.DynamicTexture_Free(actualTexture);

                // Update actual Texture:
                actualTexture = finalTexture;

                //result
                sceneTexture = actualTexture;
            }
        }
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_cancelDrag || m_hitRegion == HitRegion.None || NodeList.Count == 0)
            {
                return;
            }

            bool hitAxis = m_hitRegion == HitRegion.XAxis ||
                           m_hitRegion == HitRegion.YAxis ||
                           m_hitRegion == HitRegion.ZAxis;


            Matrix4F view = vc.Camera.ViewMatrix;
            Matrix4F proj = vc.Camera.ProjectionMatrix;
            Matrix4F vp   = view * proj;

            // create ray in world space.
            Ray3F rayW = vc.GetRay(scrPt, vp);

            // create ray in view space.
            Ray3F rayV      = vc.GetRay(scrPt, proj);
            Vec3F translate = m_translatorControl.OnDragging(rayV);

            ISnapSettings snapSettings = (ISnapSettings)DesignView;
            bool          snapToGeom   = Control.ModifierKeys == m_snapGeometryKey;

            if (snapToGeom)
            {
                Vec3F manipPos = HitMatrix.Translation;
                Vec3F manipMove;
                if (hitAxis)
                {
                    //Make rayw to point toward moving axis and starting
                    // from manipulator’s world position.
                    rayW.Direction = Vec3F.Normalize(translate);
                    rayW.Origin    = manipPos;
                    manipMove      = Vec3F.ZeroVector;
                    m_cancelDrag   = true; //stop further snap-to's
                }
                else
                {
                    manipMove = rayW.ProjectPoint(manipPos) - manipPos;
                }

                for (int i = 0; i < NodeList.Count; i++)
                {
                    ITransformable node               = NodeList[i];
                    Vec3F          snapOffset         = TransformUtils.CalcSnapFromOffset(node, snapSettings.SnapFrom);
                    Path <DomNode> path               = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                    Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                    Vec3F          orgPosW;
                    parentLocalToWorld.Transform(m_originalValues[i], out orgPosW);

                    Matrix4F parentWorldToLocal = new Matrix4F();
                    parentWorldToLocal.Invert(parentLocalToWorld);

                    rayW.MoveToIncludePoint(orgPosW + snapOffset + manipMove);

                    HitRecord[] hits    = GameEngine.RayPick(view, proj, rayW, true);
                    bool        cansnap = false;
                    HitRecord   target  = new HitRecord();
                    if (hits.Length > 0)
                    {
                        // find hit record.
                        foreach (var hit in hits)
                        {
                            if (m_snapFilter.CanSnapTo(node, GameEngine.GetAdapterFromId(hit.instanceId)))
                            {
                                target  = hit;
                                cansnap = true;
                                break;
                            }
                        }
                    }

                    if (cansnap)
                    {
                        Vec3F pos;
                        if (target.hasNearestVert && snapSettings.SnapVertex)
                        {
                            pos = target.nearestVertex;
                        }
                        else
                        {
                            pos = target.hitPt;
                        }

                        pos -= snapOffset;
                        parentWorldToLocal.Transform(ref pos);
                        Vec3F diff = pos - node.Transform.Translation;
                        node.Translation += diff;
                        bool rotateOnSnap = snapSettings.RotateOnSnap &&
                                            target.hasNormal &&
                                            (node.TransformationType & TransformationTypes.Rotation) != 0;
                        if (rotateOnSnap)
                        {
                            Vec3F localSurfaceNormal;
                            parentWorldToLocal.TransformNormal(target.normal, out localSurfaceNormal);
                            node.Rotation = TransformUtils.RotateToVector(
                                m_originalRotations[i],
                                localSurfaceNormal,
                                AxisSystemType.YIsUp);
                        }
                    }
                }
            }
            else
            {
                IGrid grid       = DesignView.Context.Cast <IGame>().Grid;
                bool  snapToGrid = Control.ModifierKeys == m_snapGridKey &&
                                   grid.Visible &&
                                   vc.Camera.ViewType == ViewTypes.Perspective;
                float gridHeight = grid.Height;
                // translate.
                for (int i = 0; i < NodeList.Count; i++)
                {
                    ITransformable node = NodeList[i];
                    Path <DomNode> path = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                    Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                    Matrix4F       parentWorldToLocal = new Matrix4F();
                    parentWorldToLocal.Invert(parentLocalToWorld);
                    Vec3F localTranslation;
                    parentWorldToLocal.TransformVector(translate, out localTranslation);
                    Vec3F trans = m_originalValues[i] + localTranslation;

                    if (snapToGrid)
                    {
                        if (grid.Snap)
                        {
                            trans = grid.SnapPoint(trans);
                        }
                        else
                        {
                            trans.Y = gridHeight;
                        }
                    }

                    node.Translation = trans;
                }
            }
        }
Example #46
0
        internal void Draw(DeviceContext graphics, ref Matrix4F matrix, Entity avatar, Universe universe,
                           AvatarController avatarController, Vector2 mouseLocation)
        {
            if (_spriteBatch == null)
            {
                _spriteBatch = new SpriteBatch(graphics.Graphics.GraphicsDevice);
            }
            else if (_spriteBatch.IsDisposed)
            {
                _spriteBatch = new SpriteBatch(graphics.Graphics.GraphicsDevice);
            }

            if (_escape)
            {
                if (!graphics.IsActive())
                {
                    Dispose();
                    return;
                }
            }

            try {
                _spriteBatch.End();
            } catch {
                // ignore
            }

            _spriteBatch.Begin();

            var size = Container.GetSize();

            Vector2 origin;

            ViewPort = graphics.Graphics.GraphicsDevice.Viewport;

            switch (Alignment)
            {
            case UiAlignment.TopLeft:
                origin = new Vector2(0, 0);
                break;

            case UiAlignment.TopCenter:
                origin = new Vector2((ViewPort.Width / 2) - (size.X / 2), 0);
                break;

            case UiAlignment.TopRight:
                origin = new Vector2(ViewPort.Width - size.X, 0);
                break;

            case UiAlignment.MiddleLeft:
                origin = new Vector2(0, (ViewPort.Height / 2) - (size.Y / 2));
                break;

            case UiAlignment.MiddleCenter:
            default:
                origin = new Vector2((ViewPort.Width / 2) - (size.X / 2), (ViewPort.Height / 2) - (size.Y / 2));
                break;

            case UiAlignment.MiddleRight:
                origin = new Vector2(ViewPort.Width - size.X, (ViewPort.Height / 2) - (size.Y / 2));
                break;

            case UiAlignment.BottomLeft:
                origin = new Vector2(0, ViewPort.Height - size.Y);
                break;

            case UiAlignment.BottomCenter:
                origin = new Vector2((ViewPort.Width / 2) - (size.X / 2), ViewPort.Height - size.Y);
                break;

            case UiAlignment.BottomRight:
                origin = new Vector2(ViewPort.Width - size.X, ViewPort.Height - size.Y);
                break;
            }

            Container.Draw(graphics, avatar, universe, origin, _spriteBatch, mouseLocation, _spriteBatch.GraphicsDevice.ScissorRectangle);
            if (!_spriteBatch.IsDisposed)
            {
                try {
                    _spriteBatch.End();
                } catch {
                    _spriteBatch.Dispose();
                }
            }
        }
Example #47
0
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_hitRegion == HitRegion.None || NodeList.Count == 0)
            {
                return;
            }
            Camera cam = vc.Camera;

            Matrix4F view = cam.ViewMatrix;
            Matrix4F mtrx = cam.ProjectionMatrix;

            Matrix4F axisMtrx = HitMatrix * view;
            Ray3F    hitRay   = HitRayV;
            Ray3F    dragRay  = vc.GetRay(scrPt, mtrx);

            Vec3F xAxis  = axisMtrx.XAxis;
            Vec3F yAxis  = axisMtrx.YAxis;
            Vec3F zAxis  = axisMtrx.ZAxis;
            Vec3F origin = axisMtrx.Translation;

            Vec3F rotAxis = new Vec3F();
            float theta   = 0;

            float snapAngle = ((ISnapSettings)DesignView).SnapAngle;

            switch (m_hitRegion)
            {
            case HitRegion.XAxis:
            {
                Plane3F xplane = new Plane3F(xAxis, origin);
                theta   = CalcAngle(origin, xplane, hitRay, dragRay, snapAngle);
                rotAxis = HitMatrix.XAxis;
            }
            break;

            case HitRegion.YAxis:
            {
                Plane3F yplane = new Plane3F(yAxis, origin);
                theta   = CalcAngle(origin, yplane, hitRay, dragRay, snapAngle);
                rotAxis = HitMatrix.YAxis;
            }
            break;

            case HitRegion.ZAxis:
            {
                Plane3F zplane = new Plane3F(zAxis, origin);
                theta   = CalcAngle(origin, zplane, hitRay, dragRay, snapAngle);
                rotAxis = HitMatrix.ZAxis;
            }
            break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            AngleAxisF axf       = new AngleAxisF(-theta, rotAxis);
            Matrix4F   deltaMtrx = new Matrix4F(axf);
            Matrix4F   rotMtrx   = new Matrix4F();

            for (int i = 0; i < NodeList.Count; i++)
            {
                ITransformable node = NodeList[i];
                rotMtrx.Set(m_rotations[i]);
                rotMtrx.Mul(rotMtrx, deltaMtrx);
                float ax, ay, az;
                rotMtrx.GetEulerAngles(out ax, out ay, out az);
                node.Rotation = new Vec3F(ax, ay, az);
            }
        }
Example #48
0
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_hitRegion == HitRegion.None || m_activeOp == null || m_activeOp.NodeList.Count == 0)
            {
                return;
            }
            Camera cam = vc.Camera;

            Matrix4F view = cam.ViewMatrix;
            Matrix4F proj = cam.ProjectionMatrix;

            Matrix4F axisMtrx = HitMatrix * view;
            Ray3F    hitRay   = HitRayV;
            Ray3F    dragRay  = vc.GetRay(scrPt, proj);

            Vec3F xAxis  = axisMtrx.XAxis;
            Vec3F yAxis  = axisMtrx.YAxis;
            Vec3F zAxis  = axisMtrx.ZAxis;
            Vec3F origin = axisMtrx.Translation;

            Vec3F rotAxis = new Vec3F();
            float theta   = 0;

            float snapAngle = ((ISnapSettings)DesignView).SnapAngle;

            switch (m_hitRegion)
            {
            case HitRegion.XAxis:
            {
                Plane3F xplane = new Plane3F(xAxis, origin);
                theta   = CalcAngle(origin, xplane, hitRay, dragRay, snapAngle);
                rotAxis = HitMatrix.XAxis;
            }
            break;

            case HitRegion.YAxis:
            {
                Plane3F yplane = new Plane3F(yAxis, origin);
                theta   = CalcAngle(origin, yplane, hitRay, dragRay, snapAngle);
                rotAxis = HitMatrix.YAxis;
            }
            break;

            case HitRegion.ZAxis:
            {
                Plane3F zplane = new Plane3F(zAxis, origin);
                theta   = CalcAngle(origin, zplane, hitRay, dragRay, snapAngle);
                rotAxis = HitMatrix.ZAxis;
            }
            break;

            case HitRegion.LookAxis:
            {
                // for billboard objects the look vector is object's negative position in viewspace.
                Vec3F   lookAxis = Vec3F.Normalize(-origin);
                Plane3F plane    = new Plane3F(lookAxis, origin);
                theta   = CalcAngle(origin, plane, hitRay, dragRay, snapAngle);
                rotAxis = m_lookAxisHitMtrx.ZAxis;
            }
            break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            AngleAxisF axf       = new AngleAxisF(-theta, rotAxis);
            Matrix4F   deltaMtrx = new Matrix4F(axf);
            Matrix4F   rotMtrx   = new Matrix4F();

            for (int i = 0; i < m_activeOp.NodeList.Count; i++)
            {
                ITransformable node = m_activeOp.NodeList[i];
                rotMtrx.Mul(m_rotations[i], deltaMtrx);
                float ax, ay, az;
                rotMtrx.GetEulerAngles(out ax, out ay, out az);
                node.Rotation = new Vec3F(ax, ay, az);
            }
        }
Example #49
0
        public HitRegion Pick(ViewControl vc, Matrix4F world, Matrix4F view, Ray3F rayL, Ray3F rayV)
        {
            float s = Util.CalcAxisScale(vc.Camera, world.Translation, Manipulator.AxisLength, vc.Height);

            m_hitRegion = HitRegion.None;
            m_hitRayV   = rayV;

            m_hitMatrix.Set(world);
            m_hitWorldView = world * view;

            float sl = s * SquareLength;


            // test xy square.
            Vec3F   p1    = new Vec3F(0, 0, 0);
            Vec3F   p2    = new Vec3F(sl, 0, 0);
            Vec3F   p3    = new Vec3F(sl, sl, 0);
            Vec3F   p4    = new Vec3F(0, sl, 0);
            Plane3F plane = new Plane3F(p1, p2, p3);
            Vec3F   p;

            if (rayL.IntersectPlane(plane, out p))
            {
                // test point in 2d rectangle.
                if (p.X > p1.X && p.X < p2.X &&
                    p.Y > p1.Y && p.Y < p4.Y)
                {
                    m_hitRegion = HitRegion.XYSquare;
                    return(m_hitRegion);
                }
            }

            // test xz square
            p1    = new Vec3F(0, 0, 0);
            p2    = new Vec3F(sl, 0, 0);
            p3    = new Vec3F(sl, 0, sl);
            p4    = new Vec3F(0, 0, sl);
            plane = new Plane3F(p1, p2, p3);
            if (rayL.IntersectPlane(plane, out p))
            {
                // test point in 2d rectangle.
                if (p.X > p1.X && p.X < p2.X &&
                    p.Z > p1.Z && p.Z < p4.Z)
                {
                    m_hitRegion = HitRegion.XZSquare;
                    return(m_hitRegion);
                }
            }


            // test yz square
            p1    = new Vec3F(0, 0, 0);
            p2    = new Vec3F(0, 0, sl);
            p3    = new Vec3F(0, sl, sl);
            p4    = new Vec3F(0, sl, 0);
            plane = new Plane3F(p1, p2, p3);
            if (rayL.IntersectPlane(plane, out p))
            {
                // test point in 2d rectangle.
                if (p.Z > p1.Z && p.Z < p2.Z &&
                    p.Y > p1.Z && p.Y < p4.Y)
                {
                    m_hitRegion = HitRegion.YZSquare;
                    return(m_hitRegion);
                }
            }

            Vec3F    min      = new Vec3F(-0.5f, -0.5f, -0.5f);
            Vec3F    max      = new Vec3F(0.5f, 0.5f, 0.5f);
            AABB     box      = new AABB(min, max);
            Matrix4F boxScale = new Matrix4F();
            Matrix4F boxTrans = new Matrix4F();
            Matrix4F BoxMtrx  = new Matrix4F();

            // X axis
            boxScale.Scale(new Vec3F(s, s * ConeDiameter, s * ConeDiameter));
            boxTrans.Translation = new Vec3F(s / 2, 0, 0);
            BoxMtrx = boxScale * boxTrans;

            Ray3F ray = rayL;

            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.XAxis;
                return(m_hitRegion);
            }

            // y axis
            boxScale.Scale(new Vec3F(s * ConeDiameter, s, s * ConeDiameter));
            boxTrans.Translation = new Vec3F(0, s / 2, 0);
            BoxMtrx = boxScale * boxTrans;
            ray     = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.YAxis;
                return(m_hitRegion);
            }

            // z axis
            boxScale.Scale(new Vec3F(s * ConeDiameter, s * ConeDiameter, s));
            boxTrans.Translation = new Vec3F(0, 0, s / 2);
            BoxMtrx = boxScale * boxTrans;

            ray = rayL;
            BoxMtrx.Invert(BoxMtrx);
            ray.Transform(BoxMtrx);
            if (box.Intersect(ray))
            {
                m_hitRegion = HitRegion.ZAxis;
            }

            return(m_hitRegion);
        }
Example #50
0
 public Manipulator()
 {
     HitMatrix  = new Matrix4F();
     DesignView = null;
 }
Example #51
0
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_hitRegion == HitRegion.None || m_activeOp == null || m_activeOp.NodeList.Count == 0)
                return;

            Matrix4F view = vc.Camera.ViewMatrix;
            // compute world * view
            Matrix4F wv = new Matrix4F();
            wv.Mul(HitMatrix, view);

            // create ray in view space.
            Ray3F rayV = vc.GetRay(scrPt, vc.Camera.ProjectionMatrix);

            Vec3F xAxis = wv.XAxis;
            Vec3F yAxis = wv.YAxis;
            Vec3F zAxis = wv.ZAxis;
            Vec3F origin = wv.Translation;

            m_scale = new Vec3F(1, 1, 1);
            float scale = 1;
            float a1, a2;

            switch (m_hitRegion)
            {
                case HitRegion.XAxis:
                case HitRegion.NegXAxis:
                    {
                        a1 = Math.Abs(Vec3F.Dot(HitRayV.Direction, yAxis));
                        a2 = Math.Abs(Vec3F.Dot(HitRayV.Direction, zAxis));
                        Vec3F axis = (a1 > a2 ? yAxis : zAxis);
                        Vec3F p0 = HitRayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                        Vec3F p1 = rayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                        float dragAmount = Vec3F.Dot((p1 - p0), xAxis);
                        if (m_hitRegion == HitRegion.NegXAxis)
                        {
                            dragAmount *= -1;
                        }
                        m_scale.X = 1.0f + dragAmount / m_hitScale;
                        scale = m_scale.X;

                    }

                    break;
                case HitRegion.YAxis:
                case HitRegion.NegYAxis:
                    {
                        a1 = Math.Abs(Vec3F.Dot(HitRayV.Direction, zAxis));
                        a2 = Math.Abs(Vec3F.Dot(HitRayV.Direction, xAxis));
                        Vec3F axis = (a1 > a2 ? zAxis : xAxis);
                        Vec3F p0 = HitRayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                        Vec3F p1 = rayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                        float dragAmount = Vec3F.Dot((p1 - p0), yAxis);
                        if (m_hitRegion == HitRegion.NegYAxis)
                        {
                            dragAmount *= -1;
                        }
                        m_scale.Y = 1.0f + dragAmount / m_hitScale;
                        scale = m_scale.Y;

                    }
                    break;
                case HitRegion.ZAxis:
                case HitRegion.NegZAxis:
                    {
                        a1 = Math.Abs(Vec3F.Dot(HitRayV.Direction, xAxis));
                        a2 = Math.Abs(Vec3F.Dot(HitRayV.Direction, yAxis));
                        Vec3F axis = (a1 > a2 ? xAxis : yAxis);
                        Vec3F p0 = HitRayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                        Vec3F p1 = rayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                        float dragAmount = Vec3F.Dot((p1 - p0), zAxis);
                        if (m_hitRegion == HitRegion.NegZAxis)
                        {
                            dragAmount *= -1;
                        }
                        m_scale.Z = 1.0f + dragAmount / m_hitScale;
                        scale = m_scale.Z;

                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }

            if(m_isUniformScaling)
                m_scale = new Vec3F(scale,scale,scale);

            // scale
            for (int i = 0; i < m_activeOp.NodeList.Count; i++)
            {
                ITransformable node = m_activeOp.NodeList[i];
                node.Scale = Vec3F.Mul(m_originalScales[i], m_scale);

                Matrix4F mtrx = TransformUtils.CalcTransform(
                   Vec3F.ZeroVector,
                   node.Rotation,
                   node.Scale,
                    m_pivotOffset[i]);
                node.Translation = m_originalTranslations[i] + mtrx.Translation;

            }
        }
Example #52
0
        /// <summary>
        /// Adjusts child transform, making it relative to new parent node's transform.
        /// Is recursive, looking for parents that also implement IRenderableNode.</summary>
        /// <param name="parent">Parent node</param>
        /// <param name="child">Child node</param>
        public static void AddChild(ITransformable parent, ITransformable child)
        {
            Path <DomNode> path          = new Path <DomNode>(parent.Cast <DomNode>().GetPath());
            Matrix4F       parentToWorld = TransformUtils.CalcPathTransform(path, path.Count - 1);

            // We want 'child' to appear in the same place in the world after adding to 'parent'.
            // local-point * original-local-to-world = world-point
            // new-local-point * new-local-to-parent * parent-to-world = world-point
            // ==> new-local-to-parent * parent-to-world = original-local-to-world
            // (multiply both sides by inverse of parent-to-world; call it world-to-parent)
            // ==> new-local-to-parent = original-local-to-world * world-to-parent
            Matrix4F worldToParent = new Matrix4F();

            worldToParent.Invert(parentToWorld);
            Matrix4F originalLocalToWorld = child.Transform;
            Matrix4F newLocalToParent     = Matrix4F.Multiply(originalLocalToWorld, worldToParent);

            // The translation component of newLocalToParent consists of pivot translation
            //  as well as the child.Translation. So, start with the original child.Translation
            //  and transform it into our new space.
            Vec3F newTranslation = child.Translation;

            worldToParent.Transform(ref newTranslation);

            // There's only one way of getting rotation info, so get it straight from matrix.
            Vec3F newRotation = new Vec3F();

            newLocalToParent.GetEulerAngles(out newRotation.X, out newRotation.Y, out newRotation.Z);
            child.Rotation = newRotation;

            // Likewise with scale.
            Vec3F newScale = newLocalToParent.GetScale();

            child.Scale = newScale;

            // We can compose together all of the separate transformations now.
            Matrix4F newTransform = CalcTransform(
                newTranslation,
                newRotation,
                newScale,
                child.ScalePivot,
                child.ScalePivotTranslation,
                child.RotatePivot,
                child.RotatePivotTranslation);

            // However, the composed matrix may not equal newLocalToParent due to rotating
            //  or scaling around a pivot. In the general case, it may be impossible to
            //  decompose newLocalToParent into all of these separate components. For example,
            //  a sheer transformation cannot be reproduced by a single rotation and scale.
            //  But for common cases, only the translation is out-of-sync now, so apply a fix.
            Vec3F    desiredTranslation = newLocalToParent.Translation;
            Vec3F    currentTranslation = newTransform.Translation;
            Vec3F    fixupTranslation   = desiredTranslation - currentTranslation;
            Matrix4F fixupTransform     = new Matrix4F(fixupTranslation);

            newTransform.Mul(newTransform, fixupTransform);

            // Save the fix and the final transform. Storing the fix in RotatePivotTranslation
            //  is done elsewhere, as well.
            child.Translation = newTranslation + fixupTranslation;
            child.Transform   = newTransform;
        }
Example #53
0
        public override void Render(ViewControl vc)
        {
            Matrix4F normWorld = GetManipulatorMatrix();
            if (normWorld == null) return;

            int axis = (int)m_hitRegion;

            // axis colors
            Color saveColor = m_axisColor[axis];
            m_axisColor[axis] = m_highlightColor;
            Color xcolor  = m_axisColor[(int)HitRegion.XAxis];
            Color ycolor  = m_axisColor[(int)HitRegion.YAxis];
            Color zcolor  = m_axisColor[(int)HitRegion.ZAxis];
            Color nxcolor = m_axisColor[(int)HitRegion.NegXAxis];
            Color nycolor = m_axisColor[(int)HitRegion.NegYAxis];
            Color nzcolor = m_axisColor[(int)HitRegion.NegZAxis];
            m_axisColor[axis] = saveColor;

            if (m_hitRegion != HitRegion.None)
            {
                normWorld.Translation = HitMatrix.Translation;
            }

            Vec3F pos = normWorld.Translation;
            float s = Util.CalcAxisScale(vc.Camera, pos, AxisLength, vc.Height);

            Vec3F sv = new Vec3F(s, s, s);
            Vec3F axscale = new Vec3F(s*AxisThickness, s, s*AxisThickness);
            bool negativeAxis = m_hitRegion == HitRegion.NegXAxis || m_hitRegion == HitRegion.NegYAxis || m_hitRegion == HitRegion.NegZAxis;
            Vec3F dragScale = new Vec3F(Math.Abs(m_scale.X),
                Math.Abs(m_scale.Y), Math.Abs(m_scale.Z));

            Matrix4F rot = new Matrix4F();
            Matrix4F scale = new Matrix4F();
            axscale.Y = negativeAxis ? s : s * dragScale.X;
            scale.Scale(axscale);
            rot.RotZ(-MathHelper.PiOver2);
            Matrix4F xform = scale * rot * normWorld;
            Util3D.DrawCylinder(xform, xcolor);

            axscale.Y = negativeAxis ? s : s * dragScale.Y;
            scale.Scale(axscale);
            xform = scale * normWorld;
            Util3D.DrawCylinder(xform, ycolor);

            axscale.Y = negativeAxis ? s : s * dragScale.Z;
            scale.Scale(axscale);
            rot.RotX(MathHelper.PiOver2);
            xform = scale * rot * normWorld;
            Util3D.DrawCylinder(xform, zcolor);

            rot.RotZ(MathHelper.PiOver2);
            axscale.Y = negativeAxis ? s * dragScale.X : s;
            scale.Scale(axscale);
            xform = scale * rot * normWorld;
            Util3D.DrawCylinder(xform, nxcolor);

            rot.RotZ(MathHelper.Pi);
            axscale.Y = negativeAxis ? s * dragScale.Y : s;
            scale.Scale(axscale);
            xform = scale * rot * normWorld;
            Util3D.DrawCylinder(xform, nycolor);

            rot.RotX(-MathHelper.PiOver2);
            axscale.Y = negativeAxis ? s * dragScale.Z : s;
            scale.Scale(axscale);
            xform = scale * rot * normWorld;
            Util3D.DrawCylinder(xform, nzcolor);

            // draw center cube
            scale.Scale(s*(1.0f / 16.0f));
            xform = scale * normWorld;
            Util3D.DrawCube(xform, Color.White);

            Vec3F handle = sv*AxisHandle;
            float handleWidth = handle.X/2;
            scale.Scale(handle);
            Matrix4F trans = new Matrix4F();

            // X handle
            float drag = m_hitRegion == HitRegion.XAxis ? dragScale.X : 1.0f;
            trans.Translation = new Vec3F(drag * sv.X - handleWidth, 0, 0);
            xform = scale * trans * normWorld;
            Util3D.DrawCube(xform, xcolor);

            // y handle
            drag = m_hitRegion == HitRegion.YAxis ? dragScale.Y : 1.0f;
            trans.Translation = new Vec3F(0, drag * sv.Y - handleWidth, 0);
            xform = scale * trans * normWorld;
            Util3D.DrawCube(xform, ycolor);

            // z handle
            drag = m_hitRegion == HitRegion.ZAxis ? dragScale.Z : 1.0f;
            trans.Translation = new Vec3F(0, 0, drag * sv.Z - handleWidth);
            xform = scale * trans * normWorld;
            Util3D.DrawCube(xform, zcolor);

            // -x handle
            drag = m_hitRegion == HitRegion.NegXAxis ? dragScale.X : 1.0f;
            trans.Translation = new Vec3F(-sv.X * drag + handleWidth, 0, 0);
            xform = scale * trans * normWorld;
            Util3D.DrawCube(xform, nxcolor);

            // -y handle
            drag = m_hitRegion == HitRegion.NegYAxis ? dragScale.Y : 1.0f;
            trans.Translation = new Vec3F(0, -sv.Y * drag + handleWidth, 0);
            xform = scale * trans * normWorld;
            Util3D.DrawCube(xform, nycolor);

            // -z handle
            drag = m_hitRegion == HitRegion.NegZAxis ? dragScale.Z : 1.0f;
            trans.Translation = new Vec3F(0, 0, -sv.Z * drag + handleWidth);
            xform = scale * trans * normWorld;
            Util3D.DrawCube(xform, nzcolor);
        }
Example #54
0
        //

        static SimpleTypes()
        {
            //string
            RegisterType(typeof(string), delegate(string value)
            {
                if (value == null)
                {
                    return("");
                    //throw new Exception( "GetSimpleTypeValue: string type, value = null" );
                }
                return(value);
            }, "");

            //bool
            RegisterType(typeof(bool), delegate(string value)
            {
                string lower = value.ToLower();
                if (value == "1" || lower == "yes" || lower == "true")
                {
                    return(true);
                }
                else if (value == "0" || lower == "no" || lower == "false")
                {
                    return(false);
                }
                else
                {
                    return(bool.Parse(value));
                }
            }, false);

            //sbyte
            RegisterType(typeof(sbyte), delegate(string value) { return(sbyte.Parse(value)); }, 0);

            //byte
            RegisterType(typeof(byte), delegate(string value) { return(byte.Parse(value)); }, 0);

            //char
            RegisterType(typeof(char), delegate(string value) { return(char.Parse(value)); }, 0);

            //short
            RegisterType(typeof(short), delegate(string value) { return(short.Parse(value)); }, 0);

            //ushort
            RegisterType(typeof(ushort), delegate(string value) { return(ushort.Parse(value)); }, 0);

            //int
            RegisterType(typeof(int), delegate(string value) { return(int.Parse(value)); }, 0);

            //uint
            RegisterType(typeof(uint), delegate(string value) { return(uint.Parse(value)); }, (uint)0);

            //long
            RegisterType(typeof(long), delegate(string value) { return(long.Parse(value)); }, (long)0);

            //ulong
            RegisterType(typeof(ulong), delegate(string value) { return(ulong.Parse(value)); }, (ulong)0);

            //float
            RegisterType(typeof(float), delegate(string value) { return(float.Parse(value)); }, 0.0f);

            //double
            RegisterType(typeof(double), delegate(string value) { return(double.Parse(value)); }, 0.0);

            //decimal
            RegisterType(typeof(decimal), delegate(string value) { return(decimal.Parse(value)); }, (decimal)0.0);

            //Vec2
            RegisterType(typeof(Vector2F), delegate(string value) { return(Vector2F.Parse(value)); }, Vector2F.Zero);

            //Range
            RegisterType(typeof(RangeF), delegate(string value) { return(RangeF.Parse(value)); }, RangeF.Zero);

            //Vec3
            RegisterType(typeof(Vector3F), delegate(string value) { return(Vector3F.Parse(value)); }, Vector3F.Zero);

            //Vec4
            RegisterType(typeof(Vector4F), delegate(string value) { return(Vector4F.Parse(value)); }, Vector4F.Zero);

            //Bounds
            RegisterType(typeof(BoundsF), delegate(string value) { return(BoundsF.Parse(value)); }, BoundsF.Zero);

            //Quat
            RegisterType(typeof(QuaternionF), delegate(string value) { return(QuaternionF.Parse(value)); }, QuaternionF.Identity);

            //ColorValue
            RegisterType(typeof(ColorValue), delegate(string value) { return(ColorValue.Parse(value)); }, ColorValue.Zero);

            //ColorValuePowered
            RegisterType(typeof(ColorValuePowered), delegate(string value) { return(ColorValuePowered.Parse(value)); }, ColorValuePowered.Zero);

            //ColorPacked
            RegisterType(typeof(ColorByte), delegate(string value) { return(ColorByte.Parse(value)); }, ColorByte.Zero);

            //SphereDir
            RegisterType(typeof(SphericalDirectionF), delegate(string value) { return(SphericalDirectionF.Parse(value)); }, SphericalDirectionF.Zero);

            //Vec2I
            RegisterType(typeof(Vector2I), delegate(string value) { return(Vector2I.Parse(value)); }, Vector2I.Zero);

            //Vec3I
            RegisterType(typeof(Vector3I), delegate(string value) { return(Vector3I.Parse(value)); }, Vector3I.Zero);

            //Vec4I
            RegisterType(typeof(Vector4I), delegate(string value) { return(Vector4I.Parse(value)); }, Vector4I.Zero);

            //Rect
            RegisterType(typeof(RectangleF), delegate(string value) { return(RectangleF.Parse(value)); }, RectangleF.Zero);

            //RectI
            RegisterType(typeof(RectangleI), delegate(string value) { return(RectangleI.Parse(value)); }, RectangleI.Zero);

            //Degree
            RegisterType(typeof(DegreeF), delegate(string value) { return(DegreeF.Parse(value)); }, DegreeF.Zero);

            //Radian
            RegisterType(typeof(RadianF), delegate(string value) { return(RadianF.Parse(value)); }, RadianF.Zero);

            //Vec2D
            RegisterType(typeof(Vector2), delegate(string value) { return(Vector2.Parse(value)); }, Vector2.Zero);

            //RangeD
            RegisterType(typeof(Range), delegate(string value) { return(Range.Parse(value)); }, Range.Zero);

            //RangeI
            RegisterType(typeof(RangeI), delegate(string value) { return(RangeI.Parse(value)); }, RangeI.Zero);

            //Vec3D
            RegisterType(typeof(Vector3), delegate(string value) { return(Vector3.Parse(value)); }, Vector3.Zero);

            //Vec4D
            RegisterType(typeof(Vector4), delegate(string value) { return(Vector4.Parse(value)); }, Vector4.Zero);

            //BoundsD
            RegisterType(typeof(Bounds), delegate(string value) { return(Bounds.Parse(value)); }, Bounds.Zero);

            //QuatD
            RegisterType(typeof(Quaternion), delegate(string value) { return(Quaternion.Parse(value)); }, Quaternion.Identity);

            //SphereDirD
            RegisterType(typeof(SphericalDirection), delegate(string value) { return(SphericalDirection.Parse(value)); }, SphericalDirection.Zero);

            //RectD
            RegisterType(typeof(Rectangle), delegate(string value) { return(Rectangle.Parse(value)); }, Rectangle.Zero);

            //DegreeD
            RegisterType(typeof(Degree), delegate(string value) { return(Degree.Parse(value)); }, Degree.Zero);

            //RadianD
            RegisterType(typeof(Radian), delegate(string value) { return(Radian.Parse(value)); }, Radian.Zero);

            //Angles
            RegisterType(typeof(AnglesF), delegate(string value) { return(AnglesF.Parse(value)); }, AnglesF.Zero);

            //AnglesD
            RegisterType(typeof(Angles), delegate(string value) { return(Angles.Parse(value)); }, Angles.Zero);

            //Mat2F
            RegisterType(typeof(Matrix2F), delegate(string value) { return(Matrix2F.Parse(value)); }, Matrix2F.Zero);

            //Mat2D
            RegisterType(typeof(Matrix2), delegate(string value) { return(Matrix2.Parse(value)); }, Matrix2.Zero);

            //Mat3F
            RegisterType(typeof(Matrix3F), delegate(string value) { return(Matrix3F.Parse(value)); }, Matrix3F.Zero);

            //Mat3D
            RegisterType(typeof(Matrix3), delegate(string value) { return(Matrix3.Parse(value)); }, Matrix3.Zero);

            //Mat4F
            RegisterType(typeof(Matrix4F), delegate(string value) { return(Matrix4F.Parse(value)); }, Matrix4F.Zero);

            //Mat4D
            RegisterType(typeof(Matrix4), delegate(string value) { return(Matrix4.Parse(value)); }, Matrix4.Zero);

            //PlaneF
            RegisterType(typeof(PlaneF), delegate(string value) { return(PlaneF.Parse(value)); }, PlaneF.Zero);

            //PlaneD
            RegisterType(typeof(Plane), delegate(string value) { return(Plane.Parse(value)); }, Plane.Zero);

            //Transform
            RegisterType(typeof(Transform), delegate(string value) { return(Transform.Parse(value)); }, Transform.Identity);

            //UIMeasureValueDouble
            RegisterType(typeof(UIMeasureValueDouble), delegate(string value) { return(UIMeasureValueDouble.Parse(value)); }, new UIMeasureValueDouble());

            //UIMeasureValueVec2
            RegisterType(typeof(UIMeasureValueVector2), delegate(string value) { return(UIMeasureValueVector2.Parse(value)); }, new UIMeasureValueVector2());

            //UIMeasureValueRect
            RegisterType(typeof(UIMeasureValueRectangle), delegate(string value) { return(UIMeasureValueRectangle.Parse(value)); }, new UIMeasureValueRectangle());

            RegisterType(typeof(RangeVector3F), delegate(string value) { return(RangeVector3F.Parse(value)); }, RangeVector3F.Zero);
            RegisterType(typeof(RangeColorValue), delegate(string value) { return(RangeColorValue.Parse(value)); }, RangeColorValue.Zero);

            //no Parse methods. This is complex structures. This is not simple types? or just can't parse?
            //Box
            //Capsule
            //Cone
            //Line3
            //Line2
            //Ray
            //Frustum?

            RegisterConvertDoubleToFloatTypes();
        }
Example #55
0
        public override void OnBeginDrag()
        {
            if (m_hitRegion == HitRegion.None)
                return;
            var selectionCntx = DesignView.Context.As<ISelectionContext>();
            var selection = selectionCntx.Selection;
            var transactionContext = DesignView.Context.As<ITransactionContext>();

            m_activeOp = null;

            var op = new ManipulatorActiveOperation(
                "Rotate", DesignView.Context.As<ISelectionContext>(),
                (ITransformable node) => (node.TransformationType & TransformationTypes.Rotation) != 0,
                false);

            m_rotations = new Matrix4F[op.NodeList.Count];
            for (int k = 0; k < op.NodeList.Count; k++)
            {
                ITransformable node = op.NodeList[k];                
                Matrix4F m = new Matrix4F(node.Transform);
                m.Translation = new Vec3F(0, 0, 0);
                m.Normalize(m);
                m_rotations[k] = m;
            }

            m_activeOp = op;
        }
Example #56
0
File: Node.cs Project: zparr/ATF
        /// <summary>
        /// Performs initialization when the adapter's node is set.
        /// This method is called each time the adapter is connected to its underlying node.
        /// Typically overridden by creators of DOM adapters.</summary>
        protected override void OnNodeSet()
        {
            base.OnNodeSet();

            // get trans, scale, and rot.
            foreach (DomNode domNode in this.DomNode.GetChildList(Schema.node.scaleChild))
            {
                m_scale = Tools.GetVector3(domNode, Schema.TargetableFloat3.Attribute);
                break;
            }

            foreach (DomNode domNode in this.DomNode.GetChildList(Schema.node.translateChild))
            {
                m_translation = Tools.GetVector3(domNode, Schema.TargetableFloat3.Attribute);
                break;
            }

            const float PiOver180 = (float)(Math.PI / 180.0f);

            foreach (DomNode node in DomNode.GetChildList(Schema.node.rotateChild))
            {
                double[] arr   = (double[])node.GetAttribute(Schema.rotate.Attribute);
                float    angle = (float)arr[3] * PiOver180;
                string   sid   = node.GetAttribute(Schema.rotate.sidAttribute) as string;
                if (string.IsNullOrEmpty(sid))
                {
                    continue;
                }
                if (sid == "rotateX")
                {
                    m_rotation.X = angle;
                }
                else if (sid == "rotateY")
                {
                    m_rotation.Y = angle;
                }
                else if (sid == "rotateZ")
                {
                    m_rotation.Z = angle;
                }
            }

            Matrix4F M    = new Matrix4F();
            Matrix4F temp = new Matrix4F();

            temp.Scale(Scale);
            M.Mul(M, temp);

            if (m_rotation.X != 0)
            {
                temp.RotX(m_rotation.X);
                M.Mul(M, temp);
            }

            if (m_rotation.Y != 0)
            {
                temp.RotY(m_rotation.Y);
                M.Mul(M, temp);
            }

            if (m_rotation.Z != 0)
            {
                temp.RotZ(m_rotation.Z);
                M.Mul(M, temp);
            }

            temp.Set(Translation);
            M.Mul(M, temp);

            Transform     = M;
            m_boundingBox = new Cached <Box>(CalculateBoundingBox);
            Visible       = true;
        }
Example #57
0
        protected override Matrix4F GetManipulatorMatrix()
        {
            ITransformable node = GetManipulatorNode(TransformationTypes.Rotation);
            if (node == null ) return null;
            
            Path<DomNode> path = new Path<DomNode>(node.Cast<DomNode>().GetPath());
            Matrix4F localToWorld = TransformUtils.CalcPathTransform(path, path.Count - 1);

            // local transform
            Matrix4F toworld = new Matrix4F(localToWorld);

            // Offset by rotate pivot
            Matrix4F P = new Matrix4F();
            P.Translation = node.Pivot;
            toworld.Mul(P, toworld);

            // Normalize            
            toworld.Normalize(toworld);

            return toworld;
        }
Example #58
0
        public void Render(GUILayer.SimpleRenderingContext context, Camera cam)
        {
            GameEngine.SetRendererFlag(context, BasicRendererFlags.WireFrame);
            IGrid grid = this.As <IGrid>();

            if (grid.Visible == false)
            {
                return;
            }

            float s = grid.Size;

            Matrix4F scale = new Matrix4F();

            scale.Scale(new Vec3F(s, s, s));

            Matrix4F gridXform = new Matrix4F();

            if (cam.Frustum.IsOrtho)
            {
                float     dist = cam.ViewMatrix.Translation.Z;
                ViewTypes vt   = cam.ViewType;
                if (vt == ViewTypes.Top)
                {
                    gridXform.Translation
                        = new Vec3F(0, dist, 0);
                }
                else if (vt == ViewTypes.Bottom)
                {
                    gridXform.Translation
                        = new Vec3F(0, -dist, 0);
                }
                else if (vt == ViewTypes.Right)
                {
                    gridXform.RotZ(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(dist, 0, 0);
                }
                else if (vt == ViewTypes.Left)
                {
                    gridXform.RotZ(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(-dist, 0, 0);
                }
                else if (vt == ViewTypes.Front)
                {
                    gridXform.RotX(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(0, 0, dist);
                }
                else if (vt == ViewTypes.Back)
                {
                    gridXform.RotX(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(0, 0, -dist);
                }
                gridXform.Mul(scale, gridXform);
            }
            else
            {
                Matrix4F trans = new Matrix4F();
                trans.Translation = new Vec3F(0, grid.Height, 0);
                gridXform         = Matrix4F.Multiply(scale, trans);
            }

            GameEngine.DrawPrimitive(context, PrimitiveType.LineList, m_gridVBId, 0, m_gridVertexCount, Color.LightGray,
                                     Matrix4F.Multiply(gridXform, cam.AxisSystem));

            GameEngine.DrawPrimitive(context, PrimitiveType.LineList, m_basisAxesVBId, 0, m_basisAxesVertexCount, Color.White,
                                     gridXform);
        }
        /// <summary>
        /// Handles mouse-move events</summary>
        /// <param name="sender">Control that raised original event</param>
        /// <param name="e">Event args</param>
        /// <returns>true, if controller handled the event</returns>
        public override bool MouseMove(object sender, MouseEventArgs e)
        {
            if (m_dragging &&
                InputScheme.ActiveControlScheme.IsControllingCamera(Control.ModifierKeys, e))
            {
                float dx = (float)(e.X - m_lastMousePoint.X) / 150.0f;
                float dy = (float)(e.Y - m_lastMousePoint.Y) / 150.0f;

                if (InputScheme.ActiveControlScheme.IsElevating(Control.ModifierKeys, e))
                {
                    // move camera up/down
                    Vec3F p = Camera.Eye;
                    p.Y += (dy < 0) ? m_scale : -m_scale;
                    Camera.Set(p);
                }
                else if (InputScheme.ActiveControlScheme.IsTurning(Control.ModifierKeys, e))
                {
                    // pitch and yaw camera
                    Matrix4F mat = Matrix4F.RotAxisRH(Camera.Right, -dy); // pitch along camera right
                    Matrix4F yaw = new Matrix4F();
                    yaw.RotY(-dx);
                    mat.Mul(yaw, mat);

                    Vec3F lookAt = Camera.LookAt;
                    Vec3F up = Camera.Up;
                    mat.Transform(ref lookAt);
                    mat.Transform(ref up);

                    Vec3F position = Camera.Eye;
                    float d = Camera.DistanceFromLookAt;
                    Camera.Set(position, position + lookAt * d, up);
                }

                m_lastMousePoint = e.Location;

                return true;
            }

            return base.MouseMove(sender, e);
        }
Example #60
0
 public Manipulator()
 {
     NodeList   = new List <ITransformable>();
     HitMatrix  = new Matrix4F();
     DesignView = null;
 }