Пример #1
0
        private void Start()
        {
            engine = Python.CreateEngine();
            engine.Runtime.LoadAssembly(typeof(GameObject).Assembly);

            engine.Runtime.LoadAssembly(typeof(Image).Assembly);
            //engine.ImportModule("");
            scope = engine.CreateScope();
            scope.SetVariable("pyConsole", pyConsole);
            engine.Execute(pythonScript, scope);
            //var scope = engine.ExecuteFile(path);
            int counter = scope.GetVariable <int>("counter");

            Debug.Log(counter);

            float timeBackup = scope.GetVariable <float>("timeBackup");

            Debug.Log(timeBackup);

            Debug.LogError("Error test");

            Debug.LogWarning("warning\nTest");

            //TestInstance();
            //TestInstance();


            //GameObject.Find("Player").transform.GetChild(0).GetComponent("MeshRenderer").sharedMaterial.color = Color.black;
            //GameObject.Find("Player").transform.localRotation = Quaternion.Euler(0, 0, 90);
            //Camera.main.transform.position = new Vector3(2,2,-5);

            //string variables = string.Join(",", scope.GetVariableNames().ToArray());
            //Debug.Log("variables: " + variables);
        }
Пример #2
0
        /// <summary>
        /// 用户自定义Python脚本
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RepairFun_PythonScript(string handler, string source)
        {
            if (source == "")
            {
                return("");
            }

            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                $"import textRepairPlugins.{handler} as customHandler\n" +
                "ResultStr = customHandler.process(SourceStr)\n"
                );
            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("SourceStr", source);

            try
            {
                pythonScript.Execute(scope);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return((string)scope.GetVariable("ResultStr"));
        }
Пример #3
0
 public ImgInterpreter()
 {
     path   = "";
     script = "scripts\\_default.py";
     py     = Python.CreateEngine(); // allows to run ironpython programs
     s      = py.CreateScope();      // you need this to get the variables
 }
Пример #4
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                "helloWorldString = 'Hello World!'\n" +
                "print helloWorldString\n" +
                "print externalString"
                );

            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("externalString", "How do you do?");

            pythonScript.Execute(scope);

            System.Console.Out.WriteLine();
            System.Console.Out.WriteLine("List of variables in the scope:");
            foreach (string name in scope.GetVariableNames())
            {
                System.Console.Out.Write(name + " ");
            }
            System.Console.Out.WriteLine();

            System.Console.Out.WriteLine();
            System.Console.Out.WriteLine("Variable values:");
            System.Console.Out.WriteLine("helloWorldString: " + scope.GetVariable("helloWorldString"));
            System.Console.Out.WriteLine("externalString: " + scope.GetVariable("externalString"));
        }
Пример #5
0
        public Script(bool redirectOutput = false)
        {
            Dictionary <string, object> options = new Dictionary <string, object>();

            options["Debug"] = true;

            if (engine != null)
            {
                engine.Runtime.Shutdown();
            }

            engine = Python.CreateEngine(options);
            scope  = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();

            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);
            scope.SetVariable("Joystick", MainV2.joystick);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            if (redirectOutput)
            {
                //Redirect output through this writer
                //this writer will not actually write to the memorystreams
                OutputWriter = new Utilities.StringRedirectWriter();
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), OutputWriter);
                engine.Runtime.IO.SetOutput(new MemoryStream(), OutputWriter);
            }
            else
            {
                OutputWriter = null;
            }

            /*
             * object thisBoxed = MainV2.comPort.MAV.cs;
             * Type test = thisBoxed.GetType();
             *
             * foreach (var field in test.GetProperties())
             * {
             *  // field.Name has the field's name.
             *  object fieldValue;
             *  try
             *  {
             *      fieldValue = field.GetValue(thisBoxed, null); // Get value
             *  }
             *  catch { continue; }
             *
             *  // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
             *  TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());
             *
             *  items.Add(field.Name);
             * }
             */
        }
Пример #6
0
        public Script()
        {
            engine = Python.CreateEngine();
            scope = engine.CreateScope();

            scope.SetVariable("cs", MainV2.cs);
            scope.SetVariable("Script", this);

            Console.WriteLine(DateTime.Now.Millisecond);
            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            Console.WriteLine(DateTime.Now.Millisecond);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);
            Console.WriteLine(DateTime.Now.Millisecond);

            object thisBoxed = MainV2.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Пример #7
0
        public Script(bool redirectOutput = false)
        {
            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;

            if (engine != null)
                engine.Runtime.Shutdown();

            engine = Python.CreateEngine(options);

            var paths = engine.GetSearchPaths();
            paths.Add(Settings.GetRunningDirectory() + "Lib.zip");
            engine.SetSearchPaths(paths);

            scope = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();
            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);
            scope.SetVariable("Joystick", MainV2.joystick);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            if (redirectOutput)
            {
                //Redirect output through this writer
                //this writer will not actually write to the memorystreams
                OutputWriter = new Utilities.StringRedirectWriter();
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), OutputWriter);
                engine.Runtime.IO.SetOutput(new MemoryStream(), OutputWriter);
            }
            else
                OutputWriter = null;

            /*
            object thisBoxed = MainV2.comPort.MAV.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
             */
        }
Пример #8
0
        private void callPythonCode()
        {
            var options = new Dictionary <string, object>();

            options["Frames"]     = true;
            options["FullFrames"] = true;

            //create ironpython engine and scope
            Microsoft.Scripting.Hosting.ScriptEngine py    = Python.CreateEngine(options);
            Microsoft.Scripting.Hosting.ScriptScope  scope = py.CreateScope();

            //add python folder to pythonpath
            string pythonCodePath      = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/";
            string pyGDPPath           = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/pyGDP-master/";
            string OWSPath             = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/owslib/";
            string owslibPath          = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/OWS/OWSLib-0.8.6/owslib/";
            string libPath             = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/Lib/";
            ICollection <string> paths = py.GetSearchPaths();

            paths.Add(pythonCodePath);
            paths.Add(pyGDPPath);
            paths.Add(OWSPath);
            paths.Add(owslibPath);
            paths.Add(libPath);
            py.SetSearchPaths(paths);

            //store variables in scope
            scope.SetVariable("futOne", futOne);
            scope.SetVariable("futTwo", futTwo);
            scope.SetVariable("futThree", futThree);
            scope.SetVariable("futFour", futFour);
            scope.SetVariable("futFive", futFive);
            scope.SetVariable("futSix", futSix);
            scope.SetVariable("histOne", histOne);
            scope.SetVariable("histTwo", histTwo);
            scope.SetVariable("filePath", filePath);

            //run code
            py.ExecuteFile(Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/module1.py", scope);

            string outputPathF2 = scope.GetVariable("outputPathF2").ToString();
            string outputPathH1 = scope.GetVariable("outputPathH1").ToString();

            //retrieve climate data
            filePath = filePath.Remove(filePath.Length - 9);

            string    urlF2     = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathF2;
            WebClient webClient = new WebClient();

            webClient.DownloadFile(urlF2, @filePath + "FutureClimateData.csv");

            string    urlH1      = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathH1;
            WebClient webClient2 = new WebClient();

            webClient2.DownloadFile(urlH1, @filePath + "HistoricalClimateData.csv");

            return;
        }
        private void Start()
        {
            engine = Python.CreateEngine();
            engine.Runtime.LoadAssembly(typeof(GameObject).Assembly);

            scope = engine.CreateScope();
            scope.SetVariable("pyConsole", pyConsole);
            scope.SetVariable("unityEvents", unityMethodsEvents);
            engine.Execute(pythonScript, scope);
        }
Пример #10
0
        public Script(bool redirectOutput = false)
        {
            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;

            if (engine != null)
                engine.Runtime.Shutdown();

            engine = Python.CreateEngine(options);
            var paths = engine.GetSearchPaths();
            paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); //Allows for additional libraries from IronPython. Requires download from https://ironpython.codeplex.com/releases/view/90087
            engine.SetSearchPaths(paths);
            scope = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();
            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);

            //engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope); //Unneeded testing
            //engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            if (redirectOutput)
            {
                //Redirect output through this writer
                //this writer will not actually write to the memorystreams
                OutputWriter = new Utilities.StringRedirectWriter();
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), OutputWriter);
                engine.Runtime.IO.SetOutput(new MemoryStream(), OutputWriter);
            }
            else
                OutputWriter = null;

            object thisBoxed = MainV2.comPort.MAV.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope  s  = py.CreateScope();

            py.Execute(
                @"import numpy as np 
    incomes = np.random.normal(27000, 15000, 10000) 
    x = np.mean(incomes)"
                , s);
        }
Пример #12
0
        static IPyInterface()
        {
            //Create the python execution engine
            engine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope scriptScope = engine.CreateScope();

            //Link to the scripts that create the Beach_Interface object
            string strInitialize = "import Interface";
            string strGet_interface = "Interface.Interface";

            //Return the Beach_Interface object
            engine.Execute(strInitialize, scriptScope);
            ipyInterface = engine.Execute(strGet_interface, scriptScope);
        }
Пример #13
0
        static IPyInterface()
        {
            //Create the python execution engine
            engine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope scriptScope = engine.CreateScope();

            //Link to the scripts that create the Beach_Interface object
            string strInitialize    = "import Interface";
            string strGet_interface = "Interface.Interface";

            //Return the Beach_Interface object
            engine.Execute(strInitialize, scriptScope);
            ipyInterface = engine.Execute(strGet_interface, scriptScope);
        }
Пример #14
0
        public override void Execute(string src, Uri uri, HttpListenerContext p, WebConfig wc, StreamWriter sw)
        {
            Microsoft.Scripting.Hosting.ScriptEngine py = IronRuby.Ruby.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope  s  = py.CreateScope();

            var sapi = new StandardScriptApi(uri, p, sw);

            foreach (var item in sapi.Variables)
            {
                s.SetVariable(item.Key, item.Value);
            }

            py.Execute(src, s);
        }
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope  s  = py.CreateScope();

            // add paths to where your libs are installed
            var libs = new[] { @"c:\path\to\lib1", @"c:\path\to\lib2" };

            py.SetSearchPaths(libs);
            py.Execute(
                @"import numpy as np 
    incomes = np.random.normal(27000, 15000, 10000) 
    x = np.mean(incomes)"
                , s);
        }
Пример #16
0
        public override void Initialize()
        {
            Func <TreeNode <string>, JObject> nodeToJObject = (node) =>
            {
                JObject obj = new JObject();
                TreeNode <string> .TreeNodeToJson(node, obj);

                return(obj);
            };


            _scriptEngine = Python.CreateEngine();
            _scope        = _scriptEngine.CreateScope();



            //  Execute main script
            {
                string entryFile = Data.GetValue("entry");
                var    src       = _scriptEngine.CreateScriptSourceFromFile(entryFile);

                Logger.Info("Main script({0}) loading...", Path.GetFileName(entryFile));
                src.Execute(_scope);


                //  Setting global variables
                SetVariable("ScriptName", Name);                            //  globalObjects의 이름
                SetVariable("RoseApi", _scriptApi);                         //  ScriptAPI instance
                SetVariable("ServerConfig", nodeToJObject(Starter.Config)); //  Config 전체
                SetVariable("ScriptConfig", nodeToJObject(Data));           //  globalObjects에 정의된 data 항목


                //  Predefined function
                FnRoseEntry              = GetVariable("roseEntry");
                FnBeforeRequestHandling  = GetVariable("beforeRequestHandling");    //  Request 핸들러
                FnBeforeResponseHandling = GetVariable("beforeResponseHandling");   //  Response 핸들러


                //  Call entry function
                if (FnRoseEntry != null)
                {
                    FnRoseEntry();
                }
            }
        }
Пример #17
0
        public Script()
        {
            Dictionary <string, object> options = new Dictionary <string, object>();

            options["Debug"] = true;

            if (engine != null)
            {
                engine.Runtime.Shutdown();
            }

            engine = Python.CreateEngine(options);
            scope  = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();

            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);


            object thisBoxed = MainV2.comPort.MAV.cs;
            Type   test      = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
    public void runScript()
    {
        String path   = @"c:\pythonSpeedTest.py";
        var    source = System.IO.File.ReadAllText(path);

        Microsoft.Scripting.Hosting.ScriptEngine py    = Python.CreateEngine();
        Microsoft.Scripting.Hosting.ScriptScope  scope = py.CreateScope();
        var paths = py.GetSearchPaths();

        paths.Add(@"c:\Program Files (x86)\IronPython 2.7\Lib");
        py.SetSearchPaths(paths);
        try {
            py.Execute(source);
        }catch (Exception ex) {
            Console.WriteLine("Error occured in python script\n" + ex);
            Console.ReadKey();
            return;
        }
    }
Пример #19
0
        /// <summary>
        /// Imports the chosen image
        /// </summary>
        /// <param name="imgpath">path to image</param>
        /// <param name="scriptpath">script path</param>
        /// <returns></returns>
        public Bitmap Load(string imgpath, string scriptpath)
        {
            py = Python.CreateEngine();
            s  = py.CreateScope();

            path   = imgpath;
            img    = new Bitmap(4, 4);
            script = scriptpath;
            if (scriptpath.Length > 100)
            {
                py.Execute(script, s);
            }
            else
            {
                py.ExecuteFile(script, s);
            }
            LoadImg();
            return(img);
        }
Пример #20
0
        private GameObject CreateObject(string expression, float x, float y)
        {
            expression = "from MarioBros import *\r\nfrom Microsoft.Xna.Framework import *\r\n" + expression;

            var source = scriptEngine.CreateScriptSourceFromString(expression);
            var scope  = scriptEngine.CreateScope();

            scope.SetVariable("x", x);
            scope.SetVariable("y", y);

            source.Execute(scope);

            if (!scope.ContainsVariable("tile"))
            {
                throw new InvalidOperationException("Tile script does not set the 'tile' variable appropriately.");
            }

            return(scope.GetVariable("tile"));
        }
Пример #21
0
        public bool IronPython(Parameter parameter)
        {
            Microsoft.Scripting.Hosting.ScriptEngine engine = global::IronPython.Hosting.Python.CreateEngine();

            Microsoft.Scripting.Hosting.ScriptScope scope = engine.CreateScope();

            scope.SetVariable("n", parameter.Numbers);

            List <int> results = new List <int>(parameter.Numbers.Length);

            foreach (int number in parameter.Numbers)
            {
                int result = engine.Execute <int>(parameter.Statements[number], scope);

                results.Add(result);
            }

            return(Assert(results, parameter.Sum));
        }
Пример #22
0
        public Script()
        {
            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;

            if (engine != null)
                engine.Runtime.Shutdown();

            engine = Python.CreateEngine(options);
            scope = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();
            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            object thisBoxed = MainV2.comPort.MAV.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Пример #23
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            textBox.Highlighter = Highlighters.Ruby;
            textBox.Images = templateBMPs;
            engine = IronRuby.Ruby.CreateEngine();
            ui = new UI(this);
            scope = engine.CreateScope();
            scope.SetVariable("ui", ui);

            // Ctrl + R で今表示されているスクリプトを実行
            // Ctrl + Esc で実行終了
            // Ctrl + RPrintScreen でスクリーンショットを撮る
            AddHotKeyAction(MOD_WIN, Keys.S, "スローモーションで実行", () => { ui.slowPlayFlag = true; Run(textBox.Text); });
            AddHotKeyAction(MOD_WIN, Keys.Q, "実行停止", () => 停止SToolStripMenuItem_Click(null, null));
            AddHotKeyAction(MOD_CONTROL, Keys.PrintScreen, "スクリーンショットを撮る", () => new BlackForm().takeScreenshot(this));

            LoadConfigData();
        }
Пример #24
0
 private void InitializeIronPython()
 {
     pyEngine = IronPython.Hosting.Python.CreateEngine();
     pyScope  = pyEngine.CreateScope();
     pyScope.SetVariable("qst", QST);
 }
Пример #25
0
 private void InitializeIronPython()
 {
     pyEngine = IronPython.Hosting.Python.CreateEngine();
     pyScope = pyEngine.CreateScope();
     pyScope.SetVariable("qst", QST);
 }
Пример #26
0
        /// <summary>
        /// Export image to chosen format
        /// </summary>
        /// <param name="path">output path</param>
        /// <param name="scriptpath">script path</param>
        public void ExportImg(string path, string scriptpath)
        {
            py = Python.CreateEngine();
            s  = py.CreateScope();
            //py.ExecuteFile(scriptpath, s);
            if (scriptpath.Length > 100)
            {
                py.Execute(scriptpath, s);
            }
            else
            {
                py.ExecuteFile(scriptpath, s);
            }

            BinaryWriter binr;

            fs   = new FileStream(path, FileMode.Create);
            binr = new BinaryWriter(fs);

            pixelFormat = s.GetVariable("IMG_PIXEL_FORMAT");
            pixelFormat = pixelFormat.ToUpper();
            if (pixelFormat.Length < 4 && BPP == 32)
            {
                pixelFormat += "A";
            }

            int           w1    = 0;
            List <string> order = s.GetVariable("WRITE_ORDER");

            for (int i = 0; i < order.Count; i++)
            {
                switch (order[i])
                {
                case "FILE_MAGIC":
                    List <Byte> magic2 = s.GetVariable("FILE_MAGIC");
                    for (int j = 0; j < magic2.Count; j++)
                    {
                        binr.Write(magic2[j]);
                    }
                    break;

                case "FILE_SIZE":
                    /*if (img.Width % 2 > 0)
                     *  w1 = 1;
                     * binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                     * binr.Write(0x36 + ((img.Width + w1) * img.Height * bpp / 8));*/
                    break;

                case "IMG_PIXELS_LEN":
                    if (img.Width % 2 > 0)
                    {
                        w1 = 1;
                    }
                    binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    binr.Write((img.Width + w1) * img.Height * BPP / 8);
                    break;

                /*case "FILE_HEADER_SIZE":
                 *  binr.Seek(s.GetVariable("FILE_HEADER_SIZE_OFFSET"), SeekOrigin.Begin);
                 *  binr.Write(s.GetVariable("FILE_HEADER_SIZE"));
                 *  break;*/
                case "IMG_WIDTH":
                    //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    //binr.Write(img.Width);
                    VarWriter.WriteInt32(binr, s, order[i], img.Width);
                    break;

                case "IMG_HEIGHT":
                    //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    //binr.Write(img.Height);
                    VarWriter.WriteInt32(binr, s, order[i], img.Height);
                    break;

                case "IMG_BPP":
                    binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    binr.Write(BPP);
                    break;

                case "IMG_PIXELS":
                    if (s.ContainsVariable("IMG_PIXELS_OFFSET"))
                    {
                        binr.Seek(s.GetVariable("IMG_PIXELS_OFFSET"), SeekOrigin.Begin);
                    }
                    //int red = 0, green = 0, blue = 0;
                    w1 = 0;
                    if (s.ContainsVariable("IMG_UNEVEN_PADDING"))
                    {
                        if (s.GetVariable("IMG_UNEVEN_PADDING"))
                        {
                            if (img.Width % 2 > 0)
                            {
                                w1 = 1;
                            }
                        }
                    }
                    if (s.ContainsVariable("IMG_UPSIDE_DOWN"))
                    {
                        if (s.GetVariable("IMG_UPSIDE_DOWN"))
                        {
                            img = Operations.FlipVertical(img);
                        }
                    }

                    List <byte> rgb = new List <byte>();
                    if (s.ContainsVariable("IMG_PIXELS_HANDLER"))
                    {
                        if (s.GetVariable("IMG_PIXELS_HANDLER"))
                        {
                            for (int j = 0; j < img.Height; j++)
                            {
                                for (int q = 0; q < img.Width + w1; q++)
                                {
                                    if (q < img.Width)
                                    {
                                        for (int c = 0; c < pixelFormat.Length; c++)
                                        {
                                            if (pixelFormat[c] == 'B')
                                            {
                                                rgb.Add(img.GetPixel(q, j).B);
                                            }
                                            if (pixelFormat[c] == 'G')
                                            {
                                                rgb.Add(img.GetPixel(q, j).G);
                                            }
                                            if (pixelFormat[c] == 'R')
                                            {
                                                rgb.Add(img.GetPixel(q, j).R);
                                            }
                                            if (pixelFormat[c] == 'A')
                                            {
                                                rgb.Add(img.GetPixel(q, j).A);
                                            }
                                        }
                                    }
                                }
                            }
                            var            SavePixels = s.GetVariable("SavePixels");
                            IList <object> rgbp       = new List <object>();
                            for (int z = 0; z < rgb.Count; z++)
                            {
                                rgbp.Add(rgb[z]);
                            }
                            List <byte> rgbl = SavePixels(rgbp, img.Width, img.Height, BPP);
                            if (rgbl.Count < img.Width * img.Height)
                            {
                                binr.Write(rgb.ToArray());
                            }
                            else
                            {
                                binr.Write(rgbl.ToArray());
                            }
                        }
                    }
                    else
                    {
                        for (int j = 0; j < img.Height; j++)
                        {
                            for (int q = 0; q < img.Width + w1; q++)
                            {
                                if (q < img.Width)
                                {
                                    for (int c = 0; c < pixelFormat.Length; c++)
                                    {
                                        if (pixelFormat[c] == 'B')
                                        {
                                            binr.Write(img.GetPixel(q, j).B);
                                        }
                                        if (pixelFormat[c] == 'G')
                                        {
                                            binr.Write(img.GetPixel(q, j).G);
                                        }
                                        if (pixelFormat[c] == 'R')
                                        {
                                            binr.Write(img.GetPixel(q, j).R);
                                        }
                                        if (pixelFormat[c] == 'A')
                                        {
                                            binr.Write(img.GetPixel(q, j).A);
                                        }
                                    }
                                }
                                else
                                {
                                    for (int c = 0; c < pixelFormat.Length; c++)
                                    {
                                        binr.Write((byte)0);
                                    }
                                }
                            }
                        }
                    }
                    if (s.ContainsVariable("IMG_UPSIDE_DOWN"))
                    {
                        if (s.GetVariable("IMG_UPSIDE_DOWN"))
                        {
                            img = Operations.FlipVertical(img);
                        }
                    }
                    break;

                default:
                    //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    //binr.Write(s.GetVariable(order[i]));
                    VarWriter.WriteScriptVar(binr, s, order[i]);
                    break;
                }
            }
            if (order.Contains("FILE_SIZE"))
            {
                int size = (int)binr.BaseStream.Position;
                binr.Seek(s.GetVariable("FILE_SIZE_OFFSET"), SeekOrigin.Begin);
                binr.Write(size);
            }
            binr.Close();
            fs.Close();
        }
Пример #27
0
 public PythonScriptEngine()
 {
     engine = Python.CreateEngine();
     scope  = engine.CreateScope();
 }
Пример #28
0
 public void ClearScope()
 {
     _scope = _engine.CreateScope();
     Init();
     EchoLine("Scope cleared.");
 }