Inheritance: UnrealBuildTool.ModuleRules
コード例 #1
0
ファイル: ProjectInfo.cs プロジェクト: ilya11211/nprof
        public Run CreateRun( Profiler p )
        {
            Run run = new Run( p, this );
            _rc.Add( run );

            return run;
        }
コード例 #2
0
        public void TestJsonProfilingStorage()
        {
            slf4net.LoggerFactory.SetFactoryResolver(new SimpleFactoryResolver(item => Console.WriteLine(item.Message)));

            var target = new JsonProfilingStorage(ProfilingStorageBase.Inline);

            // save empty result should not throw exception
            target.SaveResult(null);

            var name = "test";
            var stepName = "step1";
            var profiler = new Profiler(name, target, new [] { "test", "test2" }) as IProfiler;
            var mockParameter = new Mock<IDataParameter>();
            mockParameter.Setup(p => p.ParameterName).Returns("p1");
            mockParameter.Setup(p => p.Value).Returns(1);
            mockParameter.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterDBNull = new Mock<IDbDataParameter>();
            mockParameterDBNull.Setup(p => p.DbType).Returns(DbType.Binary);
            mockParameterDBNull.Setup(p => p.Value).Returns(DBNull.Value);
            mockParameterDBNull.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterBinary = new Mock<IDataParameter>();
            mockParameterBinary.Setup(p => p.DbType).Returns(DbType.Binary);
            mockParameterBinary.Setup(p => p.Value).Returns(new byte[100]);
            mockParameterBinary.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterBinaryTooBig = new Mock<IDbDataParameter>();
            mockParameterBinaryTooBig.Setup(p => p.DbType).Returns(DbType.Binary);
            mockParameterBinaryTooBig.Setup(p => p.Value).Returns(new byte[0x200 + 1]);
            mockParameterBinaryTooBig.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterDateTime = new Mock<IDbDataParameter>();
            mockParameterDateTime.Setup(p => p.DbType).Returns(DbType.DateTime);
            mockParameterDateTime.Setup(p => p.Value).Returns(DateTime.Now);
            mockParameterDateTime.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterEnum = new Mock<IDbDataParameter>();
            mockParameterEnum.Setup(p => p.DbType).Returns(DbType.Int32);
            mockParameterEnum.Setup(p => p.Value).Returns(DbType.Boolean);
            mockParameterEnum.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterXml = new Mock<IDbDataParameter>();
            mockParameterXml.Setup(p => p.DbType).Returns(DbType.Xml);
            mockParameterXml.Setup(p => p.Value).Returns("<xml />");
            mockParameterXml.Setup(p => p.Direction).Returns(ParameterDirection.Input);
            var mockParameterCollection = new Mock<IDataParameterCollection>();
            mockParameterCollection.Setup(collections => collections.GetEnumerator()).Returns(new IDataParameter[] { mockParameter.Object, mockParameterDBNull.Object, mockParameterBinary.Object, mockParameterBinaryTooBig.Object, mockParameterDateTime.Object, mockParameterEnum.Object, mockParameterXml.Object }.GetEnumerator());
            mockParameterCollection.Setup(collection => collection.Count).Returns(1);
            var mockCommand = new Mock<IDbCommand>();
            mockCommand.Setup(cmd => cmd.CommandText).Returns("test sql");
            mockCommand.Setup(cmd => cmd.Parameters).Returns(mockParameterCollection.Object);
            var dbTiming = new DbTiming(
                profiler, DbExecuteType.Reader, mockCommand.Object);
            using (profiler.Step(stepName, null, null))
            {
                profiler.AddCustomTiming(dbTiming);
                profiler.AddCustomTiming(new CustomTiming(profiler, "custom", "custom"));
            }
            profiler.Stop();

            // save normal result should not throw exception
            target.SaveResult(profiler);
            slf4net.LoggerFactory.Reset();
        }
コード例 #3
0
ファイル: PerformanceGraph.cs プロジェクト: bartwe/Gearset
        internal PerformanceGraph(Profiler profiler, ProfilerConfig.UiViewConfig uiviewConfig, Vector2 size)
            : base(profiler, uiviewConfig, size)
        {
            for (var i = 0; i < MaxFrames; i++)
                _frames.Enqueue(new Frame());

            DisplayedFrameCount = MaxFrames;
        }
コード例 #4
0
      protected override void ExecuteInitialize()
      {
        _currProfiler = _currFuncCode.Profiler;
        _globalContext = null;
        _deoptimizer = _ilGen.DefineLabel();

        Debug.Assert(JSRuntime.Instance.Configuration.EnableSpeculativeJIT && _currProfiler != null && _currFuncCode.IsHot && _currProfiler != null, "Invalid situation! Speculation conditions are not correct!");

        base.ExecuteInitialize();
      }
コード例 #5
0
ファイル: Run.cs プロジェクト: ilya11211/nprof
 public Run( Profiler p, ProjectInfo pi )
 {
     _p = p;
     _dtStart = DateTime.Now;
     _dtEnd = DateTime.MaxValue;
     _rs = RunState.Initializing;
     _tic = new ThreadInfoCollection();
     _pi = pi;
     _rmcMessages = new RunMessageCollection();
     _bSuccess = false;
 }
コード例 #6
0
    	public static HtmlString RenderIncludes(Profiler profiler, RenderPosition? position = null, bool? showTrivial = null, bool? showTimeWithChildren = null, int? maxTracesToShow = null, bool xhtml = false, bool? showControls = null)
        {
            const string format =
@"<link rel=""stylesheet"" type=""text/css"" href=""{path}ss-includes.css?v={version}""{closeXHTML}>
<script type=""text/javascript"">
    if (!window.jQuery) document.write(unescape(""%3Cscript src='{path}ss-jquip.all.js?v={version}' type='text/javascript'%3E%3C/script%3E""));
</script>
<script type=""text/javascript"" src=""{path}ss-includes.js?v={version}""></script>
<script type=""text/javascript"">
    jQuery(function() {{
        MiniProfiler.init({{
            ids: {ids},
            path: '{path}',
            version: '{version}',
            renderPosition: '{position}',
            showTrivial: {showTrivial},
            showChildrenTime: {showChildren},
            maxTracesToShow: {maxTracesToShow},
            showControls: {showControls}
        }});
    }});
</script>";

            var result = "";

            if (profiler != null)
            {
                // HACK: unviewed ids are added to this list during Storage.Save, but we know we haven't see the current one yet,
                // so go ahead and add it to the end - it's usually the only id, but if there was a redirect somewhere, it'll be there, too
                Profiler.Settings.EnsureStorageStrategy();
                var ids = Profiler.Settings.Storage.GetUnviewedIds(profiler.User);
                ids.Add(profiler.Id);

            	var path = EndpointHost.Config.ServiceStackHandlerFactoryPath;

                result = format.Format(new
                {
                    //path = VirtualPathUtility.ToAbsolute(MiniProfiler.Settings.RouteBasePath).EnsureTrailingSlash(),
					path = !string.IsNullOrEmpty(path) ? path + "/" : "",
                    version = Profiler.Settings.Version,
                    ids = ids.ToJson(),
                    position = (position ?? Profiler.Settings.PopupRenderPosition).ToString().ToLower(),
                    showTrivial = showTrivial ?? Profiler.Settings.PopupShowTrivial ? "true" : "false",
                    showChildren = showTimeWithChildren ?? Profiler.Settings.PopupShowTimeWithChildren ? "true" : "false",
                    maxTracesToShow = maxTracesToShow ?? Profiler.Settings.PopupMaxTracesToShow,
                    closeXHTML = xhtml ? "/" : "",
                    showControls = showControls ?? Profiler.Settings.ShowControls ? "true" : "false"
                });
            }

            return new HtmlString(result);
        }
コード例 #7
0
        /// <summary>
        /// Saves <paramref name="profiler"/> to the HttpRuntime.Cache under a key concated with <see cref="CacheKeyPrefix"/>
        /// and the parameter's <see cref="Profiler.Id"/>.
        /// </summary>
        public void Save(Profiler profiler)
        {
            InsertIntoCache(GetCacheKey(profiler.Id), profiler);

            // so we can easily follow POST -> redirects, store ids for this user
            var ids = GetPerUserUnviewedIds(profiler);
            lock (ids)
            {
                if (!ids.Contains(profiler.Id))
                {
                    ids.Add(profiler.Id);
                }
            }
        }
コード例 #8
0
ファイル: Profiler.cs プロジェクト: MattDBell/GCubed
 /// <summary>
 /// Create a Profiler
 /// </summary>
 /// <param name="name">The name of the profiler to draw with the bars</param>
 /// <param name="color">The color of the bar</param>
 /// <param name="parent">If this is a sub-profiler, give the parent Profiler. For top-level put "null"</param>
 public Profiler(String name, Color color, Profiler parent)
 {
     m_timer = new Stopwatch();
     m_name = name;
     m_color = color;
     m_children = new LinkedList<Profiler>();
     m_sample = new float[NUM_SAMPLE];
     for (int i = 0; i < NUM_SAMPLE; ++i)
         m_sample[i] = 0.0f;
     m_curSample = 0;
     m_parent = parent;
     if (null != m_parent)
         m_parent.AddChild(this);
 }
コード例 #9
0
ファイル: MainPanel.cs プロジェクト: MChehadeh/userTerminal
        public MainPanel(string mw_SerialPort,string rx_SerialPort)
        {
            InitializeComponent();
            if (!String.IsNullOrEmpty(rx_SerialPort))
            {
                rx_profiler = new Profiler(this, init_display_rx, update_display_rx);
                RC_driver = new serial_driver(rx_SerialPort, this, rx_profiler, stream_source.RC_transmitter);
                rx_status.Text = "Open";
            }
            else
            {
                rx_status.Text = "Not Available";
            }
            System.Threading.Thread.Sleep(1000);
            if (!String.IsNullOrEmpty(mw_SerialPort))
            {
                mw_profiler = new Profiler(this, init_display_mw, update_display_mw);
                hardware_driver = new serial_driver(mw_SerialPort, this, mw_profiler, stream_source.flight_controller);
                mw_commander = new commander();
                lblStrip_mw_status.Text = "Open";
            }
            else
            {
                lblStrip_mw_status.Text = "Not Available";
            }
            msg_ctrl_main = new msg_ctrl(hardware_driver.SerialParser, stream_source.flight_controller);
            msg_ctrl_main.DebugTextReceived += new msg_ctrl.DebugTextReceivedHandler(this.OnDebugTextReceived);
            mw_profiler.AttachProbeReceivedEvent();
            display_adapter_main = new dispaly_adapter(this,mw_profiler, attitudeIndicatorInstrument, rollRateInstrument);
            display.Smoothing = System.Drawing.Drawing2D.SmoothingMode.None;
            display.Refresh();
            //int tmp = Thread.CurrentThread.ManagedThreadId;
            display.PlaySpeed = 0.05f;
            session_organizer_main = new session_organizer(treeView_mrft, hardware_driver, mw_commander, msg_ctrl_main);
            flight_scenario_main = new flight_scenario(0, session_organizer_main, listViewFlightScenario, lbl_status_txt,lblStrip_mw_status,lst_flight_history, this);
            //TODO: Optimize this
            session_display_manager_main = new session_display_manager(barBeta, barAmp, barBias,txt_mrft_session_cmnt,
                txt_point_comment,txt_num_mrft_bags, chart_mrft,chart_mrft_session, tabControlTune,combo_tune_method,combo_model_type,
                combo_pid_optim, listViewMRFTPoints,barProp,barIntegral, barDerivative,barWindup,chk_en_pv_derive,
                chk_get_bias, txt_pid_comment,combo_cmd_type,combo_ref_src,txt_beta_val,txt_amp_val,txt_bias_val,
                session_organizer_main);
            DisplayUpdateTimer = new Timer();
            DisplayUpdateTimer.Interval = 100;
            DisplayUpdateTimer.Start();
            DisplayUpdateTimer.Tick += new EventHandler(OnDisplayRefreshTimerTick);

        }
コード例 #10
0
ファイル: Test.cs プロジェクト: xuchuansheng/GenXSource
			public override object GetResult(out int level)
			{
				level = 1;
				ProjectInfo project = new ProjectInfo();
				NProf.form.Project = project;
				Profiler profiler = new Profiler();
				//project.ApplicationName = @"D:\Meta\0.2\bin\Debug\Meta.exe";
				//project.Arguments = "-test";
				project.ApplicationName = Path.Combine(NProfDirectory, @"TestProfilee\bin\Debug\TestProfilee.exe");

				run = project.CreateRun(profiler);
				run.profiler.Completed += new EventHandler(profiler_Completed);
				run.Start();

				while (result == null)
				{
					Thread.Sleep(100);
				}
				return result;
			}
コード例 #11
0
 public serial_driver(String port_name, MainPanel panel_form, Profiler probe_profiler_para, stream_source stream_source_para)
 {
     main_form = panel_form;
     data_stream = new SerialPort(port_name, 115200, Parity.None, 8, StopBits.One);
     data_stream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
     data_stream.ReceivedBytesThreshold = 1;
     data_stream.Open();
     data_stream.DtrEnable = true;
     data_stream.DtrEnable = false;
     data_stream.DiscardInBuffer();
     data_stream.DiscardOutBuffer();
     frame_prop packet_config;
     packet_config.padding_len = 3;
     packet_config.padding_byte = new byte[3] { 0xFF, 0x00, 0xAA };
     packet_config.pad_EOH = 0xFF;
     packet_config.pad_EOP = 0xFF;
     packet_config.header_len = 2;
     packet_config.crc_len = 2;
     parser = new Serial_parser(packet_config, main_form, probe_profiler_para, stream_source_para);
 }
コード例 #12
0
        public void Should_be_called_during_the_final_execution_state()
        {
            string expected = "47";
            string called = null;

            FeatherVane<string> logger = new Logger<string>(Console.Out, x =>
                {
                    called = x.Data;
                    return x.Data;
                });

            FeatherVane<string> profiler = new Profiler<string>(Console.Error, TimeSpan.FromMilliseconds(2));

            Vane<string> vane = Vane.Success(profiler, logger);

            vane.Execute(expected);

            Assert.IsFalse(string.IsNullOrEmpty(called));
            Assert.AreEqual(expected, called);
        }
コード例 #13
0
ファイル: DbProfilerTest.cs プロジェクト: volkd/nanoprofiler
        public void TestDbProfiler()
        {
            var mockStorage = new Mock<IProfilingStorage>();
            var profiler = new Profiler("test", mockStorage.Object, null);
            var target = new DbProfiler(profiler) as IDbProfiler;

            var stepId = Guid.NewGuid();
            ProfilingSession.ProfilingSessionContainer.CurrentSessionStepId = stepId;
            var executeCalled = false;
            var mockCommand = new Mock<IDbCommand>();
            mockCommand.Setup(cmd => cmd.CommandText).Returns("test");
            var mockReader = new Mock<IDataReader>();

            // test execute reader
            target.ExecuteDbCommand(DbExecuteType.Reader, mockCommand.Object, () =>
            {
                executeCalled = true;
                return mockReader.Object;
            }, new[] { "tag1" });
            Assert.IsTrue(executeCalled);
            Assert.AreEqual(0, (profiler as IProfiler).CustomTimings.Count());
            target.DataReaderFinished(new ProfiledDbDataReader(mockReader.Object, target));
            Assert.AreEqual(1, (profiler as IProfiler).CustomTimings.Count());
            Assert.AreEqual("TAG1", (profiler as IProfiler).CustomTimings.Last().Tags.First());

            // test execute nonquery
            executeCalled = false;
            target.ExecuteDbCommand(DbExecuteType.NonQuery, mockCommand.Object, () =>
            {
                executeCalled = true;
                return null;
            }, null);
            Assert.IsTrue(executeCalled);
            Assert.AreEqual(2, (profiler as IProfiler).CustomTimings.Count());

            // test DataReaderFinished with invalid reader, it should not throw exception
            target.DataReaderFinished(null);
        }
コード例 #14
0
        /// <summary>
        /// Giving freshly selected collections, this method puts them in the correct
        /// hierarchy under the 'result' MiniProfiler.
        /// </summary>
        protected void MapTimings(Profiler result, List<Timing> timings, List<SqlTiming> sqlTimings, List<SqlTimingParameter> sqlParameters)
        {
            var stack = new Stack<Timing>();

            for (int i = 0; i < timings.Count; i++)
            {
                var cur = timings[i];
                foreach (var sqlTiming in sqlTimings)
                {
                    if (sqlTiming.ParentTimingId == cur.Id)
                    {
                        cur.AddSqlTiming(sqlTiming);

                        var parameters = sqlParameters.Where(p => p.ParentSqlTimingId == sqlTiming.Id);
                        if (parameters.Count() > 0)
                        {
                            sqlTiming.Parameters = parameters.ToList();
                        }
                    }
                }

                if (stack.Count > 0)
                {
                    Timing head;
                    while ((head = stack.Peek()).Id != cur.ParentTimingId)
                    {
                        stack.Pop();
                    }

                    head.AddChild(cur);
                }
                stack.Push(cur);
            }

            // TODO: .Root does all the above work again, but it's used after [DataContract] deserialization; refactor it out somehow
            result.Root = timings.First();
        }
コード例 #15
0
ファイル: AstGenerator.cs プロジェクト: jxnmaomao/ironruby
        /// <summary>
        /// Creates a new AstGenerator for a class or function definition.
        /// </summary>
        internal AstGenerator(AstGenerator/*!*/ parent, string name, bool generator, string profilerName)
            : this(name, generator, profilerName, false) {
            Assert.NotNull(parent);
            _context = parent.Context;
            _pythonContext = parent.PyContext;
            _parent = parent;
            _document = _context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid);
            _profiler = parent._profiler;

            _globals = parent._globals;
        }
コード例 #16
0
ファイル: helpers.cs プロジェクト: kig/filezoo
 public static void DrawText(Context cr, string family, double fontSize, string text, Pango.Alignment alignment)
 {
     //   return;
       lock (FontCache) {
     //   LogError("DrawText {0}", text);
     Profiler p = new Profiler ("DrawText");
     double w,h;
     Pango.Layout layout = GetLayout (cr, family, QuantizeFontSize(fontSize));
     layout.SetText (text);
     layout.Alignment = alignment;
     layout.GetExtents(out pe, out le);
     p.Time ("GetExtents {0}", pe);
     w = (double)le.Width / (double)Pango.Scale.PangoScale;
     h = (double)le.Height / (double)Pango.Scale.PangoScale;
     if (alignment == Pango.Alignment.Right) {
       cr.RelMoveTo (-w, 0);
     } else if (alignment == Pango.Alignment.Center) {
       cr.RelMoveTo (-w/2, 0);
     }
     Pango.CairoHelper.ShowLayout (cr, layout);
     p.Time ("ShowLayout");
     if (ShowTextExtents) {
       cr.Save ();
     PointD pt = cr.CurrentPoint;
     cr.MoveTo (pt.X, pt.Y);
     cr.RelLineTo(w, 0);
     cr.RelLineTo(0, h);
     cr.Operator = Operator.Over;
     cr.Color = new Color (1,0.5,1,0.5);
     cr.LineWidth = 0.5;
     cr.Stroke ();
     cr.MoveTo (pt.X, pt.Y);
       cr.Restore ();
     }
     cr.RelMoveTo (w, 0);
       }
 }
コード例 #17
0
ファイル: PythonAst.cs プロジェクト: Xiaoqing/main
        /// <summary>
        /// Creates a new PythonAst without a body.  ParsingFinished should be called afterwards to set
        /// the body.
        /// </summary>
        public PythonAst(bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context) {
            _isModule = isModule;
            _printExpressions = printExpressions;
            _languageFeatures = languageFeatures;
            _mode = ((PythonCompilerOptions)context.Options).CompilationMode ?? GetCompilationMode(context);
            _compilerContext = context;
            FuncCodeExpr = _functionCode;

            PythonCompilerOptions pco = context.Options as PythonCompilerOptions;
            Debug.Assert(pco != null);

            string name;
            if (!context.SourceUnit.HasPath || (pco.Module & ModuleOptions.ExecOrEvalCode) != 0) {
                name = "<module>";
            } else {
                name = context.SourceUnit.Path;
            }

            _name = name;
            Debug.Assert(_name != null);
            PythonOptions po = ((PythonContext)context.SourceUnit.LanguageContext).PythonOptions;

            if (po.EnableProfiler && _mode != CompilationMode.ToDisk) {
                _profiler = Profiler.GetProfiler(PyContext);
            }

            _document = context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid);
        }
コード例 #18
0
 public static void BeginSample(string name)
 {
    Profiler.BeginSample(name);
 }
コード例 #19
0
ファイル: MechJebCore.cs プロジェクト: DoctorDavinci/MechJeb2
        public void FixedUpdate()
        {
            if (!FlightGlobals.ready)
            {
                return;
            }

            LoadDelayedModules();

            CheckControlledVessel(); //make sure our onFlyByWire callback is registered with the right vessel

            if (this != vessel.GetMasterMechJeb() || (HighLogic.LoadedSceneIsFlight && !vessel.isActiveVessel))
            {
                wasMasterAndFocus = false;
            }

            if (this != vessel.GetMasterMechJeb())
            {
                return;
            }
            Profiler.BeginSample("MechJebCore.FixedUpdate");

            if (!wasMasterAndFocus && (HighLogic.LoadedSceneIsEditor || vessel.isActiveVessel))
            {
                if (HighLogic.LoadedSceneIsFlight && (lastFocus != null) && lastFocus.loaded && (lastFocus.GetMasterMechJeb() != null))
                {
                    print("Focus changed! Forcing " + lastFocus.vesselName + " to save");
                    lastFocus.GetMasterMechJeb().OnSave(null);
                }

                // Clear the modules cache
                ClearModulesCache();

                OnLoad(null); // Force Global reload

                wasMasterAndFocus = true;
                lastFocus         = vessel;
            }

            if (vessel == null)
            {
                Profiler.EndSample();
                return; //don't run ComputerModules' OnFixedUpdate in editor
            }

            Profiler.BeginSample("vesselState");
            ready = vesselState.Update(vessel);
            Profiler.EndSample();

            foreach (ComputerModule module in GetComputerModules <ComputerModule>())
            {
                Profiler.BeginSample(module.profilerName);
                try
                {
                    if (module.enabled)
                    {
                        module.OnFixedUpdate();
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnFixedUpdate: " + e);
                }
                Profiler.EndSample();
            }
            Profiler.EndSample();
        }
コード例 #20
0
ファイル: TypeCalculator.cs プロジェクト: reshadi2/mcjs
 public override void Visit(InlinedInvocation node)
 {
   var currProfile = _currProfile;
   _currProfile = node.TargetProfile;
   base.Visit(node);
   node.ValueType = GetType(node);
   _currProfile = currProfile;
 }
コード例 #21
0
 /// <summary>
 /// Saves 'profiler' to a database under its <see cref="Profiler.Id"/>.
 /// </summary>
 public abstract void Save(Profiler profiler);
コード例 #22
0
    public bool GenerateSector(int starsToGenerate = 10)
    {
        Profiler.BeginSample("GenerateSector()");

        //Debug.Log (starsToGenerate);
        float sectorSize  = GameSettings.sectorSize;
        bool  failed      = false;
        int   starCurrent = 0;

        //Vector3[] starStream = new Vector3[starsToGenerate];

        if (x == y && x == 0)
        {
            //starStream [starCurrent] = new Vector3(0, 0, 0);
            starList.Add(new Star(this, new Vector3(0f, 0f, 0)));
            //Debug.Log (starCurrent);
            starCurrent++;
        }

        int tries = 0;

        while (starCurrent < starsToGenerate)
        {
            failed = false;

            Vector3 starPos = new Vector3(
                Random.Range(-sectorSize / 2f, sectorSize / 2f),
                Random.Range(-sectorSize / 2f, sectorSize / 2f),
                0
                );

            starPos = starPos + position;
            //if (systemPlacementDebug) { Debug.Log (parentID); }

            //Vector3 sectorOffset; //Del av ev. optimering av intersector beräknignar.

            //Gammal stjärnplacering
            foreach (var starCheck in starList)
            {
                //Debug.Log (Vector3.Distance (starCheck.position, starPos));
                if (Vector3.Distance(starCheck.position, starPos) <= GameSettings.minStarDistance)
                {
                    //Debug.Log("failed");
                    failed = true;
                    break;
                }
            }

            if (!failed)
            {
                for (int i = 0; i < 8; i++)
                {
                    CheckNeighbours(i);

                    int count = 0;
                    if (neighbours [i] != null)
                    {
                        foreach (Star starCheck in neighbours[i].starList)
                        {
                            if (Vector3.Distance(starCheck.position, starPos) <= GameSettings.minStarDistance)
                            {
                                //Debug.Log("failed");
                                failed = true;
                                break;
                            }

                            count++;
                            if (count > 1000)
                            {
                                Debug.LogError("Game stuck in GenerateSector() loop");
                                break;
                            }
                        }
                    }
                    if (failed)
                    {
                        break;
                    }
                }
            }

            //Eventuell kod för att optimera intersector beräkningar.

            /*
             * if (north) {
             * } else if (south) {
             * }
             * if (east)
             *
             *
             * NotRect.notRect (
             *      this.position - sectorOffset (GameSettings.sectorSize / 2, GameSettings.sectorSize / 2, 0),
             *      this.position + sectorOffset (GameSettings.sectorSize / 2, GameSettings.sectorSize / 2, 0),
             *
             * );
             */



            if (!failed)
            {
                //starStream [starCurrent] = starPos;
                ;
                starList.Add(new Star(this, starPos));
                //Debug.Log (starCurrent);
                starCurrent++;
                tries = 0;
            }
            else
            {
                tries++;
                //Debug.Log (starCurrent + " " + starPos);
                if (tries > 10)
                {
                    starCurrent++;
                    //Debug.Log (starCurrent);
                    tries = 0;
                }
            }
        }

        starwayGen.StarwayGen.GenerateStarways(this);

        Profiler.EndSample();
        return(false);
    }
コード例 #23
0
        private void DrawStickerElement(Rect rect, int index, bool isActive, bool isFocused)
        {
            rect.y     += 2;
            rect.width -= ImageSize + ImagePadding;
            var stickerAsset = stickers.GetArrayElementAtIndex(index);

            if (stickerAsset == null)
            {
                Debug.LogWarning("Sticker asset at #" + index + " is missing");
                return;
            }

            var sticker = new SerializedObject(stickerAsset.objectReferenceValue);

            var frames      = sticker.FindProperty("Frames");
            var stickerName = sticker.FindProperty("Name");
            var sequence    = sticker.FindProperty("Sequence");
            var fps         = sticker.FindProperty("Fps");
            var reps        = sticker.FindProperty("Repetitions");

            Profiler.BeginSample("Sticker Element #" + index, stickerAsset.objectReferenceValue);
            {
                var nameRect = new Rect(rect);
                nameRect.y     += 1;
                nameRect.height = FieldHeight;

                EditorGUI.PropertyField(nameRect, stickerName);

                var sequenceRect = new Rect(rect);
                sequenceRect.y     += ButtonHeight + 2;
                sequenceRect.height = ButtonHeight;
                sequenceRect.width -= 150;
                EditorGUI.PropertyField(sequenceRect, sequence);

                EditorGUI.BeginDisabledGroup(!sequence.boolValue);
                var buttonRect = new Rect(rect);
                buttonRect.y     += ButtonHeight;
                buttonRect.xMin   = EditorGUIUtility.labelWidth + 50;
                buttonRect.height = ButtonHeight;
                if (GUI.Button(buttonRect, LoadFromFolder))
                {
                    StickerEditor.AddStickerSequence(sequence, stickerName, fps, frames);
                }

                var fieldRect = new Rect(rect);
                fieldRect.y     += FieldPadding + ButtonPadding;
                fieldRect.height = FieldHeight;
                EditorGUI.PropertyField(fieldRect, fps);
                fieldRect.y += FieldPadding;
                EditorGUI.PropertyField(fieldRect, reps);
                EditorGUI.EndDisabledGroup();

                if (frames.arraySize == 0)
                {
                    frames.InsertArrayElementAtIndex(0);
                }

                if (!sequence.boolValue && frames.arraySize > 1)
                {
                    frames.arraySize = 1;
                }

                fieldRect.y += FieldPadding;

                var firstFrameRect = new Rect(rect);
                firstFrameRect.height = ImageSize;
                firstFrameRect.x      = firstFrameRect.xMax + 4;
                firstFrameRect.y     += 1f;
                firstFrameRect.width  = ImageSize;

                var firstFrame = frames.GetArrayElementAtIndex(0);

                var firstFrameTexture = firstFrame.objectReferenceValue as Texture2D;

                var textureSize = new Vector2(firstFrameTexture != null ? firstFrameTexture.width : 0, firstFrameTexture != null ? firstFrameTexture.height : 0);

                Profiler.BeginSample("Size Help Box");
                {
                    DrawSizeHelpBox(size, fieldRect, textureSize);
                }
                Profiler.EndSample();
                fieldRect.y += FieldPadding;

                Profiler.BeginSample("Disk Size Help Box");
                {
                    DrawDiskSizeHelpBox(fieldRect, stickerAsset);
                }
                Profiler.EndSample();
                var updateIndexes = false;

                Profiler.BeginSample("Draw texture");
                {
                    if (DrawTexture(sequence, firstFrameRect, frames, fps, firstFrameTexture, firstFrame, stickerName, sticker, ref updateIndexes))
                    {
                        return;
                    }
                }
                Profiler.EndSample();

                if (sticker.ApplyModifiedProperties() && updateIndexes)
                {
                    UpdatedIndexes(list);
                }
            }
            Profiler.EndSample();

            if (sequence.boolValue && frames.arraySize > 1)
            {
                RepaintView();
            }
        }
コード例 #24
0
 static public int constructor(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         UnityEngine.CubemapArray o;
         if (matchType(l, argc, 2, typeof(int), typeof(int), typeof(UnityEngine.Experimental.Rendering.DefaultFormat), typeof(UnityEngine.Experimental.Rendering.TextureCreationFlags)))
         {
             System.Int32 a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.Experimental.Rendering.DefaultFormat a3;
             a3 = (UnityEngine.Experimental.Rendering.DefaultFormat)LuaDLL.luaL_checkinteger(l, 4);
             UnityEngine.Experimental.Rendering.TextureCreationFlags a4;
             a4 = (UnityEngine.Experimental.Rendering.TextureCreationFlags)LuaDLL.luaL_checkinteger(l, 5);
             o  = new UnityEngine.CubemapArray(a1, a2, a3, a4);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, argc, 2, typeof(int), typeof(int), typeof(UnityEngine.Experimental.Rendering.GraphicsFormat), typeof(UnityEngine.Experimental.Rendering.TextureCreationFlags)))
         {
             System.Int32 a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.Experimental.Rendering.GraphicsFormat a3;
             a3 = (UnityEngine.Experimental.Rendering.GraphicsFormat)LuaDLL.luaL_checkinteger(l, 4);
             UnityEngine.Experimental.Rendering.TextureCreationFlags a4;
             a4 = (UnityEngine.Experimental.Rendering.TextureCreationFlags)LuaDLL.luaL_checkinteger(l, 5);
             o  = new UnityEngine.CubemapArray(a1, a2, a3, a4);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, argc, 2, typeof(int), typeof(int), typeof(UnityEngine.Experimental.Rendering.GraphicsFormat), typeof(UnityEngine.Experimental.Rendering.TextureCreationFlags), typeof(int)))
         {
             System.Int32 a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.Experimental.Rendering.GraphicsFormat a3;
             a3 = (UnityEngine.Experimental.Rendering.GraphicsFormat)LuaDLL.luaL_checkinteger(l, 4);
             UnityEngine.Experimental.Rendering.TextureCreationFlags a4;
             a4 = (UnityEngine.Experimental.Rendering.TextureCreationFlags)LuaDLL.luaL_checkinteger(l, 5);
             System.Int32 a5;
             checkType(l, 6, out a5);
             o = new UnityEngine.CubemapArray(a1, a2, a3, a4, a5);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, argc, 2, typeof(int), typeof(int), typeof(UnityEngine.TextureFormat), typeof(int), typeof(bool)))
         {
             System.Int32 a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.TextureFormat a3;
             a3 = (UnityEngine.TextureFormat)LuaDLL.luaL_checkinteger(l, 4);
             System.Int32 a4;
             checkType(l, 5, out a4);
             System.Boolean a5;
             checkType(l, 6, out a5);
             o = new UnityEngine.CubemapArray(a1, a2, a3, a4, a5);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, argc, 2, typeof(int), typeof(int), typeof(UnityEngine.TextureFormat), typeof(bool), typeof(bool)))
         {
             System.Int32 a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.TextureFormat a3;
             a3 = (UnityEngine.TextureFormat)LuaDLL.luaL_checkinteger(l, 4);
             System.Boolean a4;
             checkType(l, 5, out a4);
             System.Boolean a5;
             checkType(l, 6, out a5);
             o = new UnityEngine.CubemapArray(a1, a2, a3, a4, a5);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         else if (matchType(l, argc, 2, typeof(int), typeof(int), typeof(UnityEngine.TextureFormat), typeof(bool)))
         {
             System.Int32 a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.TextureFormat a3;
             a3 = (UnityEngine.TextureFormat)LuaDLL.luaL_checkinteger(l, 4);
             System.Boolean a4;
             checkType(l, 5, out a4);
             o = new UnityEngine.CubemapArray(a1, a2, a3, a4);
             pushValue(l, true);
             pushValue(l, o);
             return(2);
         }
         return(error(l, "New object failed."));
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
コード例 #25
0
        // ----------------------------------------------------------------------------
        // internal methods
        // ----------------------------------------------------------------------------

        internal override void UpdateValue(bool force)
        {
            if (!enabled)
            {
                return;
            }

            if (force)
            {
                if (!inited && (HasData()))
                {
                    Activate();
                    return;
                }

                if (inited && (!HasData()))
                {
                    Deactivate();
                    return;
                }
            }

            if (total)
            {
#if UNITY_5_6_OR_NEWER
                long value = Profiler.GetTotalReservedMemoryLong();
#else
                long value = Profiler.GetTotalReservedMemory();
#endif
                long divisionResult = 0;

                bool newValue;
                if (precise)
                {
                    newValue = (LastTotalValue != value);
                }
                else
                {
                    divisionResult = value / MEMORY_DIVIDER;
                    newValue       = (LastTotalValue != divisionResult);
                }

                if (newValue || force)
                {
                    LastTotalValue = precise ? value : divisionResult;
                    dirty          = true;
                }
            }

            if (allocated)
            {
#if UNITY_5_6_OR_NEWER
                long value = Profiler.GetTotalAllocatedMemoryLong();
#else
                long value = Profiler.GetTotalAllocatedMemory();
#endif
                long divisionResult = 0;

                bool newValue;
                if (precise)
                {
                    newValue = (LastAllocatedValue != value);
                }
                else
                {
                    divisionResult = value / MEMORY_DIVIDER;
                    newValue       = (LastAllocatedValue != divisionResult);
                }

                if (newValue || force)
                {
                    LastAllocatedValue = precise ? value : divisionResult;
                    dirty = true;
                }
            }

            if (monoUsage)
            {
                long monoMemory         = System.GC.GetTotalMemory(false);
                long monoDivisionResult = 0;

                bool newValue;
                if (precise)
                {
                    newValue = (LastMonoValue != monoMemory);
                }
                else
                {
                    monoDivisionResult = monoMemory / MEMORY_DIVIDER;
                    newValue           = (LastMonoValue != monoDivisionResult);
                }

                if (newValue || force)
                {
                    LastMonoValue = precise ? monoMemory : monoDivisionResult;
                    dirty         = true;
                }
            }

            if (!dirty || main.OperationMode != OperationMode.Normal)
            {
                return;
            }

            bool needNewLine = false;

            text.Length = 0;
            text.Append(colorCached);

            if (total)
            {
                text.Append(LINE_START_TOTAL);

                if (precise)
                {
                    text.Append((LastTotalValue / (float)MEMORY_DIVIDER).ToString("F"));
                }
                else
                {
                    text.Append(LastTotalValue);
                }
                text.Append(LINE_END);
                needNewLine = true;
            }

            if (allocated)
            {
                if (needNewLine)
                {
                    text.Append(AFPSCounter.NEW_LINE);
                }
                text.Append(LINE_START_ALLOCATED);

                if (precise)
                {
                    text.Append((LastAllocatedValue / (float)MEMORY_DIVIDER).ToString("F"));
                }
                else
                {
                    text.Append(LastAllocatedValue);
                }
                text.Append(LINE_END);
                needNewLine = true;
            }

            if (monoUsage)
            {
                if (needNewLine)
                {
                    text.Append(AFPSCounter.NEW_LINE);
                }
                text.Append(LINE_START_MONO);

                if (precise)
                {
                    text.Append((LastMonoValue / (float)MEMORY_DIVIDER).ToString("F"));
                }
                else
                {
                    text.Append(LastMonoValue);
                }

                text.Append(LINE_END);
            }

            text.Append(TEXT_END);

            ApplyTextStyles();
        }
コード例 #26
0
        /// <summary>
        /// Schedules a job that converts input data into float3 arrays.
        /// </summary>
        /// <param name="input">Points at the input data in memory</param>
        /// <param name="count">Attribute quantity</param>
        /// <param name="inputType">Input data type</param>
        /// <param name="inputByteStride">Input byte stride</param>
        /// <param name="output">Points at the destination buffer in memory</param>
        /// <param name="outputByteStride">Ouput byte stride</param>
        /// <param name="normalized">If true, integer values have to be normalized</param>
        /// <param name="ensureUnitLength">If true, normalized values will be scaled to have unit length again (only if <see cref="normalized"/>is true)</param>
        /// <returns></returns>
        public static unsafe JobHandle?GetVector3sJob(
            void *input,
            int count,
            GLTFComponentType inputType,
            int inputByteStride,
            float3 *output,
            int outputByteStride,
            bool normalized       = false,
            bool ensureUnitLength = true
            )
        {
            JobHandle?jobHandle;

            Profiler.BeginSample("GetVector3sJob");
            if (inputType == GLTFComponentType.Float)
            {
                var job = new ConvertVector3FloatToFloatInterleavedJob {
                    inputByteStride  = (inputByteStride > 0) ? inputByteStride : 12,
                    input            = (byte *)input,
                    outputByteStride = outputByteStride,
                    result           = output
                };
#if UNITY_JOBS
                jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
            }
            else
            if (inputType == GLTFComponentType.UnsignedShort)
            {
                if (normalized)
                {
                    var job = new ConvertPositionsUInt16ToFloatInterleavedNormalizedJob {
                        inputByteStride  = (inputByteStride > 0) ? inputByteStride : 6,
                        input            = (byte *)input,
                        outputByteStride = outputByteStride,
                        result           = output
                    };
#if UNITY_JOBS
                    jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                    jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                }
                else
                {
                    var job = new ConvertPositionsUInt16ToFloatInterleavedJob {
                        inputByteStride  = (inputByteStride > 0) ? inputByteStride : 6,
                        input            = (byte *)input,
                        outputByteStride = outputByteStride,
                        result           = output
                    };
#if UNITY_JOBS
                    jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                    jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                }
            }
            else
            if (inputType == GLTFComponentType.Short)
            {
                if (normalized)
                {
                    if (ensureUnitLength)
                    {
                        // TODO: test. did not have test files
                        var job = new ConvertNormalsInt16ToFloatInterleavedNormalizedJob {
                            inputByteStride  = (inputByteStride > 0) ? inputByteStride : 6,
                            input            = (byte *)input,
                            outputByteStride = outputByteStride,
                            result           = output
                        };
#if UNITY_JOBS
                        jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                        jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                    }
                    else
                    {
                        var job = new ConvertVector3Int16ToFloatInterleavedNormalizedJob {
                            inputByteStride  = (inputByteStride > 0) ? inputByteStride : 6,
                            input            = (byte *)input,
                            outputByteStride = outputByteStride,
                            result           = output
                        };
#if UNITY_JOBS
                        jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                        jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                    }
                }
                else
                {
                    var job = new ConvertPositionsInt16ToFloatInterleavedJob {
                        inputByteStride  = (inputByteStride > 0) ? inputByteStride : 6,
                        input            = (byte *)input,
                        outputByteStride = outputByteStride,
                        result           = output
                    };
#if UNITY_JOBS
                    jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                    jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                }
            }
            else
            if (inputType == GLTFComponentType.Byte)
            {
                if (normalized)
                {
                    if (ensureUnitLength)
                    {
                        var job = new ConvertNormalsInt8ToFloatInterleavedNormalizedJob {
                            input            = (sbyte *)input,
                            inputByteStride  = (inputByteStride > 0) ? inputByteStride : 3,
                            outputByteStride = outputByteStride,
                            result           = output
                        };
    #if UNITY_JOBS
                        jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
    #else
                        jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
    #endif
                    }
                    else
                    {
                        var job = new ConvertVector3Int8ToFloatInterleavedNormalizedJob()
                        {
                            input            = (sbyte *)input,
                            inputByteStride  = (inputByteStride > 0) ? inputByteStride : 3,
                            outputByteStride = outputByteStride,
                            result           = output
                        };
#if UNITY_JOBS
                        jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                        jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                    }
                }
                else
                {
                    // TODO: test positions. did not have test files
                    var job = new ConvertPositionsInt8ToFloatInterleavedJob {
                        inputByteStride  = inputByteStride > 0 ? inputByteStride : 3,
                        input            = (sbyte *)input,
                        outputByteStride = outputByteStride,
                        result           = output
                    };
#if UNITY_JOBS
                    jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                    jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                }
            }
            else
            if (inputType == GLTFComponentType.UnsignedByte)
            {
                // TODO: test. did not have test files
                if (normalized)
                {
                    var job = new ConvertPositionsUInt8ToFloatInterleavedNormalizedJob {
                        input            = (byte *)input,
                        inputByteStride  = (inputByteStride > 0) ? inputByteStride : 3,
                        outputByteStride = outputByteStride,
                        result           = output
                    };
#if UNITY_JOBS
                    jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                    jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                }
                else
                {
                    var job = new ConvertPositionsUInt8ToFloatInterleavedJob {
                        input            = (byte *)input,
                        inputByteStride  = (inputByteStride > 0) ? inputByteStride : 3,
                        outputByteStride = outputByteStride,
                        result           = output
                    };
#if UNITY_JOBS
                    jobHandle = job.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                    jobHandle = job.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                }
            }
            else
            {
                Debug.LogError("Unknown componentType");
                jobHandle = null;
            }
            Profiler.EndSample();
            return(jobHandle);
        }
コード例 #27
0
        protected unsafe JobHandle?GetTangentsJob(
            void *input,
            int count,
            GLTFComponentType inputType,
            int inputByteStride,
            float4 *output,
            int outputByteStride,
            bool normalized = false
            )
        {
            Profiler.BeginSample("GetTangentsJob");
            JobHandle?jobHandle;

            switch (inputType)
            {
            case GLTFComponentType.Float: {
                var jobTangent = new ConvertTangentsFloatToFloatInterleavedJob {
                    inputByteStride  = inputByteStride > 0 ? inputByteStride : 16,
                    input            = (byte *)input,
                    outputByteStride = outputByteStride,
                    result           = output
                };
#if UNITY_JOBS
                jobHandle = jobTangent.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                jobHandle = jobTangent.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                break;
            }

            case GLTFComponentType.Short: {
                Assert.IsTrue(normalized);
                var jobTangent = new ConvertTangentsInt16ToFloatInterleavedNormalizedJob {
                    inputByteStride  = inputByteStride > 0 ? inputByteStride : 8,
                    input            = (short *)input,
                    outputByteStride = outputByteStride,
                    result           = output
                };
#if UNITY_JOBS
                jobHandle = jobTangent.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                jobHandle = jobTangent.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                break;
            }

            case GLTFComponentType.Byte: {
                Assert.IsTrue(normalized);
                var jobTangent = new ConvertTangentsInt8ToFloatInterleavedNormalizedJob {
                    inputByteStride  = inputByteStride > 0 ? inputByteStride : 4,
                    input            = (sbyte *)input,
                    outputByteStride = outputByteStride,
                    result           = output
                };
#if UNITY_JOBS
                jobHandle = jobTangent.ScheduleBatch(count, GltfImport.DefaultBatchCount);
#else
                jobHandle = jobTangent.Schedule(count, GltfImport.DefaultBatchCount);
#endif
                break;
            }

            default:
                logger?.Error(LogCode.TypeUnsupported, "Tangent", inputType.ToString());
                jobHandle = null;
                break;
            }

            Profiler.EndSample();
            return(jobHandle);
        }
コード例 #28
0
        public static void Main(string[] args)
        {
            Server = new MultiplayerServer();

            Server.AddLogProvider(new ConsoleLogProvider(LogCategory.Notice | LogCategory.Warning | LogCategory.Error | LogCategory.Debug));
#if DEBUG
            Server.AddLogProvider(new FileLogProvider(new StreamWriter("packets.log", false), LogCategory.Packets));
#endif

            ServerConfiguration = Configuration.LoadConfiguration <ServerConfiguration>("config.yaml");

            var buckets = ServerConfiguration.Debug?.Profiler?.Buckets?.Split(',');
            if (buckets != null)
            {
                foreach (var bucket in buckets)
                {
                    Profiler.EnableBucket(bucket.Trim());
                }
            }

            if (ServerConfiguration.Debug.DeleteWorldOnStartup)
            {
                if (Directory.Exists("world"))
                {
                    Directory.Delete("world", true);
                }
            }
            if (ServerConfiguration.Debug.DeletePlayersOnStartup)
            {
                if (Directory.Exists("players"))
                {
                    Directory.Delete("players", true);
                }
            }
            IWorld world;
            try
            {
                world = World.LoadWorld("world");
                Server.AddWorld(world);
            }
            catch
            {
                world = new World("default", new StandardGenerator());
                world.BlockRepository = Server.BlockRepository;
                world.Save("world");
                Server.AddWorld(world);
                Server.Log(LogCategory.Notice, "Generating world around spawn point...");
                for (int x = -5; x < 5; x++)
                {
                    for (int z = -5; z < 5; z++)
                    {
                        world.GetChunk(new Coordinates2D(x, z));
                    }
                    int progress = (int)(((x + 5) / 10.0) * 100);
                    if (progress % 10 == 0)
                    {
                        Server.Log(LogCategory.Notice, "{0}% complete", progress + 10);
                    }
                }
                Server.Log(LogCategory.Notice, "Simulating the world for a moment...");
                for (int x = -5; x < 5; x++)
                {
                    for (int z = -5; z < 5; z++)
                    {
                        var chunk = world.GetChunk(new Coordinates2D(x, z));
                        for (byte _x = 0; _x < Chunk.Width; _x++)
                        {
                            for (byte _z = 0; _z < Chunk.Depth; _z++)
                            {
                                for (int _y = 0; _y < chunk.GetHeight(_x, _z); _y++)
                                {
                                    var coords   = new Coordinates3D(x + _x, _y, z + _z);
                                    var data     = world.GetBlockData(coords);
                                    var provider = world.BlockRepository.GetBlockProvider(data.ID);
                                    provider.BlockUpdate(data, data, Server, world);
                                }
                            }
                        }
                    }
                    int progress = (int)(((x + 5) / 10.0) * 100);
                    if (progress % 10 == 0)
                    {
                        Server.Log(LogCategory.Notice, "{0}% complete", progress + 10);
                    }
                }
            }
            world.Save();
            CommandManager              = new CommandManager();
            Server.ChatMessageReceived += HandleChatMessageReceived;
            Server.Start(new IPEndPoint(IPAddress.Parse(ServerConfiguration.ServerAddress), ServerConfiguration.ServerPort));
            Console.CancelKeyPress += HandleCancelKeyPress;
            while (true)
            {
                Thread.Sleep(1000 * ServerConfiguration.WorldSaveInterval);
                foreach (var w in Server.Worlds)
                {
                    w.Save();
                }
            }
        }
コード例 #29
0
 private List<Guid> GetPerUserUnviewedIds(Profiler profiler)
 {
     return GetPerUserUnviewedIds(profiler.User);
 }
コード例 #30
0
        protected override IList <TreeViewItem> BuildRows(TreeViewItem root)
        {
            m_Rows.Clear();

            // find all issues matching the filters and make an array out of them
            Profiler.BeginSample("IssueTable.Match");
            var filteredItems = m_TreeViewItemIssues.Where(item =>
            {
                return(m_Filter.Match(item.ProjectIssue));
            }).ToArray();

            Profiler.EndSample();

            m_NumMatchingIssues = filteredItems.Length;
            if (m_NumMatchingIssues == 0)
            {
                m_Rows.Add(new TreeViewItem(0, 0, "No items"));
                return(m_Rows);
            }

            Profiler.BeginSample("IssueTable.BuildRows");
            if (m_Desc.groupByDescriptor && !hasSearch && !m_FlatView)
            {
                var descriptors = filteredItems.Select(i => i.ProblemDescriptor).Distinct();
                foreach (var descriptor in descriptors)
                {
                    var group = m_TreeViewItemGroups.Find(g => g.ProblemDescriptor.Equals(descriptor));
                    m_Rows.Add(group);

                    var groupIsExpanded = state.expandedIDs.Contains(group.id);
                    var children        = filteredItems.Where(item => item.ProblemDescriptor.Equals(descriptor));

                    group.displayName = string.Format("{0} ({1})", descriptor.description, children.Count());
                    if (group.children != null)
                    {
                        group.children.Clear();
                    }

                    foreach (var child in children)
                    {
                        if (groupIsExpanded)
                        {
                            m_Rows.Add(child);
                        }
                        group.AddChild(child);
                    }
                }
            }
            else
            {
                foreach (var item in filteredItems)
                {
                    m_Rows.Add(item);
                }
            }
            SortIfNeeded(m_Rows);

            Profiler.EndSample();

            return(m_Rows);
        }
コード例 #31
0
ファイル: TypeCalculator.cs プロジェクト: reshadi2/mcjs
 internal static mdr.ValueTypes GetType(GuardedCast node, Profiler profiler)
 {
   var expType = node.Expression.ValueType;
   if (expType != mdr.ValueTypes.DValueRef && JSRuntime.Instance.Configuration.EnableGuardElimination)
       node.IsRequired = false;
   if (expType == mdr.ValueTypes.DValueRef && JSRuntime.Instance.Configuration.EnableSpeculativeJIT && profiler != null)
   {
     var nodeProfile = profiler.GetNodeProfile(node) as GuardNodeProfile;
     var speculativeType = nodeProfile != null ? nodeProfile.GetHotPrimitiveType() : mdr.ValueTypes.DValueRef;
     if (speculativeType != mdr.ValueTypes.DValueRef)
     {
       expType = speculativeType;
     }
     if (JSRuntime.Instance.Configuration.EnableGuardElimination) node.IsRequired = true;
   }
   return expType;
 }
コード例 #32
0
 partial void PrepareBuffer()
 {
     Profiler.BeginSample("Editor Only");
     buffer.name = SampleName = _camera.name;
     Profiler.EndSample();
 }
コード例 #33
0
ファイル: AstGenerator.cs プロジェクト: tnachen/ironruby
        internal AstGenerator(CompilationMode mode, CompilerContext/*!*/ context, SourceSpan span, string name, bool generator, bool print)
            : this(name, generator, null, print) {
            Assert.NotNull(context);
            _context = context;
            _binderState = new BinderState(Binder);
            _document = _context.SourceUnit.Document;

            LanguageContext pc = context.SourceUnit.LanguageContext;
            switch (mode) {
                case CompilationMode.Collectable: _globals = new ArrayGlobalAllocator(pc); break;
                case CompilationMode.Lookup: _globals = new DictionaryGlobalAllocator(); break;
                case CompilationMode.ToDisk: _globals = new SavableGlobalAllocator(pc); break;
                case CompilationMode.Uncollectable: _globals = new StaticGlobalAllocator(pc, name); break;
            }

            PythonOptions po = (pc.Options as PythonOptions);
            Assert.NotNull(po);
            if (po.EnableProfiler && mode != CompilationMode.ToDisk) {
                _profiler = Profiler.GetProfiler(PythonContext);
                if (mode == CompilationMode.Lookup) {
                    _profilerName = NameForExec;
                }
            }
        }
コード例 #34
0
        public static IEnumerator EnforceAudioSourceLimitsEnumerator(GameObject currentAvatar, System.Action <AudioSource> onFound)
        {
            if (currentAvatar == null)
            {
                yield break;
            }

            Queue <GameObject> children = new Queue <GameObject>();

            if (currentAvatar != null)
            {
                children.Enqueue(currentAvatar.gameObject);
            }

            while (children.Count > 0)
            {
                if (Time.frameCount > _enforceAudioSourcesFrameNumber)
                {
                    _enforceAudioSourcesFrameNumber        = Time.frameCount;
                    _enforceAudioSourcesProcessedThisFrame = 0;
                }

                if (_enforceAudioSourcesProcessedThisFrame > ENFORCE_AUDIO_SOURCE_GAMEOBJECTS_PER_FRAME)
                {
                    yield return(null);
                }

                Profiler.BeginSample("EnforceAudioSourceLimitsEnumerator");
                _enforceAudioSourcesProcessedThisFrame++;

                GameObject child = children.Dequeue();
                if (child == null)
                {
                    Profiler.EndSample();
                    continue;
                }

                int childCount = child.transform.childCount;
                for (int idx = 0; idx < childCount; ++idx)
                {
                    children.Enqueue(child.transform.GetChild(idx).gameObject);
                }

#if VRC_CLIENT
                if (child.GetComponent <USpeaker>() != null)
                {
                    Profiler.EndSample();
                    continue;
                }
#endif

                AudioSource[] sources = child.transform.GetComponents <AudioSource>();
                if (sources != null && sources.Length > 0)
                {
                    AudioSource audioSource = sources[0];
                    if (audioSource == null)
                    {
                        Profiler.EndSample();
                        continue;
                    }


#if VRC_CLIENT
                    audioSource.outputAudioMixerGroup = VRCAudioManager.GetAvatarGroup();
                    audioSource.priority = Mathf.Clamp(audioSource.priority, 200, 255);
#else
                    ProcessSpatialAudioSources(audioSource);
#endif //!VRC_CLIENT

                    onFound(audioSource);

                    if (sources.Length > 1)
                    {
                        Debug.LogError("Disabling extra AudioSources on GameObject(" + child.name + "). Only one is allowed per GameObject.");
                        for (int i = 1; i < sources.Length; i++)
                        {
                            if (sources[i] == null)
                            {
                                Profiler.EndSample();
                                continue;
                            }

#if VRC_CLIENT
                            sources[i].enabled = false;
                            sources[i].clip    = null;
#else
                            ValidationUtils.RemoveComponent(sources[i]);
#endif //!VRC_CLIENT
                        }
                    }
                }

                Profiler.EndSample();
            }
        }
コード例 #35
0
 public virtual Tensor[] PeekConstants(string layerName)
 {
     Profiler.BeginSample("Barracuda.PeekConstants");
     return(m_Vars.PeekConstants(layerName));
 }
コード例 #36
0
        public static IEnumerator EnforceAvatarStationLimitsEnumerator(GameObject currentAvatar, System.Action <VRC.SDKBase.VRC_Station> onFound)
        {
            Queue <GameObject> children = new Queue <GameObject>();

            children.Enqueue(currentAvatar.gameObject);

            int  stationCount = 0;
            uint objectsProcessedThisFrame = 0;

            while (children.Count > 0)
            {
                if (Time.frameCount > _enforceAvatarStationsFrameNumber)
                {
                    _enforceAvatarStationsFrameNumber        = Time.frameCount;
                    _enforceAvatarStationsProcessedThisFrame = 0;
                }

                if (_enforceAvatarStationsProcessedThisFrame > ENFORCE_STATIONS_GAMEOBJECTS_PER_FRAME)
                {
                    yield return(null);
                }

                Profiler.BeginSample("EnforceAvatarStationLimitsEnumerator");
                _enforceAvatarStationsProcessedThisFrame++;

                GameObject child = children.Dequeue();
                if (child == null)
                {
                    Profiler.EndSample();
                    continue;
                }

                int childCount = child.transform.childCount;
                for (int idx = 0; idx < childCount; ++idx)
                {
                    children.Enqueue(child.transform.GetChild(idx).gameObject);
                }

                VRC.SDKBase.VRC_Station[] stations = child.transform.GetComponents <VRC.SDKBase.VRC_Station>();
                if (stations != null && stations.Length > 0)
                {
                    foreach (VRC.SDKBase.VRC_Station station in stations)
                    {
                        if (station == null)
                        {
                            Profiler.EndSample();
                            continue;
                        }

#if VRC_CLIENT
                        VRC_StationInternal stationInternal = station.transform.GetComponent <VRC_StationInternal>();
#endif
                        if (stationCount < MAX_STATIONS_PER_AVATAR)
                        {
                            bool markedForDestruction = false;
                            // keep this station, but limit it
                            if (station.disableStationExit)
                            {
                                Debug.LogError("[" + currentAvatar.name + "]==> Stations on avatars cannot disable station exit. Re-enabled.");
                                station.disableStationExit = false;
                            }

                            if (station.stationEnterPlayerLocation != null)
                            {
                                if (Vector3.Distance(station.stationEnterPlayerLocation.position, station.transform.position) > MAX_STATION_LOCATION_DISTANCE)
                                {
#if VRC_CLIENT
                                    markedForDestruction = true;
                                    Debug.LogError("[" + currentAvatar.name + "]==> Station enter location is too far from station (max dist=" + MAX_STATION_LOCATION_DISTANCE + "). Station disabled.");
#else
                                    Debug.LogError("Station enter location is too far from station (max dist=" + MAX_STATION_LOCATION_DISTANCE + "). Station will be disabled at runtime.");
#endif
                                }
                                if (Vector3.Distance(station.stationExitPlayerLocation.position, station.transform.position) > MAX_STATION_LOCATION_DISTANCE)
                                {
#if VRC_CLIENT
                                    markedForDestruction = true;
                                    Debug.LogError("[" + currentAvatar.name + "]==> Station exit location is too far from station (max dist=" + MAX_STATION_LOCATION_DISTANCE + "). Station disabled.");
#else
                                    Debug.LogError("Station exit location is too far from station (max dist=" + MAX_STATION_LOCATION_DISTANCE + "). Station will be disabled at runtime.");
#endif
                                }

                                if (markedForDestruction)
                                {
#if VRC_CLIENT
                                    ValidationUtils.RemoveComponent(station);
                                    if (stationInternal != null)
                                    {
                                        ValidationUtils.RemoveComponent(stationInternal);
                                    }
#endif
                                }
                                else
                                {
                                    if (onFound != null)
                                    {
                                        onFound(station);
                                    }
                                }
                            }
                        }
                        else
                        {
#if VRC_CLIENT
                            Debug.LogError("[" + currentAvatar.name + "]==> Removing station over limit of " + MAX_STATIONS_PER_AVATAR);
                            ValidationUtils.RemoveComponent(station);
                            if (stationInternal != null)
                            {
                                ValidationUtils.RemoveComponent(stationInternal);
                            }
#else
                            Debug.LogError("Too many stations on avatar(" + currentAvatar.name + "). Maximum allowed=" + MAX_STATIONS_PER_AVATAR + ". Extra stations will be removed at runtime.");
#endif
                        }

                        stationCount++;
                    }
                }
                Profiler.EndSample();

                if (objectsProcessedThisFrame < ENFORCE_STATIONS_GAMEOBJECTS_PER_FRAME)
                {
                    continue;
                }

                objectsProcessedThisFrame = 0;
                yield return(null);
            }
        }
コード例 #37
0
ファイル: MechJebCore.cs プロジェクト: DoctorDavinci/MechJeb2
        public void Update()
        {
            if (this != vessel.GetMasterMechJeb() || (!FlightGlobals.ready && HighLogic.LoadedSceneIsFlight) || !ready)
            {
                return;
            }
            Profiler.BeginSample("MechJebCore.Update");

            if (Input.GetKeyDown(KeyCode.V) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)))
            {
                MechJebModuleCustomWindowEditor windowEditor = GetComputerModule <MechJebModuleCustomWindowEditor>();
                if (windowEditor != null)
                {
                    windowEditor.CreateWindowFromSharingString(MuUtils.SystemClipboard);
                }
            }

            //periodically save settings in case we quit unexpectedly
            if (HighLogic.LoadedSceneIsEditor || (vessel != null && vessel.isActiveVessel))
            {
                if (Time.time > lastSettingsSaveTime + 5)
                {
                    //Debug.Log("MechJeb doing periodic settings save");
                    OnSave(null);
                    lastSettingsSaveTime = Time.time;
                }
            }

            if (ResearchAndDevelopment.Instance != null && unorderedComputerModules.Any(a => !a.unlockChecked))
            {
                foreach (ComputerModule module in GetComputerModules <ComputerModule>())
                {
                    try
                    {
                        module.UnlockCheck();
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in UnlockCheck: " + e);
                    }
                }
            }

            Profiler.BeginSample("OnMenuUpdate");
            GetComputerModule <MechJebModuleMenu>().OnMenuUpdate(); // Allow the menu movement, even while in Editor
            Profiler.EndSample();

            if (vessel == null)
            {
                Profiler.EndSample();
                return; //don't run ComputerModules' OnUpdate in editor
            }

            foreach (ComputerModule module in GetComputerModules <ComputerModule>())
            {
                Profiler.BeginSample(module.profilerName);
                try
                {
                    if (module.enabled)
                    {
                        module.OnUpdate();
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnUpdate: " + e);
                }
                Profiler.EndSample();
            }
            Profiler.EndSample();
        }
コード例 #38
0
 static public int GetWorldCorners_s(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 1)
         {
             UnityEngine.Camera a1;
             checkType(l, 1, out a1);
             var ret = NGUITools.GetWorldCorners(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 1, typeof(UnityEngine.Camera), typeof(float)))
         {
             UnityEngine.Camera a1;
             checkType(l, 1, out a1);
             System.Single a2;
             checkType(l, 2, out a2);
             var ret = NGUITools.GetWorldCorners(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 1, typeof(UnityEngine.Camera), typeof(UnityEngine.Transform)))
         {
             UnityEngine.Camera a1;
             checkType(l, 1, out a1);
             UnityEngine.Transform a2;
             checkType(l, 2, out a2);
             var ret = NGUITools.GetWorldCorners(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 3)
         {
             UnityEngine.Camera a1;
             checkType(l, 1, out a1);
             System.Single a2;
             checkType(l, 2, out a2);
             UnityEngine.Transform a3;
             checkType(l, 3, out a3);
             var ret = NGUITools.GetWorldCorners(a1, a2, a3);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function GetWorldCorners to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
コード例 #39
0
ファイル: DebugMenuManager.cs プロジェクト: pdxparrot/ggj2019
        private void RenderWindowContents()
        {
            if (null == _currentNode)
            {
                GUILayout.Label($"Random seed: {PartyParrotManager.Instance.RandomSeed}");

                GUILayout.BeginVertical("Rendering:", GUI.skin.box);
                GUILayout.Label($"Frame Time: {(int)(_lastFrameTime * 1000.0f)} ms");
                GUILayout.Label($"Min Frame Time: {(int)(_minFrameTime * 1000.0f)} ms");
                GUILayout.Label($"Max Frame Time: {(int)(_maxFrameTime * 1000.0f)} ms");
                GUILayout.Label($"Average FPS: {(int)AverageFPS}");
                GUILayout.EndVertical();

                GUILayout.BeginVertical("Memory:", GUI.skin.box);
                GUILayout.Label($"Allocated: {Profiler.GetTotalAllocatedMemoryLong() / 1048576.0f:0.00}MB");
                GUILayout.Label($"Reserved: {Profiler.GetTotalReservedMemoryLong() / 1048576.0f:0.00}MB");
                GUILayout.Label($"Unused: {Profiler.GetTotalUnusedReservedMemoryLong() / 1048576.0f:0.00}MB");
                GUILayout.Label($"Mono Heap: {Profiler.GetMonoHeapSizeLong() / 1048576.0f:0.00}MB");
                GUILayout.Label($"Mono Used: {Profiler.GetMonoUsedSizeLong() / 1048576.0f:0.00}MB");
                GUILayout.EndVertical();

                _windowScrollPos = GUILayout.BeginScrollView(_windowScrollPos);
                foreach (DebugMenuNode node in _nodes)
                {
                    node.RenderNode();
                }
                GUILayout.EndScrollView();

#if UNITY_EDITOR
                GUILayout.BeginHorizontal();
                if (GUIUtils.LayoutButton("Break"))
                {
                    Debug.Break();
                }

                _frameStepping = GUILayout.Toggle(_frameStepping, "Enable Frame Stepping (Manually disable in the Hierarchy)");
                // TODO: should we force select the manager for the user?
                GUILayout.EndHorizontal();
#endif

                GUILayout.BeginHorizontal();
                // TODO: reloading doesn't work right

                /*if(GUIUtils.LayoutButton("Reload")) {
                 *  Scenes.SceneManager.Instance.ReloadMainScene();
                 * }*/

                if (GUIUtils.LayoutButton("Quit"))
                {
                    UnityUtil.Quit();
                }

                if (GUIUtils.LayoutButton("Reset PlayerPrefs"))
                {
                    PlayerPrefs.DeleteAll();
                }
                GUILayout.EndHorizontal();
            }
            else
            {
                _windowScrollPos = GUILayout.BeginScrollView(_windowScrollPos);
                _currentNode.RenderContents();
                GUILayout.EndScrollView();

                if (GUIUtils.LayoutButton("Back"))
                {
                    SetCurrentNode(_currentNode.Parent);
                }
            }
        }
コード例 #40
0
 static public int AddChild_s(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         if (matchType(l, argc, 1, typeof(UnityEngine.GameObject)))
         {
             UnityEngine.GameObject a1;
             checkType(l, 1, out a1);
             var ret = NGUITools.AddChild(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 1, typeof(UnityEngine.GameObject)))
         {
             UnityEngine.GameObject a1;
             checkType(l, 1, out a1);
             var ret = NGUITools.AddChild <UnityEngine.Component>(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 1, typeof(UnityEngine.GameObject), typeof(bool)))
         {
             UnityEngine.GameObject a1;
             checkType(l, 1, out a1);
             System.Boolean a2;
             checkType(l, 2, out a2);
             var ret = NGUITools.AddChild(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 1, typeof(UnityEngine.GameObject), typeof(UnityEngine.GameObject)))
         {
             UnityEngine.GameObject a1;
             checkType(l, 1, out a1);
             UnityEngine.GameObject a2;
             checkType(l, 2, out a2);
             var ret = NGUITools.AddChild(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 1, typeof(UnityEngine.GameObject), typeof(bool)))
         {
             UnityEngine.GameObject a1;
             checkType(l, 1, out a1);
             System.Boolean a2;
             checkType(l, 2, out a2);
             var ret = NGUITools.AddChild <UnityEngine.Component>(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function AddChild to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
コード例 #41
0
ファイル: helpers.cs プロジェクト: kig/filezoo
 /** DESTRUCTIVE, ASYNC */
 public static ImageSurface GetThumbnail(string path)
 {
     try {
       Profiler pr = new Profiler ("GetThumbnail", 500);
       ImageSurface thumb = null;
       string thumbPath;
       if (path.StartsWith(ThumbDir)) {
     thumbPath = path;
       } else {
     thumbPath = NormalThumbDir + DirSepS + ThumbnailHash (path) + ".png";
     if (FileExists (thumbPath) && (LastModified(path) >= LastModified(thumbPath)))
       Trash(thumbPath);
       }
       pr.Time ("ThumbnailHash");
       if (!FileExists(thumbPath)) {
     if (!FileExists(ThumbDir))
       new UnixDirectoryInfo(ThumbDir).Create ();
     if (!FileExists(NormalThumbDir))
       new UnixDirectoryInfo(NormalThumbDir).Create ();
     if (CreateThumbnail(path, thumbPath, thumbSize)) {
       pr.Time ("create thumbnail");
       thumb = new ImageSurface (thumbPath);
     }
       } else {
     thumb = new ImageSurface (thumbPath);
     if (thumb.Width > thumbSize || thumb.Height > thumbSize) {
       ImageSurface nthumb = ScaleDownSurface (thumb, thumbSize);
       thumb.Destroy ();
       thumb.Destroy ();
       thumb = nthumb;
     }
       }
       if (thumb == null || thumb.Width < 1 || thumb.Height < 1) {
     if (FileExists(thumbPath)) Trash(thumbPath);
     throw new ArgumentException (String.Format("Failed to thumbnail {0}",path), "path");
       }
       pr.Time ("load as ImageSurface");
       return thumb;
     } catch (Exception e) {
       LogError ("Thumbnailing failed for {0}: {1}", path, e);
       ImageSurface thumb = new ImageSurface (Format.ARGB32, 1, 1);
       using (Context cr = new Context(thumb)) {
     cr.Color = new Color (1,0,0);
     cr.Rectangle (0,0,2,2);
     cr.Fill ();
       }
       return thumb;
     }
 }
コード例 #42
0
		private static string ResultsJson(IHttpResponse httpRes, Profiler profiler)
		{
			httpRes.ContentType = "application/json";
			return Profiler.ToJson(profiler);
		}
コード例 #43
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            bool isLitView = true;

#if UNITY_EDITOR
            if (renderingData.cameraData.isSceneViewCamera)
            {
                isLitView = UnityEditor.SceneView.currentDrawingSceneView.sceneLighting;
            }

            if (renderingData.cameraData.camera.cameraType == CameraType.Preview)
            {
                isLitView = false;
            }

            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;


            bool isSceneLit = Light2D.IsSceneLit(camera);
            if (isSceneLit)
            {
                RendererLighting.Setup(renderingData, m_Renderer2DData);

                CommandBuffer cmd = CommandBufferPool.Get("Render 2D Lighting");
                cmd.Clear();

                RendererLighting.CreateNormalMapRenderTexture(cmd);

                cmd.SetGlobalFloat("_HDREmulationScale", m_Renderer2DData.hdrEmulationScale);
                cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_Renderer2DData.hdrEmulationScale);
                cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
                cmd.SetGlobalColor("_RendererColor", Color.white);
                RendererLighting.SetShapeLightShaderGlobals(cmd);

                context.ExecuteCommandBuffer(cmd);

                DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);
                DrawingSettings normalsDrawSettings  = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

                SortingSettings sortSettings = combinedDrawSettings.sortingSettings;
                GetTransparencySortingMode(camera, ref sortSettings);
                combinedDrawSettings.sortingSettings = sortSettings;
                combinedDrawSettings.sortingSettings = sortSettings;

                const int blendStylesCount   = 4;
                bool[]    hasBeenInitialized = new bool[blendStylesCount];
                for (int i = 0; i < s_SortingLayers.Length; i++)
                {
                    // Some renderers override their sorting layer value with short.MinValue or short.MaxValue.
                    // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue.
                    // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue.
                    short layerValue = (short)s_SortingLayers[i].value;
                    var   lowerBound = (i == 0) ? short.MinValue : layerValue;
                    var   upperBound = (i == s_SortingLayers.Length - 1) ? short.MaxValue : layerValue;
                    filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound);

                    int layerToRender = s_SortingLayers[i].id;

                    Light2D.LightStats lightStats;
                    lightStats = Light2D.GetLightStatsByLayer(layerToRender, camera);

                    cmd.Clear();
                    for (int blendStyleIndex = 0; blendStyleIndex < blendStylesCount; blendStyleIndex++)
                    {
                        uint blendStyleMask = (uint)(1 << blendStyleIndex);
                        bool blendStyleUsed = (lightStats.blendStylesUsed & blendStyleMask) > 0;

                        if (blendStyleUsed && !hasBeenInitialized[blendStyleIndex])
                        {
                            RendererLighting.CreateBlendStyleRenderTexture(cmd, blendStyleIndex);
                            hasBeenInitialized[blendStyleIndex] = true;
                        }

                        RendererLighting.EnableBlendStyle(cmd, blendStyleIndex, blendStyleUsed);
                    }
                    context.ExecuteCommandBuffer(cmd);

                    // Start Rendering
                    if (lightStats.totalNormalMapUsage > 0)
                    {
                        RendererLighting.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings, depthAttachment);
                    }

                    cmd.Clear();
                    if (lightStats.totalLights > 0)
                    {
                        RendererLighting.RenderLights(camera, cmd, layerToRender, lightStats.blendStylesUsed);
                    }
                    else
                    {
                        RendererLighting.ClearDirtyLighting(cmd, lightStats.blendStylesUsed);
                    }

                    CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                    context.ExecuteCommandBuffer(cmd);

                    Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers");
                    context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings);
                    Profiler.EndSample();

                    if (lightStats.totalVolumetricUsage > 0)
                    {
                        cmd.Clear();
                        RendererLighting.RenderLightVolumes(camera, cmd, layerToRender, colorAttachment, depthAttachment, lightStats.blendStylesUsed);
                        context.ExecuteCommandBuffer(cmd);
                        cmd.Clear();
                    }
                }

                cmd.Clear();
                Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
                RendererLighting.ReleaseRenderTextures(cmd);
                Profiler.EndSample();

                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);

                filterSettings.sortingLayerRange = SortingLayerRange.all;
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
            else
            {
                CommandBuffer   cmd = CommandBufferPool.Get("Render Unlit");
                DrawingSettings unlitDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);

                CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                cmd.SetGlobalTexture("_ShapeLightTexture0", Texture2D.blackTexture);
                cmd.SetGlobalTexture("_ShapeLightTexture1", Texture2D.blackTexture);
                cmd.SetGlobalTexture("_ShapeLightTexture2", Texture2D.blackTexture);
                cmd.SetGlobalTexture("_ShapeLightTexture3", Texture2D.blackTexture);
                cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
                cmd.SetGlobalColor("_RendererColor", Color.white);
                cmd.EnableShaderKeyword("USE_SHAPE_LIGHT_TYPE_0");
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);

                Profiler.BeginSample("Render Sprites Unlit");
                context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings);
                Profiler.EndSample();

                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
        }
コード例 #44
0
 public static void EndSample()
 {
     Profiler.EndSample();
 }
コード例 #45
0
ファイル: AstGenerator.cs プロジェクト: jxnmaomao/ironruby
        /// <summary>
        /// Creates a new AstGenerator for top-level (module) code.
        /// </summary>
        internal AstGenerator(CompilationMode mode, CompilerContext/*!*/ context, SourceSpan span, string name, bool generator, bool print)
            : this(name, generator, null, print) {
            Assert.NotNull(context);
            _context = context;
            _pythonContext = (PythonContext)context.SourceUnit.LanguageContext;
            _document = _context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid);
            _funcCodeExpr.Code = _functionCode;

            switch (mode) {
                case CompilationMode.Collectable: _globals = new ArrayGlobalAllocator(_pythonContext); break;
                case CompilationMode.Lookup: _globals = new DictionaryGlobalAllocator(); break;
                case CompilationMode.ToDisk: _globals = new SavableGlobalAllocator(_pythonContext); break;
                case CompilationMode.Uncollectable: _globals = new SharedGlobalAllocator(_pythonContext); break;
            }

            PythonOptions po = (_pythonContext.Options as PythonOptions);
            Assert.NotNull(po);
            if (po.EnableProfiler && mode != CompilationMode.ToDisk) {
                _profiler = Profiler.GetProfiler(PyContext);
                if (mode == CompilationMode.Lookup) {
                    _profilerName = NameForExec;
                }
            }
        }
コード例 #46
0
        private void Expose(Vector3Int hotspotPosition, Vector3Int atLocalPosition)
        {
            Profiler.BeginSample("ExposureInit");
            var isSideExposure = hotspotPosition != atLocalPosition;
            //calculate world position
            var hotspotWorldPosition = MatrixManager.LocalToWorldInt(hotspotPosition, MatrixManager.Get(matrix));
            var atWorldPosition      = MatrixManager.LocalToWorldInt(atLocalPosition, MatrixManager.Get(matrix));

            if (!hotspots.ContainsKey(hotspotPosition))
            {
                Logger.LogError("Hotspot position key was not found in the hotspots dictionary", Category.Atmos);
                return;
            }


            //update fire exposure, reusing it to avoid creating GC.
            applyExposure.Update(isSideExposure, hotspots[hotspotPosition], hotspotWorldPosition, atLocalPosition,
                                 atWorldPosition);
            Profiler.EndSample();
            if (isSideExposure)
            {
                Profiler.BeginSample("SideExposure");
                //side exposure logic

                //already exposed by a different hotspot
                if (hotspots.ContainsKey(atLocalPosition))
                {
                    Profiler.EndSample();
                    return;
                }

                var metadata = metaDataLayer.Get(atLocalPosition);
                if (!metadata.IsOccupied)
                {
                    //atmos can pass here, so no need to check side exposure (nothing to brush up against)
                    Profiler.EndSample();
                    return;
                }

                //only expose to atmos impassable objects, since those are the things the flames would
                //actually brush up against
                matrix.ForEachRegisterTileSafe(applyExposure, atLocalPosition, true);
                //expose the tiles there
                foreach (var tilemapDamage in tilemapDamages)
                {
                    tilemapDamage.OnExposed(applyExposure.FireExposure);
                }

                Profiler.EndSample();
            }
            else
            {
                Profiler.BeginSample("DirectExposure");
                //direct exposure logic
                matrix.ForEachRegisterTileSafe(applyExposure, atLocalPosition, true);
                //expose the tiles
                foreach (var tilemapDamage in tilemapDamages)
                {
                    tilemapDamage.OnExposed(applyExposure.FireExposure);
                }

                Profiler.EndSample();
            }
        }
コード例 #47
0
        public override Primitive?CreatePrimitive()
        {
            Profiler.BeginSample("CreatePrimitive");
            Profiler.BeginSample("Job Complete");
            jobHandle.Complete();
            Profiler.EndSample();
            var msh = new UnityEngine.Mesh();

            if (positions.Length > 65536)
            {
#if UNITY_2017_3_OR_NEWER
                msh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
#else
                throw new System.Exception("Meshes with more than 65536 vertices are only supported from Unity 2017.3 onwards.");
#endif
            }
            msh.name = mesh.name;
            Profiler.BeginSample("SetVertices");
            msh.vertices = positions;
            Profiler.EndSample();

            Profiler.BeginSample("SetIndices");
            msh.subMeshCount = indices.Length;
            for (int i = 0; i < indices.Length; i++)
            {
                msh.SetIndices(indices[i], topology, i);
            }
            Profiler.EndSample();

            Profiler.BeginSample("SetUVs");
            if (uvs0 != null)
            {
                msh.uv = uvs0;
            }
            if (uvs1 != null)
            {
                msh.uv2 = uvs1;
            }
            Profiler.EndSample();

            Profiler.BeginSample("SetNormals");
            if (normals != null)
            {
                msh.normals = normals;
            }
            else
            if (topology == MeshTopology.Triangles || topology == MeshTopology.Quads)
            {
                msh.RecalculateNormals();
            }
            Profiler.EndSample();
            Profiler.BeginSample("SetColor");
            if (colors != null)
            {
                msh.colors = colors;
            }
            else if (colors32 != null)
            {
                msh.colors32 = colors32;
            }
            Profiler.EndSample();
            Profiler.BeginSample("SetTangents");
            if (tangents != null)
            {
                msh.tangents = tangents;
            }
            else
            if (topology == MeshTopology.Triangles || topology == MeshTopology.Quads)
            {
                // TODO: Improvement idea: by only calculating tangents, if they are actually needed
                Profiler.BeginSample("RecalculateTangents");
                msh.RecalculateTangents();
                Profiler.EndSample();
            }
            Profiler.EndSample();
            // primitives[c.primtiveIndex] = new Primitive(msh,c.primitive.material);
            // resources.Add(msh);

            Profiler.BeginSample("Dispose");
            Dispose();
            Profiler.EndSample();
            Profiler.EndSample();
            return(new Primitive(msh, materials));
        }
コード例 #48
0
        private void Update()
        {
            #region wind

            Profiler.BeginSample("Wind");

            int count = winds.Count;
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    if (winds.TryDequeue(out var windyNode))
                    {
                        foreach (var pushable in matrix.Get <PushPull>(windyNode.Position, true))
                        {
                            float correctedForce = (windyNode.WindForce * PushMultiplier) / (int)pushable.Pushable.Size;
                            if (correctedForce >= AtmosConstants.MinPushForce)
                            {
                                if (pushable.Pushable.IsTileSnap)
                                {
                                    byte pushes = (byte)Mathf.Clamp((int)correctedForce / 10, 1, 10);
                                    for (byte j = 0; j < pushes; j++)
                                    {
                                        //converting push to world coords because winddirection is in local coords
                                        pushable.QueuePush((transform.rotation * windyNode.WindDirection.To3Int()).To2Int(),
                                                           Random.Range((float)(correctedForce * 0.8), correctedForce));
                                    }
                                }
                                else
                                {
                                    pushable.Pushable.Nudge(new NudgeInfo
                                    {
                                        OriginPos      = pushable.Pushable.ServerPosition,
                                        Trajectory     = (Vector2)windyNode.WindDirection,
                                        SpinMode       = SpinMode.None,
                                        SpinMultiplier = 1,
                                        InitialSpeed   = correctedForce,
                                    });
                                }
                            }
                        }

                        windyNode.WindForce = (windyNode.WindForce * ((RollingAverageN - 1) / RollingAverageN));
                        if (windyNode.WindForce >= 0.5f * (1f / PushMultiplier))
                        {
                            winds.Enqueue(windyNode);
                        }
                        else
                        {
                            windyNode.WindForce     = 0;
                            windyNode.WindDirection = Vector2Int.zero;
                        }
                    }
                }
            }
            Profiler.EndSample();
            #endregion

            Profiler.BeginSample("HotspotModify");
            //perform the actual logic that needs to happen for adding / removing hotspots that have been
            //queued up to be added / removed
            foreach (var addedHotspot in hotspotsToAdd)
            {
                if (!hotspots.ContainsKey(addedHotspot.node.Position) &&
                    // only process the addition if it hasn't already been done, which
                    // could happen if multiple things try to add a hotspot to the same tile
                    addedHotspot.node.Hotspot == null)
                {
                    addedHotspot.node.Hotspot = addedHotspot;
                    hotspots.TryAdd(addedHotspot.node.Position, addedHotspot.node);
                    tileChangeManager.UpdateTile(
                        new Vector3Int(addedHotspot.node.Position.x, addedHotspot.node.Position.y, FIRE_FX_Z),
                        TileType.Effects, "Fire");

                    if (fireLightDictionary.ContainsKey(addedHotspot.node.Position))
                    {
                        continue;
                    }

                    var fireLightSpawn = Spawn.ServerPrefab(fireLight, addedHotspot.node.Position, transform);

                    fireLightDictionary.Add(addedHotspot.node.Position, fireLightSpawn.GameObject);
                }
            }

            foreach (var removedHotspot in hotspotsToRemove)
            {
                if (hotspots.TryGetValue(removedHotspot, out var affectedNode) &&
                    // only process the removal if it hasn't already been done, which
                    // could happen if multiple things try to remove a hotspot to the same tile)
                    affectedNode.HasHotspot)
                {
                    affectedNode.Hotspot = null;
                    tileChangeManager.RemoveTile(
                        new Vector3Int(affectedNode.Position.x, affectedNode.Position.y, FIRE_FX_Z),
                        LayerType.Effects, false);
                    hotspots.TryRemove(removedHotspot, out var value);

                    if (!fireLightDictionary.ContainsKey(affectedNode.Position))
                    {
                        continue;
                    }

                    var fireObject = fireLightDictionary[affectedNode.Position];

                    if (fireObject != null)
                    {
                        Despawn.ServerSingle(fireLightDictionary[affectedNode.Position]);
                    }

                    fireLightDictionary.Remove(affectedNode.Position);
                }
            }

            hotspotsToAdd.Clear();
            hotspotsToRemove.Clear();

            timePassed += Time.deltaTime;
            if (timePassed < 0.5)
            {
                Profiler.EndSample();
                return;
            }

            timePassed = 0;
            reactionTick++;

            //hotspot spread to adjacent tiles and damage
            foreach (MetaDataNode node in hotspots.Values)
            {
                foreach (var neighbor in node.Neighbors)
                {
                    if (neighbor != null)
                    {
                        ExposeHotspot(neighbor.Position);
                    }
                }
            }

            Profiler.EndSample();
        }
コード例 #49
0
ファイル: TypeCalculator.cs プロジェクト: reshadi2/mcjs
    public void Execute(CodeGenerationInfo cgInfo)
    {
      _cgInfo = cgInfo;
      _currProfile = _cgInfo.FuncCode.Profiler;
      GuardedCastProfile = new Dictionary<GuardedCast, Profiler>();
      VisitedWriteTemporaries = new HashSet<WriteTemporaryExpression>();

      VisitNode(cgInfo.FuncMetadata.FunctionIR.Statement);
    }
コード例 #50
0
ファイル: Profiler.cs プロジェクト: MattDBell/GCubed
 void AddChild(Profiler child)
 {
     m_children.AddLast(child);
 }
コード例 #51
0
 public Serial_parser(frame_prop frame_prop_para,MainPanel main_panel_instance_para,
     Profiler probe_profiler_para,stream_source stream_source_para)
 {
     packet_config = frame_prop_para;
     main_panel_instance = main_panel_instance_para;
     probe_profiler = probe_profiler_para;
 }
コード例 #52
0
    public void MakeMesh()
    {
        ResetSDFCache();

        Profiler.BeginSample("Making mesh");
        var meshFilter = GetComponent <MeshFilter>();

        if (meshFilter == null)
        {
            return;
        }

        if (meshFilter.sharedMesh == null)
        {
            meshFilter.sharedMesh = new Mesh();
        }

        var sharedMesh = meshFilter.sharedMesh;

        sharedMesh.Clear();

        allTriangles.Clear();
        allVertices.Clear();

        var vertCache = new Vector3[8];
        var trsCache  = new List <Vector3>();

        for (var i = 0; i < fieldSize; i++)
        {
            for (var j = 0; j < fieldSize; j++)
            {
                var ind = GetSquareIndex(i, j);
                var(localTris, vertMask) = squares[ind];

                if (localTris.Length == 0)
                {
                    continue;
                }

                FillVertices(i, j, vertCache, vertMask);

                trsCache.Clear();
                for (int k = 0; k < localTris.Length; k++)
                {
                    var p = vertCache[localTris[k]];
                    p.x /= fieldSize;
                    p.y /= fieldSize;
                    trsCache.Add(p);
                }

                allVertices.AddRange(trsCache);
                for (int k = 0; k < trsCache.Count; k++)
                {
                    allTriangles.Add(allTriangles.Count);
                }
            }
        }

        sharedMesh.SetVertices(allVertices);
        sharedMesh.SetTriangles(allTriangles, 0);
        //sharedMesh.SetColors(allVertices.Select(v => UnityEngine.Random.ColorHSV()).ToList());

        //Debug.Log("Verts: " + vertices.Count);
        //Debug.Log("Tris : " + triangles.Count);
        Profiler.EndSample();
        Profiler.enabled = false;
    }
コード例 #53
0
ファイル: AstGenerator.cs プロジェクト: tnachen/ironruby
        internal AstGenerator(AstGenerator/*!*/ parent, string name, bool generator, string profilerName)
            : this(name, generator, profilerName, false) {
            Assert.NotNull(parent);
            _context = parent.Context;
            _binderState = parent.BinderState;
            _parent = parent;
            _document = _context.SourceUnit.Document;
            _profiler = parent._profiler;

            _globals = parent._globals;
        }
コード例 #54
0
        //public List<>
        public void DoUpdate()
        {
            tempLst.Clear();
            //deal layer
            foreach (var pair in BoundsQuadTreeNode.obj2Node)
            {
                var val = pair.Key;
                if (!val.IsStatic && val._isMoved)
                {
                    val._isMoved = false;
                    tempLst.Add(val);
                }
            }

            //swap
            var temp = _prePairs;

            _prePairs = _curPairs;
            _curPairs = temp;
            _curPairs.Clear();
            ////class version 1.41ms
            Profiler.BeginSample("UpdateObj");
            foreach (var val in tempLst)
            {
                val._isMoved = false;
                var bound      = val.GetBounds();
                var boundsTree = GetBoundTree(val.LayerType);
                boundsTree.UpdateObj(val, bound);
            }

            Profiler.EndSample();
            ////0.32~0.42ms
            Profiler.BeginSample("CheckCollision");
            foreach (var val in tempLst)
            {
                val._isMoved = false;
                var bound        = val.GetBounds();
                var targetLayers = InterestingMasks[val.LayerType];
                foreach (var layerType in targetLayers)
                {
                    var boundsTree = GetBoundTree(layerType);
                    boundsTree.CheckCollision(val, bound);
                }
            }

            Profiler.EndSample();
            Profiler.BeginSample("CheckLastFrameCollison");
            foreach (var pairId in _curPairs)
            {
                _prePairs.Remove(pairId);
            }

            //check stay leave event
            foreach (var idPair in _prePairs)
            {
                var a = GetCollider((uint)(idPair >> 32));
                var b = GetCollider((uint)(idPair & 0xffffffff));
                if (a == null || b == null)
                {
                    continue;
                }

                bool isCollided = CollisionHelper.CheckCollision
                                      (a.Prefab, a.Transform2D, b.Prefab, b.Transform2D);
                if (isCollided)
                {
                    _curPairs.Add(idPair);
                    NotifyCollisionEvent(a, b, ECollisionEvent.Stay);
                }
                else
                {
                    NotifyCollisionEvent(a, b, ECollisionEvent.Exit);
                }
            }

            Profiler.EndSample();
        }
コード例 #55
0
 public static void BeginSample(string name, Object targetObject)
 {
     Profiler.BeginSample(name, targetObject);
 }
コード例 #56
0
        public virtual IEnumerator ExecuteAsync()
        {
            Profiler.BeginSample("Barracuda.Execute");

            ResetAllocatorIfRequested();
            m_Vars.PrepareStorage(m_Model, m_Ops, m_InputShapes);

            if (m_ModelCompiler != null)
            {
                m_ModelCompiler.PrepareModel(m_Model, m_InputShapes);
            }

            int idx = 0;

            foreach (var l in m_Model.layers)
            {
                idx++;

                m_Progress = idx / (float)m_Model.layers.Count;

                Profiler.BeginSample(l.name);
                var inputs = m_Vars.GatherInputs(l);

                Tensor X = inputs.Length > 0 ? inputs[0] : new Tensor();

                if (m_Verbose)
                {
                    D.Log("Layer: " + l.type + ((l.type == Layer.Type.Activation) ? ("." + l.activation) : "") + " " + l.name);
                }

                m_Vars.PrepareStorage(l);
                if (m_ModelCompiler != null)
                {
                    m_ModelCompiler.PreExecuteLayer(l, inputs);
                }

                // No operation, identity
                if (l.type == Layer.Type.Nop)
                {
                    Profiler.BeginSample("Barracuda.Nop");
                    X = m_Ops.Copy(X);
                }
                // Load const
                else if (l.type == Layer.Type.Load)
                {
                    Profiler.BeginSample("Barracuda.Load");
                }
                // GEMM
                else if (l.type == Layer.Type.Dense)
                {
                    Assert.AreEqual(inputs.Length, 3);
                    Profiler.BeginSample("Barracuda.Dense");
                    X = m_Ops.Dense(X, inputs[1], inputs[2], GetAndVerifyFusedActivation(l));
                }
                // 2D
                else if (l.type == Layer.Type.Conv2D)
                {
                    Assert.AreEqual(inputs.Length, 3);
                    Profiler.BeginSample("Barracuda.Conv2D");
                    var pad = X.AdjustPadToKernel(inputs[1], l.stride, l.pad);
                    X = m_Ops.Conv2D(X, inputs[1], inputs[2], l.stride, pad, GetAndVerifyFusedActivation(l));
                }
                else if (l.type == Layer.Type.DepthwiseConv2D)
                {
                    Assert.AreEqual(inputs.Length, 3);
                    Profiler.BeginSample("Barracuda.DepthwiseConv2D");
                    var pad = X.AdjustPadToKernel(inputs[1], l.stride, l.pad);
                    X = m_Ops.DepthwiseConv2D(X, inputs[1], inputs[2], l.stride, pad);
                }
                else if (l.type == Layer.Type.Conv2DTrans)
                {
                    Assert.AreEqual(inputs.Length, 3);
                    Profiler.BeginSample("Barracuda.Conv2DTrans");
                    // pool size is treated as output_adjustment aka output_padding here
                    var outputAdjustment = l.pool;
                    var pad = X.AdjustPadToKernel(inputs[1], l.stride, l.pad);
                    X = m_Ops.Conv2DTrans(X, inputs[1], inputs[2], l.stride, pad, outputAdjustment);
                }
                else if (l.type == Layer.Type.Upsample2D)
                {
                    Profiler.BeginSample("Barracuda.Upsample2D");
                    // pool size is treated as upsample scale coefficient here
                    var scale = l.pool;
                    // axis is treated as upsample point/bilinear flag
                    var bilinear = l.axis > 0;
                    if (inputs.Length > 1)
                    {
                        var size = inputs[1];
                        Assert.AreEqual(size.flatHeight, 4);
                        Assert.AreEqual(size.flatWidth, 1);
                        scale = new int[] { (int)size[2], (int)size[1] };
                    }
                    X = m_Ops.Upsample2D(X, scale, bilinear);
                }
                else if (l.type == Layer.Type.Resample2D)
                {
                    Profiler.BeginSample("Barracuda.Resample2D");
                    // pool size is treated as resample size here
                    var size = l.pool;
                    // axis is treated as upsample point/bilinear flag
                    var bilinear = l.axis > 0;
                    if (inputs.Length > 1)
                    {
                        var sizeTensor = inputs[1];
                        Assert.AreEqual(sizeTensor.length, 4);
                        size = new int[] { (int)sizeTensor[2], (int)sizeTensor[1] };
                    }
                    X = m_Ops.Resample2D(X, size, bilinear);
                }
                else if (l.type == Layer.Type.DepthToSpace)
                {
                    Profiler.BeginSample("Barracuda.DepthToSpace");
                    // pool size is treated as blocksize
                    var blocksize = l.pool;
                    // axis is treated as mode enum
                    var mode = (Layer.DepthToSpaceMode)l.axis;
                    X = m_Ops.DepthToSpace(X, blocksize, mode);
                }
                else if (l.type == Layer.Type.SpaceToDepth)
                {
                    Profiler.BeginSample("Barracuda.SpaceToDepth");
                    // pool size is treated as blocksize
                    var blocksize = l.pool;
                    X = m_Ops.SpaceToDepth(X, blocksize);
                }
                else if (l.type == Layer.Type.MaxPool2D)
                {
                    Profiler.BeginSample("Barracuda.MaxPool2D");
                    var pad = X.AdjustPadToPool(l.pool, l.stride, l.pad);
                    X = m_Ops.MaxPool2D(X, l.pool, l.stride, pad);
                }
                else if (l.type == Layer.Type.AvgPool2D)
                {
                    Profiler.BeginSample("Barracuda.AvgPool2D");
                    var pad = X.AdjustPadToPool(l.pool, l.stride, l.pad);
                    X = m_Ops.AvgPool2D(X, l.pool, l.stride, pad);
                }
                else if (l.type == Layer.Type.GlobalMaxPool2D)
                {
                    Profiler.BeginSample("Barracuda.GlobalMaxPool2D");
                    X = m_Ops.GlobalMaxPool2D(X);
                }
                else if (l.type == Layer.Type.GlobalAvgPool2D)
                {
                    Profiler.BeginSample("Barracuda.GlobalAvgPool2D");
                    X = m_Ops.GlobalAvgPool2D(X);
                }
                else if (l.type == Layer.Type.Border2D)
                {
                    Profiler.BeginSample("Barracuda.Border2D");

                    Assert.IsNotNull(l.pad);
                    // NOTE: beta is used to retrieve fillin value
                    // because beta is 0 by default (while alpha is 1 by default)
                    // 0 value is more inline with zero padding
                    float fillValue = l.beta;
                    X = m_Ops.Border2D(X, l.pad, fillValue);
                }
                else if (l.type == Layer.Type.Pad2DReflect)
                {
                    Profiler.BeginSample("Barracuda.Pad2DReflect");

                    Assert.IsNotNull(l.pad);
                    X = m_Ops.Pad2DReflect(X, l.pad);
                }
                else if (l.type == Layer.Type.Pad2DSymmetric)
                {
                    Profiler.BeginSample("Barracuda.Pad2DSymmetric");

                    Assert.IsNotNull(l.pad);
                    X = m_Ops.Pad2DSymmetric(X, l.pad);
                }
                else if (l.type == Layer.Type.Pad2DEdge)
                {
                    Profiler.BeginSample("Barracuda.Pad2DEdge");

                    Assert.IsNotNull(l.pad);
                    X = m_Ops.Pad2DEdge(X, l.pad);
                }
                // 3D
                else if (l.type == Layer.Type.Conv3D ||
                         l.type == Layer.Type.Conv3DTrans ||
                         l.type == Layer.Type.Upsample3D ||
                         l.type == Layer.Type.MaxPool3D ||
                         l.type == Layer.Type.AvgPool3D ||
                         l.type == Layer.Type.GlobalMaxPool3D ||
                         l.type == Layer.Type.GlobalAvgPool3D ||
                         l.type == Layer.Type.Border3D)
                {
                    throw new NotImplementedException("3D operations are not implemented yet!");
                }
                else if (l.type == Layer.Type.ScaleBias)
                {
                    Assert.AreEqual(inputs.Length, 3);
                    Profiler.BeginSample("Barracuda.ScaleBias");
                    X = m_Ops.ScaleBias(X, inputs[1], inputs[2]);
                }
                else if (l.type == Layer.Type.Normalization)
                {
                    Assert.AreEqual(inputs.Length, 3);
                    Profiler.BeginSample("Barracuda.Normalization");
                    // @TODO: support other types of Normalization at test time.
                    // Currently supported only pool=1 (InstanceNormalization)

                    // NOTE: beta is used to retrieve epsilon value
                    // because beta is 0 by default (while alpha is 1 by default)
                    // 0 value is more inline with very small epsilon
                    var epsilon = l.beta;
                    if (epsilon == 0)
                    {
                        epsilon = Mathf.Epsilon; // safety check to prevent division by zero
                    }
                    X = m_Ops.Normalization(X, inputs[1], inputs[2], 1, l.axis, epsilon, GetAndVerifyFusedActivation(l));
                }
                else if (l.type == Layer.Type.LRN)
                {
                    Profiler.BeginSample("Barracuda.LRN");

                    Assert.IsNotNull(l.pool);
                    Assert.AreEqual(l.pool.Length, 1);
                    int count = l.pool[0];
                    X = m_Ops.LRN(X, l.alpha, l.beta, 1.0f, count); // @TODO: bias
                }
                // Stochastic layers
                else if (l.type == Layer.Type.Dropout)
                {
                    Profiler.BeginSample("Barracuda.Dropout");

                    X = m_Ops.Dropout(X, l.alpha);
                }
                else if (l.type == Layer.Type.RandomNormal)
                {
                    Profiler.BeginSample("Barracuda.RandomNormal");

                    Assert.IsNotNull(l.pool);
                    // pool size is treated as shape constant, if not empty
                    // otherwise shape of the previous tensor is used
                    var shape = X.shape;
                    if (l.pool.Length > 0)
                    {
                        shape = new TensorShape(l.pool);
                    }

                    int   seed = (l.pad.Length > 0) ? l.pad[0] : 1337;
                    float scale = l.alpha, mean = l.beta;
                    X = m_Ops.RandomNormal(shape, mean, scale, seed);
                }
                else if (l.type == Layer.Type.RandomUniform)
                {
                    Profiler.BeginSample("Barracuda.RandomUniform");

                    Assert.IsNotNull(l.pool);
                    // pool size is treated as shape constant, if not empty
                    // otherwise shape of the previous tensor is used
                    var shape = X.shape;
                    if (l.pool.Length > 0)
                    {
                        shape = new TensorShape(l.pool);
                    }

                    int   seed = (l.pad.Length > 0) ? l.pad[0] : 1337;
                    float scale = l.alpha, mean = l.beta;
                    X = m_Ops.RandomUniform(shape, mean, scale, seed);
                }
                else if (l.type == Layer.Type.Multinomial)
                {
                    Profiler.BeginSample("Barracuda.Multinomial");

                    Assert.IsNotNull(l.pool);
                    Assert.AreEqual(l.pool.Length, 1);

                    int count = l.pool[0];
                    int seed  = (l.pad.Length > 0) ? l.pad[0] : 1337;
                    X = m_Ops.Multinomial(X, count, seed);
                }
                else if (l.type == Layer.Type.OneHot)
                {
                    Profiler.BeginSample("Barracuda.OneHot");

                    Assert.IsNotNull(l.pool);
                    Assert.AreEqual(l.pool.Length, 1);
                    int   depth = l.pool[0];
                    float on = l.alpha, off = l.beta;
                    X = m_Ops.OneHot(X, depth, on, off);
                }
                // Broadcast layers
                else if (l.type == Layer.Type.Add)
                {
                    Profiler.BeginSample("Barracuda.Add");

                    X = m_Ops.Add(inputs);
                }
                else if (l.type == Layer.Type.Sub)
                {
                    Profiler.BeginSample("Barracuda.Sub");

                    X = m_Ops.Sub(inputs);
                }
                else if (l.type == Layer.Type.Mul)
                {
                    Profiler.BeginSample("Barracuda.Mul");

                    X = m_Ops.Mul(inputs);
                }
                else if (l.type == Layer.Type.Div)
                {
                    Profiler.BeginSample("Barracuda.Div");

                    X = m_Ops.Div(inputs);
                }
                else if (l.type == Layer.Type.Pow)
                {
                    Profiler.BeginSample("Barracuda.Pow");

                    X = m_Ops.Pow(inputs);
                }
                else if (l.type == Layer.Type.Min)
                {
                    Profiler.BeginSample("Barracuda.Min");

                    X = m_Ops.Min(inputs);
                }
                else if (l.type == Layer.Type.Max)
                {
                    Profiler.BeginSample("Barracuda.Max");

                    X = m_Ops.Max(inputs);
                }
                else if (l.type == Layer.Type.Mean)
                {
                    Profiler.BeginSample("Barracuda.Mean");

                    X = m_Ops.Mean(inputs);
                }
                // Reduction layers
                else if (l.type == Layer.Type.ReduceMax)
                {
                    Profiler.BeginSample("Barracuda.ReduceMax");

                    X = m_Ops.ReduceMax(X, l.axis);
                }
                else if (l.type == Layer.Type.ReduceMean)
                {
                    Profiler.BeginSample("Barracuda.ReduceMean");

                    X = m_Ops.ReduceMean(X, l.axis);
                }
                else if (l.type == Layer.Type.ReduceMin)
                {
                    Profiler.BeginSample("Barracuda.ReduceMin");

                    X = m_Ops.ReduceMin(X, l.axis);
                }
                else if (l.type == Layer.Type.ReduceProd)
                {
                    Profiler.BeginSample("Barracuda.ReduceProd");

                    X = m_Ops.ReduceProd(X, l.axis);
                }
                else if (l.type == Layer.Type.ReduceSum)
                {
                    Profiler.BeginSample("Barracuda.ReduceSum");

                    X = m_Ops.ReduceSum(X, l.axis);
                }
                else if (
                    l.type == Layer.Type.ReduceL1 ||
                    l.type == Layer.Type.ReduceL2 ||
                    l.type == Layer.Type.ReduceLogSum ||
                    l.type == Layer.Type.ReduceLogSumExp ||
                    l.type == Layer.Type.ReduceSumSquare)
                {
                    throw new NotImplementedException("This reduction operation is not implemented yet!");
                }
                // Logical operators with broadcast
                else if (l.type == Layer.Type.Greater)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.Greater");
                    X = m_Ops.Greater(X, inputs[1]);
                }
                else if (l.type == Layer.Type.GreaterEqual)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.GreaterEqual");
                    X = m_Ops.GreaterEqual(X, inputs[1]);
                }
                else if (l.type == Layer.Type.Less)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.Less");
                    X = m_Ops.Less(X, inputs[1]);
                }
                else if (l.type == Layer.Type.LessEqual)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.LessEqual");
                    X = m_Ops.LessEqual(X, inputs[1]);
                }
                else if (l.type == Layer.Type.Equal)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.Equal");
                    X = m_Ops.Equal(X, inputs[1]);
                }
                else if (l.type == Layer.Type.LogicalOr)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.LogicalOr");
                    X = m_Ops.LogicalOr(X, inputs[1]);
                }
                else if (l.type == Layer.Type.LogicalAnd)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.LogicalAnd");
                    X = m_Ops.LogicalAnd(X, inputs[1]);
                }
                else if (l.type == Layer.Type.LogicalXor)
                {
                    Assert.AreEqual(inputs.Length, 2);
                    Profiler.BeginSample("Barracuda.LogicalXor");
                    X = m_Ops.LogicalXor(X, inputs[1]);
                }
                else if (l.type == Layer.Type.LogicalNot)
                {
                    Profiler.BeginSample("Barracuda.LogicalNot");
                    X = m_Ops.LogicalNot(X);
                }
                // Shape affecting layers
                else if (l.type == Layer.Type.Flatten)
                {
                    Profiler.BeginSample("Barracuda.Flatten");
                    X = m_Ops.Flatten(X);
                }
                else if (l.type == Layer.Type.Reshape)
                {
                    Profiler.BeginSample("Barracuda.Reshape");

                    // pool size is treated as reshape coefficient, if not empty
                    // otherwise shape of the 2nd input tensor is used
                    var size = l.pool;

                    Assert.IsNotNull(size);
                    if (size.Length == 0 && inputs.Length > 1)
                    {
                        size = inputs[1].shape.ToArray();
                    }

                    var newShape = X.shape.Reshape(size);
                    X = m_Ops.Reshape(X, newShape);
                }
                else if (l.type == Layer.Type.Expand)
                {
                    Profiler.BeginSample("Barracuda.Expand");

                    // pool size is treated as new shape
                    var newShape = l.pool;

                    Assert.IsNotNull(newShape);
                    Assert.AreEqual(newShape.Length, 4);

                    X = m_Ops.Expand(X, new TensorShape(newShape));
                }
                else if (l.type == Layer.Type.Transpose)
                {
                    Profiler.BeginSample("Barracuda.Transpose");
                    X = m_Ops.Transpose(X);
                }
                else if (l.type == Layer.Type.Gather)
                {
                    Profiler.BeginSample("Barracuda.Gather");
                    X = m_Ops.Gather(inputs, l.axis);
                }
                else if (l.type == Layer.Type.Squeeze ||
                         l.type == Layer.Type.Unsqueeze)
                {
                    throw new NotImplementedException();
                }
                else if (l.type == Layer.Type.Concat)
                {
                    Profiler.BeginSample("Barracuda.Concat");
                    X = m_Ops.Concat(inputs, l.axis);
                }
                else if (l.type == Layer.Type.StridedSlice)
                {
                    Profiler.BeginSample("Barracuda.StridedSlice");

                    Assert.IsNotNull(l.pad);
                    Assert.IsNotNull(l.pool);
                    Assert.IsNotNull(l.stride);
                    X = m_Ops.StridedSlice(X, l.pad, l.pool, l.stride);
                }
                else if (l.type == Layer.Type.Tile)
                {
                    throw new NotImplementedException();
                }
                // Activations
                else if (l.type == Layer.Type.Activation)
                {
                    Profiler.BeginSample("Barracuda.Activation");

                    if (l.activation == Layer.Activation.Relu)
                    {
                        X = m_Ops.Relu(X);
                    }
                    else if (l.activation == Layer.Activation.Softmax)
                    {
                        X = m_Ops.Softmax(X);
                    }
                    else if (l.activation == Layer.Activation.LogSoftmax)
                    {
                        X = m_Ops.LogSoftmax(X);
                    }
                    else if (l.activation == Layer.Activation.Tanh)
                    {
                        X = m_Ops.Tanh(X);
                    }
                    else if (l.activation == Layer.Activation.Sigmoid)
                    {
                        X = m_Ops.Sigmoid(X);
                    }
                    else if (l.activation == Layer.Activation.Relu6)
                    {
                        X = m_Ops.Relu6(X);
                    }
                    else if (l.activation == Layer.Activation.Elu)
                    {
                        X = m_Ops.Elu(X, l.alpha);
                    }
                    else if (l.activation == Layer.Activation.LeakyRelu)
                    {
                        X = m_Ops.LeakyRelu(X, l.alpha);
                    }
                    else if (l.activation == Layer.Activation.Selu)
                    {
                        X = m_Ops.Selu(X, l.alpha, l.beta);
                    }
                    else if (l.activation == Layer.Activation.Swish)
                    {
                        X = m_Ops.Swish(X);
                    }
                    else if (l.activation == Layer.Activation.PRelu)
                    {
                        Assert.AreEqual(inputs.Length, 2);
                        X = m_Ops.PRelu(X, inputs[1]);
                    }
                    else if (
                        l.activation == Layer.Activation.Softplus ||
                        l.activation == Layer.Activation.Softsign ||
                        l.activation == Layer.Activation.Hardmax ||
                        l.activation == Layer.Activation.HardSigmoid)
                    {
                        throw new NotImplementedException("This activation function is not implemented yet!");
                    }
                    else if (l.activation == Layer.Activation.Abs)
                    {
                        X = m_Ops.Abs(X);
                    }
                    else if (l.activation == Layer.Activation.Neg)
                    {
                        X = m_Ops.Neg(X);
                    }
                    else if (l.activation == Layer.Activation.Ceil)
                    {
                        X = m_Ops.Ceil(X);
                    }
                    else if (l.activation == Layer.Activation.Clip)
                    {
                        X = m_Ops.Clip(X, l.alpha, l.beta);
                    }
                    else if (l.activation == Layer.Activation.Floor)
                    {
                        X = m_Ops.Floor(X);
                    }
                    else if (l.activation == Layer.Activation.Reciprocal)
                    {
                        X = m_Ops.Reciprocal(X);
                    }
                    else if (l.activation == Layer.Activation.Pow)
                    {
                        X = m_Ops.Pow(X, l.alpha);
                    }
                    else if (l.activation == Layer.Activation.Exp)
                    {
                        X = m_Ops.Exp(X);
                    }
                    else if (l.activation == Layer.Activation.Log)
                    {
                        X = m_Ops.Log(X);
                    }
                    else if (l.activation == Layer.Activation.Sqrt)
                    {
                        X = m_Ops.Sqrt(X);
                    }
                    else if ((int)l.activation >= (int)Layer.Activation.Acos &&
                             (int)l.activation <= (int)Layer.Activation.Tan)
                    {
                        throw new NotImplementedException("Trig functions are not implemented yet!");
                    }
                    else
                    {
                        X = m_Ops.Copy(X);
                    }
                }
                else
                {
                    Profiler.BeginSample("Barracuda.Dummy");
                    Assert.AreEqual(l.activation, Layer.Activation.None);
                }

                m_Vars.Store(l, X);
                m_SyncTensor = X;

                // optype
                Profiler.EndSample();

                // layer.name
                Profiler.EndSample();

                yield return(null);
            }

            // request ResetAllocator before next Execute() starts
            m_RequestResetAllocator = true;
            Profiler.EndSample();

            if (m_Verbose)
            {
                D.Log(m_Vars.GetAllocator());
            }
        }
コード例 #57
0
 static public int PlaySound_s(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 1)
         {
             UnityEngine.AudioClip a1;
             checkType(l, 1, out a1);
             var ret = NGUITools.PlaySound(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 2)
         {
             UnityEngine.AudioClip a1;
             checkType(l, 1, out a1);
             System.Single a2;
             checkType(l, 2, out a2);
             var ret = NGUITools.PlaySound(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 3)
         {
             UnityEngine.AudioClip a1;
             checkType(l, 1, out a1);
             System.Single a2;
             checkType(l, 2, out a2);
             System.Single a3;
             checkType(l, 3, out a3);
             var ret = NGUITools.PlaySound(a1, a2, a3);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function PlaySound to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
コード例 #58
0
        public async Task BeforeAllAsync()
        {
            await Profiler.Run(
                async() =>
            {
                // Set up logging
                LogEventLevel consoleLevel = Context.Current.Verbose
                        ? LogEventLevel.Verbose
                        : LogEventLevel.Information;
                var loggerConfig = new LoggerConfiguration()
                                   .MinimumLevel.Verbose()
                                   .WriteTo.NUnit(consoleLevel);
                Context.Current.LogFile.ForEach(f => loggerConfig.WriteTo.File(f));
                Log.Logger = loggerConfig.CreateLogger();

                // Install IoT Edge
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    // NUnit's [Timeout] attribute isn't supported in .NET Standard
                    // and even if it were, it doesn't run the teardown method when
                    // a test times out. We need teardown to run, to remove the
                    // device registration from IoT Hub and stop the daemon. So
                    // we have our own timeout mechanism.
                    DateTime startTime      = DateTime.Now;
                    CancellationToken token = cts.Token;

                    Assert.IsNull(this.device);
                    this.device = await EdgeDevice.GetOrCreateIdentityAsync(
                        Context.Current.DeviceId,
                        this.iotHub,
                        token);

                    await this.daemon.UninstallAsync(token);
                    await this.daemon.InstallAsync(
                        this.device.ConnectionString,
                        Context.Current.PackagePath,
                        Context.Current.Proxy,
                        token);

                    try
                    {
                        await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

                        var agent = new EdgeAgent(this.device.Id, this.iotHub);
                        await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);
                        await agent.PingAsync(token);
                    }

                    // ReSharper disable once RedundantCatchClause
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        string prefix = $"{Context.Current.DeviceId}-{TestContext.CurrentContext.Test.NormalizedName()}";
                        IEnumerable <string> paths = await EdgeLogs.CollectAsync(startTime, prefix, token);
                        foreach (string path in paths)
                        {
                            TestContext.AddTestAttachment(path);
                        }
                    }
                }
            },
                "Completed end-to-end test setup");
        }
コード例 #59
0
		private static string ResultsFullPage(IHttpResponse httpRes, Profiler profiler)
		{
			httpRes.ContentType = "text/html";
			return new StringBuilder()
				.AppendLine("<html><head>")
				.AppendFormat("<title>{0} ({1} ms) - MvcMiniProfiler Results</title>", profiler.Name, profiler.DurationMilliseconds)
				.AppendLine()
				.AppendLine("<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>")
				.Append("<script type='text/javascript'> var profiler = ")
				.Append(Profiler.ToJson(profiler))
				.AppendLine(";</script>")
				.Append(RenderIncludes(profiler)) // figure out how to better pass display options
				.AppendLine("</head><body><div class='profiler-result-full'></div></body></html>")
				.ToString();
		}
コード例 #60
0
        public void DoTick()
        {
            if (reactionTick == 0)
            {
                return;
            }

            reactionTick--;

            //process the current hotspots, removing ones that can't sustain anymore.
            //(but we actually perform the add / remove after this loop so we don't concurrently modify the dict)
            foreach (MetaDataNode node in hotspots.Values)
            {
                if (node.Hotspot != null)
                {
                    if (PlasmaFireReaction.CanHoldHotspot(node.GasMix))
                    {
                        node.Hotspot.Process();
                    }
                    else
                    {
                        RemoveHotspot(node);
                    }
                }
            }

            Profiler.BeginSample("GasReactions");

            int gasReactionCount = addReaction.Count;

            if (gasReactionCount > 0)
            {
                for (int i = gasReactionCount; i >= 0; i--)
                {
                    if (addReaction.TryDequeue(out var addReactionNode))
                    {
                        var gasMix = addReactionNode.metaDataNode.GasMix;

                        addReactionNode.gasReaction.Reaction.React(gasMix, addReactionNode.metaDataNode.Position, addReactionNode.metaDataNode.PositionMatrix);

                        if (reactions.TryGetValue(addReactionNode.metaDataNode.Position, out var gasHashSet) &&
                            gasHashSet.Count == 1)
                        {
                            reactions.TryRemove(addReactionNode.metaDataNode.Position, out var value);
                            continue;
                        }

                        reactions[addReactionNode.metaDataNode.Position].Remove(addReactionNode.gasReaction);
                    }
                }
            }

            Profiler.EndSample();

            #region TileOverlays

            Profiler.BeginSample("FogModifyAdd");
            //Here we check to see if chemical fog fx needs to be applied, and if so, add them. If not, we remove them
            int addFogCount = addFog.Count;
            if (addFogCount > 0)
            {
                for (int i = 0; i < addFogCount; i++)
                {
                    if (addFog.TryDequeue(out var addFogNode))
                    {
                        if (fogTiles.ContainsKey(addFogNode.metaDataNode.Position))
                        {
                            if (fogTiles[addFogNode.metaDataNode.Position].Contains(addFogNode.gas))
                            {
                                continue;
                            }

                            fogTiles[addFogNode.metaDataNode.Position].Add(addFogNode.gas);                             //Add it to fogTiles
                        }
                        else
                        {
                            fogTiles.Add(addFogNode.metaDataNode.Position,
                                         new HashSet <Gas> {
                                addFogNode.gas
                            });                                                                       //Add it to fogTiles
                        }

                        tileChangeManager.UpdateTile(
                            new Vector3Int(addFogNode.metaDataNode.Position.x, addFogNode.metaDataNode.Position.y,
                                           addFogNode.gas.OverlayIndex),
                            TileType.Effects, addFogNode.gas.TileName);
                    }
                }
            }

            Profiler.EndSample();
            Profiler.BeginSample("FogModifyRemove");

            //Similar to above, but for removing chemical fog fx
            int removeFogCount = removeFog.Count;
            if (removeFogCount > 0)
            {
                for (int i = 0; i < removeFogCount; i++)
                {
                    if (removeFog.TryDequeue(out var removeFogNode))
                    {
                        if (!fogTiles.ContainsKey(removeFogNode.metaDataNode.Position))
                        {
                            continue;
                        }

                        if (!fogTiles[removeFogNode.metaDataNode.Position].Contains(removeFogNode.gas))
                        {
                            continue;
                        }

                        tileChangeManager.RemoveTile(
                            new Vector3Int(removeFogNode.metaDataNode.Position.x, removeFogNode.metaDataNode.Position.y,
                                           removeFogNode.gas.OverlayIndex),
                            LayerType.Effects, false);

                        if (fogTiles[removeFogNode.metaDataNode.Position].Count == 1)
                        {
                            fogTiles.Remove(removeFogNode.metaDataNode.Position);
                            continue;
                        }

                        fogTiles[removeFogNode.metaDataNode.Position].Remove(removeFogNode.gas);
                    }
                }
            }

            Profiler.EndSample();

            #endregion
        }