Example #1
0
        public void Render(RenderTreeBuilder renderTreeBuilder, RenderConfig config)
        {
            List <KeyValueModel> tableDataSource = new List <KeyValueModel>();
            var attributeConfig = (TableAttribute)config.ControlAttribute;

            renderTreeBuilder.OpenComponent(0, config.InputControlType);
            renderTreeBuilder.AddAttribute(1, nameof(BFormItemObject.EnableAlwaysRender), true);
            renderTreeBuilder.AddAttribute(2, nameof(BTable.AutoGenerateColumns), true);
            renderTreeBuilder.AddAttribute(3, nameof(BTable.DataType), typeof(KeyValueModel));
            if (attributeConfig != null)
            {
                renderTreeBuilder.AddAttribute(4, nameof(BTable.Height), attributeConfig.Height);
                renderTreeBuilder.AddAttribute(5, nameof(BTable.IsEditable), attributeConfig.IsEditable);
                if (attributeConfig.IsEditable)
                {
                    renderTreeBuilder.AddAttribute(6, nameof(BTable.DataType), typeof(KeyValueModel));
                    if (config.Page == null)
                    {
                        ExceptionHelper.Throw(ExceptionHelper.CascadingValueNotFound, "表格启用可编辑功能后必须在外面套一层 CascadingValue,值为 this,名称为 Page");
                    }
                    renderTreeBuilder.AddAttribute(7, nameof(BTable.OnSave), EventCallback.Factory.Create <TableSaveEventArgs>(config.Page, DefaultSaverAsync));
                }
            }
            renderTreeBuilder.AddAttribute(8, nameof(BTable.DataSourceChanged), EventCallback.Factory.Create <object>(this, dataSource =>
            {
                tableDataSource     = (List <KeyValueModel>)dataSource;
                config.EditingValue = dataSource;
            }));
            renderTreeBuilder.AddAttribute(9, nameof(BTable.DataSource), tableDataSource);
            renderTreeBuilder.AddComponentReferenceCapture(10, table => currentTable = (BTable)table);
            renderTreeBuilder.CloseComponent();
        }
Example #2
0
        public void Mask(Image texture, Rectangle area, float opacity = 1.0f)
        {
            //init the data we need uo upload
            Transform    transform    = new Transform();
            RenderConfig renderConfig = new RenderConfig();

            transform.World      = Matrix4x4.CreateTranslation(new System.Numerics.Vector3(area.Left, area.Top, 0));
            transform.World      = Matrix4x4.CreateScale(new System.Numerics.Vector3(area.Right - area.Left, area.Bottom - area.Top, 1)) * transform.World;
            transform.Projection = Matrix4x4.CreateOrthographicOffCenter(0, mSwapChain.Size.Width, 0, mSwapChain.Size.Height, 0, 1);

            renderConfig.Opacity = new System.Numerics.Vector4(opacity);

            //upload it to gpu memory
            mTransformBuffer.Update(transform);
            mRenderConfigBuffer.Update(renderConfig);

            //change shader
            mDevice.SetPixelShader(mMaskPixelShader);

            //set resource to shader
            mDevice.SetBuffer(mTransformBuffer, mTransformBufferSlot, GpuShaderType.VertexShader);
            mDevice.SetBuffer(mRenderConfigBuffer, mRenderConfigBufferSlot, GpuShaderType.PixelShader);
            mDevice.SetSamplerState(mGpuSamplerState, mSamplerStateSlot, GpuShaderType.PixelShader);
            mDevice.SetResourceUsage(texture.GpuResourceUsage, mTextureSlot, GpuShaderType.PixelShader);

            //draw
            mDevice.DrawIndexed(6, 0, 0);

            //reset shader
            mDevice.SetPixelShader(mDrawPixelShader);
        }
Example #3
0
        private void UpdateRenderConfig(RenderConfig renderConfig)
        {
            using (SQLiteConnection connection = new SQLiteConnection(App.databasePath))
            {
                if (!CheckIfTableExists(connection, "RenderConfig"))
                {
                    connection.CreateTable <RenderConfig>();
                }
                var isExist = connection.Table <RenderConfig>().Where(acc => acc.Name == renderConfig.Name).FirstOrDefault();
                if (isExist != null)
                {
                    SQLiteCommand command = new SQLiteCommand(connection);

                    command.CommandText =
                        "UPDATE RenderConfig SET Left = " + renderConfig.Left + ", Top = " + renderConfig.Top + ", Width = " + renderConfig.Width + ", Height = " + renderConfig.Height + ", Angle = " + renderConfig.Angle + " where Name = '" + renderConfig.Name + "'";


                    command.ExecuteNonQuery();
                }
                else
                {
                    connection.Insert(renderConfig);
                }

                connection.Close();
            }
            return;
        }
Example #4
0
        protected virtual void CreateBind(RenderConfig config, RenderTreeBuilder builder, int startIndex)
        {
            Type valueType    = CreateTwoWayBinding(config, builder, startIndex);
            var  finalType    = Nullable.GetUnderlyingType(valueType) ?? valueType;
            var  editingValue = config.EditingValue?.ToString();

            if (finalType.IsEnum)
            {
                if (config.RawValue == null && finalType != valueType)
                {
                    builder.AddAttribute(startIndex + 1, nameof(BInput <string> .Value), (object)null);
                }
                else if (config.RawValue == null)
                {
                    builder.AddAttribute(startIndex + 1, nameof(BInput <string> .Value), Activator.CreateInstance(finalType));
                }
                else
                {
                    builder.AddAttribute(startIndex + 1, nameof(BInput <string> .Value), Enum.Parse(finalType, editingValue));
                }
            }
            else
            {
                builder.AddAttribute(startIndex + 1, nameof(BInput <string> .Value), Convert.ChangeType(editingValue, valueType));
            }
        }
Example #5
0
        public virtual void FillRectangle(Rectangle <float> rectangle, Color <float> color)
        {
            //fill rectangle
            //color.alpha means the opacity of rectangle

            MatrixData   matrixData   = new MatrixData();
            RenderConfig renderConfig = new RenderConfig()
            {
                Color = color
            };

            //1.scale the rectangle
            matrixData.World = Matrix4x4.CreateScale(rectangle.Right - rectangle.Left, rectangle.Bottom - rectangle.Top, 1.0f);
            //2.translate it
            matrixData.World *= Matrix4x4.CreateTranslation(rectangle.Left, rectangle.Top, 0.0f);
            //3.keep transform matrix data
            matrixData.World *= Transform;

            //set projection matrix
            matrixData.Project = mProject;

            mMatrixDataBuffer.Update(matrixData);
            mRenderConfigBuffer.Update(renderConfig);

            mDevice.SetPixelShader(mColorPixelShader);
            mDevice.SetVertexBuffer(mSquareVertexBuffer);
            mDevice.SetIndexBuffer(mSquareIndexBuffer);

            mDevice.SetBuffer(mMatrixDataBuffer, mMatrixDataBufferSlot, GpuShaderType.VertexShader);
            mDevice.SetBuffer(mRenderConfigBuffer, mRenderConfigBufferSlot, GpuShaderType.PixelShader);

            mDevice.DrawIndexed(6, 0, 0);
        }
        public static void DrawDiagram(VoronoiDiagram v, RenderConfig config, string filename)
        {
            // Initialize surface:
            Bitmap   image = CreateBitmap(config);
            Graphics g     = Graphics.FromImage(image);

            g.Clear(Color.White);

            // Style for site centers:
            SolidBrush pointBrush = new SolidBrush(Color.Black);

            // Style for lines:
            Pen linePen = new Pen(Brushes.SlateGray)
            {
                Width = 1.0F
            };


            // Draw edges:
            foreach (Edge e in v.edges)
            {
                System.Drawing.Point a = TransposePoint(e.a, config);
                System.Drawing.Point b = TransposePoint(e.b, config);
                g.DrawLine(linePen, a, b);
            }
            // Draw site centers:
            foreach (Models.Point point in v.sites)
            {
                g.DrawPoint(point, pointBrush, config);
            }
            image.Save(filename);

            linePen.Dispose();
            pointBrush.Dispose();
        }
        public static void DrawDiagram(BruteForceVoronoi diagram, RenderConfig config, string filename)
        {
            Bitmap image = CreateBitmap(config);

            for (int row = 0; row < image.Height; row++)
            {
                for (int col = 0; col < image.Width; col++)
                {
                    bool initialPadding = col < config.xPadding || row < config.yPadding;
                    bool finalPadding   = (col - config.xPadding) >= diagram.output.GetLength(0) || (row - config.yPadding) >= diagram.output.GetLength(1);

                    if (initialPadding || finalPadding)
                    {
                        image.SetPixel(col, row, Color.White);
                    }
                    else
                    {
                        ushort pointIndex = diagram.output[col - config.xPadding, row - config.yPadding];
                        image.SetPixel(col, row, diagram.sites[pointIndex].color);
                    }
                }
            }

            // Note: graphics draws on top of the existing bitmap by reference
            Graphics   g          = Graphics.FromImage(image);
            SolidBrush whiteBrush = new SolidBrush(Color.White);

            foreach (Models.Point site in diagram.sites)
            {
                g.DrawPoint(site, whiteBrush, config);
            }
            image.Save(filename);
            whiteBrush.Dispose();
        }
 public void Render(RenderTreeBuilder renderTreeBuilder, RenderConfig config)
 {
     renderTreeBuilder.OpenComponent(0, config.InputControlType);
     renderTreeBuilder.AddAttribute(1, nameof(BFormItemObject.EnableAlwaysRender), true);
     renderTreeBuilder.AddAttribute(2, nameof(BSwitch <bool> .ActiveValue), true);
     renderTreeBuilder.AddAttribute(3, nameof(BSwitch <bool> .InactiveValue), false);
     renderTreeBuilder.CloseComponent();
 }
Example #9
0
 /// <summary>
 /// Layer 构造函数,对外隐藏
 /// 使用Render 中的GetNewLayer方法
 /// </summary>
 internal Layer(ConcurrentQueue <Action> cmdList, RenderConfig config)
 {
     UUID          = Guid.NewGuid().ToString();
     __cmdList     = cmdList;
     __config      = config;
     primitives    = new List <IPrimitive>();
     __messagePipe = new MessagePipe(this);
 }
Example #10
0
        private RenderConfig RefreshConfig()
        {
            RenderConfig config = new RenderConfig();

            config.width   = int.Parse(cfgWidth.Text);
            config.height  = int.Parse(cfgHeight.Text);
            config.samples = int.Parse(cfgSamples.Text);
            return(config);
        }
Example #11
0
        /************************/
        /*** Public Functions ***/
        /************************/

        public void Config(RenderConfig configure, object data)
        {
            switch (configure)
            {
            case RenderConfig.BG_COLOR:
                BgColor = (ConsoleColor)data;
                break;
            }
        }
Example #12
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
         }
         __config      = null;
         disposedValue = true;
     }
 }
Example #13
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="handle">绘制窗体句柄</param>
        protected AbstractRenderer()
        {
            __layers          = new List <Layer>();
            __mres            = new ManualResetEventSlim(false);
            __cmdList         = new ConcurrentQueue <Action>();
            __messagePipe     = new MessagePipe(this);
            __renderingThread = new Thread(new ThreadStart(RenderingLoop))
            {
                IsBackground = true
            };

            Configuration = new RenderConfig();
            Configuration.ClientSizeChanged += Configuration_ClientSizeChanged;
        }
        public void Render(RenderTreeBuilder renderTreeBuilder, RenderConfig config)
        {
            var inputConfig = (CheckBoxAttribute)config.ControlAttribute;

            renderTreeBuilder.OpenComponent(0, config.InputControlType);
            renderTreeBuilder.AddAttribute(1, nameof(BFormItemObject.EnableAlwaysRender), true);
            if (inputConfig != null)
            {
                renderTreeBuilder.AddAttribute(2, nameof(inputConfig.Image), inputConfig.Image);
                renderTreeBuilder.AddAttribute(3, nameof(inputConfig.Style), inputConfig.Style);
                renderTreeBuilder.AddAttribute(4, nameof(BFormItemObject.ChildContent), inputConfig.Text);
            }
            renderTreeBuilder.CloseComponent();
        }
Example #15
0
        public void Render(RenderTreeBuilder renderTreeBuilder, RenderConfig config)
        {
            var uploadConfig = (UploadAttribute)config.ControlAttribute;

            renderTreeBuilder.OpenComponent <BUpload>(0);
            renderTreeBuilder.AddAttribute(1, nameof(BUpload.Url), uploadConfig.Url);
            renderTreeBuilder.AddAttribute(2, nameof(BUpload.Width), uploadConfig.Width);
            renderTreeBuilder.AddAttribute(3, nameof(BUpload.MaxSize), uploadConfig.MaxSize);
            renderTreeBuilder.AddAttribute(4, nameof(BUpload.Tip), (RenderFragment)(builder => builder.AddMarkupContent(9, uploadConfig.Tip)));
            renderTreeBuilder.AddAttribute(5, nameof(BUpload.AllowExtensions), uploadConfig.AllowExtensions);
            renderTreeBuilder.AddAttribute(6, nameof(BUpload.Height), uploadConfig.Height);
            renderTreeBuilder.AddAttribute(7, nameof(BUpload.EnablePasteUpload), uploadConfig.EnablePasteUpload);
            renderTreeBuilder.AddAttribute(8, nameof(BUpload.UploadType), uploadConfig.Type);
            renderTreeBuilder.CloseComponent();
        }
Example #16
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             primitives.ForEach(s => s.Dispose());
             primitives.Clear();
             __messagePipe.Dispose();
         }
         __messagePipe = null;
         __cmdList     = null;
         __config      = null;
         disposedValue = true;
     }
 }
Example #17
0
        public virtual void DrawLine(Position <float> start, Position <float> end, Color <float> color,
                                     float padding = 2.0f)
        {
            //draw line with start and end position
            //padding means the width of line
            //color.Alpha means the opacity of line

            //first, we compute the matrix of world transform
            MatrixData matrixData = new MatrixData();
            Vector2    vector     = new Vector2(end.X - start.X, end.Y - start.Y);

            //1.compute the scale component, x-component is euqal the length of line, y-component is equal the padding
            matrixData.World = Matrix4x4.CreateScale(vector.Length(), padding, 1.0f);
            //2.compute the angle of rotate, we only rotate it at the z-axis
            matrixData.World *= Matrix4x4.CreateRotationZ((float)Math.Atan2(vector.Y, vector.X), new Vector3(0, padding * 0.5f, 0));
            //3.compute the translation, the position of start, but the y is start.y - padding * 0.5f
            matrixData.World *= Matrix4x4.CreateTranslation(new Vector3(start.X, start.Y - padding * 0.5f, 0));
            //4.keep transform matrix data
            matrixData.World *= Transform;

            //set project matrix
            matrixData.Project = mProject;

            //second, we set the render config
            RenderConfig renderConfig = new RenderConfig()
            {
                Color = color
            };

            //update buffer
            mMatrixDataBuffer.Update(matrixData);
            mRenderConfigBuffer.Update(renderConfig);

            //set buffer and shader
            mDevice.SetPixelShader(mColorPixelShader);
            mDevice.SetVertexBuffer(mSquareVertexBuffer);
            mDevice.SetIndexBuffer(mSquareIndexBuffer);

            mDevice.SetBuffer(mMatrixDataBuffer, mMatrixDataBufferSlot, GpuShaderType.VertexShader);
            mDevice.SetBuffer(mRenderConfigBuffer, mRenderConfigBufferSlot, GpuShaderType.PixelShader);

            //draw
            mDevice.DrawIndexed(6, 0, 0);
        }
Example #18
0
        public RenderTask(RenderConfig config, System.Windows.Controls.Image targetImage)
        {
            IsFinish = false;

            m_config    = config;
            this.Width  = m_config.width;
            this.Height = m_config.height;

            image = targetImage;

            targetImage.Width  = Width;
            targetImage.Height = Height;

            img = targetImage;

            m_targetBitmap = new WriteableBitmap(Width, Height, 0, 0, PixelFormats.Rgb24, null);
            img.Source     = m_targetBitmap;
            InitRenderContext();
        }
Example #19
0
        public static void Main(string[] args)
        {
            int       numThreads    = Environment.ProcessorCount / 2;
            const int RayTraceDepth = 50;
            const int NumSamples    = 1000;
            var       renderConfig  = new RenderConfig(numThreads, RayTraceDepth, NumSamples);

            string globeImagePath = Path.Combine(OutputDirectory, "globetex.jpg");
            // var scene = new ManySpheresScene();
            // var scene = new NoiseSpheresScene();
            // var scene = new ImageTextureScene(globeImagePath);
            // var scene = new LightsScene(globeImagePath);
            var scene = new CornellBoxScene();
            // var scene = new CornellBoxWithSmokeScene();
            IRenderer renderer    = new PerPixelRenderer();
            var       pixelBuffer = new PixelBuffer(Width, Height);

            string name = scene.GetType().Name.ToLowerInvariant();

            Console.WriteLine($"Executing {name} at resolution ({pixelBuffer.Width},{pixelBuffer.Height})");
            Console.WriteLine($"  Num Threads   = {numThreads}");
            Console.WriteLine($"  RayTraceDepth = {RayTraceDepth}");
            Console.WriteLine($"  Num Samples   = {NumSamples}");

            var sw           = Stopwatch.StartNew();
            var rendererData = renderer.Render(pixelBuffer, scene, renderConfig);

            sw.Stop();
            Console.WriteLine();
            Console.WriteLine($"Render complete: {sw.ElapsedMilliseconds}ms");
            Console.WriteLine($"Total Pixel Color Time: {rendererData.GetTotalPixelColorMilliseconds()}ms");
            Console.WriteLine($"Per Pixel Avg Time:     {rendererData.GetAveragePixelColorMilliseconds()}ms");

            string outputPath = Path.Combine(OutputDirectory, $"{name}.png");

            Console.WriteLine($"Saving image to {outputPath}");
            pixelBuffer.SaveAsFile(outputPath);


            // RunExecutors();
        }
Example #20
0
        public void Render(RenderTreeBuilder builder, RenderConfig config)
        {
            var inputConfig = (InputAttribute)config.ControlAttribute;

            Console.WriteLine(config.InputControlType);
            builder.OpenComponent(0, config.InputControlType);
            if (inputConfig != null)
            {
                builder.AddAttribute(2, nameof(inputConfig.IsClearable), inputConfig.IsClearable);
                builder.AddAttribute(3, nameof(inputConfig.IsDisabled), inputConfig.IsDisabled);
                builder.AddAttribute(4, nameof(inputConfig.Placeholder), inputConfig.Placeholder);
                builder.AddAttribute(5, nameof(inputConfig.PrefixIcon), inputConfig.PrefixIcon);
                builder.AddAttribute(6, nameof(inputConfig.SuffixIcon), inputConfig.SuffixIcon);
                builder.AddAttribute(7, nameof(inputConfig.Type), inputConfig.Type);
                builder.AddAttribute(8, nameof(inputConfig.Image), inputConfig.Image);
                builder.AddAttribute(9, nameof(inputConfig.Style), inputConfig.Style);
            }
            builder.AddAttribute(10, nameof(BFormItemObject.EnableAlwaysRender), true);
            CreateBind(config, builder, 11);
            builder.CloseComponent();
        }
Example #21
0
        private void RenderButton_OnClick(object sender, RoutedEventArgs e)
        {
            int       numThreads    = Environment.ProcessorCount;
            const int ImageWidth    = 1000;
            const int ImageHeight   = 1000;
            const int RayTraceDepth = 50;
            const int NumSamples    = 10;
            var       renderConfig  = new RenderConfig(numThreads, RayTraceDepth, NumSamples)
            {
                TwoPhase = false
            };

            var scene = new CornellBoxScene();
            // var scene = NffParser.ParseFile(Path.Combine(NffDirectory, "balls5.nff"), ImageWidth, ImageHeight);

            // var pixelBuffer = new PixelBuffer(ImageWidth, ImageHeight);
            var pixelBuffer = new WpfPixelBuffer(Dispatcher, ImageWidth, ImageHeight);

            RenderImage.Source = pixelBuffer.WriteableBitmap;
            IRenderer renderer = new PerLineRenderer();

            string name       = scene.GetType().Name.ToLowerInvariant();
            string outputPath = Path.Combine(OutputDirectory, $"{name}.png");

            renderer.Progress += (_, args) => { Dispatcher.Invoke(() => { RenderProgress.Value = args.PercentComplete; }); };
            Task.Run(() =>
            {
                Dispatcher.Invoke(() => RenderButton.IsEnabled = false);
                var sw           = Stopwatch.StartNew();
                var rendererData = renderer.Render(pixelBuffer, scene, renderConfig);
                sw.Stop();
                Dispatcher.Invoke(() =>
                {
                    RenderTime.Text        = $"{sw.ElapsedMilliseconds}ms";
                    AvgGetColorMs.Text     = $"{rendererData.GetAveragePixelColorMilliseconds()}ms";
                    RenderButton.IsEnabled = true;
                });
                pixelBuffer.SaveAsFile(outputPath);
            });
        }
Example #22
0
        // Renders a diagram based off of random points.
        // Uses same points with both methods.
        public static void RenderSameDiagram()
        {
            List <Point> points = Point.GetRandomPoints(numPointsForPic, 0, rangeForPic);

            DelaunayTriangulator tri           = new DelaunayTriangulator(points);
            VoronoiDiagram       voroEfficient = tri.GenerateVoronoi();


            BruteForceVoronoi voroBrute = new BruteForceVoronoi(points);

            voroBrute.GenerateVoronoi();

            RenderConfig config = voroBrute.FullFrameConfig;

            config.xPadding += 50;
            config.yPadding += 50;

            VoronoiRenderer.DrawDiagram(voroEfficient, config, "bowyer_output.bmp");
            VoronoiRenderer.DrawTriangulation(tri.WithoutSupertriangle(), config, "bowyer_triangulation_no_super.bmp");
            VoronoiRenderer.DrawTriangulation(tri, config, "bowyer_triangulation_super.bmp");

            VoronoiRenderer.DrawDiagram(voroBrute, config, "brute_force_output.bmp");
        }
Example #23
0
        /// <summary>
        /// Creates instance of the renderer.
        /// </summary>
        /// <param name="doc">The render document, to render content.</param>
        public Renderer(RenderDocument doc)
        {
            m_RenderDoc = doc;
            m_Config    = new RenderConfig(this);

            var xnaWindow = (Form)Control.FromHandle(this.Window.Handle);

            xnaWindow.GotFocus += (object sender, EventArgs e) =>
            {
                (sender as Form).Visible = false;
            };

            m_RasterizerState_Solid.CullMode      = CullMode.CullClockwiseFace;
            m_RasterizerState_Solid.FillMode      = FillMode.Solid;
            m_RasterizerState_Wireframe.CullMode  = CullMode.None;
            m_RasterizerState_Wireframe.FillMode  = FillMode.WireFrame;
            m_RasterizerState_Wireframe.DepthBias = -0.000001f;

            m_DepthStencilState.DepthBufferWriteEnable = true;
            m_DepthStencilState.DepthBufferEnable      = true;
            m_DepthStencilState.DepthBufferFunction    = CompareFunction.LessEqual;

            m_WireframeDepthStencilState.DepthBufferEnable      = false;
            m_WireframeDepthStencilState.DepthBufferWriteEnable = false;
            m_WireframeDepthStencilState.DepthBufferFunction    = CompareFunction.Always;


            m_Graphics = new GraphicsDeviceManager(this)
            {
                PreferredBackBufferWidth  = m_RenderDoc.ClientSize.Width,
                PreferredBackBufferHeight = m_RenderDoc.ClientSize.Height
            };

            m_Graphics.PreparingDeviceSettings += OnGraphicsPreparingDeviceSettings;
            Content.RootDirectory = "Content";
            IsMouseVisible        = true;
        }
Example #24
0
        protected Type CreateTwoWayBinding(RenderConfig config, RenderTreeBuilder builder, int startIndex, string propertyName = nameof(BInput <string> .ValueChanged), Type valueType = null)
        {
            valueType = valueType ?? config.InputControlType.GetGenericArguments()[0];
            if (config.Page == null)
            {
                Console.WriteLine("没有双向绑定");
                return(valueType);
            }
            Console.WriteLine("开始双向绑定");
            var createMethod = typeof(EventCallbackFactory).GetMethods().FirstOrDefault(x =>
            {
                if (!x.IsGenericMethod || !x.IsPublic)
                {
                    return(false);
                }
                ;
                var parameters = x.GetParameters();
                if (parameters.Length < 2)
                {
                    return(false);
                }
                var parameterType = parameters[1].ParameterType;
                if (!parameterType.IsGenericType)
                {
                    return(false);
                }
                return(parameterType.IsGenericType && parameterType.GetGenericTypeDefinition() == typeof(Action <>));
            }).MakeGenericMethod(valueType);
            var parameterExp = Expression.Parameter(valueType);
            var body         = Expression.Assign(Expression.Property(Expression.Constant(config), nameof(RenderConfig.EditingValue)), Expression.Convert(parameterExp, typeof(object)));
            var settter      = Expression.Lambda(typeof(Action <>).MakeGenericType(valueType), body, parameterExp).Compile();
            var setterMethod = createMethod.Invoke(EventCallback.Factory, new object[] { config.Page, settter });

            builder.AddAttribute(startIndex, propertyName, Convert.ChangeType(setterMethod, typeof(EventCallback <>).MakeGenericType(valueType)));
            return(valueType);
        }
Example #25
0
        public virtual void DrawImage(Rectangle <float> rectangle, Image image, Color <float> color)
        {
            //fill rectangle with texture
            //the result color's alpha is equal texture.alpha * opacity

            MatrixData   matrixData   = new MatrixData();
            RenderConfig renderConfig = new RenderConfig()
            {
                Color = color
            };

            //1.scale the rectangle
            matrixData.World = Matrix4x4.CreateScale(rectangle.Right - rectangle.Left, rectangle.Bottom - rectangle.Top, 1.0f);
            //2.translate it
            matrixData.World *= Matrix4x4.CreateTranslation(rectangle.Left, rectangle.Top, 0.0f);
            //3.keep transform matrix data
            matrixData.World *= Transform;

            //set projection matrix
            matrixData.Project = mProject;

            mMatrixDataBuffer.Update(matrixData);
            mRenderConfigBuffer.Update(renderConfig);

            mDevice.SetPixelShader(mTexturePixelShader);
            mDevice.SetVertexBuffer(mSquareVertexBuffer);
            mDevice.SetIndexBuffer(mSquareIndexBuffer);

            mDevice.SetSamplerState(mSamplerState, mSamplerStateSlot, GpuShaderType.PixelShader);

            mDevice.SetBuffer(mMatrixDataBuffer, mMatrixDataBufferSlot, GpuShaderType.VertexShader);
            mDevice.SetBuffer(mRenderConfigBuffer, mRenderConfigBufferSlot, GpuShaderType.PixelShader);
            mDevice.SetResourceUsage(image.GpuResourceUsage, mTextureSlot, GpuShaderType.PixelShader);

            mDevice.DrawIndexed(6, 0, 0);
        }
 public static Bitmap CreateBitmap(RenderConfig config)
 {
     return(new Bitmap(config.width + 2 * config.xPadding, config.height + 2 * config.yPadding));
 }
        public static void DrawCircle(this Graphics g, Models.Point center, Pen pen, double radius, RenderConfig config)
        {
            int       minX = (int)(Math.Floor(center.x) - radius + config.xPadding + config.xOffset);
            int       minY = (int)(Math.Floor(center.y) - radius + config.yPadding + config.yOffset);
            Rectangle rect = new Rectangle(minX, minY, (int)radius * 2, (int)radius * 2);

            g.DrawEllipse(pen, rect);
        }
        public static void DrawPoint(this Graphics g, VoronoiAlgorithms.Models.Point center, Brush pen, RenderConfig config, int radius = 4)
        {
            int xCoord = (int)Math.Floor(center.x - radius + config.xPadding + config.xOffset);
            int yCoord = (int)Math.Floor(center.y - radius + config.yPadding + config.yOffset);

            g.FillEllipse(pen, xCoord, yCoord, radius * 2, radius * 2);
        }
        public static void DrawTriangulation(DelaunayTriangulator tri, RenderConfig config, string filename)
        {
            // Initialize surface:
            Bitmap   image = CreateBitmap(config);
            Graphics g     = Graphics.FromImage(image);

            g.Clear(Color.White);

            // Style for site centers:
            SolidBrush pointBrush  = new SolidBrush(Color.Black);
            SolidBrush centerBrush = new SolidBrush(Color.Red);

            // Style for lines:
            Pen linePen = new Pen(Brushes.SlateGray)
            {
                Width = 1.0F
            };

            Pen circlePen = new Pen(Brushes.GreenYellow)
            {
                Width = 0.75F
            };

            Font font = new Font("Arial", 10);


            foreach (Vertex vertex in tri.triangles)
            {
                System.Drawing.Point[] drawPoints = new System.Drawing.Point[4];

                for (int i = 0; i < vertex.points.Count; i++)
                {
                    Models.Point         p           = vertex.points[i];
                    System.Drawing.Point pWithOffset = TransposePoint(p, config);
                    g.DrawString(p.ToString(), font, centerBrush, pWithOffset);
                    drawPoints[i] = pWithOffset;
                }

                drawPoints[3] = drawPoints[0];

                g.DrawLines(linePen, drawPoints);


                Models.Point point = vertex.center;
                g.DrawPoint(point, centerBrush, config);


                g.DrawCircle(point, circlePen, vertex.radius, config);
            }

            foreach (Models.Point point in tri.allPoints)
            {
                g.DrawPoint(point, pointBrush, config);
            }
            image.Save(filename);

            linePen.Dispose();
            pointBrush.Dispose();
            centerBrush.Dispose();
            circlePen.Dispose();
        }
Example #30
0
 public void RenderFactoryBase(StringBuilder sb, RenderConfig config)
 {
     string tabs = new string('\t', config.TabCount + 1);
     sb.AppendFormat("{0}public class BaseConnection\r\n", new String('\t', config.TabCount));
     sb.Append(new String('\t', config.TabCount)).Append("{\r\n");
     sb.AppendFormat("{0}private static SqlConnection _connection;\r\n\r\n", tabs);
     sb.AppendFormat("{0}public static SqlConnection GetConnection()\r\n", tabs);
     sb.Append(tabs).Append("{\r\n");
     sb.Append(tabs).Append("\tif (_connection == null)\r\n");
     sb.Append(tabs).AppendFormat("\t\t_connection = new SqlConnection(\"{0}\");\r\n", config.ConnectionString);
     sb.Append(tabs).Append("\tif (_connection.State != ConnectionState.Open)\r\n");
     sb.Append(tabs).Append("\t\t_connection.Open();\r\n");
     sb.Append(tabs).Append("\treturn _connection;\r\n");
     sb.Append(tabs).Append("}\r\n\r\n");
     sb.Append(tabs).Append("public static SqlCommand GetCommand()\r\n");
     sb.Append(tabs).Append("{\r\n");
     sb.Append(tabs).Append("\t").Append("return new SqlCommand(\"\",GetConnection());\r\n");
     sb.Append(tabs).Append("}\r\n");
     sb.Append(new String('\t', config.TabCount)).Append("}\r\n");
 }
Example #31
0
    public override void RenderFactory(StringBuilder sb, RenderConfig config)
    {

        string tabs = new string('\t', config.TabCount);

        sb.AppendFormat(TemplateComment, tabs, Summary);
        sb.AppendFormat("{0}public static partial class {1}\r\n", tabs, string.Format(config.FormatFactory, Name));
        sb.Append(tabs).Append("{\r\n ");

        config.TabCount++;
        RenderFactoryMethod(sb, config);
        config.TabCount--;
        sb.Append("\r\n").Append(tabs).Append("}\r\n");

        sb.Append("\r\n");
    }
Example #32
0
        /// <summary>
        /// Creates instance of the renderer.
        /// </summary>
        /// <param name="doc">The render document, to render content.</param>
        public Renderer(RenderDocument doc)
        {
            m_RenderDoc = doc;
            m_Config = new RenderConfig(this);

            var xnaWindow = (Form)Control.FromHandle(this.Window.Handle);
            xnaWindow.GotFocus += (object sender, EventArgs e) =>
            {
                (sender as Form).Visible = false;
                
            };

            m_RasterizerState_Solid.CullMode = CullMode.CullClockwiseFace;
            m_RasterizerState_Solid.FillMode = FillMode.Solid;
            m_RasterizerState_Wireframe.CullMode = CullMode.None;
            m_RasterizerState_Wireframe.FillMode = FillMode.WireFrame;
            m_RasterizerState_Wireframe.DepthBias = -0.000001f; 

            m_DepthStencilState.DepthBufferWriteEnable = true;
            m_DepthStencilState.DepthBufferEnable = true;
            m_DepthStencilState.DepthBufferFunction = CompareFunction.LessEqual;

            m_WireframeDepthStencilState.DepthBufferEnable = false;
            m_WireframeDepthStencilState.DepthBufferWriteEnable = false;
            m_WireframeDepthStencilState.DepthBufferFunction = CompareFunction.Always;
            

            m_Graphics = new GraphicsDeviceManager(this)
            {
                PreferredBackBufferWidth = m_RenderDoc.ClientSize.Width,
                PreferredBackBufferHeight = m_RenderDoc.ClientSize.Height
            };

            m_Graphics.PreparingDeviceSettings += OnGraphicsPreparingDeviceSettings;
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
        }
 public static System.Drawing.Point TransposePoint(VoronoiAlgorithms.Models.Point p, RenderConfig config)
 {
     return(new System.Drawing.Point((int)(p.x + config.xPadding + config.xOffset), (int)(p.y + config.yPadding + config.yOffset)));
 }
Example #34
0
    public override void RenderEntity(StringBuilder sb, RenderConfig config)
    {
        string tabs = new string('\t', config.TabCount);

        sb.AppendFormat("{0}/// <summary>\r\n", tabs);
        sb.AppendFormat("{0}/// {1}\r\n", tabs, Summary);
        sb.AppendFormat("{0}/// </summary>\r\n", tabs);
        sb.AppendFormat("{0}public partial class {1}\r\n", tabs, string.Format(config.FormatEntity, Name));
        sb.Append(tabs).Append("{\r\n ");

        config.TabCount++;
        foreach (Column item in Columns)
        {
            item.RenderEntity(sb, config);
        }
        config.TabCount--;

        sb.Append(tabs).Append(" }\r\n");

        sb.Append("\r\n");
    }
Example #35
0
 public void RenderFactory(StringBuilder sb, RenderConfig config, List<Table> tables)
 {
     foreach (Table table in tables)
     {
         table.RenderFactory(sb, config);
     }
 }
Example #36
0
    public virtual void RenderFactory(StringBuilder sb, RenderConfig config)
    {

    }
Example #37
0
    public virtual void RenderEntity(StringBuilder sb, RenderConfig config)
    {

    }
Example #38
0
    private void RenderFactoryMethod(StringBuilder sb, RenderConfig config)
    {
        string tabs = new string('\t', config.TabCount);
        string tabsItem = new string('\t', config.TabCount + 1);


        List<Column> columnsIdentity = new List<Column>();
        List<Column> columnsNotIdentity = new List<Column>();
        List<Column> columnsPrimary = new List<Column>();
        foreach (Column item in Columns)
        {
            if (item.IsIdentity)
                columnsIdentity.Add(item);
            else
                columnsNotIdentity.Add(item);
            if (item.IsPrimaryKey)
                columnsPrimary.Add(item);
        }


        #region Insert

        sb.AppendFormat(TemplateComment, tabs, "添加");
        sb.AppendFormat("{0}public static {1} {2}({3} model)\r\n",
            tabs,
            columnsIdentity.Count == 1 ? "decimal" : "int",
            string.Format(config.FormatFactoryPropery, "Insert"),
            string.Format(config.FormatEntity, Name));
        sb.Append(tabs).Append("{\r\n");

        sb.Append(tabsItem).Append("SqlCommand cmd = BaseConnection.GetCommand();\r\n");
        sb.Append(tabsItem).Append("List<string> sqlColumnName = new List<string>();\r\n");
        sb.Append(tabsItem).Append("List<string> sqlColumnValue = new List<string>();\r\n");

        bool first = true;

        foreach (Column item in columnsNotIdentity)
        {
            if (item.IsNull)
            {
                sb.Append(tabsItem).AppendFormat("if(model.{0} != null)\r\n",string.Format(config.FormatEntityProperty, item.Name));
                sb.Append(tabsItem).Append("{\r\n");
                sb.Append(tabsItem).Append("\t").AppendFormat("sqlColumnName.Add(\"{0}\");\r\n",  item.Name);
                sb.Append(tabsItem).Append("\t").AppendFormat("sqlColumnValue.Add(\"@{0}\");\r\n", item.Name);
                sb.Append(tabsItem).Append("\t").AppendFormat("cmd.Parameters.Add(\"{0}\",model.{1});\r\n", item.Name,string.Format(config.FormatEntityProperty,item.Name));
                sb.Append(tabsItem).Append("}\r\n");
            }
            else
            {
                sb.Append(tabsItem).AppendFormat("sqlColumnName.Add(\"{0}\");\r\n", item.Name);
                sb.Append(tabsItem).AppendFormat("sqlColumnValue.Add(\"@{0}\");\r\n", item.Name);
                sb.Append(tabsItem).Append("\t").AppendFormat("cmd.Parameters.Add(\"{0}\",model.{1});\r\n", item.Name,string.Format(config.FormatEntityProperty,item.Name));
            }
        }

        sb.Append(tabs)
            .Append(" cmd.CommandText = string.Format(\"insert into [" + Name +
                    "] ({0})values({1});" + (columnsIdentity.Count == 1 ? "select @@identity;" : "") +
                    "\", String.Join(\",\",sqlColumnName),String.Join(\",\",sqlColumnValue));\r\n");
        
        if (columnsIdentity.Count == 1)
        {
            sb.Append(tabsItem).Append("return (decimal)cmd.ExecuteScalar();\r\n");
        }
        else
        {
            sb.Append(tabsItem).Append("return cmd.ExecuteNonQuery();\r\n");
        }
        
        sb.Append(tabs).Append("}\r\n");

        #endregion


        #region update

        sb.AppendFormat(TemplateComment, tabs, "修改");
        sb.AppendFormat("{0}public static {1} {2}({3} model)\r\n",
            tabs,
            columnsIdentity.Count == 1 ? "decimal" : "int",
            string.Format(config.FormatFactoryPropery, "Insert"),
            string.Format(config.FormatEntity, Name));
        sb.Append(tabs).Append("{\r\n");

        sb.Append(tabs).Append("}\r\n");



        #endregion

    }
Example #39
0
    public void Render(StringBuilder sb, RenderConfig config)
    {
        string tabs = new string('\t', config.TabCount);
        sb.Append(tabs).Append("using System;\r\n");
        sb.Append(tabs).Append("using System.Data;\r\n");
        sb.Append(tabs).Append("using System.Data.SqlClient;\r\n");
        sb.Append(tabs).Append("using System.Collections.Generic;\r\n");

        new RenderBase().RenderFactoryBase(sb, config);

        RenderEntity(sb, config, GetTables());
        RenderFactory(sb, config, GetTables());
    }
Example #40
0
    public override void RenderEntity(StringBuilder sb, RenderConfig config)
    {
        string tabs = new string('\t', config.TabCount);

        sb.AppendFormat(TemplateComment, tabs, Summary);
        sb.AppendFormat("{0}public {1} {2}", tabs, GetColumnType(), string.Format(config.FormatEntityProperty, Name));
        sb.Append(" ").Append("{ get; set; }\r\n");

        sb.Append("\r\n");
    }