public static ScriptRuntime.Vector3 GetCenter(ScriptRuntime.Vector3 fvPos1, ScriptRuntime.Vector3 fvPos2)
        {
            ScriptRuntime.Vector3 fvRet = new ScriptRuntime.Vector3();

              fvRet.X = (fvPos1.X + fvPos2.X) / 2.0f;
              fvRet.Y = (fvPos1.Y + fvPos2.Y) / 2.0f;
              fvRet.Z = (fvPos1.Z + fvPos2.Z) / 2.0f;

              return fvRet;
        }
Example #2
0
        public static string GetDataFromPython()
        {
            /*直接加载py文件 =>很大局限性各种方式不能加载第三方模块
             * 方法一:
             * var result=0;
             * var pythonEngine = Python.CreateEngine();
             * var script = pythonEngine.CreateScriptSourceFromFile(System.IO.Directory.GetCurrentDirectory() + "/PythonScript/demo.py");
             * var code = script.Compile(); //编译
             * var scope = pythonEngine.CreateScope();
             * code.Execute(scope);
             * //调用py方法,带参数
             * var _func = scope.GetVariable("call");
             * result = _func(5);
             *
             * return result;
             *方法二:
             * var engine = Python.CreateEngine();
             * var scope = engine.CreateScope();
             *
             * scope.SetVariable("my_object_model", new CSharpClass());
             * string pythonscript =
             *  "import sys\n"+:“File 'PyLib.py' not found in language's search path: .”
             *
             *  "def fun(arg1):\n" +
             *  "   result = arg1+1\n" +
             *  "   return result\n" +
             *  "adder = fun(5) + my_object_model.Foo(2)\n";
             * engine.CreateScriptSourceFromString(pythonscript).Execute(scope);
             * Console.WriteLine(scope.GetVariable("adder"));
             */
            /*方法三使用ScriptRuntime*/
            ScriptRuntime runtime = Python.CreateRuntime();
            ScriptEngine  engine  = runtime.GetEngine("Python");
            var           path    = engine.GetSearchPaths();

            engine.SetSearchPaths(path);
            dynamic py = runtime.UseFile(@"PythonScript\demo.py");

            var res = py.call(40);

            Console.WriteLine("调用python输出的结果:" + res);
            string str = res.ToString();

            return(str);
        }
        protected void SetupEngine()
        {
            var setup = Python.CreateRuntimeSetup(null);

            setup.HostType = typeof(SnekScriptHost);
            var runtime = new ScriptRuntime(setup);

            engine = runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName);
            SnekImporter.OverrideImport(engine);

            defaultScope = new SnekScope(engine.CreateScope());

            SetupAssemblies();

            AddSearchPath(Application.streamingAssetsPath + "/");

            MlfProcessorManager.OnEngineInit(this);
        }
Example #4
0
 private Shotgun()
 {
     lock (this) {
         if (_pythonModule == null)
         {
             // Find out where our files are
             Assembly exAssembly  = System.Reflection.Assembly.GetExecutingAssembly();
             Uri      uriCodeBase = new Uri(exAssembly.CodeBase);
             String   installBase = Path.GetDirectoryName(uriCodeBase.LocalPath.ToString());
             // Initialize IronPython
             ScriptRuntime           ipy  = Python.CreateRuntime();
             IronPython.Runtime.List path = ipy.GetSysModule().GetVariable("path");
             // Point IronPython to our files
             path.append(Path.Combine(installBase, "Python", "PythonStatic.zip"));
             _pythonModule = ipy.UseFile(Path.Combine(installBase, "Python", "shotgun_config.py"));
         }
     }
 }
Example #5
0
        private void FromSourceCode(string code)
        {
            _sourceCode    = code;
            _scriptScope   = _scriptEngine.CreateScope();
            _scriptRuntime = _scriptEngine.Runtime;
            _scriptEngine.Execute(_sourceCode, _scriptScope);


            _variablesNames = _scriptScope.GetVariableNames().ToArray();
            string imagePath = _scriptScope.GetVariable("icon");

            Debug.WriteLine($"[PythonObject] Loading image {imagePath}");
            _icon = new Icon(imagePath);
            if (_icon.ResourceIds[0] == -1)
            {
                LogManager.EditorLogger.LogError($"Image {imagePath} was not found!");
            }
        }
Example #6
0
        protected HAPITestBase()
        {
            var ses = CreateSetup();

            ses.HostType   = typeof(TestHost);
            _runtime       = new ScriptRuntime(ses);
            _remoteRuntime = ScriptRuntime.CreateRemote(TestHelpers.CreateAppDomain("Alternate"), ses);

            _runTime = _runtime;// _remoteRuntime;

            _PYEng = _runTime.GetEngine("py");
            _RBEng = _runTime.GetEngine("rb");

            SetTestLanguage();

            _defaultScope = _runTime.CreateScope();
            _codeSnippets = new PreDefinedCodeSnippets();
        }
Example #7
0
 /// <summary>
 /// Enable task.
 /// </summary>
 /// <param name="inputData"></param>
 public virtual void Enable(Dictionary <string, object> inputData)
 {
     if (Status != TaskStatus.Enabling)
     {
         throw new Exception("Invalid status!");
     }
     this.TaskData = new Dictionary <string, object>();
     ScriptRuntime.InitializeNewTask(this, inputData, Context);
     this.Status = TaskStatus.Enabled;
     EnabledDate = DateTime.Now;
     this.OnTaskEnabling();
     if (this.Status == TaskStatus.Enabled)
     {
         Context.NotifyTaskEvent(new TaskEnabled {
             FromTaskInstanceId = this.InstanceId, ParentTaskInstanceId = this.ParentTaskInstanceId
         });
     }
 }
Example #8
0
        static void Main(string[] args)
        {
            var runtimeSetup = Python.CreateRuntimeSetup(new Dictionary <string, object>());

            runtimeSetup.DebugMode = true;

            var runtime = new ScriptRuntime(runtimeSetup);

            var scope = runtime.CreateScope(new Dictionary <string, object> {
                { "name", "Batman" }
            });

            var engine       = runtime.GetEngine("py");
            var scriptSource = engine.CreateScriptSourceFromFile("script.py");
            var compiledCode = scriptSource.Compile();

            compiledCode.Execute(scope);
        }
Example #9
0
        internal Host()
        {
            _output = new MemoryStream();
            _error  = new MemoryStream();

            var configFile = Path.GetFullPath(Uri.UnescapeDataString(new Uri(typeof(Host).Assembly.CodeBase).AbsolutePath)) + ".config";

            _runtime = new ScriptRuntime(ScriptRuntimeSetup.ReadConfiguration(configFile));
            _engine  = _runtime.GetEngine("py");
            _runtime.Globals.SetVariable("prompt", Form1.PromptString);

            _theScope = _engine.CreateScope();

            _runtime.IO.SetOutput(_output, new StreamWriter(_output));
            _runtime.IO.SetErrorOutput(_error, new StreamWriter(_error));

            _runtime.LoadAssembly(Assembly.GetAssembly(typeof(Circle)));
        }
Example #10
0
        public override void Increment(ScriptRuntime runtime)
        {
            int loopCount = runtime.LoopEndCount.Pop();
            int count     = runtime.LoopCounts.Pop();
            int begin     = runtime.LoopBegins.Pop();

            if (count < loopCount)
            {                                        //継続
                runtime.CurrentExecuter = begin + 1; //最初の部分+1しておく
                runtime.LoopCounts.Push(count + 1);
                runtime.LoopEndCount.Push(loopCount);
                runtime.LoopBegins.Push(begin);
            }
            else
            {//終了
                runtime.CurrentExecuter++;
            }
        }
Example #11
0
        public CommandRepository(string directory, ScriptRuntime runtime)
        {
            if (runtime == null)
            {
                throw new ArgumentNullException(nameof(runtime));
            }

            DirectoryInfo dir = new DirectoryInfo(directory);

            this.runtime = runtime;

            if (!dir.Exists)
            {
                dir.Create();
            }

            this.directory = dir.FullName;
        }
Example #12
0
        private static string num_to(double val, object [] args, int zeroArgMode, int oneArgMode, int precisionMin, int precisionOffset)
        {
            int precision;

            if (args.Length == 0)
            {
                precision  = 0;
                oneArgMode = zeroArgMode;
            }
            else
            {
                /* We allow a larger range of precision than
                *  ECMA requires; this is permitted by ECMA. */
                precision = ScriptConvert.ToInt32(args [0]);
                if (precision < precisionMin || precision > MAX_PRECISION)
                {
                    string msg = ScriptRuntime.GetMessage("msg.bad.precision", ScriptConvert.ToString(args [0]));
                    throw ScriptRuntime.ConstructError("RangeError", msg);
                }
            }


            switch (zeroArgMode)
            {
            case DTOSTR_FIXED:
                return(val.ToString("F" + (precision + precisionOffset), NumberFormatter));

            case DTOSTR_STANDARD_EXPONENTIAL:
                return(val.ToString("e" + (precision + precisionOffset), NumberFormatter));

            case DTOSTR_STANDARD:
                if (oneArgMode == DTOSTR_PRECISION)
                {
                    return(val.ToString(precision.ToString(), NumberFormatter));
                }
                else
                {
                    return(val.ToString(NumberFormatter));
                }
            }

            Context.CodeBug();
            return(string.Empty); // Not reached
        }
Example #13
0
        static void Main(string[] args)
        {
            TimeSpan      durationToRun = TimeSpan.Zero;
            ScriptRuntime scriptRuntime = null;

            try {
                // ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();  // This is the "standard" to do it; but it's rather less flexible.
                var optionsBuilder = new EssenceSharpOptionsBuilder();
                optionsBuilder.addScriptSearchPath(".");
                String scriptFileName = "Default.es";
                if (args.Length > 0)
                {
                    scriptFileName = args[0];
                    var extension = Path.GetExtension(scriptFileName);
                    if (extension != ".es")
                    {
                        scriptFileName = scriptFileName + ".es";
                    }
                    for (var i = 1; i < args.Length; i++)
                    {
                        optionsBuilder.loadLibrary(args[i]);
                    }
                }
                scriptRuntime = EssenceLaunchPad.CreateRuntime(optionsBuilder);
                ScriptEngine engine             = scriptRuntime.GetEngine("Essence#");
                var          compilationOptions = (ESCompilerOptions)engine.GetCompilerOptions();
                compilationOptions.EnvironmentName = "Smalltalk"; // Should eventually be specifiable by command-line argument.
                ScriptSource script     = engine.CreateScriptSourceFromPathSuffix(scriptFileName);
                var          scriptArgs = new Object[] {};        // Should eventually be specifiable by command-line argument(s).
                var          stopwatch  = new Stopwatch();
                stopwatch.Start();
                var value = script.Execute(compilationOptions, scriptArgs);
                stopwatch.Stop();
                durationToRun = stopwatch.Elapsed;
                Console.WriteLine(" => " + value);
            } finally {
                if (scriptRuntime != null)
                {
                    scriptRuntime.Shutdown();
                }
                Console.WriteLine("________________________________________");
                Console.WriteLine("Script run time = " + durationToRun.ToString() + " (includes setup and compilation time)");
            }
        }
Example #14
0
        void Awake()
        {
            IFileSystem fileSystem;

            _mConsole = new MiniConsole(scrollRect, text, 100);
            _rt       = ScriptEngine.CreateRuntime();
            var asyncManager = new DefaultAsyncManager();
            var pathResolver = new PathResolver();

            pathResolver.AddSearchPath("node_modules");

            if (fileLoader == FileLoader.Resources)
            {
                fileSystem = new ResourcesFileSystem(_mConsole);
                pathResolver.AddSearchPath("dist"); // 这里的路径相对于 Unity Resources 空间
            }
            else if (fileLoader == FileLoader.HMR)
            {
                Debug.LogWarningFormat("功能未完成");
                fileSystem = new HttpFileSystem(_mConsole, baseUrl);
            }
            else
            {
                // 演示了一般文件系统的访问, 实际项目中典型的情况需要自行实现基于 AssetBundle(或 7z/zip) 的文件访问层
                fileSystem = new DefaultFileSystem(_mConsole);
                pathResolver.AddSearchPath("Scripts/out");
                // _rt.AddSearchPath("Assets/Examples/Scripts/dist");
            }

            _rt.withStacktrace = stacktrace;
            if (sourceMap)
            {
                _rt.EnableSourceMap();
            }
            _rt.Initialize(new ScriptRuntimeArgs {
                useReflectBind      = useReflectBind,
                fileSystem          = fileSystem,
                pathResolver        = pathResolver,
                listener            = this,
                asyncManager        = asyncManager,
                logger              = _mConsole,
                byteBufferAllocator = new ByteBufferPooledAllocator()
            });
        }
Example #15
0
        public override object ExecIdCall(IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args)
        {
            if (!f.HasTag(SCRIPT_TAG))
            {
                return(base.ExecIdCall(f, cx, scope, thisObj, args));
            }
            int id = f.MethodId;

            switch (id)
            {
            case Id_constructor: {
                string        source  = (args.Length == 0) ? "" : ScriptConvert.ToString(args [0]);
                IScript       script  = compile(cx, source);
                BuiltinScript nscript = new BuiltinScript(script);
                ScriptRuntime.setObjectProtoAndParent(nscript, scope);
                return(nscript);
            }


            case Id_toString: {
                BuiltinScript real       = realThis(thisObj, f);
                IScript       realScript = real.script;
                if (realScript == null)
                {
                    return("");
                }
                return(cx.DecompileScript(realScript, 0));
            }


            case Id_exec: {
                throw Context.ReportRuntimeErrorById("msg.cant.call.indirect", "exec");
            }


            case Id_compile: {
                BuiltinScript real   = realThis(thisObj, f);
                string        source = ScriptConvert.ToString(args, 0);
                real.script = compile(cx, source);
                return(real);
            }
            }
            throw new ArgumentException(Convert.ToString(id));
        }
Example #16
0
        public void Setup()
        {
            ScriptRuntimeSetup setup = new ScriptRuntimeSetup();

            setup.LanguageSetups.Add(AplusCore.Runtime.AplusLanguageContext.LanguageSetup);

            ScriptRuntime dlrRuntime = new ScriptRuntime(setup);

            this.engine = dlrRuntime.GetEngine("A+");

            ScriptRuntimeSetup setupUni = new ScriptRuntimeSetup();

            setupUni.LanguageSetups.Add(AplusCore.Runtime.AplusLanguageContext.LanguageSetup);
            setupUni.Options.Add("LexerMode", AplusCore.Compiler.LexerMode.UNI);

            ScriptRuntime dlrRuntimeUni = new ScriptRuntime(setupUni);

            this.engineUni = dlrRuntimeUni.GetEngine("A+");
        }
Example #17
0
        private void OnInit()
        {
            if (_runMode == RunMode.Playing)
            {
                return;
            }
            _tick = Environment.TickCount;

            var logger       = new UnityLogger();
            var fileResolver = new FileResolver();
            var fileSystem   = new DefaultFileSystem(logger);

            fileResolver.AddSearchPath("Assets/Examples/Scripts/out/editor");
            fileResolver.AddSearchPath("node_modules");

            _runtime = ScriptEngine.CreateRuntime(true);
            _runtime.Initialize(fileSystem, fileResolver, this, logger, new ByteBufferPooledAllocator());
            _runtime.OnDestroy += OnDestroy;
        }
Example #18
0
        /// <summary>
        /// Create a new dlr host environment
        /// </summary>
        public DlrHost(T language)
        {
            this.language    = language;
            loadedAssemblies = new HashSet <string>();
            resolver         = new List <IDlrImportResolver>();

            // Create runtime
            this.runtimeSetup = language.CreateRuntime();
            this.runtime      = new ScriptRuntime(this.runtimeSetup);

            // Create engine
            scriptEngine = language.CreateEngine(this.runtime);

            //TODO: Refactor this:
            GenericImportModule.Host = (this as DlrHost <IronPythonLanguage>);

            // create default scope
            defaultScope = new DlrScriptScope(this);
        }
Example #19
0
 internal static string SetScriptedSend(ScriptEngine Engine, string Code)
 {
     try
     {
         ScriptRuntime Runtime      = Engine.Runtime;
         Assembly      MainAssembly = Assembly.GetExecutingAssembly();
         string        RootDir      = Directory.GetParent(MainAssembly.Location).FullName;
         Runtime.LoadAssembly(MainAssembly);
         Runtime.LoadAssembly(typeof(String).Assembly);
         Runtime.LoadAssembly(typeof(Uri).Assembly);
         ScriptSource Source = Engine.CreateScriptSourceFromString(Code);
         Source.ExecuteProgram();
         return("");
     }
     catch (Exception Exp)
     {
         return(Exp.Message);
     }
 }
Example #20
0
 private static void toSourceImpl(string uri, string localName, string prefix, System.Text.StringBuilder sb)
 {
     sb.Append("new QName(");
     if (uri == null && prefix == null)
     {
         if (!"*".Equals(localName))
         {
             sb.Append("null, ");
         }
     }
     else
     {
         Namespace.toSourceImpl(prefix, uri, sb);
         sb.Append(", ");
     }
     sb.Append('\'');
     sb.Append(ScriptRuntime.escapeString(localName, '\''));
     sb.Append("')");
 }
Example #21
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="pythonRuntimePath">运行时相对路径</param>
        /// <param name="pythonLibPath">自带类库路径</param>
        /// <param name="options"></param>
        public static void Initialize(string pythonRuntimePath, string pythonLibPath, Dictionary <string, object> options)
        {
            try
            {
                RuntimePath = (pythonRuntimePath ?? "").Replace(@"\", "/");
                LibPath     = pythonLibPath;
                _pyEngine   = options == null || options.Count == 0
                        ? Python.CreateEngine()
                        : Python.CreateEngine(options);
                _pyRuntime = _pyEngine.Runtime;
                SetPythonSearchPath(RuntimePath);

                RuntimePathWatcher(RuntimePath, true);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("PythonScriptHost Initialize path:{0} error:{1}", pythonRuntimePath, ex);
            }
        }
Example #22
0
 private void button8_Click(object sender, EventArgs e)
 {
     if (textBox3.Text != "" && textBox12.Text != "" && textBox5.Text != "")
     {
         if (isdigit(textBox3) && isdigit(textBox12) && isdigit(textBox5))
         {
             ScriptRuntime pyRumTime = Python.CreateRuntime();
             dynamic       obj       = pyRumTime.UseFile("rsa.py");
             textBox11.Text = obj.demo_cal(textBox12.Text, textBox8.Text, textBox3.Text);
             textBox12.Text = "";
         }
         else
         {
             isdigit(textBox12);
             isdigit(textBox5);
             MessageBox.Show("亲,非法输入,文本框只能输入数字", "提示", MessageBoxButtons.OK);
         }
     }
 }
        private void OnAiPursue(EntityInfo npc, ScriptRuntime.Vector3 target)
        {
            Scene scene = npc.SceneContext.CustomData as Scene;
            if (null != scene) {
                npc.GetMovementStateInfo().TargetPosition = target;
                float dir = Geometry.GetYRadian(npc.GetMovementStateInfo().GetPosition3D(), target);
                npc.GetMovementStateInfo().SetFaceDir(dir);
                npc.GetMovementStateInfo().SetMoveDir(dir);
                npc.GetMovementStateInfo().IsMoving = true;

                if (npc.GetMovementStateInfo().IsMoveStatusChanged) {
                    npc.GetMovementStateInfo().IsMoveStatusChanged = false;

                    Msg_RC_NpcMove npcMoveBuilder = DataSyncUtility.BuildNpcMoveMessage(npc);
                    if (null != npcMoveBuilder)
                        scene.NotifyAllUser(RoomMessageDefine.Msg_RC_NpcMove, npcMoveBuilder);
                }
            }
        }
Example #24
0
        private void initRuby()
        {
            ScriptRuntimeSetup runtimeSetup = ScriptRuntimeSetup.ReadConfiguration();
            var languageSetup = IronRuby.RubyHostingExtensions.AddRubySetup(runtimeSetup);

            runtimeSetup.DebugMode      = false;
            runtimeSetup.PrivateBinding = false;
            runtimeSetup.HostType       = typeof(RhoHost);

            languageSetup.Options["NoAdaptiveCompilation"] = false;
            languageSetup.Options["CompilationThreshold"]  = 0;
            languageSetup.Options["Verbosity"]             = 2;

            m_runtime = IronRuby.Ruby.CreateRuntime(runtimeSetup);
            Stream errStream = new CRhoOutputStream(true);

            m_runtime.IO.SetErrorOutput(errStream, new StreamWriter(errStream, System.Text.Encoding.UTF8));
            Stream outStream = new CRhoOutputStream(false);

            m_runtime.IO.SetOutput(outStream, new StreamWriter(outStream, System.Text.Encoding.UTF8));

            m_engine  = IronRuby.Ruby.GetEngine(m_runtime);
            m_context = (RubyContext)Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext(m_engine);

            m_context.ObjectClass.SetConstant("RHO_WP7", 1);
            m_context.ObjectClass.AddMethod(m_context, "__rhoGetCallbackObject", new RubyLibraryMethodInfo(
                                                new[] { LibraryOverload.Create(new Func <System.Object, System.Int32, System.Object>(RhoKernelOps.__rhoGetCallbackObject), false, 0, 0) },
                                                RubyMethodVisibility.Public,
                                                m_context.ObjectClass
                                                ));
            m_context.ObjectClass.AddMethod(m_context, "__rho_exist_in_resources", new RubyLibraryMethodInfo(
                                                new[] { LibraryOverload.Create(new Func <System.Object, System.String, System.Object>(RhoKernelOps.__rho_exist_in_resources), false, 0, 0) },
                                                RubyMethodVisibility.Public,
                                                m_context.ObjectClass
                                                ));

            m_context.Loader.LoadAssembly("RhoRubyLib", "rho.rubyext.rubyextLibraryInitializer", true, true);

            System.Collections.ObjectModel.Collection <string> paths = new System.Collections.ObjectModel.Collection <string>();
            paths.Add("lib");
            paths.Add("apps/app");
            m_engine.SetSearchPaths(paths);
        }
Example #25
0
        private void _JSActionCallback(ScriptRuntime runtime, JSAction action)
        {
            var e = (FileSystemEventArgs)action.args;

            switch (e.ChangeType)
            {
            case WatcherChangeTypes.Changed:
                Call(_onchange, e.Name, e.FullPath);
                break;

            case WatcherChangeTypes.Created:
                Call(_oncreate, e.Name, e.FullPath);
                break;

            case WatcherChangeTypes.Deleted:
                Call(_ondelete, e.Name, e.FullPath);
                break;
            }
        }
Example #26
0
        internal static void AssertOutput(ScriptRuntime runTime, System.Action f, string expectedOutput, OutputFlags flags)
        {
            StringBuilder builder = new StringBuilder();

            using (StringWriter output = new StringWriter(builder)) {
                RedirectOutput(runTime, output, f);
            }

            string actualOutput = builder.ToString();

            if ((flags & OutputFlags.Raw) == 0)
            {
                actualOutput   = actualOutput.Trim();
                expectedOutput = expectedOutput.Trim();
            }

            Assert.IsTrue(actualOutput == expectedOutput, "Unexpected output: '" +
                          builder.Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t") + "'.");
        }
Example #27
0
        public App()
        {
            Configuration config    = null;
            string        directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            if (Directory.Exists(directory))
            {
                string fileName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where String.Equals(fileName, Path.GetFileNameWithoutExtension(s)) select s)
                {
                    ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();

                    exeConfigurationFileMap.ExeConfigFilename = s;
                    config = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
                }
            }

            if (config == null)
            {
                config    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                directory = null;
            }

            if (config.AppSettings.Settings["Scripts"] != null)
            {
                this.runtime = new ScriptRuntime(ScriptRuntimeSetup.ReadConfiguration());

                foreach (string fileName in Directory.GetFiles(directory == null ? config.AppSettings.Settings["Scripts"].Value : Path.Combine(directory, config.AppSettings.Settings["Scripts"].Value)))
                {
                    ScriptEngine engine;

                    if (this.runtime.TryGetEngineByFileExtension(Path.GetExtension(fileName), out engine))
                    {
                        ScriptSource source = engine.CreateScriptSourceFromFile(fileName);
                        CompiledCode code   = source.Compile();

                        code.Execute(this.runtime.CreateScope());
                    }
                }
            }
        }
Example #28
0
        public CompiledCode GetCompiledScript()
        {
            try
            {
                m_scriptText = GetText();

                if (m_scriptText.IsNullOrBlank())
                {
                    throw new ApplicationException("Cannot load script, file was empty " + m_scriptPath + ".");
                }

                // Configure script engine.
                ScriptTypesEnum scriptType = GetScriptType(m_scriptPath);

                if (scriptType == ScriptTypesEnum.Python)
                {
                    logger.Debug("Compiling IronPython script file from " + m_scriptPath + ".");
                    ScriptRuntime scriptRuntime = IronPython.Hosting.Python.CreateRuntime();
                    ScriptScope   scriptScope   = scriptRuntime.CreateScope("IronPython");
                    CompiledCode  compiledCode  = scriptScope.Engine.CreateScriptSourceFromFile(m_scriptPath).Compile();
                    logger.Debug("IronPython compilation complete.");
                    return(compiledCode);
                    //return scriptScope.Engine.CreateScriptSourceFromString(m_scriptText).Compile();
                }
                else if (scriptType == ScriptTypesEnum.Ruby)
                {
                    logger.Debug("Compiling IronRuby script file from " + m_scriptPath + ".");
                    ScriptRuntime scriptRuntime = IronRuby.Ruby.CreateRuntime();
                    ScriptScope   scriptScope   = scriptRuntime.CreateScope("IronRuby");
                    return(scriptScope.Engine.CreateScriptSourceFromString(m_scriptText).Compile());
                }
                else
                {
                    throw new ApplicationException("ScriptLoader could not compile script, unrecognised proxy script type " + scriptType + ".");
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetCompiledScript. " + excp.Message);
                throw;
            }
        }
Example #29
0
        public パス(エフェクト effect, EffectPass d3dPass)
        {
            D3DPass = d3dPass;

            EffectVariable commandAnnotation = EffectParseHelper.アノテーションを取得する(d3dPass, "Script", "string");

            Command = (commandAnnotation == null) ? "" : commandAnnotation.AsString().GetString();

            if (!d3dPass.VertexShaderDescription.Variable.IsValid)
            {
                //TODO この場合標準シェーダーの頂点シェーダを利用する
            }

            if (!d3dPass.PixelShaderDescription.Variable.IsValid)
            {
                //TODO この場合標準シェーダーのピクセルシェーダを利用する
            }

            ScriptRuntime = new ScriptRuntime(Command, effect, null, this);
        }
        //[Ignore]
        public void SourceFileSearchPath_NullPathEnvironmentVariableName()
        {
            // Todo - Investigate this to verify correctness.
            // Setup derived With basic DerivedHostTest
            ScriptRuntime runtimeEnv = CreateHostRuntime(typeof(ScriptHostBasicSubTest), "-nothing");

            // Setup Env Var to null/empty
            TestHelpers.EnvSetupTearDown EnvTest = new TestHelpers.EnvSetupTearDown("DLRPATH", "");

            // Setup host
            ScriptHostBasicSubTest host = (ScriptHostBasicSubTest)runtimeEnv.Host;

            // Setup expected paths
            List <string> expectedPaths = new List <string> {
                "."
            };

            // Verify results
            ValidateSourceFileSearchPathValues(host.GetSourceFileSearchPath(), expectedPaths);
        }
Example #31
0
        public TestRuntime(Driver /*!*/ driver, TestCase /*!*/ testCase)
        {
            _driver   = driver;
            _testName = testCase.Name;

            if (testCase.Options.NoRuntime)
            {
                return;
            }

#if !WIN8
            if (_driver.SaveToAssemblies)
            {
                Environment.SetEnvironmentVariable("DLR_AssembliesFileName", _testName);
            }
#endif
            _engine  = _driver.CreateRubyEngine(testCase.Options.PrivateBinding, testCase.Options);
            _runtime = _engine.Runtime;
            _context = (RubyContext)HostingHelpers.GetLanguageContext(_engine);
        }
Example #32
0
        public void Create_PartialTrust()
        {
            // basic check of running a host in partial trust
            AppDomainSetup info = new AppDomainSetup();

            info.ApplicationBase = TestHelpers.BinDirectory;
            info.ApplicationName = "Test";
            Evidence evidence = new Evidence();

            evidence.AddHost(new Zone(SecurityZone.Internet));
            System.Security.PermissionSet permSet = SecurityManager.GetStandardSandbox(evidence);
            AppDomain newDomain = AppDomain.CreateDomain("test", evidence, info, permSet, null);

            ScriptRuntime runtime = CreateRemoteRuntime(newDomain);
            ScriptScope   scope   = runtime.CreateScope();

            scope.SetVariable("test", "value");

            AppDomain.Unload(newDomain);
        }
Example #33
0
 internal void CreateTexture(ScriptRuntime.RenderToTexture rtt)
 {
     mRenderTarget = new RenderTarget(rtt);
     ICall_createTexture_FromTarget(mInstance.Ptr, mRenderTarget.Instance.Ptr);
 }
 public EntityInfo GetNearest(ScriptRuntime.Vector3 pos, ref float minPowDist)
 {
     EntityInfo result = null;
     float powDist = 0.0f;
     for (LinkedListNode<EntityInfo> linkNode = m_Entities.FirstValue; null != linkNode; linkNode = linkNode.Next) {
         EntityInfo entity = linkNode.Value;
         if (null != entity && entity.IsCombatNpc()) {
             powDist = Geometry.DistanceSquare(pos, entity.GetMovementStateInfo().GetPosition3D());
             if (minPowDist > powDist) {
                 result = entity;
                 minPowDist = powDist;
             }
         }
     }
     return result;
 }
 private void OnAiPursue(EntityInfo entity, ScriptRuntime.Vector3 target)
 {
     if (null != entity) {
         EntityViewModel npcViewModel = EntityViewModelManager.Instance.GetEntityViewById(entity.GetId());
         npcViewModel.MoveTo(target.X, target.Y, target.Z);
     }
 }
Example #36
0
        public virtual int Run(string[] args) {
            var runtimeSetup = CreateRuntimeSetup();
            var options = new ConsoleHostOptions();
            _optionsParser = new ConsoleHostOptionsParser(options, runtimeSetup);

            try {
                ParseHostOptions(args);
            } catch (InvalidOptionException e) {
                Console.Error.WriteLine("Invalid argument: " + e.Message);
                return _exitCode = 1;
            }

            SetEnvironment();

            string provider = GetLanguageProvider(runtimeSetup);

            LanguageSetup languageSetup = null;
            foreach (var language in runtimeSetup.LanguageSetups) {
                if (language.TypeName == provider) {
                    languageSetup = language;
                }
            }
            if (languageSetup == null) {
                // the language doesn't have a setup -> create a default one:
                languageSetup = new LanguageSetup(Provider.AssemblyQualifiedName, Provider.Name);
                runtimeSetup.LanguageSetups.Add(languageSetup);
            }

            // inserts search paths for all languages (/paths option):
            InsertSearchPaths(runtimeSetup.Options, Options.SourceUnitSearchPaths);

            _consoleOptions = ParseOptions(Options.IgnoredArgs.ToArray(), runtimeSetup, languageSetup);
            if (_consoleOptions == null) {
                return _exitCode = 1;
            }

            _runtime = new ScriptRuntime(runtimeSetup);

            try {
                _engine = _runtime.GetEngineByTypeName(provider);
            } catch (Exception e) {
                Console.Error.WriteLine(e.Message);
                return _exitCode = 1;
            }

            Execute();
            return _exitCode;
        }
 public void SetPosition2D(ScriptRuntime.Vector2 pos)
 {
     m_Position.X = pos.X;
     m_Position.Z = pos.Y;
 }
 public void SetPosition(ScriptRuntime.Vector3 pos)
 {
     m_Position = pos;
 }
Example #39
0
 internal RenderTarget(ScriptRuntime.RenderToTexture rtt)
 {
     mInstance = ICall_createFromScriptRuntimeRenderToTexture(rtt);
 }
Example #40
0
 private static extern IntPtr ICall_createFromScriptRuntimeRenderToTexture(ScriptRuntime.RenderToTexture rtt);
 public void NotifyAiPursue(EntityInfo entity, ScriptRuntime.Vector3 target)
 {
     if (null != OnAiPursue)
         OnAiPursue(entity, target);
 }
Example #42
0
        public virtual int Run(string[] args) {
            var runtimeSetup = CreateRuntimeSetup();
            var options = new ConsoleHostOptions();
            _optionsParser = new ConsoleHostOptionsParser(options, runtimeSetup);

            try {
                ParseHostOptions(args);
            } catch (InvalidOptionException e) {
                Console.Error.WriteLine("Invalid argument: " + e.Message);
                return _exitCode = 1;
            }

            SetEnvironment();

            string provider = GetLanguageProvider(runtimeSetup);

            LanguageSetup languageSetup = null;
            foreach (var language in runtimeSetup.LanguageSetups) {
                if (language.TypeName == provider) {
                    languageSetup = language;
                }
            }
            if (languageSetup == null) {
                // the language doesn't have a setup -> create a default one:
                languageSetup = new LanguageSetup(Provider.AssemblyQualifiedName, Provider.Name);
                runtimeSetup.LanguageSetups.Add(languageSetup);
            }

            // inserts search paths for all languages (/paths option):
            InsertSearchPaths(runtimeSetup.Options, Options.SourceUnitSearchPaths);

            _languageOptionsParser = CreateOptionsParser();

            try {
                _languageOptionsParser.Parse(Options.IgnoredArgs.ToArray(), runtimeSetup, languageSetup, PlatformAdaptationLayer);
            } catch (InvalidOptionException e) {
                Console.Error.WriteLine(e.Message);
                return _exitCode = -1;
            }

#if !SILVERLIGHT
            if (typeof(DynamicMethod).GetConstructor(new Type[] { typeof(string), typeof(Type), typeof(Type[]), typeof(bool) }) == null) {
                Console.WriteLine(string.Format("{0} requires .NET 2.0 SP1 or later to run.", languageSetup.DisplayName));
                Environment.Exit(1);
            }
#endif

            _runtime = new ScriptRuntime(runtimeSetup);

            try {
                _engine = _runtime.GetEngineByTypeName(provider);
            } catch (Exception e) {
                Console.Error.WriteLine(e.Message);
                return _exitCode = 1;
            }

            Execute();
            return _exitCode;
        }
 internal bool CalcPosAndDir(int targetId, out ScriptRuntime.Vector3 pos, out float dir)
 {
     EntityViewModel view = GetEntityViewById(targetId);
     if (null != view) {
         MovementStateInfo msi = view.Entity.GetMovementStateInfo();
         pos = msi.GetPosition3D();
         dir = msi.GetFaceDir();
         return true;
     } else {
         pos = ScriptRuntime.Vector3.Zero;
         dir = 0;
         return false;
     }
 }