Ejemplo n.º 1
0
        static void Process()
        {
            using (var output = new StringWriter())
            {
                var parameters = new ConversionParameters
                {
                    InputPath           = @"nanovg\nansovg.c",
                    Output              = output,
                    Defines             = new string[0],
                    Namespace           = "NanoVGSharp",
                    Class               = "NanoSVG",
                    SkipStructs         = new string[0],
                    SkipGlobalVariables = new string[0],
                    SkipFunctions       = new string[0],
                    Classes             = new string[]
                    {
                    },
                    GlobalArrays = new string[0]
                };

                var cp = new ClangParser();

                cp.Process(parameters);
                var data = output.ToString();

                // Post processing
                Logger.Info("Post processing...");

                data = Utility.ReplaceNativeCalls(data);

                File.WriteAllText(@"..\..\..\..\..\src\NanoSVG.Generated.cs", data);
            }
        }
Ejemplo n.º 2
0
    public static ConversionParameters MakeSweref99L1630()
    {
        ConversionParameters p = MakeSweref99Basic();

        p.central_meridian = 16.50;
        return(p);
    }
Ejemplo n.º 3
0
        public string ApplyConversionRule(string sourceCode, ConversionParameters conversionParameters)
        {
            Logger.AddLog(String.Format("ApplyingRule Name:{0}-Type:{1}-Priority:{2}", RuleName, RuleType, RuleTypePriority));

            var match = Regex.Match(sourceCode, RuleApplicablePattern);

            if (match.Success)
            {
                Logger.AddLog("SourceCode:" + match.Value);

                string comment = match.Groups["comment"].ToString();

                var convertedCode = @"\\ " + comment.Trim();

                if (conversionParameters.CopyComments == false)
                {
                    conversionParameters.AddConvertedCode(convertedCode);
                }

                Logger.AddLog("ConvertedCode:" + convertedCode);

                return(sourceCode.Remove(match.Index, match.Length));
            }

            Logger.AddLog("MatchFailed");
            return(sourceCode);
        }
Ejemplo n.º 4
0
        public string ApplyConversionRule(string sourceCode, ConversionParameters conversionParameters)
        {
            Logger.AddApplyConversionRuleEntryLog(RuleName, RuleType, RuleTypePriority);

            var match = Regex.Match(sourceCode, RuleApplicablePattern);

            if (match.Success)
            {
                Logger.AddSourceCode(match.Value);

                string leadingSpace     = match.Groups["leadingSpace"].ToString();
                string methodName       = match.Groups["methodName"].ToString();
                string methodParameters = match.Groups["methodParameters"].ConvertToString();
                string comments         = match.Groups["comments"].ConvertToString();

                conversionParameters.AddMethodName(leadingSpace, methodName, comments);

                foreach (var variableNameWithSpace in methodParameters.Split(','))
                {
                    string variableName = variableNameWithSpace.Trim();
                    conversionParameters.AddMethodParameters(Utility.GetType(variableName), variableName);
                }

                sourceCode = sourceCode.Remove(match.Index, match.Length);

                if (sourceCode.Length > 0 && sourceCode.Substring(0, 1) == "\n")
                {
                    sourceCode = sourceCode.Remove(0, 1);
                }
                return(sourceCode);
            }

            Logger.AddLog("MatchFailed");
            return(sourceCode);
        }
Ejemplo n.º 5
0
        static void Process()
        {
            var parameters = new ConversionParameters
            {
                InputPath = @"stb_rect_pack.h",
                Defines   = new string[]
                {
                    "STB_RECT_PACK_IMPLEMENTATION"
                },
                SkipStructs = new string[]
                {
                    "stbrp_context"
                },
                SkipGlobalVariables = new string[]
                {
                },
                SkipFunctions = new string[]
                {
                },
                Classes = new string[]
                {
                },
                GlobalArrays = new string[]
                {
                }
            };

            var cp = new ClangParser();

            var result = cp.Process(parameters);

            // Write output
            var sb = new StringBuilder();

            sb.AppendLine(string.Format("// Generated by Sichem at {0}", DateTime.Now));
            sb.AppendLine();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.Runtime.InteropServices;");

            sb.AppendLine();

            sb.Append("namespace StbRectPackSharp\n{\n\t");
            sb.AppendLine("unsafe partial class StbRectPack\n\t{");

            Write(result.Constants, sb);
            Write(result.GlobalVariables, sb);
            Write(result.Enums, sb);
            Write(result.Structs, sb);
            Write(result.Methods, sb);

            sb.Append("}\n}");
            var data = sb.ToString();

            // Post processing
            Logger.Info("Post processing...");
            data = PostProcess(data);

            File.WriteAllText(@"..\..\..\..\..\src\StbRectPack.Generated.cs", data);
        }
        public void Init()
        {
            // MAKE SURE before you run this test, you MUST change the API key to yours; otherwise the test fails.
            this._settings = ConverterSettings.CreateInstance();
            this._formats  = new Formats();
            this._wrapper  = new ConverterWrapper(this._settings);

            this._input = new InputParameters()
            {
                InputFormat = this._formats.Document.Md,
                InputMethod = InputMethod.Download,
                Filepath    = "https://raw.githubusercontent.com/aliencube/CloudConvert.NET/dev/README.md",
                Filename    = "README.md",
            };
            this._output = new OutputParameters()
            {
                DownloadMethod = DownloadMethod.False,
                OutputStorage  = OutputStorage.OneDrive,
            };
            this._conversion = new ConversionParameters()
            {
                OutputFormat     = this._formats.Document.Docx,
                ConverterOptions = new MarkdownConverterOptions()
                {
                    InputMarkdownSyntax = MarkdownSyntaxType.Auto
                },
            };
        }
Ejemplo n.º 7
0
        public string ApplyConversionRule(string sourceCode, ConversionParameters conversionParameters)
        {
            Logger.AddApplyConversionRuleEntryLog(RuleName, RuleType, RuleTypePriority);

            var match = Regex.Match(sourceCode, RuleApplicablePattern);

            if (match.Success)
            {
                Logger.AddSourceCode(match.Value);

                string leadingSpace   = match.Groups["leadingSpace"].ToString();
                int    parameterCount = match.Groups["parameterCount"].ConvertToInt32();
                string parameterName  = match.Groups["parameterName"].ToString();
                string defaultValue   = match.Groups["defaultValue"].ConvertToString();

                conversionParameters.AddOptionalParameterValue(parameterName, defaultValue, parameterCount);

                sourceCode = sourceCode.Remove(match.Index, match.Length);

                if (sourceCode.Length > 0 && sourceCode.Substring(0, 1) == "\n")
                {
                    sourceCode = sourceCode.Remove(0, 1);
                }
                return(sourceCode);
            }

            Logger.AddLog("MatchFailed");
            return(sourceCode);
        }
Ejemplo n.º 8
0
        public bool IsRuleApplicable(string sourceCode, ConversionParameters conversionParameters)
        {
            // Get first Line
            var match = Regex.Match(sourceCode, RuleApplicablePattern);

            return(match.Success);
        }
Ejemplo n.º 9
0
        public void Init()
        {
            // MAKE SURE before you run this test, you MUST change the API key to yours; otherwise the test fails.
            this._settings = ConverterSettings.CreateInstance();
            this._formats  = new Formats();
            this._wrapper  = new ConverterWrapper(this._settings);

            this._input = new InputParameters()
            {
                InputFormat = this._formats.Website.Website,
                InputMethod = InputMethod.Url,
                Filepath    = "http://www.google.com"
            };
            this._output = new OutputParameters()
            {
                DownloadMethod = DownloadMethod.False,
                OutputStorage  = OutputStorage.None,
                Wait           = true
            };
            this._conversion = new ConversionParameters()
            {
                OutputFormat     = this._formats.Document.Pdf,
                ConverterOptions = null
            };
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="conversionParams">转换参数</param>
        public ConversionService(ConversionParameters conversionParams)
        {
            if (conversionParams == null || conversionParams.ConversionSevenParams == null)
            {
                throw new Exception("转换参数或转换七参数为空");
            }

            coordinateTransform = new CoordinateTransform(conversionParams);
        }
Ejemplo n.º 11
0
        static void Process()
        {
            using (var output = new StringWriter())
            {
                var parameters = new ConversionParameters
                {
                    InputPath = @"stb_dxt.h",
                    Output    = output,
                    Defines   = new[]
                    {
                        "STB_DXT_IMPLEMENTATION"
                    },
                    Namespace   = "StbSharp",
                    Class       = "StbDxt",
                    SkipStructs = new string[]
                    {
                    },
                    SkipGlobalVariables = new string[]
                    {
                    },
                    SkipFunctions = new[]
                    {
                        "stb__DitherBlock"
                    },
                    Classes = new string[]
                    {
                    },
                    GlobalArrays = new[]
                    {
                        "stb__Expand5",
                        "stb__Expand6",
                        "stb__OMatch5",
                        "stb__OMatch6",
                        "stb__QuantRBTab",
                        "stb__QuantGTab"
                    }
                };

                var cp = new ClangParser();

                cp.Process(parameters);
                var data = output.ToString();

                // Post processing
                Logger.Info("Post processing...");

                data = Utility.ReplaceNativeCalls(data);

                data = data.Replace("byte* minp;", "byte* minp = null;");
                data = data.Replace("byte* maxp;", "byte* maxp = null;");
                data = data.Replace("public static void stb__PrepareOptTable(byte* Table, byte* expand, int size)",
                                    "public static void stb__PrepareOptTable(byte[] Table, byte[] expand, int size)");

                File.WriteAllText(@"..\..\..\..\..\StbSharp\StbDxt.Generated.cs", data);
            }
        }
Ejemplo n.º 12
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     ConversionsRequested.Add(value);
     ConversionParameters.Add(parameter);
     ConversionTypes.Add(targetType);
     if (ThrowOnConversion)
     {
         throw new MvxException("Conversion throw requested");
     }
     return(ConversionResult);
 }
Ejemplo n.º 13
0
        public bool IsRuleApplicable(string sourceCode, ConversionParameters conversionParameters)
        {
            if (conversionParameters.CopyComments == false)
            {
                return(false);
            }

            // Get first Line
            var match = Regex.Match(sourceCode, RuleApplicablePattern);

            return(match.Success);
        }
Ejemplo n.º 14
0
        private CoordinateType targetCT;       // 目标坐标类型

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="parameters">转换参数</param>
        public CoordinateTransform(ConversionParameters parameters)
        {
            if (parameters == null || parameters.ConversionSevenParams == null)
            {
                throw new Exception("转换参数或转换七参数为空");
            }

            this.sevenParams    = parameters.ConversionSevenParams;
            this.sourceCS       = parameters.SourceCoordinateSystem;
            this.targetCS       = parameters.TargetCoordinateSystem;
            this.sourceMeridian = parameters.SourceCenterMeridian;
            this.targetMeridian = parameters.TargetCenterMeridian;
            this.sourceCT       = parameters.SourceCoordinateType;
            this.targetCT       = parameters.TargetCoordinateType;
        }
Ejemplo n.º 15
0
        public string ApplyConversionRule(string sourceCode, ConversionParameters conversionParameters)
        {
            Logger.AddApplyConversionRuleEntryLog(RuleName, RuleType, RuleTypePriority);

            var match = Regex.Match(sourceCode, RuleApplicablePattern);

            if (match.Success)
            {
                Logger.AddSourceCode(match.Value);

                string leadingSpace = match.Groups["leadingSpace"].ToString();
                //string variableName =

                StringBuilder convertedCodeBuilder       = new StringBuilder();
                Dictionary <string, string> groupBuilder = new Dictionary <string, string>();
                foreach (Match subMatch in Regex.Matches(match.Value, SubPattern))
                {
                    string variableName = subMatch.Groups["variableName"].Value;


                    Utility.ConvertVariables(conversionParameters, groupBuilder, convertedCodeBuilder, variableName, leadingSpace, true);
                }

                if (conversionParameters.IsLocalVariableGroupingRequired)
                {
                    foreach (KeyValuePair <string, string> keyValuePair in groupBuilder)
                    {
                        convertedCodeBuilder.AppendLine(leadingSpace + keyValuePair.Key + " " + keyValuePair.Value + ";");
                    }
                }

                string convertedCode = convertedCodeBuilder.ToString();
                conversionParameters.AddConvertedCode(convertedCode);

                Logger.AddConvertedCode(convertedCode);

                sourceCode = sourceCode.Remove(match.Index, match.Length);

                if (sourceCode.Length > 0 && sourceCode.Substring(0, 1) == "\n")
                {
                    sourceCode = sourceCode.Remove(0, 1);
                }
                return(sourceCode);
            }

            Logger.AddLog("MatchFailed");
            return(sourceCode);
        }
Ejemplo n.º 16
0
        public void ConvertVideo(long materialID)
        {
            try
            {
                if (_converter == null)
                {
                    return;
                }

                var material = _unitOfWork.MaterialRepository.Get(materialID);
                if (material == null || material.File == null)
                {
                    return;
                }

                var videoPath   = _infrastructure.GetMaterialPath(material);
                var videoUrl    = _infrastructure.StorageService.GetFileUrl(videoPath);
                var videoFormat = material.File.FileName.Extension.Trim('.');

                var input = new InputParameters()
                {
                    Filepath    = videoUrl,
                    InputFormat = videoFormat.ToLower(),
                    InputMethod = InputMethod.Download
                };

                var output = new OutputParameters()
                {
                    SaveToServer = true
                };

                var conversion = new ConversionParameters()
                {
                    OutputFormat = "mp4"
                };

                var result = _converter.ConvertAsync(input, output, conversion).Result;

                if (result != null && !String.IsNullOrWhiteSpace(result.Url))
                {
                    Task.Run(() => this.WaitForConvertaion(materialID, result.Url));
                }
            }
            catch (Exception ex) { }
        }
Ejemplo n.º 17
0
        public static void ConvertVariables(ConversionParameters conversionParameters, Dictionary <string, string> groupBuilder, StringBuilder convertedCodeBuilder, string variableName, string leadingSpace, bool isList)
        {
            string dataType = null;

            if (conversionParameters.IsLastCharacterType)
            {
                string typeString = Utility.GetType(variableName);
                dataType = isList ? "List<" + typeString + ">" : typeString;
            }
            else
            {
                dataType = isList ? "List<object>" : "object";
            }
            if (conversionParameters.IsLocalVariableGroupingRequired)
            {
                AddToGroupBuilder(groupBuilder, dataType, variableName);
            }
            else
            {
                convertedCodeBuilder.AppendLine(leadingSpace + dataType + " " + variableName + ";");
            }
        }
        public void GetConvertRequest_GivenParameters_ReturnConvertRequest()
        {
            var conversion = new ConversionParameters()
            {
                OutputFormat     = this._formats.Document.Docx,
                ConverterOptions = new MarkdownConverterOptions()
                {
                    InputMarkdownSyntax = MarkdownSyntaxType.Auto
                },
            };
            var request = this._wrapper.GetConvertRequest(this._input, this._output, conversion);

            request.InputMethod.Should().Be(InputMethod.Download.ToLower());
            request.OutputStorage.Should().Be(OutputStorage.OneDrive.ToLower());

            var serialised1 = this._wrapper.Serialise(request);

            serialised1.Should().Contain("input_markdown_syntax");

            conversion = new ConversionParameters()
            {
                OutputFormat     = this._formats.Document.Docx,
                ConverterOptions = new Dictionary <string, object>()
                {
                    { "input_markdown_syntax", MarkdownSyntaxType.Auto },
                },
            };
            request = this._wrapper.GetConvertRequest(this._input, this._output, conversion);
            request.InputMethod.Should().Be(InputMethod.Download.ToLower());
            request.OutputStorage.Should().Be(OutputStorage.OneDrive.ToLower());

            var serialised2 = this._wrapper.Serialise(request);

            serialised2.Should().Contain("input_markdown_syntax");

            serialised1.Should().BeEquivalentTo(serialised2);
        }
Ejemplo n.º 19
0
        //Convert a mbm file to dds
        public static void ConvertMBMtoDDS(ConversionParameters convParams, FolderProcessingParams cfg)
        {
            //get a new filepath with a dds extension
            var fpNew = Path.ChangeExtension(convParams.FilePath, ".dds");

            //open a new mbm file
            var mbmTemp = new MBMLoader.MBMFile(convParams.FilePath);

            //resize ratio
            var dRatio = cfg.ResizeRatio;

            if (convParams.ResizeSetting == ResizeSetting.DontAllowResize)
            {
                dRatio = 1;
            }

            //mipmaps level
            var mipmapLevel = 0;

            if (convParams.MipmapSetting == MipmapSetting.DontGenerate)
            {
                mipmapLevel = 1;
            }

            //output format
            var form = default(Format);

            switch (convParams.OutputFormat)
            {
            case OutputFormat.AutoUncompressed:
                if (mbmTemp.IsNormal)
                {
                    form = Format.A8R8G8B8;
                }
                else if (mbmTemp.ColorDepth == 24)
                {
                    form = Format.R8G8B8;
                }
                else
                {
                    form = Format.A8R8G8B8;
                }
                break;

            case OutputFormat.AutoCompressed:
                form = mbmTemp.ColorDepth == 24 ? Format.Dxt1 : Format.Dxt5;
                break;

            case OutputFormat.ForceArgb8:
                form = Format.A8R8G8B8;
                break;

            case OutputFormat.ForceRgb8:
                form = Format.R8G8B8;
                break;

            case OutputFormat.ForceDXT5:
                form = Format.Dxt5;
                break;

            case OutputFormat.ForceDXT1:
                form = Format.Dxt1;
                break;
            }

            //force normal, or automatic detection
            var bNormal = false;

            switch (convParams.NormalMapConversion)
            {
            case NormalMapConversion.Automatic:
                bNormal = mbmTemp.IsNormal;
                break;

            case NormalMapConversion.ForceNormal:
                bNormal = true;
                break;
            }

            //conversion
            using (var gs = new MemoryStream())
            {
                mbmTemp.AsBitmap().Save(gs, ImageFormat.Bmp);

                MainForm.Log_WriteLine("LOG : Converting " + convParams.FilePath + " to " + fpNew);
                MainForm.Log_WriteLine("    Format : " + form + ", normalmap : " + bNormal + ", res: " + (mbmTemp.Width * dRatio) + "x" + (mbmTemp.Height * dRatio));

                if ((((mbmTemp.Width < cfg.MinRes_Resize_Width) | (mbmTemp.Height < cfg.MinRes_Resize_Height)) & (Math.Abs(dRatio - 1) > 0.0001f)))
                {
                    MainForm.Log_WriteLine("LOG : " + convParams.FilePath.Split('.').Last() + ", resolution is too low to be resized.");
                    dRatio = 1;
                }
                gs.Position = 0;

                using (var t = TextureLoader.FromStream(dev, gs, (int)(mbmTemp.Width * dRatio), (int)(mbmTemp.Height * dRatio), mipmapLevel, Usage.None, form, Pool.SystemMemory, Filter.Triangle | Filter.Dither, Filter.Triangle | Filter.Dither, 0))
                {
                    TextureLoader.Save(fpNew, ImageFileFormat.Dds, t);
                }
            }

            //set flag for dxt5nm
            if (bNormal)
            {
                MarkAsNormal(fpNew);
            }

            //flush textures
            mbmTemp.Flush();

            var ddsifiedFile = convParams.FilePath + ".ddsified";

            //delete file after successful conversion
            if (File.Exists(fpNew))
            {
                if (cfg.BackupFile)
                {
                    if (File.Exists(ddsifiedFile))
                    {
                        File.Delete(ddsifiedFile);
                    }

                    File.Move(convParams.FilePath, convParams.FilePath + ".ddsified");
                }
                else if (cfg.DeleteFilesOnSuccess)
                {
                    File.Delete(convParams.FilePath);
                }
            }
        }
Ejemplo n.º 20
0
        static void Process()
        {
            var parameters = new ConversionParameters
            {
                InputPath = @"stb_truetype.h",
                Defines   = new[]
                {
                    "STB_TRUETYPE_IMPLEMENTATION",
                },
                SkipStructs = new string[]
                {
                },
                SkipGlobalVariables = new string[]
                {
                },
                SkipFunctions = new string[]
                {
                    "stbtt__find_table",
                },
                Classes = new string[]
                {
                    "stbtt_pack_context",
                    "stbtt_fontinfo",
                },
                GlobalArrays = new string[]
                {
                },
                GenerateSafeCode = false,
            };

            var cp = new ClangParser();

            var result = cp.Process(parameters);

            // Post processing
            Logger.Info("Post processing...");

            var outputFiles = new Dictionary <string, string>();

            Write(result.Constants, outputFiles);
            Write(result.GlobalVariables, outputFiles);
            Write(result.Enums, outputFiles);
            Write(result.Structs, outputFiles);
            Write(result.Methods, outputFiles);

            foreach (var pair in outputFiles)
            {
                var data = PostProcess(pair.Value);

                var sb = new StringBuilder();
                sb.AppendLine(string.Format("// Generated by Sichem at {0}", DateTime.Now));
                sb.AppendLine();

                sb.AppendLine("using System;");
                sb.AppendLine("using System.Runtime.InteropServices;");

                sb.AppendLine();

                sb.Append("namespace StbTrueTypeSharp\n{\n\t");
                sb.AppendLine("unsafe partial class StbTrueType\n\t{");

                data  = sb.ToString() + data;
                data += "}\n}";

                var fileName = @"..\..\..\..\..\src\StbTrueType.Generated." + pair.Key + ".cs";
                Logger.Info("Writing {0}", fileName);
                File.WriteAllText(fileName, data);
            }
        }
Ejemplo n.º 21
0
        //convert a non-mbm file to dds

        public static void ConvertFileToDDS(ConversionParameters convParams, FolderProcessingParams cfg)
        {
            var sw = Stopwatch.StartNew();

            //test: to avoid memory leak, reset the device before every conversion... As this program can't compile on for x64 OSs, large texture hit memory lmit quite fast...
            //there's a known bug with DirectX9 and his way to load TGA files, image buffer is kept in memory even when the texture is disposed. And, of course, .NET's GarbageCollector is not useful AT ALL here...
            ResetDevice();
            /////
            //normals. Since the AssumeNormalMap() function is able to determine if a file failed to load, this function should be called before anything else
            var bNormal   = false;
            var bLoadFail = false;

            switch (convParams.NormalMapConversion)
            {
            case NormalMapConversion.Automatic:
                bNormal = AssumeNormalMap(convParams.FilePath, out bLoadFail);
                break;

            case NormalMapConversion.ForceNormal:
                bNormal = true;
                break;
            }

            //skip the file if it failed to load
            if (bLoadFail)
            {
                return;
            }

            //get a new filepath for our newly created dds
            var fpNew = Path.ChangeExtension(convParams.FilePath, ".dds");
            //retrive infos from the original file
            var iInfos = TextureLoader.ImageInformationFromFile(convParams.FilePath);

            //resize ratio
            var dRatio = cfg.ResizeRatio;

            if (convParams.ResizeSetting == ResizeSetting.DontAllowResize)
            {
                dRatio = 1;
            }

            //Mipmaps level
            var mipmapLevel = 0;

            if (convParams.MipmapSetting == MipmapSetting.DontGenerate)
            {
                mipmapLevel = 1;
            }

            //Output format
            var form = default(Format);

            switch (convParams.OutputFormat)
            {
            case OutputFormat.AutoUncompressed:
                if (bNormal)
                {
                    form = Format.A8R8G8B8;
                }
                else
                {
                    form = Is32BPP(iInfos) ? Format.A8R8G8B8 : Format.R8G8B8;
                }
                break;

            case OutputFormat.AutoCompressed:
                if (bNormal)
                {
                    form = Format.Dxt5;
                }
                else
                {
                    form = Is32BPP(iInfos) ? Format.Dxt5 : Format.Dxt1;
                }
                break;

            case OutputFormat.ForceArgb8:
                form = Format.A8R8G8B8;
                break;

            case OutputFormat.ForceRgb8:
                form = Format.R8G8B8;
                break;

            case OutputFormat.ForceDXT5:
                form = Format.Dxt5;
                break;

            case OutputFormat.ForceDXT1:
                form = Format.Dxt1;
                break;
            }

            //info for log
            MainForm.Log_WriteLine("LOG : Converting " + convParams.FilePath + " to " + fpNew);

            //keep small images uncompressed. This is independent from any parameters, the value of 64 is hard-coded
            if (((iInfos.Width < MinHeightForCompressed) | (iInfos.Height < MinHeightForCompressed)))
            {
                if (((form == Format.Dxt1) | (form == Format.Dxt5)))
                {
                    MainForm.Log_WriteLine("LOG : Resolution is considered too low for DXT compression. Switching to uncompressed format for better quality.");
                }
                form        = Format.A8R8G8B8;
                mipmapLevel = 1;
            }


            //skip file if the resolution is not correct
            if (((iInfos.Width < cfg.MinRes_Process_Width) | (iInfos.Height < cfg.MinRes_Process_Width)))
            {
                MainForm.Log_WriteLine("LOG : Skipping " + convParams.FilePath + ", resolution is too low.");
                FolderLoader.FileSkipCount += 1;
                return;
            }

            //check if the file is large enough to be resized
            if ((((iInfos.Width < cfg.MinRes_Resize_Width) | (iInfos.Height < cfg.MinRes_Resize_Height)) & (Math.Abs(dRatio - 1) > 0.0001f)))
            {
                MainForm.Log_WriteLine("LOG : " + convParams.FilePath.Split('.').Last() + ", resolution is too low to be resized.");
                dRatio = 1;
            }

            //corrected width and height, we want them to be multiple of 4
            var iCorWidth  = iInfos.Width;
            var iCorHeight = iInfos.Height;

            if (((iCorWidth % 4) != 0))
            {
                iCorWidth += (4 - (iCorWidth % 4));
            }
            if (((iCorHeight % 4) != 0))
            {
                iCorHeight += (4 - (iCorHeight % 4));
            }

            //bmp format for flipping
            Texture texture;

            if (bppFormats24.Contains(iInfos.Format))
            {
                texture = TextureLoader.FromFile(dev, convParams.FilePath, iCorWidth, iCorHeight, 1, Usage.None, Format.R8G8B8, Pool.SystemMemory, Filter.None, Filter.None, 0);
                //t = TextureLoader.FromFile(dev, convParams.FilePath, iCorWidth, iCorHeight, 1, Usage.None, form, Pool.SystemMemory, Filter.None, Filter.None, 0)
            }
            else if (bppFormats32.Contains(iInfos.Format))
            {
                texture = TextureLoader.FromFile(dev, convParams.FilePath, iCorWidth, iCorHeight, 1, Usage.None, Format.A8B8G8R8, Pool.SystemMemory, Filter.None, Filter.None, 0);
            }
            else
            {
                MainForm.Log_WriteLine("ERR : Unknown file format " + iInfos.Format + ", skipping conversion for " + convParams.FilePath);
                FolderLoader.FileSkipCount += 1;
                return;
            }

            //info for log
            MainForm.Log_WriteLine("    Format : " + form + ", normalmap : " + bNormal + ", res: " + (iCorWidth * dRatio) + "x" + (iCorHeight * dRatio));

            //the output is saved in a graphicStream, but a memorystream could work just as well.
            var gs = TextureLoader.SaveToStream(ImageFileFormat.Bmp, texture);

            texture.Dispose();

            //flip
            FlipImage(gs);

            //switch to tga format if swizzling
            if (bNormal)
            {
                var sw2 = Stopwatch.StartNew();
                texture.Dispose();
                texture = TextureLoader.FromStream(dev, gs);
                gs.Close();
                gs.Dispose();
                gs = TextureLoader.SaveToStream(ImageFileFormat.Tga, texture);
                texture.Dispose();
                SwizzleImage(gs, iCorWidth, iCorHeight, Is32BPP(iInfos));
                sw.Stop();
                MainForm.Log_WriteLine(String.Format("SwizzleImage took {0}ms", sw2.Elapsed.TotalMilliseconds));
            }

            //another attempt to flush memory: the program tend to crash if too much large textures are converted
            //though, if some smaller textures are converted in between, memory is flushed correctly...
            dev.Reset(pParameters);

            //saving the texture
            texture = TextureLoader.FromStream(dev, gs, (int)(iCorWidth * dRatio), (int)(iCorHeight * dRatio), mipmapLevel, Usage.None, form, Pool.SystemMemory, Filter.Triangle | Filter.DitherDiffusion, Filter.Triangle | Filter.DitherDiffusion, 0);
            TextureLoader.Save(fpNew, ImageFileFormat.Dds, texture);
            //delete unused stuff
            texture.Dispose();
            gs.Close();
            gs.Dispose();

            //set flag for normals
            if (bNormal)
            {
                MarkAsNormal(fpNew);
            }

            var ddsifiedFile = convParams.FilePath + ".ddsified";

            //remove/Backup original file after successful conversion
            if (File.Exists(fpNew))
            {
                if (cfg.BackupFile)
                {
                    if (File.Exists(ddsifiedFile))
                    {
                        File.Delete(ddsifiedFile);
                    }

                    File.Move(convParams.FilePath, ddsifiedFile);
                }
                else if (cfg.DeleteFilesOnSuccess)
                {
                    File.Delete(convParams.FilePath);
                }
            }
            sw.Stop();

            MainForm.Log_WriteLine(String.Format("Image conversion took {0}ms", sw.Elapsed.TotalMilliseconds));
        }
Ejemplo n.º 22
0
        static void Process()
        {
            var parameters = new ConversionParameters
            {
                InputPath = @"stb_image.h",
                Defines   = new[]
                {
                    "STBI_NO_SIMD",
                    "STBI_NO_PIC",
                    "STBI_NO_PNM",
                    "STBI_NO_STDIO",
                    "STB_IMAGE_IMPLEMENTATION",
                },
                Namespace   = "StbImageSharp",
                Class       = "StbImage",
                SkipStructs = new[]
                {
                    "stbi_io_callbacks",
                    "stbi__context",
                    "img_comp",
                    "stbi__jpeg",
                    "stbi__resample",
                    "stbi__gif_lzw",
                    "stbi__gif"
                },
                SkipGlobalVariables = new[]
                {
                    "stbi__g_failure_reason",
                    "stbi__vertically_flip_on_load"
                },
                SkipFunctions = new[]
                {
                    "stbi__malloc",
                    "stbi_image_free",
                    "stbi_failure_reason",
                    "stbi__err",
                    "stbi_is_hdr_from_memory",
                    "stbi_is_hdr_from_callbacks",
                    "stbi__pnm_isspace",
                    "stbi__pnm_skip_whitespace",
                    "stbi__pic_is4",
                    "stbi__gif_parse_colortable",
                    "stbi__start_mem",
                    "stbi__start_callbacks",
                    "stbi__rewind",
                    "stbi_load_16_from_callbacks",
                    "stbi_load_from_callbacks",
                    "stbi__get8",
                    "stbi__refill_buffer",
                    "stbi__at_eof",
                    "stbi__skip",
                    "stbi__getn",
                    "stbi_load_16_from_memory",
                    "stbi_load_from_memory",
                    "stbi_load_gif_from_memory",
                    "stbi_info_from_memory",
                    "stbi_info_from_callbacks",
                    "stbi_is_16_bit_from_memory",
                    "stbi_is_16_bit_from_callbacks",
                    "stbi__hdr_test_core"
                },
                Classes = new[]
                {
                    "stbi_io_callbacks",
                    "stbi__jpeg",
                    "stbi__resample",
                    "stbi__gif",
                    "stbi__context",
                    "stbi__huffman",
                    "stbi__png"
                },
                GlobalArrays = new[]
                {
                    "stbi__bmask",
                    "stbi__jbias",
                    "stbi__jpeg_dezigzag",
                    "stbi__zlength_base",
                    "stbi__zlength_extra",
                    "stbi__zdist_base",
                    "stbi__zdist_extra",
                    "first_row_filter",
                    "stbi__depth_scale_table",
                    "stbi__zdefault_length",
                    "stbi__zdefault_distance",
                    "length_dezigzag",
                    "png_sig"
                }
            };

            var cp = new ClangParser();

            var result = cp.Process(parameters);

            // Post processing
            Logger.Info("Post processing...");

            var outputFiles = new Dictionary <string, string>();

            Write(result.Constants, outputFiles);
            Write(result.GlobalVariables, outputFiles);
            Write(result.Enums, outputFiles);
            Write(result.Structs, outputFiles);
            Write(result.Methods, outputFiles);

            foreach (var pair in outputFiles)
            {
                var data = PostProcess(pair.Value);

                var sb = new StringBuilder();
                sb.AppendLine(string.Format("// Generated by Sichem at {0}", DateTime.Now));
                sb.AppendLine();

                sb.AppendLine("using System;");
                sb.AppendLine("using System.Runtime.InteropServices;");

                sb.AppendLine();

                sb.Append("namespace StbImageSharp\n{\n\t");
                sb.AppendLine("unsafe partial class StbImage\n\t{");

                data  = sb.ToString() + data;
                data += "}\n}";

                File.WriteAllText(@"..\..\..\..\..\src\StbImage.Generated." + pair.Key + ".cs", data);
            }
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            const string dir = @"..\..\..\ZlibSharp\";

            var sourceEntries = new string[][]
            {
                new [] { "adler32.c", "Adler32", },
                new [] { "compress.c", "Compress" },
                new [] { "crc32.c", "Crc32", },
                new [] { "deflate.c", "Deflate", },
                new [] { "gzclose.c", "GZClose", },
                new [] { "gzlib.c", "GZLib", },
                new [] { "gzread.c", "GZRead", },
                new [] { "gzwrite.c", "GZWrite", },
                new [] { "infback.c", "InfBack", },
                new [] { "inffast.c", "InfFast", },
                new [] { "inflate.c", "InfLate", },
                new [] { "inftrees.c", "InfTrees" },
                new [] { "trees.c", "Trees", },
                new [] { "uncompr.c", "Uncompress", },
                new [] { "zutil.c", "ZUtil" }
            };

            Directory.CreateDirectory(dir);

            var cp = new ClangParser();
            var sb = new StringBuilder();

            for (int i = 0; i < sourceEntries.Length; i++)
            {
                Console.WriteLine();
                Console.WriteLine();

                var parameters = new ConversionParameters
                {
                    InputPath = Path.GetFullPath(@"..\..\..\zlib\" + sourceEntries[i][0]),
                    Class     = sourceEntries[i][1],
                    Namespace = "ZlibSharp",
                    Defines   = new string[] { },
                };

                Logger.Info($"Reading {parameters.InputPath}...");

                ConversionResult result;
                //try
                {
                    result = cp.Process(parameters);
                }
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex);
                //    continue;
                //}

                // Post processing
                Logger.Info($"Writing {parameters.InputPath}...");

                var builder = new StringBuilder();
                Write(GroupType.Constants, result.Constants, builder);
                Write(GroupType.Globals, result.GlobalVariables, builder);
                Write(GroupType.Enums, result.Enums, builder);
                Write(GroupType.Structs, result.Structs, builder);
                Write(GroupType.Methods, result.Methods, builder);

                var data = builder; // PostProcess(pair.Value);

                sb.Clear();
                sb.AppendLine(string.Format("// Generated by Sichem at {0}", DateTime.Now));
                sb.AppendLine();

                sb.AppendLine("using System;");
                sb.AppendLine("using System.Runtime.InteropServices;");
                sb.AppendLine("using static CRuntime;");

                sb.AppendLine();

                sb.Append($"namespace {parameters.Namespace}\n{{\n\t");
                sb.AppendLine($"unsafe class {parameters.Class}\n\t{{");

                data.Insert(0, sb);
                data.Append("}\n}");

                string path = dir + parameters.Class + ".cs";

                if (data.Length > 0)
                {
                    File.WriteAllText(path, data.ToString());
                }
                else
                {
                    Console.WriteLine("Empy " + path);
                }
            }

            Console.ReadKey();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Converts the requested file to a designated format.
        /// </summary>
        /// <param name="input"><c>InputParameters</c> object.</param>
        /// <param name="output"><c>OutputParameters</c> object.</param>
        /// <param name="conversion"><c>ConversionParameters</c> object.</param>
        /// <returns>Returns the conversion response.</returns>
        public async Task <ConvertResponse> ConvertAsync(InputParameters input, OutputParameters output, ConversionParameters conversion)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            if (conversion == null)
            {
                throw new ArgumentNullException("conversion");
            }

            var processResponse = await this.GetProcessResponseAsync(input.InputFormat, conversion.OutputFormat);

            var convertRequest  = this.GetConvertRequest(input, output, conversion);
            var convertResponse = await this.ConvertAsync(convertRequest, String.Format("https:{0}", processResponse.Url));

            return(convertResponse);
        }
Ejemplo n.º 25
0
        static void Process()
        {
            var data = string.Empty;

            using (var output = new StringWriter())
            {
                var parameters = new ConversionParameters
                {
                    InputPath = @"stb_truetype.h",
                    Output    = output,
                    Defines   = new[]
                    {
                        "STB_TRUETYPE_IMPLEMENTATION",
                    },
                    Namespace   = "StbSharpSafe",
                    Class       = "StbTrueType",
                    SkipStructs = new string[]
                    {
                        "stbtt__hheap_chunk",
                        "stbtt__hheap",
                    },
                    SkipGlobalVariables = new string[]
                    {
                    },
                    SkipFunctions = new string[]
                    {
                        "stbtt__find_table",
                        "stbtt_FreeShape",
                        "stbtt__hheap_alloc",
                        "stbtt__hheap_free",
                        "stbtt__hheap_cleanup",
                    },
                    Classes = new string[]
                    {
                        "stbtt__buf",
                        "stbtt_pack_range",
                        "stbtt_pack_context",
                        "stbtt_fontinfo",
                        "stbtt__bitmap",
                        "stbtt__csctx",
                        "stbtt__hheap_chunk",
                        "stbtt__hheap",
                        "stbtt__active_edge",
                        "stbtt_vertex",
                        "stbtt_fontinfo",
                    },
                    GlobalArrays = new string[]
                    {
                    },
                    GenerateSafeCode = true,
                    TreatStructFieldClassPointerAsArray = (structName, fieldName) =>
                    {
                        if (fieldName == "pvertices")
                        {
                            return(true);
                        }

                        return(false);
                    },
                    TreatFunctionArgClassPointerAsArray = (functionName, argName) =>
                    {
                        if (argName == "num_points" || argName == "num_contours" || argName == "contour_lengths")
                        {
                            return(FunctionArgumentType.Ref);
                        }

                        if ((functionName == "stbtt_GetCodepointShape" || functionName == "stbtt_GetGlyphShape") &&
                            (argName == "vertices" || argName == "pvertices"))
                        {
                            return(FunctionArgumentType.Ref);
                        }

                        if (argName == "vertices" || argName == "pvertices" || argName == "verts" || argName == "ranges")
                        {
                            return(FunctionArgumentType.Pointer);
                        }

                        return(FunctionArgumentType.Default);
                    },
                    TreatLocalVariableClassPointerAsArray = (functionName, localVarName) =>
                    {
                        if (localVarName == "vertices" || localVarName == "verts" || localVarName == "comp_verts")
                        {
                            return(true);
                        }

                        if (functionName == "stbtt__GetGlyphShapeTT" &&
                            localVarName == "tmp")
                        {
                            return(true);
                        }

                        if (functionName == "stbtt__run_charstring" && localVarName == "subr_stack")
                        {
                            return(true);
                        }

                        return(false);
                    }
                };

                var cp = new ClangParser();

                cp.Process(parameters);

                data = output.ToString();
            }


            // Post processing
            Logger.Info("Post processing...");

            data = Utility.ReplaceNativeCalls(data);

            data = data.Replace("(void *)(0)", "null");
            data = data.Replace("stbtt_vertex* vertices = 0;", "stbtt_vertex* vertices = null;");
            data = data.Replace("(flags & 16)?dx:-dx", "(flags & 16) != 0?dx:-dx");
            data = data.Replace("(flags & 32)?dy:-dy", "(flags & 32) != 0?dy:-dy");
            data = data.Replace("(vertices) == (0)", "vertices == null");
            data = data.Replace("sizeof((vertices[0]))", "sizeof(stbtt_vertex)");
            data = data.Replace("(int)(!(flags & 1))", "((flags & 1) != 0?0:1)");
            data = data.Replace("vertices = 0;", "vertices = null;");
            data = data.Replace("stbtt_vertex* comp_verts = 0;", "stbtt_vertex* comp_verts = null;");
            data = data.Replace("stbtt_vertex* tmp = 0;", "stbtt_vertex* tmp = null;");
            data = data.Replace(",)", ")");
            data = data.Replace("+ +", "+");
            data = data.Replace("(sizeof(stbtt__hheap_chunk) + size * count)",
                                "((ulong)sizeof(stbtt__hheap_chunk)+ size * (ulong)(count))");
            data = data.Replace("size * hh->num_remaining_in_head_chunk",
                                "size * (ulong)hh->num_remaining_in_head_chunk");
            data = data.Replace("sizeof((*z))", "sizeof(stbtt__active_edge)");
            data = data.Replace("_next_ = 0;", "_next_ = null;");
            data = data.Replace("sizeof((scanline[0]))", "sizeof(float)");
            data = data.Replace("int c = (int)(((a)->y0) < ((b)->y0));", "int c = (int)(a->y0 < b->y0?1:0);");
            data = data.Replace("sizeof((*e))", "sizeof(stbtt__edge)");
            data = data.Replace("sizeof((**contour_lengths))", "sizeof(int)");
            data = data.Replace("sizeof((points[0]))", "sizeof(stbtt__point)");
            data = data.Replace("sizeof((*context))", "sizeof(stbrp_context)");
            data = data.Replace("sizeof((*nodes))", "sizeof(stbrp_node)");
            data = data.Replace("sizeof((*rects))", "sizeof(stbrp_rect)");
            data = data.Replace("(int)(((a[0]) == (b[0])) && ((a[1]) == (b[1])));",
                                "(int)(((a[0] == b[0]) && (a[1] == b[1]))?1:0);");
            data = data.Replace("(int)(((a).Value.y0) < ((b).Value.y0));", "a.Value.y0 < b.Value.y0?1:0;");

            data = data.Replace("CRuntime.malloc((ulong)(m * sizeof(stbtt_vertex)))", "FakePtr<stbtt_vertex>.CreateWithSize(m)");
            data = data.Replace("CRuntime.malloc((ulong)((num_vertices + comp_num_verts) * sizeof(stbtt_vertex)))", "FakePtr<stbtt_vertex>.CreateWithSize(num_vertices + comp_num_verts)");
            data = data.Replace("CRuntime.malloc((ulong)(count_ctx.num_vertices * sizeof(stbtt_vertex)))", "FakePtr<stbtt_vertex>.CreateWithSize(count_ctx.num_vertices)");
            data = data.Replace("CRuntime.malloc((ulong)((result.w * 2 + 1) * sizeof(float)))", "FakePtr<float>.CreateWithSize(result.w * 2 + 1)");
            data = data.Replace("CRuntime.malloc((ulong)(sizeof((e.Value)) * (n + 1)))", "FakePtr<stbtt__edge>.CreateWithSize(n + 1)");
            data = data.Replace("CRuntime.malloc((ulong)(sizeof((contour_lengths)) * n))", "FakePtr<int>.CreateWithSize(n + 1)");
            data = data.Replace("CRuntime.malloc((ulong)(num_points * sizeof(stbtt__point)))", "FakePtr<stbtt__point>.CreateWithSize(num_points)");

            data = data.Replace("(ulong)(num_vertices * sizeof(stbtt_vertex))", "num_vertices");
            data = data.Replace("(ulong)(comp_num_verts * sizeof(stbtt_vertex))", "comp_num_verts");
            data = data.Replace("(ulong)(result.w * sizeof(float))", "result.w");
            data = data.Replace("(ulong)((result.w + 1) * sizeof(float))", "result.w + 1");

            data = data.Replace("stbtt__hheap hh, ", "");
            data = data.Replace("stbtt__active_edge z = stbtt__hheap_alloc(hh, (ulong)(sizeof((z))), userdata);", "stbtt__active_edge z = new stbtt__active_edge();");
            data = data.Replace("stbtt__hheap hh = (stbtt__hheap)({ null, null, 0 });", "");
            data = data.Replace("stbtt__hheap_free(hh, z);", "");
            data = data.Replace("stbtt__hheap_cleanup(hh, userdata);", "");
            data = data.Replace("FakePtr<stbtt__edge> a = ref t;", "FakePtr<stbtt__edge> a = new FakePtr<stbtt__edge>(t);");
            data = data.Replace("hh, ", "");

            File.WriteAllText(SourceFile, data);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets the <c>ConvertRequest</c> object.
        /// </summary>
        /// <param name="input"><c>InputParameters</c> object.</param>
        /// <param name="output"><c>OutputParameters</c> object.</param>
        /// <param name="conversion"><c>ConversionParameters</c> object.</param>
        /// <returns>Returns the <c>ConvertRequest</c> object.</returns>
        public ConvertRequest GetConvertRequest(InputParameters input, OutputParameters output, ConversionParameters conversion)
        {
            var request = Mapper.Map <ConvertRequest>(input)
                          .Map(output)
                          .Map(conversion);

            return(request);
        }
Ejemplo n.º 27
0
        static void Process()
        {
            using (var output = new StringWriter())
            {
                var parameters = new ConversionParameters
                {
                    InputPath = @"stb_vorbis.c",
                    Output    = output,
                    Defines   = new[]
                    {
                        "STB_VORBIS_NO_STDIO",
                        "STB_VORBIS_NO_INLINE_DECODE",
                        "STB_VORBIS_NO_FAST_SCALED_FLOAT"
                    },
                    Namespace   = "StbSharp",
                    Class       = "StbVorbis",
                    SkipStructs = new[]
                    {
                        "Residue",
                        "stb_vorbis",
                    },
                    SkipGlobalVariables = new[]
                    {
                        "channel_position"
                    },
                    SkipFunctions = new[]
                    {
                        "get_bits",
                    },
                    Classes = new[]
                    {
                        "Residue",
                        "stb_vorbis",
                    },
                    GlobalArrays = new[]
                    {
                        "crc_table",
                        "ogg_page_header",
                        "inverse_db_table",
                        "log2_4",
                        "channel_selector"
                    }
                };

                var cp = new ClangParser();

                cp.Process(parameters);
                var data = output.ToString();

                // Post processing
                Logger.Info("Post processing...");

                data = Utility.ReplaceNativeCalls(data);

                data = data.Replace("byte* minp;", "byte* minp = null;");
                data = data.Replace("byte* maxp;", "byte* maxp = null;");
                data = data.Replace("public static void stb__PrepareOptTable(byte* Table, byte* expand, int size)",
                                    "public static void stb__PrepareOptTable(byte[] Table, byte[] expand, int size)");

                data = data.Replace("(enum STBVorbisError)", string.Empty);
                data = data.Replace("crc_table", "_crc_table");
                data = data.Replace("memset(available, (int)(0), (ulong)(sizeof((available))))", "memset(available, 0, 32)");
                data = data.Replace("return (int)((x) < (y)?-1:(x) > (y));", "return (int)((x) < (y)?-1:((x) > (y)?1:0));");
                data = data.Replace("sizeof(float)* * n", "sizeof(float) * n");
                data = data.Replace("uint16", "ushort");
                data = data.Replace("sizeof(ushort)* * n", "sizeof(ushort) * n");
                data = data.Replace("return (int)((a->x) < (b->x)?-1:(a->x) > (b->x));",
                                    "return (int)((a->x) < (b->x)?-1:((a->x) > (b->x)?1:0));");
                data = data.Replace("!c->codewords) != 0", "c->codewords == null)");
                data = data.Replace("(void *)(0)", "null");
                data = data.Replace("sizeof((**part_classdata))", "sizeof(byte *)");
                data = data.Replace("sizeof((**part_classdata))", "sizeof(byte *)");
                data = data.Replace("alloc.alloc_buffer?", "alloc.alloc_buffer != null?");
                data = data.Replace("float*[]", "float**");
                data = data.Replace("sizeof((*buf2))", "sizeof(float)");
                data = data.Replace("f.mode_config +", "(Mode *)f.mode_config +");
                data =
                    data.Replace("memcpy(really_zero_channel, zero_channel, (ulong)(sizeof((really_zero_channel[0])) * f.channels));",
                                 "memcpy(really_zero_channel, zero_channel, (ulong)(sizeof(int) * f.channels));");
                data = data.Replace("memset(f.channel_buffers[i], (int)(0), (ulong)(sizeof((*f.channel_buffers[i])) * n2));",
                                    "memset(f.channel_buffers[i], (int)(0), (ulong)(sizeof(float) * n2));");
                data = data.Replace("if ((f.page_flag & 4))",
                                    "if ((f.page_flag & 4) != 0)");
                data = data.Replace("for ((s) == (-1); {",
                                    "for (;(s) == (-1);) {");
                data = data.Replace("float** residue_buffers = stackalloc float[16];",
                                    "float** residue_buffers = stackalloc float*[16];");
                data = data.Replace("if ((p[5] & 1))",
                                    "if ((p[5] & 1) != 0)");
                data = data.Replace("sizeof((*f.codebooks))",
                                    "sizeof(Codebook)");
                data = data.Replace("sizeof((c->codewords[0]))",
                                    "sizeof(uint)");
                data = data.Replace("sizeof((*c->codewords))",
                                    "sizeof(uint)");
                data = data.Replace("sizeof((*values))",
                                    "sizeof(uint)");
                data = data.Replace("sizeof((*c->sorted_codewords))",
                                    "sizeof(uint)");
                data = data.Replace("sizeof((*c->sorted_values))",
                                    "sizeof(int)");
                data = data.Replace("sizeof((mults[0]))",
                                    "sizeof(ushort)");
                data = data.Replace("sizeof((c->multiplicands[0]))",
                                    "sizeof(float)");
                data = data.Replace("sizeof((*f.floor_config))",
                                    "sizeof(Floor)");
                data = data.Replace("(Residue)(setup_malloc(f, (int)(f.residue_count * sizeof((f.residue_config[0])))))",
                                    "new Residue[f.residue_count]");
                data = data.Replace("sizeof((*r.classdata))",
                                    "sizeof(byte *)");
                data = data.Replace("sizeof((*f.mapping))",
                                    "sizeof(Mapping)");
                data = data.Replace("sizeof((r.classdata[j][0]))",
                                    "sizeof(byte)");
                data = data.Replace("sizeof((r.residue_books[0]))",
                                    "sizeof(short)");
                data = data.Replace("sizeof((*m->chan))",
                                    "sizeof(MappingChannel)");
                data = data.Replace("(short [8]*)(setup_malloc(f, (int)(sizeof(short) * r.classifications)))",
                                    "new short*[r.classifications]");
                data = data.Replace("sizeof(float)* *",
                                    "sizeof(float) *");
                data = data.Replace("sizeof(short)* *",
                                    "sizeof(short) *");
                data = data.Replace("sizeof(float)>> >>",
                                    "sizeof(float) >>");
                data = data.Replace("sizeof(float)+ +",
                                    "sizeof(float) +");
                data = data.Replace("sizeof(void*)+ +",
                                    "sizeof(void*) +");
                data = data.Replace("classify_mem = (uint)((f.channels * (sizeof(void*) + max_part_read * sizeof(char*)))));",
                                    "classify_mem = (uint)((f.channels * (sizeof(void*) + max_part_read * sizeof(char*))));");
                data = data.Replace("(stb_vorbis)(setup_malloc(f, (int)(sizeof((p)))))",
                                    "new stb_vorbis()");
                data = data.Replace("memset(buffer, (int)(0), (ulong)(sizeof((buffer))))",
                                    "memset(buffer, (int)(0), (ulong)(sizeof(float) * 32))");
                data = data.Replace("channel_position[num_c][j]",
                                    "channel_position[num_c,j]");
                data = data.Replace("channel_selector[buf_c][i]",
                                    "channel_selector[buf_c,i]");
                data = data.Replace("int[] channel_selector",
                                    "int[,] channel_selector");
                data = data.Replace("sizeof((*data))",
                                    "sizeof(short)");
                data = data.Replace("float** output;",
                                    "float*[] output = null;");
                data = data.Replace("float** outputs;",
                                    "float*[] outputs = null;");
                data = data.Replace("&output",
                                    "ref output");
                data = data.Replace("float*** output",
                                    "ref float*[] output");
                data = data.Replace("float** data",
                                    "float*[] data");
                data = data.Replace("if ((output) != null) *output = f.outputs;",
                                    "if ((output) != null) output = f.outputs;");
                data = data.Replace("stb_vorbis_get_frame_float(f, &n, (null));",
                                    "float*[] output = null; stb_vorbis_get_frame_float(f, &n, ref output);");
                data = data.Replace("*output = f.outputs;",
                                    "output = f.outputs;");
                data = data.Replace("*output = f.outputs;",
                                    "output = f.outputs;");
                data = data.Replace("f.current_loc_valid = (int)(f.current_loc != ~0U);",
                                    "f.current_loc_valid = f.current_loc != ~0U?1:0;");
                data = data.Replace("setup_free(p, c->sorted_values?c->sorted_values - 1:(null));",
                                    "setup_free(p, c->sorted_values != null?c->sorted_values - 1:(null));");
                data = data.Replace("f.scan[n].sample_loc = (uint)(~0);",
                                    "f.scan[n].sample_loc = uint.MaxValue;");
                data = data.Replace("; ) {}",
                                    "");
                data = data.Replace("if (((f.current_loc_valid) != 0) && (f.page_flag & 4))",
                                    "if (((f.current_loc_valid) != 0) && (f.page_flag & 4) != 0)");

                File.WriteAllText(@"..\..\..\..\..\StbSharp\StbVorbis.Generated.cs", data);
            }
        }
Ejemplo n.º 28
0
        static void Process()
        {
            var parameters = new ConversionParameters
            {
                AdditionalIncludeFolders = new string[]
                {
                    @"C:\Projects\StbSharp\FreeTypeSharp\FreeTypeTest\FreeTypeTest\freetype\include"
                },
                InputPath = @"C:\Projects\StbSharp\FreeTypeSharp\FreeTypeTest\FreeTypeTest\freetype\src\base\ftbase.c",
                Defines   = new string[]
                {
                    "_LIB",
                    "_CRT_SECURE_NO_WARNINGS",
                    "FT2_BUILD_LIBRARY"
                },
                SkipEnums = new string[]
                {
                    "FT_Encoding_",
                    "FT_Glyph_Format_",
                },
                SkipStructs = new string[]
                {
                    "FT_StreamDesc_",
                    "FT_StreamRec_",
                    "TT_Post_NamesRec_names",
                    "TT_Post_NamesRec_",
                    "FT_HashnodeRec_",
                    "FT_HashRec_",
                    "FT_Service_PsCMapsRec_",
                    "T1_Decoder_FuncsRec_",
                    "PS_BlendRec_",
                    "CFF_InternalRec_",
                    "CFF_Decoder_FuncsRec_",
                },
                SkipGlobalVariables = new string[]
                {
                },
                SkipFunctions = new string[]
                {
                    "FT_Raccess_Get_DataOffsets"
                },
                Classes = new string[]
                {
                    "FT_FaceRec_",
                    "FT_Outline_Funcs_",
                    "FT_Renderer_Class_",
                    "FT_RendererRec_",
                    "FT_ModuleRec_",
                    "FT_Module_Class_",
                    "FT_MemoryRec_",
                    "FT_LibraryRec_",
                    "FT_StreamRec_",
                    "ft_raccess_guess_rec_",
                    "FT_CharMapRec_",
                    "FT_Raster_Params_",
                    "FT_GlyphSlotRec_",
                    "FT_Slot_InternalRec_",
                    "FT_SizeRec_",
                    "FT_CharMapRec_",
                    "FT_DriverRec_",
                    "FT_Driver_ClassRec_",
                    "FT_GlyphRec_",
                    "FT_Glyph_Class_",
                    "FT_Raster_Funcs_",
                    "FT_Incremental_FuncsRec_",
                    "FT_CMapRec_",
                    "FT_CMap_ClassRec_",
                    "FT_Face_InternalRec_",
                    "FT_Incremental_InterfaceRec_",
                    "FT_GlyphLoaderRec_",
                    "TT_FaceRec_",
                    "TT_LoaderRec_",
                    "SFNT_Interface_",
                    "FT_HashRec_",
                    "PSH_Globals_FuncsRec_",
                    "PSH_GlobalsRec_",
                    "T1_Hints_FuncsRec_",
                    "T2_Hints_FuncsRec_",
                    "FT_Service_PsCMapsRec_",
                    "PS_UnicodesRec_",
                    "PS_BlendRec_",
                    "CFF_FontRec_",
                    "CFF_SubFontRec_",
                    "PSHinter_Interface_",
                    "PS_Table_FuncsRec_",
                    "PS_TableRec_",
                    "PS_Parser_FuncsRec_",
                    "PS_ParserRec_",
                    "T1_FieldRec_",
                    "PS_Builder_",
                    "CFF_GlyphSlotRec_",
                    "FT_Generic_",
                    "PS_Decoder_",
                    "T1_BuilderRec_",
                    "T1_Decoder_FuncsRec_",
                    "T1_DecoderRec_",
                    "CFF_Builder_",
                    "CFF_SizeRec_",
                    "CFF_Decoder_",
                    "AFM_ParserRec_",
                    "T1_Builder_FuncsRec_",
                    "T1_CMap_ClassesRec_",
                    "AFM_Parser_FuncsRec_",
                    "CFF_Decoder_FuncsRec_",
                    "FT_Service_PropertiesRec_",
                    "FT_Service_SFNT_TableRec_",
                    "FT_Service_PsFontNameRec_",
                    "FT_Service_GlyphDictRec_",
                    "FT_GlyphLoadRec_",
                },
                GlobalArrays = new string[]
                {
                }
            };

            var cp = new ClangParser();

            var result = cp.Process(parameters);

            // Write output
            var sb = new StringBuilder();

            sb.AppendLine(string.Format("// Generated by Sichem at {0}", DateTime.Now));
            sb.AppendLine();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.Runtime.InteropServices;");

            sb.AppendLine();

            sb.Append("namespace FreeTypeSharp\n{\n\t");
            sb.AppendLine("unsafe partial class FreeType\n\t{");

            Write(result.Constants, sb);
            Write(result.GlobalVariables, sb);
            Write(result.Enums, sb);
            Write(result.Structs, sb);
            Write(result.Methods, sb);

            sb.Append("}\n}");
            var data = sb.ToString();

            // Post processing
            Logger.Info("Post processing...");
            data = PostProcess(data);

            File.WriteAllText(@"..\..\..\..\..\src\FtBase.Generated.cs", data);
        }
Ejemplo n.º 29
0
        static void Process()
        {
            using (var output = new StringWriter())
            {
                var parameters = new ConversionParameters
                {
                    InputPath = @"stb_image_write.h",
                    Output    = output,
                    Defines   = new[]
                    {
                        "STBI_WRITE_NO_STDIO",
                        "STB_IMAGE_WRITE_IMPLEMENTATION"
                    },
                    Namespace   = "StbSharp",
                    Class       = "StbImageWrite",
                    SkipStructs = new[]
                    {
                        "stbi__write_context"
                    },
                    SkipGlobalVariables = new[]
                    {
                        "stbi_write_tga_with_rle"
                    },
                    SkipFunctions = new[]
                    {
                        "stbi__start_write_callbacks",
                        "stbiw__writefv",
                        "stbiw__writef",
                        "stbiw__outfile",
                        "stbi_write_bmp_to_func",
                        "stbi_write_tga_to_func",
                        "stbi_write_hdr_to_func",
                        "stbi_write_png_to_func",
                        "stbi_write_hdr_core",
                    },
                    Classes = new []
                    {
                        "stbi__write_context"
                    },
                    GlobalArrays = new[]
                    {
                        "lengthc",
                        "lengtheb",
                        "distc",
                        "disteb",
                        "crc_table",
                        "stbiw__jpg_ZigZag",
                        "std_dc_luminance_nrcodes",
                        "std_dc_luminance_values",
                        "std_ac_luminance_nrcodes",
                        "std_ac_luminance_values",
                        "std_dc_chrominance_nrcodes",
                        "std_dc_chrominance_values",
                        "std_ac_chrominance_nrcodes",
                        "std_ac_chrominance_values",
                        "std_dc_chrominance_nrcodes",
                        "std_dc_chrominance_values",
                        "YDC_HT",
                        "UVDC_HT",
                        "YAC_HT",
                        "UVAC_HT",
                        "YQT",
                        "UVQT",
                        "aasf",
                        "head0",
                        "head2"
                    }
                };

                var cp = new ClangParser();

                cp.Process(parameters);
                var data = output.ToString();

                // Post processing
                Logger.Info("Post processing...");

                data = Utility.ReplaceNativeCalls(data);

                data = data.Replace("int has_alpha = (int)(((comp) == (2)) || ((comp) == (4)));",
                                    "int has_alpha = (((comp) == (2)) || ((comp) == (4)))?1:0;");
                data = data.Replace("*arr?",
                                    "*arr != null?");
                data = data.Replace("sizeof(int)* * 2",
                                    "sizeof(int) * 2");
                data = data.Replace("(int)(sizeof((*(data))))",
                                    "sizeof(byte)");
                data = data.Replace("(int)(sizeof((*(_out_))))",
                                    "sizeof(byte)");
                data = data.Replace("(int)(sizeof((*(hash_table[h]))))",
                                    "sizeof(byte*)");
                data = data.Replace("sizeof((hash_table[h][0]))",
                                    "sizeof(byte*)");
                data = data.Replace("(byte***)(malloc((ulong)(16384 * sizeof(char**)))))",
                                    "(byte***)(malloc((ulong)(16384 * sizeof(byte**))))");
                data = data.Replace("(hlist)?",
                                    "(hlist != null)?");
                data = data.Replace("(hash_table[i])?",
                                    "(hash_table[i] != null)?");

                File.WriteAllText(@"..\..\..\..\..\StbSharp\StbImageWrite.Generated.cs", data);
            }
        }
Ejemplo n.º 30
0
    public static void GeodeticToGrid(double latitude, double longitude, ConversionParameters p, out double outNorthing, out double outEasting)
    {
        outNorthing = 0.0;
        outEasting  = 0.0;

        double axis             = p.axis;
        double flattening       = p.flattening;
        double central_meridian = p.central_meridian;
        double lat_of_origin    = p.lat_of_origin;
        double scale            = p.scale;
        double false_northing   = p.false_northing;
        double false_easting    = p.false_easting;

        //double x, y;

        if (central_meridian == 0.0)
        {
            outNorthing = 0.0;
            outEasting  = 0.0;
            return;
        }

        // Prepare ellipsoid-based stuff.
        double e2     = flattening * (2.0 - flattening);
        double n      = flattening / (2.0 - flattening);
        double a_roof = axis / (1.0 + n) * (1.0 + n * n / 4.0 + n * n * n * n / 64.0);
        double A      = e2;
        double B      = (5.0 * e2 * e2 - e2 * e2 * e2) / 6.0;
        double C      = (104.0 * e2 * e2 * e2 - 45.0 * e2 * e2 * e2 * e2) / 120.0;
        double D      = (1237.0 * e2 * e2 * e2 * e2) / 1260.0;
        double beta1  = n / 2.0 - 2.0 * n * n / 3.0 + 5.0 * n * n * n / 16.0 + 41.0 * n * n * n * n / 180.0;
        double beta2  = 13.0 * n * n / 48.0 - 3.0 * n * n * n / 5.0 + 557.0 * n * n * n * n / 1440.0;
        double beta3  = 61.0 * n * n * n / 240.0 - 103.0 * n * n * n * n / 140.0;
        double beta4  = 49561.0 * n * n * n * n / 161280.0;

        // Convert.
        double deg_to_rad  = Math.PI / 180.0;
        double phi         = latitude * deg_to_rad;
        double lambda      = longitude * deg_to_rad;
        double lambda_zero = central_meridian * deg_to_rad;

        double phi_star = phi - Math.Sin(phi) * Math.Cos(phi) * (A +
                                                                 B * Math.Pow(Math.Sin(phi), 2) +
                                                                 C * Math.Pow(Math.Sin(phi), 4) +
                                                                 D * Math.Pow(Math.Sin(phi), 6));
        double delta_lambda = lambda - lambda_zero;
        double xi_prim      = Math.Atan(Math.Tan(phi_star) / Math.Cos(delta_lambda));
        double eta_prim     = Math.Atan(Math.Cos(phi_star) * Math.Sin(delta_lambda));
        double x            = scale * a_roof * (xi_prim +
                                                beta1 * Math.Sin(2.0 * xi_prim) * Math.Cos(2.0 * eta_prim) +
                                                beta2 * Math.Sin(4.0 * xi_prim) * Math.Cos(4.0 * eta_prim) +
                                                beta3 * Math.Sin(6.0 * xi_prim) * Math.Cos(6.0 * eta_prim) +
                                                beta4 * Math.Sin(8.0 * xi_prim) * Math.Cos(8.0 * eta_prim)) +
                              false_northing;
        double y = scale * a_roof * (eta_prim +
                                     beta1 * Math.Cos(2.0 * xi_prim) * Math.Sinh(2.0 * eta_prim) +
                                     beta2 * Math.Cos(4.0 * xi_prim) * Math.Sinh(4.0 * eta_prim) +
                                     beta3 * Math.Cos(6.0 * xi_prim) * Math.Sinh(6.0 * eta_prim) +
                                     beta4 * Math.Cos(8.0 * xi_prim) * Math.Sinh(8.0 * eta_prim)) +
                   false_easting;

        outNorthing = x * 1000.0 / 1000.0;
        outEasting  = y * 1000.0 / 1000.0;
    }