private void CallButton_Click(object sender, RoutedEventArgs e)
        {
            string scriptCode = Chunk.Text;

            // Register types to be used in the script.
            UserData.RegisterType<BusinessObject>();
            UserData.RegisterType<EventArgs>();

            Script script = new Script();

            try
            {
                var obj = UserData.Create(bus);

                script.Globals.Set("obj", obj);

                script.DoString(scriptCode);

                Result.Foreground = new SolidColorBrush(Colors.Black);
                Result.Text = "done";
            }
            catch (Exception ex)
            {
                Result.Foreground = new SolidColorBrush(Colors.Red);
                Result.Text = ex.Message;
            }
        }
 /// <summary>
 /// Set the script this console should display the output
 /// to. The script must have been set to "redirect"
 /// </summary>
 /// <param name="script">the python script instance</param>
 public void SetScript(Script script)
 {
     readingScript = script;
     writer = readingScript.OutputWriter;
     //Only enable if writer is not null
     updateoutput.Enabled = (writer != null);//*/
 }
Beispiel #3
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="script"></param>
 public GiveXPToken(Script script)
     : base(script)
 {
     Amount = script.ReadAddr();
     Unknown0 = script.ReadShort();
     Unknown1 = script.ReadShort();
 }
Beispiel #4
0
        internal static int Interpret(Script script, string prefix)
        {
            IEnumerable<Frame> frames = script.CreateFrames();

            double range;
            {
                double maxDist = (script.Config.Width + script.Config.Height) * 10;
                range = maxDist * maxDist;
            }

            IDictionary<IVariable, VariableWithValue> previousState = new Dictionary<IVariable, VariableWithValue>();

            foreach (var f in frames) {
                var bitmap = new Bitmap(script.Config.Width, script.Config.Height);
                Graphics drawingPane = Graphics.FromImage(bitmap);

                // Compute locations for each anchor of each thing.
                Dictionary<string, double> debugExpectedResults;
                script.DebugExpectedResults.TryGetValue(f.FrameNo, out debugExpectedResults);
                IDictionary<string, IDictionary<string, ConstVector>> anchorLocations =
                    f.SolveConstraints(range, ref previousState, debugExpectedResults);
                foreach (var th in script.Things) {
                    th.Draw(drawingPane, anchorLocations[th.Name]);
                }

                bitmap.Save(string.Format("{0}{1:000000}.jpg", prefix, f.FrameNo), ImageFormat.Jpeg);
            }

            return frames.Count();
        }
 public TfsHelper(IContainer container, TextWriter stdout, Script script)
 {
     _container = container;
     _stdout = stdout;
     _script = script;
     _versionControlServer = new FakeVersionControlServer(_script);
 }
Beispiel #6
0
 public Script(Script scriptSig, Script scriptPubKey)
 {
     elements = scriptSig.elements
         .Concat(new ScriptElement[] {new ScriptElement(OpCode.OP_CODESEPARATOR)})
         .Concat(scriptPubKey.elements)
         .ToList();
 }
Beispiel #7
0
 public ScriptInvocation(dynamic function = null, WorldObject associate = null, WorldObject invoker = null, Script script = null)
 {
     Function = function;
     Associate = associate;
     Invoker = invoker;
     Script = null;
 }
Beispiel #8
0
 void Start()
 {
     try
     {
         DefaultScriptUserdataDelegateType.SetFactory(new DelegateFactory());
         List<string> scripts = new List<string>();
         scripts.Add("window");
         Script script = new Script();
         Launch.Script = script;
         script.LoadLibrary();
         script.PushAssembly(typeof(int).Assembly);
         script.PushAssembly(typeof(GameObject).Assembly);
         script.PushAssembly(GetType().Assembly);
         script.SetObject("print", new ScorpioFunction(Print));
         for (int i = 0; i < scripts.Count; ++i)
         {
             script.LoadString(scripts[i], (Resources.Load(scripts[i]) as TextAsset).text);
         }
         Util.AddComponent(obj, (ScriptTable)script.GetValue("window"));
     }
     catch (System.Exception ex)
     {
         Debug.LogError("Stack : " + Script.GetStackInfo());
         Debug.LogError("Start is error " + ex.ToString());
     }
 }
		static void ConvertToWhileLoop(Script script, DoWhileStatement originalStatement)
		{
			script.Replace(originalStatement, new WhileStatement {
				Condition = originalStatement.Condition.Clone(),
				EmbeddedStatement = originalStatement.EmbeddedStatement.Clone()
			});
		}
Beispiel #10
0
		internal static int LoadFunction(Script script, SourceCode source, ByteCode bytecode, bool usesGlobalEnv)
		{
			ScriptLoadingContext lcontext = CreateLoadingContext(script, source);

			try
			{
				FunctionDefinitionExpression fnx;

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
					fnx = new FunctionDefinitionExpression(lcontext, usesGlobalEnv);

				int beginIp = -1;

				//var srcref = new SourceRef(source.SourceID);

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
				using (bytecode.EnterSource(null))
				{
					bytecode.Emit_Nop(string.Format("Begin function {0}", source.Name));
					beginIp = fnx.CompileBody(bytecode, source.Name);
					bytecode.Emit_Nop(string.Format("End function {0}", source.Name));
				}

				//Debug_DumpByteCode(bytecode, source.SourceID);

				return beginIp;
			}
			catch (SyntaxErrorException ex)
			{
				ex.DecorateMessage(script);
				throw;
			}

		}
Beispiel #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="script"></param>
        public ChangeWallToken(Script script)
            : base(script)
        {
            Type = script.ReadByte();
            switch (Type)
            {
                // All sides
                case 0xf7:
                {
                    Target = Location.FromScript(script); // script.ReadPosition();
                    To = script.ReadByte();
                    From = script.ReadByte();
                }
                break;
                // One side
                case 0xe9:
                {
                    Target = Location.FromScript(script); // script.ReadPosition();
                    Side = script.ReadByte();
                    To = script.ReadByte();
                    From = script.ReadByte();
                }
                break;
                // Open door
                case 0xea:
                {
                    Target = Location.FromScript(script); // script.ReadPosition();
                }
                break;

            }
        }
Beispiel #12
0
 public void Execute(Script script, Regex procedure_pattern) {
     if (!_scriptcontrol.Build(script))
         return;
     var list_procedures = ListProcedures(script, procedure_pattern);
     if (_scriptcontrol.Run(list_procedures.ProcInitialize)) {
         foreach (var procedure in list_procedures) {
             if (_scriptcontrol.Run(list_procedures.ProcSetup)) {
                 if (_scriptcontrol.Run(procedure, true)) {
                     OnSuccess(new ScriptSuccess(script, procedure));
                 } else {
                     var error = _scriptcontrol.Error;
                     if (list_procedures.ProcOnError != null) {
                         list_procedures.ProcOnError.Arguments = new[] { 
                             procedure.Name,
                             _scriptcontrol.Error.ToString() 
                         };
                         if (_scriptcontrol.Run(list_procedures.ProcOnError))
                             error.AddInfo((string)_scriptcontrol.Result);
                     }
                     OnError(error);
                 }
                 _scriptcontrol.Run(list_procedures.ProcTearDown);
             }
         }
         _scriptcontrol.Run(list_procedures.ProcTerminate);
     }
     if (list_procedures.Count == 0 && script.Succeed)
         OnSuccess(new ScriptSuccess(script));
     OnInfo(script, _scriptcontrol.WScriptEcho);
 }
Beispiel #13
0
		internal static int LoadChunk(Script script, SourceCode source, ByteCode bytecode)
		{
			ScriptLoadingContext lcontext = CreateLoadingContext(script, source);
			try
			{
				Statement stat;

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
					stat = new ChunkStatement(lcontext);

				int beginIp = -1;

				//var srcref = new SourceRef(source.SourceID);

				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
				using (bytecode.EnterSource(null))
				{
					bytecode.Emit_Nop(string.Format("Begin chunk {0}", source.Name));
					beginIp = bytecode.GetJumpPointForLastInstruction();
					stat.Compile(bytecode);
					bytecode.Emit_Nop(string.Format("End chunk {0}", source.Name));
				}

				//Debug_DumpByteCode(bytecode, source.SourceID);

				return beginIp;
			}
			catch (SyntaxErrorException ex)
			{
				ex.DecorateMessage(script);
				throw;
			}
		}
Beispiel #14
0
 public static void AddApi(Script script)
 {
     UserData.RegisterType<Position>();
     #region Pings
     script.Globals["PING_ASSISTME"] = PingCategory.AssistMe;
     script.Globals["PING_DANGER"] = PingCategory.Danger;
     script.Globals["PING_ENEMYMISSING"] = PingCategory.EnemyMissing;
     script.Globals["PING_FALLBACK"] = PingCategory.Fallback;
     script.Globals["PING_NORMAL"] = PingCategory.Normal;
     script.Globals["PING_ONMYWAY"] = PingCategory.OnMyWay;
     #endregion
     script.Globals["GetTickCount"] = (Func<int>) GetTickCount;
     script.Globals["GetLatency"] = (Func<int>) GetPing;
     script.Globals["GetCursorPos"] = (Func<Position>) GetCursorPosition;
     script.Globals["GetGameTimer"] = (Func<float>) GetGameTime;
     script.Globals["WorldToScreen"] = (Func<GameUnit, Position>) WorldToScreen;
     script.Globals["GetTarget"] = (Func<GameUnit>) GetTarget;
     script.Globals["SetTarget"] = (Action<GameUnit>) SetTarget;
     script.Globals["BuyItem"] = (Action<int>) BuyItem;
     script.Globals["SellItem"] = (Action<SpellSlot>) SellItem;
     script.Globals["IsWallOfGrass"] = (Func<Position, bool>) IsWallOfGrass;
     script.Globals["KillProcess"] = (Action<string>) TaskKill;
     script.Globals["PingSignal"] = (Action<object, float, float, float, PingCategory>) Ping;
     //script.Globals["IsItemPurchasable"] = (Func<int, bool>) IsItemPurchasable;
     script.Globals["GetGameTimer"] = (Func<float>) GetGameTimer;
     script.Globals["GetMyHero"] = (Func<GameUnit>) GetMyHero;
 }
		internal void DecorateMessage(Script script)
		{
			if (Token != null)
			{
				DecorateMessage(script, Token.GetSourceRef(false));
			}
		}
Beispiel #16
0
        public void Save()
        {
            Script s = new Script();
            s.Name = Globals.GameDir + "map\\geographical_region.txt";
            s.Root = new ScriptScope();
            foreach (var region in regions)
            {
                ScriptScope ss = new ScriptScope();

                String duchieList = "";

                foreach (var titleParser in region.duchies)
                {
                    duchieList = duchieList + " " + titleParser.Name;
                }
                ss.Name = StarNames.SafeName(region.name);
                ss.Do(@"
                    duchies = {
                        " + duchieList + @"
                    }
");
                s.Root.Add(ss);
           }

            s.Save();
        }
		public static void CheckScriptOwnership(this IScriptPrivateResource resource, Script script)
		{
			if (resource.OwnerScript != null && resource.OwnerScript != script && script != null)
			{
				throw new ScriptRuntimeException("Attempt to access a resource owned by a script, from another script");
			}
		}
 public override void Duplicate(EditorControl editorControl, string suffix)
 {
     Script duplicate = new Script(script);
     duplicate.Name += suffix;
     editorControl.World.AddScript(duplicate);
     editorControl.RefreshWorldTreeView();
 }
        public override bool CheckScriptPubKey(Script scriptPubKey)
        {
            var ops = scriptPubKey.ToOps().ToArray();
            if(ops.Length < 3)
                return false;

            var sigCount = ops[0];
            if(!sigCount.IsSmallUInt)
                return false;

            var expectedKeyCount = 0;
            var keyCountIndex = 0;
            for(int i = 1 ; i < ops.Length ; i++)
            {
                if(ops[i].PushData == null)
                    return false;
                if(!PubKey.IsValidSize(ops[i].PushData.Length))
                {
                    keyCountIndex = i;
                    break;
                }
                expectedKeyCount++;
            }
            if(!ops[keyCountIndex].IsSmallUInt)
                return false;
            if(ops[keyCountIndex].GetValue() != expectedKeyCount)
                return false;
            return ops[keyCountIndex + 1].Code == OpcodeType.OP_CHECKMULTISIG &&
                  keyCountIndex + 1 == ops.Length - 1;
        }
Beispiel #20
0
        public void ScriptImplementsIEnumerable()
        {
            Script script = new Script();

            Assert.IsInstanceOfType(((IEnumerable<Statement>)script).GetEnumerator(), typeof(IEnumerator<Statement>));
            Assert.IsInstanceOfType(((IEnumerable)script).GetEnumerator(), typeof(IEnumerator));
        }
 private DefineState m_define;                                                   //define当前状态
 public ScriptParser(Script script, List<Token> listTokens, string strBreviary)
 {
     m_script = script;
     m_strBreviary = strBreviary;
     m_iNextToken = 0;
     m_listTokens = new List<Token>(listTokens);
 }
Beispiel #22
0
        //dodawanie nowego skryptu
        public bool AddNewScript(Script script)
        {
            string query = "INSERT INTO Script VALUES(@UserID, @DateOfCreate, @Path, @NameOfProject, @TypeOfDb, (SELECT Id FROM InstanceOfDb WHERE Name = @name), @UniqueName, @Version)";
            string query2 = "INSERT INTO ListOfScript VALUES(@UserID, (SELECT Id FROM Script WHERE UniqueName = @UniqueName))";
            query += query2;
            SqlCommand cmd = new SqlCommand(query, con);
            script.Path = "C:\\Praca inzynierska\\Projekt\\Pliki\\" + script.UniqueName;
            cmd.Parameters.AddWithValue("@UserID", script.UserID);
            cmd.Parameters.AddWithValue("@DateOfCreate", script.DateOfCreate);
            cmd.Parameters.AddWithValue("@Path", script.Path);
            cmd.Parameters.AddWithValue("@NameOfProject", script.NameOfProject);
            cmd.Parameters.AddWithValue("@TypeOfDb", script.TypeOfDb);
            cmd.Parameters.AddWithValue("@name", script.InstOfDb.Name);
            cmd.Parameters.AddWithValue("@UniqueName", script.UniqueName);
            cmd.Parameters.AddWithValue("@Version", script.Version);

            int rows = cmd.ExecuteNonQuery();
            if (rows == 2)
            {
                File file = new File();
                if (file.CreateFile(script.Path, script.Content))
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
Beispiel #23
0
 public void Execute(Script script, Regex procedure_pattern) {
     var textwriter = new StringWriter();
     var wscript = new WScript(script.Path, script.Arguments);
     wscript.OnEcho += textwriter.WriteLine;
     if (!_compiler.Compile(wscript, script))
         return;
     var list_procedures = ListProcedures(script, procedure_pattern);
     if (_compiler.Run(list_procedures.ProcInitialize)) {
         foreach (var procedure in list_procedures) {
             if (_compiler.Run(list_procedures.ProcSetup)) {
                 if (_compiler.Run(procedure, true)) {
                     OnSuccess(new ScriptSuccees(script, procedure));
                 } else {
                     var error = _compiler.Error;
                     if (list_procedures.ProcOnError != null) {
                         list_procedures.ProcOnError.Params = new object[] { procedure.Name, _compiler.Error.ToString() };
                         if (_compiler.Run(list_procedures.ProcOnError))
                             error.AddInformation((string)_compiler.Result);
                     }
                     OnError(error);
                 }
                 _compiler.Run(list_procedures.ProcTearDown);
             }
         }
         _compiler.Run(list_procedures.ProcTerminate);
     }
     if (list_procedures.Count == 0 && script.Succeed)
         OnSuccess(new ScriptSuccees(script));
     OnInfo(script, textwriter.ToString().CleanEnd());
 }
Beispiel #24
0
		private void DebugScript(string filename)
		{
			m_Script = new Script(CoreModules.Preset_HardSandbox);
			m_Script.Options.UseLuaErrorLocations = true;
			m_Script.Options.DebugPrint = s => { Console_WriteLine("{0}", s); };

			((ScriptLoaderBase)m_Script.Options.ScriptLoader).ModulePaths = ScriptLoaderBase.UnpackStringPaths("Modules/?;Modules/?.lua");

			try
			{
				m_Script.LoadFile(filename, null, filename.Replace(':', '|'));
			}
			catch (Exception ex)
			{
				txtOutput.Text = "";
				Console_WriteLine("{0}", ex.Message);
				return;
			}

			m_Script.AttachDebugger(this);

			Thread m_Debugger = new Thread(DebugMain);
			m_Debugger.Name = "MoonSharp Execution Thread";
			m_Debugger.IsBackground = true;
			m_Debugger.Start();
		}
Beispiel #25
0
        public Engine()
        {
            mRenderer = new vRenderer();
            mInput = new Input();
            mNetwork = new Network();
            mScript = new Script();

            mWorld = new cWorld();

            bool other = false;

            for (int y = 0; y < 10; y++)
            {
                for (int x = 0; x < 10; x++)
                {
                    World_Geom geom = new World_Geom(new Vector2(x*64, y*64), "tex_bookshelf.bmp");

                    if (!other)
                    {
                        //geom = new World_Geom(new Vector2(x, y), "tex2.bmp");

                        e_pillar door = new e_pillar(new Vector2(x+0.5f, y+0.5f), "tex_3.bmp");
                        mWorld.AddEntity(door);
                    }

                    mWorld.AddGeometry(geom);
                    other = !other;
                }
                other = !other;
            }
        }
Beispiel #26
0
        private static void UpdateAutocompleteCacheThread()
        {
            while (true)
            {
                Thread.Sleep(50);
                if (_scriptToUpdateInBackground != null)
                {
                    Script scriptToUpdate;
                    lock (_scriptLockObject)
                    {
                        scriptToUpdate = _scriptToUpdateInBackground;
                        _scriptToUpdateInBackground = null;
                    }
                    try
                    {
                        OnBackgroundCacheUpdateStatusChanged(BackgroundAutoCompleteStatus.Processing, null);

                        ConstructCache(scriptToUpdate, true);

                        OnBackgroundCacheUpdateStatusChanged(BackgroundAutoCompleteStatus.Finished, null);
                    }
                    catch (Exception ex)
                    {
                        OnBackgroundCacheUpdateStatusChanged(BackgroundAutoCompleteStatus.Error, ex);
                    }
                }
            }
        }
Beispiel #27
0
        private void AddScript(Script script)
        {
            lock (_padlock)
            {
                if (_scripts.ContainsKey(script))
                {
                    return;
                }

                var files = new string[0];

                if (Directory.Exists(_configuration.ScriptFolder))
                {
                    files = Directory.GetFiles(_configuration.ScriptFolder, script.FileName, SearchOption.AllDirectories);
                }

                if (files.Length == 0)
                {
                    AddEmbeddedScript(script);

                    return;
                }

                if (files.Length > 1)
                {
                    throw new ScriptException(string.Format(SqlResources.ScriptCountException, _configuration.ScriptFolder, script.FileName, files.Length));
                }

                _scripts.Add(script, File.ReadAllText(files[0]));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="script"></param>
        public ChangeLevelToken(Script script)
            : base(script)
        {
            Type = script.ReadByte();
            switch (Type)
            {
                // Inter level
                case 0xe5:
                {
                    Level = script.ReadByte();
                    Target = script.ReadPosition();
                    Direction = script.ReadByte();
                    Unknown0 = script.ReadByte();
                }
                break;

                // Intra level
                case 0x00:
                {
                    Target = script.ReadPosition();
                    Direction = script.ReadByte();
                }
                break;
            }
        }
Beispiel #29
0
 public static void RequestBackgroundCacheUpdate(Script scriptToUpdate)
 {
     lock (_scriptLockObject)
     {
         _scriptToUpdateInBackground = scriptToUpdate;
     }
 }
Beispiel #30
0
        public Room(int roomNumber)
            : base(roomNumber)
        {
            _script = new Script("room" + roomNumber + ".asc", "// Room script file", false);

            for (int i = 0; i < MAX_HOTSPOTS; i++)
            {
                RoomHotspot hotspot = new RoomHotspot(this);
                hotspot.ID = i;
                if (i == 0) hotspot.Description = "No hotspot";
                else hotspot.Description = "Hotspot " + i;
                _hotspots.Add(hotspot);
            }

            for (int i = 0; i < MAX_WALKABLE_AREAS; i++)
            {
                RoomWalkableArea area = new RoomWalkableArea();
                area.ID = i;
                _walkableAreas.Add(area);
            }

            for (int i = 0; i < MAX_WALK_BEHINDS; i++)
            {
                RoomWalkBehind area = new RoomWalkBehind();
                area.ID = i;
                _walkBehinds.Add(area);
            }

            for (int i = 0; i < MAX_REGIONS; i++)
            {
                RoomRegion area = new RoomRegion();
                area.ID = i;
                _regions.Add(area);
            }
        }
Beispiel #31
0
 public ScriptExecutable BlockExecutable;            //for内容
 public CodeFor(Script script)
 {
     m_Script = script;
 }
Beispiel #32
0
 static PeerBanningTest()
 {
     MinerScriptPubKey = new Key().ScriptPubKey;
 }
Beispiel #33
0
 public abstract BlockTemplate Build(ChainedHeader chainTip, Script scriptPubKey);
Beispiel #34
0
        /// <summary>
        /// Constructs a block template which will be passed to consensus.
        /// </summary>
        /// <param name="chainTip">Tip of the chain that this instance will work with without touching any shared chain resources.</param>
        /// <param name="scriptPubKey">Script that explains what conditions must be met to claim ownership of a coin.</param>
        /// <returns>The contructed <see cref="Miner.BlockTemplate"/>.</returns>
        protected void OnBuild(ChainedHeader chainTip, Script scriptPubKey)
        {
            this.Configure();

            this.ChainTip = chainTip;

            this.block        = this.BlockTemplate.Block;
            this.scriptPubKey = scriptPubKey;

            this.CreateCoinbase();
            this.ComputeBlockVersion();

            // TODO: MineBlocksOnDemand
            // -regtest only: allow overriding block.nVersion with
            // -blockversion=N to test forking scenarios
            //if (this.network. chainparams.MineBlocksOnDemand())
            //    pblock->nVersion = GetArg("-blockversion", pblock->nVersion);

            this.MedianTimePast = Utils.DateTimeToUnixTime(this.ChainTip.GetMedianTimePast());
            this.LockTimeCutoff = PowConsensusValidator.StandardLocktimeVerifyFlags.HasFlag(Transaction.LockTimeFlags.MedianTimePast)
                ? this.MedianTimePast
                : this.block.Header.Time;

            // TODO: Implement Witness Code
            // Decide whether to include witness transactions
            // This is only needed in case the witness softfork activation is reverted
            // (which would require a very deep reorganization) or when
            // -promiscuousmempoolflags is used.
            // TODO: replace this with a call to main to assess validity of a mempool
            // transaction (which in most cases can be a no-op).
            this.IncludeWitness = false; //IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;

            // add transactions from the mempool
            int nPackagesSelected;
            int nDescendantsUpdated;

            this.AddTransactions(out nPackagesSelected, out nDescendantsUpdated);

            this.LastBlockTx     = this.BlockTx;
            this.LastBlockSize   = this.BlockSize;
            this.LastBlockWeight = this.BlockWeight;

            // TODO: Implement Witness Code
            // pblocktemplate->CoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
            this.BlockTemplate.VTxFees[0]  = -this.fees;
            this.coinbase.Outputs[0].Value = this.fees + this.ConsensusLoop.Validator.GetProofOfWorkReward(this.height);
            this.BlockTemplate.TotalFee    = this.fees;

            int nSerializeSize = this.block.GetSerializedSize();

            this.logger.LogDebug("Serialized size is {0} bytes, block weight is {1}, number of txs is {2}, tx fees are {3}, number of sigops is {4}.", nSerializeSize, this.ConsensusLoop.Validator.GetBlockWeight(this.block), this.BlockTx, this.fees, this.BlockSigOpsCost);

            this.OnUpdateHeaders();

            //pblocktemplate->TxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);

            this.OnTestBlockValidity();

            //int64_t nTime2 = GetTimeMicros();

            //LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
        }
 /// <inheritdoc/>
 public BlockTemplate BuildPosBlock(ChainedHeader chainTip, Script script)
 {
     return(this.posBlockDefinition.Build(chainTip, script));
 }
Beispiel #36
0
 public PaymentOutput(Money amount, Script script)
 {
     Amount = amount;
     Script = script;
 }
Beispiel #37
0
        private Script BuildScript(FileInfo file, BuildOptions buildOptions)
        {
            Script script = (Script)null;

            Global.ToolWindowManager.ClearErrorList();
            Console.WriteLine(string.Format("Building script {0}...", file.Name));
            Global.EditorManager.Save(file);
            CompilingServices compilingServices = new CompilingServices(CodeHelper.GetCodeLang(file));

            if (buildOptions != null)
            {
                foreach (BuildReference buildReference in buildOptions.GetReferences())
                {
                    if (buildReference.Valid)
                    {
                        compilingServices.AddReference(buildReference.Path);
                    }
                }
            }
            compilingServices.AddFile(file.FullName);
            CompilerResults compilerResults = compilingServices.Compile();

            if (compilerResults.Errors.HasErrors)
            {
                Console.WriteLine("Built with errors.");
                this.OnBuildErrors(compilerResults.Errors);
                return(null);
            }
            else
            {
                if (compilerResults.Errors.HasWarnings)
                {
                    Console.WriteLine("Built with warnings.");
                    this.OnBuildErrors(compilerResults.Errors);
                }
                System.Type type1 = (System.Type)null;
                foreach (System.Type type2 in compilerResults.CompiledAssembly.GetTypes())
                {
                    if (type2.IsSubclassOf(typeof(Script)))
                    {
                        type1 = type2;
                        break;
                    }
                }
                if (type1 == null)
                {
                    Console.WriteLine("Built with errors.");
                    this.OnBuildErrors(new CompilerErrorCollection()
                    {
                        new CompilerError(file.FullName, 1, 1, "", "Script is not found, make sure that the code contains a class derived from the OpenQuant.API.Script class")
                    });
                }
                else
                {
                    script = Activator.CreateInstance(type1, false) as Script;
                    if (Application.OpenForms.Count > 0)
                    {
                        typeof(Script).GetField("mainForm", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField).SetValue((object)script, (object)Application.OpenForms[0]);
                    }
                    ++this.scriptID;
                    Console.WriteLine("Build succeeded.");
                }
                return(script);
            }
        }
Beispiel #38
0
        public static void PlayAnimation(Ped mPed, string animSet, string animName, float speed, int duration, [MarshalAs(UnmanagedType.U1)] bool lastAnimation, float playbackRate)
        {
            var           inputArgumentArray1 = new InputArgument[1];
            InputArgument inputArgument1      = new InputArgument(animSet);

            inputArgumentArray1[0] = inputArgument1;
            Function.Call(Hash.REQUEST_ANIM_DICT, inputArgumentArray1);
            DateTime dateTime = DateTime.Now + new TimeSpan(0, 0, 0, 0, 1000);

            InputArgument[] inputArgumentArray2 = new InputArgument[1];
            InputArgument   inputArgument2      = new InputArgument(animSet);

            inputArgumentArray2[0] = inputArgument2;
            if (!Function.Call <bool>(Hash.HAS_ANIM_DICT_LOADED, inputArgumentArray2))
            {
                InputArgument[] inputArgumentArray3;
                do
                {
                    Script.Yield();
                    if (!(DateTime.Now >= dateTime))
                    {
                        inputArgumentArray3 = new InputArgument[1];
                        InputArgument inputArgument3 = new InputArgument(animSet);
                        inputArgumentArray3[0] = inputArgument3;
                    }
                    else
                    {
                        goto label_4;
                    }
                }while (!Function.Call <bool>(Hash.HAS_ANIM_DICT_LOADED, inputArgumentArray3));
                goto label_3;
label_4:
                return;
            }
label_3:
            var inputArgumentArray4 = new InputArgument[11];
            var inputArgument4 = new InputArgument(mPed.Handle);

            inputArgumentArray4[0] = inputArgument4;
            var inputArgument5 = new InputArgument(animSet);

            inputArgumentArray4[1] = inputArgument5;
            var inputArgument6 = new InputArgument(animName);

            inputArgumentArray4[2] = inputArgument6;
            var inputArgument7 = new InputArgument(speed);

            inputArgumentArray4[3] = inputArgument7;
            var inputArgument8 = new InputArgument(-8.0f);

            inputArgumentArray4[4] = inputArgument8;
            var inputArgument9 = new InputArgument(duration);

            inputArgumentArray4[5] = inputArgument9;
            var inputArgument10 = new InputArgument(48);

            inputArgumentArray4[6] = inputArgument10;
            InputArgument inputArgument11 = new InputArgument(playbackRate);

            inputArgumentArray4[7] = inputArgument11;
            InputArgument inputArgument12 = new InputArgument(0);

            inputArgumentArray4[8] = inputArgument12;
            InputArgument inputArgument13 = new InputArgument(0);

            inputArgumentArray4[9] = inputArgument13;
            InputArgument inputArgument14 = new InputArgument(0);

            inputArgumentArray4[10] = inputArgument14;
            Function.Call(Hash.TASK_PLAY_ANIM, inputArgumentArray4);
        }
        public void OnTick(object o, EventArgs e)
        {
            if (server.Poll(10, SelectMode.SelectRead) && connection == null)
            {
                connection = server.Accept();
                if (notificationsEnabled)
                {
                    UI.Notify("CONNECTED");
                }
                connection.Blocking = false;
            }
            handlePipeInput();
            if (!enabled)
            {
                return;
            }

            //Array values = Enum.GetValues(typeof(Weather));


            switch (checkStatus())
            {
            case GameStatus.NeedReload:
                //TODO: need to get a new session and run?
                StopRun();
                runTask?.Wait();
                runTask = StartRun();
                //StopSession();
                //Autostart();
                if (notificationsEnabled)
                {
                    UI.Notify("need reload game");
                }
                Script.Wait(100);
                ReloadGame();
                break;

            case GameStatus.NeedStart:
                //TODO do the autostart manually or automatically?
                //Autostart();
                // use reloading temporarily
                StopRun();

                ReloadGame();
                Script.Wait(100);
                runTask?.Wait();
                runTask = StartRun();
                //Autostart();
                break;

            case GameStatus.NoActionNeeded:
                break;
            }
            if (!runTask.IsCompleted)
            {
                return;
            }
            if (!postgresTask.IsCompleted)
            {
                return;
            }

            List <byte[]> colors = new List <byte[]>();

            Game.Pause(true);
            Script.Wait(500);
            GTAData dat = GTAData.DumpData(Game.GameTime + ".tiff", new List <Weather>());

            if (dat == null)
            {
                return;
            }
            var thisframe = VisionNative.GetCurrentTime();
            var depth     = VisionNative.GetDepthBuffer();
            var stencil   = VisionNative.GetStencilBuffer();

            colors.Add(VisionNative.GetColorBuffer());

            /*
             * foreach (var wea in wantedWeather) {
             *  World.TransitionToWeather(wea, 0.0f);
             *  Script.Wait(1);
             *  colors.Add(VisionNative.GetColorBuffer());
             * }*/
            Game.Pause(false);

            /*
             * if (World.Weather != Weather.Snowing)
             * {
             *  World.TransitionToWeather(Weather.Snowing, 1);
             *
             * }*/
            var colorframe    = VisionNative.GetLastColorTime();
            var depthframe    = VisionNative.GetLastConstantTime();
            var constantframe = VisionNative.GetLastConstantTime();

            //UI.Notify("DIFF: " + (colorframe - depthframe) + " FRAMETIME: " + (1 / Game.FPS) * 1000);
            if (notificationsEnabled)
            {
                UI.Notify(colors[0].Length.ToString());
            }
            if (depth == null || stencil == null)
            {
                if (notificationsEnabled)
                {
                    UI.Notify("No DEPTH");
                }
                return;
            }

            /*
             * this code checks to see if there's drift
             * it's kinda pointless because we end up "straddling" a present call,
             * so the capture time difference can be ~1/4th of a frame but still the
             * depth/stencil and color buffers are one frame offset from each other
             * if (Math.Abs(thisframe - colorframe) < 60 && Math.Abs(colorframe - depthframe) < 60 &&
             *  Math.Abs(colorframe - constantframe) < 60)
             * {
             *
             *
             *
             *
             *
             *  PostgresExport.SaveSnapshot(dat, run.guid);
             * }
             */
            ImageUtils.WaitForProcessing();
            ImageUtils.StartUploadTask(archive, Game.GameTime.ToString(), Game.ScreenResolution.Width,
                                       Game.ScreenResolution.Height, colors, depth, stencil);

            PostgresExport.SaveSnapshot(dat, run.guid);
            S3Stream.Flush();
            if ((Int64)S3Stream.Length > (Int64)2048 * (Int64)1024 * (Int64)1024)
            {
                ImageUtils.WaitForProcessing();
                StopRun();
                runTask?.Wait();
                runTask = StartRun();
            }
        }
Beispiel #40
0
        /// <summary>
        /// Parses <see cref="XmlScript.ConditionallyInstalledFileSets"/>.
        /// </summary>
        /// <returns>A <see cref="Script"/>'s <see cref="XmlScript.ConditionallyInstalledFileSets"/>, based on the XML,
        /// or <c>null</c> if the script doesn't describe any <see cref="XmlScript.ConditionallyInstalledFileSets"/>.</returns>
        protected override List <ConditionallyInstalledFileSet> GetConditionallyInstalledFileSets()
        {
            IEnumerable <XElement> xeeRequiredInstallFiles = Script.XPathSelectElements("conditionalFileInstalls/patterns/*");

            return(ReadConditionalFileInstallInfo(xeeRequiredInstallFiles));
        }
Beispiel #41
0
        public static WrappedValue <TProps> WrapProps <TProps>(TProps propsIfAny)
        {
            // Try to extract a Key value from the props - it might be a simple "key" value or it might be a property with a "getKey" function or it
            // might be absent altogether
            Union <string, int> keyIfAny = null;
            Action <object>     refIfAny = null;

            if (propsIfAny != null)
            {
                // Pre-16, Bridge used to default to camel-casing property names and so a "Key" property would be named "key" and it would have a getter method
                // specified for it (it was possible to override these behaviours using PreserveMemberCase and [Name], [Template] or [FieldProperty] attributes)
                // but 16 has changed things such that the name casing is not changed (by default - this may also be altered using the "conventions" options)
                // and so we can't presume that a "Key" property will result in a JavaScript "key" property (or a "getKey" method).
                Script.Write(@"
					if (propsIfAny.key || (propsIfAny.key === 0)) { // Ensure that a zero key is not considered ""no-key-defined""
						keyIfAny = propsIfAny.key;
					}
					else if (propsIfAny.Key || (propsIfAny.Key === 0)) { // Ensure that a zero key is not considered ""no-key-defined""
						keyIfAny = propsIfAny.Key;
					}
					else if (propsIfAny.getKey && (typeof(propsIfAny.getKey) == ""function"")) {
						var keyIfAnyFromPropertyGetter = propsIfAny.getKey();
						if (keyIfAnyFromPropertyGetter || (keyIfAnyFromPropertyGetter === 0)) { // Ensure that a zero key is not considered ""no-key-defined""
							keyIfAny = keyIfAnyFromPropertyGetter;
						}
						else {
							keyIfAny = undefined;
						}
					}
					else {
						keyIfAny = undefined;
					}

					if (typeof(propsIfAny.ref) === ""function"") {
						refIfAny = propsIfAny.ref;
					}
					else if (typeof(propsIfAny.Ref) === ""function"") {
						refIfAny = propsIfAny.Ref;
					}
					else if (typeof(propsIfAny.getRef) === ""function"") {
						var refIfAnyFromPropertyGetter = propsIfAny.getRef();
						if (typeof(refIfAnyFromPropertyGetter) === ""function"") {
							refIfAny = refIfAnyFromPropertyGetter;
						}
						else {
							refIfAny = undefined;
						}
					}
					else {
						refIfAny = undefined;
					}
				"                );
            }

            // With the changes in React 15.0.0 (vs 0.14.7), a null Key value will be interpreted AS a key (and will either be ".$null" or ".$undefined")
            // when really we want a null Key to mean NO KEY. Possibly related to https://github.com/facebook/react/issues/2386, but I would have expected
            // to have seen this issue in 0.14 if it was that. The workaround is to return a type of "wrapped props" that doesn't even have a Key property
            // on it if there is no key value to use.
            var wrappedProps = new WrappedValue <TProps> {
                Value = propsIfAny
            };

            if (Script.Write <bool>("(typeof({0}) !== 'undefined')", keyIfAny))
            {
                Script.Write("{0}.key = {1}", wrappedProps, keyIfAny);
            }
            if (Script.Write <bool>("(typeof({0}) !== 'undefined')", refIfAny))
            {
                Script.Write("{0}.ref = {1}", wrappedProps, refIfAny);
            }
            return(wrappedProps);
        }
        public void OnKeyDown(object o, KeyEventArgs k)
        {
            System.IO.File.AppendAllText(logFilePath, "VisionExport OnKeyDown called.\n");

            if (k.KeyCode == Keys.Z)
            {
                if (notificationsEnabled)
                {
                    UI.Notify("Notifications Disabled");
                    notificationsEnabled = false;
                }
                else
                {
                    UI.Notify("Notifications Enabled");
                    notificationsEnabled = true;
                }
            }
            if (k.KeyCode == Keys.PageUp)
            {
                postgresTask?.Wait();
                postgresTask = StartSession();
                runTask?.Wait();
                runTask = StartRun();
                if (notificationsEnabled)
                {
                    UI.Notify("GTA Vision Enabled");
                }
            }
            if (k.KeyCode == Keys.PageDown)
            {
                StopRun();
                StopSession();
                if (notificationsEnabled)
                {
                    UI.Notify("GTA Vision Disabled");
                }
            }
            if (k.KeyCode == Keys.H) // temp modification
            {
                EnterVehicle();
                if (notificationsEnabled)
                {
                    UI.Notify("Trying to enter vehicle");
                }
                ToggleNavigation();
            }
            if (k.KeyCode == Keys.Y) // temp modification
            {
                ReloadGame();
            }
            if (k.KeyCode == Keys.U) // temp modification
            {
                var settings = ScriptSettings.Load("GTAVisionExport.xml");
                var loc      = AppDomain.CurrentDomain.BaseDirectory;

                //UI.Notify(ConfigurationManager.AppSettings["database_connection"]);
                var str = settings.GetValue("", "ConnectionString");
                if (notificationsEnabled)
                {
                    UI.Notify(loc);
                }
            }
            if (k.KeyCode == Keys.G) // temp modification
            {
                /*
                 * IsGamePaused = true;
                 * Game.Pause(true);
                 * Script.Wait(500);
                 * TraverseWeather();
                 * Script.Wait(500);
                 * IsGamePaused = false;
                 * Game.Pause(false);
                 */
                var data = GTAData.DumpData(Game.GameTime + ".tiff", new List <Weather>(wantedWeather));

                string path = @"C:\Users\NGV-02\Documents\Data\trymatrix.txt";
                // This text is added only once to the file.
                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter file = File.CreateText(path))
                    {
                        file.WriteLine("cam direction file");
                        file.WriteLine("direction:");
                        file.WriteLine(GameplayCamera.Direction.X.ToString() + ' ' + GameplayCamera.Direction.Y.ToString() + ' ' + GameplayCamera.Direction.Z.ToString());
                        file.WriteLine("Dot Product:");
                        file.WriteLine(Vector3.Dot(GameplayCamera.Direction, GameplayCamera.Rotation));
                        file.WriteLine("position:");
                        file.WriteLine(GameplayCamera.Position.X.ToString() + ' ' + GameplayCamera.Position.Y.ToString() + ' ' + GameplayCamera.Position.Z.ToString());
                        file.WriteLine("rotation:");
                        file.WriteLine(GameplayCamera.Rotation.X.ToString() + ' ' + GameplayCamera.Rotation.Y.ToString() + ' ' + GameplayCamera.Rotation.Z.ToString());
                        file.WriteLine("relative heading:");
                        file.WriteLine(GameplayCamera.RelativeHeading.ToString());
                        file.WriteLine("relative pitch:");
                        file.WriteLine(GameplayCamera.RelativePitch.ToString());
                        file.WriteLine("fov:");
                        file.WriteLine(GameplayCamera.FieldOfView.ToString());
                    }
                }
            }

            if (k.KeyCode == Keys.T) // temp modification
            {
                World.Weather = Weather.Raining;
                /* set it between 0 = stop, 1 = heavy rain. set it too high will lead to sloppy ground */
                Function.Call(GTA.Native.Hash._SET_RAIN_FX_INTENSITY, 0.5f);
                var test = Function.Call <float>(GTA.Native.Hash.GET_RAIN_LEVEL);
                if (notificationsEnabled)
                {
                    UI.Notify("" + test);
                }
                World.CurrentDayTime = new TimeSpan(12, 0, 0);
                //Script.Wait(5000);
            }

            if (k.KeyCode == Keys.N)
            {
                /*
                 * //var color = VisionNative.GetColorBuffer();
                 *
                 * List<byte[]> colors = new List<byte[]>();
                 * Game.Pause(true);
                 * Script.Wait(1);
                 * var depth = VisionNative.GetDepthBuffer();
                 * var stencil = VisionNative.GetStencilBuffer();
                 * foreach (var wea in wantedWeather) {
                 *  World.TransitionToWeather(wea, 0.0f);
                 *  Script.Wait(1);
                 *  colors.Add(VisionNative.GetColorBuffer());
                 * }
                 * Game.Pause(false);
                 * if (depth != null)
                 * {
                 *  var res = Game.ScreenResolution;
                 *  var t = Tiff.Open(Path.Combine(dataPath, "test.tiff"), "w");
                 *  ImageUtils.WriteToTiff(t, res.Width, res.Height, colors, depth, stencil);
                 *  t.Close();
                 *  UI.Notify(GameplayCamera.FieldOfView.ToString());
                 * }
                 * else
                 * {
                 *  UI.Notify("No Depth Data quite yet");
                 * }
                 * //UI.Notify((connection != null && connection.Connected).ToString());
                 */
                //var color = VisionNative.GetColorBuffer();
                for (int i = 0; i < 100; i++)
                {
                    List <byte[]> colors = new List <byte[]>();
                    Game.Pause(true);
                    var depth   = VisionNative.GetDepthBuffer();
                    var stencil = VisionNative.GetStencilBuffer();
                    foreach (var wea in wantedWeather)
                    {
                        World.TransitionToWeather(wea, 0.0f);
                        Script.Wait(1);
                        colors.Add(VisionNative.GetColorBuffer());
                    }

                    Game.Pause(false);
                    var res = Game.ScreenResolution;
                    var t   = Tiff.Open(Path.Combine(dataPath, "info" + i.ToString() + ".tiff"), "w");
                    ImageUtils.WriteToTiff(t, res.Width, res.Height, colors, depth, stencil);
                    t.Close();
                    if (notificationsEnabled)
                    {
                        UI.Notify(GameplayCamera.FieldOfView.ToString());
                    }
                    //UI.Notify((connection != null && connection.Connected).ToString());


                    var data = GTAData.DumpData(Game.GameTime + ".dat", new List <Weather>(wantedWeather));

                    string path = @"C:\Users\NGV-02\Documents\Data\info.txt";
                    // This text is added only once to the file.
                    if (!File.Exists(path))
                    {
                        // Create a file to write to.
                        using (StreamWriter file = File.CreateText(path))
                        {
                            file.WriteLine("cam direction & Ped pos file");
                        }
                    }

                    using (StreamWriter file = File.AppendText(path))
                    {
                        file.WriteLine("==============info" + i.ToString() + ".tiff 's metadata=======================");
                        file.WriteLine("cam pos");
                        file.WriteLine(GameplayCamera.Position.X.ToString());
                        file.WriteLine(GameplayCamera.Position.Y.ToString());
                        file.WriteLine(GameplayCamera.Position.Z.ToString());
                        file.WriteLine("cam direction");
                        file.WriteLine(GameplayCamera.Direction.X.ToString());
                        file.WriteLine(GameplayCamera.Direction.Y.ToString());
                        file.WriteLine(GameplayCamera.Direction.Z.ToString());
                        file.WriteLine("character");
                        file.WriteLine(data.Pos.X.ToString());
                        file.WriteLine(data.Pos.Y.ToString());
                        file.WriteLine(data.Pos.Z.ToString());
                        foreach (var detection in data.Detections)
                        {
                            file.WriteLine(detection.Type.ToString());
                            file.WriteLine(detection.Pos.X.ToString());
                            file.WriteLine(detection.Pos.Y.ToString());
                            file.WriteLine(detection.Pos.Z.ToString());
                        }
                    }

                    Script.Wait(200);
                }
            }
            if (k.KeyCode == Keys.I)
            {
                var info = new GTAVisionUtils.InstanceData();
                if (notificationsEnabled)
                {
                    UI.Notify(info.type);
                }
                if (notificationsEnabled)
                {
                    UI.Notify(info.publichostname);
                }
            }
        }
        private static async Task <BlockTemplate> MineBlockAsync(TestChainContext testChainContext, Script scriptPubKey, TxMempool mempool,
                                                                 MempoolSchedulerLock mempoolLock, bool getMutatedBlock = false)
        {
            BlockTemplate newBlock = CreateBlockTemplate(testChainContext, scriptPubKey, mempool, mempoolLock);

            if (getMutatedBlock)
            {
                BuildMutatedBlock(newBlock);
            }

            newBlock.Block.UpdateMerkleRoot();

            TryFindNonceForProofOfWork(testChainContext, newBlock);

            if (!getMutatedBlock)
            {
                await ValidateBlock(testChainContext, newBlock);
            }
            else
            {
                CheckBlockIsMutated(newBlock);
            }

            return(newBlock);
        }
Beispiel #44
0
 public static TProps UnWrapValueIfDefined <TProps>(WrappedValue <TProps> wrappedValueIfAny)
 {
     return(Script.Write <TProps>("{0} ? {0}.value : null", wrappedValueIfAny));
 }
 public static async Task <List <Block> > MineBlocksAsync(TestChainContext testChainContext,
                                                          int count, Script receiver)
 {
     return(await MineBlocksAsync(testChainContext, count, receiver, false));
 }
        private static BlockTemplate CreateBlockTemplate(TestChainContext testChainContext, Script scriptPubKey,
                                                         TxMempool mempool, MempoolSchedulerLock mempoolLock)
        {
            PowBlockDefinition blockAssembler = new PowBlockDefinition(testChainContext.Consensus,
                                                                       testChainContext.DateTimeProvider, testChainContext.LoggerFactory as LoggerFactory, mempool, mempoolLock,
                                                                       new MinerSettings(testChainContext.NodeSettings), testChainContext.Network, testChainContext.ConsensusRules);

            BlockTemplate newBlock = blockAssembler.Build(testChainContext.ChainIndexer.Tip, scriptPubKey);

            int         nHeight    = testChainContext.ChainIndexer.Tip.Height + 1; // Height first in coinbase required for block.version=2
            Transaction txCoinbase = newBlock.Block.Transactions[0];

            txCoinbase.Inputs[0] = TxIn.CreateCoinbase(nHeight);
            return(newBlock);
        }
Beispiel #47
0
        public void PubKeyBelongsSuccess()
        {
            Script walletScriptPubKey = _wallet.GetNextPubKey().ScriptPubKey;

            Assert.True(_wallet.PubKeyBelongs(walletScriptPubKey));
        }
        /// <summary>
        /// Mine new blocks in to the consensus database and the chain.
        /// </summary>
        private static async Task <List <Block> > MineBlocksAsync(TestChainContext testChainContext, int count, Script receiver, bool mutateLastBlock)
        {
            var blockPolicyEstimator = new BlockPolicyEstimator(new MempoolSettings(testChainContext.NodeSettings), testChainContext.LoggerFactory, testChainContext.NodeSettings);
            var mempool     = new TxMempool(testChainContext.DateTimeProvider, blockPolicyEstimator, testChainContext.LoggerFactory, testChainContext.NodeSettings);
            var mempoolLock = new MempoolSchedulerLock();

            // Simple block creation, nothing special yet:
            var blocks = new List <Block>();

            for (int i = 0; i < count; i++)
            {
                BlockTemplate newBlock = await MineBlockAsync(testChainContext, receiver, mempool, mempoolLock, mutateLastBlock&& i == count - 1);

                blocks.Add(newBlock.Block);
            }

            return(blocks);
        }
Beispiel #49
0
        public PropertyGrid(jQueryObject div, PropertyGridOptions opt)
            : base(div, opt)
        {
            if (!Script.IsValue(opt.Mode))
            {
                opt.Mode = PropertyGridMode.Insert;
            }

            items = options.Items ?? new List <PropertyItem>();

            div.AddClass("s-PropertyGrid");

            editors = new List <Widget>();

            var categoryIndexes = new JsDictionary <string, int>();

            var categoriesDiv = div;

            if (options.UseCategories)
            {
                var linkContainer = J("<div/>")
                                    .AddClass("category-links");

                categoryIndexes = CreateCategoryLinks(linkContainer, items);

                if (categoryIndexes.Count > 1)
                {
                    linkContainer.AppendTo(div);
                }
                else
                {
                    linkContainer.Find("a.category-link").Unbind("click", CategoryLinkClick).Remove();
                }

                categoriesDiv = J("<div/>")
                                .AddClass("categories")
                                .AppendTo(div);
            }

            var fieldContainer = categoriesDiv;

            string priorCategory = null;

            for (int i = 0; i < items.Count; i++)
            {
                var item = items[i];
                if (options.UseCategories &&
                    priorCategory != item.Category)
                {
                    var categoryDiv = CreateCategoryDiv(categoriesDiv, categoryIndexes, item.Category);

                    if (priorCategory == null)
                    {
                        categoryDiv.AddClass("first-category");
                    }

                    priorCategory  = item.Category;
                    fieldContainer = categoryDiv;
                }

                var editor = CreateField(fieldContainer, item);

                editors[i] = editor;
            }

            UpdateReadOnly();
        }
 public static async Task <List <Block> > MineBlocksWithLastBlockMutatedAsync(TestChainContext testChainContext,
                                                                              int count, Script receiver)
 {
     return(await MineBlocksAsync(testChainContext, count, receiver, true));
 }
Beispiel #51
0
        public override void Insertar()
        {
            try
            {
                Conexion.Open();

                //Crea el Script en base al atributo que no sea nulo
                if (!(RifCliente == null))
                {
                    string Comando = "INSERT INTO telefono (te_codigo_pais, te_codigo_area, te_numero, te_tipo, cliente_cl_rif) " +
                                     "VALUES (@pais, @area, @numero, @tipo, @cliente)";
                    Script = new NpgsqlCommand(Comando, Conexion);

                    Script.Parameters.AddWithValue("pais", Numero[NumeroTelefono.Pais]);
                    Script.Parameters.AddWithValue("area", Numero[NumeroTelefono.Area]);
                    Script.Parameters.AddWithValue("numero", Numero[NumeroTelefono.Numero]);
                    Script.Parameters.AddWithValue("tipo", Tipo);
                    Script.Parameters.AddWithValue("cliente", RifCliente);
                }
                else if (!(CodigoPersonaContacto == 0))
                {
                    string Comando = "INSERT INTO telefono (te_codigo_pais, te_codigo_area, te_numero, te_tipo, persona_contacto_pc_codigo) " +
                                     "VALUES (@pais, @area, @numero, @tipo, @persona)";
                    Script = new NpgsqlCommand(Comando, Conexion);

                    Script.Parameters.AddWithValue("pais", Numero[NumeroTelefono.Pais]);
                    Script.Parameters.AddWithValue("area", Numero[NumeroTelefono.Area]);
                    Script.Parameters.AddWithValue("numero", Numero[NumeroTelefono.Numero]);
                    Script.Parameters.AddWithValue("tipo", Tipo);
                    Script.Parameters.AddWithValue("persona", CodigoPersonaContacto);
                }
                else if (!(RifProveedor == null))
                {
                    string Comando = "INSERT INTO telefono (te_codigo_pais, te_codigo_area, te_numero, te_tipo, proveedor_pr_rif) " +
                                     "VALUES (@pais, @area, @numero, @tipo, @proveedor)";
                    Script = new NpgsqlCommand(Comando, Conexion);

                    Script.Parameters.AddWithValue("pais", Numero[NumeroTelefono.Pais]);
                    Script.Parameters.AddWithValue("area", Numero[NumeroTelefono.Area]);
                    Script.Parameters.AddWithValue("numero", Numero[NumeroTelefono.Numero]);
                    Script.Parameters.AddWithValue("tipo", Tipo);
                    Script.Parameters.AddWithValue("proveedor", RifProveedor);
                }
                else if (!(CodigoEmpleado == 0))
                {
                    string Comando = "INSERT INTO telefono (te_codigo_pais, te_codigo_area, te_numero, te_tipo, empleado_em_codigo) " +
                                     "VALUES (@pais, @area, @numero, @tipo, @empleado)";
                    Script = new NpgsqlCommand(Comando, Conexion);

                    Script.Parameters.AddWithValue("pais", Numero[NumeroTelefono.Pais]);
                    Script.Parameters.AddWithValue("area", Numero[NumeroTelefono.Area]);
                    Script.Parameters.AddWithValue("numero", Numero[NumeroTelefono.Numero]);
                    Script.Parameters.AddWithValue("tipo", Tipo);
                    Script.Parameters.AddWithValue("empleado", CodigoEmpleado);
                }
                else
                {
                    throw new Exception("telefono no valido");
                }

                Script.Prepare();

                Script.ExecuteNonQuery();

                Conexion.Close();
            }
            catch (Exception e)
            {
                Conexion.Close();
            }
        }
Beispiel #52
0
        public void Load(dynamic source)
        {
            for (var i = 0; i < editors.Count; i++)
            {
                var item   = items[i];
                var editor = editors[i];

                if (Mode == PropertyGridMode.Insert &&
                    !Script.IsNullOrUndefined(item.DefaultValue) &&
                    Script.IsUndefined(source[item.Name]))
                {
                    source[item.Name] = item.DefaultValue;
                }

                var setEditValue = editor as ISetEditValue;
                if (setEditValue != null)
                {
                    setEditValue.SetEditValue(source, item);
                }

                var stringValue = editor as IStringValue;
                if (stringValue != null)
                {
                    var value = source[item.Name];
                    if (value != null)
                    {
                        value = value.toString();
                    }
                    stringValue.Value = value;
                }
                else
                {
                    var booleanValue = editor as IBooleanValue;
                    if (booleanValue != null)
                    {
                        object value = source[item.Name];
                        if (Script.TypeOf(value) == "number")
                        {
                            booleanValue.Value = IdExtensions.IsPositiveId(value.As <Int64>());
                        }
                        else
                        {
                            booleanValue.Value = Q.IsTrue(value);
                        }
                    }
                    else
                    {
                        var doubleValue = editor as IDoubleValue;
                        if (doubleValue != null)
                        {
                            var d = source[item.Name];
                            if (d == null || (d is string && Q.IsTrimmedEmpty(d)))
                            {
                                doubleValue.Value = null;
                            }
                            else if (d is string)
                            {
                                doubleValue.Value = Q.ParseDecimal(d);
                            }
                            else if (d is Boolean)
                            {
                                doubleValue.Value = (Boolean)d ? 1 : 0;
                            }
                            else
                            {
                                doubleValue.Value = d;
                            }
                        }
                        else if (editor.Element.Is(":input"))
                        {
                            var v = source[item.Name];
                            if (!Script.IsValue(v))
                            {
                                editor.Element.Value("");
                            }
                            else
                            {
                                editor.Element.Value(((object)v).As <string>());
                            }
                        }
                    }
                }
            }
        }
 protected override Result ParseCommandSpecific(Script script, string personalityName, string line) => Result.Ok();
Beispiel #54
0
        private Widget CreateField(jQueryObject container, PropertyItem item)
        {
            var fieldDiv = J("<div/>")
                           .AddClass("field")
                           .AddClass(item.Name)
                           .Data("PropertyItem", item)
                           .AppendTo(container);

            if (!String.IsNullOrEmpty(item.CssClass))
            {
                fieldDiv.AddClass(item.CssClass);
            }

            string editorId = options.IdPrefix + item.Name;

            var label = J("<label/>")
                        .AddClass("caption")
                        .Attribute("for", editorId)
                        .Attribute("title", item.Hint ?? item.Title ?? "")
                        .Html(item.Title)
                        .AppendTo(fieldDiv);

            if (item.Required)
            {
                J("<sup>*</sup>")
                .Attribute("title", "Bu alan zorunludur")
                .PrependTo(label);
            }

            var    editorType  = GetEditorType(item.EditorType);
            var    elementAttr = editorType.GetCustomAttributes(typeof(ElementAttribute), true);
            string elementHtml = (elementAttr.Length > 0) ? elementAttr[0].As <ElementAttribute>().Html : "<input/>";

            var element = J(elementHtml)
                          .AddClass("editor")
                          .AddClass("flexify")
                          .Attribute("id", editorId)
                          .AppendTo(fieldDiv);

            if (element.Is(":input"))
            {
                element.Attribute("name", item.Name ?? "");
            }

            object editorParams = item.EditorParams;
            Type   optionsType  = null;
            var    optionsAttr  = editorType.GetCustomAttributes(typeof(OptionsTypeAttribute), true);

            if (optionsAttr != null && optionsAttr.Length > 0)
            {
                optionsType = optionsAttr[0].As <OptionsTypeAttribute>().OptionsType;
            }

            if (optionsType != null)
            {
                editorParams = jQuery.ExtendObject(Activator.CreateInstance(optionsType), item.EditorParams);
            }

            Widget editor = (Widget)(Activator.CreateInstance(editorType, element, editorParams));

            if (Script.IsValue(item.MaxLength))
            {
                SetMaxLength(editor, item.MaxLength.Value);
            }

            J("<div/>")
            .AddClass("vx")
            .AppendTo(fieldDiv);

            J("<div/>")
            .AddClass("clear")
            .AppendTo(fieldDiv);

            return(editor);
        }
Beispiel #55
0
 internal DebugService(Script script, Processor processor)
 {
     OwnerScript = script;
     m_Processor = processor;
 }
        protected override async Task LoadContent()
        {
            await base.LoadContent();

            CreatePipeline(true);

            IsMouseVisible = true;

            //Input.ActivatedGestures.Add(new GestureConfigDrag());

            // Creates all primitives
            //                                     type           pos     axis
            var primitives = new List<Tuple<GeometricPrimitive, Vector3, Vector3>>
                             {
                                 Tuple.Create(GeometricPrimitive.Cube.New(GraphicsDevice), 2 * Vector3.UnitX, new Vector3(1,1,1)),
                                 Tuple.Create(GeometricPrimitive.Teapot.New(GraphicsDevice), -2 * Vector3.UnitX, new Vector3(-1,1,1)),
                                 Tuple.Create(GeometricPrimitive.GeoSphere.New(GraphicsDevice), 2 * Vector3.UnitY, new Vector3(1,0,1)),
                                 Tuple.Create(GeometricPrimitive.Cylinder.New(GraphicsDevice), -2 * Vector3.UnitY, new Vector3(-1,-1,1)),
                                 Tuple.Create(GeometricPrimitive.Torus.New(GraphicsDevice), 2 * Vector3.UnitZ, new Vector3(1,-1,1)),
                                 Tuple.Create(GeometricPrimitive.Sphere.New(GraphicsDevice), -2 * Vector3.UnitZ, new Vector3(0,1,1)),
                             };

            primitiveEntities = new Entity[primitives.Count];
            rotationAxis = new Vector3[primitives.Count];
            var material = Asset.Load<Material>("BasicMaterial");
            for (var i =0; i < primitives.Count; ++i)
            {
                var mesh = new Mesh
                {
                    Draw = primitives[i].Item1.ToMeshDraw(),
                    MaterialIndex = 0,
                };
                mesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group1);

                var entity = new Entity
                {
                    new ModelComponent
                    {
                        Model = new Model { mesh, material }
                    },
                    new TransformationComponent { Translation = primitives[i].Item2 }
                };
                Entities.Add(entity);
                primitiveEntities[i] = entity;
                rotationAxis[i] = primitives[i].Item3;
            }

            var reflectivePrimitive = GeometricPrimitive.Sphere.New(GraphicsDevice);
            var reflectiveMesh = new Mesh
            {
                Draw = reflectivePrimitive.ToMeshDraw(),
            };
            reflectiveMesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group2);

            var reflectEntity = new Entity
            {
                new ModelComponent
                {
                    Model = new Model { reflectiveMesh }
                },
                new TransformationComponent(),
                new CubemapSourceComponent { IsDynamic = true, Size = 128 }
            };
            Entities.Add(reflectEntity);
            reflectEntity.Get<ModelComponent>().Parameters.Set(TexturingKeys.TextureCube0, reflectEntity.Get<CubemapSourceComponent>().Texture);

            var mainCameraTargetEntity = new Entity(Vector3.Zero);
            Entities.Add(mainCameraTargetEntity);
            mainCamera = new Entity
            {
                new CameraComponent
                {
                    AspectRatio = 8/4.8f,
                    FarPlane = 1000,
                    NearPlane = 1,
                    VerticalFieldOfView = 0.6f,
                    Target = mainCameraTargetEntity,
                    TargetUp = cameraUp,
                },
                new TransformationComponent
                {
                    Translation = cameraInitPos
                }
            };
            Entities.Add(mainCamera);

            RenderSystem.Pipeline.SetCamera(mainCamera.Get<CameraComponent>());

            // Add a custom script
            Script.Add(GameScript1);
        }
 public override bool CanCombineScriptSig(Script scriptPubKey, Script a, Script b)
 {
     return(PayToPubkeyHashTemplate.Instance.CheckScriptPubKey(scriptPubKey));
 }
        protected override async Task LoadContent()
        {
            CreatePipeline();

            await base.LoadContent();

            IsMouseVisible = true;
            rotateLights   = true;

            // load the model
            characterEntity = Asset.Load <Entity>("character_00");
            characterEntity.Transformation.Rotation    = Quaternion.RotationAxis(Vector3.UnitX, (float)(0.5 * Math.PI));
            characterEntity.Transformation.Translation = characterInitPos;
            Entities.Add(characterEntity);

            // create the stand
            var material    = Asset.Load <Material>("character_00_material_mc00");
            var standEntity = CreateStand(material);

            standEntity.Transformation.Translation = new Vector3(0, 0, -80);
            standEntity.Transformation.Rotation    = Quaternion.RotationAxis(Vector3.UnitX, (float)(0.5 * Math.PI));
            Entities.Add(standEntity);

            var standBorderEntity = CreateStandBorder(material);

            standBorderEntity.Transformation.Translation = new Vector3(0, 0, -80);
            standBorderEntity.Transformation.Rotation    = Quaternion.RotationAxis(Vector3.UnitX, (float)(0.5 * Math.PI));
            Entities.Add(standBorderEntity);

            // create the lights
            var directLightEntity = CreateDirectLight(new Vector3(-1, 1, -1), new Color3(1, 1, 1), 0.9f);

            directionalLight = directLightEntity.Get <LightComponent>();
            Entities.Add(directLightEntity);

            var spotLightEntity = CreateSpotLight(new Vector3(0, -500, 600), new Vector3(0, -200, 0), 15, 20, new Color3(1, 1, 1), 0.9f);

            Entities.Add(spotLightEntity);
            spotLight = spotLightEntity.Get <LightComponent>();

            var rand = new Random();

            for (var i = -800; i <= 800; i = i + 200)
            {
                for (var j = -800; j <= 800; j = j + 200)
                {
                    var position = new Vector3(i, j, (float)(rand.NextDouble() * 150));
                    var color    = new Color3((float)rand.NextDouble() + 0.3f, (float)rand.NextDouble() + 0.3f, (float)rand.NextDouble() + 0.3f);
                    var light    = CreatePointLight(position, color);
                    pointLights.Add(light.Get <LightComponent>());
                    pointLightEntities.Add(light);
                    Entities.Add(light);
                }
            }

            // set the camera
            var targetEntity = new Entity(characterInitPos);
            var cameraEntity = CreateCamera(cameraInitPos, targetEntity, (float)GraphicsDevice.BackBuffer.Width / (float)GraphicsDevice.BackBuffer.Height);

            camera = cameraEntity.Get <CameraComponent>();
            Entities.Add(cameraEntity);
            RenderSystem.Pipeline.SetCamera(camera);

            // UI
            CreateUI();

            // Add a custom script
            Script.Add(UpdateScene);
        }
 public override int EstimateScriptSigSize(Script scriptPubKey)
 {
     // return PayToPubkeyHashTemplate.Instance.GenerateScriptSig(DummySignature, DummyPubKey).Length;
     return(107);
 }
Beispiel #60
0
        public void BuildEntity(Entity entity, params object[] args)
        {
            _characterType = args.Length > 0 ? (CharacterType)args[0] : CharacterType.X;
            LoadPlayerDataFile();

            entity.AddComponent(BuildSprite());
            PlayerCharacter character = _componentFactory.Create <PlayerCharacter>();

            character.MaxDashLength    = _playerData.MaxDashLength;
            character.MaxJumpLength    = _playerData.MaxJumpLength;
            character.MoveSpeed        = _playerData.MoveSpeed;
            character.DashSpeed        = _playerData.DashSpeed;
            character.JumpSpeed        = _playerData.JumpSpeed;
            character.CharacterType    = _characterType;
            character.MaxNumberOfJumps = _playerData.MaxNumberOfJumps;

            entity.AddComponent(character);

            Health health = _componentFactory.Create <Health>();

            health.MaxHitPoints     = 16;
            health.CurrentHitPoints = 8;
            entity.AddComponent(health);

            Position position = _componentFactory.Create <Position>();

            position.Facing = Direction.Right;
            position.X      = (int?)args[1] ?? 0;
            position.Y      = (int?)args[2] ?? 0;
            entity.AddComponent(position);

            entity.AddComponent(_componentFactory.Create <LocalData>());
            entity.AddComponent(_componentFactory.Create <Velocity>());
            entity.AddComponent(_componentFactory.Create <Renderable>());
            entity.AddComponent(BuildCollisionBox());

            Nameable nameable = _componentFactory.Create <Nameable>();

            nameable.Name = _playerData.Name;
            entity.AddComponent(nameable);

            Heartbeat heartbeat = _componentFactory.Create <Heartbeat>();

            heartbeat.Interval = _playerData.HeartbeatInterval;
            entity.AddComponent(heartbeat);

            Script script = _componentFactory.Create <Script>();

            script.FilePath = _playerData.Script;
            entity.AddComponent(script);

            PlayerStateMap stateMap = _componentFactory.Create <PlayerStateMap>();

            stateMap.States.Add(PlayerState.Idle, _playerStateFactory.Create <IdleState>());
            stateMap.States.Add(PlayerState.Move, _playerStateFactory.Create <MoveState>());
            stateMap.States.Add(PlayerState.Dash, _playerStateFactory.Create <DashState>());
            stateMap.States.Add(PlayerState.Jump, _playerStateFactory.Create <JumpState>());
            stateMap.States.Add(PlayerState.Fall, _playerStateFactory.Create <FallState>());
            stateMap.States.Add(PlayerState.Land, _playerStateFactory.Create <LandState>());
            stateMap.CurrentState = PlayerState.Idle;
            entity.AddComponent(stateMap);

            Gravity gravity = _componentFactory.Create <Gravity>();

            gravity.Speed = _playerData.GravitySpeed;
            entity.AddComponent(gravity);

            PlayerStats stats = _componentFactory.Create <PlayerStats>();

            stats.Lives = 2;
            entity.AddComponent(stats);

            EntitySystem.BlackBoard.SetEntry("Player", entity);
        }