Ejemplo n.º 1
0
		public UltraSprite()
		{
			this.graphics.beginFill(0xffffff);
			this.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);
			this.graphics.lineStyle(2, 0xa0, 1);
			this.graphics.beginFill(0xffffff, 0);
			this.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);

			t = new TextField
			{
				width = DefaultWidth,
				height = DefaultHeight
			};

			t.AttachTo(this);

			this.AppendLine("This is flash.display.Sprite (version 101)");

			var Button1 = new Sprite();

			Button1.graphics.beginFill(0xff00);
			Button1.graphics.drawRect(0, 0, 64, 24);
			Button1.useHandCursor = true;
			Button1.buttonMode = true;

			Button1.AttachTo(this).MoveTo(DefaultWidth - 64 - 8, 8);

			Button1.click +=
				delegate
				{
					// jsc.meta should use Convert type for us
					if (Convert.ToBoolean(this.WebServiceEnabled.IsEnabled))
					{
						this.WebService.GetTime("[flash client time]: " + DateTime.Now + " [server time]",
							x =>
							{
								this.AppendLine(x);
							}
						);
					}
					else
					{
						this.AppendLine("WebService is disabled!");
					}
				};
		}
        // X:\jsc.svn\examples\actionscript\FlashWorkerExperiment\FlashWorkerExperiment\ApplicationSprite.cs
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201403/20140301

        public ApplicationSprite()
        {
            // when can we do this?

            //BCL needs another method, please define it.
            //Cannot call type without script attribute :
            //System.Threading.Tasks.Task for System.Threading.Tasks.TaskFactory get_Factory() used at
            //AsyncWorkerTask.ApplicationSprite..ctor at offset 0010.

            var a = Task.Factory.StartNew(
                state: new { goo = "foo " },
                function: scope =>
                {



                    // notice that jsc might need to inject serialization logic here
                    return "hello " + new { scope.goo };
                }
            );

            a.ContinueWithResult(
                r =>
                {
                    var t = new TextField
                    {
                        text = new
                        {
                            r,

                            WorkerDomain = WorkerDomain.isSupported,
                            Worker = Worker.isSupported,
                            Worker.current.isPrimordial,

                            this.loaderInfo.bytes.length
                        }.ToString(),

                        autoSize = TextFieldAutoSize.LEFT
                    };

                    t.AttachTo(this);
                }
            );


        }
Ejemplo n.º 3
0
		public UltraSprite()
		{
			this.graphics.beginFill(0xffffff);
			this.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);
			this.graphics.lineStyle(2, 0xa0, 1);
			this.graphics.beginFill(0xffffff, 0);
			this.graphics.drawRect(0, 0, DefaultWidth, DefaultHeight);

			t = new TextField
			{
				width = DefaultWidth,
				height = DefaultHeight
			};

			t.AttachTo(this);

			this.AppendLine("This is flash.display.Sprite (version 101)");
		}
        public ApplicationSprite()
        {
            // X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\ApplicationSprite.cs

            // jsc should return before getting here from the worker
            if (!Worker.current.isPrimordial)
                return;

            var t = new TextField
            {
                multiline = true,
                text = new
                {
                    __Thread.InternalPrimordialSprite,
                    this.loaderInfo.bytes.length,
                }.ToString(),
                autoSize = TextFieldAutoSize.LEFT
            };

            t.AttachTo(this);

            t.click += delegate
            {
                var sw = Stopwatch.StartNew();

                t.text = "enter click";

                __Thread tt = new Thread(
                    new ParameterizedThreadStart(
                        data =>
                        {
                            // can we render audio on the background thread now?
                            // what else can AIR do on a background thread?
                            // physics?
                            // LAN calc?

                            // how can we report to the UI thread?

                            var nn = Stopwatch.StartNew();


                            int i = 0;

                            // keep core2 buzy for a while to be noticed on the task manager
                            while (nn.ElapsedMilliseconds < 10000)
                            {
                                SharedField = new
                                {
                                    data,
                                    i,
                                    nn.ElapsedMilliseconds
                                    //, Thread.CurrentThread.ManagedThreadId 
                                }.ToString();

                                i++;
                            }

                            // i wonder, can we switch to UI thread via await and then back?



                            var xfromWorker = (MessageChannel)Worker.current.getSharedProperty("fromWorker");
                            // or are we to capture all fields modified within worker and only update those?
                            xfromWorker.send("message from worker " + new { SharedField });

                            // how do we signal our work is done?
                        }
                    )
                );

                tt.InternalBeforeStart =
                    w =>
                    {
                        // how are we supposed to get data back from the worker?

                        var fromWorker = w.createMessageChannel(Worker.current);
                        w.setSharedProperty("fromWorker", fromWorker);

                        fromWorker.channelMessage += e =>
                        {
                            var data = (string)fromWorker.receive();

                            t.appendText(

                                "\n " + new { sw.ElapsedMilliseconds, data }.ToString()

                                );

                        };
                    };

                //Thread.AllocateNamedDataSlot("").

                //Thread.SetData(
                tt.Start("hello world");
            };


        }
      /// <summary>
        /// Creates a new control
        /// </summary>
        public FlashTextScreenSaver(Qoutes.DocumentList list)
        {
            if (list == null)
                list = DefaultData;

            var type = typeof(FlashTextScreenSaver);

            var name = type.Name;

            Console.WriteLine("type: " + name);

            //try
            //{
            //    IStyleSheet.Default.AddRule("*", "cursor: url('assets/TextScreenSaver/images/cursor.cur'), auto;", 0);

            //    IStyleSheet.Default.AddRule("html",
            //        r =>
            //        {
            //            r.style.overflow = IStyle.OverflowEnum.hidden;
            //        }
            //    );
            //}
            //catch (Exception exc)
            //{
            //    new IHTMLElement(IHTMLElement.HTMLElementEnum.div, "error: " + exc.Message.Replace(",", ", ")).AttachToDocument().style.width = "80em";
            //}

            Action<Qoutes.DocumentRef, Action<Qoutes.Document>> PrepareDocument =
                (doc, done) =>
                {
                    if (doc.Document == null)
                    {
                        //Native.Document.title = "loading...";

                        //Console.WriteLine("loading: " + doc.Source);

                        doc.Source.DownloadToXML<Qoutes.Document>(Qoutes.Settings.KnownTypes,
                            newdoc =>
                            {

                                doc.Document = newdoc;
                                done(newdoc);
                            }
                        );
                    }
                    else
                        done(doc.Document);
                };


            var current = list.Documents.Random();

            var abort = default(Action);
            //var kbd = new KeyboardEvents();

            var reset = default(Action);

            //kbd.left +=
            //    ev =>
            //    {
            //        kbd.Enabled = false;
            //        ev.PreventDefault();

            //        if (abort != null)
            //            abort();
            //        current = list.Documents.Previous(i => i == current);
            //        reset();
            //    };

            //kbd.right +=
            //    ev =>
            //    {
            //        kbd.Enabled = false;
            //        ev.PreventDefault();

            //        if (abort != null)
            //            abort();

            //        current = list.Documents.Next(i => i == current);
            //        reset();
            //    };

            //Native.Document.onkeydown += kbd;


            reset =
                () =>
                PrepareDocument(current,
                doc =>
                {
                    //Native.Document.title = doc.Topic.Trim();

                    //var body = Native.Document.body;

                    //body.style.overflow = IStyle.OverflowEnum.hidden;
                    //body.style.width = "100%";
                    //body.style.height = "100%";
                    //body.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
                    ////body.style.backgroundImage = "url(assets/TextScreenSaver/powered_by_jsc.png)";
                    //body.style.backgroundRepeat = "no-repeat";


                    ////("BackgroundColor: " + doc.Style.BackgroundColor).ToConsole();
                    ////("Color: " + doc.Style.Color).ToConsole();

                    //doc.Style.ApplyTo(body.style);



                    var lines = doc.Lines();

                    var timer_handler = new Action<Timer>(delegate { });
                    var timer_ref = 100.AtInterval(timer_handler);

                    var vectors = new List<TextField>();

                    var abort_me = default(Action);

                    abort_me =
                        delegate
                        {
                            abort -= abort_me;

                            Console.WriteLine("aborting...");

                            timer_ref.stop();

                            vectors.ForEach(v => v.Orphanize());

                            abort_me = null;
                        };

                    abort += abort_me;

                    Action<Action> SpawnVector =
                        done =>
                        {
                            // we have been aborted
                            if (abort_me == null)
                                return;

                            var z = 0.5d.Random() + 0.5d;

                            var v = new TextField { text = lines.Random() };

                            // v.style.whiteSpace = IStyle.WhiteSpaceEnum.nowrap;

                            vectors.Add(v);

                            Action ApplyZ =
                                () =>
                                {
                                    //v.style.fontSize = (z * 3) + "em";
                                    //v.style.Opacity = z;
                                    //v.style.zIndex = (z * 1000).Floor();
                                };


                            ApplyZ();

                            var x = 100d;
                            var y = 80.Random();

                            // v.style.position = IStyle.PositionEnum.absolute;

                            Action UpdatePosition =
                                () =>
                                {
                                    v.x = stage.stageWidth * x;
                                    v.y = stage.stageWidth * x;

                                    //v.style.left = x + "%";
                                    //v.style.top = y + "%";
                                };

                            UpdatePosition();

                            v.AttachTo(this);


                            var handler = default(Action<Timer>);


                            Action DisposeThisVector =
                                delegate
                                {
                                    timer_handler -= handler;
                                    v.FadeOutAndOrphanize();

                                    done();
                                };

                            v.doubleClick +=
                                ev =>
                                {

                                    DisposeThisVector();
                                };

                            var IsHover = false;

                            v.mouseDown +=
                                ev =>
                                {
                                    //ev.PreventDefault();
                                };

                            v.mouseOver +=
                                delegate
                                {
                                    
                                    //v.style.color = doc.Style.HoverColor;
                                    IsHover = true;
                                };

                            v.mouseOut +=
                                delegate
                                {
                                    //v.style.color = Color.None;
                                    IsHover = false;
                                };

                            v.mouseWheelEnabled = true;
                            v.mouseWheel +=
                                ev =>
                                {
                                    z = (z + 0.02 * ev.WheelDirection()).Max(0.5).Min(1.0);

                                    ApplyZ();
                                };

                            //var drag = new DragHelper(v);

                            //drag.Enabled = true;
                            //drag.DragMove +=
                            //    delegate
                            //    {
                            //        var w = Native.Window.Width;
                            //        var h = Native.Window.Height;


                            //        x = (drag.Position.X * 100 / w);
                            //        y = (drag.Position.Y * 100 / h);

                            //        UpdatePosition();

                            //        // v.style.SetLocation(drag.Position.X, drag.Position.Y);

                            //    };

                            handler =
                                timer =>
                                {
                                    //if (drag.IsDrag)
                                    //    return;

                                    if (IsHover)
                                        return;


                                    x -= 0.4 * z;

                                    UpdatePosition();

                                    //drag.Position = new Point(v.offsetLeft, v.offsetTop);

                                    if (v.GetOffsetRight() < 0)
                                    {
                                        DisposeThisVector();
                                    }
                                };

                            timer_handler += handler;
                        };

                    var SpawnNextVector = SpawnVector.AsCyclic();


                    var SpawnRandom = default(Action<int, int, Action>);

                    SpawnRandom =
                        (counter, max, h) =>
                        {
                            max.Random().ToInt32().AtDelay(
                                delegate
                                {
                                    h();

                                    counter--;

                                    if (counter > 0)
                                        SpawnRandom(counter, max, h);
                                }
                            );
                        };


                    SpawnRandom(doc.Count.ToInt32(), 3000, SpawnNextVector);

                    //kbd.Enabled = true;
                }
            );

            reset();
        }
        public ApplicationSprite()
        {
            // http://www.yeahbutisitflash.com/?p=5469

            // http://forums.adobe.com/message/5745066

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201310/20131006-air

            //System.ArgumentException: Parameter count does not match passed in argument value count.

            //        ReferenceError: Error #1065: Variable flash.system::WorkerDomain is not defined.
            //at FlashWorkerExperiment::ApplicationSprite()[S:\web\FlashWorkerExperiment\ApplicationSprite.as:31]

            //{ isSupported = true }
            // http://esdot.ca/site/2012/intro-to-as3-workers-hello-world


            //   The swf version should be 22 and above.



            // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Worker.html
            //  For mobile platforms, concurrency is supported in AIR on Android but not in AIR on iOS. 
            // You can use the static isSupported property to check whether concurrency is supported before attempting to use it.
            if (Worker.current.isPrimordial)
            {
                //{ os = Windows 7, version = WIN 13,0,0,133, WorkerDomain = true, Worker = true, isPrimordial = true, length = 519498 }
                // before start
                // after start { w = [object Worker] }
                // main: { i = 0, isPrimordial = true, current = true }
                // { data = ready? 
                // in worker: { i = 0, isPrimordial = false, current = true }
                // in worker: { i = 1, isPrimordial = true, current = false } }click!
                // { data = hi from worker { data = hi from UI } }

                // http://forums.adobe.com/thread/1171498

                var t = new TextField
                {
                    text = new
                    {
                        // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Capabilities.html
                        Capabilities.os,
                        Capabilities.version,

                        WorkerDomain = WorkerDomain.isSupported,
                        Worker = Worker.isSupported,
                        Worker.current.isPrimordial,

                        this.loaderInfo.bytes.length
                    }.ToString(),

                    autoSize = TextFieldAutoSize.LEFT
                };

                t.AttachTo(this);

                //this.stage.loaderInfo.uncaughtErrorEvents.uncaughtError +=
                this.loaderInfo.uncaughtErrorEvents.uncaughtError +=

                    e =>
                    {
                        // http://www.adobe.com/support/flashplayer/downloads.html

                        t.appendText(

                          new { e.errorID, e.text, e.error }.ToString()

                          );
                    };

                if (WorkerDomain.isSupported)
                {
                    // http://jacksondunstan.com/articles/1968
                    // "C:\util\flex_sdk_4.6\frameworks\libs\player\11.9\playerglobal.swc"
                    // "C:\util\air3-9_sdk_sa_win\frameworks\libs\player\11.9\playerglobal.swc"
                    // "C:\util\air13_sdk_win\frameworks\libs\player\13.0\playerglobal.swc"
                    // can we create natives of it yet?
                    // call c:\util\jsc\bin\jsc.meta.exe RewriteToActionScriptNatives /SWCFiles:"C:\util\flex_sdk_4.6\frameworks\libs\player\11.1\playerglobal.swc" /SWCFiles:"C:\util\flex_sdk_4.6\frameworks\libs\framework.swc"  /SWCFiles:"C:\util\flex_sdk_4.6\frameworks\libs\mx\mx.swc" /OutputAssembly:c:\util\jsc\bin\ScriptCoreLib.ActionScript.Natives.dll  /DisableResolveExternalType:true  /DisableWorkerDomain 
                    // call c:\util\jsc\bin\jsc.meta.exe RewriteToActionScriptNatives /SWCFiles:"C:\util\air13_sdk_win\frameworks\libs\player\13.0\playerglobal.swc" /SWCFiles:"C:\util\flex_sdk_4.6\frameworks\libs\framework.swc"  /SWCFiles:"C:\util\flex_sdk_4.6\frameworks\libs\mx\mx.swc" /OutputAssembly:c:\util\jsc\bin\ScriptCoreLib.ActionScript.AIRNatives.dll  /DisableResolveExternalType:true  /DisableWorkerDomain 

                    // should flash natives gen get a copy of the playerglobal and use it instead?

                    // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/WorkerDomain.html
                    var w = WorkerDomain.current.createWorker(
                        this.loaderInfo.bytes
                    );

                    // http://jacksondunstan.com/articles/2401

                    //  channel1 = WorkerDomain.current.createMessageChannel(worker0);
                    var toWorker = Worker.current.createMessageChannel(w);
                    var fromWorker = w.createMessageChannel(Worker.current);

                    // http://esdot.ca/site/2012/intro-to-as3-workers-hello-world
                    w.setSharedProperty("toWorker", toWorker);
                    w.setSharedProperty("fromWorker", fromWorker);

                    // http://jcward.com/AIR+3.9+Workers+Beta
                    fromWorker.channelMessage +=
                        e =>
                        {
                            var data = (string)fromWorker.receive();

                            t.appendText(

                                "\n " + new { data }.ToString()

                                );
                        };

                    t.appendText(
                              "\n before start"
                              );

                    // { isSupported = true, isPrimordial = true, length = 485141 }
                    w.start();


                    t.appendText(
                              "\n after start " + new { w }
                              );

                    var list = WorkerDomain.current.listWorkers();

                    for (int i = 0; i < list.length; i++)
                    {

                        t.appendText(
                                  "\n main: " + new
                                  {
                                      i,
                                      list[i].isPrimordial,
                                      current = list[i] == Worker.current
                                  }
                         );
                    }

                    t.click +=
                        delegate
                        {
                            t.appendText(

                            "click!"


                             );

                            toWorker.send("hi from UI");
                        };
                }
            }
            else
            {
                var toWorker = (MessageChannel)Worker.current.getSharedProperty("toWorker");

                // VerifyError: Error #1014: Class flash.system::Worker could not be found.

                //WorkerDomain = true, Worker = true, isPrimordial = true, length = 517003 }
                //before start
                //after start { w = [object Worker] }{ data = ready? }click!{ data = hi from worker { data = hi from UI } }


                // http://forums.adobe.com/thread/1411606?tstart=0
                //Mobile Workers (concurrency) - Android
                //Introduced as a beta feature in AIR 3.9, we've continued to improve this feature based on your feedback for its official release in AIR 4.





                // what about automagic sync, jsc detects and marks such properties?
                var xfromWorker = (MessageChannel)Worker.current.getSharedProperty("fromWorker");

                if (xfromWorker != null)
                {
                    var w = new StringBuilder();


                    //{ WorkerDomain = true, Worker = true, isPrimordial = true, length = 519030 }
                    // before start
                    // after start { w = [object Worker] }
                    // main: { i = 0, isPrimordial = true, current = true }
                    // { data = ready? 
                    // in worker: { i = 0, isPrimordial = false, current = true }
                    // in worker: { i = 1, isPrimordial = true, current = false } }click!
                    // { data = hi from worker { data = hi from UI } }click!
                    // { data = hi from worker { data = hi from UI } }

                    var list = WorkerDomain.current.listWorkers();

                    for (int i = 0; i < list.length; i++)
                    {

                        w.Append(
                                  "\n in worker: " + new
                                  {
                                      i,
                                      list[i].isPrimordial,
                                      current = list[i] == Worker.current
                                  }
                         );
                    }

                    xfromWorker.send("ready? " + w.ToString());
                }


                toWorker.channelMessage +=
                    e =>
                    {
                        var data = (string)toWorker.receive();
                        // now what?

                        xfromWorker.send("hi from worker " + new { data });
                    };

            }
        }
        public ApplicationSprite()
        {
            //__Thread.InternalWorkerInvoke_4ebbe596_06000030(this);
            //this.__out_Method_6d788eff_06000003();

            // "X:\jsc.svn\examples\actionscript\async\AsyncWorkerTask\AsyncWorkerTask.sln"
            // X:\jsc.svn\examples\actionscript\async\AsyncWorkerTask\AsyncWorkerTask\ApplicationSprite.cs
            // X:\jsc.svn\examples\actionscript\FlashWorkerExperiment\FlashWorkerExperiment\ApplicationSprite.cs


            // https://forums.adobe.com/thread/1164500

            // this looks like chrome context capture
            #region worker
            if (!Worker.current.isPrimordial)
            {
                var sw = Stopwatch.StartNew();

                // iOS workers is still on the roadmap.  I don't have a release date, but I know it'll be an extended beta type of feature.  
                // Most of the concurrency work was gated on the new AOT compiler work, which is still being actively worked on.  
                // Lots of bug and performance fixes were added to AIR 15 and we're not stopping there.

                var xfromWorker = (MessageChannel)Worker.current.getSharedProperty("fromWorker");

                var FunctionToken_TypeFullName = (string)Worker.current.getSharedProperty("FunctionToken_TypeFullName");
                var FunctionToken_MethodName = (string)Worker.current.getSharedProperty("FunctionToken_MethodName");
                var arg0 = (string)Worker.current.getSharedProperty("arg0");

                //               enter click
                //{ { data = message from worker { { FunctionToken_TypeFullName = TestThreadStart.TheOtherClass, FunctionToken_MethodName = Invoke_6d788eff_0600001c } }, ElapsedMilliseconds = 1713 } }


                IntPtr pp = __IntPtr.OfFunctionToken(null,
                    FunctionToken_TypeFullName,
                    FunctionToken_MethodName
                );


                MethodInfo mm = new __MethodInfo { _Method = pp };

                //    t.text = "after invoke " + new { TheOtherClass.SharedField, sw.ElapsedMilliseconds };

                //xfromWorker.send("message from worker " + new { FunctionToken_TypeFullName, FunctionToken_MethodName });

                //throw null;



                mm.Invoke(null, new object[] { arg0 });

                //               enter click
                //{ { ElapsedMilliseconds = 3103, data = message from worker { { ElapsedMilliseconds = 3057, SharedField = { { data = null, i = 65534, j = 3 } } } } } }
                // {{ ElapsedMilliseconds = 3399, data = message from worker {{ ElapsedMilliseconds = 3352, SharedField = {{ data = hello world, i = 65534, j = 3 }} }} }}

                xfromWorker.send("message from worker " + new { sw.ElapsedMilliseconds, TheOtherClass.SharedField });

                return;
            }
            #endregion

            // {{ os = Windows 7, version = WIN 15,0,0,189, length = 333983, Target = null, Method = { _Target = , _Method = IntPtr { StringToken = , FunctionToken = function Function() {}, ClassToken =  } } }}
            // start0 = new __ParameterizedThreadStart(null, __IntPtr.op_Explicit_4ebbe596_06001686(TheOtherClass.Invoke_6d788eff_0600000c));
            //      start0 = new __ParameterizedThreadStart(null, __IntPtr.OfFunctionToken_4ebbe596_06001687(TheOtherClass.Invoke_6d788eff_0600000c,"TestThreadStart.TheOtherClass","Invoke_6d788eff_0600000c"));
            ParameterizedThreadStart y = TheOtherClass.Invoke;

            // can we call the method
            //            0007 0200034c ScriptCoreLib::ScriptCoreLib.ActionScript.Extensions.ZipFileEntry + Cookie`1

            //Unhandled Exception: System.AggregateException: One or more errors occurred. --->System.InvalidOperationException: internal compiler error at method
            // assembly: X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\bin\Debug\ScriptCoreLib.dll at
            // type: ScriptCoreLib.ActionScript.BCLImplementation.System.__Single, ScriptCoreLib, Version=4.5.0.0, Culture=neutral, PublicKeyToken=null
            // method: CompareTo
            // Object reference not set to an instance of an object.
            //    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
            //   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
            //   at jsc.Script.CompilerBase.  .    (Type , MethodBase , LocalVariableInfo , CompilerBase )
            //   at jsc.Script.CompilerBase.<WriteVariableName>b__0(Type , MethodBase , LocalVariableInfo )

            //           Unhandled Exception: System.AggregateException: One or more errors occurred. --->System.InvalidOperationException: internal compiler error at method
            //assembly: X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\bin\Debug\ScriptCoreLib.dll at
            //type: ScriptCoreLib.ActionScript.BCLImplementation.System.__BitConverter, ScriptCoreLib, Version=4.5.0.0, Culture=neutral, PublicKeyToken=null
            //method: GetBytes
            //Object reference not set to an instance of an object.
            //   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
            //  at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
            //  at jsc.Script.CompilerBase.  .    (Type , MethodBase , LocalVariableInfo , CompilerBase )


            //{{ os = Windows 7, version = WIN 15,0,0,189, length = 334356, Target = null, Method = { _Target = , _Method = IntPtr { StringToken = , FunctionToken = function Function() {}, ClassToken =  } }, z = Type { TypeDescription = 
            // <type name="TestThreadStart::TheOtherClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
            //  <extendsClass type="Class"/>
            //  <extendsClass type="Object"/>
            //  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
            //  <method name="Invoke_6d788eff_0600000c" declaredBy="TestThreadStart::TheOtherClass" returnType="void">
            //    <parameter index="1" type="Object" optional="false"/>
            //  </method>
            //  <factory type="TestThreadStart::TheOtherClass">
            //    <extendsClass type="Object"/>
            //  </factory>
            //</type> } }}

            //          {{ os = Windows 7, version = WIN 15,0,0,189, length = 334570, Target = null, Method = { _Target = , _Method = IntPtr { StringToken = , 
            //FunctionToken = function Function() {}, ClassToken =  } }, FullName = TestThreadStart::TheOtherClass, z = Type { TypeDescription = <type name="TestThreadStart::TheOtherClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
            //  <extendsClass type="Class"/>
            //  <extendsClass type="Object"/>
            //  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
            //  <method name="Invoke_6d788eff_0600000c" declaredBy="TestThreadStart::TheOtherClass" returnType="void">
            //    <parameter index="1" type="Object" optional="false"/>
            //  </method>
            //  <factory type="TestThreadStart::TheOtherClass">
            //    <extendsClass type="Object"/>
            //  </factory>
            //</type> }, zz = Type { TypeDescription = <type name="TestThreadStart::TheOtherClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
            //  <extendsClass type="Class"/>
            //  <extendsClass type="Object"/>
            //  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
            //  <method name="Invoke_6d788eff_0600000c" declaredBy="TestThreadStart::TheOtherClass" returnType="void">
            //    <parameter index="1" type="Object" optional="false"/>
            //  </method>
            //  <factory type="TestThreadStart::TheOtherClass">
            //    <extendsClass type="Object"/>
            //  </factory>
            //</type> } }}

            //var z = typeof(TheOtherClass);
            //var zz = Type.GetType("TestThreadStart::TheOtherClass");
            //var zz = Type.GetType("TestThreadStart.TheOtherClass");

            //var zMethod = z.GetMethods();

            __MethodInfo p = y.Method;

            //{ { os = Windows 7, version = WIN 15,0,0,189, length = 335268, 
            // FunctionToken_TypeFullName = TestThreadStart.TheOtherClass, 
            // FunctionToken_MethodName = Invoke_6d788eff_0600000c 
            // } }

            //var pt = Type.GetType(p._Method.FunctionToken_TypeFullName);




            //new ParameterizedThreadStart(null, pp);

            //new Delegate();




            var t = new TextField
            {
                multiline = true,
                //wordWrap = true,

                // {{ InternalPrimordialSprite = null, os = Windows 7, version = WIN 15,0,0,189, length = 353988, FunctionToken_TypeFullName = TestThreadStart.TheOtherClass, FunctionToken_MethodName = Invoke_6d788eff_06000016 }}

                text = new
                {
                    // did the compiler set it yet?
                    __Thread.InternalPrimordialSprite,

                    // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Capabilities.html
                    Capabilities.os,
                    Capabilities.version,

                    //WorkerDomain = WorkerDomain.isSupported,
                    //Worker = Worker.isSupported,
                    //Worker.current.isPrimordial,

                    this.loaderInfo.bytes.length,

                    // {{ os = Windows 7, version = WIN 15,0,0,189, length = 333411, Target = null, Method = { InternalFunctionPointer = function Function() {} } }}

                    //y.Target,

                    // first step is to call a static method on the other side of thread
                    //y.Method,
                    //y.Method,
                    //y.Method.DeclaringType


                    //z.FullName,

                    //z,

                    p._Method.FunctionToken_TypeFullName,
                    p._Method.FunctionToken_MethodName,

                }.ToString(),

                autoSize = TextFieldAutoSize.LEFT
            };

            t.AttachTo(this);

            t.click += delegate
            {
                var sw = Stopwatch.StartNew();

                t.text = "enter click";

                var w = WorkerDomain.current.createWorker(
                     this.loaderInfo.bytes
                 );

                //p._Method.FunctionToken_TypeFullName,
                //p._Method.FunctionToken_MethodName

                w.setSharedProperty("FunctionToken_TypeFullName", p._Method.FunctionToken_TypeFullName);
                w.setSharedProperty("FunctionToken_MethodName", p._Method.FunctionToken_MethodName);
                w.setSharedProperty("arg0", "hello world");

                var fromWorker = w.createMessageChannel(Worker.current);
                w.setSharedProperty("fromWorker", fromWorker);

                fromWorker.channelMessage +=
                        e =>
                        {
                            var data = (string)fromWorker.receive();

                            t.appendText(

                                "\n " + new { sw.ElapsedMilliseconds, data }.ToString()

                                );

                        };

                t.text = "enter click";
                w.start();


                //try
                //{
                //    // catch {{ err = ArgumentError: Error #1063: Argument count mismatch on TestThreadStart::TheOtherClass$/Invoke_6d788eff_06000013(). Expected 1, got 0. }}

                //    mm.Invoke(null, new object[1]);
                //    t.text = "after invoke " + new { TheOtherClass.SharedField, sw.ElapsedMilliseconds };
                //}
                //catch (Exception err)
                //{
                //    t.text = "catch " + new { err };
                //}


            };
        }
		// X:\util\air17_sdk_sa_win
		// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201409/20140911

		public ApplicationSprite()
		{
			// X:\jsc.svn\examples\actionscript\air\AIRStageWebViewExperiment\AIRStageWebViewExperiment\ApplicationSprite.cs

			// http://stackoverflow.com/questions/3170585/get-ip-address-with-adobe-air-2

			var t = new TextField
			{
				text = new
				{
					// http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Capabilities.html
					Capabilities.os,
					Capabilities.version,
					Capabilities.playerType,


					//Error   CS0117  'Capabilities' does not contain a definition for 'cpuArchitecture'  AIRServerSocketExperiment   X:\jsc.svn\examples\actionscript\air\AIRServerSocketExperiment\AIRServerSocketExperiment\ApplicationSprite.cs   29

#if FPARTIAL
					Capabilities.cpuArchitecture,
					Capabilities.touchscreenType,
#endif

					// why is this commented out?
					//WorkerDomain = WorkerDomain.isSupported,

					// http://na5.brightidea.com/ct/ct_a_view_idea.bix?c=9D564F43-979A-4E35-AA21-85A61B6AB8DE&idea_id=F353B3CC-5F05-45E7-9A73-1093E0A1F9DD

					NetworkInfo = NetworkInfo.isSupported,
					//Worker.current.isPrimordial,

					this.loaderInfo.bytes.length
				}.ToString(),

				autoSize = TextFieldAutoSize.LEFT
			};

			t.AttachTo(this);



			//V:\web\AIRServerSocketExperiment\ApplicationSprite.as(46): col: 127 Error: Implicit coercion of a value of type __AS3__.vec:Vector.<flash.net:NetworkInterface> to an unrelated type __AS3__.vec:Vector.<*>.

			//            LinqExtensions.WithEach_f7a1155f_06000027(CommonExtensions.AsEnumerable_4ebbe596_06001850(NetworkInfo.networkInfo.findInterfaces()), new __Action_1(class21, __IntPtr.op_Explicit_4ebbe596_06001412("__ctor_b__1_f7a1155f_06000005")));
			//                                                                                                                              ^

			//{ os = Windows 7, version = WIN 13,0,0,133, playerType = Desktop, length = 489435 }
			// { name = {84D54A45-2ACC-42B2-A59B-E01D43897D2D}, displayName = Local Area Connection, active = false }
			// address { address = 169.254.45.8, broadcast = 169.254.255.255 }
			// { name = {978F5176-96B4-49D4-A14D-6CEA5CB3D505}, displayName = Bluetooth Network Connection, active = false }
			// address { address = 169.254.6.204, broadcast = 169.254.255.255 }
			// { name = {CE7A76DF-BCB0-4C3B-8466-D712A03F10A0}, displayName = Wireless Network Connection, active = true }
			// address { address = 192.168.43.252, broadcast = 192.168.43.255 }
			// { name = {846EE342-7039-11DE-9D20-806E6F6E6963}, displayName = Loopback Pseudo-Interface 1, active = true }
			// address { address = ::1, broadcast =  }
			// address { address = 127.0.0.1, broadcast =  }
			// { name = {A5178906-144E-433A-9103-B2EB62A4C21E}, displayName = Teredo Tunneling Pseudo-Interface, active = true }
			// address { address = 2001:0:9d38:6abd:28d1:36ea:3f57:d403, broadcast =  }

			if (Capabilities.playerType == "Desktop")
			{
				// we dont want to crash flash player!
				// http://help.adobe.com/en_US/air/build/WS144092a96ffef7cc16ddeea2126bb46b82f-8000.html

				// VerifyError: Error #1014: Class flash.net::NetworkInterface could not be found.

				var ii = NetworkInfo.networkInfo.findInterfaces();
				for (int ij = 0; ij < ii.length; ij++)
				{
					var i = ii[ij];

					t.appendText("\n " + new { i.name, i.displayName, i.active });

					var aa = i.addresses;

					for (int aj = 0; aj < aa.length; aj++)
					{
						var a = aa[aj];

						t.appendText("\n address " + new { a.address, a.broadcast, a.ipVersion });
					}
				}

			}

			//V:\web\AIRServerSocketExperiment\ApplicationSprite___c__DisplayClass3.as(28): col: 105 Error: 
			// Implicit coercion of a value of type __AS3__.vec:Vector.<flash.net:InterfaceAddress> 
			// to an unrelated type __AS3__.vec:Vector.<*>.

			//            LinqExtensions.WithEach_f7a1155f_06000022(CommonExtensions.AsEnumerable_4ebbe596_06001850(i.addresses), new __Action_1(this, __IntPtr.op_Explicit_4ebbe596_06001413(this.__ctor_b__2_f7a1155f_06000006)));
			//                                                                                                        ^





			//i.addresses.AsEnumerable().WithEach(
			//    a =>
			//    {
			//    }
			//);





			////if (Capabilities.playerType == CapabilitiesPlayerType)
			//var s = new ServerSocket();
			//s.bind(8080);


			//s.connect +=
			//    e =>
			//    {

			//    };

			//s.listen(30);
		}
        public FlashTowerDefenseSized(int DefaultWidth, int DefaultHeight)
        {

            var bg = new Sprite { x = 0, y = 0 };

            //bg.graphics.beginFill(0xffffff);
            //bg.graphics.beginFill(0x808080);
            //bg.graphics.drawRect(0, 0, Width / 2, Height);



            var warzone = new Sprite { x = 0, y = 0 };

            warzone.graphics.beginFill(ColorWhite);
            warzone.graphics.drawRect(-OffscreenMargin, -OffscreenMargin, DefaultWidth + 2 * OffscreenMargin, DefaultHeight + 2 * OffscreenMargin);

            warzone.mouseChildren = false;


            GetWarzone = () => warzone;

            bg.AttachTo(GetWarzone());
            warzone.AttachTo(this);

            #region create aim
            this.Aim = new Shape();

            Aim.graphics.lineStyle(4, 0, 1);

            Aim.graphics.moveTo(-8, 0);
            Aim.graphics.lineTo(8, 0);

            Aim.graphics.moveTo(0, -8);
            Aim.graphics.lineTo(0, 8);

            Aim.filters = new[] { new DropShadowFilter() };
            Aim.AttachTo(GetWarzone());
            #endregion


            #region BlurWarzoneOnHover
            this.BlurWarzoneOnHover =
                (txt, HideAim) =>
                {


                    txt.mouseOver +=

                        delegate
                        {
                            if (!txt.mouseEnabled)
                                return;

                            txt.textColor = ColorBlue;
                            txt.filters = null;

                            if (CanFire)
                            {
                                warzone.filters = new[] { new BlurFilter() };

                                if (HideAim)
                                    Aim.visible = false;
                            }
                        };

                    txt.mouseOut +=
                        delegate
                        {

                            txt.filters = new[] { new BlurFilter() };
                            txt.textColor = ColorBlack;

                            if (CanFire)
                            {
                                warzone.filters = null;

                                if (HideAim)
                                    Aim.visible = true;
                            }
                        };
                };
            #endregion


            #region ScoreBoard
            var ScoreBoard = new TextField
            {
                x = 24,
                y = 24,

                defaultTextFormat = new TextFormat
                {
                    size = 12
                },
                autoSize = TextFieldAutoSize.LEFT,
                text = "Defend yourself by shooting those mad sheep.",
                filters = new[] { new BlurFilter() },
                selectable = false,
            };

            //ScoreBoard.AttachTo(this);


            BlurWarzoneOnHover(ScoreBoard, true);
            #endregion



            Action<double, Action> Times =
                (m, h) => (DefaultWidth * DefaultHeight * m).Times(h);

            Action<double, Func<BitmapAsset>> AddDoodads =
                (m, GetImage) => Times(m, () => GetImage().AttachTo(bg).SetCenteredPosition(DefaultWidth.Random(), DefaultHeight.Random()));

            AddDoodads(0.0001, () => Images.grass1.ToBitmapAsset());
            AddDoodads(0.00005, () => Images.bump2.ToBitmapAsset());

            Action StartIngameMusic =
                delegate
                {
                    if (this.IngameMusic != null)
                        this.IngameMusic.stop();

                    this.IngameMusic = Sounds.snd_world.ToSoundAsset().play(0, 999, new SoundTransform(IngameMusicVolume));
                };

            StartIngameMusic();

            Func<Animation> AddCactus = () =>
                new Animation(null, Images.img_cactus)
                {
                    FrameRate = 1000 / 7,
                    AnimationEnabled = true
                };




            Action<double> AddCactusAt = y =>
                {
                    var x = DefaultWidth.Random();

                    AddCactus().AttachTo(GetWarzone()).MoveTo(
                        x, y + Math.Cos(x + y) * DefaultHeight * 0.03);
                };

            (3 + 3.Random()).Times(AddCactusAt.FixParam(DefaultHeight * 0.06));
            (3 + 3.Random()).Times(AddCactusAt.FixParam(DefaultHeight * 0.94));

            PrebuiltTurret = new Animation(Images.img_turret1_gunfire_180, Images.img_turret1_gunfire_180_frames);

            PrebuiltTurret.x = (DefaultWidth - PrebuiltTurret.width) * 0.9;
            PrebuiltTurret.y = (DefaultHeight - PrebuiltTurret.height) / 2;

            PrebuiltTurret.AttachTo(GetWarzone());

            #region Messages
            var ActiveMessages = new List<TextField>();
            var ShowMessageNow = default(Action<string, Action>);

            ShowMessageNow =
                (MessageText, Done) =>
                {

                    var p = new TextField
                    {
                        textColor = ColorWhite,
                        background = true,
                        backgroundColor = ColorBlack,
                        filters = new[] { new GlowFilter(ColorBlack) },
                        autoSize = TextFieldAutoSize.LEFT,
                        text = MessageText,
                        mouseEnabled = false
                    };

                    var y = DefaultHeight - p.height - 32;

                    p.AddTo(ActiveMessages).AttachTo(this).MoveTo((DefaultWidth - p.width) / 2, DefaultHeight);

                    Sounds.snd_message.ToSoundAsset().play();

                    var MessagesToBeMoved = (from TheMessage in ActiveMessages select new { TheMessage, y = TheMessage.y - TheMessage.height }).ToArray();



                    (1000 / 24).AtInterval(
                        t =>
                        {
                            foreach (var i in MessagesToBeMoved)
                            {
                                if (i.TheMessage.y > i.y)
                                    i.TheMessage.y -= 4;

                            }

                            p.y -= 4;

                            if (p.y < y)
                            {
                                t.stop();

                                if (Done != null)
                                    Done();

                                9000.AtDelayDo(
                                    () => p.RemoveFrom(ActiveMessages).FadeOutAndOrphanize(1000 / 24, 0.21)
                                );
                            }
                        }
                    );
                };


            var QueuedMessages = new Queue<string>();

            this.ShowMessage =
                Text =>
                {
                    if (QueuedMessages.Count > 0)
                    {
                        QueuedMessages.Enqueue(Text);
                        return;
                    }

                    // not busy
                    QueuedMessages.Enqueue(Text);

                    var NextQueuedMessages = default(Action);

                    NextQueuedMessages =
                        () => ShowMessageNow(QueuedMessages.Peek(),
                            delegate
                            {
                                QueuedMessages.Dequeue();

                                if (QueuedMessages.Count > 0)
                                    NextQueuedMessages();
                            }
                        );

                    NextQueuedMessages();
                };
            #endregion

            var StatusBar = new Sprite
            {
                mouseEnabled = false,
                mouseChildren = false,
            }.MoveTo(DefaultWidth - 96, DefaultHeight - 64).AttachTo(this);



            #region  WeaponBar
            var WeaponBar = new Sprite
            {
            }.AttachTo(StatusBar);


            var AmmoAvatar = new Sprite().MoveTo(38, 24).AttachTo(WeaponBar);

            Images.Avatars.avatars_ammo.ToBitmapAsset().MoveToCenter().AttachTo(AmmoAvatar);

            var AmmoText = new TextField
            {
                defaultTextFormat = new TextFormat
                {
                    bold = true,
                    size = 20,
                    font = "_sans"
                },
                text = "200000",
                filters = new[] { new GlowFilter(ColorBlack, 0.5) },
                autoSize = TextFieldAutoSize.RIGHT,
                x = 0,
                width = 0
            }.AttachTo(AmmoAvatar);




            var WeaponAvatar = new Sprite().AttachTo(WeaponBar);
            #endregion

            var CurrentTarget = default(Point);
            var CurrentTargetTimer = default(Timer);

            #region Ego
            Ego = new PlayerWarrior
                {
                    filters = new[] { new GlowFilter(ColorGreen) }
                };

            EgoIsOnTheField = () => Ego.parent != null;
            EgoIsAlive = () => Ego.IsAlive;

            Func<bool> EgoCanManTurret = () => !PrebuiltTurretInUse; // look up if there is somebody else in it
            Func<bool> EgoIsCloseToTurret = () => new Point { x = Ego.x - PrebuiltTurret.x, y = Ego.y - PrebuiltTurret.y }.length < 32;

            var EgoAimDistance = 48;
            var EgoAimMoveSpeed = 0.1;
            var EgoMoveSpeed = 3.0;
            var EgoMoveToMouseTarget = false;

            UpdateEgoAim =
                delegate
                {
                    Aim.MoveTo(Ego.x + Math.Cos(EgoAimDirection) * EgoAimDistance, Ego.y + Math.Sin(EgoAimDirection) * EgoAimDistance);
                };


            EgoMovedSlowTimer = new Timer(200, 1);

            Ego.FoundNewWeapon +=
                weapon => ShowMessage("You found " + weapon.Name);

            Ego.FoundMoreAmmo +=
                weapon => ShowMessage("Got ammo for " + weapon.Name);



            Action Reorder =
                delegate
                {
#if Z
                    GetWarzone().Children().OrderBy(i => (double)i.y).
                       ForEach(
                        (k, i) =>
                            k.parent.setChildIndex(k, i)
                    );
#endif

                };

            Action ReorderThrottle = Reorder.ThrottleTo(1000);

            var EgoMoveUpTimer = (1000 / 30).AtInterval(
                delegate
                {
                    if (EgoMoveToMouseTarget)
                    {
                        var p = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y };

                        if (p.length <= EgoMoveSpeed)
                        {
                            // run one the pointer
                            return;
                        }

                        Ego.MoveToArc(p.GetRotation(), EgoMoveSpeed);
                    }
                    else
                        Ego.MoveToArc(EgoAimDirection, EgoMoveSpeed);

                    Ego.x = Math.Min(Math.Max(Ego.x, 0), DefaultWidth);
                    Ego.y = Math.Min(Math.Max(Ego.y, 0), DefaultHeight);
                    ReorderThrottle();

                    UpdateEgoAim();

                    EgoMovedSlowTimer.start();

                    // we moved now let's check for boxes
                    foreach (var BoxToTake in
                                     from ss in Boxes
                                     where new Point { x = Ego.x - ss.x, y = Ego.y - ss.y }.length < 32
                                     select ss)
                    {
                        BoxToTake.RemoveFrom(Boxes).Orphanize();

                        Sounds.sound20.ToSoundAsset().play();

                        if (BoxToTake.WeaponInside == null)
                        {
                            // add stuff, so the player doesn't get bored:D
                            // maybe implment them too? see Diablo.
                            var PowerUps = new[] { 
                                // gta
                                "Double Damage", 
                                "Fast Reload", 
                                "Respect",
                                "Armour",

                                // diablo
                                "Defense", 
                                "Mana", 
                                "Dexerity", 
                                "Experience", 
                                "Stamina", 
                                "Strength", 
                                "Life", 
                                "Replenish Life" 
                            };


                            ShowMessage("+1 " + PowerUps.Random());
                        }
                        else
                        {
                            Ego.AddWeapon(BoxToTake.WeaponInside);
                        }

                        if (NetworkTakeCrate != null)
                            NetworkTakeCrate(BoxToTake.NetworkId);
                    }
                });

            EgoMoveUpTimer.stop();

            var EgoAimMoveTimer = (1000 / 30).AtInterval(
                 delegate
                 {
                     EgoAimDirection += EgoAimMoveSpeed * EgoMoveSpeed;

                     if (EgoAimDirection < 0)
                         EgoAimDirection += Math.PI * 4;

                     EgoAimDirection %= Math.PI * 2;

                     UpdateEgoAim();
                 });
            EgoAimMoveTimer.stop();


            #endregion


            Ego.CurrentWeaponChanged +=
                delegate
                {
                    Sounds.SelectWeapon.ToSoundAsset().play();

                    if (WeaponAvatar.numChildren > 0)
                        WeaponAvatar.getChildAt(0).Orphanize();

                    Ego.CurrentWeapon.Type.Avatar.ToBitmapAsset().MoveToCenter().AttachTo(WeaponAvatar);
                    WeaponBar.filters = new[] { new GlowFilter(Ego.CurrentWeapon.Color) };
                };

            Ego.CurrentWeaponAmmoChanged += () => AmmoText.text = "" + Ego.CurrentWeapon.Ammo;

            SetDefaultWeapon();

            Ego.Die +=
                () =>
                {
                    ShowMessage("Meeeediiic!");
                    ShowMessage("You died a painful death");

                    PlayerWarrior.AutoResurrectDelay.AtDelayDo(
                        delegate
                        {
                            Ego.Revive();

                            if (EgoResurrect != null)
                                EgoResurrect();
                        }
                    );
                };

            #region HealthBar
            var HealthBar = new Sprite
            {
                filters = new[] { new GlowFilter(ColorRed) }
            }.MoveTo(-20, 0).AttachTo(StatusBar);

            var Hearts = new[] 
            {
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(20.DegreesToRadians(), 90).AttachTo(HealthBar),
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(7.DegreesToRadians(), 90).AttachTo(HealthBar),
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(353.DegreesToRadians(), 90).AttachTo(HealthBar),
                Images.Avatars.avatars_heart.ToBitmapAsset().MoveToArc(340.DegreesToRadians(), 90).AttachTo(HealthBar),
            };

            var EgoHeartBeat = default(SoundChannel);

            Ego.HealthChanged +=
                delegate
                {
                    if (EgoHeartBeat == null)
                    {
                        EgoHeartBeat = Sounds.heartbeat3.ToSoundAsset().play();
                        EgoHeartBeat.soundComplete +=
                            e =>
                            {
                                EgoHeartBeat = null;
                            };
                    }

                    if (Ego.Health > 0)
                    {

                        var z = (Ego.Health / Ego.MaxHealth) * Hearts.Length;
                        var f = Math.Floor(z).ToInt32();
                        var a = z % 1;

                        for (int i = 0; i < f; i++)
                        {
                            Hearts[i].alpha = 1;
                        }

                        if (f < Hearts.Length)
                        {
                            Hearts[f].alpha = a;

                            for (int i = f + 1; i < Hearts.Length; i++)
                            {
                                Hearts[i].alpha = 0;
                            }

                        }
                    }
                    else
                    {
                        for (int i = 0; i < Hearts.Length; i++)
                        {
                            Hearts[i].alpha = 0;
                        }
                    }

                    //ShowMessage("h: " + f + " " + a);
                };

            #endregion

            var PrebuiltTurretSound = default(SoundChannel);

            var runaways = 0;
            var score = 0;

            Action UpdateScoreBoard =
                delegate
                {
                    if (!CanFire) return;

                    ScoreBoard.text =
                        new
                        {
                            runaways,
                            gore = (100 * (double)BadGuys.Count(i => !i.IsAlive) / (double)BadGuys.Count()).Round() + "%",
                            score,
                            level = CurrentLevel
                        }.ToString();
                };

            Action<Point> DoMachineGunFire =
                e =>
                {
                    if (Ego.CurrentWeapon.Ammo <= 0)
                        return;


                    Ego.CurrentWeapon.Ammo--;



                    var DamagePointOfOrigin = new Point { x = PrebuiltTurret.x, y = PrebuiltTurret.y };
                    var DamageDirection = new Point { x = e.x - PrebuiltTurret.x, y = e.y - PrebuiltTurret.y }.GetRotation();

                    DoSomeDamage(DamagePointOfOrigin, DamageDirection, WeaponInfo.Machinegun);

                    if (Ego.CurrentWeapon.Ammo <= 0)
                    {
                        Sounds.OutOfAmmo.ToSoundAsset().play();
                        PrebuiltTurret.AnimationEnabled = false;
                        return;
                    }
                };



            PrebuiltTurret.AnimationEnabledChanged +=
                delegate
                {

                    if (PrebuiltTurret.AnimationEnabled)
                    {
                        if (PrebuiltTurretSound == null)
                            PrebuiltTurretSound = Sounds.gunfire.ToSoundAsset().play(0, 999);

                        PrebuiltTurret.filters = new[] { new GlowFilter() };
                    }
                    else
                    {
                        if (PrebuiltTurretSound != null)
                            PrebuiltTurretSound.stop();

                        PrebuiltTurretSound = null;
                        PrebuiltTurret.filters = null;
                    }

                };

            GetWarzone().mouseDown +=
                e =>
                {
                    if (!CanFire) return;

                    // the turret cannot fire without a man behind it
                    if (EgoIsOnTheField())
                        return;

                    if (Ego.CurrentWeapon.Ammo <= 0)
                    {
                        Sounds.OutOfAmmo.ToSoundAsset().play();
                        return;
                    }


                    PrebuiltTurret.AnimationEnabled = true;

                    var p = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(p);


                    CurrentTargetTimer =
                        (1000 / 10).AtInterval(
                            delegate
                            {
                                if (!PrebuiltTurret.AnimationEnabled)
                                {
                                    CurrentTargetTimer.stop();

                                    return;
                                }

                                DoMachineGunFire(CurrentTarget);
                            }
                        );

                };

            GetWarzone().mouseUp +=
                 e =>
                 {
                     PrebuiltTurret.AnimationEnabled = false;
                 };

            GetWarzone().mouseOut +=
                delegate
                {
                    PrebuiltTurret.AnimationEnabled = false;
                };

            GetWarzone().mouseMove +=
                e =>
                {
                    if (!CanFire)
                        return;

                    var p = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(p);


                    if (EgoIsOnTheField())
                    {
                        Mouse.show();
                        return;
                    }


                    Mouse.hide();

                    Aim.x = CurrentTarget.x;
                    Aim.y = CurrentTarget.y;
                };





            Func<double> GetEntryPointY = () => (DefaultHeight * 0.8).FixedRandom() + DefaultHeight * 0.1;



            #region AttachRules
            Func<Actor, Actor> AttachRules =
                a =>
                {
                    if (a == null)
                        throw new Exception("AttachRules");

                    var an = a;

                    //Console.WriteLine("attached KilledByLocalPlayer");


                    a.KilledByLocalPlayer +=
                        delegate
                        {
                            //Console.WriteLine("KilledByLocalPlayer: " + an.ScoreValue);

                            if (NetworkAddKillScore != null)
                                NetworkAddKillScore(an.ScoreValue);
                        };

                    if (a.NetworkId == 0)
                    {
                        a.NetworkId = int.MaxValue.FixedRandom();

                        if (0.5.ByChance())
                        {
                            a.Crate = new Crate
                                {
                                    NetworkId = int.MaxValue.FixedRandom()
                                }.AddTo(Boxes);

                            if (0.7.ByChance())
                            {
                                // add random weapon, note that this is
                                // not a fixed random, so each player
                                // gets different weapon
                                a.Crate.WeaponInside = Weapon.PredefinedWeapons.Random().Clone();
                            }
                        }
                    }

                    a.CorpseAndBloodGone += () => BadGuys.Remove(a);
                    a.Moved +=
                        delegate
                        {
                            if (a.x > (DefaultWidth + OffscreenMargin))
                            {
                                a.Crate = null;

                                a.RemoveFrom(BadGuys).Orphanize();

                                if (CanFire)
                                {
                                    WaveEndCountdown--;
                                    runaways++;

                                    ScoreBoard.textColor = ColorRed;
                                    UpdateScoreBoard();
                                }

                                a.IsAlive = false;
                                // this one was able to run away
                            }
                        };





                    a.Die +=
                        delegate
                        {
                            WaveEndCountdown--;

                            score += a.ScoreValue;
                            UpdateScoreBoard();


                            if (a.Crate != null)
                            {
                                a.Crate.MoveTo(a.x, a.y).AttachTo(GetWarzone());
                            }
                        };

                    a.AttachTo(GetWarzone()).AddTo(BadGuys);

                    if (a.PlayHelloSound != null)
                        a.PlayHelloSound();

                    return a;
                };
            #endregion

            Action EgoTakeNextWeapon = () => Ego.CurrentWeapon = Ego.OtherWeaponsLikeCurrent.Next(i => i == Ego.CurrentWeapon);
            Action EgoTakePreviousWeapon = () => Ego.CurrentWeapon = Ego.OtherWeaponsLikeCurrent.Previous(i => i == Ego.CurrentWeapon);






            GetWarzone().mouseWheel +=
                e =>
                {
                    if (e.delta > 0)
                        EgoTakeNextWeapon();
                    else
                        EgoTakePreviousWeapon();
                };

            var EgoMoveToMouseTargetAntiDoubleClick = default(Timer);

            GetWarzone().mouseDown +=
                e =>
                {
                    if (!EgoIsOnTheField())
                        return;

                    if (!EgoIsAlive())
                        return;

                    var pp = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(pp);

                    var p = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y };

                    EgoAimDirection = p.GetRotation();



                    UpdateEgoAim();

                    EgoMoveToMouseTarget = true;

                    EgoMoveToMouseTargetAntiDoubleClick =
                        200.AtDelayDo(
                        delegate
                        {
                            if (!EgoIsAlive())
                            {
                                Ego.RunAnimation = false;
                                EgoMoveUpTimer.stop();
                                return;
                            }

                            if (!EgoMoveToMouseTarget)
                                return;

                            Ego.RunAnimation = true;
                            EgoMoveSpeed = 2.5;
                            EgoMoveUpTimer.start();
                        }
                    );
                };


            GetWarzone().mouseMove +=
                e =>
                {
                    if (!EgoMoveToMouseTarget)
                        return;

                    if (!EgoIsOnTheField())
                        return;

                    if (!EgoIsAlive())
                        return;

                    var pp = new Point
                    {
                        x = e.stageX,
                        y = e.stageY,
                    };

                    CurrentTarget = this.globalToLocal(pp);

                    var p = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y };


                    EgoAimDirection = p.GetRotation();


                    UpdateEgoAim();
                };

            GetWarzone().mouseUp +=
                e =>
                {
                    if (!EgoMoveToMouseTarget)
                        return;

                    if (!EgoIsAlive())
                        return;

                    if (EgoMoveToMouseTargetAntiDoubleClick != null)
                    {
                        EgoMoveToMouseTargetAntiDoubleClick.stop();
                        EgoMoveToMouseTargetAntiDoubleClick = null;
                    }

                    EgoMoveUpTimer.stop();
                    Ego.RunAnimation = false;
                    EgoMoveToMouseTarget = false;
                };

            GetWarzone().doubleClickEnabled = true;
            GetWarzone().doubleClick +=
              e =>
              {
                  if (!EgoIsOnTheField())
                      return;

                  if (!EgoIsAlive())
                      return;

                  var pp = new Point
                  {
                      x = e.stageX,
                      y = e.stageY,
                  };

                  CurrentTarget = this.globalToLocal(pp);


                  EgoAimDirection = new Point { x = CurrentTarget.x - Ego.x, y = CurrentTarget.y - Ego.y }.GetRotation();

                  UpdateEgoAim();

                  EgoDoFireWeapon();
              };

            Action StageIsReady =
                delegate
                {

                    //stage.scaleMode = StageScaleMode.NO_BORDER;

                    // multiplay ?


                    var WeaponShortcutButtons = new[]
                    {
                        Keyboard.NUMBER_1,
                        Keyboard.NUMBER_2,
                        Keyboard.NUMBER_3,
                        Keyboard.NUMBER_4,
                        Keyboard.NUMBER_5,
                        Keyboard.NUMBER_6,
                        Keyboard.NUMBER_7,
                        Keyboard.NUMBER_8,
                        Keyboard.NUMBER_9,
                        Keyboard.NUMBER_0,
                    }.Select(
                        (Button, Index) =>
                            new KeyboardButton(stage)
                            {
                                Buttons = new[] { Button },
                                Filter = EgoIsAlive,
                                Up = () => Ego.CurrentWeapon = Ego.OtherWeaponsLikeCurrent.AtOrDefault(Index, Ego.CurrentWeapon)
                            }
                    ).ToArray();

                    var KeySpace = new KeyboardButton(stage)
                     {
                         Buttons = new[] { Keyboard.SPACE },
                         Filter = EgoIsOnTheField.And(EgoIsAlive),
                         Up =
                             delegate
                             {
                                 // car brakes, open door, take item

                                 // Add Ammo

                                 foreach (var BarrelToTake in this.Barrels.Where(i => (i.ToPoint() - Ego.ToPoint()).length < 32))
                                 {
                                     Sounds.sound20.ToSoundAsset().play();
                                     Ego.AddWeapon(BarrelToTake.ExplosiveMaterialType);
                                     BarrelToTake.RemoveFrom(Barrels).Orphanize();

                                     if (NetworkUndeployExplosiveBarrel != null)
                                         NetworkUndeployExplosiveBarrel(BarrelToTake.NetworkId);

                                 }
                             }
                     };


                    var KeyLeft = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.A],
                            MovementArrows[Keyboard.LEFT],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                EgoAimMoveSpeed = -0.1;
                                EgoAimMoveTimer.start();
                            },
                        Up = EgoAimMoveTimer.stop,
                    };

                    var KeyRight = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.D],
                            MovementArrows[Keyboard.RIGHT],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                EgoAimMoveSpeed = +0.1;
                                EgoAimMoveTimer.start();
                            },
                        Up = EgoAimMoveTimer.stop,
                    };

                    var KeyUp = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.W],
                            MovementArrows[Keyboard.UP],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                if (!Ego.IsAlive)
                                    return;

                                Ego.RunAnimation = true;
                                EgoMoveSpeed = 2.5;
                                EgoMoveUpTimer.start();
                            },
                        Up =
                            delegate
                            {
                                EgoMoveUpTimer.stop();
                                Ego.RunAnimation = false;
                            }
                    };

                    var KeyDown = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.S],
                            MovementArrows[Keyboard.DOWN],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Down =
                            delegate
                            {
                                if (!Ego.IsAlive)
                                    return;

                                Ego.RunAnimation = true;
                                EgoMoveSpeed = -1.5;
                                EgoMoveUpTimer.start();
                            },
                        Up =
                            delegate
                            {
                                EgoMoveSpeed = 1;
                                EgoMoveUpTimer.stop();
                                Ego.RunAnimation = false;
                            }
                    };

                    var KeyWeaponNext = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.X],
                            MovementArrows[Keyboard.PAGE_UP],
                        },

                        Up = EgoTakeNextWeapon,
                    };

                    var KeyWeaponPrevious = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.Z],
                            MovementArrows[Keyboard.PAGE_DOWN],
                        },
                        Up = EgoTakePreviousWeapon
                    };

                    var KeyControl = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[ new KeyboardKeyInfo { Button = Keyboard.CONTROL, Location = KeyLocation.LEFT } ],
                            MovementArrows[ new KeyboardKeyInfo { Button = Keyboard.CONTROL, Location = KeyLocation.RIGHT  } ],
                        },
                        Filter = EgoIsOnTheField.And(EgoIsAlive),
                        Up = EgoDoFireWeapon
                    };


                    var KeyMusic = new KeyboardButton(stage)
                    {
                        Buttons = new[] { Keyboard.M },
                        Up = () => ToggleMusic()
                    };




                    var KeyEnter = new KeyboardButton(stage)
                    {
                        Groups = new[]
                        {
                            MovementWASD[Keyboard.F],
                            MovementArrows[Keyboard.ENTER],
                        },
                        Filter = EgoIsAlive,
                        Up =
                            delegate
                            {
                                if (EgoIsOnTheField())
                                {
                                    if (EgoIsCloseToTurret())
                                    {
                                        if (EgoCanManTurret())
                                        {


                                            Ego.Orphanize();
                                            Ego.RunAnimation = false;
                                            EgoMoveUpTimer.stop();
                                            EgoAimMoveTimer.stop();
                                            PrebuiltTurretBlinkTimer.stop();
                                            PrebuiltTurret.alpha = 1;

                                            Ego.CurrentWeapon = Ego.Weapons.FirstOrDefault(i => i.SelectMode == Weapon.SelectModeEnum.Turret);

                                            ShowMessage("Machinegun manned!");
                                            Mouse.hide();

                                            if (CurrentTarget != null)
                                            {
                                                Aim.x = CurrentTarget.x;
                                                Aim.y = CurrentTarget.y;
                                            }

                                            Sounds.door_open.ToSoundAsset().play();

                                            if (EgoEnteredMachineGun != null)
                                                EgoEnteredMachineGun();
                                        }
                                        else
                                        {
                                            ShowMessage("Cannot man the machinegun!");
                                        }
                                    }
                                    else
                                    {
                                        ShowMessage("The machinegun is too far! Get closer!");
                                    }
                                }
                                else
                                {
                                    Sounds.door_open.ToSoundAsset().play();


                                    ShowMessage("Machinegun unmanned!");

                                    TeleportEgoNearTurret();
                                    PrebuiltTurret.AnimationEnabled = false;

                                    PrebuiltTurret.alpha = 0.5;
                                    Mouse.show();
                                    PrebuiltTurretBlinkTimer.start();



                                    if (EgoExitedMachineGun != null)
                                        EgoExitedMachineGun();
                                }
                            }
                    };



                };

            PrebuiltTurretBlinkTimer = 500.AtInterval(t => PrebuiltTurret.alpha = ((t.currentCount % 2) + 1) / 2);
            PrebuiltTurretBlinkTimer.stop();

            #region readiness
            if (stage == null)
            {
                this.addedToStage +=
                    delegate
                    {
                        StageIsReady();
                    };
            }
            else
            {
                StageIsReady();
            }
            #endregion

            //Mouse.hide();



            ShowMessage("Aim at the enemy unit and hold down the mouse!");
            ShowMessage("Press 'Enter' to exit the machinegun");
            //ShowMessage("Day " + CurrentLevel);

            GameEvent =
                delegate
                {
                    // do not add if the day is over...
                    //if (WaveEndCountdown <= 0)
                    //    return;

                    AddNewActorsToMap(UpdateScoreBoard, GetEntryPointY, AttachRules);

                };




            ReportDays =
                delegate
                {
                    if (WaveEndCountdown < 0)
                    {
                        if (InterlevelMusic == null)
                        {
                            InterlevelMusic = Sounds.snd_birds.ToSoundAsset().play(0, 999);
                            ShowMessage("Day " + CurrentLevel + " is ending...");

                            if (GameInterlevelBegin != null)
                                GameInterlevelBegin();
                        }

                        if (WaveEndsWhenAllBadGuysAreDead)
                        {
                            // wait for all actors get off stage
                            if (BadGuys.Where(i => i.IsAlive).Any())
                                return;
                        }


                        // show "level END"
                        ShowMessage("Day " + CurrentLevel + " Survived!");

                        ReportDaysTimer.stop();



                        InterlevelTimeout.AtDelayDo(
                            delegate
                            {
                                if (GameInterlevelEnd != null)
                                    GameInterlevelEnd();


                                // maybe higher levels will have more enemies?
                                WaveEndCountdown = 15;
                                CurrentLevel++;

                                // show "level START"
                                ShowMessage("Day " + CurrentLevel);
                                ReportDaysTimer.start();

                                var InterlevelMusicStopping = InterlevelMusic;
                                InterlevelMusic = null;
                                2000.AtDelayDoOnRandom(InterlevelMusicStopping.stop);
                            }
                        );


                        UpdateScoreBoard();

                        return;
                    }


                    if (CanAutoSpawnEnemies)
                    {
                        // new actors if we got less 10 
                        if (InterlevelMusic != null)
                            return;

                        if (BadGuys.Where(i => i.IsAlive).Count() < 8)
                        {

                            GameEvent();
                        }
                    }
                };

            ReportDaysTimer = 1500.AtIntervalDo(ReportDays);


            (1000 / 15).AtInterval(
                delegate
                {


                    Aim.rotation += 1;

                    foreach (var s in
                           from ss in BadGuys
                           where ss.IsAlive
                           select ss)
                        s.x += s.speed;
                }
            );

            //#region powered_by_jsc
            //var powered_by_jsc = new TextField
            //{

            //    x = 32,

            //    defaultTextFormat = new TextFormat
            //    {
            //        size = 24
            //    },
            //    autoSize = TextFieldAutoSize.LEFT,

            //    // how to make a link
            //    // http://www.actionscript.com/Article/tabid/54/ArticleID/actionscript-quick-tips-and-gotchas/Default.aspx
            //    htmlText = "<a href='http://jsc.sf.net' target='_blank'>powered by <b>jsc</b></a>",
            //    selectable = false,
            //    filters = new[] { new BlurFilter() },
            //    textColor = ColorBlack
            //}.AttachTo(this);

            //powered_by_jsc.y = DefaultHeight - powered_by_jsc.height - 32;

            //// make it fade/show in time
            //200.AtInterval(t => 
            //    {
            //        var a = (Math.Sin(t.currentCount * 0.05) + 1) * 0.5;

            //        powered_by_jsc.alpha = a;
            //        powered_by_jsc.mouseEnabled = a > 0.8;
            //    }
            //);

            //#endregion

            ScoreBoard.AttachTo(this);

            //BlurWarzoneOnHover(powered_by_jsc, true);

            40000.AtIntervalOnRandom(
                delegate
                {
                    Sounds.snd_bird2.ToSoundAsset().play();
                }
            );


            #region music on off
            var MusicButton = new Sprite
            {
                x = DefaultWidth - 32,
                y = 32,
                filters = new[] { new GlowFilter(ColorBlueLight) },

            };

            var MusicOn = Images.music_on.ToBitmapAsset().MoveToCenter();
            var MusicOff = Images.music_off.ToBitmapAsset().MoveToCenter();

            MusicButton.mouseOver +=
                delegate
                {
                    Mouse.show();
                    Aim.visible = false;
                };

            MusicButton.mouseOut +=
              delegate
              {
                  Mouse.hide();
                  Aim.visible = true;
              };

            ToggleMusic =
                delegate
                {
                    if (MusicOn.parent == MusicButton)
                    {
                        MusicOn.Orphanize();
                        MusicOff.AttachTo(MusicButton);
                        ShowMessage("Music silenced");
                        IngameMusic.soundTransform = new SoundTransform(0);
                    }
                    else
                    {
                        IngameMusic.soundTransform = new SoundTransform(IngameMusicVolume);
                        ShowMessage("Music activated");

                        MusicOff.Orphanize();
                        MusicOn.AttachTo(MusicButton);
                    }
                };

            MusicButton.click +=
                delegate
                {
                    ToggleMusic();
                };

            MusicOn.AttachTo(MusicButton);

            MusicButton.AttachTo(this);
            #endregion

            Action<InteractiveObject, InteractiveObject> OnMouseDownDisableMouseOnTarget =
                (subject, target) =>
                {
                    subject.mouseDown += delegate { target.mouseEnabled = false; };
                    subject.mouseUp += delegate { target.mouseEnabled = true; };
                };

            OnMouseDownDisableMouseOnTarget(GetWarzone(), MusicButton);
            OnMouseDownDisableMouseOnTarget(GetWarzone(), ScoreBoard);
            //OnMouseDownDisableMouseOnTarget(GetWarzone(), powered_by_jsc);
        }
        public ApplicationSprite()
        {
            var t = new TextField
            {
                text = "click on me to see console",
                autoSize = TextFieldAutoSize.LEFT
            };

            t.MoveTo(16, 16);
            t.AttachTo(this);

            t.click +=
                delegate
                {
                    t.text += "\nclicked!";

                    Console.WriteLine("clicked in flash!");
                };

            this.AtInitializeConsoleFormWriter = (
                Action<string> Console_Write,
                Action<string> Console_WriteLine
            ) =>
            {
                t.appendText("\nAtInitializeConsoleFormWriter");

                try
                {
                    var w = new __OutWriter();

                    var o = Console.Out;

                    var __reentry = false;

                    w.AtWrite =
                        x =>
                        {
                            o.Write(x);

                            if (!__reentry)
                            {
                                __reentry = true;
                                Console_Write(x);
                                __reentry = false;
                            }
                        };

                    w.AtWriteLine =
                        x =>
                        {
                            o.WriteLine(x);

                            if (!__reentry)
                            {
                                __reentry = true;
                                Console_WriteLine(x);
                                __reentry = false;
                            }
                        };

                    Console.SetOut(w);

                    Console.WriteLine("flash Console.WriteLine should now appear in JavaScript form!");
                    t.appendText("\nAtInitializeConsoleFormWriter done");
                }
                catch (Exception ex)
                {
                    t.appendText("\n error: " + new { ex, Console_Write, Console_WriteLine });

                }
            };

        }
        public ApplicationSprite()
        {
            // X:\jsc.svn\examples\actionscript\FlashMP3PitchExperiment\FlashMP3PitchExperiment\Library\MP3Pitch.cs
            // X:\jsc.svn\examples\actionscript\Test\TestThreadStartInternalWorkerInvoke\TestThreadStartInternalWorkerInvoke\ApplicationSprite.cs

            // X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\ApplicationSprite.cs

            // jsc should return before getting here from the worker
            if (!Worker.current.isPrimordial)
                return;

            var t = new TextField
            {
                multiline = true,
                text = new
                {
                    __Thread.InternalPrimordialSprite,
                    this.loaderInfo.bytes.length,
                }.ToString(),
                autoSize = TextFieldAutoSize.LEFT
            };

            t.AttachTo(this);

            t.click += delegate
            {
                var sw = Stopwatch.StartNew();

                t.text = "enter click";



                __Thread tt = new Thread(
                    new ParameterizedThreadStart(
                        data =>
                        {
                            // can we render audio on the background thread now?
                            // what else can AIR do on a background thread?
                            // physics?
                            // LAN calc?

                            // how can we report to the UI thread?

                            var nn = Stopwatch.StartNew();


                            //int i = 0;

                            //// keep core2 buzy for a while to be noticed on the task manager
                            //while (nn.ElapsedMilliseconds < 10000)
                            //{
                            //    SharedField = new
                            //    {
                            //        data,
                            //        i,
                            //        nn.ElapsedMilliseconds
                            //        //, Thread.CurrentThread.ManagedThreadId 
                            //    }.ToString();

                            //    i++;
                            //}

                            // http://stackoverflow.com/questions/16483863/flash-workers-sample-application-not-working
                            // http://probertson.com/articles/2012/11/07/as3-concurrency-workers-use-cases-best-practices-links/

                            // i cant hear it
                            // http://stackoverflow.com/questions/11902863/can-actionscript-workers-be-used-to-play-generate-sounds-in-a-separate-thread
                            // http://flexmonkey.blogspot.com/2012/09/multi-threaded-sound-synthesis-in-flex.html

                            var p = new MP3Pitch("http://visit.abstractatech.com/assets/com.abstractatech.web.design1/AbstractatechPostProductionVersion7.mp3")
                            {
                                //_rate = p._rate
                            };

                            // i wonder, can we switch to UI thread via await and then back?



                            var xfromWorker = (MessageChannel)Worker.current.getSharedProperty("fromWorker");
                            // or are we to capture all fields modified within worker and only update those?
                            xfromWorker.send("message from worker " + new { SharedField });

                            // how do we signal our work is done?
                        }
                    )
                );

                tt.InternalBeforeStart =
                    w =>
                    {
                        // how are we supposed to get data back from the worker?

                        var fromWorker = w.createMessageChannel(Worker.current);
                        w.setSharedProperty("fromWorker", fromWorker);

                        fromWorker.channelMessage += e =>
                        {
                            var data = (string)fromWorker.receive();

                            t.appendText(

                                "\n " + new { sw.ElapsedMilliseconds, data }.ToString()

                                );

                        };
                    };

                //Thread.AllocateNamedDataSlot("").

                //Thread.SetData(
                tt.Start("hello world");
            };

        }
Ejemplo n.º 12
0
        public const uint ForegroundColor = 0x202020;//(uint)(0xffffff ^ BackgroundColor);

        /// <summary>
        /// Default constructor
        /// </summary>
        public FlashZIndex()
        {
            var c = new Sprite
            {
            };


            //c.graphics.beginFill(BackgroundColor);
            //c.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
            //c.graphics.endFill();

            Func<string, string, string> ToSize =
                (e, size) => "<font size='" + size + "'>" + e + "</font>";

            Func<string, string, string> ToColor =
                (e, color) => "<font color='#" + color + "'>" + e + "</font>";

            var keywords = new[] { "from", "this", " in", "orderby", " is", " descending", "select" };

            Func<string, string> Colorize =
                e =>
                {
                    foreach (var keyword in keywords.OrderByDescending(i => i.Length))
                    {
                        e = e.Replace(keyword, ToColor(keyword, "0000ff"));
                    }

                    return e;
                };

            var t = new TextField
            {
                autoSize = TextFieldAutoSize.LEFT,
                defaultTextFormat = new TextFormat
                {
                    size = 15,
                    color = ForegroundColor
                },
                mouseEnabled = false,
                filters = new[] { new DropShadowFilter() },
                multiline = true,
                condenseWhite = true,
                x = 8,
           
                htmlText =

                Colorize(

                    ToSize("flash zIndex example powered by <b>jsc</b>", "24") + "<br />"
                    + @"click on the background to create<br /> or drag to see zIndex in effect<br /><br />"
                    + ToColor(@"
                        from v in this.Children() <br />
                        orderby v is TextField descending, v.y, v.x <br />
                        select v
                    ", "000000")
                )
            };

            c.AttachTo(this);
            t.AttachTo(this);

            c.doubleClickEnabled = true;

            Action Reorder =
                delegate
                {
                    Action<DisplayObject, int> SetZIndex =
                        (k, i) => k.parent.setChildIndex(k, i);

                    SetZIndex.ForEach(
                        from v in this.GetChildren()
                        orderby v is TextField descending, v.y, v.x
                        select v
                    );



                };

            Action ReorderThrottle = Reorder.ThrottleTo(500);

            c.click +=
                q =>
                {
                    var x = q.stageX;
                    var y = q.stageY;

                    AddSprite(ReorderThrottle, x, y);

                    ReorderThrottle();
                };

            10.To(90)(i => AddSprite(
                ReorderThrottle, 
                stage.stageWidth * i / 100, 
                stage.stageHeight.Random(0.6, 0.9)
                )
                );

            Reorder();
        }
        /// <summary>
        /// Default constructor
        /// </summary>
        public FlashGoogleMapsExample()
        {
            var MyMap = this;

            // lets create a hyperlink
            var powered_by_jsc = new TextField
            {

                x = 72,
                y = 32,

                defaultTextFormat = new TextFormat
                {
                    size = 24
                },
                autoSize = TextFieldAutoSize.LEFT,
                htmlText = "<a href='http://jsc.sf.net' target='_blank'>powered by <b>jsc</b></a>",
                selectable = false,
                filters = new[] { new BlurFilter() },
                textColor = ColorWhite
            }.AttachTo(this);

            // based on http://code.google.com/p/gmaps-samples-flash/source/browse/trunk/samplecode/com/google/maps/examples/HelloWorld.as


            //MyMap.width = 500;
            //MyMap.height = 400;

            // This key is good for all URLs in this directory:
            // http://jsc.sourceforge.net/
            MyMap.key = "ABQIAAAAP8RnR45oCW_IQn841NsRUxTWTeJzEP4t7om06_BG8dFdNnzkzRSRwPJSLIikpLP_90z2Fvj1rJhFWw";

            CommonExtensions.CombineDelegate(MyMap,

                (MapEvent e) =>
                {
                    MyMap.setCenter(new LatLng(40.736072, -73.992062), 14, MapType.HYBRID_MAP_TYPE);

                    var status = new TextField
                    {
                        x = 64,
                        y = 164,
                        autoSize = TextFieldAutoSize.LEFT,
                        background = true,
                        mouseEnabled = false,
                        backgroundColor = ColorBlack,
                        textColor = ColorWhite,
                        filters = new[] { new GlowFilter(ColorBlack) }
                    }.AttachTo(this);

                    //MyMap.MapMoveStep += e =>
                    //    {
                    //        status.text = "move: " + e.latLng.ToString();
                    //    };

                    //MyMap.MapClick += e =>
                    //    {
                    //        status.text = "click: " + e.latLng.ToString();
                    //    };
                    powered_by_jsc.AttachTo(this);
                }

                , MapEvent.MAP_READY);



            MyMap.addControl(new ZoomControl());
            MyMap.addControl(new PositionControl());
            MyMap.addControl(new MapTypeControl());


            this.contextMenu = new ContextMenu();
            this.contextMenu.hideBuiltInItems();

            #region powered by jsc

        



            powered_by_jsc.mouseOver +=

                                   delegate
                                   {

                                       powered_by_jsc.textColor = ColorYellow;
                                       powered_by_jsc.filters = new[] { new DropShadowFilter() };


                                   };

            powered_by_jsc.mouseOut +=
                delegate
                {
                    powered_by_jsc.filters = new[] { new BlurFilter() };
                    powered_by_jsc.textColor = ColorWhite;

                };

            #endregion
        }
Ejemplo n.º 14
0
		private void Initialize()
		{
			txtMain = new TextField
			{
				defaultTextFormat = new TextFormat
				{
					font = "Verdana",
					align = TextFormatAlign.LEFT,
					size = 10,
					color = 0xffffff
				},
				autoSize = TextFieldAutoSize.LEFT,
				text = "0"
			};

			AddFullscreenMenu();





			EgoView = new ViewEngineBase(DefaultWidth, DefaultHeight)
			{
				FloorAndCeilingVisible = false,

				ViewPosition = new Point { x = 4, y = 22 },
				ViewDirection = 90.DegreesToRadians(),

			};

			var Portals = new List<PortalInfo>();

			EgoView.ViewDirectionChanged += () => Portals.ForEach(Portal => Portal.View.ViewDirection = EgoView.ViewDirection);

			#region create a dual portal
			var PortalA = new PortalInfo
			{
				Color = 0xFF6A00,
				ViewVector = new Vector { Direction = EgoView.ViewDirection, Position = new Point { x = 4.5, y = 14 } },
				SpriteVector = new Vector { Direction = EgoView.ViewDirection, Position = new Point { x = 3.5, y = 20 } },
			}.AddTo(Portals);


			EgoView.Sprites.Add(PortalA.Sprite);


			var PortalB = new PortalInfo
			{
				Color = 0xff00,
				ViewVector = PortalA.SpriteVector,
				SpriteVector = PortalA.ViewVector,
			}.AddTo(Portals);


			EgoView.Sprites.Add(PortalB.Sprite);
			#endregion



			var Ego = default(SpriteInfo);


			EgoView.ViewPositionChanged +=
				delegate
				{
					foreach (var Portal in Portals)
					{
						var p = EgoView.SpritesFromPointOfView.SingleOrDefault(i => i.Sprite == Portal.Sprite);

						if (p != null)
						{
							if (p.Distance < Portal.Sprite.Range)
							{
								// we are going thro the portal, show it

								new Bitmap(EgoView.Buffer.clone())
								{
									scaleX = DefaultScale,
									scaleY = DefaultScale
								}.AttachTo(this).FadeOutAndOrphanize(1000 / 24, 0.2);

								Assets.SoundFiles.teleport.ToSoundAsset().play();

								// fixme: should use Ego.MovementDirection instead
								// currently stepping backwards into the portal will behave recursivly
								EgoView.ViewPosition = Portal.View.ViewPosition.MoveToArc(EgoView.ViewDirection, Portal.Sprite.Range + p.Distance);

								break;
							}
						}
					}

				};

			var CameraView = new ViewEngineBase(64, 48)
			{
			};


			EgoView.RenderOverlay += DrawMinimap;
			EgoView.FramesPerSecondChanged += () => txtMain.text = EgoView.FramesPerSecond + " fps " + new { EgoView.ViewPositionX, EgoView.ViewPositionY };

			EgoView.Image.AttachTo(this);

			txtMain.AttachTo(this);



			EgoView.Image.scaleX = DefaultScale;
			EgoView.Image.scaleY = DefaultScale;
			//this.filters = new[] { new BlurFilter() };


			KeyboardButton fKeyTurnLeft = new uint[] { Keyboard.LEFT, 'j', 'J', };
			KeyboardButton fKeyTurnRight = new uint[] { Keyboard.RIGHT, 'l', 'L', };

			KeyboardButton fKeyStrafeLeft = new uint[] { 'a', 'A' };
			KeyboardButton fKeyStrafeRight = new uint[] { 'd', 'D' };

			KeyboardButton fKeyUp = new uint[] { Keyboard.UP, 'i', 'I', 'w', 'W' };
			KeyboardButton fKeyDown = new uint[] { Keyboard.DOWN, 'k', 'K', 's', 'S' };


			stage.keyDown +=
				e =>
				{
					var key = e.keyCode;

					fKeyStrafeLeft.ProcessKeyDown(key);
					fKeyStrafeRight.ProcessKeyDown(key);
					fKeyTurnLeft.ProcessKeyDown(key);
					fKeyTurnRight.ProcessKeyDown(key);

					fKeyUp.ProcessKeyDown(key);
					fKeyDown.ProcessKeyDown(key);


				};

			stage.keyUp +=
				e =>
				{
					var key = e.keyCode;


					fKeyStrafeLeft.ProcessKeyUp(key);
					fKeyStrafeRight.ProcessKeyUp(key);

					fKeyTurnLeft.ProcessKeyUp(key);
					fKeyTurnRight.ProcessKeyUp(key);

					fKeyUp.ProcessKeyUp(key);
					fKeyDown.ProcessKeyUp(key);

				};


			Action UpdateEgoPosition =
				delegate
				{
					if (Ego != null)
					{
						Ego.Position = EgoView.ViewPosition;
						Ego.Direction = EgoView.ViewDirection;
					}
				};

			EgoView.ViewPositionChanged +=
				delegate
				{
					UpdateEgoPosition();
				};

			(1000 / 30).AtInterval(
					delegate
					{
						if (fKeyTurnRight.IsPressed)
							EgoView.ViewDirection += 10.DegreesToRadians();
						else if (fKeyTurnLeft.IsPressed)
							EgoView.ViewDirection -= 10.DegreesToRadians();

						if (fKeyUp.IsPressed || fKeyStrafeLeft.IsPressed || fKeyStrafeRight.IsPressed)
						{
							var d = EgoView.ViewDirection;



							if (fKeyStrafeLeft.IsPressed)
								d -= 90.DegreesToRadians();
							else if (fKeyStrafeRight.IsPressed)
								d += 90.DegreesToRadians();


							EgoView.MoveTo(
									EgoView.ViewPositionX + Math.Cos(d) * 0.2,
									EgoView.ViewPositionY + Math.Sin(d) * 0.2
							);
						}
						else if (fKeyDown.IsPressed)
							EgoView.MoveTo(
								 EgoView.ViewPositionX + Math.Cos(EgoView.ViewDirection) * -0.2,
								 EgoView.ViewPositionY + Math.Sin(EgoView.ViewDirection) * -0.2
						 );


					}
			);

			var UpdatePortals = true;

			stage.keyUp +=
				   e =>
				   {
					   if (e.keyCode == Keyboard.V)
					   {
						   UpdatePortals = !UpdatePortals;
					   }

					   if (e.keyCode == Keyboard.N)
					   {
						   EgoView.RenderLowQualityWalls = !EgoView.RenderLowQualityWalls;
					   }

					   if (e.keyCode == Keyboard.M)
					   {
						   DrawMinimapEnabled = !DrawMinimapEnabled;
					   }

					   if (e.keyCode == Keyboard.B)
					   {
						   EgoView.SpritesVisible = !EgoView.SpritesVisible;
					   }

					   if (e.keyCode == Keyboard.F)
					   {
						   EgoView.FloorAndCeilingVisible = !EgoView.FloorAndCeilingVisible;
					   }

					   if (e.keyCode == Keyboard.DELETE)
					   {
						   EgoView.Sprites.RemoveAll(p => p != Ego);
					   }
				   };


			Action<Bitmap[]> BitmapsLoadedAction =
				Bitmaps =>
				{
					if (Bitmaps == null)
						throw new Exception("No bitmaps");

					Func<Texture64[], Texture64[]> Reorder8 =
						p =>
							Enumerable.ToArray(
								from i in Enumerable.Range(0, 8)
								select p[(i + 6) % 8]
							);

					var BitmapStream = Bitmaps.Select(i => (Texture64)i).GetEnumerator();

					Func<Texture64[]> Next8 =
						delegate
						{
							// keeping compiler happy with full delegate form

							if (BitmapStream == null)
								throw new Exception("BitmapStream is null");

							return Reorder8(BitmapStream.Take(8));
						};


					var Stand = Next8();
					var Spawn = default(Func<SpriteInfo>);

					if (Bitmaps.Length == 8)
					{
						Spawn = () => CreateWalkingDummy(Stand);
					}
					else
					{
						var Walk = new[]
                        {
                            Next8(),
                            Next8(),
                            Next8(),
                            Next8(),
                        };



						Spawn = () => CreateWalkingDummy(Stand, Walk);
					}

					Ego = Spawn();


					UpdateEgoPosition();



					stage.keyUp +=
						  e =>
						  {
							  if (e.keyCode == Keyboard.SPACE)
							  {
								  var s = Spawn();

								  //s.Direction += 180.DegreesToRadians();

								  CameraView.ViewPosition = s.Position;
								  CameraView.ViewDirection = s.Direction;
							  }

							  if (e.keyCode == Keyboard.INSERT)
							  {
								  var s = Spawn();

								  s.Direction += 180.DegreesToRadians();
								  s.Position = Ego.Position.MoveToArc(Ego.Direction, 0.5);
							  }

							  if (e.keyCode == Keyboard.ENTER)
							  {
								  EgoView.ViewPosition = new Point { x = 4, y = 22 };
								  EgoView.ViewDirection = 270.DegreesToRadians();


							  }



							  if (e.keyCode == Keyboard.BACKSPACE)
							  {

								  (1000 / 30).AtInterval(
									  t =>
									  {
										  EgoView.ViewDirection += 18.DegreesToRadians();

										  if (t.currentCount == 10)
											  t.stop();
									  }
								  );
							  }
						  };
				};


			Assets.ZipFiles.MyZipFile
				.ToFiles()
				.Where(f => f.FileName.EndsWith(".png"))
				.ToBitmapArray(BitmapsLoadedAction);



			Assets.ZipFiles.MyStuff.ToFiles().ToBitmapDictionary(
					f =>
					{
						// ! important
						// ----------------------------------------------------
						// ! loading png via bytes affects pixel values
						// ! this is why map is in gif format

						EgoView.Map.WorldMap = Texture32.Of(f["Map1.gif"], false);

						Action<IEnumerator<Texture64.Entry>, Texture64, Action<SpriteInfo>> AddSpriteByTexture =
								  (SpaceForStuff, tex, handler) => SpaceForStuff.Take().Do(p => CreateDummy(tex).Do(handler).Position.To(p.XIndex + 0.5, p.YIndex + 0.5));

						var FreeSpaceForStuff = EgoView.Map.WorldMap.Entries.Where(i => i.Value == 0).Randomize().GetEnumerator();

						Action<Bitmap> AddSprite =
							e => AddSpriteByTexture(FreeSpaceForStuff, e, null);

						Assets.ZipFiles.MySprites.ToFiles().ToBitmapArray(
						   sprites =>
						   {
							   foreach (var s in sprites)
							   {
								   for (int i = 0; i < 3; i++)
								   {
									   AddSprite(s);
								   }
							   }
						   }
						);
						#region gold

						Assets.ZipFiles.MyGold.ToFiles().ToBitmapArray(
						   sprites =>
						   {
							   var GoldSprites = new List<SpriteInfo>();

							   foreach (var s in sprites)
							   {
								   for (int i = 0; i < 20; i++)
								   {
									   // compiler bug: get a delegate to BCL class
									   //AddSpriteByTexture(FreeSpaceForStuff, s, GoldSprites.Add);

									   AddSpriteByTexture(FreeSpaceForStuff, s,
										   k =>
										   {
											   k.Range = 0.5;
											   GoldSprites.Add(k);
										   }
									   );

								   }
							   }

							   var LastPosition = new Point();

							   EgoView.ViewPositionChanged +=
								   delegate
								   {
									   // only check for items each 0.5 distance travelled
									   if ((EgoView.ViewPosition - LastPosition).length < 0.5)
										   return;

									   Action Later = delegate { };


									   foreach (var Item in EgoView.SpritesFromPointOfView)
									   {
										   var Item_Sprite = Item.Sprite;

										   if (Item.Distance < Item_Sprite.Range)
										   {
											   if (GoldSprites.Contains(Item_Sprite))
											   {
												   // ding-ding-ding!

												   new Bitmap(new BitmapData(DefaultWidth, DefaultHeight, false, 0xffff00))
												   {
													   scaleX = DefaultScale,
													   scaleY = DefaultScale
												   }.AttachTo(this).FadeOutAndOrphanize(1000 / 24, 0.2);

												   InternalGotGold();
												   Later += () => EgoView.Sprites.Remove(Item_Sprite);
											   }
										   }
									   }

									   Later();

									   LastPosition = EgoView.ViewPosition;
								   };


						   }
						);
						#endregion

						#region ammo

						Assets.ZipFiles.ammo.ToFiles().ToBitmapArray(
						   sprites =>
						   {
							   var AmmoSprites = new List<SpriteInfo>();

							   foreach (var s in sprites)
							   {
								   for (int i = 0; i < 20; i++)
								   {
									   // compiler bug: get a delegate to BCL class
									   //AddSpriteByTexture(FreeSpaceForStuff, s, GoldSprites.Add);

									   AddSpriteByTexture(FreeSpaceForStuff, s,
										   k =>
										   {
											   k.Range = 0.5;
											   AmmoSprites.Add(k);
										   }
									   );

								   }
							   }

							   var LastPosition = new Point();

							   EgoView.ViewPositionChanged +=
								   delegate
								   {
									   // only check for items each 0.5 distance travelled
									   if ((EgoView.ViewPosition - LastPosition).length < 0.5)
										   return;

									   Action Later = delegate { };


									   foreach (var Item in EgoView.SpritesFromPointOfView)
									   {
										   var Item_Sprite = Item.Sprite;

										   if (Item.Distance < Item_Sprite.Range)
										   {
											   if (AmmoSprites.Contains(Item_Sprite))
											   {
												   // ding-ding-ding!

												   new Bitmap(new BitmapData(DefaultWidth, DefaultHeight, false, 0x8080ff))
												   {
													   scaleX = DefaultScale,
													   scaleY = DefaultScale
												   }.AttachTo(this).FadeOutAndOrphanize(1000 / 24, 0.2);


												   InternalGotAmmo();
												   

												   Later += () => EgoView.Sprites.Remove(Item_Sprite);
											   }
										   }
									   }

									   Later();

									   LastPosition = EgoView.ViewPosition;
								   };


						   }
						);
						#endregion

						Func<string, Texture64> t =
							texname => f[texname + ".png"];

						EgoView.FloorTexture = t("floor");
						EgoView.CeilingTexture = t("roof");



						var DynamicTextureBitmap = new Bitmap(new BitmapData(Texture64.SizeConstant, Texture64.SizeConstant, false, 0));
						Texture64 DynamicTexture = DynamicTextureBitmap;
						uint DynamicTextureKey = 0xffffff;

						EgoView.Map.WorldMap[2, 22] = DynamicTextureKey;
						EgoView.Map.WorldMap[3, 15] = DynamicTextureKey;


						EgoView.Map.Textures = new Dictionary<uint, Texture64>
                        {
                            {0xff0000, t("graywall")},
                            {0x0000ff, t("bluewall")},
                            {0x00ff00, t("greenwall")},
                            {0x7F3300, t("woodwall")},

                            {DynamicTextureKey, DynamicTexture}
                        };


						if (EgoView.CurrentTile != 0)
							throw new Exception("bad start position: " + new { EgoView.ViewPositionX, EgoView.ViewPositionY, EgoView.CurrentTile }.ToString());



						CameraView.Map.WorldMap = EgoView.Map.WorldMap;
						CameraView.Map.Textures = EgoView.Map.Textures;
						CameraView.Sprites = EgoView.Sprites;
						CameraView.ViewPosition = EgoView.ViewPosition;

						foreach (var Portal in Portals)
						{
							Portal.View.Map.WorldMap = EgoView.Map.WorldMap;
							Portal.View.Map.Textures = EgoView.Map.Textures;
							Portal.View.Sprites = EgoView.Sprites;
							Portal.AlphaMask = f["portalmask.png"];
						}


						EgoView.RenderScene();


						var MirrorFrame = f["mirror.png"];
						var counter = 0;

						stage.enterFrame += e =>
						{
							counter++;

							if (UpdatePortals)
							{
								// updateing it too often causes framerate to drop

								foreach (var Portal in Portals)
								{
									Portal.Update();
								}

								DynamicTextureBitmap.bitmapData.fillRect(DynamicTextureBitmap.bitmapData.rect, (uint)(counter * 8 % 256));
								var m = new Matrix();

								// to center
								m.translate(0, 10);
								// m.scale(0.3, 0.3);

								CameraView.RenderScene();

								DynamicTextureBitmap.bitmapData.draw(CameraView.Image.bitmapData, m);
								DynamicTextureBitmap.bitmapData.draw(MirrorFrame.bitmapData);

								DynamicTexture.Update();
							}

							EgoView.RenderScene();
						};






					}
				);

			AttachMovementInput(EgoView);
		}