Ejemplo n.º 1
0
        // <param name="mousePosition">mouse position in window coordinate system.</param>
        /// <summary>
        ///
        /// </summary>
        /// <param name="renderMode"></param>
        /// <param name="clientRectangle"></param>
        /// <param name="autoClear"></param>
        /// <param name="pickingGeometryType"></param>
        public void Render(RenderModes renderMode, Rectangle clientRectangle,
                           //Point mousePosition,
                           bool autoClear = true,
                           GeometryType pickingGeometryType = GeometryType.Point)
        {
            var arg = new RenderEventArgs(renderMode, clientRectangle, this.Camera, pickingGeometryType);

            lock (this.synObj)
            {
                if (autoClear)
                {
                    vec4 clearColor = this.ClearColor.ToVec4();
                    OpenGL.ClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);

                    OpenGL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT);
                }
                // render objects.
                SceneObject obj = this.RootObject;
                this.RenderObject(obj, arg);

                // render regular UI.
                this.UIRoot.Render(arg);

                //// render cursor.
                //UICursor cursor = this.Cursor;
                //if (cursor != null && cursor.Enabled)
                //{
                //    cursor.UpdatePosition(mousePosition);
                //    this.cursorRoot.Render(arg);
                //}
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderEventArgs"/> class.
 /// </summary>
 /// <param name="renderMode">render mode.</param>
 /// <param name="viewport"></param>
 /// <param name="camera">camera used during rendering.</param>
 /// <param name="pickingGeometryType">Target geometry type(point, line, triangle, quad or polygon) for color-coded-picking when <paramref name="renderMode"/> is <see cref="RenderModes.ColorCodedPicking"/>; otherwise useless.</param>
 public RenderEventArgs(RenderModes renderMode, Rectangle viewport, ICamera camera, GeometryType pickingGeometryType = GeometryType.Point)
 {
     this.RenderMode          = renderMode;
     this.CanvasRect          = viewport;
     this.Camera              = camera;
     this.PickingGeometryType = pickingGeometryType;
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderEventArg"/> class.
 /// </summary>
 /// <param name="renderMode">render mode.</param>
 /// <param name="camera">camera used during rendering.</param>
 /// <param name="pickingGeometryType">Target geometry type(point, line, triangle, quad or polygon) for color-coded-picking when <paramref name="renderMode"/> is <see cref="RenderModes.ColorCodedPicking"/>; otherwise useless.</param>
 public RenderEventArg(RenderModes renderMode, Rectangle viewport, ICamera camera, GeometryType pickingGeometryType = GeometryType.Point)
 {
     this.RenderMode = renderMode;
     this.CanvasRect = viewport;
     this.Camera = camera;
     this.PickingGeometryType = pickingGeometryType;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// This simulates BoundingVolume's render method.
 /// </summary>
 /// <param name="renderMode"></param>
 private void QuadsDraw(RenderModes renderMode)
 {
     OpenGL.Begin(DrawMode.Quads);
     OpenGL.Vertex3f(MaxPosition.x, MaxPosition.y, MinPosition.z); // Top Right Of The Quad (Top)
     OpenGL.Vertex3f(MinPosition.x, MaxPosition.y, MinPosition.z); // Top Left Of The Quad (Top)
     OpenGL.Vertex3f(MinPosition.x, MaxPosition.y, MaxPosition.z); // Bottom Left Of The Quad (Top)
     OpenGL.Vertex3f(MaxPosition.x, MaxPosition.y, MaxPosition.z); // Bottom Right Of The Quad (Top)
     OpenGL.Vertex3f(MaxPosition.x, MinPosition.y, MaxPosition.z); // Top Right Of The Quad (Bottom)
     OpenGL.Vertex3f(MinPosition.x, MinPosition.y, MaxPosition.z); // Top Left Of The Quad (Bottom)
     OpenGL.Vertex3f(MinPosition.x, MinPosition.y, MinPosition.z); // Bottom Left Of The Quad (Bottom)
     OpenGL.Vertex3f(MaxPosition.x, MinPosition.y, MinPosition.z); // Bottom Right Of The Quad (Bottom)
     OpenGL.Vertex3f(MaxPosition.x, MaxPosition.y, MaxPosition.z); // Top Right Of The Quad (Front)
     OpenGL.Vertex3f(MinPosition.x, MaxPosition.y, MaxPosition.z); // Top Left Of The Quad (Front)
     OpenGL.Vertex3f(MinPosition.x, MinPosition.y, MaxPosition.z); // Bottom Left Of The Quad (Front)
     OpenGL.Vertex3f(MaxPosition.x, MinPosition.y, MaxPosition.z); // Bottom Right Of The Quad (Front)
     OpenGL.Vertex3f(MaxPosition.x, MinPosition.y, MinPosition.z); // Top Right Of The Quad (Back)
     OpenGL.Vertex3f(MinPosition.x, MinPosition.y, MinPosition.z); // Top Left Of The Quad (Back)
     OpenGL.Vertex3f(MinPosition.x, MaxPosition.y, MinPosition.z); // Bottom Left Of The Quad (Back)
     OpenGL.Vertex3f(MaxPosition.x, MaxPosition.y, MinPosition.z); // Bottom Right Of The Quad (Back)
     OpenGL.Vertex3f(MinPosition.x, MaxPosition.y, MaxPosition.z); // Top Right Of The Quad (Left)
     OpenGL.Vertex3f(MinPosition.x, MaxPosition.y, MinPosition.z); // Top Left Of The Quad (Left)
     OpenGL.Vertex3f(MinPosition.x, MinPosition.y, MinPosition.z); // Bottom Left Of The Quad (Left)
     OpenGL.Vertex3f(MinPosition.x, MinPosition.y, MaxPosition.z); // Bottom Right Of The Quad (Left)
     OpenGL.Vertex3f(MaxPosition.x, MaxPosition.y, MinPosition.z); // Top Right Of The Quad (Right)
     OpenGL.Vertex3f(MaxPosition.x, MaxPosition.y, MaxPosition.z); // Top Left Of The Quad (Right)
     OpenGL.Vertex3f(MaxPosition.x, MinPosition.y, MaxPosition.z); // Bottom Left Of The Quad (Right)
     OpenGL.Vertex3f(MaxPosition.x, MinPosition.y, MinPosition.z); // Bottom Right Of The Quad (Right)
     OpenGL.End();
 }
Ejemplo n.º 5
0
        private void RenderersDraw(RenderModes renderMode, bool renderScene = true, bool renderUI = true)
        {
            var arg = new RenderEventArgs(renderMode, this.glCanvas1.ClientRectangle, this.camera, this.PickingGeometryType);

            if (renderMode == RenderModes.ColorCodedPicking)
            {
                if (renderScene)
                {
                    ColorCodedPicking.Render4Picking(arg, this.rendererDict[this.selectedModel].PickableRenderer);
                }
            }
            else if (renderMode == RenderModes.Render)
            {
                OpenGL.ClearColor(ClearColor.R / 255.0f, ClearColor.G / 255.0f, ClearColor.B / 255.0f, ClearColor.A / 255.0f);

                OpenGL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT);

                if (renderScene)
                {
                    SceneRenderersDraw(arg);
                }
                if (renderUI)
                {
                    UIRenderersDraw(arg);
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// This simulates BoundingVolume's render method.
 /// </summary>
 /// <param name="renderMode"></param>
 private void QuadsDraw(RenderModes renderMode)
 {
     GL.Begin(PrimitiveModes.Quads);
     GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z); // Top Right Of The Quad (Top)
     GL.Vertex(minPosition.x, maxPosition.y, minPosition.z); // Top Left Of The Quad (Top)
     GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z); // Bottom Left Of The Quad (Top)
     GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z); // Bottom Right Of The Quad (Top)
     GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z); // Top Right Of The Quad (Bottom)
     GL.Vertex(minPosition.x, minPosition.y, maxPosition.z); // Top Left Of The Quad (Bottom)
     GL.Vertex(minPosition.x, minPosition.y, minPosition.z); // Bottom Left Of The Quad (Bottom)
     GL.Vertex(maxPosition.x, minPosition.y, minPosition.z); // Bottom Right Of The Quad (Bottom)
     GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z); // Top Right Of The Quad (Front)
     GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z); // Top Left Of The Quad (Front)
     GL.Vertex(minPosition.x, minPosition.y, maxPosition.z); // Bottom Left Of The Quad (Front)
     GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z); // Bottom Right Of The Quad (Front)
     GL.Vertex(maxPosition.x, minPosition.y, minPosition.z); // Top Right Of The Quad (Back)
     GL.Vertex(minPosition.x, minPosition.y, minPosition.z); // Top Left Of The Quad (Back)
     GL.Vertex(minPosition.x, maxPosition.y, minPosition.z); // Bottom Left Of The Quad (Back)
     GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z); // Bottom Right Of The Quad (Back)
     GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z); // Top Right Of The Quad (Left)
     GL.Vertex(minPosition.x, maxPosition.y, minPosition.z); // Top Left Of The Quad (Left)
     GL.Vertex(minPosition.x, minPosition.y, minPosition.z); // Bottom Left Of The Quad (Left)
     GL.Vertex(minPosition.x, minPosition.y, maxPosition.z); // Bottom Right Of The Quad (Left)
     GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z); // Top Right Of The Quad (Right)
     GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z); // Top Left Of The Quad (Right)
     GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z); // Bottom Left Of The Quad (Right)
     GL.Vertex(maxPosition.x, minPosition.y, minPosition.z); // Bottom Right Of The Quad (Right)
     GL.End();
 }
Ejemplo n.º 7
0
        public override void Render(RenderModes renderMode)
        {
            BeforeRendering(renderMode);

            GL.BindVertexArray(vao[0]);

            GL.BindVertexArray(0);

            AfterRendering(renderMode);
        }
Ejemplo n.º 8
0
 public void Render(RenderModes renderMode, Rectangle clientRectangle)
 {
     var arg = new RenderEventArgs(renderMode, clientRectangle, this.Camera);
     var list = this.ObjectList.ToArray();
     foreach (var item in list)
     {
         item.Render(arg);
     }
     this.UIRoot.Render(arg);
 }
Ejemplo n.º 9
0
        public override void Render(RenderModes renderMode)
        {
            BeforeRendering(renderMode);

            GL.BindVertexArray(vao[0]);

            GL.BindVertexArray(0);

            AfterRendering(renderMode);
        }
Ejemplo n.º 10
0
        public ActionResult Thumb(int id, int width = 0, int height = 0, RenderModes mode = RenderModes.RenderMode_Fit, int trace = 0)
        {
            StringBuilder message = new StringBuilder();

            try
            {
                if (width <= 120 && height <= 120)
                {
                    byte[] cache = HttpRuntime.Cache.GetOrAddSliding(
                        string.Format("thumb_image_{0}_{1}x{2}_{3}", id, width, height, (int)mode),
                        () => {
                        byte [] img = db.Contents.Find(id).Data;
                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(img))
                            {
                                MediaController.WriteImage(src, trg, width, height, mode);
                                return(trg.GetBuffer());
                            }
                    },
                        TimeSpan.FromHours(1)
                        );

                    return(new FileStreamResult(new MemoryStream(cache), "image/png"));
                }

                else
                {
                    byte [] img = db.Contents.Find(id).Data;
                    using (MemoryStream src = new MemoryStream(img))
                    {
                        MemoryStream trg = new MemoryStream();
                        MediaController.WriteImage(src, trg, width, height, mode);
                        return(new FileStreamResult(trg, "image/png"));
                    }
                }
            }

            catch (Exception ex)
            {
                if (trace > 0)
                {
                    message.Append(ex.ToString());
                }
            }

            if (trace == 0)
            {
                return(RedirectToAction("BadImg"));
            }
            else
            {
                return(Content(message.Length == 0 ? "OK" : message.ToString()));
            }
        }
Ejemplo n.º 11
0
        public Form18PickingInScene()
        {
            InitializeComponent();

            this.glCanvas1.OpenGLDraw += glCanvas1_OpenGLDraw;
            this.glCanvas1.KeyPress   += glCanvas1_KeyPress;

            this.RenderMode = RenderModes.Render;

            Application.Idle += Application_Idle;
            OpenGL.ClearColor(0x87 / 255.0f, 0xce / 255.0f, 0xeb / 255.0f, 0xff / 255.0f);
        }
Ejemplo n.º 12
0
    private void OnMyEnable()
    {
        TMProFontCustomizedCreater.CustomizedCreaterSettings settings =
            TMProFontCustomizedCreater.GetCustomizedCreaterSettings();

        // 以字体做索引,相同的字体只会生成一次字体纹理
        string str1 = "t:Font";

        string[] fonts = AssetDatabase.FindAssets(str1, new[] { settings.fontFolderPath });

        m_FontAssetInfos.Clear();
        foreach (var font in fonts)
        {
            FontAssetInfo info = new FontAssetInfo();
            info.fontPath = AssetDatabase.GUIDToAssetPath(font);
            info.fontName = Path.GetFileNameWithoutExtension(info.fontPath);

            List <string> assetPaths = new List <string>();
            str1 = "t:TMP_FontAsset " + info.fontName + " SDF";
            var assets = AssetDatabase.FindAssets(str1, new[] { settings.fontMaterialsFolderPath });
            foreach (var asset in assets)
            {
                assetPaths.Add(AssetDatabase.GUIDToAssetPath(asset));
            }

            if (assetPaths.Count > 0)
            {
                info.assets = assetPaths.ToArray();
                m_FontAssetInfos.Add(info);
            }
        }

        m_PointSizeSamplingMode = settings.pointSizeSamplingMode;
        m_PointSize             = settings.pointSize;
        m_Padding     = settings.padding;
        m_PackingMode = (FontPackingModes)settings.packingMode;
        m_AtlasWidth  = settings.atlasWidth;
        m_AtlasHeight = settings.atlasHeight;
        m_CharacterSetSelectionMode = settings.characterSetSelectionMode;
        m_CharacterSequenceFile     = settings.characterSequenceFile;
        m_FontStyle              = (FaceStyles)settings.fontStyle;
        m_FontStyleValue         = settings.fontStyleModifier;
        m_RenderMode             = (RenderModes)settings.renderMode;
        m_IncludeKerningPairs    = settings.includeFontFeatures;
        m_FontBackupPaths        = settings.fontBackupPaths;
        m_CharacterUseFontBackup = settings.characterUseFontBackup;

        if (string.IsNullOrEmpty(m_WarningMessage) || m_SelectedFontAsset || m_LegacyFontAsset || m_SavedFontAtlas || m_IsFontAtlasInvalid)
        {
            // 仅为了去除警告
        }
    }
Ejemplo n.º 13
0
 public static int RenderToInt(RenderModes value)
 {
     switch (value)
     {
         case RenderModes.Buddhabrot:
             return 1;
         case RenderModes.AntiBuddhabrot:
             return 2;
         case RenderModes.StarField:
             return 3;
         case RenderModes.Mandelbrot:
             return 4;
         default:
             throw new Exception();
     }
 }
        private string[] UpdateShaderList(RenderModes mode, out Shader[] shaders)
        {
            string str = "t:Shader TMP_";

            str = ((mode != RenderModes.DistanceField16 && mode != RenderModes.DistanceField32) ? (str + " Bitmap") : (str + " SDF"));
            string[] array  = AssetDatabase.FindAssets(str);
            string[] array2 = new string[array.Length];
            shaders = new Shader[array.Length];
            for (int i = 0; i < array.Length; i++)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(array[i]);
                Shader shader    = AssetDatabase.LoadAssetAtPath <Shader>(assetPath);
                shaders[i] = shader;
                string text = shader.name.Replace("TextMeshPro/", "");
                text = (array2[i] = text.Replace("Mobile/", "Mobile - "));
            }
            return(array2);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Render to the provided instance of GL.
        /// </summary>
        /// <param name="renderMode">The render mode.</param>
        public virtual void Render(RenderModes renderMode)
        {
            //  Push attributes, disable lighting.
            GL.PushAttrib(GL.GL_CURRENT_BIT | GL.GL_ENABLE_BIT |
                          GL.GL_LINE_BIT | GL.GL_POLYGON_BIT);
            GL.Disable(GL.GL_LIGHTING);
            GL.Disable(GL.GL_TEXTURE_2D);
            GL.LineWidth(1.0f);
            GL.Color(BoxColor);

            //QuadsDraw(gl);

            //GL.Color(1.0f, 0, 0);
            GL.Begin(PrimitiveModes.LineLoop);
            GL.Vertex(MinPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MinPosition.y, MaxPosition.z);
            GL.End();

            //GL.Color(0, 1.0f, 0);
            GL.Begin(PrimitiveModes.LineLoop);
            GL.Vertex(MinPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MaxPosition.y, MaxPosition.z);
            GL.End();

            //GL.Color(0, 0, 1.0f);
            GL.Begin(PrimitiveModes.Lines);
            GL.Vertex(MinPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MinPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MaxPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MinPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MaxPosition.y, MaxPosition.z);
            GL.End();

            GL.PopAttrib();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// This simulates BoundingVolume's render method.
        /// </summary>
        /// <param name="gl"></param>
        /// <param name="renderMode"></param>
        private void QuadsDraw(RenderModes renderMode)
        {
            //  Push attributes, disable lighting.
            GL.PushAttrib(GL.GL_CURRENT_BIT | GL.GL_ENABLE_BIT |
                          GL.GL_LINE_BIT | GL.GL_POLYGON_BIT);
            GL.Disable(GL.GL_LIGHTING);
            GL.Disable(GL.GL_TEXTURE_2D);
            GL.LineWidth(1.0f);
            GL.PolygonMode(GL.GL_FRONT_AND_BACK,
                           renderMode == RenderModes.HitTest ? (uint)PolygonModes.Filled : (uint)PolygonModes.Lines);

            GL.Begin(PrimitiveModes.Quads);
            GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z); //GL.Vertex(hhl);	// Top Right Of The Quad (Top)
            GL.Vertex(minPosition.x, maxPosition.y, minPosition.z); //GL.Vertex(lhl);	// Top Left Of The Quad (Top)
            GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z); //GL.Vertex(lhh);	// Bottom Left Of The Quad (Top)
            GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z); //GL.Vertex(hhh);	// Bottom Right Of The Quad (Top)
            GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z); //GL.Vertex(hlh);	// Top Right Of The Quad (Bottom)
            GL.Vertex(minPosition.x, minPosition.y, maxPosition.z); //GL.Vertex(llh);	// Top Left Of The Quad (Bottom)
            GL.Vertex(minPosition.x, minPosition.y, minPosition.z); //GL.Vertex(lll);	// Bottom Left Of The Quad (Bottom)
            GL.Vertex(maxPosition.x, minPosition.y, minPosition.z); //GL.Vertex(hll);	// Bottom Right Of The Quad (Bottom)
            GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z); //GL.Vertex(hhh);	// Top Right Of The Quad (Front)
            GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z); //GL.Vertex(lhh);	// Top Left Of The Quad (Front)
            GL.Vertex(minPosition.x, minPosition.y, maxPosition.z); //GL.Vertex(llh);	// Bottom Left Of The Quad (Front)
            GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z); //GL.Vertex(hlh);	// Bottom Right Of The Quad (Front)
            GL.Vertex(maxPosition.x, minPosition.y, minPosition.z); //GL.Vertex(hll);	// Top Right Of The Quad (Back)
            GL.Vertex(minPosition.x, minPosition.y, minPosition.z); //GL.Vertex(lll);	// Top Left Of The Quad (Back)
            GL.Vertex(minPosition.x, maxPosition.y, minPosition.z); //GL.Vertex(lhl);	// Bottom Left Of The Quad (Back)
            GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z); //GL.Vertex(hhl);	// Bottom Right Of The Quad (Back)
            GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z); //GL.Vertex(lhh);	// Top Right Of The Quad (Left)
            GL.Vertex(minPosition.x, maxPosition.y, minPosition.z); //GL.Vertex(lhl);	// Top Left Of The Quad (Left)
            GL.Vertex(minPosition.x, minPosition.y, minPosition.z); //GL.Vertex(lll);	// Bottom Left Of The Quad (Left)
            GL.Vertex(minPosition.x, minPosition.y, maxPosition.z); //GL.Vertex(llh);	// Bottom Right Of The Quad (Left)
            GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z); //GL.Vertex(hhl);	// Top Right Of The Quad (Right)
            GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z); //GL.Vertex(hhh);	// Top Left Of The Quad (Right)
            GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z); //GL.Vertex(hlh);	// Bottom Left Of The Quad (Right)
            GL.Vertex(maxPosition.x, minPosition.y, minPosition.z); //GL.Vertex(hll);	// Bottom Right Of The Quad (Right)
            GL.End();

            GL.PopAttrib();
        }
Ejemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="renderMode"></param>
        /// <param name="clientRectangle"></param>
        /// <param name="mousePosition">mouse position in window coordinate system.</param>
        public void Render(RenderModes renderMode, Rectangle clientRectangle, Point mousePosition)
        {
            var arg = new RenderEventArgs(renderMode, clientRectangle, this.Camera);

            // render objects.
            {
                SceneRootObject rootObject = this.RootObject;
                this.RenderObject(rootObject, arg);
            }

            // render regular UI.
            this.UIRoot.Render(arg);

            // render cursor.
            UICursor cursor = this.Cursor;

            if (cursor.Enabled)
            {
                cursor.UpdatePosition(mousePosition);
                this.cursorRoot.Render(arg);
            }
        }
Ejemplo n.º 18
0
        // TODO: move to separate file
        public static void WriteImage(Stream inStream, Stream outStream, int panelWidth, int panelHeight, RenderModes mode)
        {
            Bitmap bmpSrc = null, bmpTrg = null;

            try
            {
                inStream.Position = 0;
                bmpSrc            = new Bitmap(inStream);

                // convert TIFF to BMP, use only the first page
                FrameDimension fd = new FrameDimension(bmpSrc.FrameDimensionsList[0]);
                bmpSrc.SelectActiveFrame(fd, 0);

                // crop/fit/stretch
                int imageHeight = bmpSrc.Height, imageWidth = bmpSrc.Width, targetWidth, targetHeight;

                if (panelWidth <= 0)
                {
                    panelWidth = imageWidth;
                }
                if (panelHeight <= 0)
                {
                    panelHeight = imageHeight;
                }

                if (panelWidth != imageWidth || panelHeight != imageHeight)
                {
                    switch (mode)
                    {
                    case RenderModes.RenderMode_Stretch:
                        if (panelWidth <= 120 && panelHeight <= 120)
                        {
                            bmpTrg = new Bitmap(bmpSrc.GetThumbnailImage(panelWidth, panelHeight, () => false, IntPtr.Zero));
                        }
                        else
                        {
                            bmpTrg = new Bitmap(bmpSrc, new Size(panelWidth, panelHeight));
                        }
                        break;

                    case RenderModes.RenderMode_Fit:
                        targetWidth  = imageWidth;
                        targetHeight = imageHeight;
                        float scale = 1F;
                        // a. panel is greater than image: grow
                        if (panelHeight > imageHeight && panelWidth > imageWidth)
                        {
                            scale        = Math.Min((float)panelWidth / imageWidth, (float)panelHeight / imageHeight);
                            targetHeight = Math.Min((int)((float)imageHeight * scale), panelHeight);
                            targetWidth  = Math.Min((int)((float)imageWidth * scale), panelWidth);
                        }
                        // b. image is greater than panel: shrink
                        else
                        {
                            scale        = Math.Max((float)imageWidth / panelWidth, (float)imageHeight / panelHeight);
                            targetWidth  = Math.Min((int)((float)imageWidth / scale), panelWidth);
                            targetHeight = Math.Min((int)((float)imageHeight / scale), panelHeight);
                        }
                        if (targetWidth <= 120 && targetHeight <= 120)
                        {
                            bmpTrg = new Bitmap(bmpSrc.GetThumbnailImage(targetWidth, targetHeight, () => false, IntPtr.Zero));
                        }
                        else
                        {
                            bmpTrg = new Bitmap(bmpSrc, new Size(targetWidth, targetHeight));
                        }
                        break;

                    case RenderModes.RenderMode_Crop:
                        targetWidth  = Math.Min(panelWidth, imageWidth);
                        targetHeight = Math.Min(panelHeight, imageHeight);
                        bmpTrg       = bmpSrc.Clone(
                            new Rectangle(0, 0, targetWidth, targetHeight),
                            bmpSrc.PixelFormat
                            );
                        break;
                    }

                    bmpTrg.Save(outStream, ImageFormat.Png);
                }
                else
                {
                    bmpSrc.Save(outStream, ImageFormat.Png);
                }

                outStream.Seek(0, SeekOrigin.Begin);
            }

            finally
            {
                if (bmpTrg != null)
                {
                    bmpTrg.Dispose();
                }
                if (bmpSrc != null)
                {
                    bmpSrc.Dispose();
                }
                GC.Collect();
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderEventArgs"/> class.
 /// </summary>
 /// <param name="renderMode">渲染模式</param>
 /// <param name="camera">渲染时所用的camera</param>
 public RenderEventArgs(RenderModes renderMode, ICamera camera)
 {
     this.RenderMode = renderMode;
     this.Camera     = camera;
 }
Ejemplo n.º 20
0
        private static Texture2D CreateFontTexture(int atlasWidth, int altasHeight, byte[] textureBuffer, RenderModes fontRenderMode)
        {
            var fontTexture = new Texture2D(atlasWidth, altasHeight, TextureFormat.Alpha8, mipmap: false, linear: true);

            Color32[] colors = new Color32[atlasWidth * altasHeight];
            for (int i = 0; i < (atlasWidth * altasHeight); i++)
            {
                byte c = textureBuffer[i];
                colors[i] = new Color32(c, c, c, c);
            }

            if (fontRenderMode == RenderModes.RasterHinted)
            {
                fontTexture.filterMode = FilterMode.Point;
            }

            fontTexture.SetPixels32(colors, miplevel: 0);
            fontTexture.Apply(updateMipmaps: false, makeNoLongerReadable: false);
            return(fontTexture);
        }
Ejemplo n.º 21
0
 public abstract void AfterRendering(RenderModes renderMode);
Ejemplo n.º 22
0
 /// <summary>
 /// This simulates BoundingVolume's render method.
 /// </summary>
 /// <param name="renderMode"></param>
 private void QuadsDraw(RenderModes renderMode)
 {
     GL.Begin(PrimitiveModes.Quads);
     GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z);// Top Right Of The Quad (Top)
     GL.Vertex(minPosition.x, maxPosition.y, minPosition.z);// Top Left Of The Quad (Top)
     GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z);// Bottom Left Of The Quad (Top)
     GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z);// Bottom Right Of The Quad (Top)
     GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z);// Top Right Of The Quad (Bottom)
     GL.Vertex(minPosition.x, minPosition.y, maxPosition.z);// Top Left Of The Quad (Bottom)
     GL.Vertex(minPosition.x, minPosition.y, minPosition.z);// Bottom Left Of The Quad (Bottom)
     GL.Vertex(maxPosition.x, minPosition.y, minPosition.z);// Bottom Right Of The Quad (Bottom)
     GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z);// Top Right Of The Quad (Front)
     GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z);// Top Left Of The Quad (Front)
     GL.Vertex(minPosition.x, minPosition.y, maxPosition.z);// Bottom Left Of The Quad (Front)
     GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z);// Bottom Right Of The Quad (Front)
     GL.Vertex(maxPosition.x, minPosition.y, minPosition.z);// Top Right Of The Quad (Back)
     GL.Vertex(minPosition.x, minPosition.y, minPosition.z);// Top Left Of The Quad (Back)
     GL.Vertex(minPosition.x, maxPosition.y, minPosition.z);// Bottom Left Of The Quad (Back)
     GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z);// Bottom Right Of The Quad (Back)
     GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z);// Top Right Of The Quad (Left)
     GL.Vertex(minPosition.x, maxPosition.y, minPosition.z);// Top Left Of The Quad (Left)
     GL.Vertex(minPosition.x, minPosition.y, minPosition.z);// Bottom Left Of The Quad (Left)
     GL.Vertex(minPosition.x, minPosition.y, maxPosition.z);// Bottom Right Of The Quad (Left)
     GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z);// Top Right Of The Quad (Right)
     GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z);// Top Left Of The Quad (Right)
     GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z);// Bottom Left Of The Quad (Right)
     GL.Vertex(maxPosition.x, minPosition.y, minPosition.z);// Bottom Right Of The Quad (Right)
     GL.End();
 }
Ejemplo n.º 23
0
        /// <summary>
        /// This simulates BoundingVolume's render method.
        /// </summary>
        /// <param name="gl"></param>
        /// <param name="renderMode"></param>
        private void QuadsDraw(RenderModes renderMode)
        {
            //  Push attributes, disable lighting.
            GL.PushAttrib(GL.GL_CURRENT_BIT | GL.GL_ENABLE_BIT |
                GL.GL_LINE_BIT | GL.GL_POLYGON_BIT);
            GL.Disable(GL.GL_LIGHTING);
            GL.Disable(GL.GL_TEXTURE_2D);
            GL.LineWidth(1.0f);
            GL.PolygonMode(GL.GL_FRONT_AND_BACK,
                renderMode == RenderModes.HitTest ? (uint)PolygonModes.Filled : (uint)PolygonModes.Lines);

            GL.Begin(PrimitiveModes.Quads);
            GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z);//GL.Vertex(hhl);	// Top Right Of The Quad (Top)
            GL.Vertex(minPosition.x, maxPosition.y, minPosition.z);//GL.Vertex(lhl);	// Top Left Of The Quad (Top)
            GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z);//GL.Vertex(lhh);	// Bottom Left Of The Quad (Top)
            GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z);//GL.Vertex(hhh);	// Bottom Right Of The Quad (Top)
            GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z);//GL.Vertex(hlh);	// Top Right Of The Quad (Bottom)
            GL.Vertex(minPosition.x, minPosition.y, maxPosition.z);//GL.Vertex(llh);	// Top Left Of The Quad (Bottom)
            GL.Vertex(minPosition.x, minPosition.y, minPosition.z);//GL.Vertex(lll);	// Bottom Left Of The Quad (Bottom)
            GL.Vertex(maxPosition.x, minPosition.y, minPosition.z);//GL.Vertex(hll);	// Bottom Right Of The Quad (Bottom)
            GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z);//GL.Vertex(hhh);	// Top Right Of The Quad (Front)
            GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z);//GL.Vertex(lhh);	// Top Left Of The Quad (Front)
            GL.Vertex(minPosition.x, minPosition.y, maxPosition.z);//GL.Vertex(llh);	// Bottom Left Of The Quad (Front)
            GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z);//GL.Vertex(hlh);	// Bottom Right Of The Quad (Front)
            GL.Vertex(maxPosition.x, minPosition.y, minPosition.z);//GL.Vertex(hll);	// Top Right Of The Quad (Back)
            GL.Vertex(minPosition.x, minPosition.y, minPosition.z);//GL.Vertex(lll);	// Top Left Of The Quad (Back)
            GL.Vertex(minPosition.x, maxPosition.y, minPosition.z);//GL.Vertex(lhl);	// Bottom Left Of The Quad (Back)
            GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z);//GL.Vertex(hhl);	// Bottom Right Of The Quad (Back)
            GL.Vertex(minPosition.x, maxPosition.y, maxPosition.z);//GL.Vertex(lhh);	// Top Right Of The Quad (Left)
            GL.Vertex(minPosition.x, maxPosition.y, minPosition.z);//GL.Vertex(lhl);	// Top Left Of The Quad (Left)
            GL.Vertex(minPosition.x, minPosition.y, minPosition.z);//GL.Vertex(lll);	// Bottom Left Of The Quad (Left)
            GL.Vertex(minPosition.x, minPosition.y, maxPosition.z);//GL.Vertex(llh);	// Bottom Right Of The Quad (Left)
            GL.Vertex(maxPosition.x, maxPosition.y, minPosition.z);//GL.Vertex(hhl);	// Top Right Of The Quad (Right)
            GL.Vertex(maxPosition.x, maxPosition.y, maxPosition.z);//GL.Vertex(hhh);	// Top Left Of The Quad (Right)
            GL.Vertex(maxPosition.x, minPosition.y, maxPosition.z);//GL.Vertex(hlh);	// Bottom Left Of The Quad (Right)
            GL.Vertex(maxPosition.x, minPosition.y, minPosition.z);//GL.Vertex(hll);	// Bottom Right Of The Quad (Right)
            GL.End();

            GL.PopAttrib();
        }
Ejemplo n.º 24
0
 public abstract void AfterRendering(RenderModes renderMode);
Ejemplo n.º 25
0
        public async Task <ActionResult> ThumbAsync(int id, int width = 0, int height = 0, RenderModes mode = RenderModes.RenderMode_Fit, string version = "", int trace = 0)
        {
            StringBuilder message = new StringBuilder();

            try
            {
                if (width <= 120 && height <= 120)
                {
                    byte[] cache = await HttpRuntime.Cache.GetOrAddSlidingAsync(
                        string.Format("thumb_image_{0}_{1}x{2}_{3}_{4}", id, width, height, (int)mode, version),
                        async (expire) =>
                    {
                        expire.After = TimeSpan.FromHours(1);
                        var data     = await db.Contents.FindAsync(id);
                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(data.Data))
                            {
                                MediaController.WriteImage(src, trg, width, height, mode);
                                return(trg.GetBuffer());
                            }
                    });

                    return(new FileStreamResult(new MemoryStream(cache), "image/png"));
                }

                else
                {
                    var data = await db.Contents.FindAsync(id);

                    using (MemoryStream src = new MemoryStream(data.Data))
                    {
                        MemoryStream trg = new MemoryStream();
                        MediaController.WriteImage(src, trg, width, height, mode);
                        return(new FileStreamResult(trg, "image/png"));
                    }
                }
            }

            catch (Exception ex)
            {
                if (trace > 0)
                {
                    message.Append(ex.ToString());
                }
            }

            if (trace == 0)
            {
                return(RedirectToAction("BadImg"));
            }
            else
            {
                return(Content(message.Length == 0 ? "OK" : message.ToString()));
            }
        }
        void DrawControls()
        {
            GUILayout.BeginVertical();
            GUILayout.Label("<b>TextMeshPro - Font Asset Creator</b>", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));
            GUILayout.Label("Font Settings", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));

            GUILayout.BeginVertical(TMP_UIStyleManager.TextureAreaBox, GUILayout.Width(300));
            EditorGUIUtility.LookLikeControls(120f, 160f);

            // FONT TTF SELECTION
            font_TTF = EditorGUILayout.ObjectField("Font Source", font_TTF, typeof(Font), false, GUILayout.Width(290)) as Font;

            // FONT SIZING
            if (FontSizingOption_Selection == 0)
            {
                FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(290));
            }
            else
            {
                EditorGUIUtility.LookLikeControls(120f, 40f);
                GUILayout.BeginHorizontal(GUILayout.Width(290));
                FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(225));
                font_size = EditorGUILayout.IntField(font_size);
                GUILayout.EndHorizontal();
            }

            EditorGUIUtility.LookLikeControls(120f, 160f);


            // FONT PADDING
            font_padding = EditorGUILayout.IntField("Font Padding", font_padding, GUILayout.Width(290));
            font_padding = (int)Mathf.Clamp(font_padding, 0f, 64f);

            // FONT PACKING METHOD SELECTION
            m_fontPackingSelection = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_fontPackingSelection, GUILayout.Width(225));

            //font_renderingMode = (FontRenderingMode)EditorGUILayout.EnumPopup("Rendering Mode", font_renderingMode, GUILayout.Width(290));

            // FONT ATLAS RESOLUTION SELECTION
            GUILayout.BeginHorizontal(GUILayout.Width(290));
            GUI.changed = false;
            EditorGUIUtility.LookLikeControls(120f, 40f);

            GUILayout.Label("Atlas Resolution:", GUILayout.Width(116));
            font_atlas_width  = EditorGUILayout.IntPopup(font_atlas_width, FontResolutionLabels, FontAtlasResolutions);  //, GUILayout.Width(80));
            font_atlas_height = EditorGUILayout.IntPopup(font_atlas_height, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));

            GUILayout.EndHorizontal();


            // FONT CHARACTER SET SELECTION
            GUI.changed = false;
            font_CharacterSet_Selection = EditorGUILayout.Popup("Character Set", font_CharacterSet_Selection, FontCharacterSets, GUILayout.Width(290));
            if (GUI.changed)
            {
                characterSequence = "";
                //Debug.Log("Resetting Sequence!");
            }

            switch (font_CharacterSet_Selection)
            {
            case 0:     // ASCII
                //characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
                characterSequence = "32 - 126, 8230";
                break;

            case 1:     // EXTENDED ASCII
                characterSequence = "32 - 126, 161 - 255, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
                break;

            case 2:     // Lowercase
                characterSequence = "32 - 64, 91 - 126";
                break;

            case 3:     // Uppercase
                characterSequence = "32 - 96, 123 - 126";
                break;

            case 4:     // Numbers & Symbols
                characterSequence = "32 - 64, 91 - 96, 123 - 126";
                break;

            case 5:     // Custom Range
                GUILayout.BeginHorizontal(GUILayout.Width(290));
                GUILayout.Label("Custom Range", GUILayout.Width(116));

                // Filter out unwanted characters.
                char chr = Event.current.character;
                if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
                {
                    Event.current.character = '\0';
                }
                characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));

                GUILayout.EndHorizontal();
                break;

            case 6:     // Custom Characters
                GUILayout.BeginHorizontal(GUILayout.Width(290));

                GUILayout.Label("Custom Characters", GUILayout.Width(116));
                characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
                GUILayout.EndHorizontal();
                break;

            case 7:     // Character List from File
                characterList = EditorGUILayout.ObjectField("Character File", characterList, typeof(TextAsset), false, GUILayout.Width(290)) as TextAsset;
                if (characterList != null)
                {
                    characterSequence = characterList.text;
                }
                break;
            }

            EditorGUIUtility.LookLikeControls(120f, 40f);

            // FONT STYLE SELECTION
            GUILayout.BeginHorizontal(GUILayout.Width(290));
            font_style     = (FaceStyles)EditorGUILayout.EnumPopup("Font Style:", font_style, GUILayout.Width(225));
            font_style_mod = EditorGUILayout.IntField((int)font_style_mod);
            GUILayout.EndHorizontal();

            // Render Mode Selection
            font_renderMode = (RenderModes)EditorGUILayout.EnumPopup("Font Render Mode:", font_renderMode, GUILayout.Width(290));

            includeKerningPairs = EditorGUILayout.Toggle("Get Kerning Pairs?", includeKerningPairs, GUILayout.MaxWidth(290));

            EditorGUIUtility.LookLikeControls(120f, 160f);

            GUILayout.Space(20);

            GUI.enabled = font_TTF == null || isProcessing ? false : true;    // Enable Preview if we are not already rendering a font.
            if (GUILayout.Button("Generate Font Atlas", GUILayout.Width(290)) && characterSequence.Length != 0 && GUI.enabled)
            {
                if (font_TTF != null)
                {
                    int error_Code;

                    error_Code = TMPro_FontPlugin.Initialize_FontEngine(); // Initialize Font Engine
                    if (error_Code != 0)
                    {
                        if (error_Code == 99)
                        {
                            //Debug.Log("Font Library was already initialized!");
                            error_Code = 0;
                        }
                        else
                        {
                            Debug.Log("Error Code: " + error_Code + "  occurred while Initializing the FreeType Library.");
                        }
                    }

                    string fontPath = AssetDatabase.GetAssetPath(font_TTF); // Get file path of TTF Font.

                    if (error_Code == 0)
                    {
                        error_Code = TMPro_FontPlugin.Load_TrueType_Font(fontPath); // Load the selected font.

                        if (error_Code != 0)
                        {
                            if (error_Code == 99)
                            {
                                //Debug.Log("Font was already loaded!");
                                error_Code = 0;
                            }
                            else
                            {
                                Debug.Log("Error Code: " + error_Code + "  occurred while Loading the font.");
                            }
                        }
                    }

                    if (error_Code == 0)
                    {
                        if (FontSizingOption_Selection == 0)
                        {
                            font_size = 72;                                    // If Auto set size to 72 pts.
                        }
                        error_Code = TMPro_FontPlugin.FT_Size_Font(font_size); // Load the selected font and size it accordingly.
                        if (error_Code != 0)
                        {
                            Debug.Log("Error Code: " + error_Code + "  occurred while Sizing the font.");
                        }
                    }

                    // Define an array containing the characters we will render.
                    if (error_Code == 0)
                    {
                        int[] character_Set = null;
                        if (font_CharacterSet_Selection == 6 || font_CharacterSet_Selection == 7)
                        {
                            List <int> char_List = new List <int>();

                            for (int i = 0; i < characterSequence.Length; i++)
                            {
                                // Check to make sure we don't include duplicates
                                if (char_List.FindIndex(item => item == characterSequence[i]) == -1)
                                {
                                    char_List.Add(characterSequence[i]);
                                }
                                else
                                {
                                    //Debug.Log("Character [" + characterSequence[i] + "] is a duplicate.");
                                }
                            }

                            character_Set = char_List.ToArray();
                        }
                        else
                        {
                            character_Set = ParseNumberSequence(characterSequence);
                        }

                        m_character_Count = character_Set.Length;

                        m_texture_buffer = new byte[font_atlas_width * font_atlas_height];

                        m_font_faceInfo = new FT_FaceInfo();

                        m_font_glyphInfo = new FT_GlyphInfo[m_character_Count];

                        int padding = font_padding;

                        bool autoSizing = FontSizingOption_Selection == 0 ? true : false;

                        float strokeSize = font_style_mod;
                        if (font_renderMode == RenderModes.DistanceField16)
                        {
                            strokeSize = font_style_mod * 16;
                        }
                        if (font_renderMode == RenderModes.DistanceField32)
                        {
                            strokeSize = font_style_mod * 32;
                        }

                        isProcessing = true;

                        ThreadPool.QueueUserWorkItem(SomeTask =>
                        {
                            isRenderingDone = false;

                            error_Code      = TMPro_FontPlugin.Render_Characters(m_texture_buffer, font_atlas_width, font_atlas_height, padding, character_Set, m_character_Count, font_style, strokeSize, autoSizing, font_renderMode, (int)m_fontPackingSelection, ref m_font_faceInfo, m_font_glyphInfo);
                            isRenderingDone = true;
                            //Debug.Log("Font Rendering is completed.");
                        });

                        previewSelection = PreviewSelectionTypes.PreviewFont;
                    }
                }
            }


            // FONT RENDERING PROGRESS BAR
            GUILayout.Space(1);
            progressRect = GUILayoutUtility.GetRect(288, 20, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Width(288), GUILayout.Height(20));

            GUI.BeginGroup(progressRect);
            GUI.DrawTextureWithTexCoords(new Rect(2, 0, 288, 20), TMP_UIStyleManager.progressTexture, new Rect(1 - m_renderingProgress, 0, 1, 1));
            GUI.EndGroup();


            // FONT STATUS & INFORMATION
            GUILayout.Space(5);
            EditorGUILayout.LabelField(output_feedback, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(48), GUILayout.MaxWidth(290));

            GUILayout.Space(10);


            // SAVE TEXTURE & CREATE and SAVE FONT XML FILE
            GUI.enabled = m_font_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
            if (GUILayout.Button("Save TextMeshPro Font Asset", GUILayout.Width(290)) && GUI.enabled)
            {
                string filePath = string.Empty;

                if (font_renderMode < RenderModes.DistanceField16) // == RenderModes.HintedSmooth || font_renderMode == RenderModes.RasterHinted)
                {
                    filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name, "asset");

                    if (filePath.Length == 0)
                    {
                        return;
                    }

                    Save_Normal_FontAsset(filePath);
                }
                else if (font_renderMode >= RenderModes.DistanceField16)
                {
                    filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");

                    if (filePath.Length == 0)
                    {
                        return;
                    }

                    Save_SDF_FontAsset(filePath);
                }
            }

            GUI.enabled = true; // Re-enable GUI

            GUILayout.Space(5);

            GUILayout.EndVertical();

            GUILayout.Space(25);

            /*
             * // GENERATE DISTANCE FIELD TEXTURE
             * GUILayout.Label("Distance Field Options", SectionLabel, GUILayout.Width(300));
             *
             * GUILayout.BeginVertical(textureAreaBox, GUILayout.Width(300));
             *
             * GUILayout.Space(5);
             *
             *
             * font_spread = EditorGUILayout.IntField("Spread", font_spread, GUILayout.Width(280));
             * font_scaledownFactor = EditorGUILayout.IntField("Scale down factor", font_scaledownFactor, GUILayout.Width(280));
             * if (GUI.changed)
             * {
             *  EditorPrefs.SetInt("Font_Spread", font_spread);
             *  EditorPrefs.SetInt("Font_ScaleDownFactor", font_scaledownFactor);
             * }
             *
             * GUILayout.Space(20);
             *
             * GUI.enabled = m_font_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
             * if (GUILayout.Button("Preview Distance Field Font Atlas", GUILayout.Width(290)))
             * {
             *
             *  if (m_font_Atlas != null && isProcessing == false)
             *  {
             *      // Generate Distance Field
             *      int width = m_font_Atlas.width;
             *      int height = m_font_Atlas.height;
             *      Color[] colors = m_font_Atlas.GetPixels(); // Should modify this to use Color32 instead
             *
             *      isProcessing = true;
             *
             *      ThreadPool.QueueUserWorkItem(SomeTask => { TMPro_DistanceTransform.Generate(colors, width, height, font_spread, font_scaledownFactor); });
             *
             *      previewSelection = PreviewSelectionTypes.PreviewDistanceField;
             *  }
             * }
             *
             * GUILayout.Space(1);
             *
             * progressRect = GUILayoutUtility.GetRect(290, 20, textAreaBox, GUILayout.Width(290), GUILayout.Height(20));
             *
             * GUI.BeginGroup(progressRect);
             *
             * GUI.DrawTextureWithTexCoords(new Rect(0, 0, 290, 20), progressTexture, new Rect(1 - ProgressPercentage, 0, 1, 1));
             * GUI.EndGroup();
             *
             * //GUILayout.Space(5);
             *
             * GUI.enabled = m_destination_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
             * if (GUILayout.Button("Save TextMeshPro (SDF) Font Asset", GUILayout.Width(290)))
             * {
             *  string filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");
             *
             *  if (filePath.Length == 0)
             *      return;
             *
             *  Save_SDF_FontAsset(filePath);
             *
             * }
             *
             * GUILayout.EndVertical();
             */

            // Figure out the size of the current UI Panel
            Rect rect = EditorGUILayout.GetControlRect(false, 5);

            if (Event.current.type == EventType.Repaint)
            {
                m_UI_Panel_Size = rect;
            }

            GUILayout.EndVertical();
        }
Ejemplo n.º 27
0
		public static void WriteImage(Stream inStream, Stream outStream, int boundWidth, int boundHeight, RenderModes mode)
		{
			Bitmap bmpSrc = null, bmpTrg = null;

			try
			{
				bmpSrc = new Bitmap(inStream);

				// convert TIFF to BMP, use only the first page
				FrameDimension fd = new FrameDimension(bmpSrc.FrameDimensionsList[0]);
				bmpSrc.SelectActiveFrame(fd, 0);

				// crop/fit/stretch
                int imageHeight = bmpSrc.Height, imageWidth = bmpSrc.Width, targetWidth, targetHeight;

				if (boundWidth < 0) boundWidth = imageWidth;
				if (boundHeight < 0) boundHeight = imageHeight;

				if (boundWidth != imageWidth || boundHeight != imageHeight)
				{
					switch (mode)
					{
						case RenderModes.RenderMode_Stretch:
							bmpTrg = new Bitmap(bmpSrc, new Size(boundWidth, boundHeight));
							break;

						case RenderModes.RenderMode_Fit:
							targetWidth = imageWidth;
                            targetHeight = imageHeight;
							float scale = 1F;
							// a. panel is greater than image: grow
							if (boundHeight > imageHeight && boundWidth > imageWidth)
							{
								scale = Math.Min((float)boundWidth / imageWidth, (float)boundHeight / imageHeight);
								targetHeight = Math.Min((int)((float)imageHeight * scale), boundHeight);
								targetWidth = Math.Min((int)((float)imageWidth * scale), boundWidth);
							}
							// b. image is greater than panel: shrink
							else
							{
								scale = Math.Max((float)imageWidth / boundWidth, (float)imageHeight / boundHeight);
								targetWidth = Math.Min((int)((float)imageWidth / scale), boundWidth);
								targetHeight = Math.Min((int)((float)imageHeight / scale), boundHeight);
							}
							bmpTrg = new Bitmap(bmpSrc, new Size(targetWidth, targetHeight));
							break;

						case RenderModes.RenderMode_Crop:
							targetWidth = Math.Min(boundWidth, imageWidth);
							targetHeight = Math.Min(boundHeight, imageHeight);
							bmpTrg = bmpSrc.Clone(
								new Rectangle(0, 0, targetWidth, targetHeight),
								bmpSrc.PixelFormat
								);
							break;
					}

					bmpTrg.Save(outStream, ImageFormat.Png);
				}
				else
					bmpSrc.Save(outStream, ImageFormat.Png);
			}

			finally
			{
				if (bmpTrg != null) bmpTrg.Dispose();
				if (bmpSrc != null) bmpSrc.Dispose();
				GC.Collect();
			}
		}
Ejemplo n.º 28
0
 private void FillModesSelectList(RenderModes? selected = null)
 {
     ViewBag.Modes = selected.TranslatedSelectList();
 }
Ejemplo n.º 29
0
        public ActionResult Thumb(int id, int width = 0, int height = 0, RenderModes mode = RenderModes.RenderMode_Fit, int trace = 0)
        {
            StringBuilder message = new StringBuilder();

            try
            {
                if (width <= 120 && height <= 120)
                {
                    byte[] cache = HttpRuntime.Cache.GetOrAddSliding(
                        string.Format("thumb_report_{0}_{1}x{2}_{3}", id, width, height, (int)mode),
                        () => {
                            byte[] img = GetReportBytes(id);
                            using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(img))
                            {
                                MediaController.WriteImage(src, trg, width, height, mode);
                                return trg.GetBuffer();
                            }
                        },
                        TimeSpan.FromMinutes(10)
                        );

                    return new FileStreamResult(new MemoryStream(cache), "image/png");
                }

                else
                {
                    byte[] img = GetReportBytes(id);
                    using (MemoryStream src = new MemoryStream(img))
                    {
                        MemoryStream trg = new MemoryStream();
                        MediaController.WriteImage(src, trg, width, height, mode);
                        return new FileStreamResult(trg, "image/png");
                    }
                }
            }

            catch (Exception ex)
            {
                if (trace > 0)
                    message.Append(ex.ToString());

                if (trace > 1)
                {
                    Report report = db.Reports
                        .Include(r => r.ReportServer)
                        .FirstOrDefault(r => r.FrameId == id)
                        ;
                    
                    message.Append("\n");
                    if (report == null)
                    {
                        message.AppendFormat("\nReport id {0} not found", id);
                    }
                    else
                    {
                        message.AppendFormat("\nReport name: {0}", report.Name);
                        message.AppendFormat("\nReport path: {0}", report.Path);
                        message.AppendFormat("\nReport server URL: {0}", report.ReportServer.BaseUrl);
                        message.AppendFormat("\nReport server account: {0}\\{1}", report.ReportServer.Domain, report.ReportServer.User);
                        //message.AppendFormat("\nReport server passwrd: {0}", HttpUtility.HtmlEncode(RsaUtil.Decrypt(report.ReportServer.Password)));
                    }
                }
            }

            if (trace == 0)
                return RedirectToAction("BadImg", "Media");
            else
                return Content(message.Length == 0 ? "OK" : message.ToString());
        }
Ejemplo n.º 30
0
 public abstract void BeforeRendering(RenderModes renderMode);
Ejemplo n.º 31
0
 public abstract void BeforeRendering(RenderModes renderMode);
Ejemplo n.º 32
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = context.Request;
            HttpResponse Response = context.Response;

            try
            {
                // set headers, prevent client caching, return PNG
                Response.Clear();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetSlidingExpiration(true);
                Response.Cache.SetNoStore();
                Response.ContentType = "image/png";

                int frameId = Convert.ToInt32(Request.QueryString["frame"]);

                byte[]      data = null;
                int         panelHeight = -1, panelWidth = -1;
                RenderModes mode = RenderModes.RenderMode_Crop;

                Report report = new Report(frameId);

                if (report.FrameId != 0)
                {
                    Panel panel = new Panel(report.PanelId);
                    if (panel.PanelId != 0)
                    {
                        panelWidth  = panel.Width;
                        panelHeight = panel.Height;
                    }

                    mode = report.Mode;

                    //TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    //BitmapSource bitmapSource = decoder.Frames[0];

                    data = HttpRuntime.Cache.GetOrAddAbsolute(
                        report.CacheKey,
                        () =>
                    {
                        // get response from report server
                        WebClient client = new WebClient();
                        if (!string.IsNullOrWhiteSpace(report.User))
                        {
                            client.Credentials = new NetworkCredential(
                                report.User.Trim(),
                                RsaUtil.Decrypt(report.Password),
                                report.Domain.Trim()
                                );
                        }

                        byte[] repBytes = client.DownloadData(report.Url);

                        if (repBytes == null)
                        {
                            return(null);
                        }

                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(repBytes))
                            {
                                Picture.WriteImage(src, trg, panelWidth, panelHeight, mode);
                                return(trg.GetBuffer());
                            }
                    },
                        DateTime.Now.AddMinutes(report.CacheInterval)
                        );
                }

                if (data != null)
                {
                    Response.OutputStream.Write(data, 0, data.Length);
                }

                else
                {
                    data = File.ReadAllBytes("~/files/404.png");
                    using (MemoryStream ms = new MemoryStream(data))
                    {
                        Picture.WriteImage(ms, Response.OutputStream, panelWidth, panelHeight, mode);
                    }
                }
            }

            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

            finally
            {
                Response.OutputStream.Flush();
            }
        }
Ejemplo n.º 33
0
        private static void SetMapProperties(Map map, Dictionary <string, string> properties, ICartoTranslator cartoTranslator)
        {
            if (properties.Count == 0)
            {
                return;
            }

            string paramValue;

            // ************************* Set background properties *************************
            Background background = map.Background;

            if (properties.TryGetValue("background-color", out paramValue))
            {
                background.ColorHtml = paramValue;
            }

            if (properties.TryGetValue("background-opacity", out paramValue))
            {
                background.Opacity = Convert.ToSingle(paramValue, CultureInfo.InvariantCulture);
            }

            // TODO more image stuff
            if (properties.TryGetValue("background-image-file", out paramValue) || properties.TryGetValue("background-image", out paramValue))
            {
                background.Image.FileName = cartoTranslator.ToPath(paramValue);
            }

            // ************************* Set render modes *************************

            RenderModes renderModes = map.RenderModes;

            if (properties.TryGetValue("render-modes-bidi", out paramValue))
            {
                renderModes.BidiMode = Convert.ToBoolean(paramValue);
            }

            if (properties.TryGetValue("render-modes-kerning", out paramValue))
            {
                renderModes.Kerning = Convert.ToBoolean(paramValue);
            }

            if (properties.TryGetValue("render-modes-scale-factor", out paramValue))
            {
                renderModes.ScaleFactor = Convert.ToSingle(paramValue);
            }

            if (properties.TryGetValue("render-modes-text-abbreviation", out paramValue))
            {
                renderModes.TextAbbreviation = Convert.ToBoolean(paramValue);
            }

            if (properties.TryGetValue("render-modes-text-contrast", out paramValue))
            {
                renderModes.TextContrast = Convert.ToInt32(paramValue);
            }

            if (properties.TryGetValue("render-modes-image-resampling", out paramValue))
            {
                renderModes.ImageResamplingMode = EnumExtensions.GetValueByName <ImageResamplingMode>(typeof(ImageResamplingMode), paramValue, StringComparison.OrdinalIgnoreCase);
            }

            if (properties.TryGetValue("render-modes-smoothing", out paramValue))
            {
                renderModes.SmoothingMode = EnumExtensions.GetValueByName <SmoothingMode>(typeof(SmoothingMode), paramValue, StringComparison.OrdinalIgnoreCase);
            }

            if (properties.TryGetValue("render-modes-text-rendering", out paramValue))
            {
                renderModes.TextRenderingMode = EnumExtensions.GetValueByName <TextRenderMode>(typeof(TextRenderMode), paramValue, StringComparison.OrdinalIgnoreCase);
            }

            // ************************* Set label settings *************************

            LabelPlacementProblemSettings labelSettings = map.LabelPlacementSettings;

            if (properties.TryGetValue("label-settings-solver", out paramValue))
            {
                labelSettings.Solver           = paramValue;
                labelSettings.SolverParameters = GetParameters(properties, "label-settings-solver-param");
            }

            if (properties.TryGetValue("label-settings-accuracy", out paramValue))
            {
                labelSettings.AccuracyMode = EnumExtensions.GetValueByName <MapSurfer.Labeling.CandidatePositionGenerators.LabelPlacementAccuracyMode>(typeof(MapSurfer.Labeling.CandidatePositionGenerators.LabelPlacementAccuracyMode), paramValue, StringComparison.OrdinalIgnoreCase);
            }

            if (properties.TryGetValue("label-settings-candidate-position-generator", out paramValue))
            {
                labelSettings.CandidatePositionGenerator           = paramValue;
                labelSettings.CandidatePositionGeneratorParameters = GetParameters(properties, "label-settings-candidate-position-generator-param");
            }

            if (properties.TryGetValue("label-settings-collision-detector", out paramValue))
            {
                labelSettings.CollisionDetector           = paramValue;
                labelSettings.CollisionDetectorParameters = GetParameters(properties, "label-settings-collision-detector-param");
            }

            string[] values = GetStringValues(properties, "label-settings-quality-evaluator-param");
            if (values.Length > 0)
            {
                labelSettings.QualityEvaluators.Clear();
                labelSettings.QualityEvaluators.AddRange(values);
            }

            // ************************* Font files *******************************

            values = GetStringValues(properties, "font-files-file");

            if (values.Length > 0)
            {
                map.FontFiles.AddRange(values);
            }

            if (properties.TryGetValue("font-directory", out paramValue))
            {
                if (Directory.Exists(paramValue))
                {
                    foreach (string fileName in Directory.EnumerateFiles(paramValue))
                    {
                        map.FontFiles.Add(fileName);
                    }
                }
            }

            // ************************* Font sets *******************************

            //TODO

            // ************************* Scales *************************

            if (properties.TryGetValue("minimum-scale", out paramValue))
            {
                map.MinimumScale = Convert.ToDouble(paramValue, CultureInfo.InvariantCulture);
            }
            if (properties.TryGetValue("maximum-scale", out paramValue))
            {
                map.MaximumScale = Convert.ToDouble(paramValue, CultureInfo.InvariantCulture);
            }

            // ************************* Buffers *************************
            int size = 256;

            if (properties.TryGetValue("buffer-size", out paramValue))
            {
                size = Convert.ToInt32(paramValue);
            }

            map.Padding = new Size(size, size);

            if (properties.TryGetValue("buffer-image-size", out paramValue)) // Extension
            {
                size       = Convert.ToInt32(paramValue);
                map.Buffer = new Size(size, size);
            }
        }
 public static extern int Render_Characters(byte[] buffer, int buffer_width, int buffer_height, int character_padding, int[] asc_set, int char_count, FaceStyles style, float style_mod, bool autoSize, RenderModes renderMode, int method, ref FT_FaceInfo fontData, FT_GlyphInfo[] Output);
Ejemplo n.º 35
0
        public async Task <ActionResult> ThumbAsync(int id, int width = 0, int height = 0, RenderModes mode = RenderModes.RenderMode_Fit, int trace = 0)
        {
            StringBuilder message = new StringBuilder();

            try
            {
                Report report = db.Frames.OfType <Report>()
                                .Include(r => r.ReportServer)
                                .FirstOrDefault(r => r.FrameId == id)
                ;

                if (width <= 120 && height <= 120)
                {
                    byte[] cache = await HttpRuntime.Cache.GetOrAddSlidingAsync(
                        string.Format("thumb_report_{0}_{1}x{2}_{3}", report.FullPath, width, height, (int)mode),
                        async (expire) =>
                    {
                        expire.After = TimeSpan.FromHours(1);
                        byte[] img   = await GetReportBytesAsync(report);
                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(img))
                            {
                                MediaController.WriteImage(src, trg, width, height, mode);
                                return(trg.GetBuffer());
                            }
                    });

                    return(new FileStreamResult(new MemoryStream(cache), "image/png"));
                }

                else
                {
                    byte[] img = await GetReportBytesAsync(report);

                    using (MemoryStream src = new MemoryStream(img))
                    {
                        MemoryStream trg = new MemoryStream();
                        MediaController.WriteImage(src, trg, width, height, mode);
                        return(new FileStreamResult(trg, "image/png"));
                    }
                }
            }

            catch (Exception ex)
            {
                if (trace > 0)
                {
                    message.Append(ex.ToString());
                }

                if (trace > 1)
                {
                    Report report = db.Frames.OfType <Report>()
                                    .Include(r => r.ReportServer)
                                    .FirstOrDefault(r => r.FrameId == id)
                    ;

                    message.Append("\n");
                    if (report == null)
                    {
                        message.AppendFormat("\nReport id {0} not found", id);
                    }
                    else
                    {
                        message.AppendFormat("\nReport name: {0}", report.Name);
                        message.AppendFormat("\nReport path: {0}", report.Path);
                        message.AppendFormat("\nReport server URL: {0}", report.ReportServer.BaseUrl);
                        message.AppendFormat("\nReport server account: {0}\\{1}", report.ReportServer.Domain, report.ReportServer.User);
                        //message.AppendFormat("\nReport server passwrd: {0}", HttpUtility.HtmlEncode(RsaUtil.Decrypt(report.ReportServer.Password)));
                    }
                }
            }

            if (trace == 0)
            {
                return(RedirectToAction("BadImg", "Media"));
            }
            else
            {
                return(Content(message.Length == 0 ? "OK" : message.ToString()));
            }
        }
Ejemplo n.º 36
0
        public async Task<ActionResult> ThumbAsync(int id, int width = 0, int height = 0, RenderModes mode = RenderModes.RenderMode_Fit, int trace = 0)
        {
            StringBuilder message = new StringBuilder();

            try
            {
                if (width <= 120 && height <= 120)
                {
                    byte[] cache = await HttpRuntime.Cache.GetOrAddSlidingAsync(
                        string.Format("thumb_image_{0}_{1}x{2}_{3}", id, width, height, (int)mode),
                        async (expire) => 
                        {
                            expire.After = TimeSpan.FromHours(1);
                            var data = await db.Contents.FindAsync(id);
                            using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(data.Data))
                            {
                                MediaController.WriteImage(src, trg, width, height, mode);
                                return trg.GetBuffer();
                            }
                        });

                    return new FileStreamResult(new MemoryStream(cache), "image/png");
                }

                else
                {
                    var data = await db.Contents.FindAsync(id);
                    using (MemoryStream src = new MemoryStream(data.Data))
                    {
                        MemoryStream trg = new MemoryStream();
                        MediaController.WriteImage(src, trg, width, height, mode);
                        return new FileStreamResult(trg, "image/png");
                    }
                }
            }

            catch (Exception ex)
            {
                if (trace > 0)
                    message.Append(ex.ToString());
            }

            if (trace == 0)
                return RedirectToAction("BadImg");
            else
                return Content(message.Length == 0 ? "OK" : message.ToString());
        }
 public static extern int Render_Character(byte[] buffer_fill, byte[] buffer_edge, int buffer_width, int buffer_height, int offset, int asc, FaceStyles style, float thickness, RenderModes rasterMode, ref FT_GlyphInfo glyphInfo);
Ejemplo n.º 38
0
        //--------------------------------------------------------------------------------------------------

        #endregion

        #region Initialization

        public Viewport()
        {
            _RenderMode = RenderModes.SolidShaded;
        }
Ejemplo n.º 39
0
        public static bool Init()
        {
            if (File.Exists("Settings.txt"))
            {
                foreach (var line in File.ReadAllLines("Settings.txt"))
                {
                    if (!line.Trim().StartsWith("#"))
                    {
                        string[] split = line.Split('=');

                        switch (split[0].ToLower().Trim())
                        {
                            case "viewoffx":
                                ViewOffX = ParseNum(split[1].Trim());
                                break;
                            case "viewoffy":
                                ViewOffY = ParseNum(split[1].Trim());
                                break;
                            case "viewwidth":
                                ViewWidth = ParseNum(split[1].Trim());
                                break;
                            case "viewheight":
                                ViewHeight = ParseNum(split[1].Trim());
                                break;
                            case "width":
                                Width = ParseNum(split[1].Trim());
                                break;
                            case "height":
                                Height = ParseNum(split[1].Trim());
                                break;
                            case "iters":
                                Iters = ParseNum(split[1].Trim());
                                break;
                            case "iters2":
                                Iters2 = ParseNum(split[1].Trim());
                                break;
                            case "iters3":
                                Iters3 = ParseNum(split[1].Trim());
                                break;
                            case "alias":
                                Alias = ParseNum(split[1].Trim());
                                break;
                            case "threads":
                                Threads = ParseNum(split[1].Trim());
                                break;
                            case "mode":
                                Mode = Utilities.IntToRender(int.Parse(split[1].Trim()));
                                break;
                            case "saveangledata":
                                SaveAngleData = bool.Parse(split[1].Trim());
                                break;
                            case "savetrilimits":
                                SaveTriLimits = bool.Parse(split[1].Trim());
                                break;
                        }
                    }
                }

                return true;
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendFormat("Width = {0}\r\n", Width);
                sb.AppendFormat("Height = {0}\r\n", Height);

                sb.AppendFormat("ViewOffX = {0}\r\n", ViewOffX);
                sb.AppendFormat("ViewOffY = {0}\r\n", ViewOffY);
                sb.AppendFormat("ViewWidth = {0}\r\n", ViewWidth);
                sb.AppendFormat("ViewHeight = {0}\r\n", ViewHeight);

                sb.AppendFormat("Iters = {0}\r\n", Iters);
                sb.AppendFormat("Iters2 = {0}\r\n", Iters2);
                sb.AppendFormat("Iters3 = {0}\r\n", Iters3);
                sb.AppendFormat("Alias = {0}\r\n", Alias);
                sb.AppendFormat("Threads = {0}\r\n", Threads);

                sb.AppendFormat("SaveAngleData = {0}\r\n", SaveAngleData);
                sb.AppendFormat("SaveTriLimits = {0}\r\n", SaveTriLimits);

                sb.AppendFormat("Mode = {0}\r\n", Utilities.RenderToInt(Mode));
                sb.Append("# 1 = Buddhabrot\r\n");
                sb.Append("# 2 = Anti-Buddhabrot\r\n");
                sb.Append("# 3 = Black Mandelbrot\r\n");
                sb.Append("# 4 = Mandelbrot\r\n");

                File.WriteAllText("Settings.txt", sb.ToString());

                return false;
            }
        }
Ejemplo n.º 40
0
 int Render_Characters(byte[] buffer, int buffer_width, int buffer_height, int character_padding, int[] asc_set, int char_count, FaceStyles style, float style_mod, bool autoSize, RenderModes renderMode, int method, ref FT_FaceInfo fontData, FT_GlyphInfo[] Output);
Ejemplo n.º 41
0
        // TODO: move to separate file
        public static void WriteImage(Stream inStream, Stream outStream, int panelWidth, int panelHeight, RenderModes mode)
        {
            Bitmap bmpSrc = null, bmpTrg = null;

            try
            {
                inStream.Position = 0;
                bmpSrc = new Bitmap(inStream);

                // convert TIFF to BMP, use only the first page
                FrameDimension fd = new FrameDimension(bmpSrc.FrameDimensionsList[0]);
                bmpSrc.SelectActiveFrame(fd, 0);

                // crop/fit/stretch
                int imageHeight = bmpSrc.Height, imageWidth = bmpSrc.Width, targetWidth, targetHeight;

                if (panelWidth <= 0) panelWidth = imageWidth;
                if (panelHeight <= 0) panelHeight = imageHeight;

                if (panelWidth != imageWidth || panelHeight != imageHeight)
                {
                    switch (mode)
                    {
                        case RenderModes.RenderMode_Stretch:
                            if (panelWidth <= 120 && panelHeight <= 120)
                                bmpTrg = new Bitmap(bmpSrc.GetThumbnailImage(panelWidth, panelHeight, () => false, IntPtr.Zero)); 
                            else
                                bmpTrg = new Bitmap(bmpSrc, new Size(panelWidth, panelHeight));
                            break;

                        case RenderModes.RenderMode_Fit:
                            targetWidth = imageWidth;
                            targetHeight = imageHeight;
                            float scale = 1F;
                            // a. panel is greater than image: grow
                            if (panelHeight > imageHeight && panelWidth > imageWidth)
                            {
                                scale = Math.Min((float)panelWidth / imageWidth, (float)panelHeight / imageHeight);
                                targetHeight = Math.Min((int)((float)imageHeight * scale), panelHeight);
                                targetWidth = Math.Min((int)((float)imageWidth * scale), panelWidth);
                            }
                            // b. image is greater than panel: shrink
                            else
                            {
                                scale = Math.Max((float)imageWidth / panelWidth, (float)imageHeight / panelHeight);
                                targetWidth = Math.Min((int)((float)imageWidth / scale), panelWidth);
                                targetHeight = Math.Min((int)((float)imageHeight / scale), panelHeight);
                            }
                            if (targetWidth <= 120 && targetHeight <= 120)
                                bmpTrg = new Bitmap(bmpSrc.GetThumbnailImage(targetWidth, targetHeight, () => false, IntPtr.Zero)); 
                            else
                                bmpTrg = new Bitmap(bmpSrc, new Size(targetWidth, targetHeight));
                            break;

                        case RenderModes.RenderMode_Crop:
                            targetWidth = Math.Min(panelWidth, imageWidth);
                            targetHeight = Math.Min(panelHeight, imageHeight);
                            bmpTrg = bmpSrc.Clone(
                                new Rectangle(0, 0, targetWidth, targetHeight),
                                bmpSrc.PixelFormat
                                );
                            break;
                    }

                    bmpTrg.Save(outStream, ImageFormat.Png);    
                }
                else
                    bmpSrc.Save(outStream, ImageFormat.Png);

                outStream.Seek(0, SeekOrigin.Begin);
            }

            finally
            {
                if (bmpTrg != null) bmpTrg.Dispose();
                if (bmpSrc != null) bmpSrc.Dispose();
                GC.Collect();
            }
        }
Ejemplo n.º 42
0
        private void SetRenderMode(RenderModes rm)
        {
            lock (renderSyncObject)
            {
                renderMode = rm;
                //if (!IsInitialized && !isInitializing)
                //    return;

                //clean up objects that will be invalid after RenderTarget change
                if (dcRenderTarget != null)
                {
                    dcRenderTarget.Dispose();
                    dcRenderTarget = null;
                }
                if (hwndRenderTarget != null)
                {
                    hwndRenderTarget.Dispose();
                    hwndRenderTarget = null;
                }
                if (bitmapRenderTarget != null)
                {
                    bitmapRenderTarget.Dispose();
                    bitmapRenderTarget = null;
                }
                //bitmap = null; //the bitmap created in dc render target can't be used in hwnd render target

                // Create the screen render target
                RECT cRect;
                User32.GetClientRect(fWindowHandle, out cRect);
                
                var size = new SizeU((uint)cRect.Width, (uint)cRect.Height);
                PixelFormat pFormat = new PixelFormat(Format.B8G8R8A8_UNORM, AlphaMode.Ignore);
                var props = new RenderTargetProperties {PixelFormat = pFormat, Usage = RenderTargetUsage.GdiCompatible};

                //if (renderMode == RenderModes.DCRenderTarget || renderMode == RenderModes.BitmapRenderTargetOnPaint)
                //{
                //    dcRenderTarget = d2DFactory.CreateDCRenderTarget(props);
                //    if (renderMode == RenderModes.BitmapRenderTargetOnPaint)
                //    {
                //        bitmapRenderTarget =
                //            dcRenderTarget.CreateCompatibleRenderTarget(
                //            CompatibleRenderTargetOptions.GdiCompatible,
                //            new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                //    }
                //    render = null;
                //}
                //else
                {
                    HwndRenderTargetProperties hProps = new HwndRenderTargetProperties(fWindowHandle, size, PresentOptions.RetainContents);
                    hwndRenderTarget = d2DFactory.CreateHwndRenderTarget(props,  hProps);
                    
                    //if (renderMode == RenderModes.BitmapRenderTargetRealTime)
                    //{
                    //    bitmapRenderTarget =
                    //        hwndRenderTarget.CreateCompatibleRenderTarget(
                    //        CompatibleRenderTargetOptions.GdiCompatible,
                    //        new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                    //}
                    //render = RenderSceneInBackground;
                }
            }
        }
Ejemplo n.º 43
0
        // PRAGMA MARK - Public Interface
        public static void Bake(Font font, bool useAutoSizing, int fontSize, int characterPadding, TMPFontPackingModes fontPackingMode, int atlasWidth, int atlasHeight, FaceStyles fontStyle, int fontStyleMod, RenderModes fontRenderMode, string charactersToBake, string outputFilePath)
        {
            int errorCode = TMPro_FontPlugin.Initialize_FontEngine();

            if (errorCode != 0 && errorCode != 99)               // 99 means that engine was already initialized
            {
                Debug.LogWarning("Error Code: " + errorCode + "  occurred while initializing TMPro_FontPlugin.");
                return;
            }

            string fontPath = AssetDatabase.GetAssetPath(font);

            errorCode = TMPro_FontPlugin.Load_TrueType_Font(fontPath);
            if (errorCode != 0 && errorCode != 99)               // 99 means that font was already loaded
            {
                Debug.LogWarning("Error Code: " + errorCode + "  occurred while loading font: " + font + ".");
                return;
            }

            if (useAutoSizing)
            {
                fontSize = 72;
            }
            errorCode = TMPro_FontPlugin.FT_Size_Font(fontSize);
            if (errorCode != 0)
            {
                Debug.LogWarning("Error Code: " + errorCode + "  occurred while sizing font: " + font + " to size: " + fontSize + ".");
                return;
            }

            byte[] textureBuffer = new byte[atlasWidth * atlasHeight];

            int[] characterArray = charactersToBake.Select(c => (int)c).ToArray();
            int   characterCount = charactersToBake.Length;

            var fontFaceInfo  = new FT_FaceInfo();
            var fontGlyphInfo = new FT_GlyphInfo[characterCount];

            float strokeSize = fontStyleMod;

            if (fontRenderMode == RenderModes.DistanceField16)
            {
                strokeSize *= 16;
            }
            else if (fontRenderMode == RenderModes.DistanceField32)
            {
                strokeSize *= 32;
            }

            errorCode = TMPro_FontPlugin.Render_Characters(textureBuffer, atlasWidth, atlasHeight, characterPadding, characterArray, characterCount, fontStyle, strokeSize, useAutoSizing, fontRenderMode, (int)fontPackingMode, ref fontFaceInfo, fontGlyphInfo);
            if (errorCode != 0)
            {
                Debug.LogWarning("Error Code: " + errorCode + "  occurred while rendering font characters!");
                return;
            }

            string outputFilename = Path.GetFileNameWithoutExtension(outputFilePath);

            // check if font asset already exists
            TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(outputFilePath, typeof(TMP_FontAsset)) as TMP_FontAsset;

            if (fontAsset == null)
            {
                fontAsset = ScriptableObject.CreateInstance <TMP_FontAsset>();                // Create new TextMeshPro Font Asset.
                AssetDatabase.CreateAsset(fontAsset, outputFilePath);
            }

            // Destroy Assets that will be replaced.
            UnityEngine.Object.DestroyImmediate(fontAsset.atlas, allowDestroyingAssets: true);

            fontAsset.fontAssetType = (fontRenderMode >= RenderModes.DistanceField16) ? TMP_FontAsset.FontAssetTypes.SDF : TMP_FontAsset.FontAssetTypes.Bitmap;

            fontAsset.AddFaceInfo(ConvertToFaceInfo(fontFaceInfo));
            fontAsset.AddGlyphInfo(ConvertToGlyphs(fontGlyphInfo));

            var fontTexture = CreateFontTexture(atlasWidth, atlasHeight, textureBuffer, fontRenderMode);

            fontTexture.name      = outputFilename + " Atlas";
            fontTexture.hideFlags = HideFlags.HideInHierarchy;

            fontAsset.atlas = fontTexture;
            AssetDatabase.AddObjectToAsset(fontTexture, fontAsset);

            // Find all Materials referencing this font atlas.
            Material[] materialReferences = TMP_EditorUtility.FindMaterialReferences(fontAsset).Where(m => m != null).ToArray();
            if (materialReferences == null || materialReferences.Length <= 0)
            {
                // Create new Material and add it as Sub-Asset
                Shader   shader       = Shader.Find("TMPro/Distance Field");
                Material fontMaterial = new Material(shader);
                fontMaterial.name = outputFilename + " Material";

                fontAsset.material     = fontMaterial;
                fontMaterial.hideFlags = HideFlags.HideInHierarchy;
                AssetDatabase.AddObjectToAsset(fontMaterial, fontAsset);

                materialReferences = new Material[] { fontMaterial };
            }

            foreach (var m in materialReferences)
            {
                m.SetTexture(ShaderUtilities.ID_MainTex, fontTexture);
                m.SetFloat(ShaderUtilities.ID_TextureWidth, fontTexture.width);
                m.SetFloat(ShaderUtilities.ID_TextureHeight, fontTexture.height);


                m.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
                m.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);

                m.SetFloat(ShaderUtilities.ID_GradientScale, characterPadding + 1);
            }

            AssetDatabase.SaveAssets();
            // Re-import font asset to get the new updated version.
            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset));
            fontAsset.ReadFontDefinition();
            AssetDatabase.Refresh();

            // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
            TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
        }
        private void DrawRightEye(GameTime time, Vector3 eyePosition, RenderModes mode, GraphicsDevice device,
                                  SpriteBatch sb)
        {
            switch (mode)
            {
                case RenderModes.StereoCrossConverged:
                    device.SetRenderTarget(0, (_takeScreenshot ? _screenshotTargetRight : _rightEyeRender));
                    break;
                case RenderModes.Stereo:
                    // Draw on the extra created window
                    device.Present(_stereoRightHandle);
                    break;
            }

            device.Clear(ClearColor);

            // Setup camera for right eye
            // Translate look at direction to new eye position
            const float focusDistance = 10.0f;
            Vector3 lookAtVector = Vector3.Normalize(Camera.LookAt - Camera.Position);
            Camera.LookAt = Camera.Position + focusDistance*lookAtVector;
            Camera.Position = eyePosition;
            Camera.UpdateMatrices();

            _basicEffect.View = Camera.View; 
            base.Draw(time);

            // Print FPS
            if (ShowFPS)
            {
                string fpsText = "FPS: " + _fpsUtil.Value;
                PrintInfo(sb, new Vector2(0.9f*_screenWidth, 0), fpsText);
            }
        }
Ejemplo n.º 45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderEventArgs"/> class.
 /// </summary>
 /// <param name="renderMode">渲染模式</param>
 /// <param name="camera">渲染时所用的camera</param>
 public RenderEventArgs(RenderModes renderMode, ICamera camera)
 {
     this.RenderMode = renderMode;
     this.Camera = camera;
 }
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            HttpRequest  Request  = context.Request;
            HttpResponse Response = context.Response;

            try
            {
                // set headers, prevent client caching, return PNG
                Response.Clear();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetSlidingExpiration(true);
                Response.Cache.SetNoStore();
                Response.ContentType = "image/png";

                int frameId = Request.IntOrZero("frame");

                byte[]      data = null;
                int         panelHeight = -1, panelWidth = -1;
                RenderModes mode = RenderModes.RenderMode_Crop;

                Report report = new Report(frameId);

                if (report.FrameId != 0)
                {
                    Panel panel = new Panel(report.PanelId);
                    if (panel.PanelId != 0)
                    {
                        panelWidth  = panel.Width;
                        panelHeight = panel.Height;
                    }

                    mode = report.Mode;

                    //TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    //BitmapSource bitmapSource = decoder.Frames[0];

                    data = await HttpRuntime.Cache.GetOrAddAbsoluteAsync(
                        report.CacheKey,
                        async (expire) =>
                    {
                        expire.When = DateTime.Now.AddMinutes(report.CacheInterval);

                        // get response from report server
                        WebClient client = new WebClient();
                        if (!string.IsNullOrWhiteSpace(report.User))
                        {
                            client.Credentials = new NetworkCredential(
                                report.User.Trim(),
                                RsaUtil.Decrypt(report.Password),
                                report.Domain.Trim()
                                );
                        }

                        byte[] repBytes = await client.DownloadDataTaskAsync(report.Url);

                        if (repBytes == null)
                        {
                            return(null);
                        }

                        using (MemoryStream trg = new MemoryStream())
                            using (MemoryStream src = new MemoryStream(repBytes))
                            {
                                await Task.Run(() => Picture.WriteImage(src, trg, panelWidth, panelHeight, mode));
                                return(trg.GetBuffer());
                            }
                    });
                }

                if (data != null)
                {
                    await Response.OutputStream.WriteAsync(data, 0, data.Length);
                }

                else
                {
                    Content missingContent = await Content.GetMissingContentAsync();

                    using (MemoryStream ms = new MemoryStream(missingContent.Data))
                    {
                        await Task.Run(() => Picture.WriteImage(ms, Response.OutputStream, -1, -1, RenderModes.RenderMode_Crop));
                    }
                }

                await Response.OutputStream.FlushAsync();
            }

            catch (Exception ex)
            {
                Debug.Print(string.Format("getReport error: {0}", ex.Message));
                Response.Write(ex.Message);
            }

            /*finally
             * {
             *  Response.OutputStream.Flush();
             * }*/
        }
Ejemplo n.º 47
0
        public static void SetupGUI(TexAsset asset)
        {
            EditorGUI.BeginDisabledGroup(onRendering);
            GUILayout.BeginHorizontal();
            GUI.changed = false;

            GUILayout.Label("Atlas Resolution", GUILayout.Width(EditorGUIUtility.labelWidth));
            _bufferWidth  = EditorGUILayout.IntPopup(_bufferWidth, FontResolutionLabels, FontAtlasResolutions);  //, GUILayout.Width(80));
            _bufferHeight = EditorGUILayout.IntPopup(_bufferHeight, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Padding", GUILayout.Width(EditorGUIUtility.labelWidth));
            _padding = EditorGUILayout.IntSlider(_padding, 1, 10);
            GUILayout.EndHorizontal();

            _render = (RenderModes)EditorGUILayout.EnumPopup(_render);
            if (GUILayout.Button("Render"))
            {
                CreateSDFAsset(asset);
            }
            EditorGUI.BeginDisabledGroup(onRendering || asset.type != TexAssetType.FontSigned);
            GUI.backgroundColor = Color.red;

            if (GUILayout.Button("Delete SDF Asset"))
            {
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(((TexFontSigned)asset).asset));
                asset = Deconvert((TexFontSigned)asset);
            }

            GUI.backgroundColor = Color.white;
            EditorGUI.EndDisabledGroup();
            {
                EditorGUILayout.Space();
                if (GUILayout.Button("Render All Fonts"))
                {
                    onRenderingBatch = (EditorUtility.DisplayDialogComplex("Confirm Action", "Are you sure? This will take few moments.\nAnd what will you do with existing SDF Asset?",
                                                                           "Overwrite", "Cancel", "Skip (Faster)"));
                    onRenderingBatch = onRenderingBatch == 1 ? 0 : (onRenderingBatch == 0 ? 1 : 2);
                    if (onRenderingBatch > 0)
                    {
                        DoBatchRendering();
                    }
                }
                EditorGUI.BeginDisabledGroup(onRendering);
                GUI.backgroundColor = new Color(0.5f, 0, 0.5f);
                if (GUILayout.Button("Delete All SDF Asset"))
                {
                    if (EditorUtility.DisplayDialog("Confirm Deletion", "Are you sure you want to delete ALL SDF Font Asset?", "Yes", "No"))
                    {
                        var fonts = TEXPreference.main.fonts;
                        for (int i = 0; i < fonts.Length; i++)
                        {
                            EditorUtility.DisplayProgressBar("Please wait", "Reimporting Fonts...", i / (float)fonts.Length);
                            if (fonts[i].type == TexAssetType.FontSigned)
                            {
                                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(((TexFontSigned)fonts[i]).asset));
                                Deconvert((TexFontSigned)fonts[i]);
                            }
                        }
                        TEXPreference.main.RebuildMaterial();
                        EditorUtility.ClearProgressBar();
                    }
                }
                GUI.backgroundColor = Color.white;
                EditorGUI.EndDisabledGroup();
            }

            EditorGUI.EndDisabledGroup();
            if (onRendering)
            {
                var prog = TMPro_FontPlugin.Check_RenderProgress();
                EditorGUI.ProgressBar(EditorGUILayout.GetControlRect(), prog, prog.ToString("P"));
                if (onRenderingBatch > 0)
                {
                    if (onRenderingBatch == 3)
                    {
                        EditorGUILayout.HelpBox("Will be stopped after current rendering is done", MessageType.Info);
                    }
                    else
                    {
                        GUI.backgroundColor = Color.yellow;
                        if (GUILayout.Button("Cancel"))
                        {
                            onRenderingBatch = 3;
                        }
                        GUI.backgroundColor = Color.white;
                    }
                }
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Render to the provided instance of GL.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        /// <param name="renderMode">The render mode.</param>
        public virtual void Render(RenderModes renderMode)
        {
            //  Push attributes, disable lighting.
            GL.PushAttrib(GL.GL_CURRENT_BIT | GL.GL_ENABLE_BIT |
                GL.GL_LINE_BIT | GL.GL_POLYGON_BIT);
            GL.Disable(GL.GL_LIGHTING);
            GL.Disable(GL.GL_TEXTURE_2D);
            GL.LineWidth(1.0f);
            GL.Color(BoxColor);

            //QuadsDraw(gl);

            //GL.Color(1.0f, 0, 0);
            GL.Begin(PrimitiveModes.LineLoop);
            GL.Vertex(MinPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MinPosition.y, MaxPosition.z);
            GL.End();

            //GL.Color(0, 1.0f, 0);
            GL.Begin(PrimitiveModes.LineLoop);
            GL.Vertex(MinPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MaxPosition.y, MaxPosition.z);
            GL.End();

            //GL.Color(0, 0, 1.0f);
            GL.Begin(PrimitiveModes.Lines);
            GL.Vertex(MinPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MinPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MinPosition.z);
            GL.Vertex(MaxPosition.x, MinPosition.y, MaxPosition.z);
            GL.Vertex(MaxPosition.x, MaxPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MinPosition.y, MaxPosition.z);
            GL.Vertex(MinPosition.x, MaxPosition.y, MaxPosition.z);
            GL.End();

            GL.PopAttrib();
        }
Ejemplo n.º 49
0
        private void RenderersDraw(RenderModes renderMode, bool renderScene = true, bool renderUI = true)
        {
            var arg = new RenderEventArgs(renderMode, this.glCanvas1.ClientRectangle, this.camera, this.PickingGeometryType);
            if (renderMode == RenderModes.ColorCodedPicking)
            {
                if (renderScene)
                {
                    ColorCodedPicking.Render4Picking(arg, this.rendererDict[this.selectedModel].PickableRenderer);
                }
            }
            else if (renderMode == RenderModes.Render)
            {
                OpenGL.ClearColor(ClearColor.R / 255.0f, ClearColor.G / 255.0f, ClearColor.B / 255.0f, ClearColor.A / 255.0f);

                OpenGL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT);

                if (renderScene) { SceneRenderersDraw(arg); }
                if (renderUI) { UIRenderersDraw(arg); }
            }
        }
Ejemplo n.º 50
0
        private void SetRenderMode(RenderModes rm)
        {
            lock (renderSyncObject)
            {
                renderMode = rm;
                if (!IsInitialized && !isInitializing)
                    return;

                //clean up objects that will be invalid after RenderTarget change
                if (dcRenderTarget != null)
                {
                    dcRenderTarget.Dispose();
                    dcRenderTarget = null;
                }
                if (hwndRenderTarget != null)
                {
                    hwndRenderTarget.Dispose();
                    hwndRenderTarget = null;
                }
                if (bitmapRenderTarget != null)
                {
                    bitmapRenderTarget.Dispose();
                    bitmapRenderTarget = null;
                }
                peelings.Clear();
                bitmap = null; //the bitmap created in dc render target can't be used in hwnd render target

                // Create the screen render target
                var size = new SizeU((uint)ClientSize.Width, (uint)ClientSize.Height);
                var props = new RenderTargetProperties
                {
                    PixelFormat = new PixelFormat(
                        Format.B8G8R8A8UNorm,
                        AlphaMode.Ignore),
                    Usage = RenderTargetUsages.GdiCompatible
                };

                if (renderMode == RenderModes.DCRenderTarget || renderMode == RenderModes.BitmapRenderTargetOnPaint)
                {
                    dcRenderTarget = d2DFactory.CreateDCRenderTarget(props);
                    if (renderMode == RenderModes.BitmapRenderTargetOnPaint)
                    {
                        bitmapRenderTarget =
                            dcRenderTarget.CreateCompatibleRenderTarget(
                            CompatibleRenderTargetOptions.GdiCompatible,
                            new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                    }
                    render = null;
                }
                else
                {
                    hwndRenderTarget = d2DFactory.CreateHwndRenderTarget(
                        props,
                        new HwndRenderTargetProperties(Handle, size, Microsoft.WindowsAPICodePack.DirectX.Direct2D1.PresentOptions.RetainContents));
                    if (renderMode == RenderModes.BitmapRenderTargetRealTime)
                    {
                        bitmapRenderTarget =
                            hwndRenderTarget.CreateCompatibleRenderTarget(
                            CompatibleRenderTargetOptions.GdiCompatible,
                            new Microsoft.WindowsAPICodePack.DirectX.Direct2D1.SizeF(ClientSize.Width, ClientSize.Height));
                    }
                    render = RenderSceneInBackground;
                }

                //move all shapes to new rendertarget and refresh
                foreach (var shape in drawingShapes)
                {
                    shape.Bitmap = Bitmap;
                    shape.RenderTarget = RenderTarget;
                }
                RefreshAll();
            }
        }
Ejemplo n.º 51
0
 int Render_Character(byte[] buffer_fill, byte[] buffer_edge, int buffer_width, int buffer_height, int offset, int asc, FaceStyles style, float thickness, RenderModes rasterMode, ref FT_GlyphInfo glyphInfo);
Ejemplo n.º 52
0
        public static void WriteImage(Stream inStream, Stream outStream, int boundWidth, int boundHeight, RenderModes mode)
        {
            Bitmap bmpSrc = null, bmpTrg = null;

            try
            {
                bmpSrc = new Bitmap(inStream);

                // convert TIFF to BMP, use only the first page
                FrameDimension fd = new FrameDimension(bmpSrc.FrameDimensionsList[0]);
                bmpSrc.SelectActiveFrame(fd, 0);

                // crop/fit/stretch
                int imageHeight = bmpSrc.Height, imageWidth = bmpSrc.Width, targetWidth, targetHeight;

                if (boundWidth < 0)
                {
                    boundWidth = imageWidth;
                }
                if (boundHeight < 0)
                {
                    boundHeight = imageHeight;
                }

                if (boundWidth != imageWidth || boundHeight != imageHeight)
                {
                    switch (mode)
                    {
                    case RenderModes.RenderMode_Stretch:
                        bmpTrg = new Bitmap(bmpSrc, new Size(boundWidth, boundHeight));
                        break;

                    case RenderModes.RenderMode_Fit:
                        targetWidth  = imageWidth;
                        targetHeight = imageHeight;
                        float scale = 1F;
                        // a. panel is greater than image: grow
                        if (boundHeight > imageHeight && boundWidth > imageWidth)
                        {
                            scale        = Math.Min((float)boundWidth / imageWidth, (float)boundHeight / imageHeight);
                            targetHeight = Math.Min((int)((float)imageHeight * scale), boundHeight);
                            targetWidth  = Math.Min((int)((float)imageWidth * scale), boundWidth);
                        }
                        // b. image is greater than panel: shrink
                        else
                        {
                            scale        = Math.Max((float)imageWidth / boundWidth, (float)imageHeight / boundHeight);
                            targetWidth  = Math.Min((int)((float)imageWidth / scale), boundWidth);
                            targetHeight = Math.Min((int)((float)imageHeight / scale), boundHeight);
                        }
                        bmpTrg = new Bitmap(bmpSrc, new Size(targetWidth, targetHeight));
                        break;

                    case RenderModes.RenderMode_Crop:
                        targetWidth  = Math.Min(boundWidth, imageWidth);
                        targetHeight = Math.Min(boundHeight, imageHeight);
                        bmpTrg       = bmpSrc.Clone(
                            new Rectangle(0, 0, targetWidth, targetHeight),
                            bmpSrc.PixelFormat
                            );
                        break;
                    }

                    bmpTrg.Save(outStream, ImageFormat.Png);
                }
                else
                {
                    bmpSrc.Save(outStream, ImageFormat.Png);
                }
            }

            finally
            {
                if (bmpTrg != null)
                {
                    bmpTrg.Dispose();
                }
                if (bmpSrc != null)
                {
                    bmpSrc.Dispose();
                }
                GC.Collect();
            }
        }
Ejemplo n.º 53
0
        void DrawControls()
        {
            GUILayout.BeginVertical();
            GUILayout.Label("<b>TextMeshPro - Font Asset Creator</b>", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));
            GUILayout.Label("Font Settings", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));

            GUILayout.BeginVertical(TMP_UIStyleManager.TextureAreaBox, GUILayout.Width(300));
            EditorGUIUtility.LookLikeControls(120f, 160f);

            // FONT TTF SELECTION
            font_TTF = EditorGUILayout.ObjectField("Font Source", font_TTF, typeof(Font), false, GUILayout.Width(290)) as Font;

            // FONT SIZING
            if (FontSizingOption_Selection == 0)
            {
                FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(290));
            }
            else
            {
                EditorGUIUtility.LookLikeControls(120f, 40f);
                GUILayout.BeginHorizontal(GUILayout.Width(290));
                FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(225));
                font_size = EditorGUILayout.IntField(font_size);
                GUILayout.EndHorizontal();
            }

            EditorGUIUtility.LookLikeControls(120f, 160f);

            
            // FONT PADDING
            font_padding = EditorGUILayout.IntField("Font Padding", font_padding, GUILayout.Width(290));
            font_padding = (int)Mathf.Clamp(font_padding, 0f, 64f);

            // FONT PACKING METHOD SELECTION
            m_fontPackingSelection = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_fontPackingSelection, GUILayout.Width(225));
            
            //font_renderingMode = (FontRenderingMode)EditorGUILayout.EnumPopup("Rendering Mode", font_renderingMode, GUILayout.Width(290));

            // FONT ATLAS RESOLUTION SELECTION
            GUILayout.BeginHorizontal(GUILayout.Width(290));
            GUI.changed = false;
            EditorGUIUtility.LookLikeControls(120f, 40f);

            GUILayout.Label("Atlas Resolution:", GUILayout.Width(116));
            font_atlas_width = EditorGUILayout.IntPopup(font_atlas_width, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));
            font_atlas_height = EditorGUILayout.IntPopup(font_atlas_height, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));

            GUILayout.EndHorizontal();


            // FONT CHARACTER SET SELECTION
            GUI.changed = false;
            font_CharacterSet_Selection = EditorGUILayout.Popup("Character Set", font_CharacterSet_Selection, FontCharacterSets, GUILayout.Width(290));
            if (GUI.changed)
            {
                characterSequence = "";
                //Debug.Log("Resetting Sequence!");
            }

            switch (font_CharacterSet_Selection)
            {
                case 0: // ASCII
                    //characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
                    characterSequence = "32 - 126, 8230";
                    break;

                case 1: // EXTENDED ASCII
                    characterSequence = "32 - 126, 160 - 255, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252, 8254, 8260, 8286, 8364";
                    break;

                case 2: // Lowercase
                    characterSequence = "32 - 64, 91 - 126";
                    break;

                case 3: // Uppercase
                    characterSequence = "32 - 96, 123 - 126";
                    break;

                case 4: // Numbers & Symbols
                    characterSequence = "32 - 64, 91 - 96, 123 - 126";
                    break;

                case 5: // Custom Range
                    GUILayout.BeginHorizontal(GUILayout.Width(290));
                    GUILayout.Label("Custom Range (Dec)", GUILayout.Width(116));

                    // Filter out unwanted characters.
                    char chr = Event.current.character;
                    if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
                    {
                        Event.current.character = '\0';
                    }
                    characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));

                    GUILayout.EndHorizontal();
                    break;

                case 6: // Unicode HEX Range
                    GUILayout.BeginHorizontal(GUILayout.Width(290));
                    GUILayout.Label("Unicode Range (Hex)", GUILayout.Width(116));

                    // Filter out unwanted characters.
                    chr = Event.current.character;
                    if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-'))
                    {
                        Event.current.character = '\0';
                    }
                    characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));

                    GUILayout.EndHorizontal();
                    break;


                case 7: // Custom Characters
                    GUILayout.BeginHorizontal(GUILayout.Width(290));

                    GUILayout.Label("Custom Characters", GUILayout.Width(116));
                    characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
                    GUILayout.EndHorizontal();
                    break;

                case 8: // Character List from File
                    characterList = EditorGUILayout.ObjectField("Character File", characterList, typeof(TextAsset), false, GUILayout.Width(290)) as TextAsset;
                    if (characterList != null)
                    {
                        characterSequence = characterList.text;
                    }
                    break;
            }

            EditorGUIUtility.LookLikeControls(120f, 40f);

            // FONT STYLE SELECTION
            GUILayout.BeginHorizontal(GUILayout.Width(290));
            font_style = (FaceStyles)EditorGUILayout.EnumPopup("Font Style:", font_style, GUILayout.Width(225));
            font_style_mod = EditorGUILayout.IntField((int)font_style_mod);
            GUILayout.EndHorizontal();

            // Render Mode Selection   
            font_renderMode = (RenderModes)EditorGUILayout.EnumPopup("Font Render Mode:", font_renderMode, GUILayout.Width(290));

            includeKerningPairs = EditorGUILayout.Toggle("Get Kerning Pairs?", includeKerningPairs, GUILayout.MaxWidth(290));

            EditorGUIUtility.LookLikeControls(120f, 160f);

            GUILayout.Space(20);

            GUI.enabled = font_TTF == null || isProcessing ? false : true;    // Enable Preview if we are not already rendering a font.
            if (GUILayout.Button("Generate Font Atlas", GUILayout.Width(290)) && characterSequence.Length != 0 && GUI.enabled)
            {
                if (font_TTF != null)
                {
                    int error_Code;

                    error_Code = TMPro_FontPlugin.Initialize_FontEngine(); // Initialize Font Engine
                    if (error_Code != 0)
                    {
                        if (error_Code == 99)
                        {
                            //Debug.Log("Font Library was already initialized!");
                            error_Code = 0;
                        }
                        else
                            Debug.Log("Error Code: " + error_Code + "  occurred while Initializing the FreeType Library.");
                    }

                    string fontPath = AssetDatabase.GetAssetPath(font_TTF); // Get file path of TTF Font.

                    if (error_Code == 0)
                    {
                        error_Code = TMPro_FontPlugin.Load_TrueType_Font(fontPath); // Load the selected font.

                        if (error_Code != 0)
                        {
                            if (error_Code == 99)
                            {
                                //Debug.Log("Font was already loaded!");
                                error_Code = 0;
                            }
                            else
                                Debug.Log("Error Code: " + error_Code + "  occurred while Loading the font.");
                        }
                    }

                    if (error_Code == 0)
                    {
                        if (FontSizingOption_Selection == 0) font_size = 72; // If Auto set size to 72 pts.

                        error_Code = TMPro_FontPlugin.FT_Size_Font(font_size); // Load the selected font and size it accordingly.
                        if (error_Code != 0)
                            Debug.Log("Error Code: " + error_Code + "  occurred while Sizing the font.");
                    }

                    // Define an array containing the characters we will render.
                    if (error_Code == 0)
                    {
                        int[] character_Set = null;
                        if (font_CharacterSet_Selection == 7 || font_CharacterSet_Selection == 8)
                        {
                            List<int> char_List = new List<int>();
                            
                            for (int i = 0; i < characterSequence.Length; i++)
                            {
                                // Check to make sure we don't include duplicates
                                if (char_List.FindIndex(item => item == characterSequence[i]) == -1)
                                    char_List.Add(characterSequence[i]);
                                else
                                {
                                    //Debug.Log("Character [" + characterSequence[i] + "] is a duplicate.");
                                }
                            }

                            character_Set = char_List.ToArray();
                        }
                        else if (font_CharacterSet_Selection == 6)
                        {
                            character_Set = ParseHexNumberSequence(characterSequence);
                        }
                        else
                        {
                            character_Set = ParseNumberSequence(characterSequence);
                        }

                        m_character_Count = character_Set.Length;

                        m_texture_buffer = new byte[font_atlas_width * font_atlas_height];

                        m_font_faceInfo = new FT_FaceInfo();

                        m_font_glyphInfo = new FT_GlyphInfo[m_character_Count];

                        int padding = font_padding;

                        bool autoSizing = FontSizingOption_Selection == 0 ? true : false;

                        float strokeSize = font_style_mod;
                        if (font_renderMode == RenderModes.DistanceField16) strokeSize = font_style_mod * 16;
                        if (font_renderMode == RenderModes.DistanceField32) strokeSize = font_style_mod * 32;
                        
                        isProcessing = true;
                        
                        ThreadPool.QueueUserWorkItem(SomeTask =>
                        {
                            isRenderingDone = false;
                            
                            error_Code = TMPro_FontPlugin.Render_Characters(m_texture_buffer, font_atlas_width, font_atlas_height, padding, character_Set, m_character_Count, font_style, strokeSize, autoSizing, font_renderMode,(int)m_fontPackingSelection, ref m_font_faceInfo, m_font_glyphInfo);
                            isRenderingDone = true;
                            //Debug.Log("Font Rendering is completed.");
                        });
                        
                        previewSelection = PreviewSelectionTypes.PreviewFont;
                        
                    }
                }
            }


            // FONT RENDERING PROGRESS BAR
            GUILayout.Space(1);
            progressRect = GUILayoutUtility.GetRect(288, 20, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Width(288), GUILayout.Height(20));

            GUI.BeginGroup(progressRect);
            GUI.DrawTextureWithTexCoords(new Rect(2, 0, 288, 20), TMP_UIStyleManager.progressTexture, new Rect(1 - m_renderingProgress, 0, 1, 1));
            GUI.EndGroup();


            // FONT STATUS & INFORMATION
            GUISkin skin = GUI.skin;
            GUI.skin = TMP_UIStyleManager.TMP_GUISkin;

            GUILayout.Space(5);
            GUILayout.BeginVertical(TMP_UIStyleManager.TextAreaBoxWindow);
            output_ScrollPosition = EditorGUILayout.BeginScrollView(output_ScrollPosition, GUILayout.Height(145));
            EditorGUILayout.LabelField(output_feedback, TMP_UIStyleManager.Label);
            EditorGUILayout.EndScrollView();
            GUILayout.EndVertical();

            GUI.skin = skin;

            GUILayout.Space(10);


            // SAVE TEXTURE & CREATE and SAVE FONT XML FILE
            GUI.enabled = m_font_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
            if (GUILayout.Button("Save TextMeshPro Font Asset", GUILayout.Width(290)) && GUI.enabled)
            {
                string filePath = string.Empty;

                if (font_renderMode < RenderModes.DistanceField16) // == RenderModes.HintedSmooth || font_renderMode == RenderModes.RasterHinted)
                {
                    filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name, "asset");

                    if (filePath.Length == 0)
                        return;

                    Save_Normal_FontAsset(filePath);
                }
                else if (font_renderMode >= RenderModes.DistanceField16)
                {
                    filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");

                    if (filePath.Length == 0)
                        return;

                    Save_SDF_FontAsset(filePath);
                }

            }

            GUI.enabled = true; // Re-enable GUI

            GUILayout.Space(5);

            GUILayout.EndVertical();

            GUILayout.Space(25);

            /*
            // GENERATE DISTANCE FIELD TEXTURE
            GUILayout.Label("Distance Field Options", SectionLabel, GUILayout.Width(300));

            GUILayout.BeginVertical(textureAreaBox, GUILayout.Width(300));

            GUILayout.Space(5);


            font_spread = EditorGUILayout.IntField("Spread", font_spread, GUILayout.Width(280));
            font_scaledownFactor = EditorGUILayout.IntField("Scale down factor", font_scaledownFactor, GUILayout.Width(280));
            if (GUI.changed)
            {
                EditorPrefs.SetInt("Font_Spread", font_spread);
                EditorPrefs.SetInt("Font_ScaleDownFactor", font_scaledownFactor);
            }

            GUILayout.Space(20);

            GUI.enabled = m_font_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
            if (GUILayout.Button("Preview Distance Field Font Atlas", GUILayout.Width(290)))
            {

                if (m_font_Atlas != null && isProcessing == false)
                {
                    // Generate Distance Field	                 
                    int width = m_font_Atlas.width;
                    int height = m_font_Atlas.height;
                    Color[] colors = m_font_Atlas.GetPixels(); // Should modify this to use Color32 instead

                    isProcessing = true;

                    ThreadPool.QueueUserWorkItem(SomeTask => { TMPro_DistanceTransform.Generate(colors, width, height, font_spread, font_scaledownFactor); });

                    previewSelection = PreviewSelectionTypes.PreviewDistanceField;
                }
            }

            GUILayout.Space(1);

            progressRect = GUILayoutUtility.GetRect(290, 20, textAreaBox, GUILayout.Width(290), GUILayout.Height(20));

            GUI.BeginGroup(progressRect);

            GUI.DrawTextureWithTexCoords(new Rect(0, 0, 290, 20), progressTexture, new Rect(1 - ProgressPercentage, 0, 1, 1));
            GUI.EndGroup();

            //GUILayout.Space(5);

            GUI.enabled = m_destination_Atlas != null ? true : false;    // Enable Save Button if font_Atlas is not Null.
            if (GUILayout.Button("Save TextMeshPro (SDF) Font Asset", GUILayout.Width(290)))
            {
                string filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");

                if (filePath.Length == 0)
                    return;

                Save_SDF_FontAsset(filePath);

            } 
                         
            GUILayout.EndVertical();
            */
             
            // Figure out the size of the current UI Panel
            Rect rect = EditorGUILayout.GetControlRect(false, 5);
            if (Event.current.type == EventType.Repaint)
                m_UI_Panel_Size = rect;

            GUILayout.EndVertical();
        }
        private void DrawStereo(RenderModes mode, GameTime time, GraphicsDevice device, SpriteBatch sb)
        {
            // Find the X-vector in the camera view plane so that
            // a positive offset is towards the right eye and
            // a negative offset is towards the left.
            Vector3 originalPos = Camera.Position;
            Vector3 originalLookAt = Camera.LookAt;
            Vector3 cameraViewX = Vector3.Cross(Camera.LookAt - Camera.Position, Camera.Up);
            cameraViewX.Normalize();

            // Place eyes some cm apart
            Vector3 leftEyePosition = originalPos - cameraViewX*HalfEyeDistance;
            Vector3 rightEyePosition = originalPos + cameraViewX*HalfEyeDistance;

            if (_settings.SwapStereo)
            {
                Vector3 tmp = rightEyePosition;
                rightEyePosition = leftEyePosition;
                leftEyePosition = tmp;
            }

            // Render left eye
            DrawLeftEye(time, leftEyePosition, mode, device, sb);

            // Render right eye
            DrawRightEye(time, rightEyePosition, mode, device, sb);

            // Restore camera position and update its internal view matrices
            Camera.Position = originalPos;
            Camera.LookAt = originalLookAt;
            Camera.UpdateMatrices();


            // Special care must be taken to present the cross converged 
            // graphics (two sources) to a single backbuffer target
            if (mode == RenderModes.StereoCrossConverged)
                PresentCrossConverged(device, sb);
        }