예제 #1
0
        public void Draw(Drawable window, Context ctx, Rectangle bounds, StateType state)
        {
            if (gradient == null)
            {
                return;
            }

            int outerBoundsThickness = 4;

            var area                    = AreaFromBounds(new RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height));
            var outerBounds             = area.Inflated(outerBoundsThickness);
            var colorBorder             = new Color(204, 204, 204, 255);
            var colorSelectedBackground = new Color(154, 154, 154, 255);
            var colorEntry              = Color.Black;

            ctx.Save();

            ctx.Rectangle(outerBounds.X, outerBounds.Y, outerBounds.Width, outerBounds.Height);
            ctx.Clip();

            // Border
            WidgetTools.SetColor(ctx, state == StateType.Selected ? colorSelectedBackground : colorBorder);
            //SetColor(ctx, colorBorder);
            ctx.LineWidth = 1.0;
            ctx.Antialias = Antialias.Default;
            ctx.Rectangle(outerBounds.X, outerBounds.Y, outerBounds.Width, outerBounds.Height);
            ctx.Stroke();

            // Clip inner area
            ctx.Rectangle(outerBounds.X + 1, outerBounds.Y + 1, outerBounds.Width - 2, outerBounds.Height - 2);
            ctx.Clip();

            // Background
            DrawBackground(ctx, outerBounds);

            // Gradient
            if (gradient.Count > 0 && area.Width > 0)
            {
                int numSteps = (int)outerBounds.Width;

                // Could be done much cheaper with cairo gradients, but this way we'll show the actual values
                for (int i = 0; numSteps > 0 && i < numSteps; i++)
                {
                    var fraction = (i - outerBoundsThickness) / area.Width;
                    fraction = MathTools.ClampNormal(fraction);

                    WidgetTools.SetColor(ctx, gradient.Evaluate(fraction));

                    float x = outerBounds.Position.X + i;
                    float y = outerBounds.Position.Y;
                    ctx.MoveTo(x, y);
                    ctx.LineTo(x, y + outerBounds.Height);
                    ctx.Antialias = Antialias.None;
                    ctx.Stroke();
                }
            }

            // Entries
            foreach (var entry in gradient)
            {
                var slice = GetEntryArea(entry.Position, area);

                ctx.Antialias = Antialias.None;

                ctx.Rectangle(slice.X, slice.Y, slice.Width, slice.Height);
                WidgetTools.SetColor(ctx, entry.Color);
                ctx.Fill();

                Color edgeColor = entry == hoveredEntry?GetComplementary1(entry.Color) : GetComplementary2(entry.Color);

                ctx.Rectangle(slice.X, slice.Y, slice.Width, slice.Height);
                ctx.LineWidth = 1;
                WidgetTools.SetColor(ctx, edgeColor);
                ctx.Stroke();

                if (entry == selectedEntry)
                {
                    ctx.Rectangle(slice.X + 1, slice.Y + 1, slice.Width - 2, slice.Height - 2);
                    ctx.LineWidth = 1;
                    WidgetTools.SetColor(ctx, edgeColor);
                    ctx.Stroke();
                }
            }

            ctx.Restore();
        }
예제 #2
0
 /// <summary>
 /// 将逻辑长度转换到屏幕长度
 /// </summary>
 /// <param name="logicLength"></param>
 /// <returns></returns>
 public int ScrnLength(float logicLength)
 {
     return(MathTools.Round(logicLength * scale));
 }
예제 #3
0
        public int[] findColorWithin(Color col, Rectangle rect, int tolerance = 0, int limit = 1, int step = 1)
        {
            // If the limit is less or equal to zero, there's nothing to do really
            if (limit <= 0)
            {
                return(new int[0]);
            }

            int byteStep = step * bytesPerPixel;

            // Create field for the matches of the maximum possible size
            int[] matches      = new int[limit];
            int   matchesFound = 0;

            int[] colBGR = { col.B, col.G, col.R };

            // Get the pixel offsets
            int byteLeft   = rect.Left * bytesPerPixel;
            int byteRight  = rect.Right * bytesPerPixel;
            int byteTop    = rect.Top * Stride;
            int byteBottom = rect.Bottom * Stride;

            // Both x and y are indexes in bytes
            for (int yLB = byteTop;
                 yLB < byteBottom;
                 yLB += Stride)
            {
                for (int xLB = byteLeft;
                     xLB < byteRight;
                     xLB += byteStep)
                {
                    bool isMatch = true;

                    // If all the pixel colors match, save the current point
                    for (int j = 0; j < bytesPerPixel && isMatch; j++)
                    {
                        if (xLB + yLB < Bytes.Length)
                        {
                            isMatch = MathTools.Compare(Bytes[xLB + yLB + j], colBGR[j], tolerance);
                        }
                        else
                        {
                            isMatch = false;
                        }
                    }

                    if (isMatch)
                    {
                        // Save the found match
                        matches[matchesFound] = xLB + yLB;
                        matchesFound++;

                        // If there are enough matches found already, break the loop and return found matches
                        if (matchesFound >= limit)
                        {
                            return(matches);
                        }
                    }
                }
            }

            // If there are less matches found than the limit, get rid of the empty ints and return the actual matches
            int[] foundMatches = new int[matchesFound];
            for (int i = 0; i < matchesFound; i++)
            {
                foundMatches[i] = matches[i];
            }

            return(foundMatches);
        }
예제 #4
0
 static StudentTNu1()
 {
     DIVIDEND = MathTools.Gamma((NU + 1.0f) * 0.5f);
     DIVISOR  = MathF.Sqrt(NU * MathF.PI) * MathTools.Gamma(NU * 0.5f);
     EXPONENT = -((NU + 1.0f) * 0.5f);
 }
예제 #5
0
    private void GetPositionBasedOnHitSides(int _topHit, int _bottomHit, Vector3 _entityPosition, ref Vector2 v4, ref Vector2 v5)
    {
        Vector3 entityPlanarOffset  = Vector3.ProjectOnPlane(_entityPosition - ptlController.transform.position, ptlController.transform.up);
        Vector2 entityRoundedOffset = MathTools.RoundVector3(entityPlanarOffset, 4);

        int bothHit = _topHit + _bottomHit;

        switch (bothHit)
        {
        // 1  == (Impossible) Only one intersection
        // 2  == Both Top (Already set to top/bottom intersection position)
        case 3:                                 // 3  == One Top One Left
            v4 = v5 = cornerLT;
            break;

        // 4  == Both Left (Already set to top/bottom intersection position)
        case 5:                                               // 5  == One Top One Bottom
            if (entityRoundedOffset.x < 0)
            {                                                 //If player is left of the portal
                v5 = (_topHit == 1) ? cornerRT : cornerRB;    //Is top    hitting Screen Top?
                v4 = (_bottomHit == 4) ? cornerRB : cornerRT; //Is bottom hitting Screen Bottom?
            }
            else
            {                                                 //If player is right of the portal
                v5 = (_topHit == 1) ? cornerLT : cornerLB;    //Is top    hitting Screen Top?
                v4 = (_bottomHit == 4) ? cornerLB : cornerLT; //Is bottom hitting Screen Bottom?
            }
            break;

        case 6:                                 // 6  == One Left One Bottom
            v4 = v5 = cornerLB;
            break;

        // 7  == (Impossible) Three intersections
        // 8  == Both Bottom (Already set to top/bottom intersection position)
        case 9:                                 // 9  == One Top One Right
            v4 = v5 = cornerRT;
            break;

        case 10:                                              // 10 == One Left One Right
            if (entityRoundedOffset.y < 0)
            {                                                 //If player is below the portal
                v5 = (_topHit == 2) ? cornerLT : cornerRT;    //Is top    hitting Screen Left?
                v4 = (_bottomHit == 8) ? cornerRT : cornerLT; //Is bottom hitting Screen Right?
            }
            else
            {                                                 //If player is above the portal
                v5 = (_topHit == 2) ? cornerLB : cornerRB;    //Is top    hitting Screen Left?
                v4 = (_bottomHit == 8) ? cornerRB : cornerLB; //Is bottom hitting Screen Right?
            }
            break;

        // 11 == (Impossible) Three intersections
        case 12:                                // 12 == One Right One Bottom
            v4 = v5 = cornerRB;
            break;

        // 13 == (Impossible) Three intersections
        // 14 == (Impossible) Three intersections
        // 15 == (Impossible) Four  intersections
        // 16 == Both right (Already set to top/bottom intersection position)
        default:
            if (bothHit != 16 && bothHit != 8 && bothHit != 4 && bothHit != 2)     //If not both hitting same side
            {
                Debug.LogError("BothHit Value not handled! -- " + bothHit);
            }
            break;
        }
    }
        public void TestOfRadianToDegree()
        {
            float radiantsToTest = 3;

            Assert.AreEqual(171.8873, MathTools.RadianToDegree(radiantsToTest), 0.1);
        }
예제 #7
0
파일: WarShip.cs 프로젝트: ingex0/smarttank
        private void HandlerControl(float seconds)
        {
            if (!isDead && openControl)
            {
                float maxSpeed = SpaceWarConfig.SpeedMax;
                float accel    = SpaceWarConfig.SpeedAccel;
                if (stillTimer < 0)
                {
                    // 硬直状态
                    // maxSpeed *= cStillSpeedScale;
                    accel *= SpaceWarConfig.StillSpeedScale;
                }

                #region  获取键盘输入

                bool Up    = InputHandler.IsKeyDown(Keys.W);
                bool Left  = InputHandler.IsKeyDown(Keys.A);
                bool Down  = InputHandler.IsKeyDown(Keys.S);
                bool Right = InputHandler.IsKeyDown(Keys.D);

                Vector2 deltaSpeed = new Vector2();
                bool    noInput    = false;

                // 左上
                if (Up && Left && !Right && !Down)
                {
                    deltaSpeed.X = -cRootTwoDivideTwo;
                    deltaSpeed.Y = -cRootTwoDivideTwo;
                }
                // 右上
                else if (Up && Right && !Left && !Down)
                {
                    deltaSpeed.X = cRootTwoDivideTwo;
                    deltaSpeed.Y = -cRootTwoDivideTwo;
                }
                // 右下
                else if (Down && Right && !Up && !Left)
                {
                    deltaSpeed.X = cRootTwoDivideTwo;
                    deltaSpeed.Y = cRootTwoDivideTwo;
                }
                // 左下
                else if (Down && Left && !Up && !Right)
                {
                    deltaSpeed.X = -cRootTwoDivideTwo;
                    deltaSpeed.Y = cRootTwoDivideTwo;
                }
                // 上
                else if (Up && !Down)
                {
                    deltaSpeed.X = 0;
                    deltaSpeed.Y = -1.0f;
                }
                // 下
                else if (Down && !Up)
                {
                    deltaSpeed.X = 0;
                    deltaSpeed.Y = 1.0f;
                }
                // 左
                else if (Left && !Right)
                {
                    deltaSpeed.X = -1.0f;
                    deltaSpeed.Y = 0;
                }
                // 右
                else if (Right && !Left)
                {
                    deltaSpeed.X = 1.0f;
                    deltaSpeed.Y = 0;
                }
                else
                {
                    noInput = true;
                }

                #endregion

                #region 获得鼠标状态

                if (InputHandler.LastMouseLeftDown)
                {
                    Vector2 mousePos = InputHandler.GetCurMousePosInLogic(BaseGame.RenderEngine);
                    float   shootAzi = MathTools.AziFromRefPos(mousePos - this.Pos);

                    this.Shoot(shootAzi);
                }

                #endregion


                if (!noInput)
                {
                    phisicalUpdater.Azi = MathTools.AziFromRefPos(Vel);
                    deltaSpeed         *= seconds * accel;
                    Vel += deltaSpeed;
                    float SpeedAbs = Vel.Length();
                    if (SpeedAbs > maxSpeed)
                    {
                        Vel *= maxSpeed / SpeedAbs;
                    }
                }
                else // 衰减
                {
                    // 假设时间间隔是均匀的,并且间隔很小。
                    if (SpaceWarConfig.SpeedDecay * seconds < 1)
                    {
                        Vel *= (1 - SpaceWarConfig.SpeedDecay * seconds);
                    }
                }
                phisicalUpdater.Vel = Vel;
            }
        }
예제 #8
0
        public void Init(string platformPath, string folder64Bit, string folder32Bit)
        {
            // pre-load native libs
            string libFolderBit;

            if (IntPtr.Size == 8)
            {
                libFolderBit = folder64Bit;
            }
            else if (IntPtr.Size == 4)
            {
                libFolderBit = folder32Bit;
            }
            else
            {
                throw new NotSupportedException("Unsupported bit size: " + IntPtr.Size.ToString());
            }

                        #if RELEASE
            const string config = "Release";
                        #else
            const string config = "Debug";
                        #endif

            // load api abstraction (api-instance and hardware-device)
            var abstractionDesc = new AbstractionDesc(AbstractionInitType.MultiGPU_BestAvaliable_AFR);
            abstractionDesc.supportedAPIs = new AbstractionAPI[] { AbstractionAPI.D3D12 };

            abstractionDesc.deviceDescD3D12.window = window;
            //abstractionDesc.deviceDescD3D12.adapterIndex = 1;
            //abstractionDesc.deviceDescD3D12.vSyncMode = SwapChainVSyncMode.VSyncOff;
                        #if DEBUG
            abstractionDesc.nativeLibPathD3D12 = Path.Combine(platformPath, @"Shared\Orbital.Video.D3D12.Native\bin", libFolderBit, config);
                        #else
            abstractionDesc.nativeLibPathD3D12 = string.Empty;
                        #endif

            abstractionDesc.deviceDescVulkan.window = window;
                        #if DEBUG
            abstractionDesc.nativeLibPathVulkan = Path.Combine(platformPath, @"Shared\Orbital.Video.Vulkan.Native\bin", libFolderBit, config);
                        #else
            abstractionDesc.nativeLibPathVulkan = string.Empty;
                        #endif

            if (!Abstraction.InitFirstAvaliable(abstractionDesc, out instance, out device))
            {
                throw new Exception("Failed to init abstraction");
            }

            // create render texture test objects
            renderTextureTest = new RenderTextureTest(device);

            // create msaa render texture
            if (!device.GetMaxMSAALevel(TextureFormat.Default, out var msaaLevel))
            {
                throw new Exception("Failed to get MSAA level");
            }
            var windowSize = window.GetSize(WindowSizeType.WorkingArea);
            renderTextureMSAA = device.CreateRenderTexture2D(windowSize.width, windowSize.height, TextureFormat.Default, RenderTextureUsage.Discard, TextureMode.GPUOptimized, StencilUsage.Discard, DepthStencilFormat.DefaultDepth, DepthStencilMode.GPUOptimized, msaaLevel, false, MultiGPUNodeResourceVisibility.All);

            // create command list
            commandList         = device.CreateRasterizeCommandList();
            commandList_Compute = device.CreateComputeCommandList();

            // create render pass
            var renderPassDesc = RenderPassDesc.CreateDefault(new Color4F(0, .2f, .4f, 1), 1);
            //renderPass = device.CreateRenderPass(renderPassDesc, device.swapChain.depthStencil);
            renderPass = renderTextureMSAA.CreateRenderPass(renderPassDesc, renderTextureMSAA.GetDepthStencil());

            // create texture
            int textureWidth = 256, textureHeight = 256;
            var textureData = new byte[textureWidth * textureHeight * 4];
            for (int y = 0; y != textureHeight; ++y)
            {
                for (int x = 0; x != textureWidth; ++x)
                {
                    int i = (x * 4) + (y * textureWidth * 4);
                    if (x % 16 <= 7 && y % 16 <= 7)
                    {
                        textureData[i + 0] = 0;
                        textureData[i + 1] = 0;
                        textureData[i + 2] = 0;
                        textureData[i + 3] = 0;
                    }
                    else
                    {
                        textureData[i + 0] = 255;
                        textureData[i + 1] = 255;
                        textureData[i + 2] = 255;
                        textureData[i + 3] = 255;
                    }
                }
            }
            texture = device.CreateTexture2D(textureWidth, textureHeight, TextureFormat.R8G8B8A8, textureData, TextureMode.GPUOptimized, MultiGPUNodeResourceVisibility.Self);

            // create texture 2
            textureWidth  = 100;
            textureHeight = 100;
            textureData   = new byte[textureWidth * textureHeight * 4];
            for (int y = 0; y != textureHeight; ++y)
            {
                for (int x = 0; x != textureWidth; ++x)
                {
                    int i = (x * 4) + (y * textureWidth * 4);
                    if (x % 16 <= 7 && y % 16 <= 7)
                    {
                        textureData[i + 0] = 0;
                        textureData[i + 1] = 0;
                        textureData[i + 2] = 0;
                        textureData[i + 3] = 0;
                    }
                    else
                    {
                        textureData[i + 0] = 255;
                        textureData[i + 1] = 255;
                        textureData[i + 2] = 255;
                        textureData[i + 3] = 255;
                    }
                }
            }
            texture2 = device.CreateTexture2D(textureWidth, textureHeight, TextureFormat.R8G8B8A8, textureData, TextureMode.GPUOptimized, MultiGPUNodeResourceVisibility.Self);

            // load shaders
            // TODO: load CS2X compiled ShaderEffect

            /*using (var stream = new FileStream("Shader.se", FileMode.Open, FileAccess.Read, FileShare.Read))
             * {
             *      shaderEffect = device.CreateShaderEffect(stream, ShaderEffectSamplerAnisotropy.Default);
             * }*/

            using (var vsStream = new FileStream("Shaders\\Shader_D3D12.vs", FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var psStream = new FileStream("Shaders\\Shader_D3D12.ps", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var vs = new Video.D3D12.Shader((Video.D3D12.Device)device, ShaderType.VS);
                    var ps = new Video.D3D12.Shader((Video.D3D12.Device)device, ShaderType.PS);
                    if (!vs.Init(vsStream))
                    {
                        throw new Exception("Failed to init VS shader");
                    }
                    if (!ps.Init(psStream))
                    {
                        throw new Exception("Failed to init PS shader");
                    }
                    var desc = new ShaderEffectDesc();
                    desc.constantBuffers    = new ShaderEffectConstantBuffer[1];
                    desc.constantBuffers[0] = new ShaderEffectConstantBuffer()
                    {
                        registerIndex = 0,
                        usage         = ShaderEffectResourceUsage.VS,
                        variables     = new ShaderVariable[2]
                    };
                    desc.constantBuffers[0].variables[0] = new ShaderVariable()
                    {
                        name = "constrast",
                        type = ShaderVariableType.Float
                    };
                    desc.constantBuffers[0].variables[1] = new ShaderVariable()
                    {
                        name = "camera",
                        type = ShaderVariableType.Float4x4
                    };
                    desc.textures    = new ShaderEffectTexture[3];
                    desc.textures[0] = new ShaderEffectTexture()
                    {
                        registerIndex = 0,
                        usage         = ShaderEffectResourceUsage.PS
                    };
                    desc.textures[1] = new ShaderEffectTexture()
                    {
                        registerIndex = 1,
                        usage         = ShaderEffectResourceUsage.PS
                    };
                    desc.textures[2] = new ShaderEffectTexture()
                    {
                        registerIndex = 2,
                        usage         = ShaderEffectResourceUsage.PS
                    };
                    desc.samplers    = new ShaderEffectSampler[1];
                    desc.samplers[0] = new ShaderEffectSampler()
                    {
                        registerIndex = 0,
                        filter        = ShaderSamplerFilter.Default,
                        anisotropy    = ShaderSamplerAnisotropy.Default,
                        addressU      = ShaderSamplerAddress.Wrap,
                        addressV      = ShaderSamplerAddress.Wrap,
                        addressW      = ShaderSamplerAddress.Wrap,
                        usage         = ShaderEffectResourceUsage.PS
                    };
                    shaderEffect = device.CreateShaderEffect(vs, ps, null, null, null, desc, true);
                }

            if (!shaderEffect.FindVariable("constrast", out shaderEffectVar_Constrast))
            {
                throw new Exception("Failed to find shader effect variable");
            }
            if (!shaderEffect.FindVariable("camera", out shaderEffectVar_Camera))
            {
                throw new Exception("Failed to find shader effect variable");
            }

            // create constant buffer
            constantBuffer = device.CreateConstantBuffer(shaderEffect.constantBufferMappings[0].size, ConstantBufferMode.Write);

            // create vertex buffer
            const float size            = 1 / 2f;
            var         rotUpAxisMat    = Mat3.FromEuler(0, MathTools.DegToRad(90), 0);
            var         rotRightAxisMat = Mat3.FromEuler(MathTools.DegToRad(90), 0, 0);
            var         vertices        = new Vertex[4 * 6]; // 4 vertices per face
            var         indices         = new ushort[6 * 6]; // 6 indices per face
            var         colorKey        = new Color4[4]
            {
                Color4.blue,
                Color4.red,
                Color4.white,
                Color4.white
            };
            for (int v = 0, i = 0, r = 0; v < (4 * 4); v += 4, i += 6, ++r)            // caluclate front, right, back, left faces
            {
                vertices[v + 0] = new Vertex(new Vec3(-size, -size, size), colorKey[r], new Vec2(0, 0)).Transform(rotUpAxisMat, r);
                vertices[v + 1] = new Vertex(new Vec3(-size, size, size), colorKey[r], new Vec2(0, 1)).Transform(rotUpAxisMat, r);
                vertices[v + 2] = new Vertex(new Vec3(size, size, size), colorKey[r], new Vec2(1, 1)).Transform(rotUpAxisMat, r);
                vertices[v + 3] = new Vertex(new Vec3(size, -size, size), colorKey[r], new Vec2(1, 0)).Transform(rotUpAxisMat, r);
                indices[i + 0]  = (ushort)(v + 0);
                indices[i + 1]  = (ushort)(v + 1);
                indices[i + 2]  = (ushort)(v + 2);
                indices[i + 3]  = (ushort)(v + 0);
                indices[i + 4]  = (ushort)(v + 2);
                indices[i + 5]  = (ushort)(v + 3);
            }
            colorKey = new Color4[2]
            {
                Color4.green,
                Color4.white
            };
            for (int v = (4 * 4), i = (6 * 4), r = 1; v < (4 * 6); v += 4, i += 6, r = 3)            // caluclate top, bottom faces
            {
                vertices[v + 0] = new Vertex(new Vec3(-size, -size, size), colorKey[r / 3], new Vec2(0, 0)).Transform(rotRightAxisMat, r);
                vertices[v + 1] = new Vertex(new Vec3(-size, size, size), colorKey[r / 3], new Vec2(0, 1)).Transform(rotRightAxisMat, r);
                vertices[v + 2] = new Vertex(new Vec3(size, size, size), colorKey[r / 3], new Vec2(1, 1)).Transform(rotRightAxisMat, r);
                vertices[v + 3] = new Vertex(new Vec3(size, -size, size), colorKey[r / 3], new Vec2(1, 0)).Transform(rotRightAxisMat, r);
                indices[i + 0]  = (ushort)(v + 0);
                indices[i + 1]  = (ushort)(v + 1);
                indices[i + 2]  = (ushort)(v + 2);
                indices[i + 3]  = (ushort)(v + 0);
                indices[i + 4]  = (ushort)(v + 2);
                indices[i + 5]  = (ushort)(v + 3);
            }
            vertexBuffer = device.CreateVertexBuffer <Vertex>(vertices, indices, VertexBufferMode.GPUOptimized);

            // create vertex buffer streamer
            var vertexBufferStreamLayout = new VertexBufferStreamLayout()
            {
                descs    = new VertexBufferStreamDesc[1],
                elements = new VertexBufferStreamElement[3]
            };
            vertexBufferStreamLayout.descs[0] = new VertexBufferStreamDesc()
            {
                vertexBuffer = vertexBuffer,
                type         = VertexBufferStreamType.VertexData
            };
            vertexBufferStreamLayout.elements[0] = new VertexBufferStreamElement()
            {
                type   = VertexBufferStreamElementType.Float3,
                usage  = VertexBufferStreamElementUsage.Position,
                offset = 0
            };
            vertexBufferStreamLayout.elements[1] = new VertexBufferStreamElement()
            {
                type   = VertexBufferStreamElementType.RGBAx8,
                usage  = VertexBufferStreamElementUsage.Color,
                offset = (sizeof(float) * 3)
            };
            vertexBufferStreamLayout.elements[2] = new VertexBufferStreamElement()
            {
                type   = VertexBufferStreamElementType.Float2,
                usage  = VertexBufferStreamElementUsage.UV,
                offset = (sizeof(float) * 3) + 4
            };
            vertexBufferStreamer = device.CreateVertexBufferStreamer(vertexBufferStreamLayout);

            // create render state
            var renderStateDesc = new RenderStateDesc()
            {
                renderPass           = renderPass,
                shaderEffect         = shaderEffect,
                constantBuffers      = new ConstantBufferBase[1],
                textures             = new TextureBase[3],
                vertexBufferTopology = VertexBufferTopology.Triangle,
                vertexBufferStreamer = vertexBufferStreamer,
                triangleCulling      = TriangleCulling.Back,
                triangleFillMode     = TriangleFillMode.Solid,
                depthStencilDesc     = DepthStencilDesc.StandardDepthTesting()
            };
            //renderStateDesc.blendDesc.renderTargetBlendDescs = new RenderTargetBlendDesc[1] {RenderTargetBlendDesc.AlphaBlending()};
            renderStateDesc.constantBuffers[0] = constantBuffer;
            renderStateDesc.textures[0]        = texture;
            renderStateDesc.textures[1]        = texture2;
            renderStateDesc.textures[2]        = renderTextureTest.renderTexture;
            renderState = device.CreateRenderState(renderStateDesc);

            // create compute shader
            using (var csStream = new FileStream("Shaders\\Compute_D3D12.cs", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var csDesc = new ComputeShaderDesc()
                {
                    randomAccessBuffers = new ComputeShaderRandomAccessBuffer[1]
                };
                csDesc.randomAccessBuffers[0] = new ComputeShaderRandomAccessBuffer()
                {
                    registerIndex = 0
                };
                computeShader = device.CreateComputeShader(csStream, csDesc);
            }

            // create compute state
            var computeStateDesc = new ComputeStateDesc()
            {
                computeShader       = computeShader,
                randomAccessBuffers = new object[1]
            };
            computeStateDesc.randomAccessBuffers[0] = renderTextureTest.renderTexture;
            computeState = device.CreateComputeState(computeStateDesc);

            // print all GPUs this abstraction supports
            if (!instance.QuerySupportedAdapters(false, out var adapters))
            {
                throw new Exception("Failed: QuerySupportedAdapters");
            }
            foreach (var adapter in adapters)
            {
                Debug.WriteLine(adapter.name);
            }

            // setup camera
            camera = new Camera();
        }
예제 #9
0
        public static string ToSI(double value, int sigFigs)
        {
            if (value == 0)
            {
                return("0.0");
            }

            if (double.IsNaN(value))
            {
                return("NaN");
            }

            if (double.IsInfinity(value))
            {
                if (double.IsNegativeInfinity(value))
                {
                    return("-∞");
                }
                else
                {
                    return("∞");
                }
            }

            string format;

            double absValue = Math.Abs(value);

            int magnitude = (int)Math.Log10(absValue);
            int significance;
            int divisorExp;
            int decimalPlaces;

            string prefix = string.Empty;

            if (magnitude < 0 || absValue < 1)
            {
                decimalPlaces = 1;

                significance = 1;
            }
            else
            {
                decimalPlaces = 0;

                significance = (sigFigs / 3) * 3;
            }

            if (Math.Abs(magnitude) >= significance)
            {
                divisorExp = magnitude - significance;
            }
            else
            {
                divisorExp = 0;
            }

            switch (divisorExp)
            {
            case 0:
                break;

            case 1:
            case 2:
            case 3:
                value     /= 1e3;
                magnitude -= 3;
                prefix     = "k";
                break;

            case 4:
            case 5:
            case 6:
                value     /= 1e6;
                magnitude -= 6;
                prefix     = "M";
                break;

            case 7:
            case 8:
            case 9:
                value     /= 1e9;
                magnitude -= 9;
                prefix     = "G";
                break;

            case 10:
            case 11:
            case 12:
                value     /= 1e12;
                magnitude -= 12;
                prefix     = "T";
                break;

            case 13:
            case 14:
            case 15:
                value     /= 1e15;
                magnitude -= 15;
                prefix     = "P";
                break;

            case 16:
            case 17:
            case 18:
                value     /= 1e18;
                magnitude -= 18;
                prefix     = "E";
                break;

            case 19:
            case 20:
            case 21:
                value     /= 1e21;
                magnitude -= 21;
                prefix     = "Z";
                break;

            case 22:
            case 23:
            case 24:
                value     /= 1e24;
                magnitude -= 24;
                prefix     = "Y";
                break;

            case -1:
            case -2:
            case -3:
                value     *= 1e3;
                magnitude += 3;
                prefix     = "m";
                break;

            case -4:
            case -5:
            case -6:
                value     *= 1e6;
                magnitude += 6;
                prefix     = "µ";
                break;

            case -7:
            case -8:
            case -9:
                value     *= 1e9;
                magnitude += 9;
                prefix     = "n";
                break;

            case -10:
            case -11:
            case -12:
                value     *= 1e12;
                magnitude += 12;
                prefix     = "p";
                break;

            case -13:
            case -14:
            case -15:
                value     *= 1e15;
                magnitude += 15;
                prefix     = "f";
                break;

            case -16:
            case -17:
            case -18:
                value     *= 1e18;
                magnitude += 18;
                prefix     = "a";
                break;

            case -19:
            case -20:
            case -21:
                value     *= 1e21;
                magnitude += 21;
                prefix     = "z";
                break;

            case -22:
            case -23:
            case -24:
                value     *= 1e24;
                magnitude += 24;
                prefix     = "y";
                break;

            default:
                if (divisorExp > 0)
                {
                    value     /= 1e24;
                    magnitude -= 24;
                    prefix     = "Y";
                }
                else
                {
                    value     *= 1e24;
                    magnitude += 24;
                    prefix     = "y";
                }

                format = string.Format("{{0:g{0}}}{1}", sigFigs < 5 ? 2 : sigFigs - 3, prefix);

                return(string.Format(format, value, prefix));
            }

            decimalPlaces += sigFigs - magnitude - 1;

            if (decimalPlaces < 0)
            {
                double divisor = MathTools.Pow(10d, -decimalPlaces);
                value         = ((int)value / divisor) * divisor;
                decimalPlaces = 0;
            }

            format = string.Format("{{0:f{0}}}{1}", decimalPlaces, prefix);

            return(string.Format(format, value, prefix));
        }
예제 #10
0
        public void CalculateDegradingPestInSoil()
        {
            try
            {
                double halflifesoil_adjusted  = 0;
                double universalgasconstant   = 8.314472;
                double ref_airtempsoil_kelvin = InputModel.RefTempHalfLifeSoil + 273.15;
                double airtemp_kelvin         = ((Engine.ClimateModule.MaxTemp + Engine.ClimateModule.MinTemp) / 2.0) + 273.15;
                if (!MathTools.DoublesAreEqual(airtemp_kelvin, 0) && !MathTools.DoublesAreEqual(ref_airtempsoil_kelvin, 0))
                {
                    halflifesoil_adjusted = InputModel.HalfLifeSoil * Math.Exp((InputModel.DegradationActivationEnergy / universalgasconstant) * (1.0 / airtemp_kelvin - 1.0 / ref_airtempsoil_kelvin));
                }
                else
                {
                    MathTools.LogDivideByZeroError("CalculateDegradingPestInSoil", "AirTemperature_kelvin or Ref_AirTemperatureSoil_kelvin", "HalfLifeSoil_adjusted");
                }
                double denom;
                double soildegrate;
                if (halflifesoil_adjusted > 0)
                {
                    soildegrate = Math.Exp(-0.693 / halflifesoil_adjusted);
                }
                else
                {
                    soildegrate = 0;
                    MathTools.LogDivideByZeroError("CalculateDegradingPestInSoil", "HalfLifeSoil_adjusted", "soildegrate");
                }

                PestInSoil = PestInSoil * soildegrate + AppliedPestOnSoil - PestLostInLeaching - TotalPestLostInRunoff;
                if (Engine.ClimateModule.Rain >= 5.0)
                {
                    PestInSoil = PestInSoil + (PestOnStubble + PestOnVeg) * InputModel.CoverWashoffFraction;
                }


                denom = (Engine.SoilModule.InputModel.BulkDensity[0] * InputModel.MixLayerThickness * 10);
                if (!MathTools.DoublesAreEqual(denom, 0))
                {
                    PestSoilConc = PestInSoil / denom;
                }
                else
                {
                    PestSoilConc = 0;
                    MathTools.LogDivideByZeroError("CalculateDegradingPestInSoil", "sim.in_BulkDensity_g_per_cm3[0]*in_MixLayerThickness_mm*10", "out_PestSoilConc_mg_per_kg");
                }


                double porosity = 1 - Engine.SoilModule.InputModel.BulkDensity[0] / 2.65;

                //calculate the denominator of the PestConcInSoilAfterLeaching Equation - need to test for denom=0
                denom = InputModel.MixLayerThickness * (InputModel.SorptionCoefficient * Engine.SoilModule.InputModel.BulkDensity[0] + porosity);

                double availwaterstorageinmixing;
                if (!MathTools.DoublesAreEqual(Engine.SoilModule.Depth[1], 0))
                {
                    availwaterstorageinmixing = (Engine.SoilModule.DrainUpperLimitRelWP[0] - Engine.SoilModule.SoilWaterRelWP[0]) * InputModel.MixLayerThickness / Engine.SoilModule.Depth[1];
                }
                else
                {
                    availwaterstorageinmixing = 0;
                    MathTools.LogDivideByZeroError("CalculateDegradingPestInSoil", "sim.depth[1]", "availwaterstorageinmixing");
                }
                if (!MathTools.DoublesAreEqual(denom, 0))
                {
                    double infiltration = Engine.ClimateModule.Rain - Engine.SoilModule.Runoff - availwaterstorageinmixing;
                    if (infiltration < 0)
                    {
                        infiltration = 0;
                    }
                    ConcSoilAfterLeach = PestSoilConc * Math.Exp(-infiltration / (denom));
                }
                else
                {
                    ConcSoilAfterLeach = 0;
                    MathTools.LogDivideByZeroError("CalculateDegradingPestInSoil", "sim.in_BulkDensity_g_per_cm3[0]*in_MixLayerThickness_mm*10", "conc_in_soil_after_leach_mg_per_kg");
                }
            }
            catch (Exception ex)
            {
                throw ErrorLogger.CreateException(ex);
            }
        }
예제 #11
0
 internal static bool IsOdd(int intValue)
 {
     return(!MathTools.IsEven(intValue));
 }
예제 #12
0
        public void ApplyAnyNewPesticides()
        {
            try
            {
                AppliedPestOnVeg     = 0;
                AppliedPestOnStubble = 0;
                AppliedPestOnSoil    = 0;

                ResetPesticideInputs();
                if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.FixedDate)
                {
                    if (Engine.TodaysDate.Day == InputModel.ApplicationDate.Day && Engine.TodaysDate.Month == InputModel.ApplicationDate.Month)
                    {
                        ProductRateApplied = InputModel.ProductRate;
                    }
                }
                else if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.FromSequenceFile)
                {
                    //int index = DateUtilities.isDateInSequenceList(Sim.Today, InputModel.PestApplicationTiming.PesticideDatesAndRates);
                    var item = InputModel.PestApplicationDateList.Dates.FirstOrDefault(x => x.DateInt == Engine.TodaysDate.DateInt);
                    if (item != null)
                    {
                        var index = InputModel.PestApplicationDateList.Dates.IndexOf(item);
                        ProductRateApplied = InputModel.PestApplicationDateList.Values[index];
                    }
                }
                else
                {
                    var crop = Engine.CurrentCrop;
                    if (crop != null)
                    {
                        if (crop.CropStatus != CropStatus.Fallow)
                        {
                            if (MathTools.DoublesAreEqual(crop.HeatUnitIndex, 0))
                            {
                                ApplicationIndex = 0;
                            }
                            if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.GDDCrop1 && crop == Engine.GetCrop(0))
                            {
                                CheckApplicationBasedOnGDD(crop);
                            }
                            else if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.GDDCrop2 && crop == Engine.GetCrop(1))
                            {
                                CheckApplicationBasedOnGDD(crop);
                            }
                            else if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.GDDCrop3 && crop == Engine.GetCrop(2))
                            {
                                CheckApplicationBasedOnGDD(crop);
                            }
                            else if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.DASCrop1 && crop == Engine.GetCrop(0))
                            {
                                CheckApplicationBasedOnDAS(crop);
                            }
                            else if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.DASCrop2 && crop == Engine.GetCrop(1))
                            {
                                CheckApplicationBasedOnDAS(crop);
                            }
                            else if (InputModel.ApplicationTiming == (int)EPestApplicationTiming.DASCrop3 && crop == Engine.GetCrop(2))
                            {
                                CheckApplicationBasedOnDAS(crop);
                            }
                        }
                        else if (crop.CropStatus == CropStatus.Fallow && InputModel.ApplicationTiming == (int)EPestApplicationTiming.DaysSinceFallow)
                        {
                            CheckApplicationBasedOnDAH();
                        }
                    }
                }
                if (ProductRateApplied > 0)
                {
                    ApplyPesticide();
                }
            }
            catch (Exception ex)
            {
                throw ErrorLogger.CreateException(ex);
            }
        }
예제 #13
0
파일: Server.cs 프로젝트: sm6uax/plegma
        //------------------------------------------------------------------------------------------------------------------------
        void HandleNewConnection(Socket newsocket)
        {
            try
            {
                #region check reconnection throttle
                try
                {
                    //setup socket
                    newsocket.ReceiveTimeout = -1;
                    newsocket.SendTimeout    = 60 * 1000;

#if NETFX
                    var re = newsocket.RemoteEndPoint.GetIPAddress().ToStringInvariant();
#elif UNIVERSAL
                    var re = newsocket.Information.RemoteAddress.ToStringInvariant();
#endif
                    //filtering
                    if (OnNewSocketConnectionFilter != null && OnNewSocketConnectionFilter(this, re) == false)
                    {
#if NETFX
                        try { newsocket.Close(); } catch { }
#endif
                        try { newsocket.Dispose(); } catch { }
                        DebugEx.TraceWarning("Connection from " + re + " closed from filter");
                        return;
                    }

                    if (IsReconnectionThrottleEnabled && re != "127.0.0.1" && re != "localhost") //no reconnection throttle for localhost connections
                    {
                        var rbe = reconnectThrottleBookKeeper.TryGetOrDefault(re);
                        if (rbe == null)
                        {
                            rbe = new ReconnectionBookkeepEntry()
                            {
                                ConnectionTimestamp = DateTime.Now + TimeSpan.FromMilliseconds(100),
                                Connections         = 1,
                            };
                            reconnectThrottleBookKeeper.ForceAdd(re, rbe);
                        }
                        else
                        {
                            if (++rbe.Connections > ReconnectionThrottleAfterConnectionCount)
                            {
                                var elapsed = DateTime.Now - rbe.ConnectionTimestamp;
                                if (elapsed < ReconnectionThrottleTimeout)
                                {
#if NETFX
                                    try { newsocket.Close(); } catch { }
#endif
                                    try { newsocket.Dispose(); } catch { }
                                    DebugEx.TraceWarning("Connection from " + re + " closed due to reconnection throttle (" + elapsed.Seconds + " sec)");
                                    return;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex) { DebugEx.TraceWarning(ex, "YPServer Reconnection throttle exception"); }

                //cleanup old entries
                reconnectThrottleBookKeeper.RemoveWhere(e => DateTime.Now - e.Value.ConnectionTimestamp > ReconnectionThrottleTimeout);
                #endregion

                //start task new connection
                Task.Run(() =>
                {
                    ServerChannel channel = null;
                    string channelKey     = null;

                    Thread.Sleep(MathTools.GetRandomNumber(1, 100));
                    try
                    {
                        //check
#if NETFX
                        if (!newsocket.Connected)
                        {
                            DebugEx.TraceWarning("YPServer newsocket not connected?");
                            try { newsocket.Close(); } catch { }
                            return;
                        }
#endif
                        //create channel
                        var con = ChannelConstructor;
                        channel = con == null ? new ServerChannel(this, Protocols, SupportedChannelSerializationModes, PreferredChannelSerializationModes, newsocket) : con(Protocols, newsocket);
                        if (channel == null)
                        {
                            DebugEx.Assert("Could not create channel");
#if NETFX
                            try { newsocket.Close(); } catch { }
#endif
                            try { newsocket.Dispose(); } catch { }
                            return;
                        }

                        //add to set
                        lock (_Channels)
                        {
                            //generate unique key
                            while (IssuedKeys.ContainsKey(channelKey = MathTools.GenerateRandomAlphaNumericString(64)))
                            {
                                ;
                            }
                            //set on channel
                            channel._ChannelKey = channelKey;
                            //add to lookups
                            _Channels.Add(channel);
                            IssuedKeys.Add(channelKey, channel);
                        }

                        //start task timeout monitor
                        bool setupFinished = false;
                        Task.Run(() =>
                        {
                            try
                            {
                                //wait
                                Thread.Sleep(30000);
                                //check
                                if (!setupFinished)
                                {
                                    DebugEx.TraceLog($"ServerChannel setup timeout ({channel})");
                                    try { channel.Close("ServerChannel setup timeout"); } catch { }
#if NETFX
                                    try { newsocket?.Close(); } catch { }
#endif
                                    try { newsocket?.Dispose(); } catch { }

                                    //remove from lookups
                                    lock (_Channels)
                                    {
                                        if (channel != null)
                                        {
                                            _Channels.Remove(channel);
                                        }
                                        if (channelKey != null)
                                        {
                                            IssuedKeys.Remove(channelKey);
                                        }
                                    }
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                DebugEx.Assert(ex, $"Unhandled exception ({channel})");
#if NETFX
                                try { newsocket?.Close(); } catch { }
#endif
                                try { newsocket?.Dispose(); } catch { }

                                //remove from lookups
                                lock (_Channels)
                                {
                                    if (channel != null)
                                    {
                                        _Channels.Remove(channel);
                                    }
                                    if (channelKey != null)
                                    {
                                        IssuedKeys.Remove(channelKey);
                                    }
                                }
                                return;
                            }
                        });

                        //set serializer
                        channel.MsgPack = MsgPackSerializer;

                        //setup channel socket
                        if (channel.SetupServerSocket() == false)
                        {
#if NETFX
                            try { newsocket?.Close(); } catch { }
#endif
                            try { newsocket?.Dispose(); } catch { }

                            //remove from lookups
                            lock (_Channels)
                            {
                                if (channel != null)
                                {
                                    _Channels.Remove(channel);
                                }
                                if (channelKey != null)
                                {
                                    IssuedKeys.Remove(channelKey);
                                }
                            }
                            return;
                        }

                        //mark setup finish
                        setupFinished = true;

                        //call event
                        OnNewChannel?.Invoke(this, channel);

                        //start heartbeat
                        channel.Start();
                    }
                    catch (Exception ex)
                    {
                        DebugEx.Assert(ex, "YPServer: Failed setting up new connection for " + channel);
#if NETFX
                        try { newsocket.Close(); } catch { }
#endif
                        try { newsocket.Dispose(); } catch { }

                        //remove from lookups
                        lock (_Channels)
                        {
                            if (channel != null)
                            {
                                _Channels.Remove(channel);
                            }
                            if (channelKey != null)
                            {
                                IssuedKeys.Remove(channelKey);
                            }
                        }
                        return;
                    }
                });
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex, "YPChannel server setup new connection error");
            }
        }
예제 #14
0
 private static double CalculateDistance(Word w1, Word w2)
 {
     return(MathTools.GetDistance(w1.BoundingRect.GetCentralPoint(), w2.BoundingRect.GetCentralPoint()));
 }
예제 #15
0
 // Called from  CalculateParticulateNInRunoff
 // extracts value directly from input time-series;
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public double GetTotalNStoreTopLayerkgPerha()
 {
     try
     {
         if (InputModel.ParticulateNinRunoff.index == 1)
         {
             double value1 = 0;
             double value2 = 0;
             double value3 = 0;
             if (InputModel.ParticulateNinRunoff.NitrateSourceData.InorganicNitrateNTimeseries.GetCount() != 0)
             {
                 value1 = InputModel.ParticulateNinRunoff.NitrateSourceData.InorganicNitrateNTimeseries.GetValueAtDate(Sim.Today);
             }
             if (InputModel.ParticulateNinRunoff.NitrateSourceData.InorganicAmmoniumNTimeseries.GetCount() != 0)
             {
                 value2 = InputModel.ParticulateNinRunoff.NitrateSourceData.InorganicAmmoniumNTimeseries.GetValueAtDate(Sim.Today);
             }
             if (InputModel.ParticulateNinRunoff.NitrateSourceData.OrganicNTimeseries.GetCount() != 0)
             {
                 value3 = InputModel.ParticulateNinRunoff.NitrateSourceData.OrganicNTimeseries.GetValueAtDate(Sim.Today);
             }
             if (MathTools.DoublesAreEqual(value1, MathTools.MISSING_DATA_VALUE) || MathTools.DoublesAreEqual(value2, MathTools.MISSING_DATA_VALUE) || MathTools.DoublesAreEqual(value3, MathTools.MISSING_DATA_VALUE))
             {
                 return(MathTools.MISSING_DATA_VALUE);
             }
             return(value1 + value1 + value3);
         }
         else if (InputModel.ParticulateNinRunoff.index == 2)
         {
             //return DataModel.SoilNLoadData3.GetValueForDayIndex("SoilNLoadData3", Nitratesdayindex3, Sim.Today);
             return(InputModel.ParticulateNinRunoff.SoilNLoadData3.GetValueForDayIndex("SoilNLoadData3", Sim.Today));
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
     return(0);
 }
예제 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public double GetAvgYieldPerYear()
        {
            double simyears = Sim.NumberOfDaysInSimulation / 365.0;

            return(MathTools.Divide(CalculateTotalYield(), simyears));
        }
예제 #17
0
        List <float> _lengthOfCurves = new List <float>(); // 路径相邻节点间curve长度列表

        /// <summary>
        /// 添加路径点
        /// </summary>
        public void AddPoint(Vector3 point /*世界坐标*/)
        {
            point = transform.InverseTransformPoint(point);
            points.Add(point);
            PathLength = MathTools.GetCatmullRomSplineLength(points, loop, ref _lengthOfCurves);
        }
 public void CalculateCATCHMODSOutputs()
 {
     try
     {
         if (Engine.SoilModule.Runoff > 0 && Engine.SoilModule.HillSlopeErosion > 0)
         {
             if (!MathTools.DoublesAreEqual(Engine.SoilModule.InputModel.SedDelivRatio, 0) && !MathTools.DoublesAreEqual(Engine.SoilModule.UsleLsFactor, 0))
             {
                 PPHLC = (ParticPExport / (Engine.SoilModule.InputModel.SedDelivRatio * Engine.SoilModule.UsleLsFactor));
             }
             else
             {
                 PPHLC = 0;
             }
         }
         else
         {
             PPHLC = 0;
         }
         //CKQ = (Sim.SoilModule.SedCatchmod);
     }
     catch (Exception ex)
     {
         throw ErrorLogger.CreateException(ex);
     }
 }
        public void TestOfDegreeToRadian()
        {
            float degreesToTest = 171.8873f;

            Assert.AreEqual(3, MathTools.DegreeToRadian(degreesToTest), 0.0002);
        }
예제 #20
0
        /// <summary>
        /// Renders the laser.
        /// </summary>
        public void RenderLaser()
        {
            if (Enabled == false || IsActive == false || m_LineRenderer == null)
            {
                if (m_LineRenderer != null)
                {
                    m_LineRenderer.enabled = false;
                }
                return;
            }
            else
            {
                m_LineRenderer.enabled = true;
                                #if UNITY_5_5 || UNITY_5_5_OR_NEWER
                m_LineRenderer.startWidth = Width;
                m_LineRenderer.endWidth   = Width;
                                #else
                m_LineRenderer.SetWidth(Width, Width);
                                #endif
            }

            RaycastHit[] _hit = Physics.RaycastAll(m_Transform.position, m_Transform.forward, LengthMax);

            for (int _i = 0; _i < _hit.Length; _i++)
            {
                if (!_hit[_i].collider.isTrigger)
                {
                    m_LaserLength      = (int)Mathf.Round(_hit[_i].distance) + 2;
                    m_LaserPosition    = new Vector3[m_LaserLength];
                    m_LaserEndPosition = _hit[_i].point;

                    if (EndEffect)
                    {
                        m_LaserEndEffectTransform.position = m_LaserEndPosition;
                        if (!EndEffect.isPlaying)
                        {
                            EndEffect.Play();
                        }
                    }

          #if UNITY_5_6_OR_NEWER
                    m_LineRenderer.positionCount = m_LaserLength;
                                        #elif UNITY_5_5 || UNITY_5_5_OR_NEWER
                    m_LineRenderer.numPositions = m_LaserLength;
                                        #else
                    m_LineRenderer.SetVertexCount(m_LaserLength);
                                        #endif


                    return;
                }
            }

            if (EndEffect)
            {
                if (EndEffect.isPlaying)
                {
                    EndEffect.Stop();
                }
            }

            m_LaserLength   = (int)LengthMax;
            m_LaserPosition = new Vector3[m_LaserLength];

      #if UNITY_5_6_OR_NEWER
            m_LineRenderer.positionCount = m_LaserLength;

            m_LineRenderer.startColor = StartColor;
            m_LineRenderer.endColor   = EndColor;
                        #elif UNITY_5_5 || UNITY_5_5_OR_NEWER
            m_LineRenderer.numPositions = m_LaserLength;

            m_LineRenderer.startColor = StartColor;
            m_LineRenderer.endColor   = EndColor;
                        #else
            m_LineRenderer.SetVertexCount(m_LaserLength);
            m_LineRenderer.SetColors(StartColor, EndColor);
                        #endif

            m_LaserEndPosition = m_Transform.position + (m_Transform.forward * m_LaserLength);

            for (int i = 0; i < m_LaserLength; i++)
            {
                Vector3 _pos = m_Transform.TransformPoint(Offset);
                //Set the position here to the current location and project it in the forward direction of the object it is attached to
                m_LaserOffset.x    = _pos.x + i * m_Transform.forward.x + Random.Range(-Noise, Noise);
                m_LaserOffset.z    = _pos.z + i * m_Transform.forward.z + Random.Range(-Noise, Noise);
                m_LaserOffset.y    = Mathf.Lerp(_pos.y, m_LaserEndPosition.y, MathTools.Normalize(i, 0, m_LaserLength)) + i * m_Transform.forward.y + Random.Range(-Noise, Noise);
                m_LaserPosition[i] = m_LaserOffset;
                m_LaserPosition[0] = _pos;

                m_LineRenderer.SetPosition(i, m_LaserPosition[i]);
            }
        }
예제 #21
0
파일: WarShip.cs 프로젝트: ingex0/smarttank
 protected bool Shoot(float ShootAzi)
 {
     if (shootTimer >= 0)
     {
         if (OnShoot != null)
         {
             InfoRePath.CallEvent(this.mgPath, "OnShoot", OnShoot, this, Pos + MathTools.NormalVectorFromAzi(ShootAzi) * SpaceWarConfig.ShootEndDest, ShootAzi);
         }
         shootTimer -= SpaceWarConfig.ShootCD;
         return(true);
     }
     return(false);
 }
예제 #22
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public double GetAvgYieldPerHarvest()
 {
     return(MathTools.Divide(CalculateTotalYield(), sum_crops_harvested));
 }
예제 #23
0
        public void BuildConvexHall(CircleList <BordPoint> border, float minOptimizeDest)
        {
            #region 获得原始凸包
            if (border.Length < 2)
            {
                return;
            }

            Stack <BordPoint> stack = new Stack <BordPoint>();

            CircleListNode <BordPoint> cur = border.First;
            stack.Push(cur.value);
            cur = cur.next;
            stack.Push(cur.value);
            cur = cur.next;
            for (int i = 2; i < border.Length; i++)
            {
                BordPoint p1 = stack.Pop();

                BordPoint p0 = stack.Peek();

                BordPoint p2 = cur.value;

                if (CountWise(p1, p0, p2))
                {
                    stack.Push(p1);
                    stack.Push(p2);
                    cur = cur.next;
                }
                else
                {
                    if (stack.Count == 1)
                    {
                        stack.Push(p2);
                        cur = cur.next;
                    }
                    else
                    {
                        i--;
                    }
                }
            }

            List <BordPoint> templist = new List <BordPoint>(stack);

            if (templist.Count > 3)
            {
                if (!CountWise(templist[0], templist[1], templist[templist.Count - 1]))
                {
                    templist.RemoveAt(0);
                }
                if (!CountWise(templist[templist.Count - 1], templist[0], templist[templist.Count - 2]))
                {
                    templist.RemoveAt(templist.Count - 1);
                }
            }
            else if (templist.Count == 3)
            {
                if (!CountWise(templist[0], templist[1], templist[templist.Count - 1]))
                {
                    templist.RemoveAt(0);
                    BordPoint temp = templist[0];
                    templist[0] = templist[1];
                    templist[1] = temp;
                }
            }

            #endregion

            #region 对凸包进行化简

            if (templist.Count > 3)
            {
                for (int i = 0; i < templist.Count; i++)
                {
                    Vector2 p1 = ConvertHelper.PointToVector2(templist[i].p);
                    Vector2 p2 = ConvertHelper.PointToVector2(templist[(i + 1) % templist.Count].p);
                    Vector2 p3 = ConvertHelper.PointToVector2(templist[(i + 2) % templist.Count].p);
                    Vector2 p4 = ConvertHelper.PointToVector2(templist[(i + 3) % templist.Count].p);

                    if (Vector2.Distance(p2, p3) > minOptimizeDest)
                    {
                        continue;
                    }

                    Vector2 seg1 = p2 - p1;
                    Vector2 seg2 = p4 - p3;

                    float ang = (float)Math.Acos(Vector2.Dot(seg1, seg2) / (seg1.Length() * seg2.Length()));
                    if (ang > MathHelper.PiOver2)
                    {
                        continue;
                    }

                    Line line1 = new Line(p1, seg1);
                    Line line2 = new Line(p4, seg2);

                    Vector2 interPoint;

                    if (!MathTools.InterPoint(line1, line2, out interPoint))
                    {
                        continue;
                    }

                    templist[(i + 1) % templist.Count] =
                        new BordPoint(templist[(i + 1) % templist.Count].index, ConvertHelper.Vector2ToPoint(interPoint));

                    templist.RemoveAt((i + 2) % templist.Count);

                    i--;
                }
            }

            #endregion

            convexPoints = templist;
        }
예제 #24
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public double GetAvgYieldPerPlanting()
 {
     return(MathTools.Divide(CalculateTotalYield(), sum_crops_planted));
 }
예제 #25
0
        IEnumerator SlowMotionImpl(UnityEngine.Camera camera, float timeScale, float fov,
                                   float effectTime, float restoreDelayTime, float restoreTime)
        {
            float curFovTime = 0;
            float fovTime    = effectTime;
            float baseFov    = camera.fieldOfView;
            float fovStart   = camera.fieldOfView;
            float fovEnd     = fov;
            bool  fovOK      = false;

            float curSlowTime    = 0;
            float slowTime       = effectTime;
            float baseTimeScale  = Time.timeScale;
            float timeScaleStart = Time.timeScale;
            float timeScaleEnd   = timeScale;
            bool  slowOK         = false;

            yield return(new WaitForEndOfFrame());

            bool inRestore = false; // 是否处于恢复过程

            while (fovOK == false || slowOK == false)
            {
                if (fovOK == false)
                {
                    curFovTime += Time.deltaTime;
                    if (curFovTime > fovTime)
                    {
                        curFovTime = fovTime;
                        fovOK      = true;
                    }
                    camera.fieldOfView = MathTools.Hermite(fovStart, fovEnd, curFovTime / fovTime);
                }

                if (slowOK == false)
                {
                    curSlowTime += Time.deltaTime;
                    if (curSlowTime > slowTime)
                    {
                        curSlowTime = slowTime;
                        slowOK      = true;
                    }
                    Time.timeScale = MathTools.Hermite(timeScaleStart, timeScaleEnd, curSlowTime / slowTime);
                }

                yield return(new WaitForEndOfFrame());

                if (fovOK && slowOK && inRestore == false)
                {
                    // 准备恢复
                    curFovTime = 0;
                    fovTime    = restoreTime;
                    fovStart   = fovEnd;
                    fovEnd     = baseFov;
                    fovOK      = false;

                    curSlowTime    = 0;
                    slowTime       = restoreTime;
                    timeScaleStart = timeScaleEnd;
                    timeScaleEnd   = baseTimeScale;
                    slowOK         = false;

                    inRestore = true;

                    yield return(new WaitForSeconds(restoreDelayTime)); // 延迟N秒开始恢复
                }
            }
        }
예제 #26
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public double GetAvgYieldPerYear()
        {
            double simyears = sim.number_of_days_in_simulation / 365.0;

            return(MathTools.Divide(CalculateTotalYield(), simyears));
        }
예제 #27
0
    void DrawRotation(bool isWidget)
    {
        GUILayout.BeginHorizontal();
        {
            bool reset = GUILayout.Button("R", GUILayout.Width(20f));

            Vector3 visible = (serializedObject.targetObject as Transform).localEulerAngles;

            visible.x = MathTools.WrapAngle(visible.x);
            visible.y = MathTools.WrapAngle(visible.y);
            visible.z = MathTools.WrapAngle(visible.z);

            Axes changed = CheckDifference(mRot);
            Axes altered = Axes.None;

            GUILayoutOption opt = GUILayout.MinWidth(30f);

            if (FloatField("X", ref visible.x, (changed & Axes.X) != 0, isWidget, opt))
            {
                altered |= Axes.X;
            }
            if (FloatField("Y", ref visible.y, (changed & Axes.Y) != 0, isWidget, opt))
            {
                altered |= Axes.Y;
            }
            if (FloatField("Z", ref visible.z, (changed & Axes.Z) != 0, false, opt))
            {
                altered |= Axes.Z;
            }

            if (reset)
            {
                mRot.quaternionValue = Quaternion.identity;
            }
            else if (altered != Axes.None)
            {
                EditorTools.RegisterUndo("Change Rotation", serializedObject.targetObjects);

                foreach (Object obj in serializedObject.targetObjects)
                {
                    Transform t = obj as Transform;
                    Vector3   v = t.localEulerAngles;

                    if ((altered & Axes.X) != 0)
                    {
                        v.x = visible.x;
                    }
                    if ((altered & Axes.Y) != 0)
                    {
                        v.y = visible.y;
                    }
                    if ((altered & Axes.Z) != 0)
                    {
                        v.z = visible.z;
                    }

                    t.localEulerAngles = v;
                }
            }
        }
        GUILayout.EndHorizontal();
    }
예제 #28
0
        private void UpdateSize()
        {
            if (this.canvasScaler.get_uiScaleMode() != 1 || this.breakPoints == null)
            {
                return;
            }
            float num1   = (float)Screen.get_width() / (float)Screen.get_height();
            float num2   = float.PositiveInfinity;
            int   index1 = 0;

            for (int index2 = 0; index2 < this.breakPoints.Length; ++index2)
            {
                float num3 = Mathf.Abs(num1 - this.breakPoints[index2].screenAspectRatio);
                if (((double)num3 <= (double)this.breakPoints[index2].screenAspectRatio || MathTools.IsNear(this.breakPoints[index2].screenAspectRatio, 0.01f)) && (double)num3 < (double)num2)
                {
                    num2   = num3;
                    index1 = index2;
                }
            }
            this.canvasScaler.set_referenceResolution(this.breakPoints[index1].referenceResolution);
        }
예제 #29
0
        public int[] findBitmap(LockedBitmap lbTarget, int tolerance = 0, int limit = 1)
        {
            // If the limit is less or equal to zero, there's nothing to do really
            if (limit <= 0)
            {
                return(new int[0]);
            }

            // Get the parameters for findColor
            // BEWARE! THE BYTES ARE IN REVERSE ORDER BECAUSE OF THE BYTE SIGNIFICANCE (BGR instead of RGB)
            Color firstPixelColor = Color.FromArgb(lbTarget.Bytes[2], lbTarget.Bytes[1], lbTarget.Bytes[0]);
            int   searchAreaSize  = Size.Width * Size.Height;

            // Search bitmap for all occurances of the first pixel color
            int[] firstPixelMatches = findColor(firstPixelColor, tolerance, searchAreaSize);

            // If the first pixel color doesn't appear in the whole bitmap, there's no reason to continue
            if (firstPixelMatches.Length <= 0)
            {
                return(new int[0]);
            }

            // Create field for the matches of the maximum possible size
            int[] matches      = new int[limit];
            int   matchesFound = 0;

            // Go through all the first pixel color matches
            for (int i = 0; i < firstPixelMatches.Length; i++)
            {
                bool isMatch = true;

                // Get the pixel offsets
                int xOffset = firstPixelMatches[i] % Stride;
                int yOffset = firstPixelMatches[i] - xOffset;

                // Both x and y are indexes in bytes
                for (int yTarget = 0, ySource = yOffset;
                     yTarget < lbTarget.Bytes.Length && isMatch;
                     yTarget += lbTarget.Stride, ySource += Stride)
                {
                    for (int xTarget = 0, xSource = xOffset;
                         xTarget < lbTarget.ByteWidth && isMatch;
                         xTarget += bytesPerPixel, xSource += bytesPerPixel)
                    {
                        // If all the pixel colors match, save the current point
                        for (int j = 0; j < bytesPerPixel && isMatch; j++)
                        {
                            if (xSource + ySource < Bytes.Length)
                            {
                                isMatch = MathTools.Compare(Bytes[xSource + ySource + j], lbTarget.Bytes[xTarget + yTarget + j], tolerance);
                            }
                            else
                            {
                                isMatch = false;
                            }
                        }
                    }
                }

                if (isMatch)
                {
                    // Save the found match
                    matches[matchesFound] = firstPixelMatches[i];
                    matchesFound++;

                    // If there are enough matches found already, break the loop and return found matches
                    if (matchesFound >= limit)
                    {
                        return(matches);
                    }
                }
            }

            // If there are less matches found than the limit, get rid of the empty Points and return the actual matches
            int[] foundMatches = new int[matchesFound];
            for (int i = 0; i < matchesFound; i++)
            {
                foundMatches[i] = matches[i];
            }

            return(foundMatches);
        }
 public void convertFromContinuedFractionToDoubleTest()
 {
     Assert.AreEqual(MathTools.convertFromContinuedFractionToDouble(MathTools.irrationalContinuedFraction(Math.E)), Math.E);
     Assert.AreEqual(MathTools.convertFromContinuedFractionToDouble(MathTools.irrationalContinuedFraction(Math.PI)), Math.PI);
     Assert.AreEqual(MathTools.convertFromContinuedFractionToDouble(MathTools.irrationalContinuedFraction(Math.PI / 2)), Math.PI / 2);
 }