commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
ff951383c36afc519c33a7c61de1f345c33a1ddc
src/as/com/threerings/util/MediaContainer.as
src/as/com/threerings/util/MediaContainer.as
package com.threerings.util { //import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Shape; import flash.errors.IOError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.StatusEvent; import flash.events.TextEvent; import flash.geom.Point; import flash.media.Video; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.system.SecurityDomain; import flash.net.URLRequest; import mx.core.ScrollPolicy; import mx.core.UIComponent; import mx.containers.Box; import mx.controls.VideoDisplay; import mx.events.VideoEvent; import com.threerings.util.StringUtil; import com.threerings.media.image.ImageUtil; /** * A wrapper class for all media that will be placed on the screen. * Subject to change. */ public class MediaContainer extends Box { /** A log instance that can be shared by sprites. */ protected static const log :Log = Log.getLog(MediaContainer); /** * Constructor. */ public function MediaContainer (url :String = null) { if (url != null) { setMedia(url); } mouseEnabled = false; mouseChildren = true; verticalScrollPolicy = ScrollPolicy.OFF; horizontalScrollPolicy = ScrollPolicy.OFF; } /** * Get the media. If the media was loaded using a URL, this will * likely be the Loader object holding the real media. */ public function getMedia () :DisplayObject { return _media; } /** * Configure the media to display. */ public function setMedia (url :String) :void { // shutdown any previous media if (_media != null) { shutdown(false); } // set up the new media if (StringUtil.endsWith(url.toLowerCase(), ".flv")) { setupVideo(url); } else { setupSwfOrImage(url); } } /** * Configure our media as an instance of the specified class. */ public function setMediaClass (clazz :Class) :void { setMediaObject(new clazz() as DisplayObject); } /** * Configure an already-instantiated DisplayObject as our media. */ public function setMediaObject (disp :DisplayObject) :void { if (_media != null) { shutdown(false); } if (disp is UIComponent) { addChild(disp); } else { rawChildren.addChild(disp); } _media = disp; updateContentDimensions(disp.width, disp.height); } /** * Configure this sprite to show a video. */ protected function setupVideo (url :String) :void { var vid :VideoDisplay = new VideoDisplay(); vid.autoPlay = false; _media = vid; addChild(vid); vid.addEventListener(ProgressEvent.PROGRESS, loadVideoProgress); vid.addEventListener(VideoEvent.READY, loadVideoReady); vid.addEventListener(VideoEvent.REWIND, videoDidRewind); // start it loading vid.source = url; vid.load(); } /** * Configure this sprite to show an image or flash movie. */ protected function setupSwfOrImage (url :String) :void { // create our loader and set up some event listeners var loader :Loader = new Loader(); _media = loader; var info :LoaderInfo = loader.contentLoaderInfo; info.addEventListener(Event.COMPLETE, loadingComplete); info.addEventListener(IOErrorEvent.IO_ERROR, loadError); info.addEventListener(ProgressEvent.PROGRESS, loadProgress); // create a mask to prevent the media from drawing out of bounds if (getMaxContentWidth() < int.MAX_VALUE && getMaxContentHeight() < int.MAX_VALUE) { configureMask(getMaxContentWidth(), getMaxContentHeight()); } // start it loading, add it as a child loader.load(new URLRequest(url), getContext(url)); rawChildren.addChild(loader); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * Display a 'broken image' to indicate there were troubles with * loading the media. */ protected function setupBrokenImage (w :int = -1, h :int = -1) :void { if (w == -1) { w = 100; } if (h == -1) { h = 100; } setMediaObject(ImageUtil.createErrorImage(w, h)); } /** * Get the application domain being used by this media, or null if * none or not applicable. */ public function getApplicationDomain () :ApplicationDomain { return (_media is Loader) ? (_media as Loader).contentLoaderInfo.applicationDomain : null; } /** * Unload the media we're displaying, clean up any resources. * * @param completely if true, we're going away and should stop * everything. Otherwise, we're just loading up new media. */ public function shutdown (completely :Boolean = true) :void { try { // remove the mask if (_media != null && _media.mask != null) { rawChildren.removeChild(_media.mask); _media.mask = null; } if (_media is Loader) { var loader :Loader = (_media as Loader); // remove any listeners removeListeners(loader.contentLoaderInfo); // dispose of media try { loader.close(); } catch (ioe :IOError) { // ignore } loader.unload(); rawChildren.removeChild(loader); } else if (_media is VideoDisplay) { var vid :VideoDisplay = (_media as VideoDisplay); // remove any listeners vid.removeEventListener(ProgressEvent.PROGRESS, loadVideoProgress); vid.removeEventListener(VideoEvent.READY, loadVideoReady); vid.removeEventListener(VideoEvent.REWIND, videoDidRewind); // dispose of media vid.pause(); try { vid.close(); } catch (ioe :IOError) { // ignore } vid.stop(); // remove from hierarchy removeChild(vid); } else if (_media != null) { if (_media is UIComponent) { removeChild(_media); } else { rawChildren.removeChild(_media); } } } catch (ioe :IOError) { log.warning("Error shutting down media: " + ioe); log.logStackTrace(ioe); } // clean everything up _w = 0; _h = 0; _media = null; } /** * Get the width of the content, bounded by the maximum. */ public function getContentWidth () :int { return Math.min(Math.abs(_w * getMediaScaleX()), getMaxContentWidth()); } /** * Get the height of the content, bounded by the maximum. */ public function getContentHeight () :int { return Math.min(Math.abs(_h * getMediaScaleY()), getMaxContentHeight()); } /** * Get the maximum allowable width for our content. */ public function getMaxContentWidth () :int { return int.MAX_VALUE; } /** * Get the maximum allowable height for our content. */ public function getMaxContentHeight () :int { return int.MAX_VALUE; } /** * Get the X scaling factor to use on the actual media. */ public function getMediaScaleX () :Number { return 1; } /** * Get the Y scaling factor to use on the actual media. */ public function getMediaScaleY () :Number { return 1; } /** * Return the LoaderContext that should be used to load the media * at the specified url. */ protected function getContext (url :String) :LoaderContext { // // We allow content to share but not overwrite our classes // return new LoaderContext(true, // new ApplicationDomain(ApplicationDomain.currentDomain), // SecurityDomain.currentDomain); // share nothing, trust nothing return new LoaderContext(false, null, null); } /** * Remove our listeners from the LoaderInfo object. */ protected function removeListeners (info :LoaderInfo) :void { info.removeEventListener(Event.COMPLETE, loadingComplete); info.removeEventListener(IOErrorEvent.IO_ERROR, loadError); info.removeEventListener(ProgressEvent.PROGRESS, loadProgress); } /** * A callback to receive IO_ERROR events. */ protected function loadError (event :IOErrorEvent) :void { setupBrokenImage(-1, -1); } /** * A callback to receive PROGRESS events. */ protected function loadProgress (event :ProgressEvent) :void { updateLoadingProgress(event.bytesLoaded, event.bytesTotal); var info :LoaderInfo = (event.target as LoaderInfo); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * A callback to receive PROGRESS events on the video. */ protected function loadVideoProgress (event :ProgressEvent) :void { var vid :VideoDisplay = (event.currentTarget as VideoDisplay); updateContentDimensions(vid.videoWidth, vid.videoHeight); updateLoadingProgress(vid.bytesLoaded, vid.bytesTotal); } /** * A callback to receive READY events for video. */ protected function loadVideoReady (event :VideoEvent) :void { var vid :VideoDisplay = (event.currentTarget as VideoDisplay); updateContentDimensions(vid.videoWidth, vid.videoHeight); updateLoadingProgress(1, 1); vid.play(); // remove the two listeners vid.removeEventListener(ProgressEvent.PROGRESS, loadVideoProgress); vid.removeEventListener(VideoEvent.READY, loadVideoReady); } /** * Callback function to receive COMPLETE events for swfs or images. */ protected function loadingComplete (event :Event) :void { var info :LoaderInfo = (event.target as LoaderInfo); removeListeners(info); // trace("Loading complete: " + info.url + // ", childAllowsParent=" + info.childAllowsParent + // ", parentAllowsChild=" + info.parentAllowsChild + // ", sameDomain=" + info.sameDomain); updateContentDimensions(info.width, info.height); updateLoadingProgress(1, 1); // // Bitmap smoothing // if (_media is Loader) { // var l :Loader = Loader(_media); // try { // if (l.content is Bitmap) { // Bitmap(l.content).smoothing = true; // trace("--- made bitmap smooth"); // } // } catch (er :Error) { // trace("--- error bitmap smooth"); // } // } } /** * Called when the video auto-rewinds. */ protected function videoDidRewind (event :VideoEvent) :void { (_media as VideoDisplay).play(); } /** * Configure the mask for this object. */ protected function configureMask (ww :int, hh :int) :void { var mask :Shape; if (_media.mask != null) { mask = (_media.mask as Shape); } else { mask = new Shape(); // the mask must be added to the display list (which is wacky) rawChildren.addChild(mask); _media.mask = mask; } mask.graphics.clear(); mask.graphics.beginFill(0xFFFFFF); mask.graphics.drawRect(0, 0, ww, hh); mask.graphics.endFill(); } /** * Called during loading as we figure out how big the content we're * loading is. */ protected function updateContentDimensions (ww :int, hh :int) :void { // update our saved size, and possibly notify our container if (_w != ww || _h != hh) { _w = ww; _h = hh; contentDimensionsUpdated(); } } /** * Called when we know the true size of the content. */ protected function contentDimensionsUpdated () :void { // nada, by default } /** * Update the graphics to indicate how much is loaded. */ protected function updateLoadingProgress ( soFar :Number, total :Number) :void { // nada, by default } /** The unscaled width of our content. */ protected var _w :int; /** The unscaled height of our content. */ protected var _h :int; /** Either a Loader or a VideoDisplay. */ protected var _media :DisplayObject; } }
package com.threerings.util { //import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Shape; import flash.errors.IOError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.StatusEvent; import flash.events.TextEvent; import flash.geom.Point; import flash.media.Video; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.system.SecurityDomain; import flash.net.URLRequest; import mx.core.ScrollPolicy; import mx.core.UIComponent; import mx.containers.Box; import mx.controls.VideoDisplay; import mx.events.VideoEvent; import com.threerings.util.StringUtil; import com.threerings.media.image.ImageUtil; /** * A wrapper class for all media that will be placed on the screen. * Subject to change. */ public class MediaContainer extends Box { /** A log instance that can be shared by sprites. */ protected static const log :Log = Log.getLog(MediaContainer); /** * Constructor. */ public function MediaContainer (url :String = null) { if (url != null) { setMedia(url); } mouseEnabled = false; mouseChildren = true; verticalScrollPolicy = ScrollPolicy.OFF; horizontalScrollPolicy = ScrollPolicy.OFF; } /** * Get the media. If the media was loaded using a URL, this will * likely be the Loader object holding the real media. */ public function getMedia () :DisplayObject { return _media; } /** * Configure the media to display. */ public function setMedia (url :String) :void { // shutdown any previous media if (_media != null) { shutdown(false); } // set up the new media if (StringUtil.endsWith(url.toLowerCase(), ".flv")) { setupVideo(url); } else { setupSwfOrImage(url); } } /** * Configure our media as an instance of the specified class. */ public function setMediaClass (clazz :Class) :void { setMediaObject(new clazz() as DisplayObject); } /** * Configure an already-instantiated DisplayObject as our media. */ public function setMediaObject (disp :DisplayObject) :void { if (_media != null) { shutdown(false); } if (disp is UIComponent) { addChild(disp); } else { rawChildren.addChild(disp); } _media = disp; updateContentDimensions(disp.width, disp.height); } /** * Configure this sprite to show a video. */ protected function setupVideo (url :String) :void { var vid :VideoDisplay = new VideoDisplay(); vid.autoPlay = false; _media = vid; addChild(vid); vid.addEventListener(ProgressEvent.PROGRESS, loadVideoProgress); vid.addEventListener(VideoEvent.READY, loadVideoReady); vid.addEventListener(VideoEvent.REWIND, videoDidRewind); // start it loading vid.source = url; vid.load(); } /** * Configure this sprite to show an image or flash movie. */ protected function setupSwfOrImage (url :String) :void { // create our loader and set up some event listeners var loader :Loader = new Loader(); _media = loader; var info :LoaderInfo = loader.contentLoaderInfo; info.addEventListener(Event.COMPLETE, loadingComplete); info.addEventListener(IOErrorEvent.IO_ERROR, loadError); info.addEventListener(ProgressEvent.PROGRESS, loadProgress); // create a mask to prevent the media from drawing out of bounds if (getMaxContentWidth() < int.MAX_VALUE && getMaxContentHeight() < int.MAX_VALUE) { configureMask(getMaxContentWidth(), getMaxContentHeight()); } // start it loading, add it as a child loader.load(new URLRequest(url), getContext(url)); rawChildren.addChild(loader); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * Display a 'broken image' to indicate there were troubles with * loading the media. */ protected function setupBrokenImage (w :int = -1, h :int = -1) :void { if (w == -1) { w = 100; } if (h == -1) { h = 100; } setMediaObject(ImageUtil.createErrorImage(w, h)); } /** * Get the application domain being used by this media, or null if * none or not applicable. */ public function getApplicationDomain () :ApplicationDomain { return (_media is Loader) ? (_media as Loader).contentLoaderInfo.applicationDomain : null; } /** * Unload the media we're displaying, clean up any resources. * * @param completely if true, we're going away and should stop * everything. Otherwise, we're just loading up new media. */ public function shutdown (completely :Boolean = true) :void { try { // remove the mask if (_media != null && _media.mask != null) { rawChildren.removeChild(_media.mask); _media.mask = null; } if (_media is Loader) { var loader :Loader = (_media as Loader); // remove any listeners removeListeners(loader.contentLoaderInfo); // dispose of media try { loader.close(); } catch (ioe :IOError) { // ignore } loader.unload(); rawChildren.removeChild(loader); } else if (_media is VideoDisplay) { var vid :VideoDisplay = (_media as VideoDisplay); // remove any listeners vid.removeEventListener(ProgressEvent.PROGRESS, loadVideoProgress); vid.removeEventListener(VideoEvent.READY, loadVideoReady); vid.removeEventListener(VideoEvent.REWIND, videoDidRewind); // dispose of media vid.pause(); try { vid.close(); } catch (ioe :IOError) { // ignore } vid.stop(); // remove from hierarchy removeChild(vid); } else if (_media != null) { if (_media is UIComponent) { removeChild(_media); } else { rawChildren.removeChild(_media); } } } catch (ioe :IOError) { log.warning("Error shutting down media: " + ioe); log.logStackTrace(ioe); } // clean everything up _w = 0; _h = 0; _media = null; } /** * Get the width of the content, bounded by the maximum. */ public function getContentWidth () :int { return Math.min(Math.abs(_w * getMediaScaleX()), getMaxContentWidth()); } /** * Get the height of the content, bounded by the maximum. */ public function getContentHeight () :int { return Math.min(Math.abs(_h * getMediaScaleY()), getMaxContentHeight()); } /** * Get the maximum allowable width for our content. */ public function getMaxContentWidth () :int { return int.MAX_VALUE; } /** * Get the maximum allowable height for our content. */ public function getMaxContentHeight () :int { return int.MAX_VALUE; } /** * Get the X scaling factor to use on the actual media. */ public function getMediaScaleX () :Number { return 1; } /** * Get the Y scaling factor to use on the actual media. */ public function getMediaScaleY () :Number { return 1; } /** * Return the LoaderContext that should be used to load the media * at the specified url. */ protected function getContext (url :String) :LoaderContext { if (isImage(url)) { // load images into our domain so that we can view their pixels return new LoaderContext(true, new ApplicationDomain(ApplicationDomain.currentDomain), SecurityDomain.currentDomain); } else { // share nothing, trust nothing return new LoaderContext(false, null, null); } } /** * Does the specified url represent an image? */ protected function isImage (url :String) :Boolean { // look at the last 4 characters in the lowercased url switch (url.toLowerCase().slice(-4)) { case ".png": case ".jpg": case ".gif": return true; default: return false; } } /** * Remove our listeners from the LoaderInfo object. */ protected function removeListeners (info :LoaderInfo) :void { info.removeEventListener(Event.COMPLETE, loadingComplete); info.removeEventListener(IOErrorEvent.IO_ERROR, loadError); info.removeEventListener(ProgressEvent.PROGRESS, loadProgress); } /** * A callback to receive IO_ERROR events. */ protected function loadError (event :IOErrorEvent) :void { setupBrokenImage(-1, -1); } /** * A callback to receive PROGRESS events. */ protected function loadProgress (event :ProgressEvent) :void { updateLoadingProgress(event.bytesLoaded, event.bytesTotal); var info :LoaderInfo = (event.target as LoaderInfo); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * A callback to receive PROGRESS events on the video. */ protected function loadVideoProgress (event :ProgressEvent) :void { var vid :VideoDisplay = (event.currentTarget as VideoDisplay); updateContentDimensions(vid.videoWidth, vid.videoHeight); updateLoadingProgress(vid.bytesLoaded, vid.bytesTotal); } /** * A callback to receive READY events for video. */ protected function loadVideoReady (event :VideoEvent) :void { var vid :VideoDisplay = (event.currentTarget as VideoDisplay); updateContentDimensions(vid.videoWidth, vid.videoHeight); updateLoadingProgress(1, 1); vid.play(); // remove the two listeners vid.removeEventListener(ProgressEvent.PROGRESS, loadVideoProgress); vid.removeEventListener(VideoEvent.READY, loadVideoReady); } /** * Callback function to receive COMPLETE events for swfs or images. */ protected function loadingComplete (event :Event) :void { var info :LoaderInfo = (event.target as LoaderInfo); removeListeners(info); // trace("Loading complete: " + info.url + // ", childAllowsParent=" + info.childAllowsParent + // ", parentAllowsChild=" + info.parentAllowsChild + // ", sameDomain=" + info.sameDomain); updateContentDimensions(info.width, info.height); updateLoadingProgress(1, 1); // // Bitmap smoothing // if (_media is Loader) { // var l :Loader = Loader(_media); // try { // if (l.content is Bitmap) { // Bitmap(l.content).smoothing = true; // trace("--- made bitmap smooth"); // } // } catch (er :Error) { // trace("--- error bitmap smooth"); // } // } } /** * Called when the video auto-rewinds. */ protected function videoDidRewind (event :VideoEvent) :void { (_media as VideoDisplay).play(); } /** * Configure the mask for this object. */ protected function configureMask (ww :int, hh :int) :void { var mask :Shape; if (_media.mask != null) { mask = (_media.mask as Shape); } else { mask = new Shape(); // the mask must be added to the display list (which is wacky) rawChildren.addChild(mask); _media.mask = mask; } mask.graphics.clear(); mask.graphics.beginFill(0xFFFFFF); mask.graphics.drawRect(0, 0, ww, hh); mask.graphics.endFill(); } /** * Called during loading as we figure out how big the content we're * loading is. */ protected function updateContentDimensions (ww :int, hh :int) :void { // update our saved size, and possibly notify our container if (_w != ww || _h != hh) { _w = ww; _h = hh; contentDimensionsUpdated(); } } /** * Called when we know the true size of the content. */ protected function contentDimensionsUpdated () :void { // nada, by default } /** * Update the graphics to indicate how much is loaded. */ protected function updateLoadingProgress ( soFar :Number, total :Number) :void { // nada, by default } /** The unscaled width of our content. */ protected var _w :int; /** The unscaled height of our content. */ protected var _h :int; /** Either a Loader or a VideoDisplay. */ protected var _media :DisplayObject; } }
Load images into our own security domain so that we can examine their pixels.
Load images into our own security domain so that we can examine their pixels. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4449 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
77a0dba7e5a05733c393b5241df77770ccc83886
src/com/esri/builder/eventbus/EventBus.as
src/com/esri/builder/eventbus/EventBus.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.eventbus { import flash.events.Event; import flash.events.EventDispatcher; /** * The EventBus allows centralized application communication. * It uses the singleton design pattern to make sure one event bus * is available globally. */ public class EventBus extends EventDispatcher { /** Application event bus instance */ public static const instance:EventBus = new EventBus(); /** * Normally the EventBus is not instantiated via the <b>new</b> method directly. * The constructor helps enforce only one EventBus available for the application * (singleton) so that it assures the communication only via a single event bus. */ public function EventBus() { } /** * The factory method is used to create a instance of the EventBus. It returns * the only instance of EventBus and makes sure no another instance is created. */ [Deprecated(replacement="instance")] public static function getInstance():EventBus { return instance; } /** * Basic dispatch function, dispatches simple named events. */ [Deprecated(replacement="AppEvent.dispatch")] public function dispatch(type:String):Boolean { return dispatchEvent(new Event(type)); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.eventbus { import flash.events.EventDispatcher; /** * The EventBus allows centralized application communication. * It uses the singleton design pattern to make sure one event bus * is available globally. */ public class EventBus extends EventDispatcher { /** Application event bus instance */ public static const instance:EventBus = new EventBus(); /** * Normally the EventBus is not instantiated via the <b>new</b> method directly. * The constructor helps enforce only one EventBus available for the application * (singleton) so that it assures the communication only via a single event bus. */ public function EventBus() { } } }
Remove deprecated EventBus functions.
Remove deprecated EventBus functions.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
decb56970cb561180fb221bdd1188f4f8c96e09b
src/as/com/threerings/util/StreamableHashMap.as
src/as/com/threerings/util/StreamableHashMap.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; import com.threerings.util.Maps; import com.threerings.util.maps.ForwardingMap; import com.threerings.util.maps.HashMap; import com.threerings.util.maps.ImmutableMap; /** * A Map that can be sent over the wire, bearing in mind that all keys and values must * be primitives or implement Streamable. * * @see com.threerings.util.Map * @see com.threerings.io.Streamable */ public class StreamableHashMap extends ForwardingMap implements Streamable { /** * Creates a new StreamableHashMap. * * @param keyClazz The class to use as the map key. May be null, but this functionality is * provided only for deserialization. A StreamableHashMap that has not been initialized * properly by either a non-null keyClazz or via readObject will throw errors on write and * always return null on read. */ public function StreamableHashMap (keyClazz :Class = null) { super(keyClazz == null ? DEFAULT_MAP : Maps.newMapOf(keyClazz)); } // documentation inherited from interface Streamable public function writeObject (out :ObjectOutputStream) :void { out.writeInt(size()); forEach(function (key :Object, value :Object) :void { out.writeObject(key); out.writeObject(value); }); } // documentation inherited from interface Streamable public function readObject (ins :ObjectInputStream) :void { var ecount :int = ins.readInt(); if (ecount > 0) { // guess the type of map based on the first key var key :Object = ins.readObject(); _source = Maps.newMapOf(ClassUtil.getClass(key)); put(key, ins.readObject()); // now read the rest for (var ii :int = 1; ii < ecount; ii++) { put(ins.readObject(), ins.readObject()); } } else { _source = Maps.newMapOf(String); // hope for the best } } protected static const DEFAULT_MAP :Map = new ImmutableMap(new HashMap()); } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; import com.threerings.util.Maps; import com.threerings.util.maps.ForwardingMap; /** * A Map that can be sent over the wire, bearing in mind that all keys and values must * be primitives or implement Streamable. * * @see com.threerings.util.Map * @see com.threerings.io.Streamable */ public class StreamableHashMap extends ForwardingMap implements Streamable { /** * Creates a new StreamableHashMap. * * @param keyClazz The class to use as the map key. May be null, but this functionality is * provided only for deserialization. A StreamableHashMap that has not been initialized * properly by either a non-null keyClazz or via readObject will throw errors on write and * always return null on read. */ public function StreamableHashMap (keyClazz :Class = null) { super(keyClazz == null ? DEFAULT_MAP : Maps.newMapOf(keyClazz)); } // documentation inherited from interface Streamable public function writeObject (out :ObjectOutputStream) :void { out.writeInt(size()); forEach(function (key :Object, value :Object) :void { out.writeObject(key); out.writeObject(value); }); } // documentation inherited from interface Streamable public function readObject (ins :ObjectInputStream) :void { var ecount :int = ins.readInt(); if (ecount > 0) { // guess the type of map based on the first key var key :Object = ins.readObject(); _source = Maps.newMapOf(ClassUtil.getClass(key)); put(key, ins.readObject()); // now read the rest for (var ii :int = 1; ii < ecount; ii++) { put(ins.readObject(), ins.readObject()); } } else { _source = DEFAULT_MAP; } } /** Used when we don't know the key class. Typically if a map is unstreamed it is * read-only anyway, so this will work for empty maps that are unstreamed. */ protected static const DEFAULT_MAP :Map = Maps.newBuilder(Object).makeImmutable().build(); } }
Use the Maps builder method. Assign the DEFAULT_MAP if we unstream an empty map, too. Comment DEFAULT_MAP.
Use the Maps builder method. Assign the DEFAULT_MAP if we unstream an empty map, too. Comment DEFAULT_MAP. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@6107 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
271d7008989a5e80cd81b03bb40a6585be0d5ee1
tests/GAv4/com/google/analytics/utils/FakeEnvironment.as
tests/GAv4/com/google/analytics/utils/FakeEnvironment.as
 package com.google.analytics.utils { public class FakeEnvironment extends Environment { private var _appName:String; private var _appVersion:Version; private var _url:String; private var _referrer:String; private var _documentTitle:String; private var _domainName:String; private var _locationPath:String; private var _locationSearch:String; private var _flashVersion:Version; private var _language:String; private var _languageEncoding:String; private var _operatingSystem:String; private var _playerType:String; private var _platform:String; private var _protocol:String; private var _screenWidth:Number; private var _screenHeight:Number; private var _screenColorDepth:String; private var _userAgent:String; private var _isInHTML:Boolean; private var _isAIR:Boolean; public function FakeEnvironment( appName:String = "", appVersion:Version = null, url:String = "", referrer:String = "", documentTitle:String = "", domainName:String = "", locationPath:String = "", locationSearch:String = "", flashVersion:Version = null, language:String = "", languageEncoding:String = "", operatingSystem:String = "", playerType:String = "", platform:String = "", protocol:String = null, screenWidth:Number = NaN, screenHeight:Number = NaN, screenColorDepth:String = "", userAgent:String = null, isInHTML:Boolean = false, isAIR:Boolean = false ) { super("", "", "", null); _appName = appName; _appVersion = appVersion; _url = url; _referrer = referrer; _documentTitle = documentTitle; _domainName = domainName; _locationPath = locationPath; _locationSearch = locationSearch; _flashVersion = flashVersion; _language = language; _languageEncoding = languageEncoding; _operatingSystem = operatingSystem; _playerType = playerType; _platform = platform; _protocol = protocol; _screenWidth = screenWidth; _screenHeight = screenHeight; _screenColorDepth = screenColorDepth; _userAgent = userAgent; _isInHTML = isInHTML; _isAIR = isAIR; } public override function get appName():String { return _appName; } public override function set appName( value:String ):void { _appName = value; } public override function get appVersion():Version { return _appVersion; } public override function set appVersion( value:Version ):void { _appVersion = value; } // ga_internal override function set url( value:String ):void // { // _url = value; // } public override function get locationSWFPath():String { return _url; } public override function get referrer():String { return _referrer; } public override function get documentTitle():String { return _documentTitle; } public override function get domainName():String { return _domainName; } public override function get locationPath():String { return _locationPath; } public override function get locationSearch():String { return _locationSearch; } public override function get flashVersion():Version { return _flashVersion; } public override function get language():String { return _language; } public override function get languageEncoding():String { return _languageEncoding; } public override function get operatingSystem():String { return _operatingSystem; } public override function get playerType():String { return _playerType; } public override function get platform():String { return _platform; } public override function get protocol():String { return _protocol; } public override function get screenWidth():Number { return _screenWidth; } public override function get screenHeight():Number { return _screenHeight; } public override function get screenColorDepth():String { return _screenColorDepth; } public override function get userAgent():String { return _userAgent; } public override function set userAgent( custom:String ):void { _userAgent = custom; } public override function isInHTML():Boolean { return _isInHTML; } public override function isAIR():Boolean { return _isAIR; } } }
 package com.google.analytics.utils { import core.version; public class FakeEnvironment extends Environment { private var _appName:String; private var _appVersion:version; private var _url:String; private var _referrer:String; private var _documentTitle:String; private var _domainName:String; private var _locationPath:String; private var _locationSearch:String; private var _flashVersion:version; private var _language:String; private var _languageEncoding:String; private var _operatingSystem:String; private var _playerType:String; private var _platform:String; private var _protocol:String; private var _screenWidth:Number; private var _screenHeight:Number; private var _screenColorDepth:String; private var _userAgent:String; private var _isInHTML:Boolean; private var _isAIR:Boolean; public function FakeEnvironment( appName:String = "", appVersion:version = null, url:String = "", referrer:String = "", documentTitle:String = "", domainName:String = "", locationPath:String = "", locationSearch:String = "", flashVersion:version = null, language:String = "", languageEncoding:String = "", operatingSystem:String = "", playerType:String = "", platform:String = "", protocol:String = null, screenWidth:Number = NaN, screenHeight:Number = NaN, screenColorDepth:String = "", userAgent:String = null, isInHTML:Boolean = false, isAIR:Boolean = false ) { super("", "", "", null); _appName = appName; _appVersion = appVersion; _url = url; _referrer = referrer; _documentTitle = documentTitle; _domainName = domainName; _locationPath = locationPath; _locationSearch = locationSearch; _flashVersion = flashVersion; _language = language; _languageEncoding = languageEncoding; _operatingSystem = operatingSystem; _playerType = playerType; _platform = platform; _protocol = protocol; _screenWidth = screenWidth; _screenHeight = screenHeight; _screenColorDepth = screenColorDepth; _userAgent = userAgent; _isInHTML = isInHTML; _isAIR = isAIR; } public override function get appName():String { return _appName; } public override function set appName( value:String ):void { _appName = value; } public override function get appVersion():version { return _appVersion; } public override function set appVersion( value:version ):void { _appVersion = value; } // ga_internal override function set url( value:String ):void // { // _url = value; // } public override function get locationSWFPath():String { return _url; } public override function get referrer():String { return _referrer; } public override function get documentTitle():String { return _documentTitle; } public override function get domainName():String { return _domainName; } public override function get locationPath():String { return _locationPath; } public override function get locationSearch():String { return _locationSearch; } public override function get flashVersion():version { return _flashVersion; } public override function get language():String { return _language; } public override function get languageEncoding():String { return _languageEncoding; } public override function get operatingSystem():String { return _operatingSystem; } public override function get playerType():String { return _playerType; } public override function get platform():String { return _platform; } public override function get protocol():String { return _protocol; } public override function get screenWidth():Number { return _screenWidth; } public override function get screenHeight():Number { return _screenHeight; } public override function get screenColorDepth():String { return _screenColorDepth; } public override function get userAgent():String { return _userAgent; } public override function set userAgent( custom:String ):void { _userAgent = custom; } public override function isInHTML():Boolean { return _isInHTML; } public override function isAIR():Boolean { return _isAIR; } } }
replace class Version by core.version
replace class Version by core.version
ActionScript
apache-2.0
Vigmar/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,drflash/gaforflash,DimaBaliakin/gaforflash,soumavachakraborty/gaforflash,jisobkim/gaforflash,dli-iclinic/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash,jeremy-wischusen/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,mrthuanvn/gaforflash
738eef3de92307d85b4a9e21c8850eca7d70cbad
Bin/Data/Scripts/Editor/EditorNodeWindow.as
Bin/Data/Scripts/Editor/EditorNodeWindow.as
// Urho3D editor attribute inspector window handling #include "Scripts/Editor/AttributeEditor.as" Window@ attributeInspectorWindow; UIElement@ parentContainer; UIElement@ nodeContainer; XMLFile@ nodeXMLResource; XMLFile@ componentXMLResource; bool applyMaterialList = true; bool attributesDirty = false; const String STRIKED_OUT = "——"; // Two unicode EM DASH (U+2014) const ShortStringHash NODE_IDS_VAR("NodeIDs"); const ShortStringHash COMPONENT_IDS_VAR("ComponentIDs"); uint componentContainerStartIndex = 0; void AddNodeContainer() { if (nodeContainer !is null) return; uint index = parentContainer.numChildren; parentContainer.LoadXML(nodeXMLResource, uiStyle); nodeContainer = GetContainer(index); SubscribeToEvent(nodeContainer.GetChild("NewVarDropDown", true), "ItemSelected", "CreateNewVariable"); SubscribeToEvent(nodeContainer.GetChild("DeleteVarButton", true), "Released", "DeleteVariable"); ++componentContainerStartIndex; } void AddComponentContainer() { parentContainer.LoadXML(componentXMLResource, uiStyle); } void DeleteAllContainers() { parentContainer.RemoveAllChildren(); nodeContainer = null; componentContainerStartIndex = 0; } UIElement@ GetContainer(uint index) { return parentContainer.children[index]; } UIElement@ GetComponentContainer(uint index) { return parentContainer.children[componentContainerStartIndex + index]; } void CreateAttributeInspectorWindow() { if (attributeInspectorWindow !is null) return; InitResourcePicker(); InitVectorStructs(); attributeInspectorWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorNodeWindow.xml")); nodeXMLResource = cache.GetResource("XMLFile", "UI/EditorNode.xml"); componentXMLResource = cache.GetResource("XMLFile", "UI/EditorComponent.xml"); parentContainer = attributeInspectorWindow.GetChild("ParentContainer"); ui.root.AddChild(attributeInspectorWindow); int height = Min(ui.root.height - 60, 500); attributeInspectorWindow.SetSize(300, height); attributeInspectorWindow.SetPosition(ui.root.width - 20 - attributeInspectorWindow.width, 40); attributeInspectorWindow.opacity = uiMaxOpacity; attributeInspectorWindow.BringToFront(); SubscribeToEvent(attributeInspectorWindow.GetChild("CloseButton", true), "Released", "HideAttributeInspectorWindow"); SubscribeToEvent(attributeInspectorWindow, "LayoutUpdated", "HandleWindowLayoutUpdated"); } void HideAttributeInspectorWindow() { attributeInspectorWindow.visible = false; } bool ShowAttributeInspectorWindow() { attributeInspectorWindow.visible = true; attributeInspectorWindow.BringToFront(); return true; } void HandleWindowLayoutUpdated() { for (uint i = 0; i < parentContainer.numChildren; ++i) { ListView@ list = GetContainer(i).GetChild("AttributeList"); // At the moment, only 'Is Enabled' container (place-holder + check box) is being created as child of the list view instead of as list item // When window resize and so the list's width is changed, adjust the 'Is enabled' container width so that check box stays at the right most position int width = list.width; for (uint i = 0; i < list.numChildren; ++i) { UIElement@ element = list.children[i]; if (!element.internal) element.SetFixedWidth(width); } } } Array<Serializable@> ToSerializableArray(Array<Node@> nodes) { Array<Serializable@> serializables; for (uint i = 0; i < nodes.length; ++i) serializables.Push(nodes[i]); return serializables; } void UpdateAttributeInspector(bool fullUpdate = true) { attributesDirty = false; // If full update delete all containers and added them back as necessary if (fullUpdate) DeleteAllContainers(); Text@ nodeTitle = nodeContainer.GetChild("TitleText"); String nodeType; if (editNodes.length == 0) nodeTitle.text = "No node"; else if (editNode !is null) { String idStr; if (editNode.id >= FIRST_LOCAL_ID) idStr = " Local ID " + String(editNode.id - FIRST_LOCAL_ID); else idStr = " ID " + String(editNode.id); nodeType = editNode.typeName; nodeTitle.text = nodeType + idStr; } else { nodeType = editNodes[0].typeName; nodeTitle.text = nodeType + " ID " + STRIKED_OUT + " (" + editNodes.length + "x)"; } IconizeUIElement(nodeTitle, nodeType); ListView@ list = nodeContainer.GetChild("AttributeList"); UpdateAttributes(ToSerializableArray(editNodes), list, fullUpdate); if (fullUpdate) { //\TODO Avoid hardcoding // Resize the node editor according to the number of variables, up to a certain maximum uint maxAttrs = Clamp(list.contentElement.numChildren, MIN_NODE_ATTRIBUTES, MAX_NODE_ATTRIBUTES); list.SetFixedHeight(maxAttrs * ATTR_HEIGHT + 2); nodeContainer.SetFixedHeight(maxAttrs * ATTR_HEIGHT + 60); } if (editComponents.empty) { Text@ componentTitle = GetComponentContainer(0).GetChild("TitleText"); if (selectedComponents.length <= 1) componentTitle.text = "No component"; else componentTitle.text = selectedComponents.length + " components"; // Ensure there is no icon IconizeUIElement(componentTitle, ""); } else { uint numEditableComponents = editComponents.length / numEditableComponentsPerNode; String multiplierText; if (numEditableComponents > 1) multiplierText = " (" + numEditableComponents + "x)"; for (uint j = 0; j < numEditableComponentsPerNode; ++j) { if (j >= parentContainer.numChildren - componentContainerStartIndex) AddComponentContainer(); Text@ componentTitle = GetComponentContainer(j).GetChild("TitleText"); componentTitle.text = GetComponentTitle(editComponents[j * numEditableComponents]) + multiplierText; IconizeUIElement(componentTitle, editComponents[j * numEditableComponents].typeName); SetIconEnabledColor(componentTitle, editComponents[j * numEditableComponents].enabledEffective); Array<Serializable@> components; for (uint i = 0; i < numEditableComponents; ++i) components.Push(editComponents[j * numEditableComponents + i]); UpdateAttributes(components, GetComponentContainer(j).GetChild("AttributeList"), fullUpdate); } } UpdateAttributeInspectorIcons(); } void UpdateNodeAttributes() { UpdateAttributes(ToSerializableArray(editNodes), nodeContainer.GetChild("AttributeList"), false); } void UpdateAttributeInspectorIcons() { Text@ nodeTitle = nodeContainer.GetChild("TitleText"); if (editNode !is null) SetIconEnabledColor(nodeTitle, editNode.enabled); else if (editNodes.length > 0) { bool hasSameEnabledState = true; for (uint i = 1; i < editNodes.length; ++i) { if (editNodes[i].enabled != editNodes[0].enabled) { hasSameEnabledState = false; break; } } SetIconEnabledColor(nodeTitle, editNodes[0].enabled, !hasSameEnabledState); } if (!editComponents.empty) { uint numEditableComponents = editComponents.length / numEditableComponentsPerNode; for (uint j = 0; j < numEditableComponentsPerNode; ++j) { Text@ componentTitle = GetComponentContainer(j).GetChild("TitleText"); bool enabledEffective = editComponents[j * numEditableComponents].enabledEffective; bool hasSameEnabledState = true; for (uint i = 1; i < numEditableComponents; ++i) { if (editComponents[j * numEditableComponents + i].enabledEffective != enabledEffective) { hasSameEnabledState = false; break; } } SetIconEnabledColor(componentTitle, enabledEffective, !hasSameEnabledState); } } } void PostEditAttribute(Array<Serializable@>@ serializables, uint index) { // If a StaticModel/AnimatedModel/Skybox model was changed, apply a possibly different material list if (applyMaterialList && serializables[0].attributeInfos[index].name == "Model") { for (uint i = 0; i < serializables.length; ++i) { StaticModel@ staticModel = cast<StaticModel>(serializables[i]); if (staticModel !is null) ApplyMaterialList(staticModel); } } SetSceneModified(); } void SetAttributeEditorID(UIElement@ attrEdit, Array<Serializable@>@ serializables) { // All target serializables must be either nodes or components, so can check the first for the type Node@ node = cast<Node>(serializables[0]); Array<Variant> ids; if (node !is null) { for (uint i = 0; i < serializables.length; ++i) ids.Push(Variant(cast<Node>(serializables[i]).id)); attrEdit.vars[NODE_IDS_VAR] = ids; } else { for (uint i = 0; i < serializables.length; ++i) ids.Push(Variant(cast<Component>(serializables[i]).id)); attrEdit.vars[COMPONENT_IDS_VAR] = ids; } } Array<Serializable@>@ GetAttributeEditorTargets(UIElement@ attrEdit) { Array<Serializable@> ret; Variant variant = attrEdit.GetVar(NODE_IDS_VAR); if (!variant.empty) { Array<Variant>@ ids = variant.GetVariantVector(); for (uint i = 0; i < ids.length; ++i) { Node@ node = editorScene.GetNode(ids[i].GetUInt()); if (node !is null) ret.Push(node); } } else { variant = attrEdit.GetVar(COMPONENT_IDS_VAR); if (!variant.empty) { Array<Variant>@ ids = variant.GetVariantVector(); for (uint i = 0; i < ids.length; ++i) { Component@ component = editorScene.GetComponent(ids[i].GetUInt()); if (component !is null) ret.Push(component); } } } return ret; } void CreateNewVariable(StringHash eventType, VariantMap& eventData) { if (editNodes.length == 0) return; DropDownList@ dropDown = eventData["Element"].GetUIElement(); LineEdit@ nameEdit = attributeInspectorWindow.GetChild("VarNameEdit", true); String sanitatedVarName = nameEdit.text.Trimmed().Replaced(";", ""); if (sanitatedVarName.empty) return; editorScene.RegisterVar(sanitatedVarName); Variant newValue; switch (dropDown.selection) { case 0: newValue = int(0); break; case 1: newValue = false; break; case 2: newValue = float(0.0); break; case 3: newValue = String(); break; case 4: newValue = Vector3(); break; case 5: newValue = Color(); break; } // If we overwrite an existing variable, must recreate the attribute-editor(s) for the correct type bool overwrite = false; for (uint i = 0; i < editNodes.length; ++i) { overwrite = overwrite || editNodes[i].vars.Contains(sanitatedVarName); editNodes[i].vars[sanitatedVarName] = newValue; } UpdateAttributeInspector(overwrite); } void DeleteVariable(StringHash eventType, VariantMap& eventData) { if (editNodes.length == 0) return; LineEdit@ nameEdit = attributeInspectorWindow.GetChild("VarNameEdit", true); String sanitatedVarName = nameEdit.text.Trimmed().Replaced(";", ""); if (sanitatedVarName.empty) return; bool erased = false; for (uint i = 0; i < editNodes.length; ++i) { // \todo Should first check whether var in question is editable erased = editNodes[i].vars.Erase(sanitatedVarName) || erased; } if (erased) UpdateAttributeInspector(false); }
// Urho3D editor attribute inspector window handling #include "Scripts/Editor/AttributeEditor.as" Window@ attributeInspectorWindow; UIElement@ parentContainer; UIElement@ nodeContainer; XMLFile@ nodeXMLResource; XMLFile@ componentXMLResource; bool applyMaterialList = true; bool attributesDirty = false; const String STRIKED_OUT = "——"; // Two unicode EM DASH (U+2014) const ShortStringHash NODE_IDS_VAR("NodeIDs"); const ShortStringHash COMPONENT_IDS_VAR("ComponentIDs"); uint componentContainerStartIndex = 0; void AddNodeContainer() { if (nodeContainer !is null) return; uint index = parentContainer.numChildren; parentContainer.LoadXML(nodeXMLResource, uiStyle); nodeContainer = GetContainer(index); SubscribeToEvent(nodeContainer.GetChild("NewVarDropDown", true), "ItemSelected", "CreateNewVariable"); SubscribeToEvent(nodeContainer.GetChild("DeleteVarButton", true), "Released", "DeleteVariable"); ++componentContainerStartIndex; } void AddComponentContainer() { parentContainer.LoadXML(componentXMLResource, uiStyle); } void DeleteAllContainers() { parentContainer.RemoveAllChildren(); nodeContainer = null; componentContainerStartIndex = 0; } UIElement@ GetContainer(uint index) { return parentContainer.children[index]; } UIElement@ GetComponentContainer(uint index) { return parentContainer.children[componentContainerStartIndex + index]; } void CreateAttributeInspectorWindow() { if (attributeInspectorWindow !is null) return; InitResourcePicker(); InitVectorStructs(); attributeInspectorWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorNodeWindow.xml")); nodeXMLResource = cache.GetResource("XMLFile", "UI/EditorNode.xml"); componentXMLResource = cache.GetResource("XMLFile", "UI/EditorComponent.xml"); parentContainer = attributeInspectorWindow.GetChild("ParentContainer"); ui.root.AddChild(attributeInspectorWindow); int height = Min(ui.root.height - 60, 500); attributeInspectorWindow.SetSize(300, height); attributeInspectorWindow.SetPosition(ui.root.width - 20 - attributeInspectorWindow.width, 40); attributeInspectorWindow.opacity = uiMaxOpacity; attributeInspectorWindow.BringToFront(); SubscribeToEvent(attributeInspectorWindow.GetChild("CloseButton", true), "Released", "HideAttributeInspectorWindow"); SubscribeToEvent(attributeInspectorWindow, "LayoutUpdated", "HandleWindowLayoutUpdated"); } void HideAttributeInspectorWindow() { attributeInspectorWindow.visible = false; } bool ShowAttributeInspectorWindow() { attributeInspectorWindow.visible = true; attributeInspectorWindow.BringToFront(); return true; } void HandleWindowLayoutUpdated() { for (uint i = 0; i < parentContainer.numChildren; ++i) { ListView@ list = GetContainer(i).GetChild("AttributeList"); // At the moment, only 'Is Enabled' container (place-holder + check box) is being created as child of the list view instead of as list item // When window resize and so the list's width is changed, adjust the 'Is enabled' container width so that check box stays at the right most position int width = list.width; for (uint i = 0; i < list.numChildren; ++i) { UIElement@ element = list.children[i]; if (!element.internal) element.SetFixedWidth(width); } } } Array<Serializable@> ToSerializableArray(Array<Node@> nodes) { Array<Serializable@> serializables; for (uint i = 0; i < nodes.length; ++i) serializables.Push(nodes[i]); return serializables; } void UpdateAttributeInspector(bool fullUpdate = true) { attributesDirty = false; // If full update delete all containers and added them back as necessary if (fullUpdate) { DeleteAllContainers(); AddNodeContainer(); AddComponentContainer(); } Text@ nodeTitle = nodeContainer.GetChild("TitleText"); String nodeType; if (editNodes.length == 0) nodeTitle.text = "No node"; else if (editNode !is null) { String idStr; if (editNode.id >= FIRST_LOCAL_ID) idStr = " Local ID " + String(editNode.id - FIRST_LOCAL_ID); else idStr = " ID " + String(editNode.id); nodeType = editNode.typeName; nodeTitle.text = nodeType + idStr; } else { nodeType = editNodes[0].typeName; nodeTitle.text = nodeType + " ID " + STRIKED_OUT + " (" + editNodes.length + "x)"; } IconizeUIElement(nodeTitle, nodeType); ListView@ list = nodeContainer.GetChild("AttributeList"); UpdateAttributes(ToSerializableArray(editNodes), list, fullUpdate); if (fullUpdate) { //\TODO Avoid hardcoding // Resize the node editor according to the number of variables, up to a certain maximum uint maxAttrs = Clamp(list.contentElement.numChildren, MIN_NODE_ATTRIBUTES, MAX_NODE_ATTRIBUTES); list.SetFixedHeight(maxAttrs * ATTR_HEIGHT + 2); nodeContainer.SetFixedHeight(maxAttrs * ATTR_HEIGHT + 60); } if (editComponents.empty) { Text@ componentTitle = GetComponentContainer(0).GetChild("TitleText"); if (selectedComponents.length <= 1) componentTitle.text = "No component"; else componentTitle.text = selectedComponents.length + " components"; // Ensure there is no icon IconizeUIElement(componentTitle, ""); } else { uint numEditableComponents = editComponents.length / numEditableComponentsPerNode; String multiplierText; if (numEditableComponents > 1) multiplierText = " (" + numEditableComponents + "x)"; for (uint j = 0; j < numEditableComponentsPerNode; ++j) { if (j >= parentContainer.numChildren - componentContainerStartIndex) AddComponentContainer(); Text@ componentTitle = GetComponentContainer(j).GetChild("TitleText"); componentTitle.text = GetComponentTitle(editComponents[j * numEditableComponents]) + multiplierText; IconizeUIElement(componentTitle, editComponents[j * numEditableComponents].typeName); SetIconEnabledColor(componentTitle, editComponents[j * numEditableComponents].enabledEffective); Array<Serializable@> components; for (uint i = 0; i < numEditableComponents; ++i) components.Push(editComponents[j * numEditableComponents + i]); UpdateAttributes(components, GetComponentContainer(j).GetChild("AttributeList"), fullUpdate); } } UpdateAttributeInspectorIcons(); } void UpdateNodeAttributes() { UpdateAttributes(ToSerializableArray(editNodes), nodeContainer.GetChild("AttributeList"), false); } void UpdateAttributeInspectorIcons() { Text@ nodeTitle = nodeContainer.GetChild("TitleText"); if (editNode !is null) SetIconEnabledColor(nodeTitle, editNode.enabled); else if (editNodes.length > 0) { bool hasSameEnabledState = true; for (uint i = 1; i < editNodes.length; ++i) { if (editNodes[i].enabled != editNodes[0].enabled) { hasSameEnabledState = false; break; } } SetIconEnabledColor(nodeTitle, editNodes[0].enabled, !hasSameEnabledState); } if (!editComponents.empty) { uint numEditableComponents = editComponents.length / numEditableComponentsPerNode; for (uint j = 0; j < numEditableComponentsPerNode; ++j) { Text@ componentTitle = GetComponentContainer(j).GetChild("TitleText"); bool enabledEffective = editComponents[j * numEditableComponents].enabledEffective; bool hasSameEnabledState = true; for (uint i = 1; i < numEditableComponents; ++i) { if (editComponents[j * numEditableComponents + i].enabledEffective != enabledEffective) { hasSameEnabledState = false; break; } } SetIconEnabledColor(componentTitle, enabledEffective, !hasSameEnabledState); } } } void PostEditAttribute(Array<Serializable@>@ serializables, uint index) { // If a StaticModel/AnimatedModel/Skybox model was changed, apply a possibly different material list if (applyMaterialList && serializables[0].attributeInfos[index].name == "Model") { for (uint i = 0; i < serializables.length; ++i) { StaticModel@ staticModel = cast<StaticModel>(serializables[i]); if (staticModel !is null) ApplyMaterialList(staticModel); } } SetSceneModified(); } void SetAttributeEditorID(UIElement@ attrEdit, Array<Serializable@>@ serializables) { // All target serializables must be either nodes or components, so can check the first for the type Node@ node = cast<Node>(serializables[0]); Array<Variant> ids; if (node !is null) { for (uint i = 0; i < serializables.length; ++i) ids.Push(Variant(cast<Node>(serializables[i]).id)); attrEdit.vars[NODE_IDS_VAR] = ids; } else { for (uint i = 0; i < serializables.length; ++i) ids.Push(Variant(cast<Component>(serializables[i]).id)); attrEdit.vars[COMPONENT_IDS_VAR] = ids; } } Array<Serializable@>@ GetAttributeEditorTargets(UIElement@ attrEdit) { Array<Serializable@> ret; Variant variant = attrEdit.GetVar(NODE_IDS_VAR); if (!variant.empty) { Array<Variant>@ ids = variant.GetVariantVector(); for (uint i = 0; i < ids.length; ++i) { Node@ node = editorScene.GetNode(ids[i].GetUInt()); if (node !is null) ret.Push(node); } } else { variant = attrEdit.GetVar(COMPONENT_IDS_VAR); if (!variant.empty) { Array<Variant>@ ids = variant.GetVariantVector(); for (uint i = 0; i < ids.length; ++i) { Component@ component = editorScene.GetComponent(ids[i].GetUInt()); if (component !is null) ret.Push(component); } } } return ret; } void CreateNewVariable(StringHash eventType, VariantMap& eventData) { if (editNodes.length == 0) return; DropDownList@ dropDown = eventData["Element"].GetUIElement(); LineEdit@ nameEdit = attributeInspectorWindow.GetChild("VarNameEdit", true); String sanitatedVarName = nameEdit.text.Trimmed().Replaced(";", ""); if (sanitatedVarName.empty) return; editorScene.RegisterVar(sanitatedVarName); Variant newValue; switch (dropDown.selection) { case 0: newValue = int(0); break; case 1: newValue = false; break; case 2: newValue = float(0.0); break; case 3: newValue = String(); break; case 4: newValue = Vector3(); break; case 5: newValue = Color(); break; } // If we overwrite an existing variable, must recreate the attribute-editor(s) for the correct type bool overwrite = false; for (uint i = 0; i < editNodes.length; ++i) { overwrite = overwrite || editNodes[i].vars.Contains(sanitatedVarName); editNodes[i].vars[sanitatedVarName] = newValue; } UpdateAttributeInspector(overwrite); } void DeleteVariable(StringHash eventType, VariantMap& eventData) { if (editNodes.length == 0) return; LineEdit@ nameEdit = attributeInspectorWindow.GetChild("VarNameEdit", true); String sanitatedVarName = nameEdit.text.Trimmed().Replaced(";", ""); if (sanitatedVarName.empty) return; bool erased = false; for (uint i = 0; i < editNodes.length; ++i) { // \todo Should first check whether var in question is editable erased = editNodes[i].vars.Erase(sanitatedVarName) || erased; } if (erased) UpdateAttributeInspector(false); }
Revert back partial changes in the Editor.
Revert back partial changes in the Editor.
ActionScript
mit
luveti/Urho3D,henu/Urho3D,henu/Urho3D,henu/Urho3D,bacsmar/Urho3D,MeshGeometry/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,codedash64/Urho3D,fire/Urho3D-1,xiliu98/Urho3D,rokups/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,xiliu98/Urho3D,codemon66/Urho3D,rokups/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,urho3d/Urho3D,helingping/Urho3D,carnalis/Urho3D,codedash64/Urho3D,rokups/Urho3D,orefkov/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,orefkov/Urho3D,PredatorMF/Urho3D,urho3d/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,codemon66/Urho3D,weitjong/Urho3D,cosmy1/Urho3D,luveti/Urho3D,eugeneko/Urho3D,iainmerrick/Urho3D,cosmy1/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,rokups/Urho3D,MeshGeometry/Urho3D,codedash64/Urho3D,helingping/Urho3D,abdllhbyrktr/Urho3D,carnalis/Urho3D,c4augustus/Urho3D,c4augustus/Urho3D,bacsmar/Urho3D,tommy3/Urho3D,tommy3/Urho3D,fire/Urho3D-1,SuperWangKai/Urho3D,PredatorMF/Urho3D,MeshGeometry/Urho3D,tommy3/Urho3D,weitjong/Urho3D,299299/Urho3D,PredatorMF/Urho3D,tommy3/Urho3D,helingping/Urho3D,henu/Urho3D,rokups/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,abdllhbyrktr/Urho3D,299299/Urho3D,luveti/Urho3D,victorholt/Urho3D,carnalis/Urho3D,codemon66/Urho3D,cosmy1/Urho3D,299299/Urho3D,tommy3/Urho3D,iainmerrick/Urho3D,MonkeyFirst/Urho3D,weitjong/Urho3D,MeshGeometry/Urho3D,rokups/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,victorholt/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D,helingping/Urho3D,victorholt/Urho3D,eugeneko/Urho3D,urho3d/Urho3D,c4augustus/Urho3D,MonkeyFirst/Urho3D,SuperWangKai/Urho3D,kostik1337/Urho3D,299299/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,codemon66/Urho3D,c4augustus/Urho3D,bacsmar/Urho3D,codemon66/Urho3D,abdllhbyrktr/Urho3D,iainmerrick/Urho3D,cosmy1/Urho3D,SirNate0/Urho3D,kostik1337/Urho3D,eugeneko/Urho3D,SirNate0/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,orefkov/Urho3D,luveti/Urho3D,iainmerrick/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,carnalis/Urho3D,299299/Urho3D,abdllhbyrktr/Urho3D,henu/Urho3D,fire/Urho3D-1,weitjong/Urho3D
0895bd5b14505a6934377c8155e87a6152ca1d7f
WEB-INF/lps/lfc/debugger/platform/swf9/LzDebug.as
WEB-INF/lps/lfc/debugger/platform/swf9/LzDebug.as
/* -*- mode: JavaScript; c-basic-offset: 2; -*- */ /* * Platform-specific DebugService * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. */ class LzAS3DebugService extends LzDebugService { #passthrough (toplevel:true) { import flash.utils.describeType; import flash.utils.Dictionary; import flash.utils.getDefinitionByName import flash.utils.getQualifiedClassName }# /** * @access private */ function LzAS3DebugService (base:LzBootstrapDebugService) { super(base); } /** ** Platform-specific implementation of debug I/O **/ /** * Instantiates an instance of the user Debugger window * Called last thing by the compiler when the app is completely loaded. * @access private */ function makeDebugWindow () { // Make the real console. This is only called if the user code // did not actually instantiate a <debug /> tag var params:Object = LFCApplication.stage.loaderInfo.parameters; var remote =( params[ "lzconsoledebug" ] ); if (remote == 'true') { // Open the remote debugger socket this.attachDebugConsole(new LzFlashRemoteDebugConsole()); } else { // This will attach itself, once it is fully initialized. new lz.LzDebugWindow(); } } // Map of object=>id var swf9_object_table:Dictionary = new Dictionary(); // Map of id=>object var swf9_id_table:Array = []; override function IDForObject (obj:*, force:Boolean=false):* { var id:Number; // in swf9 we can use the flash.utils.Dictionary object to do hash table // lookups using === object equality, so we don't need to iterate over the // id_to_object_table to see if an object has been interned. var ot = this.swf9_object_table; if (ot[obj] != null) { return ot[obj]; } if (!force) { // ID anything that has identity if (! this.isObjectLike(obj)) { return null; } } id = this.objseq++; this.swf9_object_table[obj] = id; this.swf9_id_table[id] = obj; return id; }; override function ObjectForID (id) { return this.swf9_id_table[id]; }; /** * Predicate for deciding if an object is 'Object-like' (has * interesting properties) * * @access private */ override function isObjectLike (obj:*):Boolean { // NOTE [2008-09-16 ptw] In JS2 all primitives (boolean, number, // string) are auto-wrapped, so you can't ask `obj is Object` to // distinguish primitives from objects return !!obj && (typeof(obj) == 'object'); }; /** * Predicate for deciding if an object is 'Array-like' (has a * non-negative integer length property) * * @access private */ #passthrough { public override function isArrayLike (obj:*):Boolean { // Efficiency if (! obj) { return false; } if (obj is Array) { return true; } if (obj is String) { return true; } if (! (typeof obj == 'object')) { return false; } // NOTE [2008-09-20 ptw] In JS2 you can't ask obj['length'] if the // object's class doesn't have such a property, or is not dynamic var description:XML = describeType(obj); if ((description.@isDynamic == 'true') || (description.variable.(@name == 'length').length() != 0)) { return super.isArrayLike(obj); } return false; }; }# /** * Adds handling of swf9 Class * * @access private */ override function __StringDescription (thing:*, escape:Boolean, limit:Number, readable:Boolean, depth:Number):Object { if (thing is Class) { var s = this.functionName(thing); if (s) { return {readable: false, description: s} } } return super.__StringDescription(thing, escape, limit, readable, depth); } /** * @access private * @devnote This is carefully constructed so that if there is a * preferred name but mustBeUnique cannot be satisfied, we return * null (because the debugger may re-call us without the unique * requirement, to get the preferred name). * * @devnote TODO: [2008-09-23 ptw] (LPP-7034) Remove public * declaration after 7034 is resolved */ #passthrough{ // all methods are coerced to public when compiling for debug public override function functionName (fn, mustBeUnique:Boolean=false) { if (fn is Class) { // JS2 constructors are Class if (fn['tagname']) { // Handle tag classes if ((! mustBeUnique) || (fn === lz[fn.tagname])) { return '<' + fn.tagname + '>'; } else { return null; } } // Display name takes precedence over the actual class name if (fn[Debug.FUNCTION_NAME]) { var n = fn[Debug.FUNCTION_NAME]; } else { var n = getQualifiedClassName(fn); } if (! mustBeUnique) { return n; } else { try { if (fn == getDefinitionByName(n)) { return n; } } catch (e) {}; return null; } } return super.functionName(fn, mustBeUnique); }; }# /** * Adds unenumerable object properties for DHMTL runtime * * @access private */ #passthrough { // all methods are coerced to public when compiling for debug public override function objectOwnProperties (obj:*, names:Array=null, indices:Array=null, limit:Number=Infinity, nonEnumerable:Boolean=false) { // TODO [2008-09-11 hqm] not sure what to do here, we use the introspection API // flash.utils.describeType() to at least enumerate public properties... if (names != null) { var description:XML = describeType(obj); for each(var a:XML in description.variable) { names.push(a.@name); } } return super.objectOwnProperties(obj, names, indices, limit,nonEnumerable); } }# } // In AS3, we just build the whole debugger right now Debug = new LzAS3DebugService(null); var __LzDebug = Debug;
/* -*- mode: JavaScript; c-basic-offset: 2; -*- */ /* * Platform-specific DebugService * * @copyright Copyright 2001-2010 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. */ class LzAS3DebugService extends LzDebugService { #passthrough (toplevel:true) { import flash.utils.describeType; import flash.utils.Dictionary; import flash.utils.getDefinitionByName import flash.utils.getQualifiedClassName import flash.system.Capabilities; }# /** * @access private */ function LzAS3DebugService (base:LzBootstrapDebugService) { super(base); } /** ** Platform-specific implementation of debug I/O **/ /** * Instantiates an instance of the user Debugger window * Called last thing by the compiler when the app is completely loaded. * @access private */ function makeDebugWindow () { // Make the real console. This is only called if the user code // did not actually instantiate a <debug /> tag var params:Object = LFCApplication.stage.loaderInfo.parameters; var remote =( params[ "lzconsoledebug" ] ); if (remote == 'true') { // Open the remote debugger socket this.attachDebugConsole(new LzFlashRemoteDebugConsole()); } else { // This will attach itself, once it is fully initialized. new lz.LzDebugWindow(); } if (! Capabilities.isDebugger) { Debug.warn("Install the Flash debug player (http://www.adobe.com/support/flashplayer/downloads.html) for debugging."); } } // Map of object=>id var swf9_object_table:Dictionary = new Dictionary(); // Map of id=>object var swf9_id_table:Array = []; override function IDForObject (obj:*, force:Boolean=false):* { var id:Number; // in swf9 we can use the flash.utils.Dictionary object to do hash table // lookups using === object equality, so we don't need to iterate over the // id_to_object_table to see if an object has been interned. var ot = this.swf9_object_table; if (ot[obj] != null) { return ot[obj]; } if (!force) { // ID anything that has identity if (! this.isObjectLike(obj)) { return null; } } id = this.objseq++; this.swf9_object_table[obj] = id; this.swf9_id_table[id] = obj; return id; }; override function ObjectForID (id) { return this.swf9_id_table[id]; }; /** * Predicate for deciding if an object is 'Object-like' (has * interesting properties) * * @access private */ override function isObjectLike (obj:*):Boolean { // NOTE [2008-09-16 ptw] In JS2 all primitives (boolean, number, // string) are auto-wrapped, so you can't ask `obj is Object` to // distinguish primitives from objects return !!obj && (typeof(obj) == 'object'); }; /** * Predicate for deciding if an object is 'Array-like' (has a * non-negative integer length property) * * @access private */ #passthrough { public override function isArrayLike (obj:*):Boolean { // Efficiency if (! obj) { return false; } if (obj is Array) { return true; } if (obj is String) { return true; } if (! (typeof obj == 'object')) { return false; } // NOTE [2008-09-20 ptw] In JS2 you can't ask obj['length'] if the // object's class doesn't have such a property, or is not dynamic var description:XML = describeType(obj); if ((description.@isDynamic == 'true') || (description.variable.(@name == 'length').length() != 0)) { return super.isArrayLike(obj); } return false; }; }# /** * Adds handling of swf9 Class * * @access private */ override function __StringDescription (thing:*, escape:Boolean, limit:Number, readable:Boolean, depth:Number):Object { if (thing is Class) { var s = this.functionName(thing); if (s) { return {readable: false, description: s} } } return super.__StringDescription(thing, escape, limit, readable, depth); } /** * @access private * @devnote This is carefully constructed so that if there is a * preferred name but mustBeUnique cannot be satisfied, we return * null (because the debugger may re-call us without the unique * requirement, to get the preferred name). * * @devnote TODO: [2008-09-23 ptw] (LPP-7034) Remove public * declaration after 7034 is resolved */ #passthrough{ // all methods are coerced to public when compiling for debug public override function functionName (fn, mustBeUnique:Boolean=false) { if (fn is Class) { // JS2 constructors are Class if (fn['tagname']) { // Handle tag classes if ((! mustBeUnique) || (fn === lz[fn.tagname])) { return '<' + fn.tagname + '>'; } else { return null; } } // Display name takes precedence over the actual class name if (fn[Debug.FUNCTION_NAME]) { var n = fn[Debug.FUNCTION_NAME]; } else { var n = getQualifiedClassName(fn); } if (! mustBeUnique) { return n; } else { try { if (fn == getDefinitionByName(n)) { return n; } } catch (e) {}; return null; } } return super.functionName(fn, mustBeUnique); }; }# /** * Adds unenumerable object properties for DHMTL runtime * * @access private */ #passthrough { // all methods are coerced to public when compiling for debug public override function objectOwnProperties (obj:*, names:Array=null, indices:Array=null, limit:Number=Infinity, nonEnumerable:Boolean=false) { // TODO [2008-09-11 hqm] not sure what to do here, we use the introspection API // flash.utils.describeType() to at least enumerate public properties... if (names != null) { var description:XML = describeType(obj); for each(var a:XML in description.variable) { names.push(a.@name); } } return super.objectOwnProperties(obj, names, indices, limit,nonEnumerable); } }# } // In AS3, we just build the whole debugger right now Debug = new LzAS3DebugService(null); var __LzDebug = Debug;
Change 20100208-ptw-K by [email protected] on 2010-02-08 13:27:48 EST in /Users/ptw/OpenLaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20100208-ptw-K by [email protected] on 2010-02-08 13:27:48 EST in /Users/ptw/OpenLaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Warn when swf9/10 & debug but not running debug player Bugs Fixed: LPP-8692 Debug console can't display the correct compile error in swf9 Technical Reviewer: hminsky (Message-ID: <[email protected]>) QA Reviewer: max (Message-ID: <[email protected]>) Release Notes: The debugger will issue a warning if you are using the swf9 or swf10 runtimes but do not have the debug Flash player installed. The debugger relies on the debug player for displaying human-readable error messages. Details: When creating debug console, test for debug player and warn if not present. Tests: Launch any application without the debug player installed and notice the warning. Install the debug player and notice no warning. (Good luck if you do it in the other order as the Adobe installer will apparently not let you downgrade.) git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@15653 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
78c51196ead06ee6299f4845b76d06a4602d9b83
src/aerys/minko/render/material/basic/BasicMaterial.as
src/aerys/minko/render/material/basic/BasicMaterial.as
package aerys.minko.render.material.basic { import aerys.minko.render.Effect; import aerys.minko.render.material.Material; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public class BasicMaterial extends Material { public static const DEFAULT_NAME : String = 'BasicMaterial'; public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader(); public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER); public function get diffuseFormat() : uint { return getProperty(BasicProperties.DIFFUSE_FORMAT); } public function set diffuseFormat(value : uint) : void { setProperty(BasicProperties.DIFFUSE_FORMAT, value); } public function get blending() : uint { return getProperty(BasicProperties.BLENDING); } public function set blending(value : uint) : void { setProperty(BasicProperties.BLENDING, value); } public function get triangleCulling() : uint { return getProperty(BasicProperties.TRIANGLE_CULLING); } public function set triangleCulling(value : uint) : void { setProperty(BasicProperties.TRIANGLE_CULLING, value); } public function get diffuseColor() : uint { return getProperty(BasicProperties.DIFFUSE_COLOR); } public function set diffuseColor(value : uint) : void { setProperty(BasicProperties.DIFFUSE_COLOR, value); } public function get diffuseMap() : TextureResource { return getProperty(BasicProperties.DIFFUSE_MAP); } public function set diffuseMap(value : TextureResource) : void { setProperty(BasicProperties.DIFFUSE_MAP, value); } public function get alphaMap() : TextureResource { return getProperty(BasicProperties.ALPHA_MAP) as TextureResource; } public function set alphaMap(value : TextureResource) : void { setProperty(BasicProperties.ALPHA_MAP, value); } public function get alphaThreshold() : Number { return getProperty(BasicProperties.ALPHA_THRESHOLD); } public function set alphaThreshold(value : Number) : void { setProperty(BasicProperties.ALPHA_THRESHOLD, value); } public function get depthTest() : uint { return getProperty(BasicProperties.DEPTH_TEST); } public function set depthTest(value : uint) : void { setProperty(BasicProperties.DEPTH_TEST, value); } public function get depthWriteEnabled() : Boolean { return getProperty(BasicProperties.DEPTH_WRITE_ENABLED); } public function set depthWriteEnabled(value : Boolean) : void { setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value); } public function get stencilTriangleFace() : uint { return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE); } public function set stencilTriangleFace(value : uint) : void { setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value); } public function get stencilCompareMode() : uint { return getProperty(BasicProperties.STENCIL_COMPARE_MODE); } public function set stencilCompareMode(value : uint) : void { setProperty(BasicProperties.STENCIL_COMPARE_MODE, value); } public function get stencilActionBothPass() : uint { return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS); } public function set stencilActionBothPass(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value); } public function get stencilActionDepthFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL); } public function set stencilActionDepthFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value); } public function get stencilActionDepthPassStencilFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL); } public function set stencilActionDepthPassStencilFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value); } public function get stencilReferenceValue() : Number { return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE); } public function set stencilReferenceValue(value : Number) : void { setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value); } public function get stencilReadMask() : uint { return getProperty(BasicProperties.STENCIL_READ_MASK); } public function set stencilReadMask(value : uint) : void { setProperty(BasicProperties.STENCIL_READ_MASK, value); } public function get stencilWriteMask() : uint { return getProperty(BasicProperties.STENCIL_WRITE_MASK); } public function set stencilWriteMask(value : uint) : void { setProperty(BasicProperties.STENCIL_WRITE_MASK, value); } public function get diffuseTransform() : Matrix4x4 { return getProperty(BasicProperties.DIFFUSE_TRANSFORM); } public function set diffuseTransform(value : Matrix4x4) : void { setProperty(BasicProperties.DIFFUSE_TRANSFORM, value); } public function get uvOffset() : Vector4 { return getProperty(BasicProperties.UV_OFFSET); } public function set uvOffset(value : Vector4) : void { setProperty(BasicProperties.UV_OFFSET, value); } public function get uvScale() : Vector4 { return getProperty(BasicProperties.UV_SCALE); } public function set uvScale(value : Vector4) : void { setProperty(BasicProperties.UV_SCALE, value); } public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(effect || DEFAULT_EFFECT, properties, name); } override public function clone() : IDataProvider { var mat : BasicMaterial = new BasicMaterial(this, effect, name); return mat; } } }
package aerys.minko.render.material.basic { import aerys.minko.render.Effect; import aerys.minko.render.material.Material; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public class BasicMaterial extends Material { public static const DEFAULT_NAME : String = 'BasicMaterial'; public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader(); public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER); public function get diffuseFormat() : uint { return getProperty(BasicProperties.DIFFUSE_FORMAT); } public function set diffuseFormat(value : uint) : void { setProperty(BasicProperties.DIFFUSE_FORMAT, value); } public function get blending() : uint { return getProperty(BasicProperties.BLENDING); } public function set blending(value : uint) : void { setProperty(BasicProperties.BLENDING, value); } public function get triangleCulling() : uint { return getProperty(BasicProperties.TRIANGLE_CULLING); } public function set triangleCulling(value : uint) : void { setProperty(BasicProperties.TRIANGLE_CULLING, value); } public function get diffuseColor() : Object { return getProperty(BasicProperties.DIFFUSE_COLOR); } public function set diffuseColor(value : Object) : void { setProperty(BasicProperties.DIFFUSE_COLOR, value); } public function get diffuseMap() : TextureResource { return getProperty(BasicProperties.DIFFUSE_MAP); } public function set diffuseMap(value : TextureResource) : void { setProperty(BasicProperties.DIFFUSE_MAP, value); } public function get alphaMap() : TextureResource { return getProperty(BasicProperties.ALPHA_MAP) as TextureResource; } public function set alphaMap(value : TextureResource) : void { setProperty(BasicProperties.ALPHA_MAP, value); } public function get alphaThreshold() : Number { return getProperty(BasicProperties.ALPHA_THRESHOLD); } public function set alphaThreshold(value : Number) : void { setProperty(BasicProperties.ALPHA_THRESHOLD, value); } public function get depthTest() : uint { return getProperty(BasicProperties.DEPTH_TEST); } public function set depthTest(value : uint) : void { setProperty(BasicProperties.DEPTH_TEST, value); } public function get depthWriteEnabled() : Boolean { return getProperty(BasicProperties.DEPTH_WRITE_ENABLED); } public function set depthWriteEnabled(value : Boolean) : void { setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value); } public function get stencilTriangleFace() : uint { return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE); } public function set stencilTriangleFace(value : uint) : void { setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value); } public function get stencilCompareMode() : uint { return getProperty(BasicProperties.STENCIL_COMPARE_MODE); } public function set stencilCompareMode(value : uint) : void { setProperty(BasicProperties.STENCIL_COMPARE_MODE, value); } public function get stencilActionBothPass() : uint { return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS); } public function set stencilActionBothPass(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value); } public function get stencilActionDepthFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL); } public function set stencilActionDepthFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value); } public function get stencilActionDepthPassStencilFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL); } public function set stencilActionDepthPassStencilFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value); } public function get stencilReferenceValue() : Number { return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE); } public function set stencilReferenceValue(value : Number) : void { setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value); } public function get stencilReadMask() : uint { return getProperty(BasicProperties.STENCIL_READ_MASK); } public function set stencilReadMask(value : uint) : void { setProperty(BasicProperties.STENCIL_READ_MASK, value); } public function get stencilWriteMask() : uint { return getProperty(BasicProperties.STENCIL_WRITE_MASK); } public function set stencilWriteMask(value : uint) : void { setProperty(BasicProperties.STENCIL_WRITE_MASK, value); } public function get diffuseTransform() : Matrix4x4 { return getProperty(BasicProperties.DIFFUSE_TRANSFORM); } public function set diffuseTransform(value : Matrix4x4) : void { setProperty(BasicProperties.DIFFUSE_TRANSFORM, value); } public function get uvOffset() : Vector4 { return getProperty(BasicProperties.UV_OFFSET); } public function set uvOffset(value : Vector4) : void { setProperty(BasicProperties.UV_OFFSET, value); } public function get uvScale() : Vector4 { return getProperty(BasicProperties.UV_SCALE); } public function set uvScale(value : Vector4) : void { setProperty(BasicProperties.UV_SCALE, value); } public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(effect || DEFAULT_EFFECT, properties, name); } override public function clone() : IDataProvider { var mat : BasicMaterial = new BasicMaterial(this, effect, name); return mat; } } }
set BasicMaterial.diffuseColor to be Object in order to accept both uint and Vector4 color values
set BasicMaterial.diffuseColor to be Object in order to accept both uint and Vector4 color values
ActionScript
mit
aerys/minko-as3
390831fc85f983be5492b2e6d91f7ab54fa32a2f
frameworks/projects/airspark/src/spark/components/windowClasses/TitleBar.as
frameworks/projects/airspark/src/spark/components/windowClasses/TitleBar.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.components.windowClasses { import flash.display.DisplayObject; import flash.display.NativeWindowDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.events.NativeWindowDisplayStateEvent; import flash.system.Capabilities; import mx.core.IWindow; import mx.core.mx_internal; import spark.components.Button; import spark.components.supportClasses.SkinnableComponent; import spark.components.supportClasses.TextBase; import spark.events.SkinPartEvent; import spark.primitives.BitmapImage; import spark.skins.*; import spark.skins.spark.windowChrome.MacTitleBarSkin; import spark.skins.spark.windowChrome.TitleBarSkin; use namespace mx_internal; //-------------------------------------- // SkinStates //-------------------------------------- /** * The title bar is enabled and the application is maximized. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinState("normalAndMaximized")] /** * The title bar is disabled and the application is maximized. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinState("disabledAndMaximized")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="focusBlendMode", kind="style")] [Exclude(name="focusThickness", kind="style")] /** * The TitleBar class defines the default title bar for a * WindowedApplication or a Window container. * * @see mx.core.Window * @see mx.core.WindowedApplication * * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class TitleBar extends SkinnableComponent { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ private static function isMac():Boolean { return Capabilities.os.substring(0, 3) == "Mac"; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function TitleBar():void { super(); doubleClickEnabled = true; addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * This is the actual object created from the _titleIcon class */ mx_internal var titleIconObject:Object; //-------------------------------------------------------------------------- // // Skin Parts // //-------------------------------------------------------------------------- //---------------------------------- // closeButton //---------------------------------- /** * The skin part that defines the Button control that corresponds to the close button. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="true")] public var closeButton:Button; //---------------------------------- // maximizeButton //---------------------------------- /** * The skin part that defines the Button control that corresponds to the maximize button. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var maximizeButton:Button; //---------------------------------- // minimizeButton //---------------------------------- /** * The skin part that defines the Button control that corresponds to the minimize button. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var minimizeButton:Button; //---------------------------------- // titleIconImage //---------------------------------- /** * The title icon in the TitleBar. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var titleIconImage:BitmapImage; //---------------------------------- // titleTextField //---------------------------------- /** * The skin part that defines the UITextField control that displays the application title text. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var titleText:TextBase; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // title //---------------------------------- /** * Storage for the title property. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ private var _title:String = ""; /** * @private */ private var titleChanged:Boolean = false; /** * The title that appears in the window title bar and * the dock or taskbar. * * @default "" * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get title():String { return _title; } /** * @private */ public function set title(value:String):void { _title = value; titleChanged = true; invalidateProperties(); invalidateSize(); invalidateDisplayList(); } //---------------------------------- // titleIcon //---------------------------------- /** * @private * Storage for the titleIcon property. */ private var _titleIcon:Class; /** * @private */ private var titleIconChanged:Boolean = false; /** * The icon displayed in the title bar. * * @default null * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get titleIcon():Class { return _titleIcon; } /** * @private */ public function set titleIcon(value:Class):void { _titleIcon = value; titleIconChanged = true; invalidateProperties(); invalidateSize(); } //---------------------------------- // window //---------------------------------- /** * The IWindow that owns this TitleBar. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ private function get window():IWindow { var p:DisplayObject = parent; while (p && !(p is IWindow)) p = p.parent; return IWindow(p); } //-------------------------------------------------------------------------- // // Overridden methods: SkinnableComponent // //-------------------------------------------------------------------------- /** * @private * * When we are running on the mac, switch to the mac skin and continue the load. * */ override protected function attachSkin():void { if (isMac() && getStyle("skinClass") == TitleBarSkin) { setStyle("skinClass", MacTitleBarSkin); } super.attachSkin(); } //-------------------------------------------------------------------------- // // Overridden methods: SkinnableContainer // //-------------------------------------------------------------------------- /** * @private */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == titleText) { titleText.text = title; } else if (instance == closeButton) { closeButton.focusEnabled = false; closeButton.addEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); closeButton.addEventListener(MouseEvent.CLICK, closeButton_clickHandler); } else if (instance == minimizeButton) { minimizeButton.focusEnabled = false; minimizeButton.enabled = window.minimizable; minimizeButton.addEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); minimizeButton.addEventListener(MouseEvent.CLICK, minimizeButton_clickHandler); } else if (instance == maximizeButton) { maximizeButton.focusEnabled = false; maximizeButton.enabled = window.maximizable; maximizeButton.addEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); maximizeButton.addEventListener(MouseEvent.CLICK, maximizeButton_clickHandler); var targetWindow:DisplayObject = DisplayObject(window); targetWindow.addEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, window_displayStateChangeHandler, false, 0, true); // Add this listener so we can remove the display state change handler // if our window is reskinned. This fixes an RTE when the titleBar // display state handler ran without a window after being reskinned. targetWindow.addEventListener(SkinPartEvent.PART_REMOVED, partRemovedHandler, false, 0, true); } } /** * @private */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == closeButton) { closeButton.removeEventListener(MouseEvent.CLICK, closeButton_clickHandler); } else if (instance == minimizeButton) { minimizeButton.removeEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); minimizeButton.removeEventListener(MouseEvent.CLICK, minimizeButton_clickHandler); } else if (instance == maximizeButton) { maximizeButton.removeEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); maximizeButton.removeEventListener(MouseEvent.CLICK, maximizeButton_clickHandler); var targetWindow:DisplayObject = DisplayObject(window); targetWindow.removeEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, window_displayStateChangeHandler); targetWindow.removeEventListener(SkinPartEvent.PART_REMOVED, partRemovedHandler); } } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if (titleChanged) { titleText.text = _title; titleChanged = false; } if (titleIconChanged) { if (titleIconObject) { titleIconImage.source = null; titleIconObject = null; } if (_titleIcon && titleIconImage) { titleIconObject = new _titleIcon(); titleIconImage.source = titleIconObject; } titleIconChanged = false; } } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Skin states support // //-------------------------------------------------------------------------- /** * Returns the name of the state to be applied to the skin. For example, a * Button component could return the String "up", "down", "over", or "disabled" * to specify the state. * * <p>A subclass of SkinnableComponent must override this method to return a value.</p> * * @return A string specifying the name of the state to apply to the skin. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function getCurrentSkinState():String { if (!window.nativeWindow.closed && window.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED) { return enabled ? "normalAndMaximized" : "disabledAndMaximized"; } return enabled ? "normal" : "disabled"; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function mouseDownHandler(event:MouseEvent):void { window.nativeWindow.startMove(); event.stopPropagation(); } /** * The method that handles a <code>doubleClick</code> event in a platform-appropriate manner. * * @param event The event object. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ protected function doubleClickHandler(event:MouseEvent):void { if (isMac()) { window.minimize(); } else { if (window.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED) { window.restore(); } else { window.maximize(); } } } /** * @private * Used to swallow mousedown so bar is not draggable from buttons */ private function button_mouseDownHandler(event:MouseEvent):void { event.stopPropagation(); } /** * @private */ private function minimizeButton_clickHandler(event:Event):void { window.minimize(); } /** * @private */ private function maximizeButton_clickHandler(event:Event):void { if (window.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED) { window.restore(); } else { window.maximize(); } // work around for bugs SDK-9547 & SDK-21190 maximizeButton.dispatchEvent(new MouseEvent(MouseEvent.ROLL_OUT)); } /** * @private */ private function closeButton_clickHandler(event:Event):void { window.close(); } /** * @private */ private function window_displayStateChangeHandler( event:NativeWindowDisplayStateEvent):void { // If we have been minimized or maximized then invalidate our skin state // so the maximize and restore buttons will be updated. if (event.afterDisplayState == NativeWindowDisplayState.MAXIMIZED || event.afterDisplayState == NativeWindowDisplayState.NORMAL) { invalidateSkinState(); } } /** * @private */ private function partRemovedHandler(event:SkinPartEvent):void { if (event.instance == this) { var targetWindow:DisplayObject = DisplayObject(window); targetWindow.removeEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, window_displayStateChangeHandler); targetWindow.removeEventListener(SkinPartEvent.PART_REMOVED, partRemovedHandler); } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.components.windowClasses { import flash.display.DisplayObject; import flash.display.NativeWindowDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.events.NativeWindowDisplayStateEvent; import flash.system.Capabilities; import mx.core.IWindow; import mx.core.mx_internal; import spark.components.Button; import spark.components.supportClasses.SkinnableComponent; import spark.components.supportClasses.TextBase; import spark.events.SkinPartEvent; import spark.primitives.BitmapImage; import spark.skins.*; import spark.skins.spark.windowChrome.MacTitleBarSkin; import spark.skins.spark.windowChrome.TitleBarSkin; use namespace mx_internal; //-------------------------------------- // SkinStates //-------------------------------------- /** * The title bar is enabled and the application is maximized. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinState("normalAndMaximized")] /** * The title bar is disabled and the application is maximized. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinState("disabledAndMaximized")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="focusBlendMode", kind="style")] [Exclude(name="focusThickness", kind="style")] /** * The TitleBar class defines the default title bar for a * WindowedApplication or a Window container. * * @see mx.core.Window * @see mx.core.WindowedApplication * * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class TitleBar extends SkinnableComponent { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ private static function isMac():Boolean { return Capabilities.os.substring(0, 3) == "Mac"; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function TitleBar():void { super(); doubleClickEnabled = true; addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * This is the actual object created from the _titleIcon class */ mx_internal var titleIconObject:Object; //-------------------------------------------------------------------------- // // Skin Parts // //-------------------------------------------------------------------------- //---------------------------------- // closeButton //---------------------------------- /** * The skin part that defines the Button control that corresponds to the close button. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="true")] public var closeButton:Button; //---------------------------------- // maximizeButton //---------------------------------- /** * The skin part that defines the Button control that corresponds to the maximize button. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var maximizeButton:Button; //---------------------------------- // minimizeButton //---------------------------------- /** * The skin part that defines the Button control that corresponds to the minimize button. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var minimizeButton:Button; //---------------------------------- // titleIconImage //---------------------------------- /** * The title icon in the TitleBar. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var titleIconImage:BitmapImage; //---------------------------------- // titleTextField //---------------------------------- /** * The skin part that defines the UITextField control that displays the application title text. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ [SkinPart (required="false")] public var titleText:TextBase; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // title //---------------------------------- /** * Storage for the title property. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ private var _title:String = ""; /** * @private */ private var titleChanged:Boolean = false; /** * The title that appears in the window title bar and * the dock or taskbar. * * @default "" * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get title():String { return _title; } /** * @private */ public function set title(value:String):void { _title = value; titleChanged = true; invalidateProperties(); invalidateSize(); invalidateDisplayList(); } //---------------------------------- // titleIcon //---------------------------------- /** * @private * Storage for the titleIcon property. */ private var _titleIcon:Class; /** * @private */ private var titleIconChanged:Boolean = false; /** * The icon displayed in the title bar. * * @default null * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get titleIcon():Class { return _titleIcon; } /** * @private */ public function set titleIcon(value:Class):void { _titleIcon = value; titleIconChanged = true; invalidateProperties(); invalidateSize(); } //---------------------------------- // window //---------------------------------- /** * The IWindow that owns this TitleBar. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ private function get window():IWindow { var p:DisplayObject = parent; while (p && !(p is IWindow)) p = p.parent; return IWindow(p); } //-------------------------------------------------------------------------- // // Overridden methods: SkinnableComponent // //-------------------------------------------------------------------------- /** * @private * * When we are running on the mac, switch to the mac skin and continue the load. * */ override protected function attachSkin():void { if (isMac() && getStyle("skinClass") == TitleBarSkin) { setStyle("skinClass", MacTitleBarSkin); } super.attachSkin(); } //-------------------------------------------------------------------------- // // Overridden methods: SkinnableContainer // //-------------------------------------------------------------------------- /** * @private */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == titleText) { titleText.text = title; } else if (instance == closeButton) { closeButton.focusEnabled = false; closeButton.addEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); closeButton.addEventListener(MouseEvent.CLICK, closeButton_clickHandler); } else if (instance == minimizeButton) { minimizeButton.focusEnabled = false; minimizeButton.enabled = window.minimizable; minimizeButton.addEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); minimizeButton.addEventListener(MouseEvent.CLICK, minimizeButton_clickHandler); } else if (instance == maximizeButton) { maximizeButton.focusEnabled = false; maximizeButton.enabled = window.maximizable; maximizeButton.addEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); maximizeButton.addEventListener(MouseEvent.CLICK, maximizeButton_clickHandler); var targetWindow:DisplayObject = DisplayObject(window); targetWindow.addEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, window_displayStateChangeHandler, false, 0, true); // Add this listener so we can remove the display state change handler // if our window is reskinned. This fixes an RTE when the titleBar // display state handler ran without a window after being reskinned. targetWindow.addEventListener(SkinPartEvent.PART_REMOVED, partRemovedHandler, false, 0, true); } } /** * @private */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == closeButton) { closeButton.removeEventListener(MouseEvent.CLICK, closeButton_clickHandler); } else if (instance == minimizeButton) { minimizeButton.removeEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); minimizeButton.removeEventListener(MouseEvent.CLICK, minimizeButton_clickHandler); } else if (instance == maximizeButton) { maximizeButton.removeEventListener(MouseEvent.MOUSE_DOWN, button_mouseDownHandler); maximizeButton.removeEventListener(MouseEvent.CLICK, maximizeButton_clickHandler); var targetWindow:DisplayObject = DisplayObject(window); targetWindow.removeEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, window_displayStateChangeHandler); targetWindow.removeEventListener(SkinPartEvent.PART_REMOVED, partRemovedHandler); } } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if (titleChanged) { if (titleText) { titleText.text = _title; } titleChanged = false; } if (titleIconChanged) { if (titleIconObject) { titleIconImage.source = null; titleIconObject = null; } if (_titleIcon && titleIconImage) { titleIconObject = new _titleIcon(); titleIconImage.source = titleIconObject; } titleIconChanged = false; } } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Skin states support // //-------------------------------------------------------------------------- /** * Returns the name of the state to be applied to the skin. For example, a * Button component could return the String "up", "down", "over", or "disabled" * to specify the state. * * <p>A subclass of SkinnableComponent must override this method to return a value.</p> * * @return A string specifying the name of the state to apply to the skin. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function getCurrentSkinState():String { if (!window.nativeWindow.closed && window.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED) { return enabled ? "normalAndMaximized" : "disabledAndMaximized"; } return enabled ? "normal" : "disabled"; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function mouseDownHandler(event:MouseEvent):void { window.nativeWindow.startMove(); event.stopPropagation(); } /** * The method that handles a <code>doubleClick</code> event in a platform-appropriate manner. * * @param event The event object. * * @langversion 3.0 * @playerversion AIR 1.5 * @productversion Flex 4 */ protected function doubleClickHandler(event:MouseEvent):void { if (isMac()) { window.minimize(); } else { if (window.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED) { window.restore(); } else { window.maximize(); } } } /** * @private * Used to swallow mousedown so bar is not draggable from buttons */ private function button_mouseDownHandler(event:MouseEvent):void { event.stopPropagation(); } /** * @private */ private function minimizeButton_clickHandler(event:Event):void { window.minimize(); } /** * @private */ private function maximizeButton_clickHandler(event:Event):void { if (window.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED) { window.restore(); } else { window.maximize(); } // work around for bugs SDK-9547 & SDK-21190 maximizeButton.dispatchEvent(new MouseEvent(MouseEvent.ROLL_OUT)); } /** * @private */ private function closeButton_clickHandler(event:Event):void { window.close(); } /** * @private */ private function window_displayStateChangeHandler( event:NativeWindowDisplayStateEvent):void { // If we have been minimized or maximized then invalidate our skin state // so the maximize and restore buttons will be updated. if (event.afterDisplayState == NativeWindowDisplayState.MAXIMIZED || event.afterDisplayState == NativeWindowDisplayState.NORMAL) { invalidateSkinState(); } } /** * @private */ private function partRemovedHandler(event:SkinPartEvent):void { if (event.instance == this) { var targetWindow:DisplayObject = DisplayObject(window); targetWindow.removeEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, window_displayStateChangeHandler); targetWindow.removeEventListener(SkinPartEvent.PART_REMOVED, partRemovedHandler); } } } }
Fix RTE described in FLEX-33385. titeText is optional part.
Fix RTE described in FLEX-33385. titeText is optional part. git-svn-id: f8d5f742b420a6a114b58659a4f85f335318e53c@1454944 13f79535-47bb-0310-9956-ffa450edef68
ActionScript
apache-2.0
shyamalschandra/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk
866d5e44f5d5fa4e125af922dd2edcd5ce25f386
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/DataGridView.as
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/DataGridView.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadModel; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IDataGridModel; import org.apache.flex.core.ISelectableItemRenderer; import org.apache.flex.core.ISelectionModel; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.ButtonBar; import org.apache.flex.html.Container; import org.apache.flex.html.List; import org.apache.flex.html.beads.layouts.ButtonBarLayout; import org.apache.flex.html.beads.layouts.VerticalLayout; import org.apache.flex.html.beads.models.ArraySelectionModel; import org.apache.flex.html.beads.models.DataGridPresentationModel; import org.apache.flex.html.supportClasses.DataGridColumn; import org.apache.flex.html.supportClasses.ScrollingViewport; import org.apache.flex.html.supportClasses.Viewport; /** * The DataGridView class is the visual bead for the org.apache.flex.html.DataGrid. * This class constructs the items that make the DataGrid: Lists for each column and a * org.apache.flex.html.ButtonBar for the column headers. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DataGridView implements IBeadView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DataGridView() { } private var _strand:IStrand; private var _header:ButtonBar; private var _listArea:Container; private var _lists:Array; /** * @private */ public function get host():IUIBase { return _strand as IUIBase; } /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; var host:UIBase = value as UIBase; host.addEventListener("widthChanged", handleSizeChanges); host.addEventListener("heightChanged", handleSizeChanges); _header = new ButtonBar(); _header.id = "dataGridHeader"; var scrollPort:ScrollingViewport = new ScrollingViewport(); scrollPort.showsHorizontalScrollBar = false; _listArea = new Container(); _listArea.id = "dataGridListArea"; _listArea.className = "DataGridListArea"; _listArea.addBead(scrollPort); finishSetup(null); } /** * @private */ private function finishSetup(event:Event):void { var host:UIBase = _strand as UIBase; // see if there is a presentation model already in place. if not, add one. var presentationModel:DataGridPresentationModel = _strand.getBeadByType(DataGridPresentationModel) as DataGridPresentationModel; if (presentationModel == null) { presentationModel = new DataGridPresentationModel(); _strand.addBead(presentationModel); } var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; IEventDispatcher(sharedModel).addEventListener("dataProviderChanged",handleDataProviderChanged); var columnLabels:Array = new Array(); var buttonWidths:Array = new Array(); for(var i:int=0; i < sharedModel.columns.length; i++) { var dgc:DataGridColumn = sharedModel.columns[i] as DataGridColumn; columnLabels.push(dgc.label); if (!isNaN(dgc.columnWidth)) buttonWidths.push(dgc.columnWidth); } var bblayout:ButtonBarLayout = new ButtonBarLayout(); if (buttonWidths.length == sharedModel.columns.length) { bblayout.buttonWidths = buttonWidths; } var buttonBarModel:ArraySelectionModel = new ArraySelectionModel(); buttonBarModel.dataProvider = columnLabels; _header.addBead(buttonBarModel); _header.addBead(bblayout); _header.addBead(new Viewport()); host.addElement(_header); host.addElement(_listArea); // do we know what the size is? If not, wait to be sized if (host.isHeightSizedToContent() || host.isWidthSizedToContent()) { host.addEventListener("sizeChanged", handleSizeChanges); } // else size now else { handleDataProviderChanged(event); } } /** * @private */ private function handleSizeChanges(event:Event):void { _header.x = 0; _header.y = 0; _header.width = host.width; _header.height = 25; _listArea.x = 0; _listArea.y = 26; _listArea.width = host.width; _listArea.height = host.height - _header.height; var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; if (_lists != null && _lists.length > 0) { var xpos:Number = 0; var listWidth:Number = host.width / _lists.length; for (var i:int=0; i < _lists.length; i++) { var list:List = _lists[i] as List; list.x = xpos; list.y = 0; var dataGridColumn:DataGridColumn = sharedModel.columns[i] as DataGridColumn; var colWidth:Number = dataGridColumn.columnWidth; if (!isNaN(colWidth)) list.width = colWidth; else list.width = listWidth; xpos += list.width; } } } /** * @private */ private function handleDataProviderChanged(event:Event):void { var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; if (_lists == null || _lists.length == 0) { createLists(); } for (var i:int=0; i < _lists.length; i++) { var list:List = _lists[i] as List; var listModel:ISelectionModel = list.getBeadByType(IBeadModel) as ISelectionModel; listModel.dataProvider = sharedModel.dataProvider; } handleSizeChanges(event); } /** * @private */ private function handleColumnListChange(event:Event):void { var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; var list:List = event.target as List; sharedModel.selectedIndex = list.selectedIndex; for(var i:int=0; i < _lists.length; i++) { if (list != _lists[i]) { var otherList:List = _lists[i] as List; otherList.selectedIndex = list.selectedIndex; } } IEventDispatcher(_strand).dispatchEvent(new Event('change')); } /** * @private */ private function handleColumnListRollOver(event:Event):void { var itemRenderer:ISelectableItemRenderer = event.target as ISelectableItemRenderer; var list:List = event.currentTarget as List; if (list == null) return; for(var i:int=0; i < _lists.length; i++) { if (list != _lists[i]) { var otherList:List = _lists[i] as List; otherList.rollOverIndex = itemRenderer.index; } } IEventDispatcher(_strand).dispatchEvent(new Event('rollOver')); } /** * @private */ private function handleColumnListRollOut(event:Event):void { for(var i:int=0; i < _lists.length; i++) { var otherList:List = _lists[i] as List; otherList.rollOverIndex = -1; } IEventDispatcher(_strand).dispatchEvent(new Event('rollOver')); } /** * @private */ private function createLists():void { var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; var presentationModel:DataGridPresentationModel = _strand.getBeadByType(DataGridPresentationModel) as DataGridPresentationModel; var listWidth:Number = host.width / sharedModel.columns.length; _lists = new Array(); for (var i:int=0; i < sharedModel.columns.length; i++) { var dataGridColumn:DataGridColumn = sharedModel.columns[i] as DataGridColumn; var list:List = new List(); list.id = "dataGridColumn"+String(i); list.className = "DataGridColumn"; list.addBead(sharedModel); list.itemRenderer = dataGridColumn.itemRenderer; list.labelField = dataGridColumn.dataField; list.addEventListener('change',handleColumnListChange); list.addEventListener('rollover',handleColumnListRollOver); list.addEventListener('rollout',handleColumnListRollOut); list.addBead(presentationModel); var colWidth:Number = dataGridColumn.columnWidth; if (!isNaN(colWidth)) list.width = colWidth; else list.width = listWidth; _listArea.addElement(list); _lists.push(list); } _listArea.dispatchEvent(new Event("layoutNeeded")); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadModel; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IDataGridModel; import org.apache.flex.core.ISelectableItemRenderer; import org.apache.flex.core.ISelectionModel; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.ButtonBar; import org.apache.flex.html.Container; import org.apache.flex.html.List; import org.apache.flex.html.beads.layouts.ButtonBarLayout; import org.apache.flex.html.beads.layouts.VerticalLayout; import org.apache.flex.html.beads.models.ArraySelectionModel; import org.apache.flex.html.beads.models.DataGridPresentationModel; import org.apache.flex.html.supportClasses.DataGridColumn; import org.apache.flex.html.supportClasses.ScrollingViewport; import org.apache.flex.html.supportClasses.Viewport; /** * The DataGridView class is the visual bead for the org.apache.flex.html.DataGrid. * This class constructs the items that make the DataGrid: Lists for each column and a * org.apache.flex.html.ButtonBar for the column headers. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DataGridView implements IBeadView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DataGridView() { } private var _strand:IStrand; private var _header:ButtonBar; private var _listArea:Container; private var _lists:Array; /** * @private */ public function get host():IUIBase { return _strand as IUIBase; } /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; var host:UIBase = value as UIBase; host.addEventListener("widthChanged", handleSizeChanges); host.addEventListener("heightChanged", handleSizeChanges); _header = new ButtonBar(); _header.id = "dataGridHeader"; var scrollPort:ScrollingViewport = new ScrollingViewport(); scrollPort.showsHorizontalScrollBar = false; _listArea = new Container(); _listArea.id = "dataGridListArea"; _listArea.className = "DataGridListArea"; _listArea.addBead(scrollPort); finishSetup(null); } /** * @private */ private function finishSetup(event:Event):void { var host:UIBase = _strand as UIBase; // see if there is a presentation model already in place. if not, add one. var presentationModel:DataGridPresentationModel = _strand.getBeadByType(DataGridPresentationModel) as DataGridPresentationModel; if (presentationModel == null) { presentationModel = new DataGridPresentationModel(); _strand.addBead(presentationModel); } var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; IEventDispatcher(sharedModel).addEventListener("dataProviderChanged",handleDataProviderChanged); var columnLabels:Array = new Array(); var buttonWidths:Array = new Array(); for(var i:int=0; i < sharedModel.columns.length; i++) { var dgc:DataGridColumn = sharedModel.columns[i] as DataGridColumn; columnLabels.push(dgc.label); if (!isNaN(dgc.columnWidth)) buttonWidths.push(dgc.columnWidth); } var bblayout:ButtonBarLayout = new ButtonBarLayout(); if (buttonWidths.length == sharedModel.columns.length) { bblayout.buttonWidths = buttonWidths; } var buttonBarModel:ArraySelectionModel = new ArraySelectionModel(); buttonBarModel.dataProvider = columnLabels; _header.addBead(buttonBarModel); _header.addBead(bblayout); _header.addBead(new Viewport()); host.addElement(_header); host.addElement(_listArea); // do we know what the size is? If not, wait to be sized if (host.isHeightSizedToContent() || host.isWidthSizedToContent()) { host.addEventListener("sizeChanged", handleSizeChanges); } // else size now else { handleDataProviderChanged(event); } } /** * @private */ private function handleSizeChanges(event:Event):void { var useWidth:Number = _listArea.width; var useHeight:Number = _listArea.height; if (host.width > 0) { useWidth = host.width; } _header.x = 0; _header.y = 0; _header.width = useWidth; _header.height = 25; if (host.height > 0) { useHeight = host.height - _header.height; } _listArea.x = 0; _listArea.y = 26; _listArea.width = useWidth; _listArea.height = useHeight; var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; if (_lists != null && _lists.length > 0) { var xpos:Number = 0; var listWidth:Number = host.width / _lists.length; for (var i:int=0; i < _lists.length; i++) { var list:List = _lists[i] as List; list.x = xpos; list.y = 0; var dataGridColumn:DataGridColumn = sharedModel.columns[i] as DataGridColumn; var colWidth:Number = dataGridColumn.columnWidth; if (!isNaN(colWidth)) list.width = colWidth; else list.width = listWidth; xpos += list.width; } } } /** * @private */ private function handleDataProviderChanged(event:Event):void { var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; if (_lists == null || _lists.length == 0) { createLists(); } for (var i:int=0; i < _lists.length; i++) { var list:List = _lists[i] as List; var listModel:ISelectionModel = list.getBeadByType(IBeadModel) as ISelectionModel; listModel.dataProvider = sharedModel.dataProvider; } handleSizeChanges(event); } /** * @private */ private function handleColumnListChange(event:Event):void { var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; var list:List = event.target as List; sharedModel.selectedIndex = list.selectedIndex; for(var i:int=0; i < _lists.length; i++) { if (list != _lists[i]) { var otherList:List = _lists[i] as List; otherList.selectedIndex = list.selectedIndex; } } IEventDispatcher(_strand).dispatchEvent(new Event('change')); } /** * @private */ private function handleColumnListRollOver(event:Event):void { var itemRenderer:ISelectableItemRenderer = event.target as ISelectableItemRenderer; var list:List = event.currentTarget as List; if (list == null) return; for(var i:int=0; i < _lists.length; i++) { if (list != _lists[i]) { var otherList:List = _lists[i] as List; otherList.rollOverIndex = itemRenderer.index; } } IEventDispatcher(_strand).dispatchEvent(new Event('rollOver')); } /** * @private */ private function handleColumnListRollOut(event:Event):void { for(var i:int=0; i < _lists.length; i++) { var otherList:List = _lists[i] as List; otherList.rollOverIndex = -1; } IEventDispatcher(_strand).dispatchEvent(new Event('rollOver')); } /** * @private */ private function createLists():void { var sharedModel:IDataGridModel = _strand.getBeadByType(IBeadModel) as IDataGridModel; var presentationModel:DataGridPresentationModel = _strand.getBeadByType(DataGridPresentationModel) as DataGridPresentationModel; var listWidth:Number = host.width / sharedModel.columns.length; _lists = new Array(); for (var i:int=0; i < sharedModel.columns.length; i++) { var dataGridColumn:DataGridColumn = sharedModel.columns[i] as DataGridColumn; var list:List = new List(); list.id = "dataGridColumn"+String(i); list.className = "DataGridColumn"; list.addBead(sharedModel); list.itemRenderer = dataGridColumn.itemRenderer; list.labelField = dataGridColumn.dataField; list.addEventListener('change',handleColumnListChange); list.addEventListener('rollover',handleColumnListRollOver); list.addEventListener('rollout',handleColumnListRollOut); list.addBead(presentationModel); var colWidth:Number = dataGridColumn.columnWidth; if (!isNaN(colWidth)) list.width = colWidth; else list.width = listWidth; _listArea.addElement(list); _lists.push(list); } _listArea.dispatchEvent(new Event("layoutNeeded")); } } }
Stop DataGridView from resizing if the size of the strand is 0x0.
Stop DataGridView from resizing if the size of the strand is 0x0.
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
80739a0e09a232de71ee27d1f48b17d8fa5578d7
dolly-framework/src/main/actionscript/dolly/Copier.as
dolly-framework/src/main/actionscript/dolly/Copier.as
package dolly { import dolly.core.dolly_internal; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.IMetadataContainer; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Copier { private static function getCopyableFieldsOfType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE); if (isTypeCloneable) { for each(variable in type.variables) { if (!variable.isStatic) { result.push(variable); } } for each(accessor in type.accessors) { if (!accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE) { result.push(accessor); } } } else { const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE); for each(var metadataContainer:IMetadataContainer in metadataContainers) { if (metadataContainer is Variable) { variable = metadataContainer as Variable; if (!variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) { result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (!accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE && accessor.hasMetadata(MetadataName.COPYABLE)) { result.push(accessor); } } } } return result; } dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = getCopyableFieldsOfType(type); return result; } public static function copy(source:*):* { const type:Type = Type.forInstance(source); const copy:* = new (type.clazz)(); const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type); var name:String; for each(var field:Field in fieldsToCopy) { name = field.name; copy[name] = source[name]; } return copy; } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.IMetadataContainer; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Copier { private static function getCopyableFieldsOfType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE); if (isTypeCloneable) { for each(variable in type.variables) { if (!variable.isStatic) { result.push(variable); } } for each(accessor in type.accessors) { if (!accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE) { result.push(accessor); } } } else { const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE); for each(var metadataContainer:IMetadataContainer in metadataContainers) { if (metadataContainer is Variable) { variable = metadataContainer as Variable; if (!variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) { result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (!accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE && accessor.hasMetadata(MetadataName.COPYABLE)) { result.push(accessor); } } } } return result; } dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> { var result:Vector.<Field> = getCopyableFieldsOfType(type); var superType:Type; var superTypeCopyableFields:Vector.<Field>; for each(var superTypeName:String in type.extendsClasses) { superType = Type.forName(superTypeName); superTypeCopyableFields = getCopyableFieldsOfType(superType); if (superTypeCopyableFields.length > 0) { result = result.concat(superTypeCopyableFields); } } return result; } public static function copy(source:*):* { const type:Type = Type.forInstance(source); const copy:* = new (type.clazz)(); const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type); var name:String; for each(var field:Field in fieldsToCopy) { name = field.name; copy[name] = source[name]; } return copy; } } }
Add finding of copyable fields in superclasses.
Add finding of copyable fields in superclasses.
ActionScript
mit
Yarovoy/dolly
d1740b9728209b5db97f7b0be3d840419fa3784f
dolly-framework/src/main/actionscript/dolly/Copier.as
dolly-framework/src/main/actionscript/dolly/Copier.as
package dolly { import dolly.core.dolly_internal; import dolly.core.metadata.MetadataName; import flash.utils.Dictionary; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.IMetadataContainer; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Copier { private static function getCopyableFieldsOfType(type:Type, foundFieldsMap:Dictionary):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE); if (isTypeCloneable) { for each(variable in type.variables) { if (!foundFieldsMap[variable.name] && !variable.isStatic) { foundFieldsMap[variable.name] = variable; result.push(variable); } } for each(accessor in type.accessors) { if (!foundFieldsMap[accessor.name] && !accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE) { foundFieldsMap[accessor.name] = accessor; result.push(accessor); } } } else { const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE); for each(var metadataContainer:IMetadataContainer in metadataContainers) { if (metadataContainer is Variable) { variable = metadataContainer as Variable; if (!foundFieldsMap[variable.name] && !variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) { foundFieldsMap[variable.name] = variable; result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (!foundFieldsMap[accessor.name] && !accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE && accessor.hasMetadata(MetadataName.COPYABLE)) { foundFieldsMap[accessor.name] = accessor; result.push(accessor); } } } } return result; } dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> { var foundFields:Dictionary = new Dictionary(); var result:Vector.<Field> = getCopyableFieldsOfType(type, foundFields); var superType:Type; var superTypeCopyableFields:Vector.<Field>; for each(var superTypeName:String in type.extendsClasses) { superType = Type.forName(superTypeName); superTypeCopyableFields = getCopyableFieldsOfType(superType, foundFields); if (superTypeCopyableFields.length > 0) { result = result.concat(superTypeCopyableFields); } } return result; } public static function copy(source:*):* { const type:Type = Type.forInstance(source); const copy:* = new (type.clazz)(); const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type); var name:String; for each(var field:Field in fieldsToCopy) { name = field.name; copy[name] = source[name]; } return copy; } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.metadata.MetadataName; import flash.utils.Dictionary; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.IMetadataContainer; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Copier { private static function getCopyableFieldsOfType(type:Type, foundFields:Dictionary):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE); if (isTypeCloneable) { for each(variable in type.variables) { if (!foundFields[variable.name] && !variable.isStatic) { foundFields[variable.name] = variable; result.push(variable); } } for each(accessor in type.accessors) { if (!foundFields[accessor.name] && !accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE) { foundFields[accessor.name] = accessor; result.push(accessor); } } } else { const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE); for each(var metadataContainer:IMetadataContainer in metadataContainers) { if (metadataContainer is Variable) { variable = metadataContainer as Variable; if (!foundFields[variable.name] && !variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) { foundFields[variable.name] = variable; result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (!foundFields[accessor.name] && !accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE && accessor.hasMetadata(MetadataName.COPYABLE)) { foundFields[accessor.name] = accessor; result.push(accessor); } } } } return result; } dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> { var foundFields:Dictionary = new Dictionary(); var result:Vector.<Field> = getCopyableFieldsOfType(type, foundFields); var superType:Type; var superTypeCopyableFields:Vector.<Field>; for each(var superTypeName:String in type.extendsClasses) { superType = Type.forName(superTypeName); superTypeCopyableFields = getCopyableFieldsOfType(superType, foundFields); if (superTypeCopyableFields.length > 0) { result = result.concat(superTypeCopyableFields); } } return result; } public static function copy(source:*):* { const type:Type = Type.forInstance(source); const copy:* = new (type.clazz)(); const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type); var name:String; for each(var field:Field in fieldsToCopy) { name = field.name; copy[name] = source[name]; } return copy; } } }
Rename argument's name.
Rename argument's name.
ActionScript
mit
Yarovoy/dolly
8ed43be14447c207998c1c54dd61973bac1cae17
as3/com/netease/protobuf/SimpleWebRPC.as
as3/com/netease/protobuf/SimpleWebRPC.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.net.*; import flash.utils.*; import flash.events.*; public final class SimpleWebRPC { private var urlPrefix:String public function SimpleWebRPC(urlPrefix:String) { this.urlPrefix = urlPrefix; } private static const REF:Dictionary = new Dictionary(); public function send(qualifiedMethodName:String, input:IExternalizable, callback:Function, outputType:Class):void { const loader:URLLoader = new URLLoader REF[loader] = true; loader.dataFormat = URLLoaderDataFormat.BINARY loader.addEventListener(Event.COMPLETE, function(event:Event):void { delete REF[loader] const output:IExternalizable = new outputType output.readExternal(loader.data) callback(output) }) function errorEventHandler(event:Event):void { delete REF[loader] callback(event) } loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler) loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, errorEventHandler) const request:URLRequest = new URLRequest( urlPrefix + qualifiedMethodName) request.method = URLRequestMethod.POST const requestContent:ByteArray = new ByteArray input.writeExternal(requestContent) request.data = requestContent request.contentType = "application/x-protobuf" loader.load(request) } } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.net.*; import flash.utils.*; import flash.events.*; public final class SimpleWebRPC { private var urlPrefix:String public function SimpleWebRPC(urlPrefix:String) { this.urlPrefix = urlPrefix; } private static const REF:Dictionary = new Dictionary(); public function send(qualifiedMethodName:String, input:IExternalizable, rpcResult:Function, outputType:Class):void { const loader:URLLoader = new URLLoader REF[loader] = true; loader.dataFormat = URLLoaderDataFormat.BINARY loader.addEventListener(Event.COMPLETE, function(event:Event):void { delete REF[loader] const output:IExternalizable = new outputType output.readExternal(loader.data) rpcResult(output) }) function errorEventHandler(event:Event):void { delete REF[loader] rpcResult(event) } loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler) loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, errorEventHandler) const request:URLRequest = new URLRequest( urlPrefix + qualifiedMethodName) request.method = URLRequestMethod.POST const requestContent:ByteArray = new ByteArray input.writeExternal(requestContent) request.data = requestContent request.contentType = "application/x-protobuf" loader.load(request) } } }
把另一处 callback 也改成其他名字
把另一处 callback 也改成其他名字
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
0b47eb2228b3cb57c62875ade793ad59cc35d985
src/aerys/minko/type/loader/AssetsLibrary.as
src/aerys/minko/type/loader/AssetsLibrary.as
package aerys.minko.type.loader { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.node.Mesh; import aerys.minko.type.Signal; public final class AssetsLibrary { private var _numGeometries : uint = 0; private var _numMaterials : uint = 0; private var _numTextures : uint = 0; private var _geometryList : Vector.<Geometry> = new Vector.<Geometry>(); private var _materialList : Vector.<Material> = new Vector.<Material>(); private var _textureList : Vector.<TextureResource> = new Vector.<TextureResource>(); private var _geometries : Object; private var _textures : Object; private var _materials : Object; private var _layers : Vector.<String>; private var _nameToLayer : Object; private var _geometryAdded : Signal; private var _textureAdded : Signal; private var _materialAdded : Signal; private var _layerAdded : Signal; public function AssetsLibrary() { initialize(); initializeSignals(); } public function get numTextures() : uint { return _numTextures; } public function get numGeometries() : uint { return _numGeometries; } public function get numMaterials() : uint { return _numMaterials; } public function getMaterialAt(index : uint): Material { return _materialList[index]; } public function getGeometryAt(index : uint): Geometry { return _geometryList[index]; } public function getTextureAt(index : uint): TextureResource { return _textureList[index]; } public function getMaterialByName(name : String) : Material { return _materials[name]; } public function getTextureByName(name : String) : TextureResource { return _textures[name]; } public function getGeometryByName(name : String) : Geometry { return _geometries[name]; } private function initialize() : void { _geometries = {}; _textures = {}; _materials = {}; _layers = new Vector.<String>(32, true); _layers[0] = 'Default'; for (var i : uint = 1; i < _layers.length; ++i) _layers[i] = 'Layer_' + i; _nameToLayer = {}; } private function initializeSignals() : void { _geometryAdded = new Signal('AssetsLibrary.geometryAdded'); _textureAdded = new Signal('AssetsLibrary.textureAdded'); _materialAdded = new Signal('AssetsLibrary.materialAdded'); _layerAdded = new Signal('AssetsLibrary.layerAdded'); } public function get layerAdded() : Signal { return _layerAdded; } public function get materialAdded() : Signal { return _materialAdded; } public function get textureAdded() : Signal { return _textureAdded; } public function get geometryAdded() : Signal { return _geometryAdded; } public function setGeometry(name : String, geometry : Geometry) : void { ++_numGeometries; _geometryList.push(geometry); _geometries[name] = geometry; _geometryAdded.execute(this, name, geometry); } public function setTexture(name : String, texture : TextureResource) : void { ++_numTextures; _textureList.push(texture); _textures[name] = texture; _textureAdded.execute(this, name, texture); } public function setMaterial(name : String, material : Material) : void { name ||= material.name; ++_numMaterials; _materialList.push(material); _materials[name] = material; _materialAdded.execute(this, name, material); } public function setLayer(name : String, layer : uint) : void { name ||= 'Layer_' + layer; _layers[layer] = name; _layerAdded.execute(this, name, layer); } public function getLayerTag(name : String, ... params) : uint { var tag : uint = 0; if (_nameToLayer[name]) { tag |= 1 << _nameToLayer[name]; } for each (name in params) { if (_nameToLayer[name]) { tag |= 1 << _nameToLayer[name]; } } return tag; } public function getLayerName(tag : uint) : String { var names : Vector.<String> = new <String>[]; var name : String = null; var i : uint = 0; for (i = 0; i < 32; ++i) { if (tag & (1 << i)) names.push(_layers[i]); } name = names.join('|'); return name; } public function merge(other : AssetsLibrary) : AssetsLibrary { var name : String = null; var i : uint = 0; for (name in other._geometries) setGeometry(name, other._geometries[name]); for (name in other._materials) setMaterial(name, other._materials[name]); for (name in other._textures) setTexture(name, other._textures[name]); for each (name in other._layers) setLayer(name, i++); return this; } } }
package aerys.minko.type.loader { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.node.Mesh; import aerys.minko.type.Signal; public final class AssetsLibrary { private var _numGeometries : uint = 0; private var _numMaterials : uint = 0; private var _numTextures : uint = 0; private var _geometryList : Vector.<Geometry> = new Vector.<Geometry>(); private var _materialList : Vector.<Material> = new Vector.<Material>(); private var _textureList : Vector.<TextureResource> = new Vector.<TextureResource>(); private var _geometries : Object; private var _textures : Object; private var _materials : Object; private var _layers : Vector.<String>; private var _nameToLayer : Object; private var _geometryAdded : Signal; private var _textureAdded : Signal; private var _materialAdded : Signal; private var _layerAdded : Signal; public function AssetsLibrary() { initialize(); initializeSignals(); } public function get numTextures() : uint { return _numTextures; } public function get numGeometries() : uint { return _numGeometries; } public function get numMaterials() : uint { return _numMaterials; } public function getMaterialAt(index : uint): Material { return _materialList[index]; } public function getGeometryAt(index : uint): Geometry { return _geometryList[index]; } public function getTextureAt(index : uint): TextureResource { return _textureList[index]; } public function getMaterialByName(name : String) : Material { return _materials[name]; } public function getTextureByName(name : String) : TextureResource { return _textures[name]; } public function getGeometryByName(name : String) : Geometry { return _geometries[name]; } private function initialize() : void { _geometries = {}; _textures = {}; _materials = {}; _layers = new Vector.<String>(32, true); _layers[0] = 'Default'; for (var i : uint = 1; i < _layers.length; ++i) _layers[i] = 'Layer_' + i; _nameToLayer = {}; } private function initializeSignals() : void { _geometryAdded = new Signal('AssetsLibrary.geometryAdded'); _textureAdded = new Signal('AssetsLibrary.textureAdded'); _materialAdded = new Signal('AssetsLibrary.materialAdded'); _layerAdded = new Signal('AssetsLibrary.layerAdded'); } public function get layerAdded() : Signal { return _layerAdded; } public function get materialAdded() : Signal { return _materialAdded; } public function get textureAdded() : Signal { return _textureAdded; } public function get geometryAdded() : Signal { return _geometryAdded; } public function setGeometry(name : String, geometry : Geometry) : void { if (_geometryList.indexOf(geometry) == -1) { ++_numGeometries; _geometryList.push(geometry); _geometries[name] = geometry; _geometryAdded.execute(this, name, geometry); } } public function setTexture(name : String, texture : TextureResource) : void { if (_textureList.indexOf(texture) == -1) { ++_numTextures; _textureList.push(texture); _textures[name] = texture; _textureAdded.execute(this, name, texture); } } public function setMaterial(name : String, material : Material) : void { material ||= new BasicMaterial(); name ||= material.name; if (_materialList.indexOf(material) == -1) { ++_numMaterials; _materialList.push(material); _materials[name] = material; _materialAdded.execute(this, name, material); } } public function setLayer(name : String, layer : uint) : void { name ||= 'Layer_' + layer; _layers[layer] = name; _layerAdded.execute(this, name, layer); } public function getLayerTag(name : String, ... params) : uint { var tag : uint = 0; if (_nameToLayer[name]) { tag |= 1 << _nameToLayer[name]; } for each (name in params) { if (_nameToLayer[name]) { tag |= 1 << _nameToLayer[name]; } } return tag; } public function getLayerName(tag : uint) : String { var names : Vector.<String> = new <String>[]; var name : String = null; var i : uint = 0; for (i = 0; i < 32; ++i) { if (tag & (1 << i)) names.push(_layers[i]); } name = names.join('|'); return name; } public function merge(other : AssetsLibrary) : AssetsLibrary { var name : String = null; var i : uint = 0; for (name in other._geometries) setGeometry(name, other._geometries[name]); for (name in other._materials) setMaterial(name, other._materials[name]); for (name in other._textures) setTexture(name, other._textures[name]); for each (name in other._layers) setLayer(name, i++); return this; } } }
Fix function that add assets to lists
Fix function that add assets to lists
ActionScript
mit
aerys/minko-as3
70052b5743fb2788a3381fcf93f3d422a1267d26
src/aerys/minko/scene/controller/TransformController.as
src/aerys/minko/scene/controller/TransformController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private static const INIT_NONE : uint = 0; private static const INIT_LOCAL_TO_WORLD : uint = 1; private static const INIT_WORLD_TO_LOCAL : uint = 2; private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _initialized : Vector.<uint>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateLocalToWorld(nodeId : uint = 0) : void { var numNodes : uint = _transforms.length; var childrenOffset : uint = 1; var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[childId]; if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE) { rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); rootTransform._hasChanged = false; _initialized[nodeId] = INIT_LOCAL_TO_WORLD; root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } for (; nodeId < numNodes; ++nodeId) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged; localToWorld._hasChanged = false; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !_initialized[childId]; if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; childLocalToWorld .copyFrom(childTransform) .append(localToWorld); childTransform._hasChanged = false; _initialized[childId] = INIT_LOCAL_TO_WORLD; child.localToWorldTransformChanged.execute(child, childLocalToWorld); } } } } private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void { var dirtyRoot : int = -1; while (nodeId >= 0) { if ((_transforms[nodeId] as Matrix4x4)._hasChanged || !_initialized[nodeId]) dirtyRoot = nodeId; nodeId = _parentId[nodeId]; } if (dirtyRoot >= 0) updateLocalToWorld(dirtyRoot); } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _initialized = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _initialized = new <uint>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _initialized[nodeId] = INIT_NONE; if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) { worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); _initialized[nodeId] |= INIT_WORLD_TO_LOCAL; } } if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL)) { _initialized[nodeId] |= INIT_WORLD_TO_LOCAL; worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); } return worldToLocalTransform; } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private static const INIT_NONE : uint = 0; private static const INIT_LOCAL_TO_WORLD : uint = 1; private static const INIT_WORLD_TO_LOCAL : uint = 2; private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _initialized : Vector.<uint>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateLocalToWorld(nodeId : uint = 0) : void { var numNodes : uint = _transforms.length; var childrenOffset : uint = 1; var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[childId]; if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE) { rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); rootTransform._hasChanged = false; _initialized[nodeId] = INIT_LOCAL_TO_WORLD; root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } for (; nodeId < numNodes; ++nodeId) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged; localToWorld._hasChanged = false; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !_initialized[childId]; if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; childLocalToWorld .copyFrom(childTransform) .append(localToWorld); childTransform._hasChanged = false; _initialized[childId] = INIT_LOCAL_TO_WORLD; child.localToWorldTransformChanged.execute(child, childLocalToWorld); } } } } private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void { var dirtyRoot : int = -1; while (nodeId >= 0) { if ((_transforms[nodeId] as Matrix4x4)._hasChanged || !_initialized[nodeId]) dirtyRoot = nodeId; nodeId = _parentId[nodeId]; } if (dirtyRoot >= 0) updateLocalToWorld(dirtyRoot); } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _initialized = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _initialized = new <uint>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _initialized[nodeId] = INIT_NONE; if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) { worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); _initialized[nodeId] |= INIT_WORLD_TO_LOCAL; } } if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL)) { _initialized[nodeId] |= INIT_WORLD_TO_LOCAL; worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); } return worldToLocalTransform; } } }
fix uint instead of int for nodeId argument that might cause infinite loop in TransformController.updateAncestorsAndSelfLocalToWorldTransform()
fix uint instead of int for nodeId argument that might cause infinite loop in TransformController.updateAncestorsAndSelfLocalToWorldTransform()
ActionScript
mit
aerys/minko-as3
ab1010353662c99c8459d12abf0f73e27da31bfb
src/aerys/minko/scene/controller/TransformController.as
src/aerys/minko/scene/controller/TransformController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) { var rootTransform : Matrix4x4 = _transforms[0]; var isDirty : Boolean = rootTransform._hasChanged; if (isDirty) { _localToWorldTransforms[0].copyFrom(rootTransform); rootTransform._hasChanged = false; } updateLocalToWorld(); } } private function updateLocalToWorld(nodeId : uint = 0) : void { var numNodes : uint = _transforms.length; var childrenOffset : uint = 1; var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[childId]; if (rootTransform._hasChanged) { rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } for (; nodeId < numNodes; ++nodeId) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var isDirty : Boolean = localToWorld._hasChanged; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; localToWorld._hasChanged = false; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged; if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; childLocalToWorld .copyFrom(childTransform) .append(localToWorld); childTransform._hasChanged = false; child.localToWorldTransformChanged.execute(child, childLocalToWorld); } } } } private function getDirtyRoot(nodeId : int) : int { var dirtyRoot : int = nodeId; while (nodeId >= 0) { if ((_transforms[nodeId] as Matrix4x4)._hasChanged) dirtyRoot = nodeId; nodeId = _parentId[nodeId]; } return dirtyRoot; } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; if (forceUpdate) { var dirtyRoot : int = getDirtyRoot(nodeId); if (dirtyRoot >= 0) updateLocalToWorld(dirtyRoot); } return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); } if (forceUpdate) { var dirtyRoot : int = getDirtyRoot(nodeId); if (dirtyRoot >= 0) { updateLocalToWorld(dirtyRoot); worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); } } return worldToLocalTransform; } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _localToWorldTransformsInitialized : Vector.<Boolean>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateLocalToWorld(nodeId : uint = 0) : void { var numNodes : uint = _transforms.length; var childrenOffset : uint = 1; var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[childId]; if (rootTransform._hasChanged || !_localToWorldTransformsInitialized[nodeId]) { rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); rootTransform._hasChanged = false; _localToWorldTransformsInitialized[nodeId] = true; root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } for (; nodeId < numNodes; ++nodeId) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged || !_localToWorldTransformsInitialized[nodeId]; localToWorld._hasChanged = false; _localToWorldTransformsInitialized[nodeId] = true; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !_localToWorldTransformsInitialized[childId]; if (childIsDirty || _localToWorldTransformsInitialized[childId]) { var child : ISceneNode = _idToNode[childId]; childLocalToWorld .copyFrom(childTransform) .append(localToWorld); childTransform._hasChanged = false; _localToWorldTransformsInitialized[childId] = true; child.localToWorldTransformChanged.execute(child, childLocalToWorld); } } } } private function getDirtyRoot(nodeId : int) : int { var dirtyRoot : int = -1; while (nodeId >= 0) { if ((_transforms[nodeId] as Matrix4x4)._hasChanged || !_localToWorldTransformsInitialized[nodeId]) dirtyRoot = nodeId; nodeId = _parentId[nodeId]; } return dirtyRoot; } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _localToWorldTransformsInitialized = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _localToWorldTransformsInitialized = new <Boolean>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _localToWorldTransformsInitialized[nodeId] = false; if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; if (forceUpdate) { var dirtyRoot : int = getDirtyRoot(nodeId); if (dirtyRoot >= 0) updateLocalToWorld(dirtyRoot); } return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { if (_invalidList || _nodeToId[node] == undefined) updateTransformsList(); var nodeId : uint = _nodeToId[node]; var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); } if (forceUpdate) { var dirtyRoot : int = getDirtyRoot(nodeId); if (dirtyRoot >= 0) { updateLocalToWorld(dirtyRoot); worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); } } return worldToLocalTransform; } } }
Fix local to world transform update when an object is added.
Fix local to world transform update when an object is added.
ActionScript
mit
aerys/minko-as3
6f16d3f420910924bece04fe4bdd81ac930928df
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
package aerys.minko.render.shader.part { import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; public class DiffuseShaderPart extends ShaderPart { /** * The shader part to use a diffuse map or fallback and use a solid color. * * @param main * */ public function DiffuseShaderPart(main : Shader) { super(main); } public function getDiffuseColor(killOnAlphaThreshold : Boolean = true, uv : SFloat = null) : SFloat { var diffuseColor : SFloat = null; uv ||= vertexUV.xy; if (meshBindings.propertyExists(BasicProperties.UV_SCALE)) uv.scaleBy(meshBindings.getParameter(BasicProperties.UV_SCALE, 2)); if (meshBindings.propertyExists(BasicProperties.UV_OFFSET)) uv.incrementBy(meshBindings.getParameter(BasicProperties.UV_OFFSET, 2)); uv = interpolate(uv); if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP) && meshBindings.propertyExists(VertexComponent.UV.nativeFormatString)) { var diffuseMap : SFloat = meshBindings.getTextureParameter( BasicProperties.DIFFUSE_MAP, meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FILTERING, SamplerFiltering.LINEAR), meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING, SamplerMipMapping.LINEAR), meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_WRAPPING, SamplerWrapping.REPEAT), 0, meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FORMAT, SamplerFormat.RGBA) ); diffuseColor = sampleTexture(diffuseMap, uv); } else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR)) { diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4); } else { diffuseColor = float4(0., 0., 0., 1.); } if (meshBindings.propertyExists(BasicProperties.ALPHA_MAP)) { var alphaMap : SFloat = meshBindings.getTextureParameter( BasicProperties.ALPHA_MAP, meshBindings.getProperty(BasicProperties.ALPHA_MAP_FILTERING, SamplerFiltering.LINEAR), meshBindings.getProperty(BasicProperties.ALPHA_MAP_MIPMAPPING, SamplerMipMapping.LINEAR), meshBindings.getProperty(BasicProperties.ALPHA_MAP_WRAPPING, SamplerWrapping.REPEAT), 0, meshBindings.getProperty(BasicProperties.ALPHA_MAP_FORMAT, SamplerFormat.RGBA)); var alphaSample : SFloat = sampleTexture(alphaMap, uv); diffuseColor = float4(diffuseColor.rgb, alphaSample.r); } if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM)) { diffuseColor = multiply4x4( diffuseColor, meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16) ); } if (killOnAlphaThreshold && meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD)) { var alphaThreshold : SFloat = meshBindings.getParameter( BasicProperties.ALPHA_THRESHOLD, 1 ); kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold))); } return diffuseColor; } } }
package aerys.minko.render.shader.part { import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; public class DiffuseShaderPart extends ShaderPart { /** * The shader part to use a diffuse map or fallback and use a solid color. * * @param main * */ public function DiffuseShaderPart(main : Shader) { super(main); } public function getDiffuseColor(killOnAlphaThreshold : Boolean = true, uv : SFloat = null) : SFloat { var diffuseColor : SFloat = null; var useVertexUv : Boolean = uv == null; uv ||= vertexUV.xy; if (meshBindings.propertyExists(BasicProperties.UV_SCALE)) uv.scaleBy(meshBindings.getParameter(BasicProperties.UV_SCALE, 2)); if (meshBindings.propertyExists(BasicProperties.UV_OFFSET)) uv.incrementBy(meshBindings.getParameter(BasicProperties.UV_OFFSET, 2)); if (useVertexUv) uv = interpolate(uv); if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP) && meshBindings.propertyExists(VertexComponent.UV.nativeFormatString)) { var diffuseMap : SFloat = meshBindings.getTextureParameter( BasicProperties.DIFFUSE_MAP, meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FILTERING, SamplerFiltering.LINEAR), meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING, SamplerMipMapping.LINEAR), meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_WRAPPING, SamplerWrapping.REPEAT), 0, meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FORMAT, SamplerFormat.RGBA) ); diffuseColor = sampleTexture(diffuseMap, uv); } else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR)) { diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4); } else { diffuseColor = float4(0., 0., 0., 1.); } if (meshBindings.propertyExists(BasicProperties.ALPHA_MAP)) { var alphaMap : SFloat = meshBindings.getTextureParameter( BasicProperties.ALPHA_MAP, meshBindings.getProperty(BasicProperties.ALPHA_MAP_FILTERING, SamplerFiltering.LINEAR), meshBindings.getProperty(BasicProperties.ALPHA_MAP_MIPMAPPING, SamplerMipMapping.LINEAR), meshBindings.getProperty(BasicProperties.ALPHA_MAP_WRAPPING, SamplerWrapping.REPEAT), 0, meshBindings.getProperty(BasicProperties.ALPHA_MAP_FORMAT, SamplerFormat.RGBA)); var alphaSample : SFloat = sampleTexture(alphaMap, uv); diffuseColor = float4(diffuseColor.rgb, alphaSample.r); } if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM)) { diffuseColor = multiply4x4( diffuseColor, meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16) ); } if (killOnAlphaThreshold && meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD)) { var alphaThreshold : SFloat = meshBindings.getParameter( BasicProperties.ALPHA_THRESHOLD, 1 ); kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold))); } return diffuseColor; } } }
fix DiffuseShaderPart.getDiffuseColor() to use vertexUV if the provided uv argument is null
fix DiffuseShaderPart.getDiffuseColor() to use vertexUV if the provided uv argument is null
ActionScript
mit
aerys/minko-as3
8863c2a187367f733409674b77bf440ce343bc9f
src/ageofai/map/model/MapModel.as
src/ageofai/map/model/MapModel.as
/** * Created by vizoli on 4/8/16. */ package ageofai.map.model { import ageofai.home.vo.HomeVO; import ageofai.map.astar.AStar; import ageofai.map.constant.CMap; import ageofai.map.constant.CMapNodeType; import ageofai.map.event.MapCreatedEvent; import ageofai.map.geom.IntPoint; import ageofai.map.vo.MapDataVO; import ageofai.unit.base.BaseUnitView; import ageofai.villager.view.VillagerView; import common.mvc.model.base.BaseModel; public class MapModel extends BaseModel implements IMapModel { private var _astarMap:GeneralAStarMap; private var _map:Vector.<Vector.<MapNode>>; private var _units:Vector.<Vector.<BaseUnitView>>; private var _homes:Vector.<HomeVO>; private var _fruits:Vector.<IntPoint>; private var _trees:Vector.<IntPoint>; public function get map():Vector.<Vector.<MapNode>> { return this._map; } public function get homes():Vector.<HomeVO> { return this._homes; } public function get fruits():Vector.<IntPoint> { return this._fruits; } public function get trees():Vector.<IntPoint> { return this._trees; } public function createMap( rowCount:int, columnCount:int ):void { this._map = new Vector.<Vector.<MapNode>>( rowCount, true ); for( var i:int = 0; i < rowCount; i++ ) { this._map[ i ] = new Vector.<MapNode>( columnCount, true ); for( var j:int = 0; j < columnCount; j++ ) { this._map[ i ][ j ] = this.getMapNode(); } } // Get homes this._homes = this.getHomes( columnCount, rowCount ); for each ( var home:HomeVO in this._homes ) { for( i = home.pos.y; i < home.pos.y + 1; i++ ) { for( j = home.pos.x; j < home.pos.x + 1; j++ ) { this._map[ i ][ j ].objectType = CMapNodeType.OBJECT_HOME; } } } // Fruits this._fruits = this.getFruits(columnCount, rowCount); for each (var fruit:IntPoint in this._fruits) { this._map[fruit.y][fruit.x].objectType = CMapNodeType.OBJECT_FRUIT; } // Trees this._trees = this.getTrees(columnCount, rowCount); for each (var tree:IntPoint in this._trees) { this._map[ tree.y ][ tree.x ].objectType = CMapNodeType.OBJECT_TREE; } this.eventDispatcher.dispatchEvent( new MapCreatedEvent( MapCreatedEvent.MAP_CREATED, this.getMapData() ) ); } private function getHomes( columnCount:int, rowCount:int ):Vector.<HomeVO> { var homes:Vector.<HomeVO> = new Vector.<HomeVO>( CMap.HOME_COUNT, true ); var minDistanceX:int = columnCount / CMap.HOME_COUNT; var minDistanceY:int = rowCount / CMap.HOME_COUNT; var offsetX:int, offsetY:int; do { offsetX = offsetY = 0; for( var i:int = 0; i < CMap.HOME_COUNT - 1; i++ ) { var home:HomeVO = new HomeVO(); home.pos = getRandomPoint( offsetX, offsetX += minDistanceX, offsetY, offsetY += minDistanceY ); homes[ i ] = home; } home = new HomeVO(); home.pos = getRandomPoint( offsetX, columnCount - 1, offsetY, rowCount - 1 ); homes[ i ] = home; var isHomeInWalkableArea:Boolean = true; for( i = 0; i < CMap.HOME_COUNT; i++ ) { if( this.isUnWalkablePointNextToIt( homes[ i ].pos ) ) { isHomeInWalkableArea = false; break; } } if( !isHomeInWalkableArea ) { continue; } // Make sure they are valid _astarMap = new GeneralAStarMap( _map ); for( i = 0; i < CMap.HOME_COUNT; i++ ) { if( this.isUnWalkablePointNextToIt( homes[ i ].pos ) ) { break; } for( var j:int = 0; j < CMap.HOME_COUNT; j++ ) { if( i == j ) { continue; } var aStar:AStar = new AStar( _astarMap, homes[ i ].pos, homes[ j ].pos ); var solution:Vector.<IntPoint> = aStar.solve(); if( solution ) { break; } } if( !solution ) { break; } } }while( !solution ); return homes; } private function isUnWalkablePointNextToIt( pos:IntPoint ):Boolean { var offsets:Array = [ [ -1, -1 ], [ 0, -1 ], [ 1, -1 ], [ 2, -1 ], [ -1, 0 ], [ 0, 0 ],[ 1, 0 ],[ 2, 0 ], [ -1, 1 ], [ 0, 1 ],[ 1, 1 ],[ 2, 1 ], [ -1, 2 ], [ 0, 2 ], [ 1, 2 ], [ 2, 2 ], ]; for( var i:int = 0; i < offsets.length; i++ ) { var colIndex:int = pos.y + offsets[ i ][ 0 ]; var rowIndex:int = pos.x + offsets[ i ][ 1 ]; if( colIndex >= 0 && rowIndex >= 0 && colIndex < this._map.length && rowIndex < this._map[ 0 ].length && this.isUnWalkablePoint( new IntPoint( colIndex, rowIndex ) ) ) { return true; } } return false; } private function isUnWalkablePoint( pos:IntPoint ):Boolean { return !this._map[ pos.x ][ pos.y ].walkable; } private function getFruits( columnCount:int, rowCount:int ):Vector.<IntPoint> { var fruits:Vector.<IntPoint> = new Vector.<IntPoint>(); for( var i:int = 0; i < CMap.HOME_COUNT; i++ ) { var nearFruitsNo:int = Math.round( Math.random() * 4 ) + 2; for( var j:int = 0; j < nearFruitsNo; j++ ) { do{ var fruitX:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.x - 3); var fruitY:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.y - 3); }while( fruitX < 0 || fruitX >= columnCount || fruitY < 0 || fruitY >= rowCount || (fruitX >= this._homes[ i ].pos.x && fruitX <= this._homes[ i ].pos.x + 2 && fruitY >= this._homes[ i ].pos.y && fruitY <= this._homes[ i ].pos.y + 2) || !this._map[ fruitY ][ fruitX ].walkable || this.isHomeInTheNear( fruitY, fruitX ) ) fruits[ fruits.length ] = new IntPoint( fruitX, fruitY ); } } var farFruitsNo:int = Math.round( Math.random() * 2 ) + 8; for( i = 0; i < farFruitsNo; i++ ) { do{ var fruitPos:IntPoint = getRandomPoint( 0, columnCount, 0, rowCount ); }while( !this._map[ fruitPos.y ][ fruitPos.x ].walkable || distanceLessThan( 8, fruitPos ) ) fruits[ fruits.length ] = fruitPos; } return fruits; } private function getTrees( columnCount:int, rowCount:int ):Vector.<IntPoint> { var trees:Vector.<IntPoint> = new Vector.<IntPoint>(); for( var i:int = 0; i < CMap.HOME_COUNT; i++ ) { var nearTreesNo:int = Math.round( Math.random() * 3 ) + 2; for( var j:int = 0; j < nearTreesNo; j++ ) { do{ var treeX:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.x - 3); var treeY:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.y - 3); }while( treeX < 0 || treeX >= columnCount || treeY < 0 || treeY >= rowCount || (treeX >= this._homes[ i ].pos.x && treeX <= this._homes[ i ].pos.x + 2 && treeY >= this._homes[ i ].pos.y && treeY <= this._homes[ i ].pos.y + 2) || !this._map[ treeY ][ treeX ].walkable || this.isHomeInTheNear( treeY, treeX ) ) trees[ trees.length ] = new IntPoint( treeX, treeY ); } } var farTreesNo:int = Math.round( Math.random() * 2 ) + 14; for( i = 0; i < farTreesNo; i++ ) { do{ var treePos:IntPoint = getRandomPoint( 0, columnCount, 0, rowCount ); }while( !this._map[ treePos.y ][ treePos.x ].walkable || distanceLessThan( 8, treePos ) ) trees[ trees.length ] = treePos; } return trees; } private function isHomeInTheNear( col:uint, row:uint ):Boolean { var offsets:Array = [ [ -1, -1 ], [ 0, -1 ], [ 1, -1 ], [ -1, 0 ], [ 0, 0 ], [ 1, 0 ], [ -1, 1 ], [ 0, 1 ], [ 1, 1 ] ]; for( var i:int = 0; i < offsets.length; i++ ) { var colIndex:int = col + offsets[ i ][ 0 ]; var rowIndex:int = row + offsets[ i ][ 1 ]; if( this._map.length < rowIndex && rowIndex > 0 && this.map[ 0 ].length <= colIndex && colIndex > 0 && this._map[ colIndex ][ rowIndex ].objectType == CMapNodeType.OBJECT_HOME ) { return true; } } return false; } /* INTERFACE ageofai.map.model.IMapModel */ public function getMapData():MapDataVO { var mapData:MapDataVO = new MapDataVO(); mapData.fruits = this._fruits; mapData.homes = this._homes; mapData.map = this._map; mapData.trees = this._trees; return mapData; } public function addUnit( villager:VillagerView ):void { if( !this._units ) { this._units = new <Vector.<BaseUnitView>>[]; } this._units.push( villager ); this.eventDispatcher.dispatchEvent( new MapCreatedEvent( MapCreatedEvent.MAP_CREATED, this.getMapData() ) ); } public function getPath( startPos:IntPoint, endPos:IntPoint ):Vector.<IntPoint> { var aStar:AStar = new AStar( this._astarMap, startPos, endPos ); return aStar.solve(); } private function getMapNode():MapNode { var rnd:Number = Math.random() * 100; var type:int; if( rnd <= 50 ) { type = CMapNodeType.GRASS; } else if( rnd <= 95 ) { type = CMapNodeType.DARK_GRASS; } else { type = CMapNodeType.WATER; } return new MapNode( type ); } private function getRandomPoint( offsetX:int, limitX:int, offsetY:int, limitY:int ):IntPoint { var x:int = Math.random() * (limitX - offsetX) + offsetX; var y:int = Math.random() * (limitY - offsetY) + offsetY; return new IntPoint( x, y ); } private function distanceLessThan( units:int, pos:IntPoint ):Boolean { for( var i:int = 0, count:int = this._homes.length; i < count; i++ ) { if( Math.abs( pos.x - this._homes[ i ].pos.x ) + Math.abs( pos.y - this._homes[ i ].pos.y ) < units ) { return true; } } return false; } } }
/** * Created by vizoli on 4/8/16. */ package ageofai.map.model { import ageofai.home.vo.HomeVO; import ageofai.map.astar.AStar; import ageofai.map.constant.CMap; import ageofai.map.constant.CMapNodeType; import ageofai.map.event.MapCreatedEvent; import ageofai.map.geom.IntPoint; import ageofai.map.vo.MapDataVO; import ageofai.unit.base.BaseUnitView; import ageofai.villager.view.VillagerView; import common.mvc.model.base.BaseModel; public class MapModel extends BaseModel implements IMapModel { private var _astarMap:GeneralAStarMap; private var _map:Vector.<Vector.<MapNode>>; private var _units:Vector.<Vector.<BaseUnitView>>; private var _homes:Vector.<HomeVO>; private var _fruits:Vector.<IntPoint>; private var _trees:Vector.<IntPoint>; public function get map():Vector.<Vector.<MapNode>> { return this._map; } public function get homes():Vector.<HomeVO> { return this._homes; } public function get fruits():Vector.<IntPoint> { return this._fruits; } public function get trees():Vector.<IntPoint> { return this._trees; } public function createMap( rowCount:int, columnCount:int ):void { this._map = new Vector.<Vector.<MapNode>>( rowCount, true ); for( var i:int = 0; i < rowCount; i++ ) { this._map[ i ] = new Vector.<MapNode>( columnCount, true ); for( var j:int = 0; j < columnCount; j++ ) { this._map[ i ][ j ] = this.getMapNode(); } } // Get homes this._homes = this.getHomes( columnCount, rowCount ); for each ( var home:HomeVO in this._homes ) { for( i = home.pos.y; i < home.pos.y + 1; i++ ) { for( j = home.pos.x; j < home.pos.x + 1; j++ ) { this._map[ i ][ j ].objectType = CMapNodeType.OBJECT_HOME; } } } // Fruits this._fruits = this.getFruits(columnCount, rowCount); for each (var fruit:IntPoint in this._fruits) { this._map[fruit.y][fruit.x].objectType = CMapNodeType.OBJECT_FRUIT; } // Trees this._trees = this.getTrees(columnCount, rowCount); for each (var tree:IntPoint in this._trees) { this._map[ tree.y ][ tree.x ].objectType = CMapNodeType.OBJECT_TREE; } this.eventDispatcher.dispatchEvent( new MapCreatedEvent( MapCreatedEvent.MAP_CREATED, this.getMapData() ) ); } private function getHomes( columnCount:int, rowCount:int ):Vector.<HomeVO> { var homes:Vector.<HomeVO> = new Vector.<HomeVO>( CMap.HOME_COUNT, true ); var minDistanceX:int = columnCount / CMap.HOME_COUNT; var minDistanceY:int = rowCount / CMap.HOME_COUNT; var offsetX:int, offsetY:int; do { offsetX = offsetY = 1; for( var i:int = 0; i < CMap.HOME_COUNT - 1; i++ ) { var home:HomeVO = new HomeVO(); home.pos = getRandomPoint( offsetX, offsetX += minDistanceX, offsetY, offsetY += minDistanceY ); homes[ i ] = home; } home = new HomeVO(); home.pos = getRandomPoint( offsetX, columnCount - 1, offsetY, rowCount - 1 ); homes[ i ] = home; var isHomeInWalkableArea:Boolean = true; for( i = 0; i < CMap.HOME_COUNT; i++ ) { if( this.isUnWalkablePointNextToIt( homes[ i ].pos ) ) { isHomeInWalkableArea = false; break; } } if( !isHomeInWalkableArea ) { continue; } // Make sure they are valid _astarMap = new GeneralAStarMap( _map ); for( i = 0; i < CMap.HOME_COUNT; i++ ) { if( this.isUnWalkablePointNextToIt( homes[ i ].pos ) ) { break; } for( var j:int = 0; j < CMap.HOME_COUNT; j++ ) { if( i == j ) { continue; } var aStar:AStar = new AStar( _astarMap, homes[ i ].pos, homes[ j ].pos ); var solution:Vector.<IntPoint> = aStar.solve(); if( solution ) { break; } } if( !solution ) { break; } } }while( !solution ); return homes; } private function isUnWalkablePointNextToIt( pos:IntPoint ):Boolean { var offsets:Array = [ [ -1, -1 ], [ 0, -1 ], [ 1, -1 ], [ 2, -1 ], [ -1, 0 ], [ 0, 0 ],[ 1, 0 ],[ 2, 0 ], [ -1, 1 ], [ 0, 1 ],[ 1, 1 ],[ 2, 1 ], [ -1, 2 ], [ 0, 2 ], [ 1, 2 ], [ 2, 2 ], ]; for( var i:int = 0; i < offsets.length; i++ ) { var colIndex:int = pos.y + offsets[ i ][ 0 ]; var rowIndex:int = pos.x + offsets[ i ][ 1 ]; if( colIndex >= 0 && rowIndex >= 0 && colIndex < this._map.length && rowIndex < this._map[ 0 ].length && this.isUnWalkablePoint( new IntPoint( colIndex, rowIndex ) ) ) { return true; } } return false; } private function isUnWalkablePoint( pos:IntPoint ):Boolean { return !this._map[ pos.x ][ pos.y ].walkable; } private function getFruits( columnCount:int, rowCount:int ):Vector.<IntPoint> { var fruits:Vector.<IntPoint> = new Vector.<IntPoint>(); for( var i:int = 0; i < CMap.HOME_COUNT; i++ ) { var nearFruitsNo:int = Math.round( Math.random() * 4 ) + 2; for( var j:int = 0; j < nearFruitsNo; j++ ) { do{ var fruitX:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.x - 3); var fruitY:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.y - 3); }while( fruitX < 0 || fruitX >= columnCount || fruitY < 0 || fruitY >= rowCount || (fruitX >= this._homes[ i ].pos.x && fruitX <= this._homes[ i ].pos.x + 2 && fruitY >= this._homes[ i ].pos.y && fruitY <= this._homes[ i ].pos.y + 2) || !this._map[ fruitY ][ fruitX ].walkable || this.isHomeInTheNear( fruitY, fruitX ) ) fruits[ fruits.length ] = new IntPoint( fruitX, fruitY ); } } var farFruitsNo:int = Math.round( Math.random() * 2 ) + 8; for( i = 0; i < farFruitsNo; i++ ) { do{ var fruitPos:IntPoint = getRandomPoint( 0, columnCount, 0, rowCount ); }while( !this._map[ fruitPos.y ][ fruitPos.x ].walkable || distanceLessThan( 8, fruitPos ) ) fruits[ fruits.length ] = fruitPos; } return fruits; } private function getTrees( columnCount:int, rowCount:int ):Vector.<IntPoint> { var trees:Vector.<IntPoint> = new Vector.<IntPoint>(); for( var i:int = 0; i < CMap.HOME_COUNT; i++ ) { var nearTreesNo:int = Math.round( Math.random() * 3 ) + 2; for( var j:int = 0; j < nearTreesNo; j++ ) { do{ var treeX:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.x - 3); var treeY:int = Math.round( Math.random() * 8 ) + (this._homes[ i ].pos.y - 3); }while( treeX < 0 || treeX >= columnCount || treeY < 0 || treeY >= rowCount || (treeX >= this._homes[ i ].pos.x && treeX <= this._homes[ i ].pos.x + 2 && treeY >= this._homes[ i ].pos.y && treeY <= this._homes[ i ].pos.y + 2) || !this._map[ treeY ][ treeX ].walkable || this.isHomeInTheNear( treeY, treeX ) ) trees[ trees.length ] = new IntPoint( treeX, treeY ); } } var farTreesNo:int = Math.round( Math.random() * 2 ) + 14; for( i = 0; i < farTreesNo; i++ ) { do{ var treePos:IntPoint = getRandomPoint( 0, columnCount, 0, rowCount ); }while( !this._map[ treePos.y ][ treePos.x ].walkable || distanceLessThan( 8, treePos ) ) trees[ trees.length ] = treePos; } return trees; } private function isHomeInTheNear( col:uint, row:uint ):Boolean { var offsets:Array = [ [ -1, -1 ], [ 0, -1 ], [ 1, -1 ], [ -1, 0 ], [ 0, 0 ], [ 1, 0 ], [ -1, 1 ], [ 0, 1 ], [ 1, 1 ] ]; for( var i:int = 0; i < offsets.length; i++ ) { var colIndex:int = col + offsets[ i ][ 0 ]; var rowIndex:int = row + offsets[ i ][ 1 ]; if( this._map.length < rowIndex && rowIndex > 0 && this.map[ 0 ].length <= colIndex && colIndex > 0 && this._map[ colIndex ][ rowIndex ].objectType == CMapNodeType.OBJECT_HOME ) { return true; } } return false; } /* INTERFACE ageofai.map.model.IMapModel */ public function getMapData():MapDataVO { var mapData:MapDataVO = new MapDataVO(); mapData.fruits = this._fruits; mapData.homes = this._homes; mapData.map = this._map; mapData.trees = this._trees; return mapData; } public function addUnit( villager:VillagerView ):void { if( !this._units ) { this._units = new <Vector.<BaseUnitView>>[]; } this._units.push( villager ); this.eventDispatcher.dispatchEvent( new MapCreatedEvent( MapCreatedEvent.MAP_CREATED, this.getMapData() ) ); } public function getPath( startPos:IntPoint, endPos:IntPoint ):Vector.<IntPoint> { var aStar:AStar = new AStar( this._astarMap, startPos, endPos ); return aStar.solve(); } private function getMapNode():MapNode { var rnd:Number = Math.random() * 100; var type:int; if( rnd <= 50 ) { type = CMapNodeType.GRASS; } else if( rnd <= 95 ) { type = CMapNodeType.DARK_GRASS; } else { type = CMapNodeType.WATER; } return new MapNode( type ); } private function getRandomPoint( offsetX:int, limitX:int, offsetY:int, limitY:int ):IntPoint { var x:int = Math.random() * (limitX - offsetX) + offsetX; var y:int = Math.random() * (limitY - offsetY) + offsetY; return new IntPoint( x, y ); } private function distanceLessThan( units:int, pos:IntPoint ):Boolean { for( var i:int = 0, count:int = this._homes.length; i < count; i++ ) { if( Math.abs( pos.x - this._homes[ i ].pos.x ) + Math.abs( pos.y - this._homes[ i ].pos.y ) < units ) { return true; } } return false; } } }
fix 2
fix 2
ActionScript
apache-2.0
goc-flashplusplus/ageofai
f7146abdd5d47201cd6e19c770a219c7c5cc2c7e
src/org/mangui/osmf/plugins/loader/HLSLoaderBase.as
src/org/mangui/osmf/plugins/loader/HLSLoaderBase.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.loader { import org.mangui.hls.HLS; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.model.Level; import org.mangui.hls.constant.HLSTypes; import org.mangui.osmf.plugins.HLSMediaElement; import org.mangui.osmf.plugins.utils.ErrorManager; import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait; import org.osmf.events.MediaError; import org.osmf.events.MediaErrorEvent; import org.osmf.media.MediaElement; import org.osmf.media.MediaResourceBase; import org.osmf.media.URLResource; import org.osmf.net.DynamicStreamingItem; import org.osmf.net.DynamicStreamingResource; import org.osmf.net.StreamType; import org.osmf.net.StreamingURLResource; import org.osmf.traits.LoadState; import org.osmf.traits.LoadTrait; import org.osmf.traits.LoaderBase; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** * Loader for .m3u8 playlist file. * Works like a F4MLoader */ public class HLSLoaderBase extends LoaderBase { private var _loadTrait : LoadTrait; /** Reference to the framework. **/ private var _hls : HLS = null; public function HLSLoaderBase() { super(); } public static function canHandle(resource : MediaResourceBase) : Boolean { if (resource !== null && resource is URLResource) { var urlResource : URLResource = URLResource(resource); // check for m3u/m3u8 if (urlResource.url.search(/(https?|file)\:\/\/.*?\m3u(\?.*)?/i) !== -1) { return true; } var contentType : Object = urlResource.getMetadataValue("content-type"); if (contentType && contentType is String) { // If the filename doesn't include a .m3u or m3u8 extension, but // explicit content-type metadata is found on the // URLResource, we can handle it. Must be either of: // - "application/x-mpegURL" // - "vnd.apple.mpegURL" if ((contentType as String).search(/(application\/x-mpegURL|vnd.apple.mpegURL)/i) !== -1) { return true; } } } return false; } override public function canHandleResource(resource : MediaResourceBase) : Boolean { return canHandle(resource); } override protected function executeLoad(loadTrait : LoadTrait) : void { _loadTrait = loadTrait; updateLoadTrait(loadTrait, LoadState.LOADING); if (_hls != null) { _hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.removeEventListener(HLSEvent.ERROR, _errorHandler); _hls.dispose(); _hls = null; } _hls = new HLS(); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); /* load playlist */ _hls.load(URLResource(loadTrait.resource).url); } override protected function executeUnload(loadTrait : LoadTrait) : void { updateLoadTrait(loadTrait, LoadState.UNINITIALIZED); } /** Update video A/R on manifest load. **/ private function _manifestHandler(event : HLSEvent) : void { var resource : MediaResourceBase = URLResource(_loadTrait.resource); // retrieve stream type var streamType : String = (resource as StreamingURLResource).streamType; if (streamType == null || streamType == StreamType.LIVE_OR_RECORDED) { if (_hls.type == HLSTypes.LIVE) { streamType = StreamType.LIVE; } else { streamType = StreamType.RECORDED; } } var levels : Vector.<Level> = _hls.levels; var nbLevel : int = levels.length; var urlRes : URLResource = resource as URLResource; var dynamicRes : DynamicStreamingResource = new DynamicStreamingResource(urlRes.url); var streamItems : Vector.<DynamicStreamingItem> = new Vector.<DynamicStreamingItem>(); for (var i : int = 0; i < nbLevel; i++) { if (levels[i].width) { streamItems.push(new DynamicStreamingItem(level2label(levels[i]), levels[i].bitrate / 1024, levels[i].width, levels[i].height)); } else { streamItems.push(new DynamicStreamingItem(level2label(levels[i]), levels[i].bitrate / 1024)); } } dynamicRes.streamItems = streamItems; dynamicRes.initialIndex = _hls.startlevel; resource = dynamicRes; // set Stream Type var streamUrlRes : StreamingURLResource = resource as StreamingURLResource; streamUrlRes.streamType = streamType; try { var loadedElem : MediaElement = new HLSMediaElement(resource, _hls, event.levels[_hls.startlevel].duration); LoadFromDocumentLoadTrait(_loadTrait).mediaElement = loadedElem; updateLoadTrait(_loadTrait, LoadState.READY); } catch(e : Error) { updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR); _loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(e.errorID, e.message))); } }; private function level2label(level : Level) : String { if (level.name) { return level.name; } else { if (level.height) { return(level.height + 'p / ' + Math.round(level.bitrate / 1024) + 'kb'); } else { return(Math.round(level.bitrate / 1024) + 'kb'); } } } private function _errorHandler(event : HLSEvent) : void { var errorCode : int = ErrorManager.getMediaErrorCode(event); var errorMsg : String = ErrorManager.getMediaErrorMessage(event); CONFIG::LOGGING { Log.warn("HLS Error event received, dispatching MediaError " + errorCode + "," + errorMsg); } updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR); _loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(errorCode, errorMsg))); } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.loader { import org.mangui.hls.HLS; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.model.Level; import org.mangui.hls.constant.HLSTypes; import org.mangui.osmf.plugins.HLSMediaElement; import org.mangui.osmf.plugins.utils.ErrorManager; import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait; import org.osmf.events.MediaError; import org.osmf.events.MediaErrorEvent; import org.osmf.media.MediaElement; import org.osmf.media.MediaResourceBase; import org.osmf.media.URLResource; import org.osmf.net.DynamicStreamingItem; import org.osmf.net.DynamicStreamingResource; import org.osmf.net.StreamType; import org.osmf.net.StreamingURLResource; import org.osmf.traits.LoadState; import org.osmf.traits.LoadTrait; import org.osmf.traits.LoaderBase; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** * Loader for .m3u8 playlist file. * Works like a F4MLoader */ public class HLSLoaderBase extends LoaderBase { private var _loadTrait : LoadTrait; /** Reference to the framework. **/ private var _hls : HLS = null; public function HLSLoaderBase() { super(); } public static function canHandle(resource : MediaResourceBase) : Boolean { if (resource !== null && resource is URLResource) { var urlResource : URLResource = URLResource(resource); // check for m3u/m3u8 if (urlResource.url.search(/(https?|file)\:\/\/.*?\m3u(\?.*)?/i) !== -1) { return true; } var contentType : Object = urlResource.getMetadataValue("content-type"); if (contentType && contentType is String) { // If the filename doesn't include a .m3u or m3u8 extension, but // explicit content-type metadata is found on the // URLResource, we can handle it. Must be either of: // - "application/x-mpegURL" // - "vnd.apple.mpegURL" if ((contentType as String).search(/(application\/x-mpegURL|vnd.apple.mpegURL)/i) !== -1) { return true; } } } return false; } override public function canHandleResource(resource : MediaResourceBase) : Boolean { return canHandle(resource); } override protected function executeLoad(loadTrait : LoadTrait) : void { _loadTrait = loadTrait; updateLoadTrait(loadTrait, LoadState.LOADING); if (_hls != null) { _hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.removeEventListener(HLSEvent.ERROR, _errorHandler); _hls.dispose(); _hls = null; } _hls = new HLS(); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); /* load playlist */ _hls.load(URLResource(loadTrait.resource).url); } override protected function executeUnload(loadTrait : LoadTrait) : void { updateLoadTrait(loadTrait, LoadState.UNINITIALIZED); } /** Update video A/R on manifest load. **/ private function _manifestLoadedHandler(event : HLSEvent) : void { var resource : MediaResourceBase = URLResource(_loadTrait.resource); // retrieve stream type var streamType : String = (resource as StreamingURLResource).streamType; if (streamType == null || streamType == StreamType.LIVE_OR_RECORDED) { if (_hls.type == HLSTypes.LIVE) { streamType = StreamType.LIVE; } else { streamType = StreamType.RECORDED; } } var levels : Vector.<Level> = _hls.levels; var nbLevel : int = levels.length; var urlRes : URLResource = resource as URLResource; var dynamicRes : DynamicStreamingResource = new DynamicStreamingResource(urlRes.url); var streamItems : Vector.<DynamicStreamingItem> = new Vector.<DynamicStreamingItem>(); for (var i : int = 0; i < nbLevel; i++) { if (levels[i].width) { streamItems.push(new DynamicStreamingItem(level2label(levels[i]), levels[i].bitrate / 1024, levels[i].width, levels[i].height)); } else { streamItems.push(new DynamicStreamingItem(level2label(levels[i]), levels[i].bitrate / 1024)); } } dynamicRes.streamItems = streamItems; dynamicRes.initialIndex = _hls.startlevel; resource = dynamicRes; // set Stream Type var streamUrlRes : StreamingURLResource = resource as StreamingURLResource; streamUrlRes.streamType = streamType; try { var loadedElem : MediaElement = new HLSMediaElement(resource, _hls, event.levels[_hls.startlevel].duration); LoadFromDocumentLoadTrait(_loadTrait).mediaElement = loadedElem; updateLoadTrait(_loadTrait, LoadState.READY); } catch(e : Error) { updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR); _loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(e.errorID, e.message))); } }; private function level2label(level : Level) : String { if (level.name) { return level.name; } else { if (level.height) { return(level.height + 'p / ' + Math.round(level.bitrate / 1024) + 'kb'); } else { return(Math.round(level.bitrate / 1024) + 'kb'); } } } private function _errorHandler(event : HLSEvent) : void { var errorCode : int = ErrorManager.getMediaErrorCode(event); var errorMsg : String = ErrorManager.getMediaErrorMessage(event); CONFIG::LOGGING { Log.warn("HLS Error event received, dispatching MediaError " + errorCode + "," + errorMsg); } updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR); _loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(errorCode, errorMsg))); } } }
rename method for sake of clarity
rename method for sake of clarity
ActionScript
mpl-2.0
hola/flashls,Corey600/flashls,thdtjsdn/flashls,mangui/flashls,neilrackett/flashls,NicolasSiver/flashls,loungelogic/flashls,aevange/flashls,vidible/vdb-flashls,hola/flashls,tedconf/flashls,fixedmachine/flashls,aevange/flashls,clappr/flashls,jlacivita/flashls,mangui/flashls,dighan/flashls,JulianPena/flashls,thdtjsdn/flashls,codex-corp/flashls,aevange/flashls,vidible/vdb-flashls,suuhas/flashls,suuhas/flashls,NicolasSiver/flashls,loungelogic/flashls,jlacivita/flashls,neilrackett/flashls,suuhas/flashls,dighan/flashls,Peer5/flashls,aevange/flashls,suuhas/flashls,tedconf/flashls,Peer5/flashls,Peer5/flashls,Boxie5/flashls,Corey600/flashls,Boxie5/flashls,codex-corp/flashls,clappr/flashls,Peer5/flashls,fixedmachine/flashls,JulianPena/flashls
f13a10cb0ce9dca8637a706ab165debf94414340
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
// Editor debug icons // to add new std debug icons just add IconType, IconsTypesMaterials and ComponentTypes items enum IconsTypes { ICON_POINT_LIGHT = 0, ICON_SPOT_LIGHT, ICON_DIRECTIONAL_LIGHT, ICON_CAMERA, ICON_SOUND_SOURCE, ICON_SOUND_SOURCE_3D, ICON_SOUND_LISTENERS, ICON_ZONE, ICON_SPLINE_PATH, ICON_TRIGGER, ICON_CUSTOM_GEOMETRY, ICON_PARTICLE_EMITTER, ICON_COUNT } enum IconsColorType { ICON_COLOR_DEFAULT = 0, ICON_COLOR_SPLINE_PATH_BEGIN, ICON_COLOR_SPLINE_PATH_END } Array<Color> debugIconsColors = { Color(1,1,1) , Color(1,1,0), Color(0,1,0) }; Array<String> IconsTypesMaterials = {"DebugIconPointLight.xml", "DebugIconSpotLight.xml", "DebugIconLight.xml", "DebugIconCamera.xml", "DebugIconSoundSource.xml", "DebugIconSoundSource.xml", "DebugIconSoundListener.xml", "DebugIconZone.xml", "DebugIconSplinePathPoint.xml", "DebugIconCollisionTrigger.xml", "DebugIconCustomGeometry.xml", "DebugIconParticleEmitter.xml"}; Array<String> ComponentTypes = {"Light", "Light", "Light", "Camera", "SoundSource", "SoundSource3D", "SoundListener", "Zone", "SplinePath", "RigidBody", "CustomGeometry", "ParticleEmitter"}; Array<BillboardSet@> debugIconsSet(ICON_COUNT); Node@ debugIconsNode = null; int stepDebugIconsUpdate = 100; //ms uint timeToNextDebugIconsUpdate = 0; int stepDebugIconsUpdateSplinePath = 1000; //ms uint timeToNextDebugIconsUpdateSplinePath = 0; const int splinePathResolution = 16; const float splineStep = 1.0f / splinePathResolution; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(64, 64); Vector2 debugIconsSizeSmall = debugIconsSize / 1.5; VariantMap debugIconsPlacement; const int debugIconsPlacementIndent = 1.0; const float debugIconsOrthoDistance = 15.0; const float debugIconAlphaThreshold = 0.1; const float maxDistance = 50.0; void CreateDebugIcons(Node@ tempNode) { if (editorScene is null) return; debugIconsSet.Resize(ICON_COUNT); for (int i = 0; i < ICON_COUNT; ++i) { debugIconsSet[i] = tempNode.CreateComponent("BillboardSet"); debugIconsSet[i].material = cache.GetResource("Material", "Materials/Editor/" + IconsTypesMaterials[i]); debugIconsSet[i].sorted = true; debugIconsSet[i].temporary = true; debugIconsSet[i].fixedScreenSize = true; debugIconsSet[i].viewMask = 0x80000000; } } void UpdateViewDebugIcons() { if (editorScene is null || timeToNextDebugIconsUpdate > time.systemTime) return; debugIconsNode = editorScene.GetChild("DebugIconsContainer", true); if (debugIconsNode is null) { debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL); debugIconsNode.temporary = true; } // Checkout if debugIconsNode do not have any BBS component, add all at once BillboardSet@ isBSExist = debugIconsNode.GetComponent("BillboardSet"); if (isBSExist is null) CreateDebugIcons(debugIconsNode); if (debugIconsSet[ICON_POINT_LIGHT] !is null) { for (int i = 0; i < ICON_COUNT; ++i) debugIconsSet[i].enabled = debugIconsShow; } if (debugIconsShow == false) return; Vector3 camPos = activeViewport.cameraNode.worldPosition; bool isOrthographic = activeViewport.camera.orthographic; debugIconsPlacement.Clear(); for (int iconType = 0; iconType < ICON_COUNT; ++iconType) { if (debugIconsSet[iconType] !is null) { // SplinePath update resolution if (iconType == ICON_SPLINE_PATH && timeToNextDebugIconsUpdateSplinePath > time.systemTime) continue; Array<Node@> nodes = editorScene.GetChildrenWithComponent(ComponentTypes[iconType], true); // Clear old data if (iconType == ICON_SPLINE_PATH) ClearCommit(ICON_SPLINE_PATH, ICON_SPLINE_PATH + 1, nodes.length * splinePathResolution); else if (iconType == ICON_POINT_LIGHT || iconType == ICON_SPOT_LIGHT || iconType == ICON_DIRECTIONAL_LIGHT) ClearCommit(ICON_POINT_LIGHT, ICON_DIRECTIONAL_LIGHT + 1, nodes.length); else if (iconType == ICON_SOUND_SOURCE || iconType == ICON_SOUND_SOURCE_3D) ClearCommit(ICON_SOUND_SOURCE, ICON_SOUND_SOURCE_3D + 1, nodes.length); else ClearCommit(iconType, iconType + 1, nodes.length); if (nodes.length > 0) { // Fill with new data for (uint i = 0; i < nodes.length; ++i) { Component@ component = nodes[i].GetComponent(ComponentTypes[iconType]); if (component is null) continue; Color finalIconColor = debugIconsColors[ICON_COLOR_DEFAULT]; float distance = (camPos - nodes[i].worldPosition).length; if (isOrthographic) distance = debugIconsOrthoDistance; int iconsOffset = debugIconsPlacement[StringHash(nodes[i].id)].GetInt(); float iconsYPos = 0; if (iconType == ICON_SPLINE_PATH) { SplinePath@ sp = cast<SplinePath>(component); if (sp !is null) { if (sp.length > 0.01f) { for (int step = 0; step < splinePathResolution; step++) { int index = (i * splinePathResolution) + step; Vector3 splinePoint = sp.GetPoint(splineStep * step); Billboard@ bb = debugIconsSet[ICON_SPLINE_PATH].billboards[index]; float stepDistance = (camPos - splinePoint).length; if (isOrthographic) stepDistance = debugIconsOrthoDistance; if (step == 0) // SplinePath start { bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_BEGIN]; bb.size = debugIconsSize; bb.position = splinePoint; } else if ((step+1) >= (splinePathResolution - splineStep)) // SplinePath end { bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_END]; bb.size = debugIconsSize; bb.position = splinePoint; } else // SplinePath middle points { bb.color = finalIconColor; bb.size = debugIconsSizeSmall; bb.position = splinePoint; } bb.enabled = sp.enabled; // Blend Icon relatively by distance to it bb.color = Color(bb.color.r, bb.color.g, bb.color.b, 1.2f - 1.0f / (maxDistance / stepDistance)); if (bb.color.a < debugIconAlphaThreshold) bb.enabled = false; } } } } else { Billboard@ bb = debugIconsSet[iconType].billboards[i]; bb.size = debugIconsSize; if (iconType == ICON_TRIGGER) { RigidBody@ rigidbody = cast<RigidBody>(component); if (rigidbody !is null) { if (rigidbody.trigger == false) continue; } } else if (iconType == ICON_POINT_LIGHT || iconType == ICON_SPOT_LIGHT || iconType == ICON_DIRECTIONAL_LIGHT) { Light@ light = cast<Light>(component); if (light !is null) { if (light.lightType == LIGHT_POINT) bb = debugIconsSet[ICON_POINT_LIGHT].billboards[i]; else if (light.lightType == LIGHT_DIRECTIONAL) bb = debugIconsSet[ICON_DIRECTIONAL_LIGHT].billboards[i]; else if (light.lightType == LIGHT_SPOT) bb = debugIconsSet[ICON_SPOT_LIGHT].billboards[i]; finalIconColor = light.effectiveColor; } } bb.position = nodes[i].worldPosition; // Blend Icon relatively by distance to it bb.color = Color(finalIconColor.r, finalIconColor.g, finalIconColor.b, 1.2f - 1.0f / (maxDistance / distance)); bb.enabled = component.enabled; // Discard billboard if it almost transparent if (bb.color.a < debugIconAlphaThreshold) bb.enabled = false; IncrementIconPlacement(bb.enabled, nodes[i], 1); } } Commit(iconType, iconType+1); // SplinePath update resolution if (iconType == ICON_SPLINE_PATH) timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath; } } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; } void ClearCommit(int begin, int end, int newLength) { for (int i = begin; i < end; ++i) { BillboardSet@ iconSet = debugIconsSet[i]; iconSet.numBillboards = newLength; for (int j = 0; j < newLength; ++j) { Billboard@ bb = iconSet.billboards[j]; bb.enabled = false; } iconSet.Commit(); } } void Commit(int begin, int end) { for (int i = begin; i < end; ++i) { debugIconsSet[i].Commit(); } } void IncrementIconPlacement(bool componentEnabled, Node@ node, int offset) { if (componentEnabled == true) { int oldPlacement = debugIconsPlacement[StringHash(node.id)].GetInt(); debugIconsPlacement[StringHash(node.id)] = Variant(oldPlacement + offset); } }
// Editor debug icons // to add new std debug icons just add IconType, IconsTypesMaterials and ComponentTypes items enum IconsTypes { ICON_POINT_LIGHT = 0, ICON_SPOT_LIGHT, ICON_DIRECTIONAL_LIGHT, ICON_CAMERA, ICON_SOUND_SOURCE, ICON_SOUND_SOURCE_3D, ICON_SOUND_LISTENERS, ICON_ZONE, ICON_SPLINE_PATH, ICON_TRIGGER, ICON_CUSTOM_GEOMETRY, ICON_PARTICLE_EMITTER, ICON_COUNT } enum IconsColorType { ICON_COLOR_DEFAULT = 0, ICON_COLOR_SPLINE_PATH_BEGIN, ICON_COLOR_SPLINE_PATH_END } Array<Color> debugIconsColors = { Color(1,1,1) , Color(1,1,0), Color(0,1,0) }; Array<String> iconsTypesMaterials = {"DebugIconPointLight.xml", "DebugIconSpotLight.xml", "DebugIconLight.xml", "DebugIconCamera.xml", "DebugIconSoundSource.xml", "DebugIconSoundSource.xml", "DebugIconSoundListener.xml", "DebugIconZone.xml", "DebugIconSplinePathPoint.xml", "DebugIconCollisionTrigger.xml", "DebugIconCustomGeometry.xml", "DebugIconParticleEmitter.xml"}; Array<String> componentTypes = {"Light", "Light", "Light", "Camera", "SoundSource", "SoundSource3D", "SoundListener", "Zone", "SplinePath", "RigidBody", "CustomGeometry", "ParticleEmitter"}; Array<BillboardSet@> debugIconsSet(ICON_COUNT); Node@ debugIconsNode = null; int stepDebugIconsUpdate = 100; //ms uint timeToNextDebugIconsUpdate = 0; int stepDebugIconsUpdateSplinePath = 1000; //ms uint timeToNextDebugIconsUpdateSplinePath = 0; const int splinePathResolution = 16; const float splineStep = 1.0f / splinePathResolution; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(64, 64); Vector2 debugIconsSizeSmall = debugIconsSize / 1.5; VariantMap debugIconsPlacement; const int debugIconsPlacementIndent = 1.0; const float debugIconsOrthoDistance = 15.0; const float debugIconAlphaThreshold = 0.1; const float maxDistance = 50.0; void CreateDebugIcons(Node@ tempNode) { if (editorScene is null) return; debugIconsSet.Resize(ICON_COUNT); for (int i = 0; i < ICON_COUNT; ++i) { debugIconsSet[i] = tempNode.CreateComponent("BillboardSet"); debugIconsSet[i].material = cache.GetResource("Material", "Materials/Editor/" + iconsTypesMaterials[i]); debugIconsSet[i].sorted = true; debugIconsSet[i].temporary = true; debugIconsSet[i].fixedScreenSize = true; debugIconsSet[i].viewMask = 0x80000000; } } void UpdateViewDebugIcons() { if (editorScene is null || timeToNextDebugIconsUpdate > time.systemTime) return; debugIconsNode = editorScene.GetChild("DebugIconsContainer", true); if (debugIconsNode is null) { debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL); debugIconsNode.temporary = true; } // Checkout if debugIconsNode do not have any BBS component, add all at once BillboardSet@ isBSExist = debugIconsNode.GetComponent("BillboardSet"); if (isBSExist is null) CreateDebugIcons(debugIconsNode); if (debugIconsSet[ICON_POINT_LIGHT] !is null) { for (int i = 0; i < ICON_COUNT; ++i) debugIconsSet[i].enabled = debugIconsShow; } if (debugIconsShow == false) return; Vector3 camPos = activeViewport.cameraNode.worldPosition; bool isOrthographic = activeViewport.camera.orthographic; debugIconsPlacement.Clear(); for (int iconType = 0; iconType < ICON_COUNT; ++iconType) { if (debugIconsSet[iconType] !is null) { // SplinePath update resolution if (iconType == ICON_SPLINE_PATH && timeToNextDebugIconsUpdateSplinePath > time.systemTime) continue; Array<Node@> nodes = editorScene.GetChildrenWithComponent(componentTypes[iconType], true); // Clear old data if (iconType == ICON_SPLINE_PATH) ClearCommit(ICON_SPLINE_PATH, ICON_SPLINE_PATH + 1, nodes.length * splinePathResolution); else if (iconType == ICON_POINT_LIGHT || iconType == ICON_SPOT_LIGHT || iconType == ICON_DIRECTIONAL_LIGHT) ClearCommit(ICON_POINT_LIGHT, ICON_DIRECTIONAL_LIGHT + 1, nodes.length); else ClearCommit(iconType, iconType + 1, nodes.length); if (nodes.length > 0) { // Fill with new data for (uint i = 0; i < nodes.length; ++i) { Component@ component = nodes[i].GetComponent(componentTypes[iconType]); if (component is null) continue; Color finalIconColor = debugIconsColors[ICON_COLOR_DEFAULT]; float distance = (camPos - nodes[i].worldPosition).length; if (isOrthographic) distance = debugIconsOrthoDistance; int iconsOffset = debugIconsPlacement[StringHash(nodes[i].id)].GetInt(); float iconsYPos = 0; if (iconType == ICON_SPLINE_PATH) { SplinePath@ sp = cast<SplinePath>(component); if (sp !is null) { if (sp.length > 0.01f) { for (int step = 0; step < splinePathResolution; step++) { int index = (i * splinePathResolution) + step; Vector3 splinePoint = sp.GetPoint(splineStep * step); Billboard@ bb = debugIconsSet[ICON_SPLINE_PATH].billboards[index]; float stepDistance = (camPos - splinePoint).length; if (isOrthographic) stepDistance = debugIconsOrthoDistance; if (step == 0) // SplinePath start { bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_BEGIN]; bb.size = debugIconsSize; bb.position = splinePoint; } else if ((step+1) >= (splinePathResolution - splineStep)) // SplinePath end { bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_END]; bb.size = debugIconsSize; bb.position = splinePoint; } else // SplinePath middle points { bb.color = finalIconColor; bb.size = debugIconsSizeSmall; bb.position = splinePoint; } bb.enabled = sp.enabled; // Blend Icon relatively by distance to it bb.color = Color(bb.color.r, bb.color.g, bb.color.b, 1.2f - 1.0f / (maxDistance / stepDistance)); if (bb.color.a < debugIconAlphaThreshold) bb.enabled = false; } } } } else { Billboard@ bb = debugIconsSet[iconType].billboards[i]; if (iconType == ICON_TRIGGER) { RigidBody@ rigidbody = cast<RigidBody>(component); if (rigidbody !is null) { if (rigidbody.trigger == false) continue; } } else if (iconType == ICON_POINT_LIGHT || iconType == ICON_SPOT_LIGHT || iconType == ICON_DIRECTIONAL_LIGHT) { Light@ light = cast<Light>(component); if (light !is null) { if (light.lightType == LIGHT_POINT) bb = debugIconsSet[ICON_POINT_LIGHT].billboards[i]; else if (light.lightType == LIGHT_DIRECTIONAL) bb = debugIconsSet[ICON_DIRECTIONAL_LIGHT].billboards[i]; else if (light.lightType == LIGHT_SPOT) bb = debugIconsSet[ICON_SPOT_LIGHT].billboards[i]; finalIconColor = light.effectiveColor; } } bb.position = nodes[i].worldPosition; bb.size = debugIconsSize; // Blend Icon relatively by distance to it bb.color = Color(finalIconColor.r, finalIconColor.g, finalIconColor.b, 1.2f - 1.0f / (maxDistance / distance)); bb.enabled = component.enabled; // Discard billboard if it almost transparent if (bb.color.a < debugIconAlphaThreshold) bb.enabled = false; IncrementIconPlacement(bb.enabled, nodes[i], 1); } } Commit(iconType, iconType+1); // SplinePath update resolution if (iconType == ICON_SPLINE_PATH) timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath; } } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; } void ClearCommit(int begin, int end, int newLength) { for (int i = begin; i < end; ++i) { BillboardSet@ iconSet = debugIconsSet[i]; iconSet.numBillboards = newLength; for (int j = 0; j < newLength; ++j) { Billboard@ bb = iconSet.billboards[j]; bb.enabled = false; } iconSet.Commit(); } } void Commit(int begin, int end) { for (int i = begin; i < end; ++i) { debugIconsSet[i].Commit(); } } void IncrementIconPlacement(bool componentEnabled, Node@ node, int offset) { if (componentEnabled == true) { int oldPlacement = debugIconsPlacement[StringHash(node.id)].GetInt(); debugIconsPlacement[StringHash(node.id)] = Variant(oldPlacement + offset); } }
Fix behavior of SoundSource debug icons in editor. Closes #1620.
Fix behavior of SoundSource debug icons in editor. Closes #1620.
ActionScript
mit
codemon66/Urho3D,luveti/Urho3D,rokups/Urho3D,eugeneko/Urho3D,kostik1337/Urho3D,henu/Urho3D,weitjong/Urho3D,tommy3/Urho3D,carnalis/Urho3D,SuperWangKai/Urho3D,bacsmar/Urho3D,SirNate0/Urho3D,bacsmar/Urho3D,henu/Urho3D,henu/Urho3D,xiliu98/Urho3D,helingping/Urho3D,carnalis/Urho3D,tommy3/Urho3D,iainmerrick/Urho3D,xiliu98/Urho3D,SirNate0/Urho3D,MeshGeometry/Urho3D,fire/Urho3D-1,abdllhbyrktr/Urho3D,carnalis/Urho3D,299299/Urho3D,rokups/Urho3D,MeshGeometry/Urho3D,orefkov/Urho3D,luveti/Urho3D,weitjong/Urho3D,henu/Urho3D,bacsmar/Urho3D,carnalis/Urho3D,MonkeyFirst/Urho3D,weitjong/Urho3D,MeshGeometry/Urho3D,MeshGeometry/Urho3D,fire/Urho3D-1,iainmerrick/Urho3D,MonkeyFirst/Urho3D,helingping/Urho3D,PredatorMF/Urho3D,SirNate0/Urho3D,abdllhbyrktr/Urho3D,SirNate0/Urho3D,helingping/Urho3D,tommy3/Urho3D,tommy3/Urho3D,eugeneko/Urho3D,kostik1337/Urho3D,299299/Urho3D,orefkov/Urho3D,weitjong/Urho3D,299299/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,abdllhbyrktr/Urho3D,PredatorMF/Urho3D,kostik1337/Urho3D,urho3d/Urho3D,MonkeyFirst/Urho3D,abdllhbyrktr/Urho3D,SuperWangKai/Urho3D,cosmy1/Urho3D,tommy3/Urho3D,codedash64/Urho3D,victorholt/Urho3D,MonkeyFirst/Urho3D,victorholt/Urho3D,urho3d/Urho3D,urho3d/Urho3D,carnalis/Urho3D,codedash64/Urho3D,eugeneko/Urho3D,iainmerrick/Urho3D,bacsmar/Urho3D,rokups/Urho3D,rokups/Urho3D,helingping/Urho3D,SuperWangKai/Urho3D,SuperWangKai/Urho3D,weitjong/Urho3D,SirNate0/Urho3D,c4augustus/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,xiliu98/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,helingping/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,orefkov/Urho3D,henu/Urho3D,urho3d/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,codemon66/Urho3D,cosmy1/Urho3D,kostik1337/Urho3D,luveti/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,c4augustus/Urho3D,cosmy1/Urho3D,eugeneko/Urho3D,c4augustus/Urho3D,299299/Urho3D,codedash64/Urho3D,PredatorMF/Urho3D,cosmy1/Urho3D,rokups/Urho3D,luveti/Urho3D,codemon66/Urho3D,cosmy1/Urho3D,299299/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,codemon66/Urho3D,luveti/Urho3D,xiliu98/Urho3D,victorholt/Urho3D,299299/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,fire/Urho3D-1,codedash64/Urho3D,iainmerrick/Urho3D,codemon66/Urho3D,rokups/Urho3D
6dbeaa00dcd299a9ba6715e2053eabae81b55a43
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/DataGridColumnView.as
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/DataGridColumnView.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import org.apache.flex.core.IStrand; import org.apache.flex.html.supportClasses.DataGridColumn; /** * The DataGridColumnView class extends org.apache.flex.html.beads.ListView and * provides properties to the org.apache.flex.html.List that makes a column in * the org.apache.flex.html.DataGrid. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DataGridColumnView extends ListView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DataGridColumnView() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; _strand = value; } private var _columnIndex:uint; /** * The zero-based index for the column. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get columnIndex():uint { return _columnIndex; } public function set columnIndex(value:uint):void { _columnIndex = value; } private var _column:DataGridColumn; /** * The org.apache.flex.html.support.DataGridColumn containing information used to * present the org.apache.flex.html.List as a column in the * org.apache.flex.html.DataGrid. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get column():DataGridColumn { return _column; } public function set column(value:DataGridColumn):void { _column = value; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import org.apache.flex.core.IStrand; import org.apache.flex.html.supportClasses.DataGridColumn; /** * The DataGridColumnView class extends org.apache.flex.html.beads.ListView and * provides properties to the org.apache.flex.html.List that makes a column in * the org.apache.flex.html.DataGrid. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DataGridColumnView extends ListView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DataGridColumnView() { } /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; } private var _columnIndex:uint; /** * The zero-based index for the column. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get columnIndex():uint { return _columnIndex; } public function set columnIndex(value:uint):void { _columnIndex = value; } private var _column:DataGridColumn; /** * The org.apache.flex.html.support.DataGridColumn containing information used to * present the org.apache.flex.html.List as a column in the * org.apache.flex.html.DataGrid. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get column():DataGridColumn { return _column; } public function set column(value:DataGridColumn):void { _column = value; } } }
fix asdoc. Falcon didn't notice private override of protected var
fix asdoc. Falcon didn't notice private override of protected var
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
2ec5361f1fb1e4a6524418d57c179cbdedd0db63
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
package com.kaltura.kdpfl { import com.kaltura.kdpfl.controller.InitMacroCommand; import com.kaltura.kdpfl.controller.LayoutReadyCommand; import com.kaltura.kdpfl.controller.PlaybackCompleteCommand; import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand; import com.kaltura.kdpfl.controller.SequenceSkipNextCommand; import com.kaltura.kdpfl.controller.StartupCommand; import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand; import com.kaltura.kdpfl.controller.media.LiveStreamCommand; import com.kaltura.kdpfl.controller.media.MediaReadyCommand; import com.kaltura.kdpfl.events.DynamicEvent; import com.kaltura.kdpfl.model.ExternalInterfaceProxy; import com.kaltura.kdpfl.model.type.DebugLevel; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.controls.KTrace; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import com.kaltura.puremvc.as3.core.KView; import flash.display.DisplayObject; import mx.utils.ObjectProxy; import org.osmf.media.MediaPlayerState; import org.puremvc.as3.interfaces.IFacade; import org.puremvc.as3.interfaces.IMediator; import org.puremvc.as3.interfaces.IProxy; import org.puremvc.as3.patterns.facade.Facade; public class ApplicationFacade extends Facade implements IFacade { /** * The current version of the KDP. */ public var kdpVersion : String = "v3.6.14"; /** * save any mediator name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _mediatorNameArray : Array = new Array(); /** * save any proxy name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _proxyNameArray : Array = new Array(); /** * save any notification that create a command name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _commandNameArray : Array = new Array(); /** * The bindObject create dynamicly all attributes that need to be binded on it */ public var bindObject:ObjectProxy = new ObjectProxy(); /** * a reference to KDP3 main application */ private var _app : DisplayObject; /** * the url of the kdp */ public var appFolder : String; public var debugMode : Boolean = false; /** * * will affect the traces that will be sent. See DebugLevel enum */ public var debugLevel:int; private var externalInterface : ExternalInterfaceProxy; /** * return the one and only instance of the ApplicationFacade, * if not exist it will be created. * @return * */ public static function getInstance() : ApplicationFacade { if (instance == null) instance = new ApplicationFacade(); return instance as ApplicationFacade; } /** * All this simply does is fire a notification which is routed to * "StartupCommand" via the "registerCommand" handlers * @param app * */ public function start(app:DisplayObject):void { _app = app; appFolder = app.root.loaderInfo.url; appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1); sendNotification(NotificationType.STARTUP, app); externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy; } /** * Created to trace all notifications for debug * @param notificationName * @param body * @param type * */ override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void { if (debugMode) { var s:String; if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) || (notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) || (notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE)) { if (notificationName == NotificationType.PLAYER_STATE_CHANGE) s = 'Sent ' + notificationName + ' ==> ' + body.toString(); else { s = 'Sent ' + notificationName; if (body) { var found:Boolean = false; for (var o:* in body) { s += ", " + o + ":" + body[o]; found = true; } if (!found) { s += ", " + body.toString(); } } } } if (s && s != "null") { var curTime:Number = 0; var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator; if (kmediaPlayerMediator && kmediaPlayerMediator.player && kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING && kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED && kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR) { curTime = kmediaPlayerMediator.player.currentTime; } var date:Date = new Date(); KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime); } } super.sendNotification(notificationName, body, type); //For external Flash/Flex application application listening to the KDP events _app.dispatchEvent(new DynamicEvent(notificationName, body)); //For external Javascript application listening to the KDP events if (externalInterface) externalInterface.notifyJs(notificationName, body); } /** * controls the routing of notifications to our controllers, * we all know them as commands * */ override protected function initializeController():void { super.initializeController(); registerCommand(NotificationType.STARTUP, StartupCommand); // we do both init start KDP life cycle, and start to load the entry simultaneously registerCommand(NotificationType.INITIATE_APP, InitMacroCommand); //There are several things that need to be done as soon as the layout of the kdp is ready. registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand ); //when one call change media we fire the load media command again registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand); registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand ); registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand ); registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand); registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand); registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand); } override protected function initializeView():void { if ( view != null ) return; view = KView.getInstance(); } override protected function initializeFacade():void { initializeView(); initializeModel(); initializeController(); } /** * Help to remove all commands, mediator, proxies from the facade * */ public function dispose() : void { var i:int =0; for(i=0; i<_commandNameArray.length; i++) this.removeCommand( _commandNameArray[i] ); for(i=0; i<_mediatorNameArray.length; i++) this.removeMediator( _mediatorNameArray[i] ); for(i=0; i<_proxyNameArray.length; i++) this.removeProxy( _proxyNameArray[i] ); _commandNameArray = new Array(); _mediatorNameArray = new Array(); _proxyNameArray = new Array(); } /** * after registartion add the notification name to a * @param notificationName * @param commandClassRef * */ override public function registerCommand(notificationName:String, commandClassRef:Class):void { super.registerCommand(notificationName, commandClassRef); //save the notification name so we can delete it later _commandNameArray.push( notificationName ); } override public function registerMediator(mediator:IMediator):void { super.registerMediator(mediator); //save the mediator name so we can delete it later _mediatorNameArray.push( mediator.getMediatorName() ); } override public function registerProxy(proxy:IProxy):void { bindObject[proxy.getProxyName()] = proxy.getData(); super.registerProxy(proxy); //save the proxy name so we can delete it later _proxyNameArray.push( proxy.getProxyName() ); } /** * add notification observer for a given mediator * @param notification the notification to listen for * @param notificationHandler handler to be called * @param mediator * */ public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void { (view as KView).addNotificationInterest(notification, notificationHandler, mediator); } public function get app () : DisplayObject { return _app; } public function set app (disObj : DisplayObject) : void { _app = disObj; } } }
package com.kaltura.kdpfl { import com.kaltura.kdpfl.controller.InitMacroCommand; import com.kaltura.kdpfl.controller.LayoutReadyCommand; import com.kaltura.kdpfl.controller.PlaybackCompleteCommand; import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand; import com.kaltura.kdpfl.controller.SequenceSkipNextCommand; import com.kaltura.kdpfl.controller.StartupCommand; import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand; import com.kaltura.kdpfl.controller.media.LiveStreamCommand; import com.kaltura.kdpfl.controller.media.MediaReadyCommand; import com.kaltura.kdpfl.events.DynamicEvent; import com.kaltura.kdpfl.model.ExternalInterfaceProxy; import com.kaltura.kdpfl.model.type.DebugLevel; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.controls.KTrace; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import com.kaltura.puremvc.as3.core.KView; import flash.display.DisplayObject; import mx.utils.ObjectProxy; import org.osmf.media.MediaPlayerState; import org.puremvc.as3.interfaces.IFacade; import org.puremvc.as3.interfaces.IMediator; import org.puremvc.as3.interfaces.IProxy; import org.puremvc.as3.patterns.facade.Facade; public class ApplicationFacade extends Facade implements IFacade { /** * The current version of the KDP. */ public var kdpVersion : String = "v3.6.14"; /** * save any mediator name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _mediatorNameArray : Array = new Array(); /** * save any proxy name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _proxyNameArray : Array = new Array(); /** * save any notification that create a command name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _commandNameArray : Array = new Array(); /** * The bindObject create dynamicly all attributes that need to be binded on it */ public var bindObject:ObjectProxy = new ObjectProxy(); /** * a reference to KDP3 main application */ private var _app : DisplayObject; /** * the url of the kdp */ public var appFolder : String; public var debugMode : Boolean = false; /** * * will affect the traces that will be sent. See DebugLevel enum */ public var debugLevel:int; private var externalInterface : ExternalInterfaceProxy; /** * return the one and only instance of the ApplicationFacade, * if not exist it will be created. * @return * */ public static function getInstance() : ApplicationFacade { if (instance == null) instance = new ApplicationFacade(); return instance as ApplicationFacade; } /** * All this simply does is fire a notification which is routed to * "StartupCommand" via the "registerCommand" handlers * @param app * */ public function start(app:DisplayObject):void { CONFIG::isSDK46 { kdpVersion += ".sdk46"; } _app = app; appFolder = app.root.loaderInfo.url; appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1); sendNotification(NotificationType.STARTUP, app); externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy; } /** * Created to trace all notifications for debug * @param notificationName * @param body * @param type * */ override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void { if (debugMode) { var s:String; if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) || (notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) || (notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE)) { if (notificationName == NotificationType.PLAYER_STATE_CHANGE) s = 'Sent ' + notificationName + ' ==> ' + body.toString(); else { s = 'Sent ' + notificationName; if (body) { var found:Boolean = false; for (var o:* in body) { s += ", " + o + ":" + body[o]; found = true; } if (!found) { s += ", " + body.toString(); } } } } if (s && s != "null") { var curTime:Number = 0; var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator; if (kmediaPlayerMediator && kmediaPlayerMediator.player && kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING && kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED && kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR) { curTime = kmediaPlayerMediator.player.currentTime; } var date:Date = new Date(); KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime); } } super.sendNotification(notificationName, body, type); //For external Flash/Flex application application listening to the KDP events _app.dispatchEvent(new DynamicEvent(notificationName, body)); //For external Javascript application listening to the KDP events if (externalInterface) externalInterface.notifyJs(notificationName, body); } /** * controls the routing of notifications to our controllers, * we all know them as commands * */ override protected function initializeController():void { super.initializeController(); registerCommand(NotificationType.STARTUP, StartupCommand); // we do both init start KDP life cycle, and start to load the entry simultaneously registerCommand(NotificationType.INITIATE_APP, InitMacroCommand); //There are several things that need to be done as soon as the layout of the kdp is ready. registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand ); //when one call change media we fire the load media command again registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand); registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand ); registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand ); registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand); registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand); registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand); } override protected function initializeView():void { if ( view != null ) return; view = KView.getInstance(); } override protected function initializeFacade():void { initializeView(); initializeModel(); initializeController(); } /** * Help to remove all commands, mediator, proxies from the facade * */ public function dispose() : void { var i:int =0; for(i=0; i<_commandNameArray.length; i++) this.removeCommand( _commandNameArray[i] ); for(i=0; i<_mediatorNameArray.length; i++) this.removeMediator( _mediatorNameArray[i] ); for(i=0; i<_proxyNameArray.length; i++) this.removeProxy( _proxyNameArray[i] ); _commandNameArray = new Array(); _mediatorNameArray = new Array(); _proxyNameArray = new Array(); } /** * after registartion add the notification name to a * @param notificationName * @param commandClassRef * */ override public function registerCommand(notificationName:String, commandClassRef:Class):void { super.registerCommand(notificationName, commandClassRef); //save the notification name so we can delete it later _commandNameArray.push( notificationName ); } override public function registerMediator(mediator:IMediator):void { super.registerMediator(mediator); //save the mediator name so we can delete it later _mediatorNameArray.push( mediator.getMediatorName() ); } override public function registerProxy(proxy:IProxy):void { bindObject[proxy.getProxyName()] = proxy.getData(); super.registerProxy(proxy); //save the proxy name so we can delete it later _proxyNameArray.push( proxy.getProxyName() ); } /** * add notification observer for a given mediator * @param notification the notification to listen for * @param notificationHandler handler to be called * @param mediator * */ public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void { (view as KView).addNotificationInterest(notification, notificationHandler, mediator); } public function get app () : DisplayObject { return _app; } public function set app (disObj : DisplayObject) : void { _app = disObj; } } }
add ".sdk46" to sdk 4.6 client tag
qnd: add ".sdk46" to sdk 4.6 client tag git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@91631 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
kaltura/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp
ef4684a70650066c7b061a3f2fac260cbd7e1535
WeaveJS/src/weavejs/data/source/SpatialJoinTransform.as
WeaveJS/src/weavejs/data/source/SpatialJoinTransform.as
package weavejs.data.source { import weavejs.WeaveAPI; import weavejs.api.data.ColumnMetadata; import weavejs.api.data.IDataSource; import weavejs.api.data.IQualifiedKey; import weavejs.api.data.ISelectableAttributes; import weavejs.core.LinkableString; import weavejs.data.ColumnUtils; import weavejs.data.column.DynamicColumn; import weavejs.data.column.ProxyColumn; import weavejs.data.column.StringColumn; import weavejs.util.ArrayUtils; import weavejs.util.JS; import weavejs.util.StandardLib; public class SpatialJoinTransform extends AbstractDataSource implements ISelectableAttributes { WeaveAPI.ClassRegistry.registerImplementation(IDataSource, SpatialJoinTransform, "Spatial Join Transform"); public const geometryColumn:DynamicColumn = Weave.linkableChild(this, DynamicColumn); public const xColumn:DynamicColumn = Weave.linkableChild(this, DynamicColumn); public const yColumn:DynamicColumn = Weave.linkableChild(this, DynamicColumn); public const pointProjection:LinkableString = Weave.linkableChild(this, LinkableString); private var _source:Object; /* This is a ol.source.Vector */ private var _parser:Object; /* This is an ol.format.GeoJSON */ /* Output dataType is determined by the geometryColumn input. */ /* Output keyType is determined by the xColumn/yColumn input. */ public function get selectableAttributes():/*/Map<string, (weavejs.api.data.IColumnWrapper|weavejs.api.core.ILinkableHashMap)>/*/Object { return new JS.Map() .set("Join Geometry", geometryColumn) .set("Datapoint X", xColumn) .set("Datapoint Y", yColumn); } public function SpatialJoinTransform() { _source = new StandardLib.ol.source.Vector() _parser = new StandardLib.ol.format.GeoJSON(); } override protected function initialize(forceRefresh:Boolean = false):void { super.initialize(true); } override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void { var metadata:Object = proxyColumn.getProxyMetadata(); var geomKeys:Array = geometryColumn.keys; var rawGeometries:Array = weavejs.data.ColumnUtils.getGeoJsonGeometries(geometryColumn, geometryColumn.keys); var key:IQualifiedKey; var feature:*; _source.clear(); for (var idx:int = 0; idx < geomKeys.length; idx++) { var rawGeom:* = rawGeometries[idx]; key = geomKeys[idx] as IQualifiedKey; var geometry:* = _parser.readGeometry(rawGeom, { dataProjection: StandardLib.ol.proj.get(geometryColumn.getMetadata(ColumnMetadata.PROJECTION)), featureProjection: StandardLib.ol.proj.get(pointProjection.value) } ); if (geometry.getExtent().some(StandardLib.lodash.isNaN)) { JS.error("Dropping feature", key, "due to containing NaN coordinates. Possibly misconfigured projection?"); continue; } feature = new StandardLib.ol.Feature({id: key, geometry: geometry}); _source.addFeature(feature); } var keys:Array = []; var data:Array = []; for each (key in ArrayUtils.union(xColumn.keys, yColumn.keys)) { var x:Number = xColumn.getValueFromKey(key, Number); var y:Number = yColumn.getValueFromKey(key, Number); var features:Array = _source.getFeaturesAtCoordinate([x,y]); for each (feature in features) { var featureKey:* = feature.getId(); keys.push(key); data.push(featureKey.localName); } } var column:StringColumn = new StringColumn(); column.setRecords(keys, data); proxyColumn.setInternalColumn(column); } } }
package weavejs.data.source { import weavejs.WeaveAPI; import weavejs.api.data.ColumnMetadata; import weavejs.api.data.IDataSource; import weavejs.api.data.IQualifiedKey; import weavejs.api.data.ISelectableAttributes; import weavejs.api.data.IWeaveTreeNode; import weavejs.core.LinkableString; import weavejs.data.ColumnUtils; import weavejs.data.column.DynamicColumn; import weavejs.data.column.ProxyColumn; import weavejs.data.column.StringColumn; import weavejs.data.hierarchy.ColumnTreeNode; import weavejs.util.ArrayUtils; import weavejs.util.JS; import weavejs.util.StandardLib; public class SpatialJoinTransform extends AbstractDataSource implements ISelectableAttributes { WeaveAPI.ClassRegistry.registerImplementation(IDataSource, SpatialJoinTransform, "Spatial Join Transform"); public const geometryColumn:DynamicColumn = Weave.linkableChild(this, DynamicColumn); public const xColumn:DynamicColumn = Weave.linkableChild(this, DynamicColumn); public const yColumn:DynamicColumn = Weave.linkableChild(this, DynamicColumn); public const pointProjection:LinkableString = Weave.linkableChild(this, LinkableString); private var _source:Object; /* This is a ol.source.Vector */ private var _parser:Object; /* This is an ol.format.GeoJSON */ /* Output dataType is determined by the geometryColumn input. */ /* Output keyType is determined by the xColumn/yColumn input. */ public function get selectableAttributes():/*/Map<string, (weavejs.api.data.IColumnWrapper|weavejs.api.core.ILinkableHashMap)>/*/Object { return new JS.Map() .set("Join Geometry", geometryColumn) .set("Datapoint X", xColumn) .set("Datapoint Y", yColumn); } public function SpatialJoinTransform() { _source = new StandardLib.ol.source.Vector(); _parser = new StandardLib.ol.format.GeoJSON(); } override protected function initialize(forceRefresh:Boolean = false):void { super.initialize(true); } override public function getHierarchyRoot():IWeaveTreeNode { if (!_rootNode) { _rootNode = new ColumnTreeNode({ dataSource: this, data: this, label: getLabel, hasChildBranches: false, children: [ generateHierarchyNode({}) ] }); } return _rootNode; } override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode { metadata[ColumnMetadata.TITLE] = ColumnUtils.getTitle(this.geometryColumn) metadata[ColumnMetadata.KEY_TYPE] = this.xColumn.getMetadata(ColumnMetadata.KEY_TYPE); metadata[ColumnMetadata.DATA_TYPE] = this.geometryColumn.getMetadata(ColumnMetadata.KEY_TYPE); return new ColumnTreeNode({ dataSource: this, idFields: [], data: metadata }); } override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void { var metadata:Object = proxyColumn.getProxyMetadata(); var geomKeys:Array = geometryColumn.keys; var rawGeometries:Array = weavejs.data.ColumnUtils.getGeoJsonGeometries(geometryColumn, geometryColumn.keys); var key:IQualifiedKey; var feature:*; _source.clear(); for (var idx:int = 0; idx < geomKeys.length; idx++) { var rawGeom:* = rawGeometries[idx]; key = geomKeys[idx] as IQualifiedKey; var geometry:* = _parser.readGeometry(rawGeom, { dataProjection: StandardLib.ol.proj.get(geometryColumn.getMetadata(ColumnMetadata.PROJECTION)), featureProjection: StandardLib.ol.proj.get(pointProjection.value) } ); if (geometry.getExtent().some(StandardLib.lodash.isNaN)) { JS.error("Dropping feature", key, "due to containing NaN coordinates. Possibly misconfigured projection?"); continue; } feature = new StandardLib.ol.Feature(geometry); feature.setId(key); _source.addFeature(feature); } var keys:Array = []; var data:Array = []; for each (key in ArrayUtils.union(xColumn.keys, yColumn.keys)) { var x:Number = xColumn.getValueFromKey(key, Number); var y:Number = yColumn.getValueFromKey(key, Number); var features:Array = _source.getFeaturesAtCoordinate([x,y]); for each (feature in features) { var featureKey:* = feature.getId(); keys.push(key); data.push(featureKey.localName); } } var column:StringColumn = new StringColumn(metadata); column.setRecords(keys, data); proxyColumn.setInternalColumn(column); } } }
Add hierarchy generation to SpatialJoinTransform
Add hierarchy generation to SpatialJoinTransform
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
be68f9f7e0846c143b50438432e377a12a77843a
src/as/com/threerings/ezgame/client/EZGameConfigurator.as
src/as/com/threerings/ezgame/client/EZGameConfigurator.as
// // $Id$ // // Vilya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/vilya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.ezgame.client { import mx.core.UIComponent; import mx.controls.CheckBox; import mx.controls.ComboBox; import mx.controls.HSlider; import mx.controls.Label; import com.threerings.util.StreamableHashMap; import com.threerings.util.StringUtil; import com.threerings.flex.LabeledSlider; import com.threerings.parlor.game.client.FlexGameConfigurator; import com.threerings.ezgame.data.ChoiceParameter; import com.threerings.ezgame.data.EZGameConfig; import com.threerings.ezgame.data.Parameter; import com.threerings.ezgame.data.RangeParameter; import com.threerings.ezgame.data.ToggleParameter; /** * Adds custom configuration of options specified in XML. */ public class EZGameConfigurator extends FlexGameConfigurator { // from GameConfigurator override protected function gotGameConfig () :void { super.gotGameConfig(); var params :Array = (_config as EZGameConfig).getGameDefinition().params; if (params == null) { return; } for each (var param :Parameter in params) { if (param is RangeParameter) { var range :RangeParameter = (param as RangeParameter); var slider :HSlider = new HSlider(); slider.minimum = range.minimum; slider.maximum = range.maximum; slider.value = range.start; slider.liveDragging = true; slider.snapInterval = 1; addLabeledControl(param, new LabeledSlider(slider)); } else if (param is ChoiceParameter) { var choice :ChoiceParameter = (param as ChoiceParameter); var startDex :int = choice.choices.indexOf(choice.start); if (startDex == -1) { Log.getLog(this).warning( "Start value does not appear in list of choices [param=" + choice + "]."); } else { var combo :ComboBox = new ComboBox(); combo.dataProvider = choice.choices; combo.selectedIndex = startDex; addLabeledControl(param, combo); } } else if (param is ToggleParameter) { var check :CheckBox = new CheckBox(); check.selected = (param as ToggleParameter).start; addLabeledControl(param, check); } else { Log.getLog(this).warning("Unknown parameter in config [param=" + param + "]."); } } } override protected function flushGameConfig () :void { super.flushGameConfig(); // if there were any custom XML configs, flush those as well. if (_customConfigs.length > 0) { var params :StreamableHashMap = new StreamableHashMap(); for (var ii :int = 0; ii < _customConfigs.length; ii += 2) { var ident :String = String(_customConfigs[ii]); var control :UIComponent = (_customConfigs[ii + 1] as UIComponent); if (control is LabeledSlider) { params.put(ident, (control as LabeledSlider).slider.value); } else if (control is CheckBox) { params.put(ident, (control as CheckBox).selected); } else if (control is ComboBox) { params.put(ident, (control as ComboBox).value); } else { Log.getLog(this).warning("Unknow custom config type " + control); } } (_config as EZGameConfig).params = params; } } /** * Add a control that came from parsing our custom option XML. */ protected function addLabeledControl (param :Parameter, control :UIComponent) :void { if (StringUtil.isBlank(param.name)) { param.name = param.ident; } var lbl :Label = new Label(); lbl.text = param.name + ":"; lbl.styleName = "lobbyLabel"; lbl.toolTip = param.tip; control.toolTip = param.tip; addControl(lbl, control); _customConfigs.push(param.ident, control); } /** Contains pairs of identString, control, identString, control.. */ protected var _customConfigs :Array = []; } }
// // $Id$ // // Vilya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/vilya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.ezgame.client { import mx.core.UIComponent; import mx.controls.CheckBox; import mx.controls.ComboBox; import mx.controls.HSlider; import mx.controls.Label; import com.threerings.util.Integer; import com.threerings.util.StreamableHashMap; import com.threerings.util.StringUtil; import com.threerings.flex.LabeledSlider; import com.threerings.parlor.game.client.FlexGameConfigurator; import com.threerings.ezgame.data.ChoiceParameter; import com.threerings.ezgame.data.EZGameConfig; import com.threerings.ezgame.data.Parameter; import com.threerings.ezgame.data.RangeParameter; import com.threerings.ezgame.data.ToggleParameter; /** * Adds custom configuration of options specified in XML. */ public class EZGameConfigurator extends FlexGameConfigurator { // from GameConfigurator override protected function gotGameConfig () :void { super.gotGameConfig(); var params :Array = (_config as EZGameConfig).getGameDefinition().params; if (params == null) { return; } for each (var param :Parameter in params) { if (param is RangeParameter) { var range :RangeParameter = (param as RangeParameter); var slider :HSlider = new HSlider(); slider.minimum = range.minimum; slider.maximum = range.maximum; slider.value = range.start; slider.liveDragging = true; slider.snapInterval = 1; addLabeledControl(param, new LabeledSlider(slider)); } else if (param is ChoiceParameter) { var choice :ChoiceParameter = (param as ChoiceParameter); var startDex :int = choice.choices.indexOf(choice.start); if (startDex == -1) { Log.getLog(this).warning( "Start value does not appear in list of choices [param=" + choice + "]."); } else { var combo :ComboBox = new ComboBox(); combo.dataProvider = choice.choices; combo.selectedIndex = startDex; addLabeledControl(param, combo); } } else if (param is ToggleParameter) { var check :CheckBox = new CheckBox(); check.selected = (param as ToggleParameter).start; addLabeledControl(param, check); } else { Log.getLog(this).warning("Unknown parameter in config [param=" + param + "]."); } } } override protected function flushGameConfig () :void { super.flushGameConfig(); // if there were any custom XML configs, flush those as well. if (_customConfigs.length > 0) { var params :StreamableHashMap = new StreamableHashMap(); for (var ii :int = 0; ii < _customConfigs.length; ii += 2) { var ident :String = String(_customConfigs[ii]); var control :UIComponent = (_customConfigs[ii + 1] as UIComponent); if (control is LabeledSlider) { params.put(ident, new Integer((control as LabeledSlider).slider.value)); } else if (control is CheckBox) { params.put(ident, (control as CheckBox).selected); } else if (control is ComboBox) { params.put(ident, (control as ComboBox).value); } else { Log.getLog(this).warning("Unknow custom config type " + control); } } (_config as EZGameConfig).params = params; } } /** * Add a control that came from parsing our custom option XML. */ protected function addLabeledControl (param :Parameter, control :UIComponent) :void { if (StringUtil.isBlank(param.name)) { param.name = param.ident; } var lbl :Label = new Label(); lbl.text = param.name + ":"; lbl.styleName = "lobbyLabel"; lbl.toolTip = param.tip; control.toolTip = param.tip; addControl(lbl, control); _customConfigs.push(param.ident, control); } /** Contains pairs of identString, control, identString, control.. */ protected var _customConfigs :Array = []; } }
Use an Integer here so that we play nicely with Java managers.
Use an Integer here so that we play nicely with Java managers. git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@289 c613c5cb-e716-0410-b11b-feb51c14d237
ActionScript
lgpl-2.1
threerings/vilya,threerings/vilya
7c4fbc332a1c20ed162df213f74cb0b2c268d9ad
src/aerys/minko/render/shader/node/leaf/AbstractLeaf.as
src/aerys/minko/render/shader/node/leaf/AbstractLeaf.as
package aerys.minko.render.shader.node.leaf { import aerys.minko.render.shader.compiler.visitor.IShaderNodeVisitor; import aerys.minko.render.shader.node.INode; import flash.utils.getQualifiedClassName; public class AbstractLeaf implements INode { public function get name() : String { return getQualifiedClassName(this); } public function get size() : uint { throw new Error('Must be overriden'); } public function AbstractLeaf() { } public function accept(v : IShaderNodeVisitor) : void { } public function isSame(node : INode) : Boolean { throw new Error('Must be overriden'); } public function toString() : String { return name; } } }
package aerys.minko.render.shader.node.leaf { import aerys.minko.render.shader.compiler.visitor.IShaderNodeVisitor; import aerys.minko.render.shader.node.INode; import flash.utils.getQualifiedClassName; public class AbstractLeaf implements INode { public function get name() : String { var className : String = getQualifiedClassName(this); return className.substr(className.lastIndexOf(":") + 1); } public function get size() : uint { throw new Error('Must be overriden'); } public function AbstractLeaf() { } public function accept(v : IShaderNodeVisitor) : void { } public function isSame(node : INode) : Boolean { throw new Error('Must be overriden'); } public function toString() : String { return name; } } }
Remove the package name from the name getter in AbstractLeaf
Remove the package name from the name getter in AbstractLeaf
ActionScript
mit
aerys/minko-as3
6d4521d9afc382fda800c002f541610dc353b328
frameworks/projects/CreateJS/src/main/flex/org/apache/flex/createjs/Application.as
frameworks/projects/CreateJS/src/main/flex/org/apache/flex/createjs/Application.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.createjs { import org.apache.flex.core.ApplicationBase; import org.apache.flex.core.IApplicationView; import org.apache.flex.core.IParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.IValuesImpl; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.utils.MXMLDataInterpreter; COMPILE::JS { import org.apache.flex.core.WrappedHTMLElement; import createjs.DisplayObject; import createjs.Stage; } //-------------------------------------- // Events //-------------------------------------- /** * Dispatched at startup. Attributes and sub-instances of * the MXML document have been created and assigned. * The component lifecycle is different * than the Flex SDK. There is no creationComplete event. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="initialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup before the instances get created. * Beads can call preventDefault and defer initialization. * This event will be dispatched on every frame until no * listeners call preventDefault(), then the initialize() * method will be called. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="preinitialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. This event is sent before * applicationComplete is dispatched. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="viewChanged", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="applicationComplete", type="org.apache.flex.events.Event")] /** * The Application class is the main class and entry point for a FlexJS * application. This Application class is different than the * Flex SDK's mx:Application or spark:Application in that it does not contain * user interface elements. Those UI elements go in the views (ViewBase). This * Application class expects there to be a main model, a controller, and * an initial view. * * This is the CreateJS Application class which must be used in place of the normal * FlexJS Application. CreateJS uses the HTML5 &lt;canvas&gt;, rather than the HTML DOM. This * class sets up the canvas and injects the necessary HTML elements into the index.html * file to bootstrap CreateJS. * * @see ViewBase * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ COMPILE::SWF public class Application extends org.apache.flex.core.Application { // does nothing different for SWF side } COMPILE::JS public class Application extends ApplicationBase implements IStrand, IParent, IEventDispatcher { /** * FalconJX will inject html into the index.html file. Surround with * "inject_html" tag as follows: * * <inject_html> * <script src="https://code.createjs.com/easeljs-0.8.1.min.js"></script> * <script src="https://code.createjs.com/tweenjs-0.6.2.min.js"></script> * </inject_html> */ public function Application() { super(); } private var stage:Stage; /** * @private * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement * @flexjsignorecoercion HTMLBodyElement * @flexjsignorecoercion HTMLCanvasElement * @flexjsignorecoercion createjs.Stage */ public function start():void { var body:HTMLBodyElement; var canvas:HTMLCanvasElement; // For createjs, the application is the same as the canvas // and it provides convenient access to the stage. element = document.createElement('canvas') as WrappedHTMLElement; element.flexjs_wrapper = this; canvas = element as HTMLCanvasElement; canvas.id = 'flexjsCanvas'; canvas.width = 700; canvas.height = 500; body = document.getElementsByTagName('body')[0] as HTMLBodyElement; body.appendChild(this.element); stage = new createjs.Stage('flexjsCanvas'); MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor); dispatchEvent('initialize'); for (var index:int in beads) { addBead(beads[index]); } dispatchEvent(new org.apache.flex.events.Event("beadsAdded")); initialView.applicationModel = this.model; addElement(initialView); dispatchEvent('viewChanged'); stage.update(); dispatchEvent('applicationComplete'); } /** * The org.apache.flex.core.IValuesImpl that will * determine the default values and other values * for the application. The most common choice * is org.apache.flex.core.SimpleCSSValuesImpl. * * @see org.apache.flex.core.SimpleCSSValuesImpl * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set valuesImpl(value:IValuesImpl):void { ValuesManager.valuesImpl = value; ValuesManager.valuesImpl.init(this); } /** * The initial view. * * @see org.apache.flex.core.ViewBase * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Bindable("__NoChangeEvent__")] public var initialView:IApplicationView; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Bindable("__NoChangeEvent__")] private var _model:Object; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Bindable("__NoChangeEvent__")] override public function get model():Object { return _model; } /** * @private */ [Bindable("__NoChangeEvent__")] override public function set model(value:Object):void { _model = value; } /** * The controller. The controller typically watches * the UI for events and updates the model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var controller:Object; /** * An array of data that describes the MXML attributes * and tags in an MXML document. This data is usually * decoded by an MXMLDataInterpreter * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get MXMLDescriptor():Array { return null; } /** * An method called by the compiler's generated * code to kick off the setting of MXML attribute * values and instantiation of child tags. * * The call has to be made in the generated code * in order to ensure that the constructors have * completed first. * * @param data The encoded data representing the * MXML attributes. * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateMXMLAttributes(data:Array):void { MXMLDataInterpreter.generateMXMLProperties(this, data); } /** * The array property that is used to add additional * beads to an MXML tag. From ActionScript, just * call addBead directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var beads:Array; /** * @copy org.apache.flex.core.IParent#addElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion createjs.DisplayObject */ public function addElement(c:Object, dispatchEvent:Boolean = true):void { stage.addChild(c.element as DisplayObject); c.addedToParent(); } /** * @copy org.apache.flex.core.IParent#addElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion createjs.DisplayObject */ public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void { stage.addChildAt(c.element as DisplayObject, index); c.addedToParent(); } /** * @copy org.apache.flex.core.IParent#getElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement */ public function getElementAt(index:int):Object { var c:WrappedHTMLElement = stage.getChildAt(index) as WrappedHTMLElement; return c.flexjs_wrapper; } /** * @copy org.apache.flex.core.IParent#getElementIndex() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion createjs.DisplayObject */ public function getElementIndex(c:Object):int { return stage.getChildIndex(c.element as DisplayObject) } /** * @copy org.apache.flex.core.IParent#removeElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeElement(c:Object, dispatchEvent:Boolean = true):void { stage.removeChild(c.element as DisplayObject); } /** * @copy org.apache.flex.core.IParent#numElements * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get numElements():int { return stage.numChildren(); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.createjs { import org.apache.flex.core.ApplicationBase; import org.apache.flex.core.IApplicationView; import org.apache.flex.core.IParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.IValuesImpl; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.utils.MXMLDataInterpreter; COMPILE::JS { import org.apache.flex.core.WrappedHTMLElement; import createjs.DisplayObject; import createjs.Stage; } //-------------------------------------- // Events //-------------------------------------- /** * Dispatched at startup. Attributes and sub-instances of * the MXML document have been created and assigned. * The component lifecycle is different * than the Flex SDK. There is no creationComplete event. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="initialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup before the instances get created. * Beads can call preventDefault and defer initialization. * This event will be dispatched on every frame until no * listeners call preventDefault(), then the initialize() * method will be called. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="preinitialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. This event is sent before * applicationComplete is dispatched. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="viewChanged", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="applicationComplete", type="org.apache.flex.events.Event")] /** * The Application class is the main class and entry point for a FlexJS * application. This Application class is different than the * Flex SDK's mx:Application or spark:Application in that it does not contain * user interface elements. Those UI elements go in the views (ViewBase). This * Application class expects there to be a main model, a controller, and * an initial view. * * This is the CreateJS Application class which must be used in place of the normal * FlexJS Application. CreateJS uses the HTML5 &lt;canvas&gt;, rather than the HTML DOM. This * class sets up the canvas and injects the necessary HTML elements into the index.html * file to bootstrap CreateJS. * * @see ViewBase * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ COMPILE::SWF public class Application extends org.apache.flex.core.Application { // does nothing different for SWF side } COMPILE::JS public class Application extends ApplicationBase implements IStrand, IParent, IEventDispatcher { /** * FalconJX will inject html into the index.html file. Surround with * "inject_html" tag as follows: * * <inject_html> * <script src="https://code.createjs.com/easeljs-0.8.1.min.js"></script> * <script src="https://code.createjs.com/tweenjs-0.6.2.min.js"></script> * </inject_html> */ public function Application() { super(); } private var stage:Stage; /** * @private * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement * @flexjsignorecoercion HTMLBodyElement * @flexjsignorecoercion HTMLCanvasElement * @flexjsignorecoercion createjs.Stage */ public function start():void { var body:HTMLBodyElement; var canvas:HTMLCanvasElement; // For createjs, the application is the same as the canvas // and it provides convenient access to the stage. element = document.createElement('canvas') as WrappedHTMLElement; element.flexjs_wrapper = this; canvas = element as HTMLCanvasElement; canvas.id = 'flexjsCanvas'; canvas.width = 700; canvas.height = 500; body = document.getElementsByTagName('body')[0] as HTMLBodyElement; body.appendChild(this.element); stage = new createjs.Stage('flexjsCanvas'); MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor); dispatchEvent('initialize'); for (var index:int in beads) { addBead(beads[index]); } dispatchEvent(new org.apache.flex.events.Event("beadsAdded")); initialView.applicationModel = this.model; addElement(initialView); dispatchEvent('viewChanged'); stage.update(); dispatchEvent('applicationComplete'); } /** * The org.apache.flex.core.IValuesImpl that will * determine the default values and other values * for the application. The most common choice * is org.apache.flex.core.SimpleCSSValuesImpl. * * @see org.apache.flex.core.SimpleCSSValuesImpl * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set valuesImpl(value:IValuesImpl):void { ValuesManager.valuesImpl = value; ValuesManager.valuesImpl.init(this); } /** * The initial view. * * @see org.apache.flex.core.ViewBase * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Bindable("__NoChangeEvent__")] public var initialView:IApplicationView; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Bindable("__NoChangeEvent__")] private var _model:Object; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Bindable("__NoChangeEvent__")] override public function get model():Object { return _model; } /** * @private */ [Bindable("__NoChangeEvent__")] override public function set model(value:Object):void { _model = value; } /** * The controller. The controller typically watches * the UI for events and updates the model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var controller:Object; /** * An array of data that describes the MXML attributes * and tags in an MXML document. This data is usually * decoded by an MXMLDataInterpreter * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get MXMLDescriptor():Array { return null; } /** * An method called by the compiler's generated * code to kick off the setting of MXML attribute * values and instantiation of child tags. * * The call has to be made in the generated code * in order to ensure that the constructors have * completed first. * * @param data The encoded data representing the * MXML attributes. * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateMXMLAttributes(data:Array):void { MXMLDataInterpreter.generateMXMLProperties(this, data); } /** * The array property that is used to add additional * beads to an MXML tag. From ActionScript, just * call addBead directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var beads:Array; /** * @copy org.apache.flex.core.IParent#addElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion createjs.DisplayObject */ public function addElement(c:Object, dispatchEvent:Boolean = true):void { stage.addChild(c.element as DisplayObject); c.addedToParent(); } /** * @copy org.apache.flex.core.IParent#addElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion createjs.DisplayObject */ public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void { stage.addChildAt(c.element as DisplayObject, index); c.addedToParent(); } /** * @copy org.apache.flex.core.IParent#getElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement */ public function getElementAt(index:int):Object { var c:WrappedHTMLElement = stage.getChildAt(index) as WrappedHTMLElement; return c.flexjs_wrapper; } /** * @copy org.apache.flex.core.IParent#getElementIndex() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 * @flexjsignorecoercion createjs.DisplayObject */ public function getElementIndex(c:Object):int { return stage.getChildIndex(c.element as DisplayObject) } /** * @copy org.apache.flex.core.IParent#removeElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeElement(c:Object, dispatchEvent:Boolean = true):void { stage.removeChild(c.element as DisplayObject); } /** * @copy org.apache.flex.core.IParent#numElements * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get numElements():int { return stage.numChildren; } } }
fix error found by nonfunction test
fix error found by nonfunction test
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
5a3570bba679aca137c3a727d8d334fb3e1447d8
frameworks/projects/HTML/src/main/flex/org/apache/flex/html/beads/SimpleAlertView.as
frameworks/projects/HTML/src/main/flex/org/apache/flex/html/beads/SimpleAlertView.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.IAlertModel; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IMeasurementBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.IParent; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.geom.Rectangle; import org.apache.flex.html.Label; import org.apache.flex.html.TextButton; import org.apache.flex.utils.CSSContainerUtils; /** * The SimpleAlertView class creates the visual elements of the * org.apache.flex.html.SimpleAlert component. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleAlertView extends BeadViewBase implements IBeadView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleAlertView() { } private var messageLabel:Label; private var okButton:TextButton; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; var backgroundColor:Object = ValuesManager.valuesImpl.getValue(value, "background-color"); var backgroundImage:Object = ValuesManager.valuesImpl.getValue(value, "background-image"); if (backgroundColor != null || backgroundImage != null) { if (value.getBeadByType(IBackgroundBead) == null) value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBackgroundBead")) as IBead); } var borderStyle:String; var borderStyles:Object = ValuesManager.valuesImpl.getValue(value, "border"); if (borderStyles is Array) { borderStyle = borderStyles[1]; } if (borderStyle == null) { borderStyle = ValuesManager.valuesImpl.getValue(value, "border-style") as String; } if (borderStyle != null && borderStyle != "none") { if (value.getBeadByType(IBorderBead) == null) value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBorderBead")) as IBead); } var model:IAlertModel = _strand.getBeadByType(IAlertModel) as IAlertModel; model.addEventListener("messageChange",handleMessageChange); model.addEventListener("htmlMessageChange",handleMessageChange); messageLabel = new Label(); messageLabel.text = model.message; messageLabel.html = model.htmlMessage; IParent(_strand).addElement(messageLabel); okButton = new TextButton(); okButton.text = model.okLabel; IParent(_strand).addElement(okButton); okButton.addEventListener("click",handleOK); handleMessageChange(null); } /** * @private */ private function handleMessageChange(event:Event):void { var ruler:IMeasurementBead = messageLabel.getBeadByType(IMeasurementBead) as IMeasurementBead; if( ruler == null ) { messageLabel.addBead(ruler = new (ValuesManager.valuesImpl.getValue(messageLabel, "iMeasurementBead")) as IMeasurementBead); } var maxWidth:Number = Math.max(UIBase(_strand).width,ruler.measuredWidth); var metrics:Rectangle = CSSContainerUtils.getBorderAndPaddingMetrics(_strand); messageLabel.x = metrics.left; messageLabel.y = metrics.top; messageLabel.width = maxWidth; okButton.x = (maxWidth - okButton.width)/2; okButton.y = messageLabel.y + messageLabel.height + 20; UIBase(_strand).width = maxWidth + metrics.left + metrics.right; UIBase(_strand).height = okButton.y + okButton.height + metrics.bottom; } /** * @private */ private function handleOK(event:Event):void { var newEvent:Event = new Event("close"); IEventDispatcher(_strand).dispatchEvent(newEvent); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.IAlertModel; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IMeasurementBead; import org.apache.flex.core.IParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.MouseEvent; import org.apache.flex.geom.Rectangle; import org.apache.flex.html.Label; import org.apache.flex.html.TextButton; import org.apache.flex.utils.CSSContainerUtils; /** * The SimpleAlertView class creates the visual elements of the * org.apache.flex.html.SimpleAlert component. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleAlertView extends BeadViewBase implements IBeadView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleAlertView() { } private var messageLabel:Label; private var okButton:TextButton; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; var backgroundColor:Object = ValuesManager.valuesImpl.getValue(value, "background-color"); var backgroundImage:Object = ValuesManager.valuesImpl.getValue(value, "background-image"); if (backgroundColor != null || backgroundImage != null) { if (value.getBeadByType(IBackgroundBead) == null) value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBackgroundBead")) as IBead); } var borderStyle:String; var borderStyles:Object = ValuesManager.valuesImpl.getValue(value, "border"); if (borderStyles is Array) { borderStyle = borderStyles[1]; } if (borderStyle == null) { borderStyle = ValuesManager.valuesImpl.getValue(value, "border-style") as String; } if (borderStyle != null && borderStyle != "none") { if (value.getBeadByType(IBorderBead) == null) value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBorderBead")) as IBead); } var model:IAlertModel = _strand.getBeadByType(IAlertModel) as IAlertModel; model.addEventListener("messageChange",handleMessageChange); model.addEventListener("htmlMessageChange",handleMessageChange); messageLabel = new Label(); messageLabel.text = model.message; messageLabel.html = model.htmlMessage; IParent(_strand).addElement(messageLabel); okButton = new TextButton(); okButton.text = model.okLabel; IParent(_strand).addElement(okButton); okButton.addEventListener("click",handleOK); handleMessageChange(null); } /** * @private */ private function handleMessageChange(event:Event):void { var ruler:IMeasurementBead = messageLabel.getBeadByType(IMeasurementBead) as IMeasurementBead; if( ruler == null ) { messageLabel.addBead(ruler = new (ValuesManager.valuesImpl.getValue(messageLabel, "iMeasurementBead")) as IMeasurementBead); } var maxWidth:Number = Math.max(UIBase(_strand).width,ruler.measuredWidth); var metrics:Rectangle = CSSContainerUtils.getBorderAndPaddingMetrics(_strand); messageLabel.x = metrics.left; messageLabel.y = metrics.top; messageLabel.width = maxWidth; okButton.x = (maxWidth - okButton.width)/2; okButton.y = messageLabel.y + messageLabel.height + 20; UIBase(_strand).width = maxWidth + metrics.left + metrics.right; UIBase(_strand).height = okButton.y + okButton.height + metrics.bottom; } /** * @private */ private function handleOK(event:MouseEvent):void { var newEvent:Event = new Event("close"); IEventDispatcher(_strand).dispatchEvent(newEvent); } } }
Fix ticket
Fix ticket FLEX-35103
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
98dd01ecfe586bd94eb7fe425da5b7fc77cdf909
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/AbstractStateCommand.as
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/AbstractStateCommand.as
package org.servebox.cafe.core.command { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import org.servebox.cafe.core.signal.SignalAggregator; public class AbstractStateCommand extends EventDispatcher implements IStateCommand { public function AbstractStateCommand(target:IEventDispatcher=null) { super(target); } [Autowired] public var signalAggregator : SignalAggregator; private var _parameters : Array; public function get executable():Boolean { return true; } public function set executable(value:Boolean):void { } public function get parameters():Array { if ( _parameters == null ) { _parameters = new Array(); } return _parameters; } public function set parameters(value:Array):void { _parameters = value; } protected function getParameter( key : String ) : IParameterObject { var paramToReturn : IParameterObject; for each ( var param : IParameterObject in _parameters ) { if ( param.key == key ) { paramToReturn = param; } } if ( !paramToReturn ) { throw new Error("No parameter " + key + " in " + this + " command, check command binding "); } return paramToReturn; } public function addParameter( key : String , value : Object ) : void { var param : AbstractParameterObject = new AbstractParameterObject( key, value ); parameters.push( param ); } public function execute( e : Event = null ) : void { } } }
package org.servebox.cafe.core.command { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import org.servebox.cafe.core.signal.SignalAggregator; public class AbstractStateCommand extends EventDispatcher implements IStateCommand { public function AbstractStateCommand(target:IEventDispatcher=null) { super(target); } [Autowired] public var signalAggregator : SignalAggregator; private var _parameters : Array; public function get executable():Boolean { return true; } public function set executable(value:Boolean):void { } public function get parameters():Array { if ( _parameters == null ) { _parameters = new Array(); } return _parameters; } public function set parameters(value:Array):void { _parameters = value; } protected function getParameter( key : String ) : IParameterObject { var paramToReturn : IParameterObject; for each ( var param : IParameterObject in _parameters ) { if ( param.key == key ) { paramToReturn = param; if ( paramToReturn.value == null ) { throw new Error("Parameter value for " + key + " in " + this + " is null, check command binding "); } } } if ( !paramToReturn ) { throw new Error("No parameter " + key + " in " + this + " command, check command binding "); } return paramToReturn; } public function addParameter( key : String , value : Object ) : void { var param : AbstractParameterObject = new AbstractParameterObject( key, value ); parameters.push( param ); } public function execute( e : Event = null ) : void { } } }
Add throw error for parameter value.
Add throw error for parameter value.
ActionScript
mit
servebox/as-cafe
cf31a4ec40407f08ecec88a30399fc5dad4c1b60
dolly-framework/src/main/actionscript/dolly/Cloner.as
dolly-framework/src/main/actionscript/dolly/Cloner.as
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import dolly.utils.ClassUtil; import flash.utils.ByteArray; import flash.utils.Dictionary; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary(); private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } private static function isTypePreparedForCloning(type:Type):Boolean { return _isClassPreparedForCloningMap[type.clazz]; } private static function failIfTypeIsNotCloneable(type:Type):void { if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } } private static function prepareTypeForCloning(type:Type):void { if (isTypePreparedForCloning(type)) { return; } ClassUtil.registerAliasFor(type.clazz); _isClassPreparedForCloningMap[type.clazz] = true; const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); for each(var field:Field in fieldsToClone) { var fieldType:Type = field.type; if (isTypeCloneable(fieldType)) { prepareTypeForCloning(fieldType); } } } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { failIfTypeIsNotCloneable(type); if (!isTypePreparedForCloning(type)) { prepareTypeForCloning(type); } const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } dolly_internal static function doClone(source:*, type:Type = null):* { if (!type) { type = Type.forInstance(source); } prepareTypeForCloning(type); const byteArray:ByteArray = new ByteArray(); byteArray.writeObject(source); byteArray.position = 0; const clonedInstance:* = byteArray.readObject(); return clonedInstance; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); failIfTypeIsNotCloneable(type); return doClone(source, type); } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import dolly.utils.ClassUtil; import flash.utils.ByteArray; import flash.utils.Dictionary; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary(); private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } private static function isTypePreparedForCloning(type:Type):Boolean { return _isClassPreparedForCloningMap[type.clazz]; } private static function failIfTypeIsNotCloneable(type:Type):void { if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } } private static function prepareTypeForCloning(type:Type):void { if (isTypePreparedForCloning(type)) { return; } ClassUtil.registerAliasFor(type.clazz); _isClassPreparedForCloningMap[type.clazz] = true; const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); for each(var field:Field in fieldsToClone) { var fieldType:Type = field.type; if (isTypeCloneable(fieldType)) { prepareTypeForCloning(fieldType); } } } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { failIfTypeIsNotCloneable(type); if (!isTypePreparedForCloning(type)) { prepareTypeForCloning(type); } const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } dolly_internal static function doClone(source:*):* { const byteArray:ByteArray = new ByteArray(); byteArray.writeObject(source); byteArray.position = 0; return byteArray.readObject(); } public static function clone(source:*):* { const type:Type = Type.forInstance(source); failIfTypeIsNotCloneable(type); prepareTypeForCloning(type); return doClone(source); } } }
Refactor method Cloner.doClone(): currently it only do cloning of objects by using ByteArray.
Refactor method Cloner.doClone(): currently it only do cloning of objects by using ByteArray.
ActionScript
mit
Yarovoy/dolly
96affe5df3289ec9bad4013b105433ef2293b38c
dolly-framework/src/test/actionscript/dolly/CloningOfPropertyLevelCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CloningOfPropertyLevelCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.PropertyLevelCloneableClass; import org.as3commons.reflect.Type; use namespace dolly_internal; public class CloningOfPropertyLevelCloneableClassTest { private var propertyLevelCloneable:PropertyLevelCloneableClass; private var propertyLevelCloneableType:Type; [Before] public function before():void { propertyLevelCloneable = new PropertyLevelCloneableClass(); propertyLevelCloneable.property1 = "property1 value"; propertyLevelCloneable.writableField1 = "writableField1 value"; propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable); } [After] public function after():void { propertyLevelCloneable = null; propertyLevelCloneableType = null; } /** * <code>Cloner.findingAllWritableFieldsForType()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function findingAllWritableFieldsForType():void { Cloner.findAllWritableFieldsForType(propertyLevelCloneableType); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloner():void { Cloner.clone(propertyLevelCloneable); } /** * Method <code>clone()</code> will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloneFunction():void { clone(propertyLevelCloneable); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.PropertyLevelCloneableClass; import org.as3commons.reflect.Type; use namespace dolly_internal; public class CloningOfPropertyLevelCloneableClassTest { private var propertyLevelCloneable:PropertyLevelCloneableClass; private var propertyLevelCloneableType:Type; [Before] public function before():void { propertyLevelCloneable = new PropertyLevelCloneableClass(); propertyLevelCloneable.property1 = "property1 value"; propertyLevelCloneable.writableField1 = "writableField1 value"; propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable); } [After] public function after():void { propertyLevelCloneable = null; propertyLevelCloneableType = null; } /** * <code>Cloner.findingAllWritableFieldsForType()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneableClass</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function findingAllWritableFieldsForType():void { Cloner.findAllWritableFieldsForType(propertyLevelCloneableType); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneableClass</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloner():void { Cloner.clone(propertyLevelCloneable); } /** * Method <code>clone()</code> will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneableClass</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloneFunction():void { clone(propertyLevelCloneable); } } }
Fix ASDoc.
Fix ASDoc.
ActionScript
mit
Yarovoy/dolly
db530455699f74a47a9f9a9aca4939bbc8cc0f0e
exporter/src/main/as/flump/export/AutomaticExporter.as
exporter/src/main/as/flump/export/AutomaticExporter.as
package flump.export { import aspire.util.StringUtil; import flash.events.ErrorEvent; import flash.events.UncaughtErrorEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flump.executor.Executor; import flump.executor.Future; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import react.BoolValue; import react.BoolView; /** * This class expects to be run from the command-line script found at rsrc/flump-export. It sends * output to File.applicationDirectory.nativePath + "/exporter.log" rather than spawning any * UI windows for user interaction, and acts as though the user pressed the export all button, then * shuts down. */ public class AutomaticExporter { public function AutomaticExporter (project :File) { _complete.connect(function (complete :Boolean) :void { if (!complete) return; if (OUT != null) { OUT.close(); OUT = null; } }); FlumpApp.app.loaderInfo.uncaughtErrorEvents .addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, exit); var outFile :File = new File(File.applicationDirectory.nativePath + "/exporter.log"); OUT = new FileStream(); OUT.open(outFile, FileMode.WRITE); _confFile = project; exportProject(); } public function get complete () :BoolView { return _complete; } public function get projectName () :String { return (_confFile != null ? _confFile.name.replace(/\.flump$/i, "") : "Untitled Project"); } protected function exportProject () :void { println("Exporting project: " + _confFile.nativePath); println(); try { _conf = ProjectConf.fromJSON(JSONFormat.readJSON(_confFile)); _importDirectory = new File(_confFile.parent.resolvePath(_conf.importDir).nativePath); if (!_importDirectory.exists || !_importDirectory.isDirectory) { exit(new ParseError(_confFile.nativePath, ParseError.CRIT, "Import directory doesn't exist (" + _importDirectory.nativePath + ")")); return; } } catch (e :Error) { exit(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); return; } findFlashDocuments(_importDirectory, new Executor(), true); } protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.connect(function (files :Array) :void { for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { exit(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, " + "did you mean " + base.parent.nativePath + "?")); return; } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { // Ignore hidden VCS directories, and recovered backups created by Flash continue; } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function addFlashDocument (file :File) :void { var importPathLen :int = _importDirectory.nativePath.length + 1; var name :String = file.nativePath.substring(importPathLen).replace( new RegExp("\\" + File.separator, "g"), "/"); var load :Future; switch (Files.getExtension(file)) { case "xfl": name = name.substr(0, name.lastIndexOf("/")); load = new XflLoader().load(name, file.parent); println("Loading XFL: " + name + "..."); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); println("Loading FLA: " + name + "..."); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _statuses[_statuses.length] = status; load.succeeded.connect(function (lib :XflLibrary) :void { println("Load completed: " + name + "..."); status.lib = lib; for each (var err :ParseError in lib.getErrors()) printErr(err); status.updateValid(Ternary.of(lib.valid)); checkValid(); }); // any failed load means we can't finish the export load.failed.connect(exit); } /** returns all libs if all known flash docs are done loading, else null */ protected function getLibs () :Vector.<XflLibrary> { var libs :Vector.<XflLibrary> = new <XflLibrary>[]; for each (var status :DocStatus in _statuses) { if (status.lib == null) return null; // not done loading yet libs[libs.length] = status.lib; } return libs; } protected function checkValid () :void { if (getLibs() == null) return; // not done loading yet var valid :Boolean = _statuses.every(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); if (!valid) { // we've already printed our parse errors exit(); return; } println("\nLoading complete..."); if (_conf.exportDir == null) { exit("No export directory specified."); return; } if (_conf.exportDir == null) { exit("No export directory specified."); return; } var hasCombined :Boolean = false; var hasSingle :Boolean = false; for each (var config :ExportConf in _conf.exports) { hasCombined ||= config.combine; hasSingle ||= !config.combine; if (hasCombined && hasSingle) break; } try { var publisher :Publisher = new Publisher(new File(_conf.exportDir), _conf, projectName); // if we have one or more combined export format, publish them if (hasCombined) { println("Exporting combined formats..."); var numPublished :int = publisher.publishCombined(getLibs()); if (numPublished == 0) { printErr("No suitable formats were found for combined publishing"); } else { println("" + numPublished + " combined formats published..."); } } // now publish any appropriate single formats if (hasSingle) { for each (var status :DocStatus in _statuses) { println("Exporting document " + status.path + "..."); numPublished = publisher.publishSingle(status.lib); if (numPublished == 0) { printErr("No suitable formats were found for single publishing"); } else { println("" + numPublished + " formats published..."); } } } } catch (e :Error) { exit(e); return; } println("\nPublishing complete..."); exit(); } protected function printErr (err :*) :void { if (err is ParseError) { var pe :ParseError = ParseError(err); println("[" + pe.severity + "] @ " + pe.location + ": " + pe.message); } else if (err is Error) { println(Error(err).getStackTrace()) } else if (err is ErrorEvent) { println("ErrorEvent: " + ErrorEvent(err).toString()); if (err is UncaughtErrorEvent) { println(UncaughtErrorEvent(err).error.getStackTrace()); } } else { println("" + err); } } protected function print (message :String) :void { OUT.writeUTFBytes(message); } protected function println (message :String = "") :void { print(message + "\n"); } protected function exit (err :* = null) :void { if (err != null) printErr(err); _complete.value = true; } protected const _complete :BoolValue = new BoolValue(false); protected var OUT :FileStream; protected var _confFile :File; protected var _conf :ProjectConf; protected var _importDirectory :File; protected var _statuses :Array = []; } }
package flump.export { import aspire.util.StringUtil; import flash.events.ErrorEvent; import flash.events.UncaughtErrorEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flump.executor.Executor; import flump.executor.Future; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import react.BoolValue; import react.BoolView; /** * This class expects to be run from the command-line script found at rsrc/flump-export. It sends * output to File.applicationDirectory.nativePath + "/exporter.log" rather than spawning any * UI windows for user interaction, and acts as though the user pressed the export all button, then * shuts down. */ public class AutomaticExporter { public function AutomaticExporter (project :File) { _complete.connect(function (complete :Boolean) :void { if (!complete) return; if (OUT != null) { OUT.close(); OUT = null; } }); FlumpApp.app.loaderInfo.uncaughtErrorEvents .addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, exit); var outFile :File = new File(File.applicationDirectory.nativePath + "/exporter.log"); OUT = new FileStream(); OUT.open(outFile, FileMode.WRITE); _confFile = project; exportProject(); } public function get complete () :BoolView { return _complete; } public function get projectName () :String { return (_confFile != null ? _confFile.name.replace(/\.flump$/i, "") : "Untitled Project"); } protected function exportProject () :void { println("Exporting project: " + _confFile.nativePath); println(); try { _conf = ProjectConf.fromJSON(JSONFormat.readJSON(_confFile)); _importDirectory = new File(_confFile.parent.resolvePath(_conf.importDir).nativePath); if (!_importDirectory.exists || !_importDirectory.isDirectory) { exit(new ParseError(_confFile.nativePath, ParseError.CRIT, "Import directory doesn't exist (" + _importDirectory.nativePath + ")")); return; } } catch (e :Error) { exit(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); return; } findFlashDocuments(_importDirectory, new Executor(), true); } protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.connect(function (files :Array) :void { for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { exit(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, " + "did you mean " + base.parent.nativePath + "?")); return; } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { // Ignore hidden VCS directories, and recovered backups created by Flash continue; } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function addFlashDocument (file :File) :void { var importPathLen :int = _importDirectory.nativePath.length + 1; var name :String = file.nativePath.substring(importPathLen).replace( new RegExp("\\" + File.separator, "g"), "/"); var load :Future; switch (Files.getExtension(file)) { case "xfl": name = name.substr(0, name.lastIndexOf("/")); load = new XflLoader().load(name, file.parent); println("Loading XFL: " + name + "..."); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); println("Loading FLA: " + name + "..."); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _statuses[_statuses.length] = status; load.succeeded.connect(function (lib :XflLibrary) :void { println("Load completed: " + name + "..."); status.lib = lib; for each (var err :ParseError in lib.getErrors()) printErr(err); status.updateValid(Ternary.of(lib.valid)); checkValid(); }); // any failed load means we can't finish the export load.failed.connect(exit); } /** returns all libs if all known flash docs are done loading, else null */ protected function getLibs () :Vector.<XflLibrary> { var libs :Vector.<XflLibrary> = new <XflLibrary>[]; for each (var status :DocStatus in _statuses) { if (status.lib == null) return null; // not done loading yet libs[libs.length] = status.lib; } return libs; } protected function checkValid () :void { if (getLibs() == null) return; // not done loading yet var valid :Boolean = _statuses.every(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); if (!valid) { // we've already printed our parse errors exit(); return; } println("\nLoading complete..."); if (_conf.exportDir == null) { exit("No export directory specified."); return; } var hasCombined :Boolean = false; var hasSingle :Boolean = false; for each (var config :ExportConf in _conf.exports) { hasCombined ||= config.combine; hasSingle ||= !config.combine; if (hasCombined && hasSingle) break; } try { var publisher :Publisher = new Publisher(new File(_conf.exportDir), _conf, projectName); // if we have one or more combined export format, publish them if (hasCombined) { println("Exporting combined formats..."); var numPublished :int = publisher.publishCombined(getLibs()); if (numPublished == 0) { printErr("No suitable formats were found for combined publishing"); } else { println("" + numPublished + " combined formats published..."); } } // now publish any appropriate single formats if (hasSingle) { for each (var status :DocStatus in _statuses) { println("Exporting document " + status.path + "..."); numPublished = publisher.publishSingle(status.lib); if (numPublished == 0) { printErr("No suitable formats were found for single publishing"); } else { println("" + numPublished + " formats published..."); } } } } catch (e :Error) { exit(e); return; } println("\nPublishing complete..."); exit(); } protected function printErr (err :*) :void { if (err is ParseError) { var pe :ParseError = ParseError(err); println("[" + pe.severity + "] @ " + pe.location + ": " + pe.message); } else if (err is Error) { println(Error(err).getStackTrace()) } else if (err is ErrorEvent) { println("ErrorEvent: " + ErrorEvent(err).toString()); if (err is UncaughtErrorEvent) { println(UncaughtErrorEvent(err).error.getStackTrace()); } } else { println("" + err); } } protected function print (message :String) :void { OUT.writeUTFBytes(message); } protected function println (message :String = "") :void { print(message + "\n"); } protected function exit (err :* = null) :void { if (err != null) printErr(err); _complete.value = true; } protected const _complete :BoolValue = new BoolValue(false); protected var OUT :FileStream; protected var _confFile :File; protected var _conf :ProjectConf; protected var _importDirectory :File; protected var _statuses :Array = []; } }
Remove redundant check.
Remove redundant check.
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
e0751b31ac4904f0d4b2bd7c99809690896aac9a
test/acceptance/mmgc/pauseForGCIfCollectionImminent.as
test/acceptance/mmgc/pauseForGCIfCollectionImminent.as
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ import avmplus.* ; // System class in the avmshell import flash.system.* ; // System class in the flash player var SECTION = "System::pauseForGCIfCollectionImminent"; var VERSION = ""; startTest(); var TITLE = "Test pauseForGCIfCollectionImminent api"; class Node { var left: Node, right: Node; var i: int, j: int; function Node(l: Node = null, r: Node = null) { left = l; right = r; } } // DO NOT MESS WITH THE PARAMETER VALUES. // // If the test takes to long to run on mobile with these values then either set the values // differently on mobile, or disable the test on mobile. On desktop we need a decent // number of iterations in order to be able to run reliably, the test is statistical and // sometimes getting a hit is tricky on a fast machine. var i_loops = 1000; var j_loops = 1000; var start = new Date(); var fractions = [Number.MIN_VALUE, 0, -0, 0.25, 0.5, 0.75, 1.0]; for each(var f in fractions) { trace("starting pauseForGCIfCollectionImminent test @ " + f); var hits = 0; var a = []; for (var i = 0; i < i_loops; i++) { for (var j = 0; j < j_loops; j++) a[0] = 3.14159 + i * j; // compute a Number and store it in a * location to box it // Bugzilla 685161: Invoking a System method can disrupt // observed memory if its MethodSignature had been evicted but // weakly-held until some GC during loop freed it and cleared // the weak ref. // // As work-around, pre-call pauseForGCIfCollectionImminent // with imminence=1.0 (which should be a no-op) and the two // getters, ensuring all MethodSignatures are available before // memory observations in critical section. System.pauseForGCIfCollectionImminent(1.0); System.totalMemory; System.freeMemory; // Start critical section var beforeTotal = System.totalMemory; var beforeFree = System.freeMemory; System.pauseForGCIfCollectionImminent(f); var afterTotal = System.totalMemory; var afterFree = System.freeMemory; // End of critical section // Bugzilla 678975: 'total' once denoted used+free; now 'total' is used var beforeUsed = beforeTotal; var afterUsed = afterTotal; if (after < before) hits++; if (((i + 1) % 100) == 0) trace("Hits: " + hits); } AddTestCase("pauseForGCIfCollectionImminent test f=" + f + " : hits="+hits, true, ((hits > 0) == (f < 1.0))); } trace('Main tests: '+(new Date() - start)) start = new Date(); var error_cases = [NaN, undefined, Number.NEGATIVE_INFINITY, -1, 1.000000001, 10000, Number.MAX_VALUE, Number.POSITIVE_INFINITY]; for each (var ec in error_cases) { error = "no error"; try { System.pauseForGCIfCollectionImminent(ec); } catch (err) { error = err.toString(); } AddTestCase("pauseForGCIfCollectionImminent test @ " + ec, "no error", error); } var loop_time = new Date() - start; trace("error tests: "+loop_time); test();
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ import avmplus.* ; // System class in the avmshell import flash.system.* ; // System class in the flash player var SECTION = "System::pauseForGCIfCollectionImminent"; var VERSION = ""; startTest(); var TITLE = "Test pauseForGCIfCollectionImminent api"; class Node { var left: Node, right: Node; var i: int, j: int; function Node(l: Node = null, r: Node = null) { left = l; right = r; } } // DO NOT MESS WITH THE PARAMETER VALUES. // // If the test takes to long to run on mobile with these values then either set the values // differently on mobile, or disable the test on mobile. On desktop we need a decent // number of iterations in order to be able to run reliably, the test is statistical and // sometimes getting a hit is tricky on a fast machine. var i_loops = 1000; var j_loops = 1000; var start = new Date(); var fractions = [Number.MIN_VALUE, 0, -0, 0.25, 0.5, 0.75, 1.0]; for each(var f in fractions) { trace("starting pauseForGCIfCollectionImminent test @ " + f); var hits = 0; var a = []; for (var i = 0; i < i_loops; i++) { for (var j = 0; j < j_loops; j++) a[0] = 3.14159 + i * j; // compute a Number and store it in a * location to box it // Bugzilla 685161: Invoking a System method can disrupt // observed memory if its MethodSignature had been evicted but // weakly-held until some GC during loop freed it and cleared // the weak ref. // // As work-around, pre-call pauseForGCIfCollectionImminent // with imminence=1.0 (which should be a no-op) and the two // getters, ensuring all MethodSignatures are available before // memory observations in critical section. System.pauseForGCIfCollectionImminent(1.0); System.totalMemory; System.freeMemory; // Start critical section var beforeTotal = System.totalMemory; var beforeFree = System.freeMemory; System.pauseForGCIfCollectionImminent(f); var afterTotal = System.totalMemory; var afterFree = System.freeMemory; // End of critical section // Bugzilla 678975: 'total' once denoted used+free; now 'total' is used var beforeUsed = beforeTotal; var afterUsed = afterTotal; if (afterUsed < beforeUsed) hits++; if (((i + 1) % 100) == 0) trace("Hits: " + hits); } AddTestCase("pauseForGCIfCollectionImminent test f=" + f + " : hits="+hits, true, ((hits > 0) == (f < 1.0))); } trace('Main tests: '+(new Date() - start)) start = new Date(); var error_cases = [NaN, undefined, Number.NEGATIVE_INFINITY, -1, 1.000000001, 10000, Number.MAX_VALUE, Number.POSITIVE_INFINITY]; for each (var ec in error_cases) { error = "no error"; try { System.pauseForGCIfCollectionImminent(ec); } catch (err) { error = err.toString(); } AddTestCase("pauseForGCIfCollectionImminent test @ " + ec, "no error", error); } var loop_time = new Date() - start; trace("error tests: "+loop_time); test();
Fix build breakage due to presumed oversight in changeset 84a074bbb8cf
Fix build breakage due to presumed oversight in changeset 84a074bbb8cf Bug 678975: change shell totalMemory to match FR meaning, i.e. usedMemory, and fix dependencies on former meaning (r=fklockii). interrupted! take a look at this. This is a quick and not carefully considered fix to get the build going again.
ActionScript
mpl-2.0
pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux
f2ab526f6c44f9dd922ab418d65109c622f8f4c8
src/aerys/minko/render/resource/Context3DResource.as
src/aerys/minko/render/resource/Context3DResource.as
package aerys.minko.render.resource { import flash.display.BitmapData; import flash.display3D.Context3D; import flash.display3D.IndexBuffer3D; import flash.display3D.Program3D; import flash.display3D.VertexBuffer3D; import flash.display3D.textures.CubeTexture; import flash.display3D.textures.Texture; import flash.display3D.textures.TextureBase; import flash.geom.Rectangle; public final class Context3DResource { private var _context : Context3D; private var _enableErrorChecking : Boolean; private var _rttTarget : TextureBase; private var _rttDepthAndStencil : Boolean; private var _rttAntiAliasing : int; private var _rttSurfaceSelector : int; private var _rectangle : Rectangle; private var _depthMask : Boolean; private var _passCompareMode : String; private var _program : Program3D; private var _blendingSource : String; private var _blendingDestination : String; private var _triangleCulling : String; private var _vertexBuffers : Vector.<VertexBuffer3D>; private var _vertexBuffersOffsets : Vector.<int>; private var _vertexBuffersFormats : Vector.<String>; private var _textures : Vector.<TextureBase>; private var _colorMaskRed : Boolean; private var _colorMaskGreen : Boolean; private var _colorMaskBlue : Boolean; private var _colorMaskAlpha : Boolean; private var _stencilRefNum : uint; private var _stencilReadMask : uint; private var _stencilWriteMask : uint; private var _stencilTriangleFace : String; private var _stencilCompareMode : String; private var _stencilActionOnBothPass : String; private var _stencilActionOnDepthFail : String; private var _stencilActionOnDepthPassStencilFail : String; public function get enabledErrorChecking() : Boolean { return _enableErrorChecking; } public function set enableErrorChecking(value : Boolean) : void { if (value != _enableErrorChecking) { _enableErrorChecking = value; _context.enableErrorChecking = value; } } public function Context3DResource(context : Context3D) { _context = context; initialize(); } private function initialize() : void { _vertexBuffers = new Vector.<VertexBuffer3D>(8, true); _vertexBuffersOffsets = new Vector.<int>(8, true); _vertexBuffersFormats = new Vector.<String>(8, true); _textures = new Vector.<TextureBase>(8, true); } public function clear(red : Number = 0.0, green : Number = 0.0, blue : Number = 0.0, alpha : Number = 1.0, depth : Number = 1.0, stencil : uint = 0, mask : uint = 0xffffffff) : void { _context.clear(red, green, blue, alpha, depth, stencil, mask); } public function configureBackBuffer(width : int, height : int, antiAlias : int, enabledDepthAndStencil : Boolean) : Context3DResource { _context.configureBackBuffer(width, height, antiAlias, enabledDepthAndStencil); return this; } public function createCubeTexture(size : int, format : String, optimizeForRenderToTexture : Boolean) : CubeTexture { return _context.createCubeTexture(size, format, optimizeForRenderToTexture); } public function createIndexBuffer(numIndices : int) : IndexBuffer3D { return _context.createIndexBuffer(numIndices); } public function createProgram() : Program3D { return _context.createProgram(); } public function createTexture(width : int, height : int, format : String, optimizeForRenderToTexture : Boolean) : Texture { return _context.createTexture(width, height, format, optimizeForRenderToTexture); } public function createVertexBuffer(numVertices : int, data32PerVertex : int) : VertexBuffer3D { return _context.createVertexBuffer(numVertices, data32PerVertex); } public function dispose() : void { _context.dispose(); } public function drawToBitmapData(destination : BitmapData) : Context3DResource { _context.drawToBitmapData(destination); return this; } public function drawTriangles(indexBuffer : IndexBuffer3D, firstIndex : int = 0, numTriangles : int = -1) : Context3DResource { _context.drawTriangles(indexBuffer, firstIndex, numTriangles); return this; } public function present() : Context3DResource { _context.present(); return this; } public function setBlendFactors(source : String, destination : String) : Context3DResource { if (source != _blendingSource || destination != _blendingDestination) { _blendingSource = source; _blendingDestination = destination; _context.setBlendFactors(_blendingSource, _blendingDestination); } return this; } public function setColorMask(red : Boolean, green : Boolean, blue : Boolean, alpha : Boolean) : Context3DResource { if (red != _colorMaskRed || green != _colorMaskGreen || blue != _colorMaskBlue || alpha != _colorMaskAlpha) { _colorMaskRed = red; _colorMaskGreen = green; _colorMaskBlue = blue; _colorMaskAlpha = alpha; _context.setColorMask( _colorMaskRed, _colorMaskGreen, _colorMaskBlue, _colorMaskAlpha ); } return this; } public function setCulling(triangleCulling : String) : Context3DResource { if (triangleCulling != _triangleCulling) { _triangleCulling = triangleCulling; _context.setCulling(triangleCulling); } return this; } public function setDepthTest(depthMask : Boolean, passCompareMode : String) : Context3DResource { if (depthMask != _depthMask || passCompareMode != _passCompareMode) { _depthMask = depthMask; _passCompareMode = passCompareMode; _context.setDepthTest(_depthMask, _passCompareMode); } return this; } public function setProgram(program : Program3D) : Context3DResource { if (_program != program) { _program = program; _context.setProgram(program); } return this; } public function setProgramConstantsFromVector(programeType : String, offset : uint, values : Vector.<Number>, numRegisters : int = -1) : Context3DResource { _context.setProgramConstantsFromVector(programeType, offset, values, numRegisters); return this; } public function setRenderToBackBuffer() : Context3DResource { if (_rttTarget != null) { _rttTarget = null; _context.setRenderToBackBuffer(); } return this; } public function setRenderToTexture(texture : TextureBase, enableDepthAndStencil : Boolean = false, antiAlias : int = 0, surfaceSelector : int = 0) : Context3DResource { if (texture != _rttTarget || enableDepthAndStencil != _rttDepthAndStencil || antiAlias != _rttAntiAliasing || surfaceSelector != _rttSurfaceSelector) { _rttTarget = texture; _rttDepthAndStencil = enableDepthAndStencil; _rttAntiAliasing = antiAlias; _rttSurfaceSelector = surfaceSelector; _context.setRenderToTexture( texture, enableDepthAndStencil, antiAlias, surfaceSelector ); } return this; } public function setScissorRectangle(rectangle : Rectangle) : Context3DResource { if (_rectangle != rectangle) { _rectangle = rectangle; _context.setScissorRectangle(_rectangle); } return this; } public function setTextureAt(sampler : uint, texture : TextureBase) : Context3DResource { if (_textures[sampler] != texture) { _textures[sampler] = texture; _context.setTextureAt(sampler, texture); } return this; } public function setVertexBufferAt(index : int, vertexBuffer : VertexBuffer3D, bufferOffset : int = 0, format : String = 'float4') : Context3DResource { if (_vertexBuffers[index] != vertexBuffer || _vertexBuffersOffsets[index] != bufferOffset || _vertexBuffersFormats[index] != format) { _vertexBuffers[index] = vertexBuffer; _vertexBuffersOffsets[index] = bufferOffset; _vertexBuffersFormats[index] = format; _context.setVertexBufferAt( index, vertexBuffer, bufferOffset, format ); } return this; } public function setStencilReferenceValue(refNum : uint = 0, readMask : uint = 255, writeMask : uint = 255) : Context3DResource { if (refNum != _stencilRefNum || readMask != _stencilReadMask || writeMask != _stencilWriteMask ) { _context.setStencilReferenceValue(refNum, readMask, writeMask); _stencilRefNum = refNum; _stencilReadMask = readMask; _stencilWriteMask = writeMask; } return this; } public function setStencilActions(triangleFace : String = 'frontAndBack', compareMode : String = 'always', actionOnBothPass : String = 'keep', actionOnDepthFail : String = 'keep', actionOnDepthPassStencilFail : String = 'keep') : Context3DResource { if (triangleFace != _stencilTriangleFace || compareMode != _stencilCompareMode || actionOnBothPass != _stencilActionOnBothPass || actionOnDepthFail != _stencilActionOnDepthFail || actionOnDepthPassStencilFail != _stencilActionOnDepthPassStencilFail ) { _context.setStencilActions( triangleFace, compareMode, actionOnBothPass, actionOnDepthFail, actionOnDepthPassStencilFail ); _stencilTriangleFace = triangleFace; _stencilCompareMode = compareMode; _stencilActionOnBothPass = actionOnBothPass; _stencilActionOnDepthFail = actionOnDepthFail; _stencilActionOnDepthPassStencilFail = actionOnDepthPassStencilFail; } return this; } } }
package aerys.minko.render.resource { import flash.display.BitmapData; import flash.display3D.Context3D; import flash.display3D.IndexBuffer3D; import flash.display3D.Program3D; import flash.display3D.VertexBuffer3D; import flash.display3D.textures.CubeTexture; import flash.display3D.textures.Texture; import flash.display3D.textures.TextureBase; import flash.geom.Rectangle; import aerys.minko.ns.minko_render; public final class Context3DResource { private var _context : Context3D; private var _enableErrorChecking : Boolean; private var _rttTarget : TextureBase; private var _rttDepthAndStencil : Boolean; private var _rttAntiAliasing : int; private var _rttSurfaceSelector : int; private var _rectangle : Rectangle; private var _depthMask : Boolean; private var _passCompareMode : String; private var _program : Program3D; private var _blendingSource : String; private var _blendingDestination : String; private var _triangleCulling : String; private var _vertexBuffers : Vector.<VertexBuffer3D>; private var _vertexBuffersOffsets : Vector.<int>; private var _vertexBuffersFormats : Vector.<String>; private var _textures : Vector.<TextureBase>; private var _colorMaskRed : Boolean; private var _colorMaskGreen : Boolean; private var _colorMaskBlue : Boolean; private var _colorMaskAlpha : Boolean; private var _stencilRefNum : uint; private var _stencilReadMask : uint; private var _stencilWriteMask : uint; private var _stencilTriangleFace : String; private var _stencilCompareMode : String; private var _stencilActionOnBothPass : String; private var _stencilActionOnDepthFail : String; private var _stencilActionOnDepthPassStencilFail : String; minko_render function get context() : Context3D { return _context; } public function get enabledErrorChecking() : Boolean { return _enableErrorChecking; } public function set enableErrorChecking(value : Boolean) : void { if (value != _enableErrorChecking) { _enableErrorChecking = value; _context.enableErrorChecking = value; } } public function Context3DResource(context : Context3D) { _context = context; initialize(); } private function initialize() : void { _vertexBuffers = new Vector.<VertexBuffer3D>(8, true); _vertexBuffersOffsets = new Vector.<int>(8, true); _vertexBuffersFormats = new Vector.<String>(8, true); _textures = new Vector.<TextureBase>(8, true); } public function clear(red : Number = 0.0, green : Number = 0.0, blue : Number = 0.0, alpha : Number = 1.0, depth : Number = 1.0, stencil : uint = 0, mask : uint = 0xffffffff) : void { _context.clear(red, green, blue, alpha, depth, stencil, mask); } public function configureBackBuffer(width : int, height : int, antiAlias : int, enabledDepthAndStencil : Boolean) : Context3DResource { _context.configureBackBuffer(width, height, antiAlias, enabledDepthAndStencil); return this; } public function createCubeTexture(size : int, format : String, optimizeForRenderToTexture : Boolean) : CubeTexture { return _context.createCubeTexture(size, format, optimizeForRenderToTexture); } public function createIndexBuffer(numIndices : int) : IndexBuffer3D { return _context.createIndexBuffer(numIndices); } public function createProgram() : Program3D { return _context.createProgram(); } public function createTexture(width : int, height : int, format : String, optimizeForRenderToTexture : Boolean) : Texture { return _context.createTexture(width, height, format, optimizeForRenderToTexture); } public function createVertexBuffer(numVertices : int, data32PerVertex : int) : VertexBuffer3D { return _context.createVertexBuffer(numVertices, data32PerVertex); } public function dispose() : void { _context.dispose(); } public function drawToBitmapData(destination : BitmapData) : Context3DResource { _context.drawToBitmapData(destination); return this; } public function drawTriangles(indexBuffer : IndexBuffer3D, firstIndex : int = 0, numTriangles : int = -1) : Context3DResource { _context.drawTriangles(indexBuffer, firstIndex, numTriangles); return this; } public function present() : Context3DResource { _context.present(); return this; } public function setBlendFactors(source : String, destination : String) : Context3DResource { if (source != _blendingSource || destination != _blendingDestination) { _blendingSource = source; _blendingDestination = destination; _context.setBlendFactors(_blendingSource, _blendingDestination); } return this; } public function setColorMask(red : Boolean, green : Boolean, blue : Boolean, alpha : Boolean) : Context3DResource { if (red != _colorMaskRed || green != _colorMaskGreen || blue != _colorMaskBlue || alpha != _colorMaskAlpha) { _colorMaskRed = red; _colorMaskGreen = green; _colorMaskBlue = blue; _colorMaskAlpha = alpha; _context.setColorMask( _colorMaskRed, _colorMaskGreen, _colorMaskBlue, _colorMaskAlpha ); } return this; } public function setCulling(triangleCulling : String) : Context3DResource { if (triangleCulling != _triangleCulling) { _triangleCulling = triangleCulling; _context.setCulling(triangleCulling); } return this; } public function setDepthTest(depthMask : Boolean, passCompareMode : String) : Context3DResource { if (depthMask != _depthMask || passCompareMode != _passCompareMode) { _depthMask = depthMask; _passCompareMode = passCompareMode; _context.setDepthTest(_depthMask, _passCompareMode); } return this; } public function setProgram(program : Program3D) : Context3DResource { if (_program != program) { _program = program; _context.setProgram(program); } return this; } public function setProgramConstantsFromVector(programeType : String, offset : uint, values : Vector.<Number>, numRegisters : int = -1) : Context3DResource { _context.setProgramConstantsFromVector(programeType, offset, values, numRegisters); return this; } public function setRenderToBackBuffer() : Context3DResource { if (_rttTarget != null) { _rttTarget = null; _context.setRenderToBackBuffer(); } return this; } public function setRenderToTexture(texture : TextureBase, enableDepthAndStencil : Boolean = false, antiAlias : int = 0, surfaceSelector : int = 0) : Context3DResource { if (texture != _rttTarget || enableDepthAndStencil != _rttDepthAndStencil || antiAlias != _rttAntiAliasing || surfaceSelector != _rttSurfaceSelector) { _rttTarget = texture; _rttDepthAndStencil = enableDepthAndStencil; _rttAntiAliasing = antiAlias; _rttSurfaceSelector = surfaceSelector; _context.setRenderToTexture( texture, enableDepthAndStencil, antiAlias, surfaceSelector ); } return this; } public function setScissorRectangle(rectangle : Rectangle) : Context3DResource { if (_rectangle != rectangle) { _rectangle = rectangle; _context.setScissorRectangle(_rectangle); } return this; } public function setTextureAt(sampler : uint, texture : TextureBase) : Context3DResource { if (_textures[sampler] != texture) { _textures[sampler] = texture; _context.setTextureAt(sampler, texture); } return this; } public function setVertexBufferAt(index : int, vertexBuffer : VertexBuffer3D, bufferOffset : int = 0, format : String = 'float4') : Context3DResource { if (_vertexBuffers[index] != vertexBuffer || _vertexBuffersOffsets[index] != bufferOffset || _vertexBuffersFormats[index] != format) { _vertexBuffers[index] = vertexBuffer; _vertexBuffersOffsets[index] = bufferOffset; _vertexBuffersFormats[index] = format; _context.setVertexBufferAt( index, vertexBuffer, bufferOffset, format ); } return this; } public function setStencilReferenceValue(refNum : uint = 0, readMask : uint = 255, writeMask : uint = 255) : Context3DResource { if (refNum != _stencilRefNum || readMask != _stencilReadMask || writeMask != _stencilWriteMask ) { _context.setStencilReferenceValue(refNum, readMask, writeMask); _stencilRefNum = refNum; _stencilReadMask = readMask; _stencilWriteMask = writeMask; } return this; } public function setStencilActions(triangleFace : String = 'frontAndBack', compareMode : String = 'always', actionOnBothPass : String = 'keep', actionOnDepthFail : String = 'keep', actionOnDepthPassStencilFail : String = 'keep') : Context3DResource { if (triangleFace != _stencilTriangleFace || compareMode != _stencilCompareMode || actionOnBothPass != _stencilActionOnBothPass || actionOnDepthFail != _stencilActionOnDepthFail || actionOnDepthPassStencilFail != _stencilActionOnDepthPassStencilFail ) { _context.setStencilActions( triangleFace, compareMode, actionOnBothPass, actionOnDepthFail, actionOnDepthPassStencilFail ); _stencilTriangleFace = triangleFace; _stencilCompareMode = compareMode; _stencilActionOnBothPass = actionOnBothPass; _stencilActionOnDepthFail = actionOnDepthFail; _stencilActionOnDepthPassStencilFail = actionOnDepthPassStencilFail; } return this; } } }
Add getter on context (minko_render namespace)
Add getter on context (minko_render namespace)
ActionScript
mit
aerys/minko-as3
912b4e5c23ae6b1abd2ae0cea2594df766f6d63c
src/aerys/minko/scene/controller/TransformController.as
src/aerys/minko/scene/controller/TransformController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; import mx.olap.aggregators.MaxAggregator; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private static const FLAG_NONE : uint = 0; private static const FLAG_INIT_LOCAL_TO_WORLD : uint = 1; private static const FLAG_INIT_WORLD_TO_LOCAL : uint = 2; private static const FLAG_SYNCHRONIZE_TRANSFORMS : uint = 4; private static const FLAG_LOCK_TRANSFORMS : uint = 8; private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _flags : Vector.<uint>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateRootLocalToWorld(nodeId : uint = 0) : void { var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[nodeId]; var rootFlags : uint = _flags[nodeId]; if (rootTransform._hasChanged || !(rootFlags & FLAG_INIT_LOCAL_TO_WORLD)) { if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.lock(); rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.unlock(); rootTransform._hasChanged = false; _flags[nodeId] |= FLAG_INIT_LOCAL_TO_WORLD; root.localToWorldTransformChanged.execute(root, rootLocalToWorld); if (rootFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var rootWorldToLocal : Matrix4x4 = _worldToLocalTransforms[nodeId] || (_worldToLocalTransforms[nodeId] = new Matrix4x4()); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.lock(); rootWorldToLocal.copyFrom(rootLocalToWorld).invert(); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.unlock(); } } } private function updateLocalToWorld(nodeId : uint = 0, targetNodeId : int = -1) : void { var numNodes : uint = _transforms.length; var subtreeMax : uint = nodeId; updateRootLocalToWorld(nodeId); if (nodeId == targetNodeId) return; while (nodeId < numNodes) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged; localToWorld._hasChanged = false; if (lastChildId > subtreeMax) subtreeMax = lastChildId; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !(childFlags & FLAG_INIT_LOCAL_TO_WORLD); if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.lock(); childLocalToWorld .copyFrom(childTransform) .append(localToWorld); if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.unlock(); childTransform._hasChanged = false; _flags[childId] |= FLAG_INIT_LOCAL_TO_WORLD; child.localToWorldTransformChanged.execute(child, childLocalToWorld); if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId] || (_worldToLocalTransforms[childId] = new Matrix4x4()); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.lock(); childWorldToLocal.copyFrom(childLocalToWorld).invert(); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.unlock(); } if (childId == targetNodeId) return; } } if (targetNodeId >= 0 && nodeId && nodeId >= subtreeMax) { // jump to the first brother who has children var parentId : uint = _parentId[nodeId]; nodeId = _firstChildId[parentId]; while (!_numChildren[nodeId] && nodeId < subtreeMax) ++nodeId; if (nodeId >= subtreeMax) return ; nodeId = _firstChildId[nodeId]; } else ++nodeId; } } private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void { var dirtyRoot : int = -1; var tmpNodeId : int = nodeId; while (tmpNodeId >= 0) { if ((_transforms[tmpNodeId] as Matrix4x4)._hasChanged || !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD)) dirtyRoot = tmpNodeId; tmpNodeId = _parentId[tmpNodeId]; } if (dirtyRoot >= 0) updateLocalToWorld(dirtyRoot, nodeId); } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _flags = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function getNodeId(node : ISceneNode) : uint { if (_invalidList || !(node in _nodeToId)) updateTransformsList(); return _nodeToId[node]; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; var oldNodeToId : Dictionary = _nodeToId; var oldInitialized : Vector.<uint> = _flags; var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms; var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _flags = new <uint>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; if (oldNodeToId && node in oldNodeToId) { var oldNodeId : uint = oldNodeToId[node]; _localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId]; _worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId]; _flags[nodeId] = oldInitialized[oldNodeId]; } else { _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _worldToLocalTransforms[nodeId] = null; _flags[nodeId] = FLAG_NONE; } if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) { worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; } } if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); var flags : uint = _flags[nodeId]; if (!(flags & FLAG_INIT_WORLD_TO_LOCAL)) { _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.lock(); worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.unlock(); } return worldToLocalTransform; } public function setSharedLocalToWorldTransformReference(node : ISceneNode, matrix : Matrix4x4) : void { var nodeId : uint = getNodeId(node); if (_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD) matrix.copyFrom(_localToWorldTransforms[nodeId]); _localToWorldTransforms[nodeId] = matrix; } public function setSharedWorldToLocalTransformReference(node : ISceneNode, matrix : Matrix4x4) : void { var nodeId : uint = getNodeId(node); if (_flags[nodeId] & FLAG_INIT_WORLD_TO_LOCAL) matrix.copyFrom(_worldToLocalTransforms[nodeId]); _worldToLocalTransforms[nodeId] = matrix; } public function synchronizeTransforms(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_SYNCHRONIZE_TRANSFORMS : _flags[nodeId] & ~FLAG_SYNCHRONIZE_TRANSFORMS; } public function lockTransformsBeforeUpdate(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_LOCK_TRANSFORMS : _flags[nodeId] & ~FLAG_LOCK_TRANSFORMS; } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; import mx.olap.aggregators.MaxAggregator; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private static const FLAG_NONE : uint = 0; private static const FLAG_INIT_LOCAL_TO_WORLD : uint = 1; private static const FLAG_INIT_WORLD_TO_LOCAL : uint = 2; private static const FLAG_SYNCHRONIZE_TRANSFORMS : uint = 4; private static const FLAG_LOCK_TRANSFORMS : uint = 8; private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _flags : Vector.<uint>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateRootLocalToWorld(nodeId : uint = 0) : void { var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[nodeId]; var rootFlags : uint = _flags[nodeId]; if (rootTransform._hasChanged || !(rootFlags & FLAG_INIT_LOCAL_TO_WORLD)) { if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.lock(); rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.unlock(); rootTransform._hasChanged = false; rootFlags = (rootFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (rootFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var rootWorldToLocal : Matrix4x4 = _worldToLocalTransforms[nodeId] || (_worldToLocalTransforms[nodeId] = new Matrix4x4()); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.lock(); rootWorldToLocal.copyFrom(rootLocalToWorld).invert(); rootFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.unlock(); } _flags[nodeId] = rootFlags; root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } } private function updateLocalToWorld(nodeId : uint = 0, targetNodeId : int = -1) : void { var numNodes : uint = _transforms.length; var subtreeMax : uint = nodeId; updateRootLocalToWorld(nodeId); if (nodeId == targetNodeId) return; while (nodeId < numNodes) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged; localToWorld._hasChanged = false; if (lastChildId > subtreeMax) subtreeMax = lastChildId; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !(childFlags & FLAG_INIT_LOCAL_TO_WORLD); if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.lock(); childLocalToWorld .copyFrom(childTransform) .append(localToWorld); if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.unlock(); childTransform._hasChanged = false; childFlags = (childFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId] || (_worldToLocalTransforms[childId] = new Matrix4x4()); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.lock(); childWorldToLocal.copyFrom(childLocalToWorld).invert(); childFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.unlock(); } _flags[childId] = childFlags; child.localToWorldTransformChanged.execute(child, childLocalToWorld); if (childId == targetNodeId) return; } } if (targetNodeId >= 0 && nodeId && nodeId >= subtreeMax) { // jump to the first brother who has children var parentId : uint = _parentId[nodeId]; nodeId = _firstChildId[parentId]; while (!_numChildren[nodeId] && nodeId < subtreeMax) ++nodeId; if (nodeId >= subtreeMax) return ; nodeId = _firstChildId[nodeId]; } else ++nodeId; } } private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void { var dirtyRoot : int = -1; var tmpNodeId : int = nodeId; while (tmpNodeId >= 0) { if ((_transforms[tmpNodeId] as Matrix4x4)._hasChanged || !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD)) dirtyRoot = tmpNodeId; tmpNodeId = _parentId[tmpNodeId]; } if (dirtyRoot >= 0) updateLocalToWorld(dirtyRoot, nodeId); } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _flags = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function getNodeId(node : ISceneNode) : uint { if (_invalidList || !(node in _nodeToId)) updateTransformsList(); return _nodeToId[node]; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; var oldNodeToId : Dictionary = _nodeToId; var oldInitialized : Vector.<uint> = _flags; var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms; var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _flags = new <uint>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; if (oldNodeToId && node in oldNodeToId) { var oldNodeId : uint = oldNodeToId[node]; _localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId]; _worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId]; _flags[nodeId] = oldInitialized[oldNodeId]; } else { _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _worldToLocalTransforms[nodeId] = null; _flags[nodeId] = FLAG_NONE; } if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) { worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; } } if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); var flags : uint = _flags[nodeId]; if (!(flags & FLAG_INIT_WORLD_TO_LOCAL)) { _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.lock(); worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.unlock(); } return worldToLocalTransform; } public function setSharedLocalToWorldTransformReference(node : ISceneNode, matrix : Matrix4x4) : void { var nodeId : uint = getNodeId(node); if (_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD) matrix.copyFrom(_localToWorldTransforms[nodeId]); _localToWorldTransforms[nodeId] = matrix; } public function setSharedWorldToLocalTransformReference(node : ISceneNode, matrix : Matrix4x4) : void { var nodeId : uint = getNodeId(node); if (_flags[nodeId] & FLAG_INIT_WORLD_TO_LOCAL) matrix.copyFrom(_worldToLocalTransforms[nodeId]); _worldToLocalTransforms[nodeId] = matrix; } public function synchronizeTransforms(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_SYNCHRONIZE_TRANSFORMS : _flags[nodeId] & ~FLAG_SYNCHRONIZE_TRANSFORMS; } public function lockTransformsBeforeUpdate(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_LOCK_TRANSFORMS : _flags[nodeId] & ~FLAG_LOCK_TRANSFORMS; } } }
fix TransformController.updateRootLocalToWorld() and TransformController.updateLocalToWorld() to update the node's flags properly in order to make sure world to local is not still marked as init. when local to world has changed the ISceneNode.localToWorldChanged signal will also be called after world to local has been updated (if required) in order to avoid a race condition when calling TransformController.getWorldToLocalTransform(node) in one of this signal callbacks
fix TransformController.updateRootLocalToWorld() and TransformController.updateLocalToWorld() to update the node's flags properly in order to make sure world to local is not still marked as init. when local to world has changed the ISceneNode.localToWorldChanged signal will also be called after world to local has been updated (if required) in order to avoid a race condition when calling TransformController.getWorldToLocalTransform(node) in one of this signal callbacks
ActionScript
mit
aerys/minko-as3
76a219e2f1489d85b246e686004b32aa5a6f4900
test/src/FRESteamWorksTest.as
test/src/FRESteamWorksTest.as
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; private var _appId:uint; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); addButton("List subscribed files", enumerateSubscribedFiles); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { //Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); _appId = Steamworks.getAppID(); log("App ID: " + _appId); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp()); log("getFileCount() == "+Steamworks.getFileCount()); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt')); log("getDLCCount() == " + Steamworks.getDLCCount()); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); } private function enumerateSubscribedFiles(e:Event = null):void { if(!Steamworks.isReady) return; log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0)); } private var id:String; private function onSteamResponse(e:SteamEvent):void{ switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; case SteamConstants.RESPONSE_OnPublishWorkshopFile: log("RESPONSE_OnPublishWorkshopFile: " + e.response); var file:String = Steamworks.publishWorkshopFileResult(); log("File published as " + file); log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file)); break; case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles: log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response); var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult(); log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults); for(var i:int = 0; i < result.resultsReturned; i++) { id = result.publishedFileId[i]; var apiCall:Boolean = Steamworks.getPublishedFileDetails(result.publishedFileId[i]); log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ") - " + apiCall); } break; case SteamConstants.RESPONSE_OnGetPublishedFileDetails: log("RESPONSE_OnGetPublishedFileDetails: " + e.response); var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id); log("Result for " + id + ": " + res); if(res) log("File: " + res.fileName + ", handle: " + res.fileHandle); break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xccccccc); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); }); button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); }); var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; private var _appId:uint; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); addButton("List subscribed files", enumerateSubscribedFiles); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { //Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); _appId = Steamworks.getAppID(); log("App ID: " + _appId); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp()); log("getFileCount() == "+Steamworks.getFileCount()); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt')); log("getDLCCount() == " + Steamworks.getDLCCount()); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); } private function enumerateSubscribedFiles(e:Event = null):void { if(!Steamworks.isReady) return; log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0)); } private var id:String; private var handle:String; private function onSteamResponse(e:SteamEvent):void{ var apiCall:Boolean; switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; case SteamConstants.RESPONSE_OnPublishWorkshopFile: log("RESPONSE_OnPublishWorkshopFile: " + e.response); var file:String = Steamworks.publishWorkshopFileResult(); log("File published as " + file); log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file)); break; case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles: log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response); var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult(); log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults); for(var i:int = 0; i < result.resultsReturned; i++) { id = result.publishedFileId[i]; apiCall = Steamworks.getPublishedFileDetails(result.publishedFileId[i]); log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ") - " + apiCall); } break; case SteamConstants.RESPONSE_OnGetPublishedFileDetails: log("RESPONSE_OnGetPublishedFileDetails: " + e.response); var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id); log("Result for " + id + ": " + res); if(res) { log("File: " + res.fileName + ", handle: " + res.fileHandle); handle = res.fileHandle; apiCall = Steamworks.UGCDownload(res.fileHandle, 0); log("UGCDownload(...) == " + apiCall); } break; case SteamConstants.RESPONSE_OnUGCDownload: log("RESPONSE_OnUGCDownload: " + e.response); var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle); log("Result for " + handle + ": " + ugcResult); if(ugcResult) { log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size); var ba:ByteArray = new ByteArray(); ba.length = ugcResult.size; apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ba.length, 0, ba); log("UGCRead(...) == " + apiCall); if(apiCall) { log("Result length: " + ba.position + "//" + ba.length); log("Result: " + ba.readUTFBytes(ugcResult.size)); } break; } default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xccccccc); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); }); button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); }); var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
Add UGCDownload/UGCRead tests
Add UGCDownload/UGCRead tests
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
d65dc84d1b919397c15ea99111199967773b7f89
src/as/com/threerings/util/Integer.as
src/as/com/threerings/util/Integer.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { /** * Equivalent to java.lang.Integer. */ // Unfortunately, I think this is necessary. // I was going to remove this class and just make the streaming stuff // autotranslate between int <--> java.lang.Integer and // Number <--> java.lang.Double. However, a Number object that refers // to an integer value is actually an int. Yes, it's totally fucked. public class Integer implements Equalable, Boxed { public static function valueOf (val :int) :Integer { return new Integer(val); } /** * Access the immutable value. */ public function get value () :int { return _value; } /** * Constructor. */ public function Integer (intValue :int) { _value = intValue; } // from Equalable public function equals (other :Object) :Boolean { return (other is Integer) && (_value === (other as Integer).value); } // from Boxed public function unbox () :Object { return _value; } // cannot use the override keyword on toString() because actionscript is stupid public function toString () :String { return _value.toString(); } /** * Compares to int values in an overflow safe manner. */ public static function compare (val1 :int, val2 :int) :int { return (val1 > val2) ? 1 : (val1 == val2 ? 0 : -1); } protected var _value :int; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { /** * Equivalent to java.lang.Integer. */ // Unfortunately, I think this is necessary. // I was going to remove this class and just make the streaming stuff // autotranslate between int <--> java.lang.Integer and // Number <--> java.lang.Double. However, a Number object that refers // to an integer value is actually an int. Yes, it's totally fucked. public class Integer implements Equalable, Boxed { public static function valueOf (val :int) :Integer { return new Integer(val); } /** * Access the immutable value. */ public function get value () :int { return _value; } /** * Constructor. */ public function Integer (intValue :int) { _value = intValue; } // from Equalable public function equals (other :Object) :Boolean { return (other is Integer) && (_value === (other as Integer).value); } // from Boxed public function unbox () :Object { return _value; } // cannot use the override keyword on toString() because actionscript is stupid public function toString () :String { return _value.toString(); } /** * Compares two int values in an overflow safe manner. */ public static function compare (val1 :int, val2 :int) :int { return (val1 > val2) ? 1 : (val1 == val2 ? 0 : -1); } protected var _value :int; } }
Fix typo.
Fix typo. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5754 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
479a5ae2b027860b1aa80d06e5d619d3c26807ac
plugins/bitrateDetectionPlugin/src/com/kaltura/kdpfl/plugin/component/BitrateDetectionMediator.as
plugins/bitrateDetectionPlugin/src/com/kaltura/kdpfl/plugin/component/BitrateDetectionMediator.as
package com.kaltura.kdpfl.plugin.component { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.SequenceProxy; import com.kaltura.kdpfl.model.type.EnableType; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.types.KalturaMediaType; import com.kaltura.vo.KalturaMediaEntry; import flash.display.Loader; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.TimerEvent; import flash.net.URLRequest; import flash.utils.Timer; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class BitrateDetectionMediator extends Mediator { public static var NAME:String = "bitrateDetectionMediator"; /** * Flag indicating autoPlay flashvar was true */ private var _wasAutoPlay:Boolean = false; /** * Flag indicating singleAutoPlay was true */ private var _wasSingleAutoPlay:Boolean = false; /** * The url loader */ private var _loader:Loader; /** * average download speed */ private var _avgSpeed:Number = 0; /** * counter for progress events, will be used to calculate average speed */ private var _progressCount:int; /** * timer for the download process */ private var _downloadTimer:Timer; /** * startTime of the download process */ private var _startTime:Number; /** * Indicating if player has already played */ private var _playedPlayed:Boolean = false; private var _configProxy:ConfigProxy; private var _prevTime:Number; private var _prevBytesLoaded:int; private var _forceBitrate:int; private var _viewComp:bitrateDetectionPluginCode; public function BitrateDetectionMediator(viewComponentObject:Object = null , forceBitrate:int = 0) { _forceBitrate = forceBitrate; _viewComp = viewComponentObject as bitrateDetectionPluginCode; super(NAME, viewComponentObject); } override public function listNotificationInterests():Array { return [ NotificationType.DO_SWITCH, NotificationType.KDP_EMPTY, NotificationType.KDP_READY, NotificationType.PLAYER_PLAYED, NotificationType.MEDIA_READY ]; } private var _bandwidth:Number = 0; private var _bandwidthByUser:Number = 0; override public function handleNotification(notification:INotification):void { switch (notification.getName()) { //in case the user switched the flavor manually case NotificationType.DO_SWITCH: _bandwidthByUser = int(notification.getBody()) break; case NotificationType.MEDIA_READY: if(_bandwidthByUser) { sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidthByUser}); return; } if(_bandwidth) sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidth}); break; case NotificationType.KDP_EMPTY: case NotificationType.KDP_READY: var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; if (!mediaProxy.vo.entry || ((mediaProxy.vo.entry is KalturaMediaEntry) && (int(mediaProxy.vo.entry.mediaType)==KalturaMediaType.IMAGE))) return; if (_viewComp.runPreCheck) { if (mediaProxy.vo.kalturaMediaFlavorArray && mediaProxy.vo.kalturaMediaFlavorArray.length) { var highBR:int = mediaProxy.vo.kalturaMediaFlavorArray[mediaProxy.vo.kalturaMediaFlavorArray.length - 1].bitrate; if ((highBR <= mediaProxy.vo.preferedFlavorBR) || (highBR - mediaProxy.vo.preferedFlavorBR)<=(highBR * 0.2)) { trace ("***** no BW CHECK***"); //// if the last preferred bitrate is higher or equals (with 20% error range) to the current highest bitrate, //no need to perform BW check return; } } } _configProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy; startDownload(); break; case NotificationType.PLAYER_PLAYED: if(_bandwidth) return; _playedPlayed = true; break; } } /** * Start a download process to find the preferred bitrate * */ public function startDownload() : void { trace ("bitrate detection: start download"); if (!_viewComp.downloadUrl) return; var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; //disable autoPlay - will change it back once the bitrate detection will finish if (_configProxy.vo.flashvars.autoPlay == "true") { trace ("bitrate detection: was auto play"); _configProxy.vo.flashvars.autoPlay = "false"; _wasAutoPlay = true; } if (mediaProxy.vo.singleAutoPlay) { mediaProxy.vo.singleAutoPlay = false; _wasSingleAutoPlay = true; } _startTime = ( new Date( ) ).getTime( ); _progressCount = 0; _prevTime = _startTime; _prevBytesLoaded = 0; _loader = new Loader( ); _loader.contentLoaderInfo.addEventListener( Event.COMPLETE, downloadComplete ); _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress); _loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler ); _downloadTimer = new Timer (_viewComp.downloadTimeoutMS, 1); _downloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete); sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: false, enableType: EnableType.FULL}); sendNotification( NotificationType.SWITCHING_CHANGE_STARTED, {newIndex: -2, newBitrate: null}); _loader.load( new URLRequest( _viewComp.downloadUrl + "?" + ( Math.random( ) * 100000 )) ); _downloadTimer.start(); } /** * on download progress- calculate average speed * @param event * */ private function onProgress (event:ProgressEvent):void { var curTime:Number = ( new Date( ) ).getTime( ); _progressCount++; if (event.bytesLoaded!=0) { var totalTime:Number =( curTime - _startTime ) / 1000; var totalKB:Number = event.bytesLoaded / 1024; _avgSpeed = totalKB / totalTime; } _prevTime = curTime; _prevBytesLoaded = event.bytesLoaded; } /** * download complete handler - set the preferred bitrate, enable GUI * */ private function downloadComplete( e:Event = null):void { _downloadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete); _loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress ); var bitrateVal:int = _avgSpeed * 8; trace("*** preferred bitrate for bitrate detection plugin:", bitrateVal); //for debugging - force a bitrate value to override the calculated one if(_forceBitrate > 0) { bitrateVal = _forceBitrate; } sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: bitrateVal}); _bandwidth = bitrateVal; finishDownloadProcess(); } /** * default timer time has passed, stop listening to progress event and continue the flow * @param event * */ private function onTimerComplete (event:TimerEvent):void { downloadComplete(); } /** * I/O error getting the sample file, release the UI * @param event * */ private function ioErrorHandler(event:IOErrorEvent) : void { //Bypass: ignore #2124 error (loaded file is an unknown type) if (!event.text || event.text.indexOf("Error #2124")==-1) { trace ("bitrate detection i/o error:", event.text); finishDownloadProcess(); } } /** * enable back the GUI. * call Do_Play if we were in auto play and set back relevant flashvars * */ private function finishDownloadProcess():void { //if we changed variables, set them back if (_wasAutoPlay || _wasSingleAutoPlay) { var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; var sequenceProxy:SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy; if (_wasAutoPlay) { _configProxy.vo.flashvars.autoPlay = "true"; } else { mediaProxy.vo.singleAutoPlay = true; } //play if we should have played if (!_playedPlayed && !mediaProxy.vo.isMediaDisabled && !sequenceProxy.vo.isInSequence) { sendNotification(NotificationType.DO_PLAY); } } sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: true, enableType: EnableType.FULL}); } } }
package com.kaltura.kdpfl.plugin.component { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.SequenceProxy; import com.kaltura.kdpfl.model.type.EnableType; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.types.KalturaMediaType; import com.kaltura.vo.KalturaMediaEntry; import flash.display.Loader; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.TimerEvent; import flash.net.URLRequest; import flash.utils.Timer; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class BitrateDetectionMediator extends Mediator { public static var NAME:String = "bitrateDetectionMediator"; /** * Flag indicating autoPlay flashvar was true */ private var _wasAutoPlay:Boolean = false; /** * Flag indicating singleAutoPlay was true */ private var _wasSingleAutoPlay:Boolean = false; /** * The url loader */ private var _loader:Loader; /** * average download speed */ private var _avgSpeed:Number = 0; /** * counter for progress events, will be used to calculate average speed */ private var _progressCount:int; /** * timer for the download process */ private var _downloadTimer:Timer; /** * startTime of the download process */ private var _startTime:Number; /** * Indicating if player has already played */ private var _playedPlayed:Boolean = false; private var _configProxy:ConfigProxy; private var _prevTime:Number; private var _prevBytesLoaded:int; private var _forceBitrate:int; private var _viewComp:bitrateDetectionPluginCode; public function BitrateDetectionMediator(viewComponentObject:Object = null , forceBitrate:int = 0) { _forceBitrate = forceBitrate; _viewComp = viewComponentObject as bitrateDetectionPluginCode; super(NAME, viewComponentObject); } override public function listNotificationInterests():Array { return [ NotificationType.DO_SWITCH, NotificationType.KDP_EMPTY, NotificationType.KDP_READY, NotificationType.PLAYER_PLAYED, NotificationType.MEDIA_READY ]; } private var _bandwidth:Number = 0; private var _bandwidthByUser:Number = 0; override public function handleNotification(notification:INotification):void { switch (notification.getName()) { //in case the user switched the flavor manually case NotificationType.DO_SWITCH: _bandwidthByUser = int(notification.getBody()) break; case NotificationType.MEDIA_READY: if(_bandwidthByUser) { sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidthByUser}); return; } if(_bandwidth) sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidth}); break; case NotificationType.KDP_EMPTY: case NotificationType.KDP_READY: var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; if (!mediaProxy.vo.entry || ((mediaProxy.vo.entry is KalturaMediaEntry) && (int(mediaProxy.vo.entry.mediaType)==KalturaMediaType.IMAGE))) return; if (_viewComp.runPreCheck) { if (mediaProxy.vo.kalturaMediaFlavorArray && mediaProxy.vo.kalturaMediaFlavorArray.length) { var highBR:int = mediaProxy.vo.kalturaMediaFlavorArray[mediaProxy.vo.kalturaMediaFlavorArray.length - 1].bitrate; if (0.8 * highBR <= mediaProxy.vo.preferedFlavorBR) { trace ("***** no BW CHECK***"); //// if the last preferred bitrate is higher or equals (with 20% error range) to the current highest bitrate, //no need to perform BW check return; } } } _configProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy; startDownload(); break; case NotificationType.PLAYER_PLAYED: if(_bandwidth) return; _playedPlayed = true; break; } } /** * Start a download process to find the preferred bitrate * */ public function startDownload() : void { trace ("bitrate detection: start download"); if (!_viewComp.downloadUrl) return; var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; //disable autoPlay - will change it back once the bitrate detection will finish if (_configProxy.vo.flashvars.autoPlay == "true") { trace ("bitrate detection: was auto play"); _configProxy.vo.flashvars.autoPlay = "false"; _wasAutoPlay = true; } if (mediaProxy.vo.singleAutoPlay) { mediaProxy.vo.singleAutoPlay = false; _wasSingleAutoPlay = true; } _startTime = ( new Date( ) ).getTime( ); _progressCount = 0; _prevTime = _startTime; _prevBytesLoaded = 0; _loader = new Loader( ); _loader.contentLoaderInfo.addEventListener( Event.COMPLETE, downloadComplete ); _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress); _loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler ); _downloadTimer = new Timer (_viewComp.downloadTimeoutMS, 1); _downloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete); sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: false, enableType: EnableType.FULL}); sendNotification( NotificationType.SWITCHING_CHANGE_STARTED, {newIndex: -2, newBitrate: null}); _loader.load( new URLRequest( _viewComp.downloadUrl + "?" + ( Math.random( ) * 100000 )) ); _downloadTimer.start(); } /** * on download progress- calculate average speed * @param event * */ private function onProgress (event:ProgressEvent):void { var curTime:Number = ( new Date( ) ).getTime( ); _progressCount++; if (event.bytesLoaded!=0) { var totalTime:Number =( curTime - _startTime ) / 1000; var totalKB:Number = event.bytesLoaded / 1024; _avgSpeed = totalKB / totalTime; } _prevTime = curTime; _prevBytesLoaded = event.bytesLoaded; } /** * download complete handler - set the preferred bitrate, enable GUI * */ private function downloadComplete( e:Event = null):void { _downloadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete); _loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress ); var bitrateVal:int = _avgSpeed * 8; trace("*** preferred bitrate for bitrate detection plugin:", bitrateVal); //for debugging - force a bitrate value to override the calculated one if(_forceBitrate > 0) { bitrateVal = _forceBitrate; } sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: bitrateVal}); _bandwidth = bitrateVal; finishDownloadProcess(); } /** * default timer time has passed, stop listening to progress event and continue the flow * @param event * */ private function onTimerComplete (event:TimerEvent):void { downloadComplete(); } /** * I/O error getting the sample file, release the UI * @param event * */ private function ioErrorHandler(event:IOErrorEvent) : void { //Bypass: ignore #2124 error (loaded file is an unknown type) if (!event.text || event.text.indexOf("Error #2124")==-1) { trace ("bitrate detection i/o error:", event.text); finishDownloadProcess(); } } /** * enable back the GUI. * call Do_Play if we were in auto play and set back relevant flashvars * */ private function finishDownloadProcess():void { //if we changed variables, set them back if (_wasAutoPlay || _wasSingleAutoPlay) { var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; var sequenceProxy:SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy; if (_wasAutoPlay) { _configProxy.vo.flashvars.autoPlay = "true"; } else { mediaProxy.vo.singleAutoPlay = true; } //play if we should have played if (!_playedPlayed && !mediaProxy.vo.isMediaDisabled && !sequenceProxy.vo.isInSequence) { sendNotification(NotificationType.DO_PLAY); } } sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: true, enableType: EnableType.FULL}); } } }
fix condition
qnd: fix condition git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@91100 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
56ea6f07e1262a86c60e8d42fa1d12cbf1f7f9c8
com/segonquart/menuColourIdiomes.as
com/segonquart/menuColourIdiomes.as
import mx.transitions.easing.*; import com.mosesSupposes.fuse.*; class menuColouridiomes extends MoviieClip { public var cat, es, en ,fr:MovieClip; public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr"); function menuColourIdiomes ():Void { this.onRollOver = this.mOver; this.onRollOut = this.mOut; this.onRelease =this.mOver; } private function mOver():Void { arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc"); } private function mOut():Void { arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc"); } }
import mx.transitions.easing.*; import com.mosesSupposes.fuse.*; class menuColouridiomes extends MoviieClip { public var cat, es, en ,fr:MovieClip; public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr"); function menuColourIdiomes ():Void { this.onRollOver = this.mOver; this.onRollOut = this.mOut; this.onRelease =this.mOver; } private function mOver() { arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc"); } private function mOut() { arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc"); } }
Update menuColourIdiomes.as
Update menuColourIdiomes.as
ActionScript
bsd-3-clause
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
94a189babc6f74663819457b9d148f4987e70d9c
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/controllers/DropDownListController.as
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/controllers/DropDownListController.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads.controllers { import flash.display.DisplayObject; import flash.geom.Point; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadController; import org.apache.flex.core.ISelectionModel; import org.apache.flex.core.IStrand; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.beads.IDropDownListView; /** * The DropDownListController class is the controller for * org.apache.flex.html.DropDownList. Controllers * watch for events from the interactive portions of a View and * update the data model or dispatch a semantic event. * This controller watches for the click event and displays the * dropdown/popup, and watches the dropdown/popup for change events * and updates the selection model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DropDownListController implements IBead, IBeadController { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DropDownListController() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("click", clickHandler); } private function clickHandler(event:Event):void { var viewBead:IDropDownListView = _strand.getBeadByType(IDropDownListView) as IDropDownListView; viewBead.popUpVisible = true; var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel; var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel; popUpModel.dataProvider = selectionModel.dataProvider; popUpModel.selectedIndex = selectionModel.selectedIndex; DisplayObject(viewBead.popUp).width = DisplayObject(_strand).width; var pt:Point = new Point(DisplayObject(_strand).x, DisplayObject(_strand).y + DisplayObject(_strand).height); pt = DisplayObject(_strand).parent.localToGlobal(pt); DisplayObject(viewBead.popUp).x = pt.x; DisplayObject(viewBead.popUp).y = pt.y; IEventDispatcher(viewBead.popUp).addEventListener("change", changeHandler); } private function changeHandler(event:Event):void { var viewBead:IDropDownListView = _strand.getBeadByType(IDropDownListView) as IDropDownListView; viewBead.popUpVisible = false; var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel; var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel; selectionModel.selectedIndex = popUpModel.selectedIndex; IEventDispatcher(_strand).dispatchEvent(new Event("change")); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads.controllers { import flash.display.DisplayObject; import flash.geom.Point; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadController; import org.apache.flex.core.ISelectionModel; import org.apache.flex.core.IStrand; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.beads.IDropDownListView; /** * The DropDownListController class is the controller for * org.apache.flex.html.DropDownList. Controllers * watch for events from the interactive portions of a View and * update the data model or dispatch a semantic event. * This controller watches for the click event and displays the * dropdown/popup, and watches the dropdown/popup for change events * and updates the selection model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DropDownListController implements IBead, IBeadController { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DropDownListController() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("click", clickHandler); } private function clickHandler(event:Event):void { var viewBead:IDropDownListView = _strand.getBeadByType(IDropDownListView) as IDropDownListView; viewBead.popUpVisible = true; var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel; var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel; DisplayObject(viewBead.popUp).width = DisplayObject(_strand).width; popUpModel.dataProvider = selectionModel.dataProvider; popUpModel.selectedIndex = selectionModel.selectedIndex; var pt:Point = new Point(DisplayObject(_strand).x, DisplayObject(_strand).y + DisplayObject(_strand).height); pt = DisplayObject(_strand).parent.localToGlobal(pt); DisplayObject(viewBead.popUp).x = pt.x; DisplayObject(viewBead.popUp).y = pt.y; IEventDispatcher(viewBead.popUp).addEventListener("change", changeHandler); } private function changeHandler(event:Event):void { var viewBead:IDropDownListView = _strand.getBeadByType(IDropDownListView) as IDropDownListView; viewBead.popUpVisible = false; var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel; var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel; selectionModel.selectedIndex = popUpModel.selectedIndex; IEventDispatcher(_strand).dispatchEvent(new Event("change")); } } }
fix sizing of dropdownlist popup
fix sizing of dropdownlist popup
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
bd2e20dec85b9246810a90735cfc0acb60de1502
src/aerys/minko/scene/controller/AbstractController.as
src/aerys/minko/scene/controller/AbstractController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_scene; import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.Signal; import flash.display.BitmapData; import flash.utils.getQualifiedClassName; /** * Controllers work on scene nodes to modify and update them. They offer the best * way to add any kind of behavior on one or multiple scene nodes. They can be used * to create animations, add physics, artificial intelligence... * * @author Jean-Marc Le Roux * */ public class AbstractController { private var _targetType : Class = null; private var _targets : Vector.<ISceneNode> = new <ISceneNode>[]; private var _targetAdded : Signal = new Signal('AbstractController.targetAdded'); private var _targetRemoved : Signal = new Signal('AbstractController.targetRemoved'); /** * The number of scene nodes targeted by this very controller. * @return * */ public function get numTargets() : uint { return _targets.length; } /** * The signal executed when a target is added to the controller. * @return * */ public function get targetAdded() : Signal { return _targetAdded; } /** * The signal executed when a target is removed from the controller. * @return * */ public function get targetRemoved() : Signal { return _targetRemoved; } public function AbstractController(targetType : Class = null) { _targetType = targetType || ISceneNode; } /** * Add a target to the controller. * @param target * */ minko_scene function addTarget(target : ISceneNode) : void { if (_targetType && !(target is _targetType)) { throw new Error( "Controller '" + getQualifiedClassName(this) + " cannot target objects from class '" + getQualifiedClassName(target) + "'." ); } _targets.push(target); _targetAdded.execute(this, target); } /** * Remove a target from the controller. * @param target * */ minko_scene function removeTarget(target : ISceneNode) : void { var index : int = _targets.indexOf(target); var numTargets : int = _targets.length - 1; if (index < 0) throw new Error(); _targets[index] = _targets[numTargets]; _targets.length = numTargets; _targetRemoved.execute(this, target); } /** * Get the target at the specified index. * @param index * @return * */ public function getTarget(index : uint) : ISceneNode { return _targets[index]; } public function clone() : AbstractController { throw new Error("The method AbstractController.clone() must be overriden."); } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_scene; import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.Signal; import flash.display.BitmapData; import flash.utils.getQualifiedClassName; /** * Controllers work on scene nodes to modify and update them. They offer the best * way to add any kind of behavior on one or multiple scene nodes. They can be used * to create animations, add physics, artificial intelligence... * * @author Jean-Marc Le Roux * */ public class AbstractController { private var _targetType : Class = null; private var _targets : Vector.<ISceneNode> = new <ISceneNode>[]; private var _targetAdded : Signal = new Signal('AbstractController.targetAdded'); private var _targetRemoved : Signal = new Signal('AbstractController.targetRemoved'); /** * The number of scene nodes targeted by this very controller. * @return * */ public function get numTargets() : uint { return _targets.length; } /** * The signal executed when a target is added to the controller. * @return * */ public function get targetAdded() : Signal { return _targetAdded; } /** * The signal executed when a target is removed from the controller. * @return * */ public function get targetRemoved() : Signal { return _targetRemoved; } public function AbstractController(targetType : Class = null) { _targetType = targetType || ISceneNode; } /** * Add a target to the controller. * @param target * */ minko_scene function addTarget(target : ISceneNode) : void { if (_targetType && !(target is _targetType)) { throw new Error( 'Controller \'' + getQualifiedClassName(this) + ' cannot target objects from class \'' + getQualifiedClassName(target) + '\'.' ); } _targets.push(target); _targetAdded.execute(this, target); } /** * Remove a target from the controller. * @param target * */ minko_scene function removeTarget(target : ISceneNode) : void { var index : int = _targets.indexOf(target); var numTargets : int = _targets.length - 1; if (index < 0) throw new Error(); _targets[index] = _targets[numTargets]; _targets.length = numTargets; _targetRemoved.execute(this, target); } /** * Get the target at the specified index. * @param index * @return * */ public function getTarget(index : uint) : ISceneNode { return _targets[index]; } public function clone() : AbstractController { throw new Error('The method AbstractController.clone() must be overriden.'); } } }
fix minor coding style issue in AbstractController
fix minor coding style issue in AbstractController
ActionScript
mit
aerys/minko-as3
5e6235724401e401c19f6bba6c9cb6133abcae3b
src/aerys/minko/scene/controller/camera/CameraController.as
src/aerys/minko/scene/controller/camera/CameraController.as
package aerys.minko.scene.controller.camera { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.Camera; import aerys.minko.scene.node.Scene; import aerys.minko.type.data.DataBindings; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public final class CameraController extends AbstractController { private var _camera : Camera = null; public function CameraController() { super(Camera); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(controller : CameraController, target : Camera) : void { if (_camera != null) throw new Error(); _camera = target; _camera.addedToScene.add(addedToSceneHandler); _camera.removedFromScene.add(removedFromSceneHandler); _camera.worldToLocal.changed.add(worldToLocalChangedHandler); } private function targetRemovedHandler(controller : CameraController, target : Camera) : void { _camera.addedToScene.remove(addedToSceneHandler); _camera.removedFromScene.remove(removedFromSceneHandler); _camera.worldToLocal.changed.remove(worldToLocalChangedHandler); _camera = null; } private function addedToSceneHandler(camera : Camera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; sceneBindings.addProvider(camera.cameraData); sceneBindings.addCallback('viewportWidth', viewportSizeChanged); sceneBindings.addCallback('viewportHeight', viewportSizeChanged); updateProjection(); } private function removedFromSceneHandler(camera : Camera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; sceneBindings.removeProvider(camera.cameraData); sceneBindings.removeCallback('viewportWidth', viewportSizeChanged); sceneBindings.removeCallback('viewportHeight', viewportSizeChanged); } private function worldToLocalChangedHandler(worldToLocal : Matrix4x4, propertyName : String) : void { var cameraData : CameraDataProvider = _camera.cameraData; cameraData.worldToScreen.lock() .copyFrom(_camera.worldToLocal) .append(cameraData.projection) .unlock(); cameraData.screenToWorld.lock() .copyFrom(cameraData.screenToView) .append(_camera.localToWorld) .unlock(); } private function viewportSizeChanged(bindings : DataBindings, key : String, newValue : Object) : void { updateProjection(); } private function updateProjection() : void { var cameraData : CameraDataProvider = _camera.cameraData; var screenToView : Matrix4x4 = cameraData.screenToView; var sceneBindings : DataBindings = Scene(_camera.root).bindings; var viewportWidth : Number = sceneBindings.getProperty('viewportWidth'); var viewportHeight : Number = sceneBindings.getProperty('viewportHeight'); var ratio : Number = viewportWidth / viewportHeight; cameraData.projection.perspectiveFoV(cameraData.fieldOfView, ratio, cameraData.zNear, cameraData.zFar); screenToView.lock() .copyFrom(cameraData.projection) .invert() .unlock(); cameraData.screenToWorld.lock() .copyFrom(cameraData.screenToView) .append(_camera.localToWorld) .unlock(); cameraData.worldToScreen.lock() .copyFrom(_camera.worldToLocal) .append(cameraData.projection) .unlock(); } } }
package aerys.minko.scene.controller.camera { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.Camera; import aerys.minko.scene.node.Scene; import aerys.minko.type.data.DataBindings; import aerys.minko.type.data.IDataProvider; import aerys.minko.type.math.Matrix4x4; public final class CameraController extends AbstractController { private var _camera : Camera = null; public function CameraController() { super(Camera); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(controller : CameraController, target : Camera) : void { if (_camera != null) throw new Error(); _camera = target; _camera.addedToScene.add(addedToSceneHandler); _camera.removedFromScene.add(removedFromSceneHandler); _camera.worldToLocal.changed.add(worldToLocalChangedHandler); } private function targetRemovedHandler(controller : CameraController, target : Camera) : void { _camera.addedToScene.remove(addedToSceneHandler); _camera.removedFromScene.remove(removedFromSceneHandler); _camera.worldToLocal.changed.remove(worldToLocalChangedHandler); _camera = null; } private function addedToSceneHandler(camera : Camera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; sceneBindings.addProvider(camera.cameraData); sceneBindings.addCallback('viewportWidth', viewportSizeChanged); sceneBindings.addCallback('viewportHeight', viewportSizeChanged); camera.cameraData.changed.add(cameraPropertyChangedHandler); updateProjection(); } private function removedFromSceneHandler(camera : Camera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; sceneBindings.removeProvider(camera.cameraData); sceneBindings.removeCallback('viewportWidth', viewportSizeChanged); sceneBindings.removeCallback('viewportHeight', viewportSizeChanged); camera.cameraData.changed.remove(cameraPropertyChangedHandler); } private function worldToLocalChangedHandler(worldToLocal : Matrix4x4, propertyName : String) : void { var cameraData : CameraDataProvider = _camera.cameraData; cameraData.worldToScreen.lock() .copyFrom(_camera.worldToLocal) .append(cameraData.projection) .unlock(); cameraData.screenToWorld.lock() .copyFrom(cameraData.screenToView) .append(_camera.localToWorld) .unlock(); } private function viewportSizeChanged(bindings : DataBindings, key : String, newValue : Object) : void { updateProjection(); } private function cameraPropertyChangedHandler(provider : IDataProvider, property : String) : void { updateProjection(); } private function updateProjection() : void { var cameraData : CameraDataProvider = _camera.cameraData; var screenToView : Matrix4x4 = cameraData.screenToView; var sceneBindings : DataBindings = Scene(_camera.root).bindings; var viewportWidth : Number = sceneBindings.getProperty('viewportWidth'); var viewportHeight : Number = sceneBindings.getProperty('viewportHeight'); var ratio : Number = viewportWidth / viewportHeight; cameraData.projection.perspectiveFoV(cameraData.fieldOfView, ratio, cameraData.zNear, cameraData.zFar); screenToView.lock() .copyFrom(cameraData.projection) .invert() .unlock(); cameraData.screenToWorld.lock() .copyFrom(cameraData.screenToView) .append(_camera.localToWorld) .unlock(); cameraData.worldToScreen.lock() .copyFrom(_camera.worldToLocal) .append(cameraData.projection) .unlock(); } } }
update projection when the camera properties are updated
update projection when the camera properties are updated
ActionScript
mit
aerys/minko-as3
ecc91fd5c0fdef223b3676d80a45626800942f7f
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
package com.kaltura.hls.m2ts { import flash.utils.ByteArray; import flash.net.ObjectEncoding; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; import flash.utils.IDataOutput; import com.hurlant.util.Hex; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Process packetized elementary streams and extract NALUs and other data. */ public class PESProcessor { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor"); } public var types:Object = {}; public var streams:Object = {}; public var lastVideoNALU:NALU = null; public var transcoder:FLVTranscoder = new FLVTranscoder(); public var headerSent:Boolean = false; public var pmtStreamId:int = -1; protected var pendingBuffers:Vector.<Object> = new Vector.<Object>(); protected var pendingLastConvertedIndex:int = 0; public var lastPTS:Number = 0, lastDTS:Number = 0; /** * Given a MPEG timestamp we've seen previously, determine if the new timestamp * has wrapped and correct it to follow the old timestamp. */ static function handleMpegTimestampWrap(newTime:Number, oldTime:Number):Number { while (!isNaN(oldTime) && (Math.abs(newTime - oldTime) > 4294967296)) newTime += (oldTime < newTime) ? -8589934592 : 8589934592; return newTime; } public function logStreams():void { CONFIG::LOGGING { logger.debug("----- PES state -----"); for(var k:* in streams) { logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]); } } } public function clear(clearAACConfig:Boolean = true):void { streams = {}; lastVideoNALU = null; transcoder.clear(clearAACConfig); // Reset PTS/DTS reference. lastPTS = lastDTS = 0; } private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean { // Get the section length. var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3]; // Check the section length for a single PMT. CONFIG::LOGGING { if (sectionLen > 13) { logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one."); } } // Grab the PMT ID. pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF; CONFIG::LOGGING { logger.debug("Saw PMT ID of " + pmtStreamId); } return true; } private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean { var sectionLength:uint; var sectionLimit:uint; var programInfoLength:uint; var type:uint; var pid:uint; var esInfoLength:uint; var seenPIDsByClass:Array; var mediaClass:int; var hasAudio:Boolean = false, hasVideo:Boolean = false; // Set up types. types = []; seenPIDsByClass = []; seenPIDsByClass[MediaClass.VIDEO] = Infinity; seenPIDsByClass[MediaClass.AUDIO] = Infinity; // Process section length and limit. cursor++; sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; if(sectionLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 1"); } return false; } // Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid sectionLimit = cursor + sectionLength; cursor += 7; // And get the program info length. programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; // If not enough data to proceed, bail. if(programInfoLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 2"); } return false; } cursor += programInfoLength; const CRC_SIZE:int = 4; while(cursor < sectionLimit - CRC_SIZE) { type = bytes[cursor++]; pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1]; cursor += 2; mediaClass = MediaClass.calculate(type); if(mediaClass == MediaClass.VIDEO) hasVideo = true if(mediaClass == MediaClass.AUDIO) hasAudio = true // For video & audio, select the lowest PID for each kind. if(mediaClass == MediaClass.OTHER || pid < seenPIDsByClass[mediaClass]) { // Clear a higher PID if present. if(mediaClass != MediaClass.OTHER && seenPIDsByClass[mediaClass] < Infinity) types[seenPIDsByClass[mediaClass]] = -1; types[pid] = type; seenPIDsByClass[mediaClass] = pid; } // Skip the esInfo data. esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; cursor += esInfoLength; } // Cook out header to transcoder. //transcoder.writeHeader(hasAudio, hasVideo); headerSent = true; return true; } public function append(packet:PESPacket):Boolean { // logger.debug("saw packet of " + packet.buffer.length); var b:ByteArray = packet.buffer; b.position = 0; if(b.length < 8) { CONFIG::LOGGING { logger.error("Ignoring too short PES packet, length=" + b.length); } return true; } // Get the start code. var startCode:uint = b.readUnsignedInt(); if((startCode & 0xFFFFFF00) != 0x00000100) { // It could be a program association table. if((startCode & 0xFFFFFF00) == 0x0000b000) { parseProgramAssociationTable(b, 1); return true; } // It could be the program map table. if((startCode & 0xFFFFFC00) == 0x0002b000) { parseProgramMapTable(b, 1); return true; } var tmp:ByteArray = new ByteArray(); tmp.writeInt(startCode); CONFIG::LOGGING { logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true)); } return true; } // Get the stream ID. var streamID:int = startCode & 0xFF; // Get the length. var packetLength:uint = b.readUnsignedShort(); if(packetLength) { if(b.length < packetLength ) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length); } return false; // not enough bytes in packet } } if(b.length < 9) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - too short to read header!"); } return false; } // Read the rest of the header. var cursor:uint = 6; var dataAlignment:Boolean = (b[cursor] & 0x04) != 0; cursor++; var ptsDts:uint = (b[cursor] & 0xc0) >> 6; cursor++; var pesHeaderDataLength:uint = b[cursor]; cursor++; //logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength); var pts:Number = 0, dts:Number = 0; if(ptsDts & 0x02) { // has PTS at least if(cursor + 5 > b.length) return true; pts = b[cursor] & 0x0e; pts *= 128; pts += b[cursor + 1]; pts *= 256; pts += b[cursor + 2] & 0xfe; pts *= 128; pts += b[cursor + 3]; pts *= 256; pts += b[cursor + 4] & 0xfe; pts /= 2; if(ptsDts & 0x01) { // DTS too! if(cursor + 10 > b.length) return true; dts = b[cursor + 5] & 0x0e; dts *= 128; dts += b[cursor + 6]; dts *= 256; dts += b[cursor + 7] & 0xfe; dts *= 128; dts += b[cursor + 8]; dts *= 256; dts += b[cursor + 9] & 0xfe; dts /= 2; } else { //logger.debug("Filling in DTS") dts = pts; } } // Condition PTS and DTS. pts = handleMpegTimestampWrap(pts, lastPTS); lastPTS = pts; dts = handleMpegTimestampWrap(dts, lastDTS); lastDTS = dts; packet.pts = pts; packet.dts = dts; //logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000); cursor += pesHeaderDataLength; if(cursor > b.length) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - ran out of bytes"); } return true; } if(types[packet.packetID] == undefined) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - unknown type"); } return true; } var pes:PESPacketStream; if(streams[packet.packetID] == undefined) { if(dts < 0.0) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - invalid decode timestamp, skipping"); } return true; } pes = new PESPacketStream(); streams[packet.packetID] = pes; } else { pes = streams[packet.packetID]; } if(headerSent == false) { CONFIG::LOGGING { logger.warn("Skipping data that came before PMT"); } return true; } // Note the type at this moment in time. packet.type = types[packet.packetID]; packet.headerLength = cursor; // And process. if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO) { var start:int = NALU.scan(b, cursor, true); if(start == -1 && lastVideoNALU) { CONFIG::LOGGING { logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor); return true; } else if((start - cursor) > 0 && lastVideoNALU) { // Shove into previous buffer. CONFIG::LOGGING { logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } // If it's identical timestamps, accumulate it into the current unit and keep going. if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts) { CONFIG::LOGGING { logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } else { // Submit previous data. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); } // Update NALU state. lastVideoNALU = new NALU(); lastVideoNALU.buffer = new ByteArray(); lastVideoNALU.pts = pts; lastVideoNALU.dts = dts; lastVideoNALU.type = packet.type; lastVideoNALU.buffer.writeBytes(b, cursor); } } else if(types[packet.packetID] == 0x0F) { // It's an AAC stream. pendingBuffers.push(packet.clone()); } else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04) { // It's an MP3 stream. pendingBuffers.push(packet.clone()); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A)."); } } bufferPendingNalus(); return true; } /** * To avoid transcoding all content on flush, we buffer it into FLV * tags as we go. However, they remain undelivered until we can gather * final SPS/PPS information. This method is responsible for * incrementally buffering in the FLV transcoder as we go. */ public function bufferPendingNalus():void { // Iterate and buffer new NALUs. for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++) { if(pendingBuffers[i] is NALU) { transcoder.convert(pendingBuffers[i] as NALU); } else if(pendingBuffers[i] is PESPacket) { var packet:PESPacket = pendingBuffers[i] as PESPacket; if(packet.type == 0x0F) { // It's an AAC stream. transcoder.convertAAC(packet); } else if(packet.type == 0x03 || packet.type == 0x04) { // It's an MP3 stream. Pass through directly. transcoder.convertMP3(packet); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B)."); } } } } // Note the last item we converted so we can avoid duplicating work. pendingLastConvertedIndex = pendingBuffers.length; } public function processAllNalus():void { // Consume any unposted video NALUs. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); lastVideoNALU = null; } // First walk all the video NALUs and get the correct SPS/PPS if(pendingBuffers.length == 0) return; // Then emit SPS/PPS transcoder.emitSPSPPSUnbuffered(); // Complete buffering and emit it all. bufferPendingNalus(); transcoder.emitBufferedTags(); // Don't forget to clear the pending list. pendingBuffers.length = 0; pendingLastConvertedIndex = 0; } } }
package com.kaltura.hls.m2ts { import flash.utils.ByteArray; import flash.net.ObjectEncoding; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; import flash.utils.IDataOutput; import com.hurlant.util.Hex; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Process packetized elementary streams and extract NALUs and other data. */ public class PESProcessor { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor"); } public var types:Object = {}; public var streams:Object = {}; public var lastVideoNALU:NALU = null; public var transcoder:FLVTranscoder = new FLVTranscoder(); public var headerSent:Boolean = false; public var pmtStreamId:int = -1; protected var pendingBuffers:Vector.<Object> = new Vector.<Object>(); protected var pendingLastConvertedIndex:int = 0; public var lastPTS:Number = 0, lastDTS:Number = 0; /** * Given a MPEG timestamp we've seen previously, determine if the new timestamp * has wrapped and correct it to follow the old timestamp. */ static function handleMpegTimestampWrap(newTime:Number, oldTime:Number):Number { while (!isNaN(oldTime) && (Math.abs(newTime - oldTime) > 4294967296)) newTime += (oldTime < newTime) ? -8589934592 : 8589934592; return newTime; } public function logStreams():void { CONFIG::LOGGING { logger.debug("----- PES state -----"); for(var k:* in streams) { logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]); } } } public function clear(clearAACConfig:Boolean = true):void { streams = {}; lastVideoNALU = null; transcoder.clear(clearAACConfig); // Reset PTS/DTS reference. lastPTS = lastDTS = 0; } private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean { // Get the section length. var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3]; // Check the section length for a single PMT. CONFIG::LOGGING { if (sectionLen > 13) { logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one."); } } // Grab the PMT ID. pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF; CONFIG::LOGGING { logger.debug("Saw PMT ID of " + pmtStreamId); } return true; } private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean { var sectionLength:uint; var sectionLimit:uint; var programInfoLength:uint; var type:uint; var pid:uint; var esInfoLength:uint; var seenPIDsByClass:Array; var mediaClass:int; var hasAudio:Boolean = false, hasVideo:Boolean = false; // Set up types. types = []; seenPIDsByClass = []; seenPIDsByClass[MediaClass.VIDEO] = Infinity; seenPIDsByClass[MediaClass.AUDIO] = Infinity; // Process section length and limit. cursor++; sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; if(sectionLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 1"); } return false; } // Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid sectionLimit = cursor + sectionLength; cursor += 7; // And get the program info length. programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; // If not enough data to proceed, bail. if(programInfoLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 2"); } return false; } cursor += programInfoLength; const CRC_SIZE:int = 4; while(cursor < sectionLimit - CRC_SIZE) { type = bytes[cursor++]; pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1]; cursor += 2; mediaClass = MediaClass.calculate(type); if(mediaClass == MediaClass.VIDEO) hasVideo = true if(mediaClass == MediaClass.AUDIO) hasAudio = true // For video & audio, select the lowest PID for each kind. if(mediaClass == MediaClass.OTHER || pid < seenPIDsByClass[mediaClass]) { // Clear a higher PID if present. if(mediaClass != MediaClass.OTHER && seenPIDsByClass[mediaClass] < Infinity) types[seenPIDsByClass[mediaClass]] = -1; types[pid] = type; seenPIDsByClass[mediaClass] = pid; } // Skip the esInfo data. esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; cursor += esInfoLength; } // Cook out header to transcoder. //transcoder.writeHeader(hasAudio, hasVideo); headerSent = true; return true; } public function append(packet:PESPacket):Boolean { // logger.debug("saw packet of " + packet.buffer.length); var b:ByteArray = packet.buffer; b.position = 0; if(b.length < 8) { CONFIG::LOGGING { logger.error("Ignoring too short PES packet, length=" + b.length); } return true; } // Get the start code. var startCode:uint = b.readUnsignedInt(); if((startCode & 0xFFFFFF00) != 0x00000100) { // It could be a program association table. if((startCode & 0xFFFFFF00) == 0x0000b000) { parseProgramAssociationTable(b, 1); return true; } // It could be the program map table. if((startCode & 0xFFFFFC00) == 0x0002b000) { parseProgramMapTable(b, 1); return true; } var tmp:ByteArray = new ByteArray(); tmp.writeInt(startCode); CONFIG::LOGGING { logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true)); } return true; } // Get the stream ID. var streamID:int = startCode & 0xFF; // Get the length. var packetLength:uint = b.readUnsignedShort(); if(packetLength) { if(b.length < packetLength ) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length); } return false; // not enough bytes in packet } } if(b.length < 9) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - too short to read header!"); } return false; } // Read the rest of the header. var cursor:uint = 6; var dataAlignment:Boolean = (b[cursor] & 0x04) != 0; cursor++; var ptsDts:uint = (b[cursor] & 0xc0) >> 6; cursor++; var pesHeaderDataLength:uint = b[cursor]; cursor++; //logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength); var pts:Number = 0, dts:Number = 0; if(ptsDts & 0x02) { // has PTS at least if(cursor + 5 > b.length) return true; pts = b[cursor] & 0x0e; pts *= 128; pts += b[cursor + 1]; pts *= 256; pts += b[cursor + 2] & 0xfe; pts *= 128; pts += b[cursor + 3]; pts *= 256; pts += b[cursor + 4] & 0xfe; pts /= 2; if(ptsDts & 0x01) { // DTS too! if(cursor + 10 > b.length) return true; dts = b[cursor + 5] & 0x0e; dts *= 128; dts += b[cursor + 6]; dts *= 256; dts += b[cursor + 7] & 0xfe; dts *= 128; dts += b[cursor + 8]; dts *= 256; dts += b[cursor + 9] & 0xfe; dts /= 2; } else { //logger.debug("Filling in DTS") dts = pts; } } // Condition PTS and DTS. pts = handleMpegTimestampWrap(pts, lastPTS); lastPTS = pts; dts = handleMpegTimestampWrap(dts, lastDTS); lastDTS = dts; packet.pts = pts; packet.dts = dts; //logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000); cursor += pesHeaderDataLength; if(cursor > b.length) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - ran out of bytes"); } return true; } if(types[packet.packetID] == undefined) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - unknown type"); } return true; } var pes:PESPacketStream; if(streams[packet.packetID] == undefined) { if(dts < 0.0) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - invalid decode timestamp? DTS=" + dts); } //return true; } pes = new PESPacketStream(); streams[packet.packetID] = pes; } else { pes = streams[packet.packetID]; } if(headerSent == false) { CONFIG::LOGGING { logger.warn("Skipping data that came before PMT"); } return true; } // Note the type at this moment in time. packet.type = types[packet.packetID]; packet.headerLength = cursor; // And process. if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO) { var start:int = NALU.scan(b, cursor, true); if(start == -1 && lastVideoNALU) { CONFIG::LOGGING { logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor); return true; } else if((start - cursor) > 0 && lastVideoNALU) { // Shove into previous buffer. CONFIG::LOGGING { logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } // If it's identical timestamps, accumulate it into the current unit and keep going. if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts) { CONFIG::LOGGING { logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } else { // Submit previous data. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); } // Update NALU state. lastVideoNALU = new NALU(); lastVideoNALU.buffer = new ByteArray(); lastVideoNALU.pts = pts; lastVideoNALU.dts = dts; lastVideoNALU.type = packet.type; lastVideoNALU.buffer.writeBytes(b, cursor); } } else if(types[packet.packetID] == 0x0F) { // It's an AAC stream. pendingBuffers.push(packet.clone()); } else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04) { // It's an MP3 stream. pendingBuffers.push(packet.clone()); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A)."); } } bufferPendingNalus(); return true; } /** * To avoid transcoding all content on flush, we buffer it into FLV * tags as we go. However, they remain undelivered until we can gather * final SPS/PPS information. This method is responsible for * incrementally buffering in the FLV transcoder as we go. */ public function bufferPendingNalus():void { // Iterate and buffer new NALUs. for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++) { if(pendingBuffers[i] is NALU) { transcoder.convert(pendingBuffers[i] as NALU); } else if(pendingBuffers[i] is PESPacket) { var packet:PESPacket = pendingBuffers[i] as PESPacket; if(packet.type == 0x0F) { // It's an AAC stream. transcoder.convertAAC(packet); } else if(packet.type == 0x03 || packet.type == 0x04) { // It's an MP3 stream. Pass through directly. transcoder.convertMP3(packet); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B)."); } } } } // Note the last item we converted so we can avoid duplicating work. pendingLastConvertedIndex = pendingBuffers.length; } public function processAllNalus():void { // Consume any unposted video NALUs. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); lastVideoNALU = null; } // First walk all the video NALUs and get the correct SPS/PPS if(pendingBuffers.length == 0) return; // Then emit SPS/PPS transcoder.emitSPSPPSUnbuffered(); // Complete buffering and emit it all. bufferPendingNalus(); transcoder.emitBufferedTags(); // Don't forget to clear the pending list. pendingBuffers.length = 0; pendingLastConvertedIndex = 0; } } }
Fix issue with unwrapped negative DTS dropping PES packets.
Fix issue with unwrapped negative DTS dropping PES packets.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
05977a0baec6b06186cce71d311d86d78d2d5908
src/aerys/minko/scene/node/camera/AbstractCamera.as
src/aerys/minko/scene/node/camera/AbstractCamera.as
package aerys.minko.scene.node.camera { import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Ray; public class AbstractCamera extends AbstractSceneNode { public static const DEFAULT_ZNEAR : Number = .1; public static const DEFAULT_ZFAR : Number = 500.; protected var _cameraData : CameraDataProvider = null; protected var _enabled : Boolean = true; protected var _activated : Signal = new Signal('Camera.activated'); protected var _deactivated : Signal = new Signal('Camera.deactivated'); public function get cameraData() : CameraDataProvider { return _cameraData; } public function get zNear() : Number { return _cameraData.zNear; } public function set zNear(value : Number) : void { _cameraData.zNear = value; } public function get zFar() : Number { return _cameraData.zFar; } public function set zFar(value : Number) : void { _cameraData.zFar = value; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { if (value != _enabled) { _enabled = value; if (_enabled) _activated.execute(this); else _deactivated.execute(this); } } public function get activated() : Signal { return _activated; } public function get deactivated() : Signal { return _deactivated; } public function get worldToView() : Matrix4x4 { return worldToLocal; } public function get viewToWorld() : Matrix4x4 { return localToWorld; } public function get worldToScreen() : Matrix4x4 { return _cameraData.worldToScreen; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); _cameraData = new CameraDataProvider(worldToView, viewToWorld); _cameraData.zNear = zNear; _cameraData.zFar = zFar; initialize(); } protected function initialize() : void { throw new Error('Must be overriden.'); } public function unproject(x : Number, v : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } public function getWorldToScreen(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.worldToScreen) : _cameraData.worldToScreen.clone(); } public function getScreenToWorld(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.screenToWorld) : _cameraData.screenToWorld.clone(); } public function getProjection(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.projection) : _cameraData.projection.clone(); } } }
package aerys.minko.scene.node.camera { import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Ray; public class AbstractCamera extends AbstractSceneNode { public static const DEFAULT_ZNEAR : Number = .1; public static const DEFAULT_ZFAR : Number = 500.; protected var _cameraData : CameraDataProvider = null; protected var _enabled : Boolean = true; protected var _activated : Signal = new Signal('Camera.activated'); protected var _deactivated : Signal = new Signal('Camera.deactivated'); public function get cameraData() : CameraDataProvider { return _cameraData; } public function get zNear() : Number { return _cameraData.zNear; } public function set zNear(value : Number) : void { _cameraData.zNear = value; } public function get zFar() : Number { return _cameraData.zFar; } public function set zFar(value : Number) : void { _cameraData.zFar = value; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { if (value != _enabled) { _enabled = value; if (_enabled) _activated.execute(this); else _deactivated.execute(this); } } public function get activated() : Signal { return _activated; } public function get deactivated() : Signal { return _deactivated; } public function get worldToView() : Matrix4x4 { return worldToLocal; } public function get viewToWorld() : Matrix4x4 { return localToWorld; } public function get worldToScreen() : Matrix4x4 { return _cameraData.worldToScreen; } public function get projection() : Matrix4x4 { return _cameraData.projection; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); _cameraData = new CameraDataProvider(worldToView, viewToWorld); _cameraData.zNear = zNear; _cameraData.zFar = zFar; initialize(); } protected function initialize() : void { throw new Error('Must be overriden.'); } public function unproject(x : Number, v : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } } }
add Camera.projection property and remove duplicates
add Camera.projection property and remove duplicates
ActionScript
mit
aerys/minko-as3
f8008bf820abcc6c3119b9388d062be3ec287c13
frameworks/projects/framework/src/mx/core/DebuggableWorker.as
frameworks/projects/framework/src/mx/core/DebuggableWorker.as
/** * User: DoubleFx Date: 30/04/2014 Time: 17:34 */ package mx.core { import flash.display.Sprite; import flash.system.Capabilities; import flash.utils.setInterval; /** * DebuggableWorker should be used as a base class * for workers instead of Sprite. * it allows the debugging of those workers using FDB. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 3.4 * @productversion Flex 4 */ public class DebuggableWorker extends Sprite { include "../core/Version.as"; public function DebuggableWorker() { // Stick a timer here so that we will execute script every 1.5s // no matter what. // This is strictly for the debugger to be able to halt. // Note: isDebugger is true only with a Debugger Player. if (Capabilities.isDebugger == true) { setInterval(debugTickler, 1500); } } /** * @private * This is here so we get the this pointer set to Application. */ private function debugTickler():void { // We need some bytes of code in order to have a place to break. var i:int = 0; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.core { import flash.display.Sprite; import flash.system.Capabilities; import flash.utils.setInterval; /** * DebuggableWorker should be used as a base class * for workers instead of Sprite. * it allows the debugging of those workers using FDB. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 3.4 * @productversion Flex 4 */ public class DebuggableWorker extends Sprite { include "../core/Version.as"; public function DebuggableWorker() { // Stick a timer here so that we will execute script every 1.5s // no matter what. // This is strictly for the debugger to be able to halt. // Note: isDebugger is true only with a Debugger Player. if (Capabilities.isDebugger == true) { setInterval(debugTickler, 1500); } } /** * @private * This is here so we get the this pointer set to Application. */ private function debugTickler():void { // We need some bytes of code in order to have a place to break. var i:int = 0; } } }
Create a base Class for workers making them debuggable via FDB - Added the missing Apache Header
FLEX-34294: Create a base Class for workers making them debuggable via FDB - Added the missing Apache Header
ActionScript
apache-2.0
danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk
0929f09dd6d07ee48080929a336342919a7ce27a
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
package com.kaltura.hls.m2ts { import flash.utils.ByteArray; import flash.net.ObjectEncoding; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; import flash.utils.IDataOutput; import com.hurlant.util.Hex; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Process packetized elementary streams and extract NALUs and other data. */ public class PESProcessor { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor"); } public var types:Object = {}; public var streams:Object = {}; public var lastVideoNALU:NALU = null; public var transcoder:FLVTranscoder = new FLVTranscoder(); public var headerSent:Boolean = false; public var pmtStreamId:int = -1; protected var pendingBuffers:Vector.<Object> = new Vector.<Object>(); protected var pendingLastConvertedIndex:int = 0; public var lastPTS:Number = 0, lastDTS:Number = 0; /** * Given a MPEG timestamp we've seen previously, determine if the new timestamp * has wrapped and correct it to follow the old timestamp. */ static function handleMpegTimestampWrap(newTime:Number, oldTime:Number):Number { while (!isNaN(oldTime) && (Math.abs(newTime - oldTime) > 4294967296)) newTime += (oldTime < newTime) ? -8589934592 : 8589934592; return newTime; } public function logStreams():void { CONFIG::LOGGING { logger.debug("----- PES state -----"); for(var k:* in streams) { logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]); } } } public function clear(clearAACConfig:Boolean = true):void { streams = {}; lastVideoNALU = null; transcoder.clear(clearAACConfig); } private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean { // Get the section length. var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3]; // Check the section length for a single PMT. CONFIG::LOGGING { if (sectionLen > 13) { logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one."); } } // Grab the PMT ID. pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF; CONFIG::LOGGING { logger.debug("Saw PMT ID of " + pmtStreamId); } return true; } private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean { var sectionLength:uint; var sectionLimit:uint; var programInfoLength:uint; var type:uint; var pid:uint; var esInfoLength:uint; var seenPIDsByClass:Array; var mediaClass:int; var hasAudio:Boolean = false, hasVideo:Boolean = false; // Set up types. types = []; seenPIDsByClass = []; seenPIDsByClass[MediaClass.VIDEO] = Infinity; seenPIDsByClass[MediaClass.AUDIO] = Infinity; // Process section length and limit. cursor++; sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; if(sectionLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 1"); } return false; } // Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid sectionLimit = cursor + sectionLength; cursor += 7; // And get the program info length. programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; // If not enough data to proceed, bail. if(programInfoLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 2"); } return false; } cursor += programInfoLength; const CRC_SIZE:int = 4; while(cursor < sectionLimit - CRC_SIZE) { type = bytes[cursor++]; pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1]; cursor += 2; mediaClass = MediaClass.calculate(type); if(mediaClass == MediaClass.VIDEO) hasVideo = true if(mediaClass == MediaClass.AUDIO) hasAudio = true // For video & audio, select the lowest PID for each kind. if(mediaClass == MediaClass.OTHER || pid < seenPIDsByClass[mediaClass]) { // Clear a higher PID if present. if(mediaClass != MediaClass.OTHER && seenPIDsByClass[mediaClass] < Infinity) types[seenPIDsByClass[mediaClass]] = -1; types[pid] = type; seenPIDsByClass[mediaClass] = pid; } // Skip the esInfo data. esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; cursor += esInfoLength; } // Cook out header to transcoder. //transcoder.writeHeader(hasAudio, hasVideo); headerSent = true; return true; } public function append(packet:PESPacket):Boolean { // logger.debug("saw packet of " + packet.buffer.length); var b:ByteArray = packet.buffer; b.position = 0; if(b.length < 8) { CONFIG::LOGGING { logger.error("Ignoring too short PES packet, length=" + b.length); } return true; } // Get the start code. var startCode:uint = b.readUnsignedInt(); if((startCode & 0xFFFFFF00) != 0x00000100) { // It could be a program association table. if((startCode & 0xFFFFFF00) == 0x0000b000) { parseProgramAssociationTable(b, 1); return true; } // It could be the program map table. if((startCode & 0xFFFFFC00) == 0x0002b000) { parseProgramMapTable(b, 1); return true; } var tmp:ByteArray = new ByteArray(); tmp.writeInt(startCode); CONFIG::LOGGING { logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true)); } return true; } // Get the stream ID. var streamID:int = startCode & 0xFF; // Get the length. var packetLength:uint = b.readUnsignedShort(); if(packetLength) { if(b.length < packetLength ) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length); } return false; // not enough bytes in packet } } if(b.length < 9) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - too short to read header!"); } return false; } // Read the rest of the header. var cursor:uint = 6; var dataAlignment:Boolean = (b[cursor] & 0x04) != 0; cursor++; var ptsDts:uint = (b[cursor] & 0xc0) >> 6; cursor++; var pesHeaderDataLength:uint = b[cursor]; cursor++; //logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength); var pts:Number = 0, dts:Number = 0; if(ptsDts & 0x02) { // has PTS at least if(cursor + 5 > b.length) return true; pts = b[cursor] & 0x0e; pts *= 128; pts += b[cursor + 1]; pts *= 256; pts += b[cursor + 2] & 0xfe; pts *= 128; pts += b[cursor + 3]; pts *= 256; pts += b[cursor + 4] & 0xfe; pts /= 2; if(ptsDts & 0x01) { // DTS too! if(cursor + 10 > b.length) return true; dts = b[cursor + 5] & 0x0e; dts *= 128; dts += b[cursor + 6]; dts *= 256; dts += b[cursor + 7] & 0xfe; dts *= 128; dts += b[cursor + 8]; dts *= 256; dts += b[cursor + 9] & 0xfe; dts /= 2; } else { //logger.debug("Filling in DTS") dts = pts; } } // Condition PTS and DTS. pts = handleMpegTimestampWrap(pts, lastPTS); lastPTS = pts; dts = handleMpegTimestampWrap(dts, lastDTS); lastDTS = dts; packet.pts = pts; packet.dts = dts; //logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000); cursor += pesHeaderDataLength; if(cursor > b.length) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - ran out of bytes"); } return true; } if(types[packet.packetID] == undefined) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - unknown type"); } return true; } var pes:PESPacketStream; if(streams[packet.packetID] == undefined) { if(dts < 0.0) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - invalid decode timestamp, skipping"); } return true; } pes = new PESPacketStream(); streams[packet.packetID] = pes; } else { pes = streams[packet.packetID]; } if(headerSent == false) { CONFIG::LOGGING { logger.warn("Skipping data that came before PMT"); } return true; } // Note the type at this moment in time. packet.type = types[packet.packetID]; packet.headerLength = cursor; // And process. if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO) { var start:int = NALU.scan(b, cursor, true); if(start == -1 && lastVideoNALU) { CONFIG::LOGGING { logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor); return true; } else if((start - cursor) > 0 && lastVideoNALU) { // Shove into previous buffer. CONFIG::LOGGING { logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } // If it's identical timestamps, accumulate it into the current unit and keep going. if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts) { CONFIG::LOGGING { logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } else { // Submit previous data. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); } // Update NALU state. lastVideoNALU = new NALU(); lastVideoNALU.buffer = new ByteArray(); lastVideoNALU.pts = pts; lastVideoNALU.dts = dts; lastVideoNALU.type = packet.type; lastVideoNALU.buffer.writeBytes(b, cursor); } } else if(types[packet.packetID] == 0x0F) { // It's an AAC stream. pendingBuffers.push(packet.clone()); } else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04) { // It's an MP3 stream. pendingBuffers.push(packet.clone()); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A)."); } } bufferPendingNalus(); return true; } /** * To avoid transcoding all content on flush, we buffer it into FLV * tags as we go. However, they remain undelivered until we can gather * final SPS/PPS information. This method is responsible for * incrementally buffering in the FLV transcoder as we go. */ public function bufferPendingNalus():void { // Iterate and buffer new NALUs. for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++) { if(pendingBuffers[i] is NALU) { transcoder.convert(pendingBuffers[i] as NALU); } else if(pendingBuffers[i] is PESPacket) { var packet:PESPacket = pendingBuffers[i] as PESPacket; if(packet.type == 0x0F) { // It's an AAC stream. transcoder.convertAAC(packet); } else if(packet.type == 0x03 || packet.type == 0x04) { // It's an MP3 stream. Pass through directly. transcoder.convertMP3(packet); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B)."); } } } } // Note the last item we converted so we can avoid duplicating work. pendingLastConvertedIndex = pendingBuffers.length; } public function processAllNalus():void { // Consume any unposted video NALUs. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); lastVideoNALU = null; } // First walk all the video NALUs and get the correct SPS/PPS if(pendingBuffers.length == 0) return; // Then emit SPS/PPS transcoder.emitSPSPPSUnbuffered(); // Complete buffering and emit it all. bufferPendingNalus(); transcoder.emitBufferedTags(); // Don't forget to clear the pending list. pendingBuffers.length = 0; pendingLastConvertedIndex = 0; } } }
package com.kaltura.hls.m2ts { import flash.utils.ByteArray; import flash.net.ObjectEncoding; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; import flash.utils.IDataOutput; import com.hurlant.util.Hex; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Process packetized elementary streams and extract NALUs and other data. */ public class PESProcessor { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor"); } public var types:Object = {}; public var streams:Object = {}; public var lastVideoNALU:NALU = null; public var transcoder:FLVTranscoder = new FLVTranscoder(); public var headerSent:Boolean = false; public var pmtStreamId:int = -1; protected var pendingBuffers:Vector.<Object> = new Vector.<Object>(); protected var pendingLastConvertedIndex:int = 0; public var lastPTS:Number = 0, lastDTS:Number = 0; /** * Given a MPEG timestamp we've seen previously, determine if the new timestamp * has wrapped and correct it to follow the old timestamp. */ static function handleMpegTimestampWrap(newTime:Number, oldTime:Number):Number { while (!isNaN(oldTime) && (Math.abs(newTime - oldTime) > 4294967296)) newTime += (oldTime < newTime) ? -8589934592 : 8589934592; return newTime; } public function logStreams():void { CONFIG::LOGGING { logger.debug("----- PES state -----"); for(var k:* in streams) { logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]); } } } public function clear(clearAACConfig:Boolean = true):void { streams = {}; lastVideoNALU = null; transcoder.clear(clearAACConfig); // Reset PTS/DTS reference. lastPTS = lastDTS = 0; } private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean { // Get the section length. var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3]; // Check the section length for a single PMT. CONFIG::LOGGING { if (sectionLen > 13) { logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one."); } } // Grab the PMT ID. pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF; CONFIG::LOGGING { logger.debug("Saw PMT ID of " + pmtStreamId); } return true; } private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean { var sectionLength:uint; var sectionLimit:uint; var programInfoLength:uint; var type:uint; var pid:uint; var esInfoLength:uint; var seenPIDsByClass:Array; var mediaClass:int; var hasAudio:Boolean = false, hasVideo:Boolean = false; // Set up types. types = []; seenPIDsByClass = []; seenPIDsByClass[MediaClass.VIDEO] = Infinity; seenPIDsByClass[MediaClass.AUDIO] = Infinity; // Process section length and limit. cursor++; sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; if(sectionLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 1"); } return false; } // Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid sectionLimit = cursor + sectionLength; cursor += 7; // And get the program info length. programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; // If not enough data to proceed, bail. if(programInfoLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 2"); } return false; } cursor += programInfoLength; const CRC_SIZE:int = 4; while(cursor < sectionLimit - CRC_SIZE) { type = bytes[cursor++]; pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1]; cursor += 2; mediaClass = MediaClass.calculate(type); if(mediaClass == MediaClass.VIDEO) hasVideo = true if(mediaClass == MediaClass.AUDIO) hasAudio = true // For video & audio, select the lowest PID for each kind. if(mediaClass == MediaClass.OTHER || pid < seenPIDsByClass[mediaClass]) { // Clear a higher PID if present. if(mediaClass != MediaClass.OTHER && seenPIDsByClass[mediaClass] < Infinity) types[seenPIDsByClass[mediaClass]] = -1; types[pid] = type; seenPIDsByClass[mediaClass] = pid; } // Skip the esInfo data. esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; cursor += esInfoLength; } // Cook out header to transcoder. //transcoder.writeHeader(hasAudio, hasVideo); headerSent = true; return true; } public function append(packet:PESPacket):Boolean { // logger.debug("saw packet of " + packet.buffer.length); var b:ByteArray = packet.buffer; b.position = 0; if(b.length < 8) { CONFIG::LOGGING { logger.error("Ignoring too short PES packet, length=" + b.length); } return true; } // Get the start code. var startCode:uint = b.readUnsignedInt(); if((startCode & 0xFFFFFF00) != 0x00000100) { // It could be a program association table. if((startCode & 0xFFFFFF00) == 0x0000b000) { parseProgramAssociationTable(b, 1); return true; } // It could be the program map table. if((startCode & 0xFFFFFC00) == 0x0002b000) { parseProgramMapTable(b, 1); return true; } var tmp:ByteArray = new ByteArray(); tmp.writeInt(startCode); CONFIG::LOGGING { logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true)); } return true; } // Get the stream ID. var streamID:int = startCode & 0xFF; // Get the length. var packetLength:uint = b.readUnsignedShort(); if(packetLength) { if(b.length < packetLength ) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length); } return false; // not enough bytes in packet } } if(b.length < 9) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - too short to read header!"); } return false; } // Read the rest of the header. var cursor:uint = 6; var dataAlignment:Boolean = (b[cursor] & 0x04) != 0; cursor++; var ptsDts:uint = (b[cursor] & 0xc0) >> 6; cursor++; var pesHeaderDataLength:uint = b[cursor]; cursor++; //logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength); var pts:Number = 0, dts:Number = 0; if(ptsDts & 0x02) { // has PTS at least if(cursor + 5 > b.length) return true; pts = b[cursor] & 0x0e; pts *= 128; pts += b[cursor + 1]; pts *= 256; pts += b[cursor + 2] & 0xfe; pts *= 128; pts += b[cursor + 3]; pts *= 256; pts += b[cursor + 4] & 0xfe; pts /= 2; if(ptsDts & 0x01) { // DTS too! if(cursor + 10 > b.length) return true; dts = b[cursor + 5] & 0x0e; dts *= 128; dts += b[cursor + 6]; dts *= 256; dts += b[cursor + 7] & 0xfe; dts *= 128; dts += b[cursor + 8]; dts *= 256; dts += b[cursor + 9] & 0xfe; dts /= 2; } else { //logger.debug("Filling in DTS") dts = pts; } } // Condition PTS and DTS. pts = handleMpegTimestampWrap(pts, lastPTS); lastPTS = pts; dts = handleMpegTimestampWrap(dts, lastDTS); lastDTS = dts; packet.pts = pts; packet.dts = dts; //logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000); cursor += pesHeaderDataLength; if(cursor > b.length) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - ran out of bytes"); } return true; } if(types[packet.packetID] == undefined) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - unknown type"); } return true; } var pes:PESPacketStream; if(streams[packet.packetID] == undefined) { if(dts < 0.0) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - invalid decode timestamp, skipping"); } return true; } pes = new PESPacketStream(); streams[packet.packetID] = pes; } else { pes = streams[packet.packetID]; } if(headerSent == false) { CONFIG::LOGGING { logger.warn("Skipping data that came before PMT"); } return true; } // Note the type at this moment in time. packet.type = types[packet.packetID]; packet.headerLength = cursor; // And process. if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO) { var start:int = NALU.scan(b, cursor, true); if(start == -1 && lastVideoNALU) { CONFIG::LOGGING { logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor); return true; } else if((start - cursor) > 0 && lastVideoNALU) { // Shove into previous buffer. CONFIG::LOGGING { logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } // If it's identical timestamps, accumulate it into the current unit and keep going. if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts) { CONFIG::LOGGING { logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } else { // Submit previous data. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); } // Update NALU state. lastVideoNALU = new NALU(); lastVideoNALU.buffer = new ByteArray(); lastVideoNALU.pts = pts; lastVideoNALU.dts = dts; lastVideoNALU.type = packet.type; lastVideoNALU.buffer.writeBytes(b, cursor); } } else if(types[packet.packetID] == 0x0F) { // It's an AAC stream. pendingBuffers.push(packet.clone()); } else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04) { // It's an MP3 stream. pendingBuffers.push(packet.clone()); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A)."); } } bufferPendingNalus(); return true; } /** * To avoid transcoding all content on flush, we buffer it into FLV * tags as we go. However, they remain undelivered until we can gather * final SPS/PPS information. This method is responsible for * incrementally buffering in the FLV transcoder as we go. */ public function bufferPendingNalus():void { // Iterate and buffer new NALUs. for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++) { if(pendingBuffers[i] is NALU) { transcoder.convert(pendingBuffers[i] as NALU); } else if(pendingBuffers[i] is PESPacket) { var packet:PESPacket = pendingBuffers[i] as PESPacket; if(packet.type == 0x0F) { // It's an AAC stream. transcoder.convertAAC(packet); } else if(packet.type == 0x03 || packet.type == 0x04) { // It's an MP3 stream. Pass through directly. transcoder.convertMP3(packet); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B)."); } } } } // Note the last item we converted so we can avoid duplicating work. pendingLastConvertedIndex = pendingBuffers.length; } public function processAllNalus():void { // Consume any unposted video NALUs. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); lastVideoNALU = null; } // First walk all the video NALUs and get the correct SPS/PPS if(pendingBuffers.length == 0) return; // Then emit SPS/PPS transcoder.emitSPSPPSUnbuffered(); // Complete buffering and emit it all. bufferPendingNalus(); transcoder.emitBufferedTags(); // Don't forget to clear the pending list. pendingBuffers.length = 0; pendingLastConvertedIndex = 0; } } }
Fix for scrub/reset cases.
Fix for scrub/reset cases.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
5ba36c6ea9c4f29c65379cbb7cc7ab2e96d1aadc
src/aerys/minko/render/geometry/primitive/BillboardsGeometry.as
src/aerys/minko/render/geometry/primitive/BillboardsGeometry.as
package aerys.minko.render.geometry.primitive { import aerys.minko.render.Effect; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; /** * The BillboardsGeometry stores a list of 2D billboards meant to be used * in particle effects or 2D sprites rendering. * * @author Jean-Marc Le Roux * */ public class BillboardsGeometry extends Geometry { public static const PARTICLE_FORMAT : VertexFormat = new VertexFormat( VertexComponent.XY, VertexComponent.ID ); public function BillboardsGeometry(numQuads : uint) { super(); initialize(numQuads); } private function initialize(numQuads : uint) : void { var vertices : Vector.<Number> = new <Number>[]; var indices : Vector.<uint> = new <uint>[]; for (var particleId : int = 0; particleId < numQuads; ++particleId) { vertices.push( -0.5, 0.5, particleId, 0.5, 0.5, particleId, 0.5, -0.5, particleId, -0.5, -0.5, particleId ); indices.push( particleId * 4, particleId * 4 + 2, particleId * 4 + 1, particleId * 4, particleId * 4 + 3, particleId * 4 + 2 ); } setVertexStream( new VertexStream( StreamUsage.STATIC, PARTICLE_FORMAT, vertices ), 0 ); indexStream = new IndexStream(StreamUsage.STATIC, indices); } } }
package aerys.minko.render.geometry.primitive { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IndexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; /** * The BillboardsGeometry stores a list of 2D billboards meant to be used * in particle effects or 2D sprites rendering. * * @author Jean-Marc Le Roux * */ public class BillboardsGeometry extends Geometry { public static const BILLBOARD_FORMAT : VertexFormat = new VertexFormat( VertexComponent.XY, VertexComponent.ID ); public function BillboardsGeometry(numQuads : uint) { super(); initialize(numQuads); } private function initialize(numBillboards : uint) : void { var vertices : Vector.<Number> = new <Number>[]; var indices : Vector.<uint> = new <uint>[]; for (var billboardId : int = 0; billboardId < numBillboards; ++billboardId) { vertices.push( -0.5, 0.5, billboardId, 0.5, 0.5, billboardId, 0.5, -0.5, billboardId, -0.5, -0.5, billboardId ); indices.push( billboardId * 4, billboardId * 4 + 2, billboardId * 4 + 1, billboardId * 4, billboardId * 4 + 3, billboardId * 4 + 2 ); } setVertexStream(new VertexStream(StreamUsage.STATIC, BILLBOARD_FORMAT, vertices), 0); indexStream = new IndexStream(StreamUsage.STATIC, indices); } } }
fix BillboardsGeometry variables/constants naming
fix BillboardsGeometry variables/constants naming
ActionScript
mit
aerys/minko-as3
a545535bd04c0b4db2aada215e341253072c0808
Arguments/src/classes/Language.as
Arguments/src/classes/Language.as
package classes { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.ByteArray; import mx.controls.Alert; import org.osmf.layout.AbsoluteLayoutFacet; public class Language { //I will set the language to either GERMAN, RUSSIAN or ENGLISH //based on this, you could read the values into the variables //by default, the language is EN-US public static const GERMAN:String = "GER"; public static const ENGLISH:String = "EN-US"; public static const RUSSIAN:String = "RUS"; public static var language:String = GERMAN; public static var xml:XML; private static var ready:Boolean=false; public static function init():void { [Embed(source="../../../translation.xml", mimeType="application/octet-stream")] const MyData:Class; var byteArray:ByteArray = new MyData() as ByteArray; var x:XML = new XML(byteArray.readUTFBytes(byteArray.length)); xml = x; ready=true; } /**The key function. Use this to look up a label from the translation document according to the set language.*/ public static function lookup(label:String):String{ if(!ready){ init(); } trace("Now looking up:" + label); var lbl:XMLList = xml.descendants(label); var lang:XMLList = lbl.descendants(language); var output:String = lang.attribute("text"); if(!output){ output = "error | ошибка | Fehler --- There was a problem getting the text for this item. The label was: " + label; } trace("Output is: " + output); return output; } } }
package classes { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.ByteArray; import mx.controls.Alert; import org.osmf.layout.AbsoluteLayoutFacet; public class Language { //I will set the language to either GERMAN, RUSSIAN or ENGLISH //based on this, you could read the values into the variables //by default, the language is EN-US public static const GERMAN:String = "GER"; public static const ENGLISH:String = "EN-US"; public static const RUSSIAN:String = "RUS"; public static var language:String = ENGLISH; public static var xml:XML; private static var ready:Boolean=false; public static function init():void { [Embed(source="../../../translation.xml", mimeType="application/octet-stream")] const MyData:Class; var byteArray:ByteArray = new MyData() as ByteArray; var x:XML = new XML(byteArray.readUTFBytes(byteArray.length)); xml = x; ready=true; } /**The key function. Use this to look up a label from the translation document according to the set language.*/ public static function lookup(label:String):String{ if(!ready){ init(); } trace("Now looking up:" + label); var lbl:XMLList = xml.descendants(label); var lang:XMLList = lbl.descendants(language); var output:String = lang.attribute("text"); if(!output){ output = "error | ошибка | Fehler --- There was a problem getting the text for this item. The label was: " + label; } trace("Output is: " + output); return output; } } }
Set language back to english
Set language back to english
ActionScript
agpl-3.0
mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA
c9c90ffb67dd729ffa5797bab6d3373b5a07c77c
frameworks/projects/Core/as/src/org/apache/flex/core/CSSTextField.as
frameworks/projects/Core/as/src/org/apache/flex/core/CSSTextField.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.utils.CSSUtils; /** * The CSSTextField class implements CSS text styles in a TextField. * Not every CSS text style is currently supported. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class CSSTextField extends TextField { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function CSSTextField() { super(); } /** * @private * The styleParent property is set if the CSSTextField * is used in a SimpleButton-based instance because * the parent property is null, defeating CSS lookup. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var styleParent:Object; /** * @private * The parentDrawsBackground property is set if the CSSTextField * shouldn't draw a background * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var parentDrawsBackground:Boolean; /** * @private * The parentHandlesPadding property is set if the CSSTextField * shouldn't worry about padding * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var parentHandlesPadding:Boolean; /** * @private */ override public function set text(value:String):void { var sp:Object = parent; if (styleParent) sp = styleParent; sp.addEventListener("classNameChanged", updateStyles); var tf: TextFormat = new TextFormat(); tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String; tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize"); tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold"; tf.color = CSSUtils.toColor(ValuesManager.valuesImpl.getValue(sp, "color")); if (!parentHandlesPadding) { var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding"); var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left"); var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right"); tf.leftMargin = CSSUtils.getLeftValue(paddingLeft, padding, width); tf.rightMargin = CSSUtils.getRightValue(paddingRight, padding, width); } var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align"); if (align == "center") { autoSize = TextFieldAutoSize.NONE; tf.align = "center"; } else if (align == "right") { tf.align = "right"; autoSize = TextFieldAutoSize.NONE; } if (!parentDrawsBackground) { var backgroundColor:Object = ValuesManager.valuesImpl.getValue(sp, "background-color"); if (backgroundColor != null) { this.background = true; this.backgroundColor = CSSUtils.toColor(backgroundColor); } } defaultTextFormat = tf; super.text = value; } private function updateStyles(event:Event):void { // force styles to be re-calculated this.text = text; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.utils.CSSUtils; /** * The CSSTextField class implements CSS text styles in a TextField. * Not every CSS text style is currently supported. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class CSSTextField extends TextField { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function CSSTextField() { super(); } /** * @private * The styleParent property is set if the CSSTextField * is used in a SimpleButton-based instance because * the parent property is null, defeating CSS lookup. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var styleParent:Object; /** * @private * The CSS pseudo-state for lookups. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var styleState:String; /** * @private * The parentDrawsBackground property is set if the CSSTextField * shouldn't draw a background * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var parentDrawsBackground:Boolean; /** * @private * The parentHandlesPadding property is set if the CSSTextField * shouldn't worry about padding * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var parentHandlesPadding:Boolean; /** * @private */ override public function set text(value:String):void { var sp:Object = parent; if (styleParent) sp = styleParent; sp.addEventListener("classNameChanged", updateStyles); var tf: TextFormat = new TextFormat(); tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily", styleState) as String; tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize", styleState); tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight", styleState) == "bold"; tf.color = CSSUtils.toColor(ValuesManager.valuesImpl.getValue(sp, "color", styleState)); if (!parentHandlesPadding) { var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding", styleState); var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left", styleState); var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right", styleState); tf.leftMargin = CSSUtils.getLeftValue(paddingLeft, padding, width); tf.rightMargin = CSSUtils.getRightValue(paddingRight, padding, width); } var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align", styleState); if (align == "center") { autoSize = TextFieldAutoSize.NONE; tf.align = "center"; } else if (align == "right") { tf.align = "right"; autoSize = TextFieldAutoSize.NONE; } if (!parentDrawsBackground) { var backgroundColor:Object = ValuesManager.valuesImpl.getValue(sp, "background-color", styleState); if (backgroundColor != null) { this.background = true; this.backgroundColor = CSSUtils.toColor(backgroundColor); } } defaultTextFormat = tf; super.text = value; } private function updateStyles(event:Event):void { // force styles to be re-calculated this.text = text; } } }
allow pseudo-state specific styles
allow pseudo-state specific styles
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
9f558c7f43fda83f595cb87ab8deaa6342922895
src/org/mangui/hls/model/FragmentData.as
src/org/mangui/hls/model/FragmentData.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls.model { import org.mangui.hls.demux.ID3Tag; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.utils.AES; import org.mangui.hls.utils.PTS; import flash.utils.ByteArray; /** Fragment Data. **/ public class FragmentData { /** valid fragment **/ public var valid : Boolean; /** fragment byte array **/ public var bytes : ByteArray; /* Total bytes this Fragment _will_ have */ public var bytesTotal: int; /** bytes Loaded **/ public var bytesLoaded : int; /** AES decryption instance **/ public var decryptAES : AES; /** Start PTS of this chunk. **/ public var pts_start : Number; /** computed Start PTS of this chunk. **/ public var pts_start_computed : Number; /** min/max audio/video PTS/DTS of this chunk. **/ public var pts_min_audio : Number; public var pts_max_audio : Number; public var pts_min_video : Number; public var pts_max_video : Number; public var dts_min : Number; /** audio/video found ? */ public var audio_found : Boolean; public var video_found : Boolean; /** tag related stuff */ public var metadata_tag_injected : Boolean; private var tags_pts_min_audio : Number; private var tags_pts_max_audio : Number; private var tags_pts_min_video : Number; private var tags_pts_max_video : Number; private var tags_audio_found : Boolean; private var tags_video_found : Boolean; public var tags : Vector.<FLVTag>; /* video dimension */ public var video_width : int; public var video_height : int; /* is fragment loaded selected by autolevel algo */ public var auto_level : Boolean; /* ID3 tags linked to this fragment */ public var id3_tags : Vector.<ID3Tag>; /** tag duration */ private var audio_tag_duration : Number; private var video_tag_duration : Number; private var audio_tag_last_dts : Number; private var video_tag_last_dts : Number; /** Fragment metrics **/ public function FragmentData() { this.pts_start = NaN; this.pts_start_computed = NaN; this.valid = true; this.video_width = 0; this.video_height = 0; }; public function appendTags(tags : Vector.<FLVTag>) : void { // Audio PTS/DTS normalization + min/max computation for each (var tag : FLVTag in tags) { tag.pts = PTS.normalize(pts_start_computed, tag.pts); tag.dts = PTS.normalize(pts_start_computed, tag.dts); dts_min = Math.min(dts_min, tag.dts); switch( tag.type ) { case FLVTag.AAC_RAW: case FLVTag.AAC_HEADER: case FLVTag.MP3_RAW: audio_found = true; tags_audio_found = true; audio_tag_duration = tag.dts - audio_tag_last_dts; audio_tag_last_dts = tag.dts; tags_pts_min_audio = Math.min(tags_pts_min_audio, tag.pts); tags_pts_max_audio = Math.max(tags_pts_max_audio, tag.pts); pts_min_audio = Math.min(pts_min_audio, tag.pts); pts_max_audio = Math.max(pts_max_audio, tag.pts); break; case FLVTag.AVC_HEADER: case FLVTag.AVC_NALU: video_found = true; tags_video_found = true; video_tag_duration = tag.dts - video_tag_last_dts; video_tag_last_dts = tag.dts; tags_pts_min_video = Math.min(tags_pts_min_video, tag.pts); tags_pts_max_video = Math.max(tags_pts_max_video, tag.pts); pts_min_video = Math.min(pts_min_video, tag.pts); pts_max_video = Math.max(pts_max_video, tag.pts); break; case FLVTag.DISCONTINUITY: case FLVTag.METADATA: default: break; } this.tags.push(tag); } } public function flushTags() : void { // clean-up tags tags = new Vector.<FLVTag>(); tags_audio_found = tags_video_found = false; metadata_tag_injected = false; pts_min_audio = pts_min_video = dts_min = tags_pts_min_audio = tags_pts_min_video = Number.POSITIVE_INFINITY; pts_max_audio = pts_max_video = tags_pts_max_audio = tags_pts_max_video = Number.NEGATIVE_INFINITY; audio_found = video_found = tags_audio_found = tags_video_found = false; } public function shiftTags() : void { tags = new Vector.<FLVTag>(); if (tags_audio_found) { tags_pts_min_audio = tags_pts_max_audio; tags_audio_found = false; } if (tags_video_found) { tags_pts_min_video = tags_pts_max_video; tags_video_found = false; } } public function get pts_min() : Number { if (audio_found) { return pts_min_audio; } else { return pts_min_video; } } public function get pts_max() : Number { if (audio_found) { return pts_max_audio; } else { return pts_max_video; } } public function get tag_duration() : Number { var duration : Number; if (audio_found) { duration = audio_tag_duration; } else { duration = video_tag_duration; } if(isNaN(duration)) { duration = 0; } return duration; } public function get tag_pts_min() : Number { if (audio_found) { return tags_pts_min_audio; } else { return tags_pts_min_video; } } public function get tag_pts_max() : Number { if (audio_found) { return tags_pts_max_audio; } else { return tags_pts_max_video; } } public function get tag_pts_start_offset() : Number { if (tags_audio_found) { return tags_pts_min_audio - pts_min_audio; } else { return tags_pts_min_video - pts_min_video; } } public function get tag_pts_end_offset() : Number { if (tags_audio_found) { return tags_pts_max_audio - pts_min_audio; } else { return tags_pts_max_video - pts_min_video; } } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls.model { import org.mangui.hls.demux.ID3Tag; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.utils.AES; import org.mangui.hls.utils.PTS; import flash.utils.ByteArray; /** Fragment Data. **/ public class FragmentData { /** valid fragment **/ public var valid : Boolean; /** fragment byte array **/ public var bytes : ByteArray; /* Total bytes this Fragment _will_ have */ public var bytesTotal: int; /** bytes Loaded **/ public var bytesLoaded : int; /** AES decryption instance **/ public var decryptAES : AES; /** Start PTS of this chunk. **/ public var pts_start : Number; /** computed Start PTS of this chunk. **/ public var pts_start_computed : Number; /** min/max audio/video PTS/DTS of this chunk. **/ public var pts_min_audio : Number; public var pts_max_audio : Number; public var pts_min_video : Number; public var pts_max_video : Number; public var dts_min : Number; /** audio/video found ? */ public var audio_found : Boolean; public var video_found : Boolean; /** tag related stuff */ public var metadata_tag_injected : Boolean; private var tags_pts_min_audio : Number; private var tags_pts_max_audio : Number; private var tags_pts_min_video : Number; private var tags_pts_max_video : Number; private var tags_audio_found : Boolean; private var tags_video_found : Boolean; public var tags : Vector.<FLVTag>; /* video dimension */ public var video_width : int; public var video_height : int; /* is fragment loaded selected by autolevel algo */ public var auto_level : Boolean; /* ID3 tags linked to this fragment */ public var id3_tags : Vector.<ID3Tag>; /** Whether this Fragment starts with IDR **/ public var starts_with_idr : Boolean; /** PTS of earliest AVC_HEADER */ public var pts_min_video_header : Number; /** tag duration */ private var audio_tag_duration : Number; private var video_tag_duration : Number; private var audio_tag_last_dts : Number; private var video_tag_last_dts : Number; /** Fragment metrics **/ public function FragmentData() { this.pts_start = NaN; this.pts_start_computed = NaN; this.valid = true; this.video_width = 0; this.video_height = 0; this.starts_with_idr = false; this.pts_min_video_header = NaN; }; public function appendTags(tags : Vector.<FLVTag>) : void { // Audio PTS/DTS normalization + min/max computation for each (var tag : FLVTag in tags) { tag.pts = PTS.normalize(pts_start_computed, tag.pts); tag.dts = PTS.normalize(pts_start_computed, tag.dts); dts_min = Math.min(dts_min, tag.dts); switch( tag.type ) { case FLVTag.AAC_RAW: case FLVTag.AAC_HEADER: case FLVTag.MP3_RAW: audio_found = true; tags_audio_found = true; audio_tag_duration = tag.dts - audio_tag_last_dts; audio_tag_last_dts = tag.dts; tags_pts_min_audio = Math.min(tags_pts_min_audio, tag.pts); tags_pts_max_audio = Math.max(tags_pts_max_audio, tag.pts); pts_min_audio = Math.min(pts_min_audio, tag.pts); pts_max_audio = Math.max(pts_max_audio, tag.pts); break; case FLVTag.AVC_HEADER: if (isNaN(pts_min_video_header)) { pts_min_video_header = tag.pts; } case FLVTag.AVC_NALU: video_found = true; tags_video_found = true; video_tag_duration = tag.dts - video_tag_last_dts; video_tag_last_dts = tag.dts; tags_pts_min_video = Math.min(tags_pts_min_video, tag.pts); tags_pts_max_video = Math.max(tags_pts_max_video, tag.pts); pts_min_video = Math.min(pts_min_video, tag.pts); pts_max_video = Math.max(pts_max_video, tag.pts); starts_with_idr = !isNaN(pts_min_video_header) && pts_min_video_header <= tag.pts; break; case FLVTag.DISCONTINUITY: case FLVTag.METADATA: default: break; } this.tags.push(tag); } } public function flushTags() : void { // clean-up tags tags = new Vector.<FLVTag>(); tags_audio_found = tags_video_found = false; metadata_tag_injected = false; pts_min_audio = pts_min_video = dts_min = tags_pts_min_audio = tags_pts_min_video = Number.POSITIVE_INFINITY; pts_max_audio = pts_max_video = tags_pts_max_audio = tags_pts_max_video = Number.NEGATIVE_INFINITY; audio_found = video_found = tags_audio_found = tags_video_found = false; starts_with_idr = false; pts_min_video_header = NaN; } public function shiftTags() : void { tags = new Vector.<FLVTag>(); if (tags_audio_found) { tags_pts_min_audio = tags_pts_max_audio; tags_audio_found = false; } if (tags_video_found) { tags_pts_min_video = tags_pts_max_video; tags_video_found = false; } } public function get pts_min() : Number { if (audio_found) { return pts_min_audio; } else { return pts_min_video; } } public function get pts_max() : Number { if (audio_found) { return pts_max_audio; } else { return pts_max_video; } } public function get tag_duration() : Number { var duration : Number; if (audio_found) { duration = audio_tag_duration; } else { duration = video_tag_duration; } if(isNaN(duration)) { duration = 0; } return duration; } public function get tag_pts_min() : Number { if (audio_found) { return tags_pts_min_audio; } else { return tags_pts_min_video; } } public function get tag_pts_max() : Number { if (audio_found) { return tags_pts_max_audio; } else { return tags_pts_max_video; } } public function get tag_pts_start_offset() : Number { if (tags_audio_found) { return tags_pts_min_audio - pts_min_audio; } else { return tags_pts_min_video - pts_min_video; } } public function get tag_pts_end_offset() : Number { if (tags_audio_found) { return tags_pts_max_audio - pts_min_audio; } else { return tags_pts_max_video - pts_min_video; } } } }
Add `starts_with_idr` and `pts_min_video_header`
[FragmentData] Add `starts_with_idr` and `pts_min_video_header`
ActionScript
mpl-2.0
codex-corp/flashls,codex-corp/flashls
c23ef757c22560ef1a9b13dc800d067230423149
src/aerys/minko/render/material/phong/AbstractShadowMappingEffect.as
src/aerys/minko/render/material/phong/AbstractShadowMappingEffect.as
package aerys.minko.render.material.phong { import aerys.minko.ns.minko_lighting; import aerys.minko.render.Effect; import aerys.minko.render.RenderTarget; import aerys.minko.render.Viewport; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.render.shader.Shader; import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import flash.display.BitmapData; public class AbstractShadowMappingEffect extends Effect { use namespace minko_lighting; private const SHADOW_FACTORIES : Vector.<Function> = new <Function>[ manageNoShadowing, // 0: ShadowMappingType.NONE manageMatrixShadowing, // 1: ShadowMappingType.MATRIX manageDualParaboloidShadowing, // 2: ShadowMappingType.DUAL_PARABOLOID manageCubicShadowing // 3: ShadowMappingType.CUBIC ]; private var _scene : Scene; private var _renderingPass : Shader; private var _watchedProperties : Vector.<String>; private var _updatePasses : Boolean; public function get scene() : Scene { return _scene; } public function AbstractShadowMappingEffect(scene : Scene, renderingShader : Shader) { _renderingPass = renderingShader; _watchedProperties = new Vector.<String>(); _scene = scene; _updatePasses = true; scene.enterFrame.add(onSceneEnterFrame); } private function onSceneEnterFrame(scene : Scene, viewport : Viewport, destination : BitmapData, timer : uint) : void { if (_updatePasses) { updatePasses(); _updatePasses = false; } } private function propertyChangedHandler(sceneBindings : DataBindings, propertyName : String, oldValue : Object, newValue : Object) : void { _updatePasses = true; } private function updatePasses() : void { var passes : Vector.<Shader> = new <Shader>[]; var sceneBindings : DataBindings = _scene.bindings; var shader : Shader = null; var renderTarget : RenderTarget = null; while (_watchedProperties.length != 0) sceneBindings.removeCallback(_watchedProperties.pop(), propertyChangedHandler); for (var lightId : uint = 0; ; ++lightId) { if (!lightPropertyExists(lightId, 'type')) break ; var shadowCastingPropertyName : String = LightDataProvider.getLightPropertyName( 'shadowCastingType', lightId ); _watchedProperties.push(shadowCastingPropertyName); sceneBindings.addCallback(shadowCastingPropertyName, propertyChangedHandler); if (sceneBindings.propertyExists(shadowCastingPropertyName)) SHADOW_FACTORIES[sceneBindings.getProperty(shadowCastingPropertyName)](lightId, passes); } passes.push(_renderingPass); setPasses(passes); } private function manageNoShadowing(lightId : uint, passes : Vector.<Shader>) : void { // nothing to do here, no extra rendering is necessary } private function manageMatrixShadowing(lightId : uint, passes : Vector.<Shader>) : void { var textureResource : TextureResource = getLightProperty(lightId, 'shadowMap'); var renderTarget : RenderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new MatrixShadowMapShader(lightId, lightId + 1, renderTarget)); } private function manageDualParaboloidShadowing(lightId : uint, passes : Vector.<Shader>) : void { var frontTextureResource : TextureResource = getLightProperty(lightId, 'shadowMapDPFront'); var backTextureResource : TextureResource = getLightProperty(lightId, 'shadowMapDPBack'); var size : uint = frontTextureResource.width; var frontRenderTarget : RenderTarget = new RenderTarget(size, size, frontTextureResource, 0, 0xffffffff); var backRenderTarget : RenderTarget = new RenderTarget(size, size, backTextureResource, 0, 0xffffffff); passes.push( new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget), new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget) ); } private function manageCubicShadowing(lightId : uint, passes : Vector.<Shader>) : void { var textureResource : CubeTextureResource = getLightProperty(lightId, 'shadowMapCube'); var size : uint = textureResource.size; var renderTarget0 : RenderTarget = new RenderTarget(size, size, textureResource, 0, 0xffffffff); var renderTarget1 : RenderTarget = new RenderTarget(size, size, textureResource, 1, 0xffffffff); var renderTarget2 : RenderTarget = new RenderTarget(size, size, textureResource, 2, 0xffffffff); var renderTarget3 : RenderTarget = new RenderTarget(size, size, textureResource, 3, 0xffffffff); var renderTarget4 : RenderTarget = new RenderTarget(size, size, textureResource, 4, 0xffffffff); var renderTarget5 : RenderTarget = new RenderTarget(size, size, textureResource, 5, 0xffffffff); passes.push( new CubeShadowMapShader(lightId, 0, lightId + 0.1, renderTarget0), new CubeShadowMapShader(lightId, 1, lightId + 0.2, renderTarget1), new CubeShadowMapShader(lightId, 2, lightId + 0.3, renderTarget2), new CubeShadowMapShader(lightId, 3, lightId + 0.4, renderTarget3), new CubeShadowMapShader(lightId, 4, lightId + 0.5, renderTarget4), new CubeShadowMapShader(lightId, 5, lightId + 0.6, renderTarget5) ); } private function lightPropertyExists(lightId : uint, propertyName : String) : Boolean { return _scene.bindings.propertyExists( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } private function getLightProperty(lightId : uint, propertyName : String) : * { return _scene.bindings.getProperty( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } } }
package aerys.minko.render.material.phong { import aerys.minko.ns.minko_lighting; import aerys.minko.render.Effect; import aerys.minko.render.RenderTarget; import aerys.minko.render.Viewport; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.render.shader.Shader; import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import flash.display.BitmapData; public class AbstractShadowMappingEffect extends Effect { use namespace minko_lighting; private const SHADOW_FACTORIES : Vector.<Function> = new <Function>[ manageNoShadowing, // 0: ShadowMappingType.NONE manageMatrixShadowing, // 1: ShadowMappingType.MATRIX manageDualParaboloidShadowing, // 2: ShadowMappingType.DUAL_PARABOLOID manageCubicShadowing // 3: ShadowMappingType.CUBIC ]; private var _scene : Scene; private var _renderingPass : Shader; private var _watchedProperties : Vector.<String>; public function get scene() : Scene { return _scene; } public function AbstractShadowMappingEffect(scene : Scene, renderingShader : Shader) { _renderingPass = renderingShader; _watchedProperties = new Vector.<String>(); _scene = scene; scene.enterFrame.add(sceneEnterFrameHandler); } private function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, timer : uint) : void { scene.enterFrame.remove(sceneEnterFrameHandler); updatePasses(); } private function propertyChangedHandler(sceneBindings : DataBindings, propertyName : String, oldValue : Object, newValue : Object) : void { scene.enterFrame.add(sceneEnterFrameHandler); } private function updatePasses() : void { var passes : Vector.<Shader> = new <Shader>[]; var sceneBindings : DataBindings = _scene.bindings; var shader : Shader = null; var renderTarget : RenderTarget = null; while (_watchedProperties.length != 0) sceneBindings.removeCallback(_watchedProperties.pop(), propertyChangedHandler); for (var lightId : uint = 0; ; ++lightId) { if (!lightPropertyExists(lightId, 'type')) break ; var shadowCastingPropertyName : String = LightDataProvider.getLightPropertyName( 'shadowCastingType', lightId ); _watchedProperties.push(shadowCastingPropertyName); sceneBindings.addCallback(shadowCastingPropertyName, propertyChangedHandler); if (sceneBindings.propertyExists(shadowCastingPropertyName)) SHADOW_FACTORIES[sceneBindings.getProperty(shadowCastingPropertyName)](lightId, passes); } passes.push(_renderingPass); setPasses(passes); } private function manageNoShadowing(lightId : uint, passes : Vector.<Shader>) : void { // nothing to do here, no extra rendering is necessary } private function manageMatrixShadowing(lightId : uint, passes : Vector.<Shader>) : void { var textureResource : TextureResource = getLightProperty(lightId, 'shadowMap'); var renderTarget : RenderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new MatrixShadowMapShader(lightId, lightId + 1, renderTarget)); } private function manageDualParaboloidShadowing(lightId : uint, passes : Vector.<Shader>) : void { var frontTextureResource : TextureResource = getLightProperty(lightId, 'shadowMapDPFront'); var backTextureResource : TextureResource = getLightProperty(lightId, 'shadowMapDPBack'); var size : uint = frontTextureResource.width; var frontRenderTarget : RenderTarget = new RenderTarget(size, size, frontTextureResource, 0, 0xffffffff); var backRenderTarget : RenderTarget = new RenderTarget(size, size, backTextureResource, 0, 0xffffffff); passes.push( new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget), new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget) ); } private function manageCubicShadowing(lightId : uint, passes : Vector.<Shader>) : void { var textureResource : CubeTextureResource = getLightProperty(lightId, 'shadowMapCube'); var size : uint = textureResource.size; var renderTarget0 : RenderTarget = new RenderTarget(size, size, textureResource, 0, 0xffffffff); var renderTarget1 : RenderTarget = new RenderTarget(size, size, textureResource, 1, 0xffffffff); var renderTarget2 : RenderTarget = new RenderTarget(size, size, textureResource, 2, 0xffffffff); var renderTarget3 : RenderTarget = new RenderTarget(size, size, textureResource, 3, 0xffffffff); var renderTarget4 : RenderTarget = new RenderTarget(size, size, textureResource, 4, 0xffffffff); var renderTarget5 : RenderTarget = new RenderTarget(size, size, textureResource, 5, 0xffffffff); passes.push( new CubeShadowMapShader(lightId, 0, lightId + 0.1, renderTarget0), new CubeShadowMapShader(lightId, 1, lightId + 0.2, renderTarget1), new CubeShadowMapShader(lightId, 2, lightId + 0.3, renderTarget2), new CubeShadowMapShader(lightId, 3, lightId + 0.4, renderTarget3), new CubeShadowMapShader(lightId, 4, lightId + 0.5, renderTarget4), new CubeShadowMapShader(lightId, 5, lightId + 0.6, renderTarget5) ); } private function lightPropertyExists(lightId : uint, propertyName : String) : Boolean { return _scene.bindings.propertyExists( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } private function getLightProperty(lightId : uint, propertyName : String) : * { return _scene.bindings.getProperty( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } } }
remove trace() in AbstractShadowMappingEffect
remove trace() in AbstractShadowMappingEffect
ActionScript
mit
aerys/minko-as3
b81624dbd934ffdda2336980e55306fdf6d0af45
src/org/flintparticles/common/initializers/DictionaryInitializer.as
src/org/flintparticles/common/initializers/DictionaryInitializer.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2010 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.initializers { import org.flintparticles.common.emitters.Emitter; import org.flintparticles.common.particles.Particle; /** * The DictionaryInit Initializer copies properties from an initializing object to a particle's dictionary. */ public class DictionaryInitializer extends InitializerBase { private var _initValues:*; /** * The constructor creates a DictionaryInit initializer for use by * an emitter. To add a DictionaryInit to all particles created by an emitter, use the * emitter's addInitializer method. * * @param initValues The object containing the properties for copying to the particle's dictionary. * May be an object or a dictionary. * * @see org.flintparticles.common.emitters.Emitter#addInitializer() */ public function DictionaryInitializer( initValues:* ) { _initValues = initValues; } /** * The object containing the properties for copying to the particle's dictionary. * May be an object or a dictionary. */ public function get initValues():* { return _initValues; } public function set initValues( value:* ):void { _initValues = value; } /** * @inheritDoc */ override public function initialize( emitter:Emitter, particle:Particle ):void { if ( !_initValues ) { return; } for( var key:* in _initValues ) { particle.dictionary[ key ] = _initValues[ key ]; } } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2010 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.initializers { import org.flintparticles.common.emitters.Emitter; import org.flintparticles.common.particles.Particle; /** * The Dictionary Initializer copies properties from an initializing object to a particle's dictionary. */ public class DictionaryInitializer extends InitializerBase { private var _initValues:*; /** * The constructor creates a DictionaryInit initializer for use by * an emitter. To add a DictionaryInit to all particles created by an emitter, use the * emitter's addInitializer method. * * @param initValues The object containing the properties for copying to the particle's dictionary. * May be an object or a dictionary. * * @see org.flintparticles.common.emitters.Emitter#addInitializer() */ public function DictionaryInitializer( initValues:* ) { _initValues = initValues; } /** * The object containing the properties for copying to the particle's dictionary. * May be an object or a dictionary. */ public function get initValues():* { return _initValues; } public function set initValues( value:* ):void { _initValues = value; } /** * @inheritDoc */ override public function initialize( emitter:Emitter, particle:Particle ):void { if ( !_initValues ) { return; } for( var key:* in _initValues ) { particle.dictionary[ key ] = _initValues[ key ]; } } } }
Fix incorrect class name in class description
Fix incorrect class name in class description
ActionScript
mit
richardlord/Flint
5314d2c9b9dbdcc00aeafe2427526cb05507fc21
src/aerys/minko/scene/controller/SkeletonController.as
src/aerys/minko/scene/controller/SkeletonController.as
package aerys.minko.scene.controller { /** * The SkeletonController aggregates AnimationController objects * and control them in order to start/stop playing animations on * multiple scene nodes at the same time and control a whole * skeleton. * * @author Jean-Marc Le Roux * */ public final class SkeletonController { private var _animations : Vector.<AnimationController> = null; public function SkeletonController(animations : Vector.<AnimationController>) { _animations = animations.slice(); } public function get animations() : Vector.<AnimationController> { return _animations; } public function seek(time : Object) : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).seek(time); return this; } public function stop() : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).stop(); return this; } public function play() : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).play(); return this; } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).setPlaybackWindow(beginTime, endTime); return this; } public function resetPlaybackWindow() : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).resetPlaybackWindow(); return this; } } }
package aerys.minko.scene.controller { import aerys.minko.scene.controller.animation.AnimationController; /** * The SkeletonController aggregates AnimationController objects * and control them in order to start/stop playing animations on * multiple scene nodes at the same time and control a whole * skeleton. * * @author Jean-Marc Le Roux * */ public final class SkeletonController { private var _animations : Vector.<AnimationController> = null; public function SkeletonController(animations : Vector.<AnimationController>) { _animations = animations.slice(); } public function get animations() : Vector.<AnimationController> { return _animations; } public function seek(time : Object) : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).seek(time); return this; } public function stop() : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).stop(); return this; } public function play() : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).play(); return this; } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).setPlaybackWindow(beginTime, endTime); return this; } public function resetPlaybackWindow() : SkeletonController { var numAnimations : uint = _animations.length; for (var animId : uint = 0; animId < numAnimations; ++animId) (_animations[animId] as AnimationController).resetPlaybackWindow(); return this; } } }
add MasterAnimationController
add MasterAnimationController
ActionScript
mit
aerys/minko-as3
494abd0e5b8c50d42339029ab5d39972af3fa975
frameworks/as/projects/FlexJSJX/src/org/apache/flex/effects/Move.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/effects/Move.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.effects { import org.apache.flex.core.IDocument; import org.apache.flex.core.IUIBase; /** * The Move effect animates a UI component's x or y position. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Move extends Tween implements IDocument { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param target Object ID or reference to an object that will * have its x and/or y property animated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Move(target:IUIBase = null) { super(); this.actualTarget = target; startValue = 0; endValue = 1; listener = this; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * The document. */ private var document:Object; /** * @private * The actual target. */ private var actualTarget:IUIBase; /** * The target as the String id * of a widget in an MXML Document. */ public var target:String; /** * The change in x. */ public var xBy:Number; /** * The change in y. */ public var yBy:Number; /** * @private * The starting x. */ private var xStart:Number; /** * @private * The staring y. */ private var yStart:Number; /** * Starting x value. If NaN, the current x value is used */ public var xFrom:Number; /** * Ending x value. If NaN, the current x value is not changed */ public var xTo:Number; /** * Starting y value. If NaN, the current y value is used */ public var yFrom:Number; /** * Ending y value. If NaN, the current y value is not changed */ public var yTo:Number; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- public function setDocument(document:Object, id:String = null):void { this.document = document; } /** * @private */ override public function play():void { if (target != null) actualTarget = document[target]; if (isNaN(xFrom)) xStart = actualTarget.x; if (isNaN(xBy)) { if (isNaN(xTo)) xBy = 0; else xBy = xTo - xStart; } if (isNaN(yFrom)) yStart = actualTarget.y; if (isNaN(yBy)) { if (isNaN(yTo)) yBy = 0; else yBy = yTo - yStart; } super.play(); } public function onTweenUpdate(value:Number):void { if (xBy) actualTarget.x = xStart + value * xBy; if (yBy) actualTarget.y = yStart + value * yBy; } public function onTweenEnd(value:Number):void { if (xBy) actualTarget.x = xStart + xBy; if (yBy) actualTarget.y = yStart + yBy; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.effects { import org.apache.flex.core.IDocument; import org.apache.flex.core.IUIBase; /** * The Move effect animates a UI component's x or y position. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Move extends Tween implements IDocument { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param target Object ID or reference to an object that will * have its x and/or y property animated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Move(target:IUIBase = null) { super(); this.actualTarget = target; startValue = 0; endValue = 1; listener = this; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * The document. */ private var document:Object; /** * @private * The actual target. */ private var actualTarget:IUIBase; /** * The target as the String id * of a widget in an MXML Document. */ public var target:String; /** * The change in x. */ public var xBy:Number; /** * The change in y. */ public var yBy:Number; /** * @private * The starting x. */ private var xStart:Number; /** * @private * The staring y. */ private var yStart:Number; /** * Starting x value. If NaN, the current x value is used */ public var xFrom:Number; /** * Ending x value. If NaN, the current x value is not changed */ public var xTo:Number; /** * Starting y value. If NaN, the current y value is used */ public var yFrom:Number; /** * Ending y value. If NaN, the current y value is not changed */ public var yTo:Number; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- public function setDocument(document:Object, id:String = null):void { this.document = document; } /** * @private */ override public function play():void { if (target != null) actualTarget = document[target]; if (isNaN(xFrom)) xStart = actualTarget.x; else xStart = xFrom; if (isNaN(xBy)) { if (isNaN(xTo)) xBy = 0; else xBy = xTo - xStart; } if (isNaN(yFrom)) yStart = actualTarget.y; else yStart = yFrom; if (isNaN(yBy)) { if (isNaN(yTo)) yBy = 0; else yBy = yTo - yStart; } super.play(); } public function onTweenUpdate(value:Number):void { if (xBy) actualTarget.x = xStart + value * xBy; if (yBy) actualTarget.y = yStart + value * yBy; } public function onTweenEnd(value:Number):void { if (xBy) actualTarget.x = xStart + xBy; if (yBy) actualTarget.y = yStart + yBy; } } }
fix bug in startup
fix bug in startup
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
1d97eaf75c1e554cadd8ae7c295b9619d8c40c02
common/actionscript/org/concord/sparks/circuit/resistor/resistor_5band/Resistor.as
common/actionscript/org/concord/sparks/circuit/resistor/resistor_5band/Resistor.as
package org.concord.sparks.circuit.resistor.resistor_5band { import flash.display.Graphics; import flash.display.Loader; import flash.display.MovieClip; import flash.display.Shape; import flash.events.MouseEvent; import flash.events.IOErrorEvent; import flash.geom.Point; import flash.net.URLRequest; import org.concord.sparks.util.Assert; public class Resistor { // Instance names in Flash movie public static var names = { resistorContainer : 'resistor_5band_mc', leftLeadRollOver : 'resistor_rollover', rightLeadRollOver : 'resistor_rollover_right', leftLeadEngaged : 'probe_engaged', rightLeadEngaged : 'probe_engaged_right' }; var root; var container:MovieClip; var value:Number; var x = 430; var y = 200; var width = 260; var height = 80; public var lead1:ResistorLead; public var lead2:ResistorLead; public var snapRadius = 35; var band1Loader:Loader = new Loader(); var band2Loader:Loader = new Loader(); var band3Loader:Loader = new Loader(); var band4Loader:Loader = new Loader(); var band5Loader:Loader = new Loader(); var colors = []; public function Resistor(root) { this.root = root; // Assert the root has the named objects for each (var name:String in names) { Assert.assertContains(root, name); } lead1 = new ResistorLead('resistor_lead1', new Point(591, 104), root[names.leftLeadRollOver], root[names.leftLeadEngaged]); lead2 = new ResistorLead('resistor_lead2', new Point(867, 102), root[names.rightLeadRollOver], root[names.rightLeadEngaged]); container = root[names.resistorContainer]; container.band1.addChild(band1Loader); container.band2.addChild(band2Loader); container.band3.addChild(band3Loader); container.band4.addChild(band4Loader); container.band5.addChild(band5Loader); setLabel('red', 'white', 'blue', 'black', 'silver'); } public function show() { container.visible = true; } public function hide() { container.visible = false; } public function isVisible():Boolean { return container.visible; } public function getColors() { return colors; } public function setLabel(color1, color2, color3, color4, color5):void { trace('Enter setLabel'); this.colors = [color1, color2, color3, color4, color5]; loadBandImage(band1Loader, 't_' + color1 + '.png'); loadBandImage(band2Loader, 's_' + color2 + '.png'); loadBandImage(band3Loader, 's_' + color3 + '.png'); loadBandImage(band4Loader, 's_' + color4 + '.png'); loadBandImage(band5Loader, 's_' + color5 + '.png'); } private function loadBandImage(loader:Loader, fname:String):void { var s = '../../common/images/resistor/' + fname; //trace('path=' + s); try { var req:URLRequest = new URLRequest(s); loader.load(req); //trace('Loaded ' + s); } catch (e:IOErrorEvent) { trace("Failed to load " + s); } } } }
package org.concord.sparks.circuit.resistor.resistor_5band { import flash.display.Graphics; import flash.display.Loader; import flash.display.MovieClip; import flash.display.Shape; import flash.events.MouseEvent; import flash.events.IOErrorEvent; import flash.geom.Point; import flash.net.URLRequest; import org.concord.sparks.util.Assert; public class Resistor { // Instance names in Flash movie public static var names = { resistorContainer : 'resistor_5band_mc', leftLeadRollOver : 'resistor_rollover', rightLeadRollOver : 'resistor_rollover_right', leftLeadEngaged : 'probe_engaged', rightLeadEngaged : 'probe_engaged_right' }; var root; var container:MovieClip; var value:Number; var x = 430; var y = 200; var width = 260; var height = 80; public var lead1:ResistorLead; public var lead2:ResistorLead; public var snapRadius = 35; var band1Loader:Loader = new Loader(); var band2Loader:Loader = new Loader(); var band3Loader:Loader = new Loader(); var band4Loader:Loader = new Loader(); var band5Loader:Loader = new Loader(); var colors = []; public function Resistor(root) { this.root = root; // Assert the root has the named objects for each (var name:String in names) { Assert.assertContains(root, name); } lead1 = new ResistorLead('resistor_lead1', new Point(591, 104), root[names.leftLeadRollOver], root[names.leftLeadEngaged]); lead2 = new ResistorLead('resistor_lead2', new Point(867, 102), root[names.rightLeadRollOver], root[names.rightLeadEngaged]); container = root[names.resistorContainer]; container.band1.addChild(band1Loader); container.band2.addChild(band2Loader); container.band3.addChild(band3Loader); container.band4.addChild(band4Loader); container.band5.addChild(band5Loader); setLabel('red', 'white', 'blue', 'black', 'silver'); } public function show() { container.visible = true; } public function hide() { container.visible = false; } public function isVisible():Boolean { return container.visible; } public function getColors() { return colors; } public function setLabel(color1, color2, color3, color4, color5):void { trace('Enter setLabel'); this.colors = [color1, color2, color3, color4, color5]; loadBandImage(band1Loader, 't_' + color1 + '.png'); loadBandImage(band2Loader, 's_' + color2 + '.png'); loadBandImage(band3Loader, 's_' + color3 + '.png'); loadBandImage(band4Loader, 's_' + color4 + '.png'); loadBandImage(band5Loader, 's_' + color5 + '.png'); } private function loadBandImage(loader:Loader, fname:String):void { var s = '/sparks-content/common/images/resistor/' + fname; //trace('path=' + s); try { var req:URLRequest = new URLRequest(s); loader.load(req); //trace('Loaded ' + s); } catch (e:IOErrorEvent) { trace("Failed to load " + s); } } } }
use full path for resistor images
use full path for resistor images
ActionScript
apache-2.0
concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks
793f09c47adf5907c91e06dbe8a56c8f1828f06b
exporter/src/main/as/flump/xfl/XflMovie.as
exporter/src/main/as/flump/xfl/XflMovie.as
// // Flump - Copyright 2013 Flump Authors package flump.xfl { import aspire.util.Set; import aspire.util.Sets; import aspire.util.XmlUtil; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.MovieMold; public class XflMovie extends XflSymbol { use namespace xflns; /** Returns true if the given movie symbol is marked for "Export for ActionScript" */ public static function isExported (xml :XML) :Boolean { return XmlUtil.hasAttr(xml, EXPORT_CLASS_NAME); } /** Returns the library name of the given movie */ public static function getName (xml :XML) :String { return XmlUtil.getStringAttr(xml, NAME); } /** Return a Set of all the symbols this movie references. */ public static function getSymbolNames (mold :MovieMold) :Set { var names :Set = Sets.newSetOf(String); for each (var layer :LayerMold in mold.layers) { if (!layer.flipbook) { for each (var kf :KeyframeMold in layer.keyframes) { if (kf.ref != null) names.add(kf.ref); } } } return names; } public static function parse (lib :XflLibrary, xml :XML) :MovieMold { const movie :MovieMold = new MovieMold(); const name :String = getName(xml); const exportName :String = XmlUtil.getStringAttr(xml, EXPORT_CLASS_NAME, null); movie.id = lib.createId(movie, name, exportName); const location :String = lib.location + ":" + movie.id; const layerEls :XMLList = xml.timeline.DOMTimeline[0].layers.DOMLayer; if (XmlUtil.getStringAttr(layerEls[0], XflLayer.NAME) == "flipbook") { movie.layers.push(XflLayer.parse(lib, location, layerEls[0], true)); if (exportName == null) { lib.addError(location, ParseError.CRIT, "Flipbook movie '" + movie.id + "' not exported"); } for each (var kf :KeyframeMold in movie.layers[0].keyframes) { kf.ref = movie.id + "_flipbook_" + kf.index; } } else { var maskName:String; for each (var layerEl :XML in layerEls) { var layerType :String = XmlUtil.getStringAttr(layerEl, XflLayer.TYPE, ""); if ((layerType != XflLayer.TYPE_GUIDE) && (layerType != XflLayer.TYPE_FOLDER)) { if (XmlUtil.hasAttr(layerEl, "parentLayerIndex")) { if (maskName) { movie.layers.unshift(XflLayer.parse(lib, location, layerEl, false, maskName)); } else { lib.addError(location, ParseError.WARN, "Only one masked layer is authorized on '" + movie.id + "'. The other masked layers are ignored from mask."); movie.layers.unshift(XflLayer.parse(lib, location, layerEl, false)); } } else movie.layers.unshift(XflLayer.parse(lib, location, layerEl, false)); maskName = layerType == XflLayer.TYPE_MASK ? movie.layers[0].name : null; } } } movie.fillLabels(); if (movie.layers.length == 0) { lib.addError(location, ParseError.CRIT, "Movies must have at least one layer"); } return movie; } } }
// // Flump - Copyright 2013 Flump Authors package flump.xfl { import aspire.util.Set; import aspire.util.Sets; import aspire.util.XmlUtil; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.MovieMold; public class XflMovie extends XflSymbol { use namespace xflns; /** Returns true if the given movie symbol is marked for "Export for ActionScript" */ public static function isExported (xml :XML) :Boolean { return XmlUtil.hasAttr(xml, EXPORT_CLASS_NAME); } /** Returns the library name of the given movie */ public static function getName (xml :XML) :String { return XmlUtil.getStringAttr(xml, NAME); } /** Return a Set of all the symbols this movie references. */ public static function getSymbolNames (mold :MovieMold) :Set { var names :Set = Sets.newSetOf(String); for each (var layer :LayerMold in mold.layers) { if (!layer.flipbook) { for each (var kf :KeyframeMold in layer.keyframes) { if (kf.ref != null) names.add(kf.ref); } } } return names; } public static function parse (lib :XflLibrary, xml :XML) :MovieMold { const movie :MovieMold = new MovieMold(); const name :String = getName(xml); const exportName :String = XmlUtil.getStringAttr(xml, EXPORT_CLASS_NAME, null); movie.id = lib.createId(movie, name, exportName); const location :String = lib.location + ":" + movie.id; const layerEls :XMLList = xml.timeline.DOMTimeline[0].layers.DOMLayer; if (XmlUtil.getStringAttr(xml, EXPORT_BASE_CLASS_NAME, null)=="Flipbook" || XmlUtil.getStringAttr(layerEls[0], XflLayer.NAME) == "flipbook") { movie.layers.push(XflLayer.parse(lib, location, layerEls[0], true)); if (exportName == null) { lib.addError(location, ParseError.CRIT, "Flipbook movie '" + movie.id + "' not exported"); } for each (var kf :KeyframeMold in movie.layers[0].keyframes) { kf.ref = movie.id + "_flipbook_" + kf.index; } } else { var maskName:String; for each (var layerEl :XML in layerEls) { var layerType :String = XmlUtil.getStringAttr(layerEl, XflLayer.TYPE, ""); if ((layerType != XflLayer.TYPE_GUIDE) && (layerType != XflLayer.TYPE_FOLDER)) { if (XmlUtil.hasAttr(layerEl, "parentLayerIndex")) { if (maskName) { movie.layers.unshift(XflLayer.parse(lib, location, layerEl, false, maskName)); } else { lib.addError(location, ParseError.WARN, "Only one masked layer is authorized on '" + movie.id + "'. The other masked layers are ignored from mask."); movie.layers.unshift(XflLayer.parse(lib, location, layerEl, false)); } } else movie.layers.unshift(XflLayer.parse(lib, location, layerEl, false)); maskName = layerType == XflLayer.TYPE_MASK ? movie.layers[0].name : null; } } } movie.fillLabels(); if (movie.layers.length == 0) { lib.addError(location, ParseError.CRIT, "Movies must have at least one layer"); } return movie; } } }
Fix merge Flipbook
Fix merge Flipbook
ActionScript
mit
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
c79659c0db8fb64119f5c96a39334791e4e83348
src/AIR/ChildBrowser/src/blackberry/polarmobile/childbrowser/ChildBrowser.as
src/AIR/ChildBrowser/src/blackberry/polarmobile/childbrowser/ChildBrowser.as
/** * Author: Shane Jonas * Child Browser Implementation for the PlayBook */ package blackberry.polarmobile.childbrowser { // flash import flash.geom.Rectangle; import flash.display.Stage; import flash.events.MouseEvent; import flash.display.Sprite; import flash.events.StageOrientationEvent; import flash.utils.setTimeout; import caurina.transitions.Tweener; // qnx import qnx.media.QNXStageWebView; import qnx.ui.buttons.IconButton; import qnx.ui.skins.buttons.OutlineButtonSkinBlack; // webworks import webworks.extension.DefaultExtension; public class ChildBrowser extends DefaultExtension { private var childWebView:QNXStageWebView = null; private var closeButton:IconButton; private var refreshButton:IconButton; private var bgshape:Sprite; private var loading_bg_shape:Sprite; private var browserHeight; private var isVisible:Boolean = false; private var webViewUI:Sprite; //icons [Embed(source="assets/close.png")] public static var Close:Class; [Embed(source="assets/refresh.png")] public static var Refresh:Class; [Embed(source="assets/ajax-spinner-black-bg.gif")] public static var Spinner:Class; public function ChildBrowser() { super(); this.isVisible = false } override public function getFeatureList():Array { return new Array ("blackberry.polarmobile.childbrowser"); } private function initBG() { var self = this; webViewUI = new Sprite(); bgshape = new Sprite(); bgshape.graphics.beginFill(0x323232); bgshape.graphics.drawRect(0,0,webView.stage.stageWidth, webView.stage.stageHeight); webViewUI.addChildAt(bgshape, 0); //build buttons this.initUI(); webViewUI.y = webView.stage.stageHeight; webView.stage.addChild(webViewUI); function loaded(){ setTimeout(function(){ childWebView.stage = webView.stage; childWebView.zOrder = 1; self.isVisible = true; }, 1000); } Tweener.addTween(webViewUI, { y: 0, time: 1, transition: 'easeOutExpo', onComplete: loaded }); } public function clearCookies() { //if we dont have a webview, make one and put it in the background this.createBrowser() //clear the webviews cookies childWebView.clearCookies(); childWebView.stage = null; //childWebView.dispose(); //childWebView = null; } private function createBrowser() { if (childWebView == null) { childWebView = new QNXStageWebView("ChildBrowser"); childWebView.stage = webView.stage; childWebView.viewPort = new Rectangle(0,50,webView.stage.stageWidth,browserHeight); childWebView.zOrder = -1; this.isVisible = true // events webView.stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, onOrientationChange); } } public function loadURL(url:String) { var self = this; browserHeight = webView.stage.stageHeight - 50; //if we dont have a webview, make one and put it in the background this.createBrowser(); //put webview behind stage webView.zOrder = -1; //load this url childWebView.loadURL(url); this.initBG(); } private function onOrientationChange(event:StageOrientationEvent) { var self = this this.removeUI(); this.initBG() childWebView.viewPort = new Rectangle(0,50,bgshape.width,bgshape.height - 50); } public function getLocation():String { return childWebView.location; } public function forward() { childWebView.historyForward(); } public function back() { childWebView.historyBack(); } public function refresh() { childWebView.reload(); } public function close() { childWebView.stage = null; childWebView.dispose(); childWebView = null; Tweener.addTween(webViewUI, { y: webView.stage.stageHeight, delay: 0.5, time: 1, transition: 'easeOutExpo', onComplete: closeUI }); } private function closeUI() { // the `dispose` method does not work when running inside of webworks, // as it closes then main `webView` instance. as a temp. work-around, // we hide the child this.removeUI(); webView.stage.removeChild(webViewUI); this.isVisible = false; webView.zOrder = 1; } public function closeCLICK(e:MouseEvent) { this.close(); } public function refreshCLICK(e:MouseEvent) { this.refresh(); } private function removeUI() { removeChild(bgshape); removeChild(closeButton); removeChild(refreshButton) } //close button private function addClose() { closeButton = new IconButton(); closeButton.setIcon(new Close()); closeButton.setSize(266, 50); closeButton.setPosition(-5, 0); closeButton.setSkin(new OutlineButtonSkinBlack()); closeButton.addEventListener(MouseEvent.CLICK, closeCLICK); addChild(closeButton); } //refresh button private function addRefresh() { refreshButton = new IconButton(); refreshButton.setIcon(new Refresh()); refreshButton.setSize(266, 50); refreshButton.setPosition(256, 0); refreshButton.setSkin(new OutlineButtonSkinBlack()) refreshButton.addEventListener(MouseEvent.CLICK, refreshCLICK); addChild(refreshButton); } // UI Buttons private function initUI() { this.addClose(); this.addRefresh(); } public function getVisible():Boolean { return this.isVisible; } // our own addChild implementation // maps back to stage of WebWorkAppTemplate.as private function addChild(obj) { webViewUI.addChild(obj); //always set added obj's to top //webViewUI.setChildIndex(obj, webView.stage.numChildren -1); } private function removeChild(obj) { webViewUI.removeChild(obj); } } }
/** * Author: Shane Jonas * Child Browser Implementation for the PlayBook */ package blackberry.polarmobile.childbrowser { // flash import flash.geom.Rectangle; import flash.display.Stage; import flash.events.MouseEvent; import flash.display.Sprite; import flash.events.StageOrientationEvent; import flash.utils.setTimeout; import caurina.transitions.Tweener; // qnx import qnx.media.QNXStageWebView; import qnx.ui.buttons.IconButton; import qnx.ui.skins.buttons.OutlineButtonSkinBlack; // webworks import webworks.extension.DefaultExtension; public class ChildBrowser extends DefaultExtension { private var childWebView:QNXStageWebView = null; private var closeButton:IconButton; private var refreshButton:IconButton; private var bgshape:Sprite; private var loading_bg_shape:Sprite; private var browserHeight; private var isVisible:Boolean = false; private var webViewUI:Sprite; //icons [Embed(source="assets/close.png")] public static var Close:Class; [Embed(source="assets/refresh.png")] public static var Refresh:Class; [Embed(source="assets/ajax-spinner-black-bg.gif")] public static var Spinner:Class; public function ChildBrowser() { super(); this.isVisible = false } override public function getFeatureList():Array { return new Array ("blackberry.polarmobile.childbrowser"); } private function initBG() { if (this.isVisible) { return; } var self = this; webViewUI = new Sprite(); bgshape = new Sprite(); bgshape.graphics.beginFill(0x323232); bgshape.graphics.drawRect(0,0,webView.stage.stageWidth, webView.stage.stageHeight); webViewUI.addChildAt(bgshape, 0); //build buttons this.initUI(); webViewUI.y = webView.stage.stageHeight; webView.stage.addChild(webViewUI); function loaded(){ setTimeout(function(){ childWebView.stage = webView.stage; childWebView.zOrder = 1; self.isVisible = true; }, 1000); } Tweener.addTween(webViewUI, { y: 0, time: 1, transition: 'easeOutExpo', onComplete: loaded }); } public function clearCookies() { //if we dont have a webview, make one and put it in the background this.createBrowser() //clear the webviews cookies childWebView.clearCookies(); childWebView.stage = null; //childWebView.dispose(); //childWebView = null; } private function createBrowser() { if (childWebView == null) { childWebView = new QNXStageWebView("ChildBrowser"); childWebView.stage = webView.stage; childWebView.viewPort = new Rectangle(0,50,webView.stage.stageWidth,browserHeight); childWebView.zOrder = -1; // events webView.stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, onOrientationChange); } } public function loadURL(url:String) { var self = this; browserHeight = webView.stage.stageHeight - 50; //if we dont have a webview, make one and put it in the background this.createBrowser(); //put webview behind stage webView.zOrder = -1; //load this url childWebView.loadURL(url); this.initBG(); } private function onOrientationChange(event:StageOrientationEvent) { var self = this this.removeUI(); this.initBG() childWebView.viewPort = new Rectangle(0,50,bgshape.width,bgshape.height - 50); } public function getLocation():String { return childWebView.location; } public function forward() { childWebView.historyForward(); } public function back() { childWebView.historyBack(); } public function refresh() { childWebView.reload(); } public function close() { childWebView.stage = null; childWebView.dispose(); childWebView = null; Tweener.addTween(webViewUI, { y: webView.stage.stageHeight, delay: 0.5, time: 1, transition: 'easeOutExpo', onComplete: closeUI }); } private function closeUI() { // the `dispose` method does not work when running inside of webworks, // as it closes then main `webView` instance. as a temp. work-around, // we hide the child this.removeUI(); webView.stage.removeChild(webViewUI); webView.zOrder = 1; } public function closeCLICK(e:MouseEvent) { this.close(); } public function refreshCLICK(e:MouseEvent) { this.refresh(); } private function removeUI() { removeChild(bgshape); removeChild(closeButton); removeChild(refreshButton) this.isVisible = false; } //close button private function addClose() { closeButton = new IconButton(); closeButton.setIcon(new Close()); closeButton.setSize(266, 50); closeButton.setPosition(-5, 0); closeButton.setSkin(new OutlineButtonSkinBlack()); closeButton.addEventListener(MouseEvent.CLICK, closeCLICK); addChild(closeButton); } //refresh button private function addRefresh() { refreshButton = new IconButton(); refreshButton.setIcon(new Refresh()); refreshButton.setSize(266, 50); refreshButton.setPosition(256, 0); refreshButton.setSkin(new OutlineButtonSkinBlack()) refreshButton.addEventListener(MouseEvent.CLICK, refreshCLICK); addChild(refreshButton); } // UI Buttons private function initUI() { this.addClose(); this.addRefresh(); } public function getVisible():Boolean { return this.isVisible; } // our own addChild implementation // maps back to stage of WebWorkAppTemplate.as private function addChild(obj) { webViewUI.addChild(obj); //always set added obj's to top //webViewUI.setChildIndex(obj, webView.stage.numChildren -1); } private function removeChild(obj) { webViewUI.removeChild(obj); } } }
fix issue with multiple sets of controls being created if loadURL() called multiple times
fix issue with multiple sets of controls being created if loadURL() called multiple times
ActionScript
mit
polarmobile/blackberry.polarmobile.childbrowser
338ec3c2c3757e669e43ed4a89116b20267f7784
actionscript-cafe/src/main/flex/org/servebox/cafe/core/modularity/LocalApplicationUnitImpl.as
actionscript-cafe/src/main/flex/org/servebox/cafe/core/modularity/LocalApplicationUnitImpl.as
package org.servebox.cafe.core.modularity { import flash.utils.getQualifiedClassName; import org.servebox.cafe.core.Container; import org.servebox.cafe.core.application.ApplicationInitializer; import org.servebox.cafe.core.layout.ILayoutArea; import org.servebox.cafe.core.layout.ILayoutAreaManager; import org.servebox.cafe.core.observer.AbstractObserver; import org.servebox.cafe.core.signal.ISignalObserver; import org.servebox.cafe.core.signal.SignalAggregator; import org.servebox.cafe.core.spring.IApplicationContext; import org.servebox.cafe.core.spring.IApplicationContextListener; import org.servebox.cafe.core.util.ApplicationUnitUtils; import org.servebox.cafe.core.view.IView; public class LocalApplicationUnitImpl extends AbstractObserver implements IApplicationUnit, IApplicationContextListener, ISignalObserver { private var _id : String; private var _loadAtStartup :Boolean = false; private var _configLocations : Array; private var _context : IApplicationContext; [Autowired] public var signalAggregator : SignalAggregator; public function LocalApplicationUnitImpl() { super(); } public function get id():String { return _id; } public function set id(value:String):void { _id = value; } public function get loadAtStartup():Boolean { return _loadAtStartup; } public function set loadAtStartup(value:Boolean):void { _loadAtStartup = value; } public function get configLocations():Array { if( _configLocations == null ) { _configLocations = [ApplicationUnitUtils.getDefaultContextLocation( this )]; } return _configLocations; } public function set configLocations(value:Array):void { _configLocations = value; } protected function getContext() : IApplicationContext { return _context; } protected function initializeContext( parentContext : IApplicationContext ) : void { _context = ApplicationInitializer.getContextInstance( configLocations, parentContext ); } public function prepare(parentContext:IApplicationContext):void { initializeContext( parentContext ); // Should we do that ? I guess so getContext().setListener( this ); getContext().load(); } public function applicationContextReady() : void { start(); } public function getLayoutAreaManager() : ILayoutAreaManager { return Container.getInstance().getLayoutAreaManager(); } public function cleanLayout( layoutName : String ) : void { var layoutArea : ILayoutArea = getLayoutAreaManager().getArea(layoutName); for each ( var view : IView in layoutArea.getViews() ) { layoutArea.remove(view); } } public function getView( id : String ) : IView { return getContext().getObject(getQualifiedClassName(this) + id ); } public function start():void { } } }
package org.servebox.cafe.core.modularity { import flash.utils.getQualifiedClassName; import org.servebox.cafe.core.Container; import org.servebox.cafe.core.application.ApplicationInitializer; import org.servebox.cafe.core.layout.ILayoutArea; import org.servebox.cafe.core.layout.ILayoutAreaManager; import org.servebox.cafe.core.observer.AbstractObserver; import org.servebox.cafe.core.signal.ISignalObserver; import org.servebox.cafe.core.signal.SignalAggregator; import org.servebox.cafe.core.spring.IApplicationContext; import org.servebox.cafe.core.spring.IApplicationContextListener; import org.servebox.cafe.core.util.ApplicationUnitUtils; import org.servebox.cafe.core.view.IView; public class LocalApplicationUnitImpl extends AbstractObserver implements IApplicationUnit, IApplicationContextListener, ISignalObserver { private var _id : String; private var _loadAtStartup :Boolean = false; private var _configLocations : Array; private var _context : IApplicationContext; [Autowired] public var signalAggregator : SignalAggregator; public function LocalApplicationUnitImpl() { super(); } public function get id():String { return _id; } public function set id(value:String):void { _id = value; } public function get loadAtStartup():Boolean { return _loadAtStartup; } public function set loadAtStartup(value:Boolean):void { _loadAtStartup = value; } public function get configLocations():Array { if( _configLocations == null ) { _configLocations = [ApplicationUnitUtils.getDefaultContextLocation( this )]; } return _configLocations; } public function set configLocations(value:Array):void { _configLocations = value; } protected function getContext() : IApplicationContext { return _context; } protected function initializeContext( parentContext : IApplicationContext ) : void { _context = ApplicationInitializer.getContextInstance( configLocations, parentContext ); } public function prepare(parentContext:IApplicationContext):void { initializeContext( parentContext ); // Should we do that ? I guess so getContext().setListener( this ); getContext().load(); } public function applicationContextReady() : void { start(); } public function getLayoutAreaManager() : ILayoutAreaManager { return Container.getInstance().getLayoutAreaManager(); } public function cleanLayout( layoutName : String ) : void { var layoutArea : ILayoutArea = getLayoutAreaManager().getArea(layoutName); for each ( var view : IView in layoutArea.getViews() ) { layoutArea.remove(view); } } public function getView( id : String ) : IView { return getContext().getObject( id ); } public function start():void { } } }
Remove applicationunit name from view id in applicationunit context.
Remove applicationunit name from view id in applicationunit context.
ActionScript
mit
servebox/as-cafe
04d74d3f337cfecaa8ff4db4b6045ca9d10a0469
bin/Data/Scripts/40_Localization.as
bin/Data/Scripts/40_Localization.as
// Localization example. // This sample demonstrates: // - Loading a collection of strings from JSON-files // - Creating text elements that automatically translates itself by changing the language // - The manually reaction to change language #include "Scripts/Utilities/Sample.as" void Start() { // Execute the common startup for samples SampleStart(); // Enable OS cursor input.mouseVisible = true; // Load strings from JSON files and subscribe to the change language event InitLocalizationSystem(); // Init the 3D space CreateScene(); // Init the user interface CreateGUI(); } void InitLocalizationSystem() { // JSON files must be in UTF8 encoding without BOM // The first founded language will be set as current localization.LoadJSONFile("StringsEnRu.json"); // You can load multiple files localization.LoadJSONFile("StringsDe.json"); // Hook up to the change language SubscribeToEvent("ChangeLanguage", "HandleChangeLanguage"); } void CreateGUI() { ui.root.defaultStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml"); Window@ window = Window(); ui.root.AddChild(window); window.SetMinSize(384, 192); window.SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6)); window.SetAlignment(HA_CENTER, VA_CENTER); window.SetStyleAuto(); Text@ windowTitle = Text(); windowTitle.name = "WindowTitle"; windowTitle.SetStyleAuto(); window.AddChild(windowTitle); // In this place the current language is "en" because it was found first when loading the JSON files String langName = localization.language; // Languages are numbered in the loading order int langIndex = localization.languageIndex; // == 0 at the beginning // Get string with identifier "title" in the current language String localizedString = localization.Get("title"); // Localization.Get returns String::EMPTY if the id is empty. // Localization.Get returns the id if translation is not found and will be added a warning into the log. windowTitle.text = localizedString + " (" + String(langIndex) + " " + langName + ")"; Button@ b = Button(); window.AddChild(b); b.SetStyle("Button"); b.minHeight = 24; Text@ t = b.CreateChild("Text", "ButtonTextChangeLang"); // The showing text value will automatically change when language is changed t.autoLocalizable = true; // The text value used as a string identifier in this mode. // Remember that a letter case of the id and of the lang name is important. t.text = "Press this button"; t.SetAlignment(HA_CENTER, VA_CENTER); t.SetStyle("Text"); SubscribeToEvent(b, "Released", "HandleChangeLangButtonPressed"); b = Button(); window.AddChild(b); b.SetStyle("Button"); b.minHeight = 24; t = b.CreateChild("Text", "ButtonTextQuit"); t.SetAlignment(HA_CENTER, VA_CENTER); t.SetStyle("Text"); // Manually set text in the current language t.text = localization.Get("quit"); SubscribeToEvent(b, "Released", "HandleQuitButtonPressed"); } void CreateScene() { scene_ = Scene(); scene_.CreateComponent("Octree"); Zone@ zone = scene_.CreateComponent("Zone"); zone.boundingBox = BoundingBox(-1000.0f, 1000.0f); zone.ambientColor = Color(0.5f, 0.5f, 0.5f); zone.fogColor = Color(0.4f, 0.5f, 0.8f); zone.fogStart = 1.0f; zone.fogEnd = 100.0f; Node@ planeNode = scene_.CreateChild("Plane"); planeNode.scale = Vector3(300.0f, 1.0f, 300.0f); StaticModel@ planeObject = planeNode.CreateComponent("StaticModel"); planeObject.model = cache.GetResource("Model", "Models/Plane.mdl"); planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml"); Node@ lightNode = scene_.CreateChild("DirectionalLight"); lightNode.direction = Vector3(0.6f, -1.0f, 0.8f); Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; light.color = Color(0.8f, 0.8f, 0.8f); cameraNode = scene_.CreateChild("Camera"); cameraNode.CreateComponent("Camera"); cameraNode.position = Vector3(0.0f, 10.0f, -30.0f); Node@ text3DNode = scene_.CreateChild("Text3D"); text3DNode.position = Vector3(0.0f, 0.1f, 30.0f); text3DNode.SetScale(15); Text3D@ text3D = text3DNode.CreateComponent("Text3D"); // Manually set text in the current language. text3D.text = localization.Get("lang"); text3D.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30); text3D.color = Color::BLACK; text3D.SetAlignment(HA_CENTER, VA_BOTTOM); Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; SubscribeToEvent("Update", "HandleUpdate"); } void HandleUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); const float MOUSE_SENSITIVITY = 0.1f; IntVector2 mouseMove = input.mouseMove; yaw += MOUSE_SENSITIVITY * mouseMove.x; pitch += MOUSE_SENSITIVITY * mouseMove.y; pitch = Clamp(pitch, -90.0f, 90.0f); cameraNode.rotation = Quaternion(pitch, yaw, 0.0f); } void HandleChangeLangButtonPressed(StringHash eventType, VariantMap& eventData) { // Languages are numbered in the loading order int lang = localization.languageIndex; lang++; if (lang >= localization.numLanguages) lang = 0; localization.SetLanguage(lang); } void HandleQuitButtonPressed(StringHash eventType, VariantMap& eventData) { engine.Exit(); } // You can manually change texts, sprites and other aspects of the game when language is changed void HandleChangeLanguage(StringHash eventType, VariantMap& eventData) { Text@ windowTitle = ui.root.GetChild("WindowTitle", true); windowTitle.text = localization.Get("title") + " (" + String(localization.languageIndex) + " " + localization.language + ")"; Text@ buttonText = ui.root.GetChild("ButtonTextQuit", true); buttonText.text = localization.Get("quit"); Text3D@ text3D = scene_.GetChild("Text3D").GetComponent("Text3D"); text3D.text = localization.Get("lang"); // A text on the button "Press this button" changes automatically } String patchInstructions = "";
// Localization example. // This sample demonstrates: // - Loading a collection of strings from JSON-files // - Creating text elements that automatically translates itself by changing the language // - The manually reaction to change language #include "Scripts/Utilities/Sample.as" void Start() { // Execute the common startup for samples SampleStart(); // Enable OS cursor input.mouseVisible = true; // Load strings from JSON files and subscribe to the change language event InitLocalizationSystem(); // Init the 3D space CreateScene(); // Init the user interface CreateGUI(); } void InitLocalizationSystem() { // JSON files must be in UTF8 encoding without BOM // The first founded language will be set as current localization.LoadJSONFile("StringsEnRu.json"); // You can load multiple files localization.LoadJSONFile("StringsDe.json"); // Hook up to the change language SubscribeToEvent("ChangeLanguage", "HandleChangeLanguage"); } void CreateGUI() { ui.root.defaultStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml"); Window@ window = Window(); ui.root.AddChild(window); window.SetMinSize(384, 192); window.SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6)); window.SetAlignment(HA_CENTER, VA_CENTER); window.SetStyleAuto(); Text@ windowTitle = Text(); windowTitle.name = "WindowTitle"; windowTitle.SetStyleAuto(); window.AddChild(windowTitle); // In this place the current language is "en" because it was found first when loading the JSON files String langName = localization.language; // Languages are numbered in the loading order int langIndex = localization.languageIndex; // == 0 at the beginning // Get string with identifier "title" in the current language String localizedString = localization.Get("title"); // Localization.Get returns String::EMPTY if the id is empty. // Localization.Get returns the id if translation is not found and will be added a warning into the log. windowTitle.text = localizedString + " (" + String(langIndex) + " " + langName + ")"; Button@ b = Button(); window.AddChild(b); b.SetStyle("Button"); b.minHeight = 24; Text@ t = b.CreateChild("Text", "ButtonTextChangeLang"); // The showing text value will automatically change when language is changed t.autoLocalizable = true; // The text value used as a string identifier in this mode. // Remember that a letter case of the id and of the lang name is important. t.text = "Press this button"; t.SetAlignment(HA_CENTER, VA_CENTER); t.SetStyle("Text"); SubscribeToEvent(b, "Released", "HandleChangeLangButtonPressed"); b = Button(); window.AddChild(b); b.SetStyle("Button"); b.minHeight = 24; t = b.CreateChild("Text", "ButtonTextQuit"); t.SetAlignment(HA_CENTER, VA_CENTER); t.SetStyle("Text"); // Manually set text in the current language t.text = localization.Get("quit"); SubscribeToEvent(b, "Released", "HandleQuitButtonPressed"); } void CreateScene() { scene_ = Scene(); scene_.CreateComponent("Octree"); Zone@ zone = scene_.CreateComponent("Zone"); zone.boundingBox = BoundingBox(-1000.0f, 1000.0f); zone.ambientColor = Color(0.5f, 0.5f, 0.5f); zone.fogColor = Color(0.4f, 0.5f, 0.8f); zone.fogStart = 1.0f; zone.fogEnd = 100.0f; Node@ planeNode = scene_.CreateChild("Plane"); planeNode.scale = Vector3(300.0f, 1.0f, 300.0f); StaticModel@ planeObject = planeNode.CreateComponent("StaticModel"); planeObject.model = cache.GetResource("Model", "Models/Plane.mdl"); planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml"); Node@ lightNode = scene_.CreateChild("DirectionalLight"); lightNode.direction = Vector3(0.6f, -1.0f, 0.8f); Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; light.color = Color(0.8f, 0.8f, 0.8f); cameraNode = scene_.CreateChild("Camera"); cameraNode.CreateComponent("Camera"); cameraNode.position = Vector3(0.0f, 10.0f, -30.0f); Node@ text3DNode = scene_.CreateChild("Text3D"); text3DNode.position = Vector3(0.0f, 0.1f, 30.0f); text3DNode.SetScale(15); Text3D@ text3D = text3DNode.CreateComponent("Text3D"); // Manually set text in the current language. text3D.text = localization.Get("lang"); text3D.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30); text3D.color = BLACK; text3D.SetAlignment(HA_CENTER, VA_BOTTOM); Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; SubscribeToEvent("Update", "HandleUpdate"); } void HandleUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); const float MOUSE_SENSITIVITY = 0.1f; IntVector2 mouseMove = input.mouseMove; yaw += MOUSE_SENSITIVITY * mouseMove.x; pitch += MOUSE_SENSITIVITY * mouseMove.y; pitch = Clamp(pitch, -90.0f, 90.0f); cameraNode.rotation = Quaternion(pitch, yaw, 0.0f); } void HandleChangeLangButtonPressed(StringHash eventType, VariantMap& eventData) { // Languages are numbered in the loading order int lang = localization.languageIndex; lang++; if (lang >= localization.numLanguages) lang = 0; localization.SetLanguage(lang); } void HandleQuitButtonPressed(StringHash eventType, VariantMap& eventData) { engine.Exit(); } // You can manually change texts, sprites and other aspects of the game when language is changed void HandleChangeLanguage(StringHash eventType, VariantMap& eventData) { Text@ windowTitle = ui.root.GetChild("WindowTitle", true); windowTitle.text = localization.Get("title") + " (" + String(localization.languageIndex) + " " + localization.language + ")"; Text@ buttonText = ui.root.GetChild("ButtonTextQuit", true); buttonText.text = localization.Get("quit"); Text3D@ text3D = scene_.GetChild("Text3D").GetComponent("Text3D"); text3D.text = localization.Get("lang"); // A text on the button "Press this button" changes automatically } String patchInstructions = "";
Fix Color::BLACK to just BLACK in Localization AngelScript sample. Thanks JSandusky.
Fix Color::BLACK to just BLACK in Localization AngelScript sample. Thanks JSandusky.
ActionScript
mit
helingping/Urho3D,PredatorMF/Urho3D,cosmy1/Urho3D,299299/Urho3D,helingping/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,carnalis/Urho3D,luveti/Urho3D,c4augustus/Urho3D,helingping/Urho3D,kostik1337/Urho3D,luveti/Urho3D,MonkeyFirst/Urho3D,xiliu98/Urho3D,urho3d/Urho3D,MonkeyFirst/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,eugeneko/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,codedash64/Urho3D,codemon66/Urho3D,henu/Urho3D,helingping/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,urho3d/Urho3D,tommy3/Urho3D,fire/Urho3D-1,SirNate0/Urho3D,SuperWangKai/Urho3D,luveti/Urho3D,abdllhbyrktr/Urho3D,299299/Urho3D,rokups/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,carnalis/Urho3D,cosmy1/Urho3D,bacsmar/Urho3D,rokups/Urho3D,eugeneko/Urho3D,SirNate0/Urho3D,299299/Urho3D,SuperWangKai/Urho3D,orefkov/Urho3D,henu/Urho3D,cosmy1/Urho3D,abdllhbyrktr/Urho3D,eugeneko/Urho3D,bacsmar/Urho3D,victorholt/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,weitjong/Urho3D,codedash64/Urho3D,rokups/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,xiliu98/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,xiliu98/Urho3D,PredatorMF/Urho3D,luveti/Urho3D,iainmerrick/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,tommy3/Urho3D,iainmerrick/Urho3D,weitjong/Urho3D,rokups/Urho3D,299299/Urho3D,MeshGeometry/Urho3D,victorholt/Urho3D,henu/Urho3D,codemon66/Urho3D,299299/Urho3D,codemon66/Urho3D,MonkeyFirst/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,tommy3/Urho3D,eugeneko/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,299299/Urho3D,victorholt/Urho3D,orefkov/Urho3D,victorholt/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,orefkov/Urho3D,PredatorMF/Urho3D,tommy3/Urho3D,carnalis/Urho3D,weitjong/Urho3D,fire/Urho3D-1,iainmerrick/Urho3D,carnalis/Urho3D,codedash64/Urho3D,henu/Urho3D,MeshGeometry/Urho3D,helingping/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,codemon66/Urho3D,tommy3/Urho3D,rokups/Urho3D,urho3d/Urho3D,victorholt/Urho3D,fire/Urho3D-1,codedash64/Urho3D,MeshGeometry/Urho3D,urho3d/Urho3D,codedash64/Urho3D,PredatorMF/Urho3D
e9d1d50ae0823be2473695e9977b9b19812e9a7b
src/main/actionscript/com/castlabs/dash/boxes/SampleEntry.as
src/main/actionscript/com/castlabs/dash/boxes/SampleEntry.as
/* * Copyright (c) 2014 castLabs GmbH * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.castlabs.dash.boxes { import com.castlabs.dash.DashContext; import flash.utils.ByteArray; public class SampleEntry extends Box { public static var channelCount:uint; public static var sampleSize:uint; private var _data:ByteArray; protected var _type:String; public function SampleEntry(context:DashContext, offset:uint, size:uint, type:String) { super(context, offset, size); _type = type; } public function get data():ByteArray { return _data; } public override function parse(ba:ByteArray):void { if (_type == "avc1") { parseAvc1(ba); } if (_type == "mp4a") { parseMp4a(ba); } ba.position = end; } protected function parseAvc1(ba:ByteArray):void { // skip ba.position += 78; parseAvc1Data(ba); } protected function parseMp4a(ba:ByteArray):void { // skip ba.position += 16; channelCount = ba.readUnsignedShort(); sampleSize = ba.readUnsignedShort(); // skip ba.position += 8; _data = parseMp4aData(ba); } private function parseAvc1Data(ba:ByteArray):void { ba.position = goToBox("avcC", ba); var size:Number = ba.readUnsignedInt(); // skip: type("avcC") ba.position += 4; _data = new ByteArray(); ba.readBytes(_data, 0, size - SIZE_AND_TYPE); } protected function goToBox(type:String, ba:ByteArray):uint { var typeBegin:String = type.slice(0, 1); var typeOther:String = type.slice(1); while (ba.bytesAvailable) { if (ba.readUTFBytes(typeBegin.length) != typeBegin) { continue; } if (ba.readUTFBytes(typeOther.length) == typeOther) { return ba.position - SIZE_AND_TYPE; } } throw _context.console.logAndBuildError("Couldn't find any '" + type + "' box"); } private function parseMp4aData(ba:ByteArray):ByteArray { // 4-bytes size ba.position += 4; if (ba.readUTFBytes(4) != 'esds') { throw _context.console.logAndBuildError("Couldn't find a 'esds' box"); } // // 4-bytes version/flags // ba.position += 4; // // 1-byte type (0x03) // ba.position += 1; ba.position += 5; // 3-bytes header (optional) and 1-byte size getDescriptorSize(ba); // // 2-bytes ID // ba.position += 2; // // 1-byte priority // ba.position += 1; // // 1-byte type (0x04) // ba.position += 1; ba.position += 4; // 3-bytes header (optional) and 1-byte size getDescriptorSize(ba); // // 1-byte ID // ba.position += 1; // // 1-byte type/flags // ba.position += 1; // // 3-bytes buffer size // ba.position += 3; // // 4-bytes maximum bit rate // ba.position += 4; // // 4-bytes average bit rate // ba.position += 4; // // 1-byte type (0x05) // ba.position += 1; ba.position += 14; var sdf:ByteArray = new ByteArray(); ba.readBytes(sdf, 0, getDescriptorSize(ba)); return sdf; } private function getDescriptorSize(ba:ByteArray):uint { var headerOrSize:uint = ba.readUnsignedByte(); if (headerOrSize == 0x80) { // 2-bytes header ba.position += 2; // size return ba.readUnsignedByte(); } // size return headerOrSize; } } }
/* * Copyright (c) 2014 castLabs GmbH * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.castlabs.dash.boxes { import com.castlabs.dash.DashContext; import flash.utils.ByteArray; public class SampleEntry extends Box { public static var channelCount:uint; public static var sampleSize:uint; private var _data:ByteArray; protected var _type:String; public function SampleEntry(context:DashContext, offset:uint, size:uint, type:String) { super(context, offset, size); _type = type; } public function get data():ByteArray { return _data; } public override function parse(ba:ByteArray):void { if (_type == "avc1") { parseAvc1(ba); } if (_type == "mp4a") { parseMp4a(ba); } ba.position = end; } protected function parseAvc1(ba:ByteArray):void { // skip ba.position += 78; parseAvc1Data(ba); } protected function parseMp4a(ba:ByteArray):void { ba.position += 6; var soundVersion:uint; soundVersion = ba.readUnsignedShort(); ba.position += 8; channelCount = ba.readUnsignedShort(); sampleSize = ba.readUnsignedShort(); // skip ba.position += 8; if (soundVersion==1) { ba.position += 16; } if (soundVersion==2) { ba.position += 36; } _data = parseMp4aData(ba); } private function parseAvc1Data(ba:ByteArray):void { ba.position = goToBox("avcC", ba); var size:Number = ba.readUnsignedInt(); // skip: type("avcC") ba.position += 4; _data = new ByteArray(); ba.readBytes(_data, 0, size - SIZE_AND_TYPE); } protected function goToBox(type:String, ba:ByteArray):uint { var typeBegin:String = type.slice(0, 1); var typeOther:String = type.slice(1); while (ba.bytesAvailable) { if (ba.readUTFBytes(typeBegin.length) != typeBegin) { continue; } if (ba.readUTFBytes(typeOther.length) == typeOther) { return ba.position - SIZE_AND_TYPE; } } throw _context.console.logAndBuildError("Couldn't find any '" + type + "' box"); } private function parseMp4aData(ba:ByteArray):ByteArray { // 4-bytes size ba.position += 4; if (ba.readUTFBytes(4) != 'esds') { throw _context.console.logAndBuildError("Couldn't find a 'esds' box"); } // // 4-bytes version/flags // ba.position += 4; // // 1-byte type (0x03) // ba.position += 1; ba.position += 5; // 3-bytes header (optional) and 1-byte size getDescriptorSize(ba); // // 2-bytes ID // ba.position += 2; // // 1-byte priority // ba.position += 1; // // 1-byte type (0x04) // ba.position += 1; ba.position += 4; // 3-bytes header (optional) and 1-byte size getDescriptorSize(ba); // // 1-byte ID // ba.position += 1; // // 1-byte type/flags // ba.position += 1; // // 3-bytes buffer size // ba.position += 3; // // 4-bytes maximum bit rate // ba.position += 4; // // 4-bytes average bit rate // ba.position += 4; // // 1-byte type (0x05) // ba.position += 1; ba.position += 14; var sdf:ByteArray = new ByteArray(); ba.readBytes(sdf, 0, getDescriptorSize(ba)); return sdf; } private function getDescriptorSize(ba:ByteArray):uint { var headerOrSize:uint = ba.readUnsignedByte(); if (headerOrSize == 0x80) { // 2-bytes header ba.position += 2; // size return ba.readUnsignedByte(); } // size return headerOrSize; } } }
support for apples AudioSampleEntry box with soundversion 1 & 2
support for apples AudioSampleEntry box with soundversion 1 & 2
ActionScript
mpl-2.0
XamanSoft/dashas,Cinemacloud/dashas,castlabs/dashas,XamanSoft/dashas,XamanSoft/dashas,Cinemacloud/dashas,Cinemacloud/dashas,castlabs/dashas,castlabs/dashas
17da25b19b681a992fe74030f2d133914a172757
frameworks/as/projects/FlexJSUI/src/org/apache/flex/events/MouseEvent.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/events/MouseEvent.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.events { import flash.events.MouseEvent; import org.apache.flex.core.IUIBase; import org.apache.flex.geom.Point; import org.apache.flex.utils.PointUtils; /** * Mouse events * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class MouseEvent extends Event { public static const MOUSE_DOWN:String = "mouseDown"; public static const MOUSE_MOVE:String = "mouseMove"; public static const MOUSE_UP:String = "mouseUp"; public static const MOUSE_OUT:String = "mouseOut"; public static const MOUSE_OVER:String = "mouseOver"; public static const ROLL_OVER:String = "rollOver"; public static const ROLL_OUT:String = "rollOut"; public static const CLICK:String = "click"; /** * Constructor. * * @param type The name of the event. * @param bubbles Whether the event bubbles. * @param cancelable Whether the event can be canceled. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function MouseEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, localX:Number = NaN, localY:Number = NaN, relatedObject:Object = null, ctrlKey:Boolean = false, altKey:Boolean = false, shiftKey:Boolean = false, buttonDown:Boolean = false, delta:int = 0, commandKey:Boolean = false, controlKey:Boolean = false, clickCount:int = 0) { super(type, bubbles, cancelable); this.localX = localX; this.localY = localY; this.relatedObject = relatedObject; this.ctrlKey = ctrlKey; this.altKey = altKey; this.shiftKey = shiftKey; this.buttonDown = buttonDown; this.delta = delta; this.commandKey = commandKey; this.controlKey = controlKey; this.clickCount = clickCount; } private var _localX:Number; public function get localX():Number { return _localX; } public function set localX(value:Number):void { _localX = value; _stagePoint = null; } private var _localY:Number; public function get localY():Number { return _localY; } public function set localY(value:Number):void { _localY = value; _stagePoint = null; } public var relatedObject:Object; public var ctrlKey:Boolean; public var altKey:Boolean; public var shiftKey:Boolean; public var buttonDown:Boolean; public var delta:int; public var commandKey:Boolean; public var controlKey:Boolean; public var clickCount:int; private var _stagePoint:Point; public function get stageX():Number { if (!target) return localX; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.x; } public function get stageY():Number { if (!target) return localY; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.y; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.events { import flash.events.MouseEvent; import org.apache.flex.core.IUIBase; import org.apache.flex.geom.Point; import org.apache.flex.utils.PointUtils; /** * Mouse events * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class MouseEvent extends Event { public static const MOUSE_DOWN:String = "mouseDown"; public static const MOUSE_MOVE:String = "mouseMove"; public static const MOUSE_UP:String = "mouseUp"; public static const MOUSE_OUT:String = "mouseOut"; public static const MOUSE_OVER:String = "mouseOver"; public static const ROLL_OVER:String = "rollOver"; public static const ROLL_OUT:String = "rollOut"; public static const CLICK:String = "click"; /** * Constructor. * * @param type The name of the event. * @param bubbles Whether the event bubbles. * @param cancelable Whether the event can be canceled. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function MouseEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, localX:Number = NaN, localY:Number = NaN, relatedObject:Object = null, ctrlKey:Boolean = false, altKey:Boolean = false, shiftKey:Boolean = false, buttonDown:Boolean = false, delta:int = 0, commandKey:Boolean = false, controlKey:Boolean = false, clickCount:int = 0) { super(type, bubbles, cancelable); this.localX = localX; this.localY = localY; this.relatedObject = relatedObject; this.ctrlKey = ctrlKey; this.altKey = altKey; this.shiftKey = shiftKey; this.buttonDown = buttonDown; this.delta = delta; this.commandKey = commandKey; this.controlKey = controlKey; this.clickCount = clickCount; } private var _localX:Number; public function get localX():Number { return _localX; } public function set localX(value:Number):void { _localX = value; clientX = value; _stagePoint = null; } private var _localY:Number; public function get localY():Number { return _localY; } public function set localY(value:Number):void { _localY = value; clientY = value; _stagePoint = null; } public var relatedObject:Object; public var ctrlKey:Boolean; public var altKey:Boolean; public var shiftKey:Boolean; public var buttonDown:Boolean; public var delta:int; public var commandKey:Boolean; public var controlKey:Boolean; public var clickCount:int; // these map directly to JS MouseEvent fields. public var clientX:Number; public var clientY:Number; private var _stagePoint:Point; public function get screenX():Number { if (!target) return localX; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.x; } public function get screenY():Number { if (!target) return localY; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.y; } } }
use screenXY and clientXY
use screenXY and clientXY
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
18028f5f13a9b5cc51417861ecf7847863d2c0d3
WEB-INF/lps/lfc/kernel/swf9/LzTextSprite.as
WEB-INF/lps/lfc/kernel/swf9/LzTextSprite.as
/** * LzTextSprite.as * * @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LzTextSprite extends LzSprite { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.text.*; import flash.net.URLRequest; }# #passthrough { public var textfield:TextField = null; public static var PAD_TEXTWIDTH:Number = 4; public static var DEFAULT_SIZE = 11; var font = null; public var lineheight = 11; public var textcolor = 0; public var text:String = ""; public var resize:Boolean = true; public var multiline:Boolean = false; public var underline:Boolean = false; public var closeformat:String; public var sizeToHeight:Boolean = false; public var password:Boolean = false; public var scrollheight:Number = 0; public function LzTextSprite (newowner = null, args = null) { super(newowner,false); // owner:*, isroot:Boolean this.textfield = createTextField(0,0,400,20); } override public function setClickable( c:Boolean ):void { if (this.clickable == c) return; this.textfield.mouseEnabled = c; this.clickable = c; if (c) { attachMouseEvents(this.textfield); } else { removeMouseEvents(this.textfield); } } override public function setWidth( w:* ):void { super.setWidth(w); if (w) { this.textfield.width = w; } } override public function setHeight( h:* ):void { super.setHeight(h); if (h) { this.textfield.height = h; } } private function createTextField(nx:Number, ny:Number, w:Number, h:Number):TextField { var tfield:TextField = new TextField(); tfield.x = nx; tfield.y = ny; tfield.width = w; tfield.height = h; tfield.border = false; tfield.mouseEnabled = false; //tfield.cacheAsBitmap = true; addChild(tfield); return tfield; } public function __initTextProperties (args:Object) { this.password = args.password ? true : false; var textclip:TextField = this.textfield; textclip.displayAsPassword = this.password; textclip.selectable = args.selectable; textclip.autoSize = TextFieldAutoSize.NONE; // TODO [hqm 2008-01] have to figure out how the Flex textfield multiline // maps to Laszlo model. this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; textclip.background = false; // multiline text fields are left justified if (args.multiline) { textclip.autoSize = TextFieldAutoSize.LEFT; } // To compute our width: // + if text is multiline: // if no width is supplied, use parent width // + if text is single line: // if no width was supplied and there's no constraint, measure the text width: // if empty text content was supplied, use DEFAULT_WIDTH //(args.width == null && typeof(args.$refs.width) != "function") // To compute our height: // + If height is supplied, use it. // + if no height supplied: // if single line, use font line height // else get height from flash textobject.textHeight // if (args['height'] == null) { this.sizeToHeight = true; } else if (! args.height is LzValueExpr) { // Does setting height of the text object do the right thing in swf9? textclip.height = args.height; } // Default the scrollheight to the visible height. this.scrollheight = this.height; // TODO [hqm 2008-01] There ought to be only call to // __setFormat during instantiation of an lzText. Figure // out how to suppress the other calls from setters. this.__setFormat(); this.setText(args.text); if (this.sizeToHeight) { //text and format is set, measure it var lm:TextLineMetrics = textclip.getLineMetrics(0); var h = lm.ascent + lm.descent + lm.leading; //TODO [anba 20080602] is this ok for multiline? if (this.multiline) h *= textclip.numLines; h += 4;//2*2px gutter, see flash docs for flash.text.TextLineMetrics this.setHeight(h); } } override public function setBGColor( c:* ):void { if (c == null) { this.textfield.background = false; } else { this.textfield.background = true; this.textfield.backgroundColor = c; } } public function setBorder ( onroff:Boolean):void { this.textfield.border = (onroff == true); } public function setEmbedFonts ( onroff:Boolean ):void { this.textfield.embedFonts = (onroff == true); } /* * setFontSize( Number:size ) o Sets the size of the font in pixels */ public function setFontSize ( fsize:String ):void { this.fontsize = fsize; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } public function setFontStyle ( fstyle:String ):void { this.fontstyle = fstyle; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } /* setFontName( String:name ) o Sets the name of the font o Can be a comma-separated list of font names */ override public function setFontName ( fname:String , prop=null):void{ this.fontname = fname; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } function setFontInfo () { this.font = LzFontManager.getFont( this.fontname , this.fontstyle ); //trace('setFontInfo this.font = ', this.font, 'this.fontname = ', this.fontname, this.fontstyle); if (this.font != null) { //trace('font.leading', this.font.leading, 'font.height = ',this.font.height, 'fontsize =',this.fontsize); this.lineheight = Number(this.font.leading) + ( Number(this.font.height) * Number(this.fontsize) / DEFAULT_SIZE ); } } /** * Sets the color of all the text in the field to the given hex color. * @param Number c: The color for the text -- from 0x0 (black) to 0xFFFFFF (white) */ public override function setColor ( col:* ):void { if (col != null) { this.textcolor = col; this.__setFormat(); this.setText( this.text ); } } public function appendText( t:String ):void { this.textfield.appendText(t); this.text = this.textfield.text; } public function getText():String { return this.text; } /** setText( String:text ) o Sets the contents to the specified text o Uses the widthchange callback method if multiline is false and text is not resizable o Uses the heightchange callback method if multiline is true */ /** * setText sets the text of the field to display * @param String t: the string to which to set the text */ public function setText ( t:String ):void { //this.textfield.cacheAsBitmap = false; if (t == null || typeof(t) == 'undefined' || t == 'null') { t = ""; } else if (typeof(t) != "string") { t = t.toString(); } this.text = t; this.textfield.htmlText = t; if (this.resize && (this.multiline == false)) { // single line resizable fields adjust their width to match the text var w:Number = this.getTextWidth(); //trace('lztextsprite resize setwidth ', w, this.lzheight ); if (w != this.lzwidth) { this.setWidth(w); } } //multiline resizable fields adjust their height if (this.sizeToHeight) { if (this.multiline) { //FIXME [20080602 anba] won't possibly work, example: //textfield.textHeight=100 //textfield.height=10 //=> setHeight(Math.max(100, 10)) == setHeight(100) //setHeight sets textfield.height to 100 //next round: //textfield.textHeight=10 (new text was entered) //textfield.height=100 (set above!) //=> setHeight(Math.max(10, 100)) == setHeight(100) // => textfield.height still 100, sprite-height didn't change, but it should! this.setHeight(Math.max(this.textfield.textHeight, this.textfield.height)); } } //this.textfield.cacheAsBitmap = true; } /** * Sets the format string for the text field. * @access private */ public function __setFormat ():void { this.setFontInfo(); var cfontname = LzFontManager.__fontnameCacheMap[this.fontname]; if (cfontname == null) { cfontname = LzFontManager.__findMatchingFont(this.fontname); LzFontManager.__fontnameCacheMap[this.fontname] = cfontname; //Debug.write("caching fontname", this.fontname, cfontname); } // trace("__setFormat this.font=", this.font, 'this.fontname = ',this.fontname, //'cfontname=', cfontname); var tf:TextFormat = new TextFormat(); tf.size = this.fontsize; tf.font = (this.font == null ? cfontname : this.font.name); tf.color = this.textcolor; // If there is no font found, assume a device font if (this.font == null) { this.textfield.embedFonts = false; } else { this.textfield.embedFonts = true; } if (this.fontstyle == "bold" || this.fontstyle =="bolditalic"){ tf.bold = true; } if (this.fontstyle == "italic" || this.fontstyle =="bolditalic"){ tf.italic = true; } if (this.underline){ tf.underline = true; } this.textfield.defaultTextFormat = tf; } public function setMultiline ( ml:Boolean ):void { this.multiline = (ml == true); if (this.multiline) { this.textfield.multiline = true; this.textfield.wordWrap = true; } else { this.textfield.multiline = false; this.textfield.wordWrap = false; } } /** * Sets the selectability (with Ibeam cursor) of the text field * @param Boolean isSel: true if the text may be selected by the user */ public function setSelectable ( isSel:Boolean ):void { this.textfield.selectable = isSel; } public function getTextWidth ( ):Number { var tf:TextField = this.textfield; var ml:Boolean = tf.multiline; var mw:Boolean = tf.wordWrap; tf.multiline = false; tf.wordWrap = false; var twidth:Number = (tf.textWidth == 0) ? 0 : tf.textWidth + LzTextSprite.PAD_TEXTWIDTH; tf.multiline = ml; tf.wordWrap = mw; return twidth; } public function getTextHeight ( ):Number { return this.textfield.textHeight; } public function getTextfieldHeight ( ) { return this.textfield.height; } function setHScroll (s){} function setAntiAliasType( aliasType ){} function getAntiAliasType() {} function setGridFit( gridFit ){} function getGridFit() {} function setSharpness( sharpness ){} function getSharpness() { } function setThickness( thickness ){} function getThickness() {} function setMaxLength ( val ){} function setPattern ( val ){} function setSelection ( start , end ){ } function setResize ( val ){ this.resize = val; } function setScroll ( h ){ trace("LzTextSprite.setScroll not yet implemented"); } function getScroll ( ){ trace("LzTextSprite.getScroll not yet implemented"); } function getMaxScroll ( ){ trace("LzTextSprite.getMaxScroll not yet implemented"); } function getBottomScroll ( ){ trace("LzTextSprite.getBottomScroll not yet implemented"); } function setXScroll ( n ){ trace("LzTextSprite.setXScroll not yet implemented"); } function setYScroll ( n ){ trace("LzTextSprite.setYScroll not yet implemented"); } function setWordWrap ( wrap ){ trace("LzTextSprite.setWordWrap not yet implemented"); } function getSelectionPosition ( ){ trace("LzTextSprite.getSelectionPosition not yet implemented"); } function getSelectionSize ( ){ trace("LzTextSprite.getSelectionSize not yet implemented"); } }# }
/** * LzTextSprite.as * * @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LzTextSprite extends LzSprite { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.text.*; import flash.net.URLRequest; }# #passthrough { public var textfield:TextField = null; public static var PAD_TEXTWIDTH:Number = 4; public static var DEFAULT_SIZE = 11; var font = null; public var lineheight = 11; public var textcolor = 0; public var text:String = ""; public var resize:Boolean = true; public var multiline:Boolean = false; public var underline:Boolean = false; public var closeformat:String; public var sizeToHeight:Boolean = false; public var password:Boolean = false; public var scrollheight:Number = 0; public function LzTextSprite (newowner = null, args = null) { super(newowner,false); // owner:*, isroot:Boolean this.textfield = createTextField(0,0,400,20); } override public function setClickable( c:Boolean ):void { if (this.clickable == c) return; this.textfield.mouseEnabled = c || this.textfield.selectable; this.clickable = c; if (c) { attachMouseEvents(this.textfield); } else { removeMouseEvents(this.textfield); } } override public function setWidth( w:* ):void { super.setWidth(w); if (w) { this.textfield.width = w; } } override public function setHeight( h:* ):void { super.setHeight(h); if (h) { this.textfield.height = h; } } private function createTextField(nx:Number, ny:Number, w:Number, h:Number):TextField { var tfield:TextField = new TextField(); tfield.x = nx; tfield.y = ny; tfield.width = w; tfield.height = h; tfield.border = false; tfield.mouseEnabled = false; //tfield.cacheAsBitmap = true; addChild(tfield); return tfield; } public function __initTextProperties (args:Object) { this.password = args.password ? true : false; var textclip:TextField = this.textfield; textclip.displayAsPassword = this.password; textclip.selectable = args.selectable; textclip.autoSize = TextFieldAutoSize.NONE; // TODO [hqm 2008-01] have to figure out how the Flex textfield multiline // maps to Laszlo model. this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; textclip.background = false; // multiline text fields are left justified if (args.multiline) { textclip.autoSize = TextFieldAutoSize.LEFT; } // To compute our width: // + if text is multiline: // if no width is supplied, use parent width // + if text is single line: // if no width was supplied and there's no constraint, measure the text width: // if empty text content was supplied, use DEFAULT_WIDTH //(args.width == null && typeof(args.$refs.width) != "function") // To compute our height: // + If height is supplied, use it. // + if no height supplied: // if single line, use font line height // else get height from flash textobject.textHeight // if (args['height'] == null) { this.sizeToHeight = true; } else if (! args.height is LzValueExpr) { // Does setting height of the text object do the right thing in swf9? textclip.height = args.height; } // Default the scrollheight to the visible height. this.scrollheight = this.height; // TODO [hqm 2008-01] There ought to be only call to // __setFormat during instantiation of an lzText. Figure // out how to suppress the other calls from setters. this.__setFormat(); this.setText(args.text); if (this.sizeToHeight) { //text and format is set, measure it var lm:TextLineMetrics = textclip.getLineMetrics(0); var h = lm.ascent + lm.descent + lm.leading; //TODO [anba 20080602] is this ok for multiline? if (this.multiline) h *= textclip.numLines; h += 4;//2*2px gutter, see flash docs for flash.text.TextLineMetrics this.setHeight(h); } } override public function setBGColor( c:* ):void { if (c == null) { this.textfield.background = false; } else { this.textfield.background = true; this.textfield.backgroundColor = c; } } public function setBorder ( onroff:Boolean):void { this.textfield.border = (onroff == true); } public function setEmbedFonts ( onroff:Boolean ):void { this.textfield.embedFonts = (onroff == true); } /* * setFontSize( Number:size ) o Sets the size of the font in pixels */ public function setFontSize ( fsize:String ):void { this.fontsize = fsize; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } public function setFontStyle ( fstyle:String ):void { this.fontstyle = fstyle; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } /* setFontName( String:name ) o Sets the name of the font o Can be a comma-separated list of font names */ override public function setFontName ( fname:String , prop=null):void{ this.fontname = fname; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } function setFontInfo () { this.font = LzFontManager.getFont( this.fontname , this.fontstyle ); //trace('setFontInfo this.font = ', this.font, 'this.fontname = ', this.fontname, this.fontstyle); if (this.font != null) { //trace('font.leading', this.font.leading, 'font.height = ',this.font.height, 'fontsize =',this.fontsize); this.lineheight = Number(this.font.leading) + ( Number(this.font.height) * Number(this.fontsize) / DEFAULT_SIZE ); } } /** * Sets the color of all the text in the field to the given hex color. * @param Number c: The color for the text -- from 0x0 (black) to 0xFFFFFF (white) */ public override function setColor ( col:* ):void { if (col != null) { this.textcolor = col; this.__setFormat(); this.setText( this.text ); } } public function appendText( t:String ):void { this.textfield.appendText(t); this.text = this.textfield.text; } public function getText():String { return this.text; } /** setText( String:text ) o Sets the contents to the specified text o Uses the widthchange callback method if multiline is false and text is not resizable o Uses the heightchange callback method if multiline is true */ /** * setText sets the text of the field to display * @param String t: the string to which to set the text */ public function setText ( t:String ):void { //this.textfield.cacheAsBitmap = false; if (t == null || typeof(t) == 'undefined' || t == 'null') { t = ""; } else if (typeof(t) != "string") { t = t.toString(); } this.text = t; this.textfield.htmlText = t; if (this.resize && (this.multiline == false)) { // single line resizable fields adjust their width to match the text var w:Number = this.getTextWidth(); //trace('lztextsprite resize setwidth ', w, this.lzheight ); if (w != this.lzwidth) { this.setWidth(w); } } //multiline resizable fields adjust their height if (this.sizeToHeight) { if (this.multiline) { //FIXME [20080602 anba] won't possibly work, example: //textfield.textHeight=100 //textfield.height=10 //=> setHeight(Math.max(100, 10)) == setHeight(100) //setHeight sets textfield.height to 100 //next round: //textfield.textHeight=10 (new text was entered) //textfield.height=100 (set above!) //=> setHeight(Math.max(10, 100)) == setHeight(100) // => textfield.height still 100, sprite-height didn't change, but it should! this.setHeight(Math.max(this.textfield.textHeight, this.textfield.height)); } } //this.textfield.cacheAsBitmap = true; } /** * Sets the format string for the text field. * @access private */ public function __setFormat ():void { this.setFontInfo(); var cfontname = LzFontManager.__fontnameCacheMap[this.fontname]; if (cfontname == null) { cfontname = LzFontManager.__findMatchingFont(this.fontname); LzFontManager.__fontnameCacheMap[this.fontname] = cfontname; //Debug.write("caching fontname", this.fontname, cfontname); } // trace("__setFormat this.font=", this.font, 'this.fontname = ',this.fontname, //'cfontname=', cfontname); var tf:TextFormat = new TextFormat(); tf.size = this.fontsize; tf.font = (this.font == null ? cfontname : this.font.name); tf.color = this.textcolor; // If there is no font found, assume a device font if (this.font == null) { this.textfield.embedFonts = false; } else { this.textfield.embedFonts = true; } if (this.fontstyle == "bold" || this.fontstyle =="bolditalic"){ tf.bold = true; } if (this.fontstyle == "italic" || this.fontstyle =="bolditalic"){ tf.italic = true; } if (this.underline){ tf.underline = true; } this.textfield.defaultTextFormat = tf; } public function setMultiline ( ml:Boolean ):void { this.multiline = (ml == true); if (this.multiline) { this.textfield.multiline = true; this.textfield.wordWrap = true; } else { this.textfield.multiline = false; this.textfield.wordWrap = false; } } /** * Sets the selectability (with Ibeam cursor) of the text field * @param Boolean isSel: true if the text may be selected by the user */ public function setSelectable ( isSel:Boolean ):void { this.textfield.selectable = isSel; this.textfield.mouseEnabled = isSel || this.clickable; } public function getTextWidth ( ):Number { var tf:TextField = this.textfield; var ml:Boolean = tf.multiline; var mw:Boolean = tf.wordWrap; tf.multiline = false; tf.wordWrap = false; var twidth:Number = (tf.textWidth == 0) ? 0 : tf.textWidth + LzTextSprite.PAD_TEXTWIDTH; tf.multiline = ml; tf.wordWrap = mw; return twidth; } public function getTextHeight ( ):Number { return this.textfield.textHeight; } public function getTextfieldHeight ( ) { return this.textfield.height; } function setHScroll (s){} function setAntiAliasType( aliasType ){} function getAntiAliasType() {} function setGridFit( gridFit ){} function getGridFit() {} function setSharpness( sharpness ){} function getSharpness() { } function setThickness( thickness ){} function getThickness() {} function setMaxLength ( val ){} function setPattern ( val ){} function setSelection ( start , end ){ } function setResize ( val ){ this.resize = val; } function setScroll ( h ){ trace("LzTextSprite.setScroll not yet implemented"); } function getScroll ( ){ trace("LzTextSprite.getScroll not yet implemented"); } function getMaxScroll ( ){ trace("LzTextSprite.getMaxScroll not yet implemented"); } function getBottomScroll ( ){ trace("LzTextSprite.getBottomScroll not yet implemented"); } function setXScroll ( n ){ trace("LzTextSprite.setXScroll not yet implemented"); } function setYScroll ( n ){ trace("LzTextSprite.setYScroll not yet implemented"); } function setWordWrap ( wrap ){ trace("LzTextSprite.setWordWrap not yet implemented"); } function getSelectionPosition ( ){ trace("LzTextSprite.getSelectionPosition not yet implemented"); } function getSelectionSize ( ){ trace("LzTextSprite.getSelectionSize not yet implemented"); } }# }
Change 20080606-hqm-S by [email protected] on 2008-06-06 11:08:01 EDT in /Users/hqm/openlaszlo/trunk2 for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20080606-hqm-S by [email protected] on 2008-06-06 11:08:01 EDT in /Users/hqm/openlaszlo/trunk2 for http://svn.openlaszlo.org/openlaszlo/trunk Summary: fix text selectability in swf9 New Features: Bugs Fixed: LPP-6114 Technical Reviewer: andre QA Reviewer: pbr Doc Reviewer: (pending) Documentation: Release Notes: Details: mouseEnabled must be true to allow selecting of text setSelectable(..): this.textfield.mouseEnabled = isSel || this.clickable; setClickable(..): this.textfield.mouseEnabled = c || this.textfield.selectable; Tests: text which says "I am selectable..." is selectable in test/swf9/hello.lzx test git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@9494 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
b7646c07bd3b32ada1ca299f1b5887686fdb3190
WEB-INF/lps/lfc/kernel/swf9/LzTimeKernel.as
WEB-INF/lps/lfc/kernel/swf9/LzTimeKernel.as
/** * LzTimeKernel.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ // Receives and sends timing events final class LzTimeKernelClass { #passthrough (toplevel:true) { import flash.utils.getTimer; import flash.utils.setTimeout; import flash.utils.setInterval; import flash.utils.clearTimeout; import flash.utils.clearInterval; }# const getTimer :Function = flash.utils.getTimer; const setTimeout :Function = flash.utils.setTimeout; const setInterval :Function = flash.utils.setInterval; const clearTimeout :Function = flash.utils.clearTimeout; const clearInterval :Function = flash.utils.clearInterval; function LzTimeKernelClass() { } } var LzTimeKernel = new LzTimeKernelClass();
/** * LzTimeKernel.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ // Receives and sends timing events final class LzTimeKernelClass { #passthrough (toplevel:true) { import flash.utils.getTimer; import flash.events.TimerEvent; }# private const MAX_POOL :int = 10; private var timerPool :Array = []; private var timers :Object = {}; /** * Creates a new timer and returns an unique identifier which can be used to remove the timer. */ private function createTimer (delay:Number, repeatCount:int, closure:Function, args:Array) :uint { var timer:LzKernelTimer = this.timerPool.pop() || new LzKernelTimer(); this.timers[timer.timerID] = timer; timer.delay = delay; timer.repeatCount = repeatCount; timer.closure = closure; timer.arguments = args; timer.addEventListener(TimerEvent.TIMER, this.timerHandler); timer.addEventListener(TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler); timer.start(); return timer.timerID; } /** * Stops and removes the timer with the given id. */ private function removeTimer (id:uint) :void { var timer:LzKernelTimer = this.timers[id]; if (timer) { timer.closure = null; timer.arguments = null; timer.removeEventListener(TimerEvent.TIMER, this.timerHandler); timer.removeEventListener(TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler); timer.reset(); delete this.timers[id]; if (this.timerPool.length < this.MAX_POOL) { this.timerPool.push(timer); } } } private function timerHandler (event:TimerEvent) :void { var timer:LzKernelTimer = LzKernelTimer(event.target); if (timer.closure) { timer.closure.apply(null, timer.arguments); } } private function timerCompleteHandler (event:TimerEvent) :void { var timer:LzKernelTimer = LzKernelTimer(event.target); this.removeTimer(timer.timerID); } public const getTimer :Function = flash.utils.getTimer; // const setTimeout :Function = flash.utils.setTimeout; public function setTimeout (closure:Function, delay:Number, ...args) :uint { return this.createTimer(delay, 1, closure, args); } // const setInterval :Function = flash.utils.setInterval; public function setInterval (closure:Function, delay:Number, ...args) :uint { return this.createTimer(delay, 0, closure, args); } // const clearTimeout :Function = flash.utils.clearTimeout; public function clearTimeout (id:uint) :void { this.removeTimer(id); } // const clearInterval :Function = flash.utils.clearInterval; public function clearInterval (id:uint) :void { this.removeTimer(id); } function LzTimeKernelClass() { } } var LzTimeKernel = new LzTimeKernelClass(); /** * This is a helper class for LzTimeKernel. In addition to the flash.utils.Timer * class, each timer has got an unique id and holds a reference to a function * and an arguments array. * @see LzTimeKernelClass#createTimer * @see LzTimeKernelClass#removeTimer */ final class LzKernelTimer extends Timer { #passthrough (toplevel:true) { import flash.utils.Timer; }# #passthrough { private static var idCounter :uint = 0; public function LzKernelTimer () { super(0); this._timerID = LzKernelTimer.idCounter++; } private var _timerID :uint; public function get timerID () :uint { return this._timerID; } private var _closure :Function; public function get closure () :Function { return this._closure; } public function set closure (c:Function) :void { this._closure = c; } private var _arguments :Array; public function get arguments () :Array { return this._arguments; } public function set arguments (a:Array) :void { this._arguments = a; } }# }
Change 20090218-bargull-hTy by bargull@dell--p4--2-53 on 2009-02-18 02:13:27 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090218-bargull-hTy by bargull@dell--p4--2-53 on 2009-02-18 02:13:27 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: use flash.utils.Timer for LzTimeKernel New Features: Bugs Fixed: LPP-7763 Technical Reviewer: ptw QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: Changed LzTimeKernelClass#setTimeout, #setInterval, #clearTimeout, #clearInterval to use flash.utils.Timer instead of the functions defined in flash.utils.* It was necessary to change the implementation because the setTimeout etc. functions apparently create memory leaks within the flash player. I created a subclass of flash.utils.Timer so that we can easily identify each instance (timerID property) and to support functions callbacks instead the event based mechanism (closure and arguments property). To reduce the overall number of LzKernelTimer instances up to MAX_POOL (currently set to 10) are cached. Tests: testcase from bugreport, note that cpu usage stays low git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12917 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
7253949084bf12933dd9fba4acd74f64e4e94fa0
exporter/src/main/as/flump/export/AutomaticExporter.as
exporter/src/main/as/flump/export/AutomaticExporter.as
package flump.export { import aspire.util.F; import flash.events.ErrorEvent; import flash.events.UncaughtErrorEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.setTimeout; import flump.executor.Executor; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import react.BoolValue; import react.BoolView; /** * This class expects to be run from the command-line script found at rsrc/flump-export. It sends * output to File.applicationDirectory.nativePath + "/exporter.log" rather than spawning any * UI windows for user interaction, and acts as though the user pressed the export all button, then * shuts down. */ public class AutomaticExporter extends ExportController { public function AutomaticExporter (project :File) { _complete.connect(function (complete :Boolean) :void { if (!complete) return; if (OUT != null) { OUT.close(); OUT = null; } }); FlumpApp.app.loaderInfo.uncaughtErrorEvents .addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, exit); var outFile :File = new File(File.applicationDirectory.nativePath + "/exporter.log"); OUT = new FileStream(); OUT.open(outFile, FileMode.WRITE); _confFile = project; println("Exporting project: '" + _confFile.nativePath + "'"); println(); if (readProjectConfig()) { var exec :Executor = new Executor(); exec.completed.connect(function () :void { // if finding docs generates a crit error, we need to fail immediately if (_handledCritError) exit(); }); findFlashDocuments(_importDirectory, exec, true); } else exit(); } public function get complete () :BoolView { return _complete; } protected function checkValid () :void { if (getLibs() == null) return; // not done loading yet var valid :Boolean = _statuses.every(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); if (!valid) { // we've already printed our parse errors exit(); return; } println("Loading complete.\n"); if (_conf.exportDir == null) { exit("No export directory specified."); return; } var exportDir :File = _confFile.parent.resolvePath(_conf.exportDir); println("Publishing to " + exportDir.nativePath + "..."); if (exportDir.exists && !exportDir.isDirectory) { exit("Configured export directory exists as a file!"); return; } if (!exportDir.exists) exportDir.createDirectory(); var publisher :Publisher = new Publisher(exportDir, _conf, projectName); // wait a frame for the output to flush before starting the (long frame) publish setTimeout(F.bind(publish, publisher), 0); } protected function publish (publisher :Publisher) :void { var hasCombined :Boolean = false; var hasSingle :Boolean = false; for each (var config :ExportConf in _conf.exports) { hasCombined ||= config.combine; hasSingle ||= !config.combine; if (hasCombined && hasSingle) break; } try { var libs :Vector.<XflLibrary> = getLibs(); // if we have one or more combined export format, publish them if (hasCombined) { // TODO: publisher.modified checks for SWF modifications, but ignores // FLA modifications, which leads to false negatives. if (true || publisher.modified(libs)) { println("Exporting combined formats..."); var numPublished :int = publisher.publishCombined(libs); if (numPublished == 0) { printErr("No suitable formats were found for combined publishing."); } else { println("" + numPublished + " combined formats published."); } } else { println("Skipping 'Export Combined' (files are unmodified)."); } } // now publish any appropriate single formats if (hasSingle) { for each (var status :DocStatus in _statuses) { if (true || publisher.modified(new <XflLibrary>[status.lib], 0)) { println("Exporting '" + status.path + "'..."); numPublished = publisher.publishSingle(status.lib); if (numPublished == 0) { printErr("No suitable formats were found for single publishing."); } else { println("" + numPublished + " formats published."); } } else { println("Skipping unmodified '" + status.path + "'.") } } } } catch (e :Error) { exit(e); return; } println("Publishing complete.\n"); exit(); } override protected function handleParseError (err :ParseError) :void { if (err.severity == ParseError.CRIT) _handledCritError = true; printErr(err); } override protected function addDocStatus (status :DocStatus) :void { _statuses[_statuses.length] = status; println("Loading document: '" + status.path + "'..."); } override protected function getDocStatuses () :Array { return _statuses; } override protected function docLoadSucceeded (doc :DocStatus, lib :XflLibrary) :void { super.docLoadSucceeded(doc, lib); println("Load complete: '" + doc.path + "'."); checkValid(); } override protected function docLoadFailed (file :File, doc :DocStatus, err :*) :void { super.docLoadFailed(file, doc, err); // this is a serious failure - simple parse errors are handled separately exit(err); } protected function printErr (err :*) :void { if (err is ParseError) { var pe :ParseError = ParseError(err); println("[" + pe.severity + "] @ " + pe.location + ": " + pe.message); } else if (err is Error) { println(Error(err).getStackTrace()) } else if (err is ErrorEvent) { println("ErrorEvent: " + ErrorEvent(err).toString()); if (err is UncaughtErrorEvent) { println(UncaughtErrorEvent(err).error.getStackTrace()); } } else { println("" + err); } } protected function print (message :String) :void { OUT.writeUTFBytes(message); } protected function println (message :String = "") :void { print(message + "\n"); } protected function exit (err :* = null) :void { if (err != null) printErr(err); _complete.value = true; } protected const _complete :BoolValue = new BoolValue(false); protected var OUT :FileStream; protected var _handledCritError :Boolean = false; protected var _statuses :Array = []; } }
package flump.export { import aspire.util.F; import flash.events.ErrorEvent; import flash.events.UncaughtErrorEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.setTimeout; import flump.executor.Executor; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import react.BoolValue; import react.BoolView; /** * This class expects to be run from the command-line script found at rsrc/flump-export. It sends * output to File.applicationDirectory.nativePath + "/exporter.log" rather than spawning any * UI windows for user interaction, and acts as though the user pressed the export all button, then * shuts down. */ public class AutomaticExporter extends ExportController { public function AutomaticExporter (project :File) { _complete.connect(function (complete :Boolean) :void { if (!complete) return; if (OUT != null) { OUT.close(); OUT = null; } }); FlumpApp.app.loaderInfo.uncaughtErrorEvents .addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, exit); var outFile :File = new File(File.applicationDirectory.nativePath + "/exporter.log"); OUT = new FileStream(); OUT.open(outFile, FileMode.WRITE); _confFile = project; println("Exporting project: '" + _confFile.nativePath + "'"); println(); if (readProjectConfig()) { var exec :Executor = new Executor(); exec.completed.connect(function () :void { // if finding docs generates a crit error, we need to fail immediately if (_handledCritError) exit(); }); findFlashDocuments(_importDirectory, exec, true); } else exit(); } public function get complete () :BoolView { return _complete; } protected function checkValid () :void { if (getLibs() == null) return; // not done loading yet var valid :Boolean = _statuses.every(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); if (!valid) { // we've already printed our parse errors exit(); return; } println("Loading complete.\n"); if (_conf.exportDir == null) { exit("No export directory specified."); return; } var exportDir :File = _confFile.parent.resolvePath(_conf.exportDir); println("Publishing to " + exportDir.nativePath + "..."); if (exportDir.exists && !exportDir.isDirectory) { exit("Configured export directory exists as a file!"); return; } if (!exportDir.exists) exportDir.createDirectory(); var publisher :Publisher = new Publisher(exportDir, _conf, projectName); // wait a frame for the output to flush before starting the (long frame) publish setTimeout(F.bind(publish, publisher), 0); } protected function publish (publisher :Publisher) :void { var hasCombined :Boolean = false; var hasSingle :Boolean = false; for each (var config :ExportConf in _conf.exports) { hasCombined ||= config.combine; hasSingle ||= !config.combine; if (hasCombined && hasSingle) break; } try { var libs :Vector.<XflLibrary> = getLibs(); // if we have one or more combined export format, publish them if (hasCombined) { if (publisher.modified(libs)) { println("Exporting combined formats..."); var numPublished :int = publisher.publishCombined(libs); if (numPublished == 0) { printErr("No suitable formats were found for combined publishing."); } else { println("" + numPublished + " combined formats published."); } } else { println("Skipping 'Export Combined' (files are unmodified)."); } } // now publish any appropriate single formats if (hasSingle) { for each (var status :DocStatus in _statuses) { if (publisher.modified(new <XflLibrary>[status.lib], 0)) { println("Exporting '" + status.path + "'..."); numPublished = publisher.publishSingle(status.lib); if (numPublished == 0) { printErr("No suitable formats were found for single publishing."); } else { println("" + numPublished + " formats published."); } } else { println("Skipping unmodified '" + status.path + "'.") } } } } catch (e :Error) { exit(e); return; } println("Publishing complete.\n"); exit(); } override protected function handleParseError (err :ParseError) :void { if (err.severity == ParseError.CRIT) _handledCritError = true; printErr(err); } override protected function addDocStatus (status :DocStatus) :void { _statuses[_statuses.length] = status; println("Loading document: '" + status.path + "'..."); } override protected function getDocStatuses () :Array { return _statuses; } override protected function docLoadSucceeded (doc :DocStatus, lib :XflLibrary) :void { super.docLoadSucceeded(doc, lib); println("Load complete: '" + doc.path + "'."); checkValid(); } override protected function docLoadFailed (file :File, doc :DocStatus, err :*) :void { super.docLoadFailed(file, doc, err); // this is a serious failure - simple parse errors are handled separately exit(err); } protected function printErr (err :*) :void { if (err is ParseError) { var pe :ParseError = ParseError(err); println("[" + pe.severity + "] @ " + pe.location + ": " + pe.message); } else if (err is Error) { println(Error(err).getStackTrace()) } else if (err is ErrorEvent) { println("ErrorEvent: " + ErrorEvent(err).toString()); if (err is UncaughtErrorEvent) { println(UncaughtErrorEvent(err).error.getStackTrace()); } } else { println("" + err); } } protected function print (message :String) :void { OUT.writeUTFBytes(message); } protected function println (message :String = "") :void { print(message + "\n"); } protected function exit (err :* = null) :void { if (err != null) printErr(err); _complete.value = true; } protected const _complete :BoolValue = new BoolValue(false); protected var OUT :FileStream; protected var _handledCritError :Boolean = false; protected var _statuses :Array = []; } }
Revert "AutomaticExporter: don't check Publisher.modified"
Revert "AutomaticExporter: don't check Publisher.modified" This reverts commit 66bd67a5f293259ef411770b0f321cfca4b0fcc1. Always exporting sucks as well. We need a better solution.
ActionScript
mit
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump
81a2aab88b930f1a7232841bb433a0387e7c7c87
frameworks/as/src/org/apache/flex/core/SimpleCSSValuesImpl.as
frameworks/as/src/org/apache/flex/core/SimpleCSSValuesImpl.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import flash.utils.getQualifiedSuperclassName; import flash.utils.getDefinitionByName; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.events.EventDispatcher; public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl { public function SimpleCSSValuesImpl() { super(); } private var mainClass:Object; private var conditionCombiners:Object; public function init(mainClass:Object):void { var styleClassName:String; var c:Class; if (!values) { values = {}; this.mainClass = mainClass; var mainClassName:String = getQualifiedClassName(mainClass); styleClassName = "_" + mainClassName + "_Styles"; c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class; } else { var className:String = getQualifiedClassName(mainClass); c = ApplicationDomain.currentDomain.getDefinition(className) as Class; } generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]); } public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void { var declarationName:String = ""; var segmentName:String = ""; var n:int = arr.length; for (var i:int = 0; i < n; i++) { var className:int = arr[i]; if (className == CSSClass.CSSSelector) { var selectorName:String = arr[++i]; segmentName = selectorName + segmentName; if (declarationName != "") declarationName += " "; declarationName += segmentName; segmentName = ""; } else if (className == CSSClass.CSSCondition) { if (!conditionCombiners) { conditionCombiners = {}; conditionCombiners["class"] = "."; conditionCombiners["id"] = "#"; conditionCombiners["pseudo"] = ':'; } var conditionType:String = arr[++i]; var conditionName:String = arr[++i]; segmentName = segmentName + conditionCombiners[conditionType] + conditionName; } else if (className == CSSClass.CSSStyleDeclaration) { var factoryName:int = arr[++i]; // defaultFactory or factory var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory; /* if (defaultFactory) { mergedStyle = styleManager.getMergedStyleDeclaration(declarationName); style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); } else { style = styleManager.getStyleDeclaration(declarationName); if (!style) { style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); if (factoryName == CSSFactory.Override) newSelectors.push(style); } } */ var finalName:String; var valuesFunction:Function; var valuesObject:Object; if (defaultFactory) { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); finalName = fixNames(declarationName); values[finalName] = valuesObject; } else { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); var o:Object = values[declarationName]; finalName = fixNames(declarationName); if (o == null) values[finalName] = valuesObject; else { valuesFunction.prototype = o; values[finalName] = new valuesFunction(); } } declarationName = ""; } } } private function fixNames(s:String):String { if (s == "") return "*"; var arr:Array = s.split(" "); var n:int = arr.length; for (var i:int = 0; i < n; i++) { var segmentName:String = arr[i]; if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".") continue; var c:int = segmentName.lastIndexOf("."); if (c > -1) // it is 0 for class selectors { segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1); arr[i] = segmentName; } } return arr.join(" "); } public var values:Object; public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):Object { var value:*; var o:Object; var className:String; var selectorName:String; if ("className" in thisObject) { className = thisObject.className; if (state) { selectorName = className + ":" + state; o = values["." + selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values["." + className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } className = getQualifiedClassName(thisObject); while (className != "Object") { if (state) { selectorName = className + ":" + state; o = values[selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values[className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } className = getQualifiedSuperclassName(thisObject); thisObject = getDefinitionByName(className); } o = values["global"]; value = o[valueName]; if (value !== undefined) return value; o = values["*"]; return o[valueName]; } public function setValue(thisObject:Object, valueName:String, value:Object):void { var oldValue:Object = values[valueName]; if (oldValue != value) { values[valueName] = value; dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value)); } } public function getInstance(valueName:String):Object { var o:Object = values["global"]; if (o is Class) { o[valueName] = new o[valueName](); if (o[valueName] is IDocument) o[valueName].setDocument(mainClass); } return o[valueName]; } } } class CSSClass { public static const CSSSelector:int = 0; public static const CSSCondition:int = 1; public static const CSSStyleDeclaration:int = 2; } class CSSFactory { public static const DefaultFactory:int = 0; public static const Factory:int = 1; public static const Override:int = 2; } class CSSDataType { public static const Native:int = 0; public static const Definition:int = 1; }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import flash.utils.getQualifiedSuperclassName; import flash.utils.getDefinitionByName; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.events.EventDispatcher; public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl { public function SimpleCSSValuesImpl() { super(); } private var mainClass:Object; private var conditionCombiners:Object; public function init(mainClass:Object):void { var styleClassName:String; var c:Class; if (!values) { values = {}; this.mainClass = mainClass; var mainClassName:String = getQualifiedClassName(mainClass); styleClassName = "_" + mainClassName + "_Styles"; c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class; } else { var className:String = getQualifiedClassName(mainClass); c = ApplicationDomain.currentDomain.getDefinition(className) as Class; } generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]); } public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void { if (factoryFunctions == null) return; if (arr == null) return; var declarationName:String = ""; var segmentName:String = ""; var n:int = arr.length; for (var i:int = 0; i < n; i++) { var className:int = arr[i]; if (className == CSSClass.CSSSelector) { var selectorName:String = arr[++i]; segmentName = selectorName + segmentName; if (declarationName != "") declarationName += " "; declarationName += segmentName; segmentName = ""; } else if (className == CSSClass.CSSCondition) { if (!conditionCombiners) { conditionCombiners = {}; conditionCombiners["class"] = "."; conditionCombiners["id"] = "#"; conditionCombiners["pseudo"] = ':'; } var conditionType:String = arr[++i]; var conditionName:String = arr[++i]; segmentName = segmentName + conditionCombiners[conditionType] + conditionName; } else if (className == CSSClass.CSSStyleDeclaration) { var factoryName:int = arr[++i]; // defaultFactory or factory var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory; /* if (defaultFactory) { mergedStyle = styleManager.getMergedStyleDeclaration(declarationName); style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); } else { style = styleManager.getStyleDeclaration(declarationName); if (!style) { style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); if (factoryName == CSSFactory.Override) newSelectors.push(style); } } */ var finalName:String; var valuesFunction:Function; var valuesObject:Object; if (defaultFactory) { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); finalName = fixNames(declarationName); values[finalName] = valuesObject; } else { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); var o:Object = values[declarationName]; finalName = fixNames(declarationName); if (o == null) values[finalName] = valuesObject; else { valuesFunction.prototype = o; values[finalName] = new valuesFunction(); } } declarationName = ""; } } } private function fixNames(s:String):String { if (s == "") return "*"; var arr:Array = s.split(" "); var n:int = arr.length; for (var i:int = 0; i < n; i++) { var segmentName:String = arr[i]; if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".") continue; var c:int = segmentName.lastIndexOf("."); if (c > -1) // it is 0 for class selectors { segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1); arr[i] = segmentName; } } return arr.join(" "); } public var values:Object; public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):Object { var value:*; var o:Object; var className:String; var selectorName:String; if ("className" in thisObject) { className = thisObject.className; if (state) { selectorName = className + ":" + state; o = values["." + selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values["." + className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } className = getQualifiedClassName(thisObject); while (className != "Object") { if (state) { selectorName = className + ":" + state; o = values[selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values[className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } className = getQualifiedSuperclassName(thisObject); thisObject = getDefinitionByName(className); } o = values["global"]; value = o[valueName]; if (value !== undefined) return value; o = values["*"]; return o[valueName]; } public function setValue(thisObject:Object, valueName:String, value:Object):void { var oldValue:Object = values[valueName]; if (oldValue != value) { values[valueName] = value; dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value)); } } public function getInstance(valueName:String):Object { var o:Object = values["global"]; if (o is Class) { o[valueName] = new o[valueName](); if (o[valueName] is IDocument) o[valueName].setDocument(mainClass); } return o[valueName]; } } } class CSSClass { public static const CSSSelector:int = 0; public static const CSSCondition:int = 1; public static const CSSStyleDeclaration:int = 2; } class CSSFactory { public static const DefaultFactory:int = 0; public static const Factory:int = 1; public static const Override:int = 2; } class CSSDataType { public static const Native:int = 0; public static const Definition:int = 1; }
Handle MXML views not having any styles
Handle MXML views not having any styles
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
d7e1a332f3b9ece48805d4a50d0bc897358273b8
mustella/as3/src/mustella/TestCase.as
mustella/as3/src/mustella/TestCase.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import flash.display.DisplayObject; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.utils.getQualifiedClassName; import flash.utils.getTimer; import flash.utils.Timer; /** * A Test. A Test script comprises several of these * TestCases. Each TestCase consists of a * setup, body and cleanup section which are sets * of TestStep-derived classes like SetProperty, * RunCode, AssertPropertyValue, etc. * * MXML Properties (not attributes) * setup * body * cleanup */ public class TestCase extends EventDispatcher { /** * The history of bugs that this test case has encountered */ public var bugs:Array; /** * The sequence of TestSteps that comprise the test setup */ public var setup:Array; /** * The sequence of TestSteps that comprise the test */ public var body:Array; /** * The sequence of TestSteps that restore the test environment */ public var cleanup:Array; /** * An identifier for the test */ public var testID:String; /** * A description of the test */ public var description:String; /** * keywords, summarizing the tests */ public var keywords:String; /** * frequency, an estimate of the tests's intersection with real-world * usage. 1 = most frequent usage; 2 somewhat common; 3 = unusual */ public var frequency:String; /** * The current set of steps (setup, body, cleanup) we are executing */ private var currentSteps:Array; /** * Which step we're currently executing (or waiting on an event for) */ private var currentIndex:int = 0; /** * Number of steps in currentSteps */ private var numSteps:int = 0; /** * The root of the SWF (SystemManager) */ private var root:DisplayObject; /** * The shared timer we listen to */ private var timer:Timer; /** * The unit tester */ private var context:UnitTester; /** * Whether we need to emit a runComplete event or not */ private var needCompleteEvent:Boolean = false; /** * If non-zero, the time when we'll give up on waiting */ private var expirationTime:int; /** * the last expected Error thrown by SetProperty */ public var lastError:Error; /** * Called by test steps looking for a timeout indicator */ public function setExpirationTime(time:int):void { expirationTime = time + UnitTester.timeout_plus; } /** * Storage for the cleanupAsserts */ private var _cleanupAsserts:Array; /** * Steps we have to review at the end of the body to see if * they failed or not. These steps monitor activity like * checking for duplicate events or making sure unwanted events * don't fire. */ public function get cleanupAsserts():Array { return _cleanupAsserts; } /** * Storage for this tests's result */ private var _testResult:TestResult; /** * This tests's result */ public function get testResult():TestResult { _testResult.testID = testID; return _testResult; } /** * Constructor. Create the TestResult associated with this TestCase */ public function TestCase() { _testResult = new TestResult(); _testResult.testID = testID; _cleanupAsserts = []; } /** * Called by the UnitTester when it is time to execute * this test case. * * @param root The SystemManager * @param timer The shared Timer; * @param the UnitTester that contains these tests */ public function runTest(root:DisplayObject, timer:Timer, context:UnitTester):Boolean { _testResult.beginTime = new Date().time; _testResult.context = context; this.timer = timer; this.timer.addEventListener("timer", timerHandler); this.root = root; this.context = context; if (UnitTester.hasRTE) { return true; } // do a sanity test here if (UnitTester.verboseMode) { var needWaitEvent:Boolean = false; var i:int; if (setup) { for (i = 0; i < setup.length; i++) { if (setup[i] is ResetComponent) needWaitEvent = true; if (needWaitEvent) { if (setup[i].waitEvent) { needWaitEvent = false; break; } } } if (needWaitEvent) TestOutput.logResult("WARNING: Test " + getQualifiedClassName(context) + "." + testID + " ResetComponent used without any setup steps using a waitEvent\n"); } var allAsserts:Boolean = true; needWaitEvent = false; for (i = 0; i < body.length; i++) { if (body[i] is SetProperty || body[i] is SetStyle) needWaitEvent = true; if (!(body[i] is Assert)) allAsserts = false; if (allAsserts && body[i] is AssertEvent) { TestOutput.logResult("WARNING: Test " + getQualifiedClassName(context) + "." + testID + " no non-Assert steps in body before AssertEvent\n"); } if (needWaitEvent) { if (body[i].waitEvent) { needWaitEvent = false; break; } } } if (needWaitEvent) TestOutput.logResult("WARNING: Test " + getQualifiedClassName(context) + "." + testID + " tests setting values without a waitEvent\n"); } return runSetup(); } /** * Execute the setup portion of the test * * @param continuing If true, don't reset the counter to zero * and just continue on with the test at the currentIndex */ private function runSetup(continuing:Boolean = false):Boolean { if (!testResult.hasStatus()) { if (setup) { testResult.phase = TestResult.SETUP; currentSteps = setup; if (!continuing) currentIndex = 0; numSteps = setup.length; // return if we need to wait for something if (!runSteps()) return false; } } return runBody(); } /** * Execute the body portion of the test * * @param continuing If true, don't reset the counter to zero * and just continue on with the test at the currentIndex */ private function runBody(continuing:Boolean = false):Boolean { if (!testResult.hasStatus()) { if (body) { testResult.phase = TestResult.BODY; currentSteps = body; if (!continuing) currentIndex = 0; numSteps = body.length; // return if we need to wait for something if (!runSteps()) return false; } } return runCleanup(); } /** * Execute the cleanup portion of the test * * @param continuing If true, don't reset the counter to zero * and just continue on with the test at the currentIndex */ private function runCleanup(continuing:Boolean = false):Boolean { if (!testResult.hasStatus()) { if (cleanup) { testResult.phase = TestResult.CLEANUP; currentSteps = cleanup; if (!continuing) currentIndex = 0; numSteps = cleanup.length; // return if we need to wait for something if (!runSteps()) return false; } } return runComplete(); } /** * Clean up when all three phases are done. Sends an event * to the UnitTester harness to tell it that it can run * the next test case. */ private function runComplete():Boolean { var n:int = cleanupAsserts.length; for (var i:int = 0; i < n; i++) { var assert:Assert = cleanupAsserts[i]; assert.cleanup(); } timer.removeEventListener("timer", timerHandler); if (needCompleteEvent) dispatchEvent(new Event("runComplete")); return true; } /** * Go through the currentSteps, executing each one. * Returns true if no test steps required waiting. * Returns false if we have to wait for an event before * continuing. */ private function runSteps():Boolean { while (currentIndex < numSteps) { // return if a step failed if (testResult.hasStatus()) return true; /* The following lets you step each step but makes tests more sensitive to which step actually sends the event. For example, cb.mouseDown/mouseUp, the tween starts on mousedown and fires its event before you step. Another example is asserting with waitEvent=updateComplete. It could have fired a long time before you step */ if (UnitTester.playbackControl == "pause") { UnitTester.callback = pauseHandler; needCompleteEvent = true; return false; } else if (UnitTester.playbackControl == "step") UnitTester.playbackControl = "pause"; var step:TestStep = currentSteps[currentIndex]; if (!(step is Assert)) { // look at subsequent steps for Asserts and set them up early for (var j:int = currentIndex + 1; j < numSteps; j++) { // scan following asserts for AssertEvents and set them up early var nextStep:TestStep = currentSteps[j]; if (nextStep is Assert) { Assert(nextStep).preview(root, context, this, testResult); // do a check to be sure folks are using AssertEventPropertyValue correctly if (nextStep is AssertEventPropertyValue) { // AEPV must follow an AssertEvent or another AEPV if (j == 0 || !(currentSteps[j-1] is AssertEvent || currentSteps[j-1] is AssertEventPropertyValue)) TestOutput.logResult("WARNING: AssertEventPropertyValue may be missing preceding AssertEvent"); } else if (nextStep is AssertError) { if (step is SetProperty) SetProperty(step).expectError = true; } } else break; } } if (UnitTester.verboseMode) { TestOutput.logResult(step.toString()); } UnitTester.lastStep = step; UnitTester.lastStepLine = currentIndex; step.addEventListener("stepComplete", stepCompleteHandler); if (!step.execute(root, context, this, testResult)) { needCompleteEvent = true; return false; } step.removeEventListener("stepComplete", stepCompleteHandler); currentIndex++; } return true; } private function stepCompleteHandler(event:Event):void { var step:TestStep = currentSteps[currentIndex]; step.removeEventListener("stepComplete", stepCompleteHandler); if (UnitTester.playbackControl == "play") UnitTester.callback = runNextSteps; else { currentIndex++; UnitTester.callback = pauseHandler; } } /** * Handler for timer events to see if we've waited too long */ private function timerHandler(event:Event):void { if (expirationTime > 0) if (expirationTime < getTimer()) { var step:TestStep = currentSteps[currentIndex]; step.timeoutCallback(); } } /** * Determines which set of steps (setup, body, cleanup) to run next */ private function runNextSteps():void { currentIndex++; if (currentSteps == setup) runSetup(true); else if (currentSteps == body) runBody(true); else if (currentSteps == cleanup) runCleanup(true); else runComplete(); } /** * Determines which set of steps (setup, body, cleanup) to run next */ private function continueSteps():void { if (currentSteps == setup) runSetup(true); else if (currentSteps == body) runBody(true); else if (currentSteps == cleanup) runCleanup(true); else runComplete(); } /** * Determines which set of steps (setup, body, cleanup) to run next */ private function pauseHandler():void { if (UnitTester.playbackControl == "step") continueSteps(); else if (UnitTester.playbackControl == "play") continueSteps(); else UnitTester.callback = pauseHandler; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import flash.display.DisplayObject; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.utils.getQualifiedClassName; import flash.utils.getTimer; import flash.utils.Timer; /** * A Test. A Test script comprises several of these * TestCases. Each TestCase consists of a * setup, body and cleanup section which are sets * of TestStep-derived classes like SetProperty, * RunCode, AssertPropertyValue, etc. * * MXML Properties (not attributes) * setup * body * cleanup */ public class TestCase extends EventDispatcher { /** * The history of bugs that this test case has encountered */ public var bugs:Array; /** * The sequence of TestSteps that comprise the test setup */ public var setup:Array; /** * The sequence of TestSteps that comprise the test */ public var body:Array; /** * The sequence of TestSteps that restore the test environment */ public var cleanup:Array; /** * An identifier for the test */ public var testID:String; /** * A description of the test */ public var description:String; /** * keywords, summarizing the tests */ public var keywords:String; /** * frequency, an estimate of the tests's intersection with real-world * usage. 1 = most frequent usage; 2 somewhat common; 3 = unusual */ public var frequency:String; /** * The current set of steps (setup, body, cleanup) we are executing */ private var currentSteps:Array; /** * Which step we're currently executing (or waiting on an event for) */ private var currentIndex:int = 0; /** * Number of steps in currentSteps */ private var numSteps:int = 0; /** * The root of the SWF (SystemManager) */ private var root:DisplayObject; /** * The shared timer we listen to */ private var timer:Timer; /** * The unit tester */ private var context:UnitTester; /** * Whether we need to emit a runComplete event or not */ private var needCompleteEvent:Boolean = false; /** * If non-zero, the time when we'll give up on waiting */ public var expirationTime:int; /** * the last expected Error thrown by SetProperty */ public var lastError:Error; /** * Called by test steps looking for a timeout indicator */ public function setExpirationTime(time:int):void { expirationTime = (time > 0) ? time + UnitTester.timeout_plus : 0; } /** * Storage for the cleanupAsserts */ private var _cleanupAsserts:Array; /** * Steps we have to review at the end of the body to see if * they failed or not. These steps monitor activity like * checking for duplicate events or making sure unwanted events * don't fire. */ public function get cleanupAsserts():Array { return _cleanupAsserts; } /** * Storage for this tests's result */ private var _testResult:TestResult; /** * This tests's result */ public function get testResult():TestResult { _testResult.testID = testID; return _testResult; } /** * Constructor. Create the TestResult associated with this TestCase */ public function TestCase() { _testResult = new TestResult(); _testResult.testID = testID; _cleanupAsserts = []; } /** * Called by the UnitTester when it is time to execute * this test case. * * @param root The SystemManager * @param timer The shared Timer; * @param the UnitTester that contains these tests */ public function runTest(root:DisplayObject, timer:Timer, context:UnitTester):Boolean { _testResult.beginTime = new Date().time; _testResult.context = context; this.timer = timer; this.timer.addEventListener("timer", timerHandler); this.root = root; this.context = context; if (UnitTester.hasRTE) { return true; } // do a sanity test here if (UnitTester.verboseMode) { var needWaitEvent:Boolean = false; var i:int; if (setup) { for (i = 0; i < setup.length; i++) { if (setup[i] is ResetComponent) needWaitEvent = true; if (needWaitEvent) { if (setup[i].waitEvent) { needWaitEvent = false; break; } } } if (needWaitEvent) TestOutput.logResult("WARNING: Test " + getQualifiedClassName(context) + "." + testID + " ResetComponent used without any setup steps using a waitEvent\n"); } var allAsserts:Boolean = true; needWaitEvent = false; for (i = 0; i < body.length; i++) { if (body[i] is SetProperty || body[i] is SetStyle) needWaitEvent = true; if (!(body[i] is Assert)) allAsserts = false; if (allAsserts && body[i] is AssertEvent) { TestOutput.logResult("WARNING: Test " + getQualifiedClassName(context) + "." + testID + " no non-Assert steps in body before AssertEvent\n"); } if (needWaitEvent) { if (body[i].waitEvent) { needWaitEvent = false; break; } } } if (needWaitEvent) TestOutput.logResult("WARNING: Test " + getQualifiedClassName(context) + "." + testID + " tests setting values without a waitEvent\n"); } return runSetup(); } /** * Execute the setup portion of the test * * @param continuing If true, don't reset the counter to zero * and just continue on with the test at the currentIndex */ private function runSetup(continuing:Boolean = false):Boolean { if (!testResult.hasStatus()) { if (setup) { testResult.phase = TestResult.SETUP; currentSteps = setup; if (!continuing) currentIndex = 0; numSteps = setup.length; // return if we need to wait for something if (!runSteps()) return false; } } return runBody(); } /** * Execute the body portion of the test * * @param continuing If true, don't reset the counter to zero * and just continue on with the test at the currentIndex */ private function runBody(continuing:Boolean = false):Boolean { if (!testResult.hasStatus()) { if (body) { testResult.phase = TestResult.BODY; currentSteps = body; if (!continuing) currentIndex = 0; numSteps = body.length; // return if we need to wait for something if (!runSteps()) return false; } } return runCleanup(); } /** * Execute the cleanup portion of the test * * @param continuing If true, don't reset the counter to zero * and just continue on with the test at the currentIndex */ private function runCleanup(continuing:Boolean = false):Boolean { if (!testResult.hasStatus()) { if (cleanup) { testResult.phase = TestResult.CLEANUP; currentSteps = cleanup; if (!continuing) currentIndex = 0; numSteps = cleanup.length; // return if we need to wait for something if (!runSteps()) return false; } } return runComplete(); } /** * Clean up when all three phases are done. Sends an event * to the UnitTester harness to tell it that it can run * the next test case. */ private function runComplete():Boolean { var n:int = cleanupAsserts.length; for (var i:int = 0; i < n; i++) { var assert:Assert = cleanupAsserts[i]; assert.cleanup(); } timer.removeEventListener("timer", timerHandler); if (needCompleteEvent) dispatchEvent(new Event("runComplete")); return true; } /** * Go through the currentSteps, executing each one. * Returns true if no test steps required waiting. * Returns false if we have to wait for an event before * continuing. */ private function runSteps():Boolean { while (currentIndex < numSteps) { // return if a step failed if (testResult.hasStatus()) return true; /* The following lets you step each step but makes tests more sensitive to which step actually sends the event. For example, cb.mouseDown/mouseUp, the tween starts on mousedown and fires its event before you step. Another example is asserting with waitEvent=updateComplete. It could have fired a long time before you step */ if (UnitTester.playbackControl == "pause") { UnitTester.callback = pauseHandler; needCompleteEvent = true; return false; } else if (UnitTester.playbackControl == "step") UnitTester.playbackControl = "pause"; var step:TestStep = currentSteps[currentIndex]; if (!(step is Assert)) { // look at subsequent steps for Asserts and set them up early for (var j:int = currentIndex + 1; j < numSteps; j++) { // scan following asserts for AssertEvents and set them up early var nextStep:TestStep = currentSteps[j]; if (nextStep is Assert) { Assert(nextStep).preview(root, context, this, testResult); // do a check to be sure folks are using AssertEventPropertyValue correctly if (nextStep is AssertEventPropertyValue) { // AEPV must follow an AssertEvent or another AEPV if (j == 0 || !(currentSteps[j-1] is AssertEvent || currentSteps[j-1] is AssertEventPropertyValue)) TestOutput.logResult("WARNING: AssertEventPropertyValue may be missing preceding AssertEvent"); } else if (nextStep is AssertError) { if (step is SetProperty) SetProperty(step).expectError = true; } } else break; } } if (UnitTester.verboseMode) { TestOutput.logResult(step.toString()); } UnitTester.lastStep = step; UnitTester.lastStepLine = currentIndex; step.addEventListener("stepComplete", stepCompleteHandler); if (!step.execute(root, context, this, testResult)) { needCompleteEvent = true; return false; } step.removeEventListener("stepComplete", stepCompleteHandler); currentIndex++; } return true; } private function stepCompleteHandler(event:Event):void { var step:TestStep = currentSteps[currentIndex]; step.removeEventListener("stepComplete", stepCompleteHandler); if (UnitTester.playbackControl == "play") UnitTester.callback = runNextSteps; else { currentIndex++; UnitTester.callback = pauseHandler; } } /** * Handler for timer events to see if we've waited too long */ private function timerHandler(event:Event):void { if (expirationTime > 0) if (expirationTime < getTimer()) { var step:TestStep = currentSteps[currentIndex]; step.timeoutCallback(); } } /** * Determines which set of steps (setup, body, cleanup) to run next */ private function runNextSteps():void { currentIndex++; if (currentSteps == setup) runSetup(true); else if (currentSteps == body) runBody(true); else if (currentSteps == cleanup) runCleanup(true); else runComplete(); } /** * Determines which set of steps (setup, body, cleanup) to run next */ private function continueSteps():void { if (currentSteps == setup) runSetup(true); else if (currentSteps == body) runBody(true); else if (currentSteps == cleanup) runCleanup(true); else runComplete(); } /** * Determines which set of steps (setup, body, cleanup) to run next */ private function pauseHandler():void { if (UnitTester.playbackControl == "step") continueSteps(); else if (UnitTester.playbackControl == "play") continueSteps(); else UnitTester.callback = pauseHandler; } } }
Fix random timeouts in mobile tests that use step_timeout/timeout_plus.
Fix random timeouts in mobile tests that use step_timeout/timeout_plus. git-svn-id: f8d5f742b420a6a114b58659a4f85f335318e53c@1433777 13f79535-47bb-0310-9956-ffa450edef68
ActionScript
apache-2.0
danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk
71faaf04e11c7ef0773a968019d14eacd33410b6
src/org/mangui/hls/stream/HLSNetStream.as
src/org/mangui/hls/stream/HLSNetStream.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls.stream { import org.mangui.hls.controller.BufferThresholdController; import org.mangui.hls.event.HLSPlayMetrics; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Hex; import flash.events.Event; import flash.events.NetStatusEvent; import flash.events.TimerEvent; import flash.net.*; import flash.utils.*; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state * * play state transition : * FROM TO condition * HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called * HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength * HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength * HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength * HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength */ public class HLSNetStream extends NetStream { /** Reference to the framework controller. **/ private var _hls : HLS; /** reference to buffer threshold controller */ private var _bufferThresholdController : BufferThresholdController; /** FLV Tag Buffer . **/ private var _streamBuffer : StreamBuffer; /** means that last fragment of a VOD playlist has been loaded */ private var _reached_vod_end : Boolean; /** Timer used to check buffer and position. **/ private var _timer : Timer; /** Current playback state. **/ private var _playbackState : String; /** Current seek state. **/ private var _seekState : String; /** current playback level **/ private var _playbackLevel : int; /** Netstream client proxy */ private var _client : HLSNetStreamClient; /** Create the buffer. **/ public function HLSNetStream(connection : NetConnection, hls : HLS, streamBuffer : StreamBuffer) : void { super(connection); super.bufferTime = 0.1; _hls = hls; _bufferThresholdController = new BufferThresholdController(hls); _streamBuffer = streamBuffer; _hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler); _playbackState = HLSPlayStates.IDLE; _seekState = HLSSeekStates.IDLE; _timer = new Timer(100, 0); _timer.addEventListener(TimerEvent.TIMER, _checkBuffer); _client = new HLSNetStreamClient(); _client.registerCallback("onHLSFragmentChange", onHLSFragmentChange); _client.registerCallback("onID3Data", onID3Data); super.client = _client; }; public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void { CONFIG::LOGGING { Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc); } _playbackLevel = level; var tag_list : Array = new Array(); for (var i : uint = 0; i < tags.length; i++) { tag_list.push(tags[i]); CONFIG::LOGGING { Log.debug("custom tag:" + tags[i]); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list))); } // function is called by SCRIPT in FLV public function onID3Data(data : ByteArray) : void { var dump : String = "unset"; // we dump the content as hex to get it to the Javascript in the browser. // from lots of searching, we could use base64, but even then, the decode would // not be native, so hex actually seems more efficient dump = Hex.fromArray(data); CONFIG::LOGGING { Log.debug("id3:" + dump); } _hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump)); } /** timer function, check/update NetStream state, and append tags if needed **/ private function _checkBuffer(e : Event) : void { var buffer : Number = this.bufferLength; // Log.info("netstream/total:" + super.bufferLength + "/" + this.bufferLength); // Set playback state. no need to check buffer status if seeking if (_seekState != HLSSeekStates.SEEKING) { // check low buffer condition if (buffer <= 0.1) { if (_reached_vod_end) { // Last tag done? Then append sequence end. super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); super.appendBytes(new ByteArray()); // reach end of playlist + playback complete (as buffer is empty). // stop timer, report event and switch to IDLE mode. _timer.stop(); CONFIG::LOGGING { Log.debug("reached end of VOD playlist, notify playback complete"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE)); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); return; } else { // buffer <= 0.1 and not EOS, pause playback super.pause(); } } // if buffer len is below lowBufferLength, get into buffering state if (!_reached_vod_end && buffer < _bufferThresholdController.lowBufferLength) { if (_playbackState == HLSPlayStates.PLAYING) { // low buffer condition and play state. switch to play buffering state _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } else if (_playbackState == HLSPlayStates.PAUSED) { // low buffer condition and pause state. switch to paused buffering state _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } } // if buffer len is above minBufferLength, get out of buffering state if (buffer >= _bufferThresholdController.minBufferLength || _reached_vod_end) { if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { CONFIG::LOGGING { Log.debug("resume playback"); } // resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s) super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { _setPlaybackState(HLSPlayStates.PAUSED); } } } }; /** Return the current playback state. **/ public function get playbackState() : String { return _playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _seekState; }; /** Return the current playback quality level **/ public function get playbackLevel() : int { return _playbackLevel; }; /** append tags to NetStream **/ public function appendTags(tags : Vector.<FLVTag>) : void { if (_seekState == HLSSeekStates.SEEKING) { /* this is our first injection after seek(), let's flush netstream now this is to avoid black screen during seek command */ super.close(); CONFIG::FLASH_11_1 { try { super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder; } catch(e : Error) { } } super.play(null); super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); // immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream super.pause(); } // append all tags for each (var tagBuffer : FLVTag in tags) { try { if (tagBuffer.type == FLVTag.DISCONTINUITY) { super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); super.appendBytes(FLVTag.getHeader()); } super.appendBytes(tagBuffer.data); } catch (error : Error) { var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } } if (_seekState == HLSSeekStates.SEEKING) { // dispatch event to mimic NetStream behaviour dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"})); _setSeekState(HLSSeekStates.SEEKED); } }; private function _lastVODFragmentLoadedHandler(event : HLSEvent) : void { CONFIG::LOGGING { Log.debug("last fragment loaded"); } _reached_vod_end = true; } /** Change playback state. **/ private function _setPlaybackState(state : String) : void { if (state != _playbackState) { CONFIG::LOGGING { Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state); } _playbackState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState)); } }; /** Change seeking state. **/ private function _setSeekState(state : String) : void { if (state != _seekState) { CONFIG::LOGGING { Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state); } _seekState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState)); } }; override public function play(...args) : void { var _playStart : Number; if (args.length >= 2) { _playStart = Number(args[1]); } else { _playStart = -1; } CONFIG::LOGGING { Log.info("HLSNetStream:play(" + _playStart + ")"); } seek(_playStart); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } override public function play2(param : NetStreamPlayOptions) : void { CONFIG::LOGGING { Log.info("HLSNetStream:play2(" + param.start + ")"); } seek(param.start); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } /** Pause playback. **/ override public function pause() : void { CONFIG::LOGGING { Log.info("HLSNetStream:pause"); } if (_playbackState == HLSPlayStates.PLAYING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED); } else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } }; /** Resume playback. **/ override public function resume() : void { CONFIG::LOGGING { Log.info("HLSNetStream:resume"); } if (_playbackState == HLSPlayStates.PAUSED) { super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { // dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } }; /** get Buffer Length **/ override public function get bufferLength() : Number { return netStreamBufferLength + _streamBuffer.bufferLength; }; public function get netStreamBufferLength() : Number { if (_seekState == HLSSeekStates.SEEKING) { return 0; } else { return super.bufferLength; } }; /** Start playing data in the buffer. **/ override public function seek(position : Number) : void { CONFIG::LOGGING { Log.info("HLSNetStream:seek(" + position + ")"); } _streamBuffer.seek(position); _reached_vod_end = false; _setSeekState(HLSSeekStates.SEEKING); /* if HLS was in paused state before seeking, * switch to paused buffering state * otherwise, switch to playing buffering state */ switch(_playbackState) { case HLSPlayStates.PAUSED: case HLSPlayStates.PAUSED_BUFFERING: _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); break; case HLSPlayStates.PLAYING: case HLSPlayStates.PLAYING_BUFFERING: _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); break; default: break; } /* always pause NetStream while seeking, even if we are in play state * in that case, NetStream will be resumed after first fragment loading */ super.pause(); _timer.start(); }; public override function set client(client : Object) : void { _client.delegate = client; }; public override function get client() : Object { return _client.delegate; } /** Stop playback. **/ override public function close() : void { CONFIG::LOGGING { Log.info("HLSNetStream:close"); } super.close(); _streamBuffer.stop(); _timer.stop(); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); }; public function dispose_() : void { close(); _bufferThresholdController.dispose(); _hls.removeEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler); } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls.stream { import org.mangui.hls.controller.BufferThresholdController; import org.mangui.hls.event.HLSPlayMetrics; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Hex; import flash.events.Event; import flash.events.NetStatusEvent; import flash.events.TimerEvent; import flash.net.*; import flash.utils.*; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state * * play state transition : * FROM TO condition * HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called * HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength * HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength * HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength * HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength */ public class HLSNetStream extends NetStream { /** Reference to the framework controller. **/ private var _hls : HLS; /** reference to buffer threshold controller */ private var _bufferThresholdController : BufferThresholdController; /** FLV Tag Buffer . **/ private var _streamBuffer : StreamBuffer; /** means that last fragment of a VOD playlist has been loaded */ private var _reached_vod_end : Boolean; /** Timer used to check buffer and position. **/ private var _timer : Timer; /** Current playback state. **/ private var _playbackState : String; /** Current seek state. **/ private var _seekState : String; /** current playback level **/ private var _playbackLevel : int; /** Netstream client proxy */ private var _client : HLSNetStreamClient; /** Create the buffer. **/ public function HLSNetStream(connection : NetConnection, hls : HLS, streamBuffer : StreamBuffer) : void { super(connection); super.bufferTime = 0.1; _hls = hls; _bufferThresholdController = new BufferThresholdController(hls); _streamBuffer = streamBuffer; _hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler); _playbackState = HLSPlayStates.IDLE; _seekState = HLSSeekStates.IDLE; _timer = new Timer(100, 0); _timer.addEventListener(TimerEvent.TIMER, _checkBuffer); _client = new HLSNetStreamClient(); _client.registerCallback("onHLSFragmentChange", onHLSFragmentChange); _client.registerCallback("onID3Data", onID3Data); super.client = _client; }; public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void { CONFIG::LOGGING { Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc); } _playbackLevel = level; var tag_list : Array = new Array(); for (var i : uint = 0; i < tags.length; i++) { tag_list.push(tags[i]); CONFIG::LOGGING { Log.debug("custom tag:" + tags[i]); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list))); } // function is called by SCRIPT in FLV public function onID3Data(data : ByteArray) : void { var dump : String = "unset"; // we dump the content as hex to get it to the Javascript in the browser. // from lots of searching, we could use base64, but even then, the decode would // not be native, so hex actually seems more efficient dump = Hex.fromArray(data); CONFIG::LOGGING { Log.debug("id3:" + dump); } _hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump)); } /** timer function, check/update NetStream state, and append tags if needed **/ private function _checkBuffer(e : Event) : void { var buffer : Number = this.bufferLength; // Log.info("netstream/total:" + super.bufferLength + "/" + this.bufferLength); // Set playback state. no need to check buffer status if seeking if (_seekState != HLSSeekStates.SEEKING) { // check low buffer condition if (buffer <= 0.1) { if (_reached_vod_end) { // Last tag done? Then append sequence end. super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); super.appendBytes(new ByteArray()); // reach end of playlist + playback complete (as buffer is empty). // stop timer, report event and switch to IDLE mode. _timer.stop(); CONFIG::LOGGING { Log.debug("reached end of VOD playlist, notify playback complete"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE)); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); return; } else { // buffer <= 0.1 and not EOS, pause playback super.pause(); } } // if buffer len is below lowBufferLength, get into buffering state if (!_reached_vod_end && buffer < _bufferThresholdController.lowBufferLength) { if (_playbackState == HLSPlayStates.PLAYING) { // low buffer condition and play state. switch to play buffering state _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } else if (_playbackState == HLSPlayStates.PAUSED) { // low buffer condition and pause state. switch to paused buffering state _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } } // if buffer len is above minBufferLength, get out of buffering state if (buffer >= _bufferThresholdController.minBufferLength || _reached_vod_end) { if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { CONFIG::LOGGING { Log.debug("resume playback"); } // resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s) super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { _setPlaybackState(HLSPlayStates.PAUSED); } } } }; /** Return the current playback state. **/ public function get playbackState() : String { return _playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _seekState; }; /** Return the current playback quality level **/ public function get playbackLevel() : int { return _playbackLevel; }; /** append tags to NetStream **/ public function appendTags(tags : Vector.<FLVTag>) : void { if (_seekState == HLSSeekStates.SEEKING) { /* this is our first injection after seek(), let's flush netstream now this is to avoid black screen during seek command */ super.close(); CONFIG::FLASH_11_1 { try { super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder; } catch(e : Error) { } } super.play(null); super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); // immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream super.pause(); } // append all tags for each (var tagBuffer : FLVTag in tags) { try { if (tagBuffer.type == FLVTag.DISCONTINUITY) { super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); super.appendBytes(FLVTag.getHeader()); } super.appendBytes(tagBuffer.data); } catch (error : Error) { var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } } if (_seekState == HLSSeekStates.SEEKING) { // dispatch event to mimic NetStream behaviour dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"})); _setSeekState(HLSSeekStates.SEEKED); } }; private function _lastVODFragmentLoadedHandler(event : HLSEvent) : void { CONFIG::LOGGING { Log.debug("last fragment loaded"); } _reached_vod_end = true; } /** Change playback state. **/ private function _setPlaybackState(state : String) : void { if (state != _playbackState) { CONFIG::LOGGING { Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state); } _playbackState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState)); } }; /** Change seeking state. **/ private function _setSeekState(state : String) : void { if (state != _seekState) { CONFIG::LOGGING { Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state); } _seekState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState)); } }; override public function play(...args) : void { var _playStart : Number; if (args.length >= 2) { _playStart = Number(args[1]); } else { _playStart = -1; } CONFIG::LOGGING { Log.info("HLSNetStream:play(" + _playStart + ")"); } seek(_playStart); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } override public function play2(param : NetStreamPlayOptions) : void { CONFIG::LOGGING { Log.info("HLSNetStream:play2(" + param.start + ")"); } seek(param.start); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } /** Pause playback. **/ override public function pause() : void { CONFIG::LOGGING { Log.info("HLSNetStream:pause"); } if (_playbackState == HLSPlayStates.PLAYING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED); } else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } }; /** Resume playback. **/ override public function resume() : void { CONFIG::LOGGING { Log.info("HLSNetStream:resume"); } if (_playbackState == HLSPlayStates.PAUSED) { super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { // dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } }; /** get Buffer Length **/ override public function get bufferLength() : Number { return netStreamBufferLength + _streamBuffer.bufferLength; }; public function get netStreamBufferLength() : Number { if (_seekState == HLSSeekStates.SEEKING) { return 0; } else { return super.bufferLength; } }; /** Start playing data in the buffer. **/ override public function seek(position : Number) : void { CONFIG::LOGGING { Log.info("HLSNetStream:seek(" + position + ")"); } _streamBuffer.seek(position); _reached_vod_end = false; _setSeekState(HLSSeekStates.SEEKING); /* if HLS was in paused state before seeking, * switch to paused buffering state * otherwise, switch to playing buffering state */ switch(_playbackState) { case HLSPlayStates.PAUSED: case HLSPlayStates.PAUSED_BUFFERING: _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); break; case HLSPlayStates.PLAYING: case HLSPlayStates.PLAYING_BUFFERING: _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); break; default: break; } /* always pause NetStream while seeking, even if we are in play state * in that case, NetStream will be resumed during next call to appendTags() */ super.pause(); _timer.start(); }; public override function set client(client : Object) : void { _client.delegate = client; }; public override function get client() : Object { return _client.delegate; } /** Stop playback. **/ override public function close() : void { CONFIG::LOGGING { Log.info("HLSNetStream:close"); } super.close(); _streamBuffer.stop(); _timer.stop(); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); }; public function dispose_() : void { close(); _bufferThresholdController.dispose(); _hls.removeEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler); } } }
adjust comments
adjust comments
ActionScript
mpl-2.0
suuhas/flashls,viktorot/flashls,dighan/flashls,thdtjsdn/flashls,tedconf/flashls,mangui/flashls,jlacivita/flashls,School-Improvement-Network/flashls,loungelogic/flashls,aevange/flashls,clappr/flashls,codex-corp/flashls,fixedmachine/flashls,Peer5/flashls,mangui/flashls,aevange/flashls,clappr/flashls,tedconf/flashls,Corey600/flashls,neilrackett/flashls,vidible/vdb-flashls,JulianPena/flashls,NicolasSiver/flashls,suuhas/flashls,Peer5/flashls,jlacivita/flashls,thdtjsdn/flashls,loungelogic/flashls,School-Improvement-Network/flashls,Corey600/flashls,aevange/flashls,codex-corp/flashls,viktorot/flashls,neilrackett/flashls,Boxie5/flashls,hola/flashls,viktorot/flashls,NicolasSiver/flashls,hola/flashls,vidible/vdb-flashls,dighan/flashls,JulianPena/flashls,aevange/flashls,School-Improvement-Network/flashls,fixedmachine/flashls,suuhas/flashls,Peer5/flashls,Peer5/flashls,Boxie5/flashls,suuhas/flashls
8be8fd65b93295262534d25131218f6a22612d68
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/AbstractStateCommand.as
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/AbstractStateCommand.as
package org.servebox.cafe.core.command { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import org.servebox.cafe.core.signal.SignalAggregator; public class AbstractStateCommand extends EventDispatcher implements IStateCommand { public function AbstractStateCommand(target:IEventDispatcher=null) { super(target); } [Autowired] public var signalAggregator : SignalAggregator; private var _parameters : Array; public function get executable():Boolean { return true; } public function set executable(value:Boolean):void { } public function get parameters():Array { return _parameters; } public function set parameters(value:Array):void { _parameters = value; } protected function getParameter( key : String ) : IParameterObject { var paramToReturn : IParameterObject; for each ( var param : IParameterObject in _parameters ) { if ( param.key == key ) { paramToReturn = param; } } if ( !paramToReturn ) { throw new Error("No parameter " + key + " in " + this + " command, check command binding "); } return paramToReturn; } public function execute( e : Event = null ) : void { } } }
package org.servebox.cafe.core.command { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import org.servebox.cafe.core.signal.SignalAggregator; public class AbstractStateCommand extends EventDispatcher implements IStateCommand { public function AbstractStateCommand(target:IEventDispatcher=null) { super(target); } [Autowired] public var signalAggregator : SignalAggregator; private var _parameters : Array; public function get executable():Boolean { return true; } public function set executable(value:Boolean):void { } public function get parameters():Array { if ( _parameters == null ) { _parameters = new Array(); } return _parameters; } public function set parameters(value:Array):void { _parameters = value; } protected function getParameter( key : String ) : IParameterObject { var paramToReturn : IParameterObject; for each ( var param : IParameterObject in _parameters ) { if ( param.key == key ) { paramToReturn = param; } } if ( !paramToReturn ) { throw new Error("No parameter " + key + " in " + this + " command, check command binding "); } return paramToReturn; } public function addParameter( key : String , value : Object ) : void { var param : AbstractParameterObject = new AbstractParameterObject( key, value ); parameters.push( param ); } public function execute( e : Event = null ) : void { } } }
Add addParameter method.
Add addParameter method.
ActionScript
mit
servebox/as-cafe
45f55adf6c790b358a924ac081e62de615fdf671
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
package aerys.minko.render.shader.compiler.graph { import aerys.minko.Minko; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.Signature; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Interpolate; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter; import aerys.minko.render.shader.compiler.graph.nodes.vertex.VariadicExtract; import aerys.minko.render.shader.compiler.graph.visitors.*; import aerys.minko.render.shader.compiler.register.Components; import aerys.minko.render.shader.compiler.sequence.AgalInstruction; import aerys.minko.type.log.DebugLevel; import aerys.minko.render.geometry.stream.format.VertexComponent; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; /** * @private * @author Romain Gilliotte * */ public class ShaderGraph { private static const SPLITTER : SplitterVisitor = new SplitterVisitor(); private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor(); private static const MERGER : MergeVisitor = new MergeVisitor(); private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor(); private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor(); private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor(); private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor(); private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor(); private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation(); private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor(); private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor(); private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder(); private static const WRITE_DOT : WriteDot = new WriteDot(); private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper(); private var _position : AbstractNode; private var _positionComponents : uint; private var _interpolates : Vector.<AbstractNode>; private var _color : AbstractNode; private var _colorComponents : uint; private var _kills : Vector.<AbstractNode>; private var _killComponents : Vector.<uint>; private var _computableConstants : Object; private var _isCompiled : Boolean; private var _vertexSequence : Vector.<AgalInstruction>; private var _fragmentSequence : Vector.<AgalInstruction>; private var _bindings : Object; private var _vertexComponents : Vector.<VertexComponent>; private var _vertexIndices : Vector.<uint>; private var _vsConstants : Vector.<Number>; private var _fsConstants : Vector.<Number>; private var _textures : Vector.<ITextureResource>; public function get position() : AbstractNode { return _position; } public function set position(v : AbstractNode) : void { _position = v; } public function get interpolates() : Vector.<AbstractNode> { return _interpolates; } public function get color() : AbstractNode { return _color; } public function set color(v : AbstractNode) : void { _color = v; } public function get kills() : Vector.<AbstractNode> { return _kills; } public function get positionComponents() : uint { return _positionComponents; } public function set positionComponents(v : uint) : void { _positionComponents = v; } public function get colorComponents() : uint { return _colorComponents; } public function set colorComponents(v : uint) : void { _colorComponents = v; } public function get killComponents() : Vector.<uint> { return _killComponents; } public function get computableConstants() : Object { return _computableConstants; } public function ShaderGraph(position : AbstractNode, color : AbstractNode, kills : Vector.<AbstractNode>) { _isCompiled = false; _position = position; _positionComponents = Components.createContinuous(0, 0, 4, position.size); _interpolates = new Vector.<AbstractNode>(); _color = color; _colorComponents = Components.createContinuous(0, 0, 4, color.size); _kills = kills; _killComponents = new Vector.<uint>(); _computableConstants = new Object(); var numKills : uint = kills.length; for (var killId : uint = 0; killId < numKills; ++killId) _killComponents[killId] = Components.createContinuous(0, 0, 1, 1); } public function generateProgram(name : String, signature : Signature) : Program3DResource { if (!_isCompiled) compile(); if (Minko.debugLevel & DebugLevel.SHADER_AGAL) Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name)); var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true); var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false); var program : Program3DResource = new Program3DResource( name, signature, vsProgram, fsProgram, _vertexComponents, _vertexIndices, _vsConstants, _fsConstants, _textures, _bindings ); return program; } public function generateAGAL(name : String) : String { var instruction : AgalInstruction; var shader : String = name + "\n"; if (!_isCompiled) compile(); shader += "- vertex shader\n"; for each (instruction in _vertexSequence) shader += instruction.getAgal(true); shader += "- fragment shader\n"; for each (instruction in _fragmentSequence) shader += instruction.getAgal(false); return shader; } private function compile() : void { // execute consecutive visitors to optimize the shader graph. // Warning: the order matters, do not swap lines. MERGER .process(this); // merge duplicate nodes REMOVE_EXTRACT .process(this); // remove all extract nodes OVERWRITER_CLEANER .process(this); // remove nested overwriters RESOLVE_CONSTANT .process(this); // resolve constant computation CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy // REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...) RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters // MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU COPY_INSERTER .process(this); // ensure there are no operations between constants SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2] if (Minko.debugLevel & DebugLevel.SHADER_DOTTY) { WRITE_DOT.process(this); Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result); WRITE_DOT.clear(); } // generate final program INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future. ALLOCATOR .process(this); // allocate memory and generate final code. // retrieve program _vertexSequence = ALLOCATOR.vertexSequence; _fragmentSequence = ALLOCATOR.fragmentSequence; _bindings = ALLOCATOR.parameterBindings; _vertexComponents = ALLOCATOR.vertexComponents; _vertexIndices = ALLOCATOR.vertexIndices; _vsConstants = ALLOCATOR.vertexConstants; _fsConstants = ALLOCATOR.fragmentConstants; _textures = ALLOCATOR.textures; ALLOCATOR.clear(); _isCompiled = true; } private function computeBinaryProgram(sequence : Vector.<AgalInstruction>, isVertexShader : Boolean) : ByteArray { var program : ByteArray = new ByteArray(); program.endian = Endian.LITTLE_ENDIAN; program.writeByte(0xa0); // tag version program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000 program.writeByte(0xa1); // tag program id program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment for each (var instruction : AgalInstruction in sequence) instruction.getBytecode(program); return program; } } }
package aerys.minko.render.shader.compiler.graph { import aerys.minko.Minko; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.Signature; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.graph.visitors.*; import aerys.minko.render.shader.compiler.register.Components; import aerys.minko.render.shader.compiler.sequence.AgalInstruction; import aerys.minko.type.log.DebugLevel; import flash.utils.ByteArray; import flash.utils.Endian; /** * @private * @author Romain Gilliotte * */ public class ShaderGraph { private static const SPLITTER : SplitterVisitor = new SplitterVisitor(); private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor(); private static const MERGER : MergeVisitor = new MergeVisitor(); private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor(); private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor(); private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor(); private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor(); private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor(); private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation(); private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor(); private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor(); private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder(); private static const WRITE_DOT : WriteDot = new WriteDot(); private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper(); private var _position : AbstractNode; private var _positionComponents : uint; private var _interpolates : Vector.<AbstractNode>; private var _color : AbstractNode; private var _colorComponents : uint; private var _kills : Vector.<AbstractNode>; private var _killComponents : Vector.<uint>; private var _computableConstants : Object; private var _isCompiled : Boolean; private var _vertexSequence : Vector.<AgalInstruction>; private var _fragmentSequence : Vector.<AgalInstruction>; private var _bindings : Object; private var _vertexComponents : Vector.<VertexComponent>; private var _vertexIndices : Vector.<uint>; private var _vsConstants : Vector.<Number>; private var _fsConstants : Vector.<Number>; private var _textures : Vector.<ITextureResource>; public function get position() : AbstractNode { return _position; } public function set position(v : AbstractNode) : void { _position = v; } public function get interpolates() : Vector.<AbstractNode> { return _interpolates; } public function get color() : AbstractNode { return _color; } public function set color(v : AbstractNode) : void { _color = v; } public function get kills() : Vector.<AbstractNode> { return _kills; } public function get positionComponents() : uint { return _positionComponents; } public function set positionComponents(v : uint) : void { _positionComponents = v; } public function get colorComponents() : uint { return _colorComponents; } public function set colorComponents(v : uint) : void { _colorComponents = v; } public function get killComponents() : Vector.<uint> { return _killComponents; } public function get computableConstants() : Object { return _computableConstants; } public function ShaderGraph(position : AbstractNode, color : AbstractNode, kills : Vector.<AbstractNode>) { _isCompiled = false; _position = position; _positionComponents = Components.createContinuous(0, 0, 4, position.size); _interpolates = new Vector.<AbstractNode>(); _color = color; _colorComponents = Components.createContinuous(0, 0, 4, color.size); _kills = kills; _killComponents = new Vector.<uint>(); _computableConstants = new Object(); var numKills : uint = kills.length; for (var killId : uint = 0; killId < numKills; ++killId) _killComponents[killId] = Components.createContinuous(0, 0, 1, 1); } public function generateProgram(name : String, signature : Signature) : Program3DResource { if (!_isCompiled) compile(); if (Minko.debugLevel & DebugLevel.SHADER_AGAL) Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name)); var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true); var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false); var program : Program3DResource = new Program3DResource( name, signature, vsProgram, fsProgram, _vertexComponents, _vertexIndices, _vsConstants, _fsConstants, _textures, _bindings ); return program; } public function generateAGAL(name : String) : String { var instruction : AgalInstruction; var shader : String = name + "\n"; if (!_isCompiled) compile(); shader += "- vertex shader\n"; for each (instruction in _vertexSequence) shader += instruction.getAgal(true); shader += "- fragment shader\n"; for each (instruction in _fragmentSequence) shader += instruction.getAgal(false); return shader; } private function compile() : void { // execute consecutive visitors to optimize the shader graph. // Warning: the order matters, do not swap lines. MERGER .process(this); // merge duplicate nodes REMOVE_EXTRACT .process(this); // remove all extract nodes OVERWRITER_CLEANER .process(this); // remove nested overwriters RESOLVE_CONSTANT .process(this); // resolve constant computation CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy // REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...) RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters // MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU COPY_INSERTER .process(this); // ensure there are no operations between constants SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2] if (Minko.debugLevel & DebugLevel.SHADER_DOTTY) { WRITE_DOT.process(this); Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result); WRITE_DOT.clear(); } // generate final program INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future. ALLOCATOR .process(this); // allocate memory and generate final code. // retrieve program _vertexSequence = ALLOCATOR.vertexSequence; _fragmentSequence = ALLOCATOR.fragmentSequence; _bindings = ALLOCATOR.parameterBindings; _vertexComponents = ALLOCATOR.vertexComponents; _vertexIndices = ALLOCATOR.vertexIndices; _vsConstants = ALLOCATOR.vertexConstants; _fsConstants = ALLOCATOR.fragmentConstants; _textures = ALLOCATOR.textures; ALLOCATOR.clear(); _isCompiled = true; } private function computeBinaryProgram(sequence : Vector.<AgalInstruction>, isVertexShader : Boolean) : ByteArray { var program : ByteArray = new ByteArray(); program.endian = Endian.LITTLE_ENDIAN; program.writeByte(0xa0); // tag version program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000 program.writeByte(0xa1); // tag program id program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment for each (var instruction : AgalInstruction in sequence) instruction.getBytecode(program); return program; } } }
remove useless imports
remove useless imports
ActionScript
mit
aerys/minko-as3
d25c5e6a8b411d3764dec1fd86c7244cacf06573
runtime/src/main/as/flump/display/Movie.as
runtime/src/main/as/flump/display/Movie.as
// // Flump - Copyright 2012 Three Rings Design package flump.display { import flump.mold.MovieMold; import org.osflash.signals.Signal; import starling.animation.IAnimatable; import starling.display.DisplayObject; import starling.display.Sprite; import starling.events.Event; /** * A movie created from flump-exported data. It has children corresponding to the layers in the * movie in Flash, in the same order and with the same names. It fills in those children * initially with the image or movie of the symbol on that exported layer. After the initial * population, it only applies the keyframe-based transformations to the child at the index * corresponding to the layer. This means it's safe to swap in other DisplayObjects at those * positions to have them animated in place of the initial child. * * <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function * is otherwise called). When the movie is added to a juggler, it advances its playhead with the * frame ticks if isPlaying is true. It will automatically remove itself from its juggler when * removed from the stage.</p> * * @see Library and LibraryLoader to create instances of Movie. */ public class Movie extends Sprite implements IAnimatable { /** A label fired by all movies when entering their first frame. */ public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME"; /** A label fired by all movies when entering their last frame. */ public static const LAST_FRAME :String = "flump.movie.LAST_FRAME"; /** Fires the label string whenever it's passed in playing. */ public const labelPassed :Signal = new Signal(String); /** @private */ public function Movie (src :MovieMold, frameRate :Number, library :Library) { name = src.id; _labels = src.labels; _frameRate = frameRate; if (src.flipbook) { _layers = new Vector.<Layer>(1, true); _layers[0] = new Layer(this, src.layers[0], library, /*flipbook=*/true); _frames = src.layers[0].frames; } else { _layers = new Vector.<Layer>(src.layers.length, true); for (var ii :int = 0; ii < _layers.length; ii++) { _layers[ii] = new Layer(this, src.layers[ii], library, /*flipbook=*/false); _frames = Math.max(src.layers[ii].frames, _frames); } } _duration = _frames / _frameRate; updateFrame(0, /*fromSkip=*/true, /*overDuration=*/false); // When we're removed from the stage, remove ourselves from any juggler animating us. addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void { dispatchEventWith(Event.REMOVE_FROM_JUGGLER); }); } /** @return the frame being displayed. */ public function get frame () :int { return _frame; } /** @return the number of frames in the movie. */ public function get frames () :int { return _frames; } /** @return true if the movie is currently playing. */ public function get isPlaying () :Boolean { return _playing; } /** Starts playing if not already doing so, and continues to do so indefinitely. */ public function loop () :Movie { _playing = true; _stopFrame = NO_FRAME; return this; } /** * Moves to the given String label or int frame. Doesn't alter playing status or stop frame. * If there are labels at the given position, they're fired as part of the goto, even if the * current frame is equal to the destination. Labels between the current frame and the * destination frame are not fired. * * @param position the int frame or String label to goto. * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie */ public function goto (position :Object) :Movie { const frame :int = extractFrame(position); updateFrame(frame, /*fromSkip=*/true, /*overDuration=*/false); return this; } /** * Starts playing if not already doing so, and continues to do so to the last frame in the * movie. */ public function play () :Movie { return playTo(LAST_FRAME); } /** * Starts playing if not already doing so, and continues to do so to the given stop label or * frame. * * @param position to int frame or String label to stop at * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie. */ public function playTo (position :Object) :Movie { _stopFrame = extractFrame(position); _playing = true; return this; } /** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */ public function stop () :Movie { _playing = false; return this; } /** Advances the playhead by the give number of seconds. From IAnimatable. */ public function advanceTime (dt :Number) :void { if (!_playing) return; _playTime += dt; var actualPlaytime :Number = _playTime; if (_playTime >= _duration) _playTime = _playTime % _duration; var newFrame :int = int(_playTime * _frameRate); const overDuration :Boolean = dt >= _duration; // If the update crosses or goes to the stopFrame, go to the stop frame, stop the movie and // clear it if (_stopFrame != NO_FRAME) { // how many frames remain to the stopframe? var framesRemaining :int = (_frame <= _stopFrame ? _stopFrame - _frame : _frames - _frame + _stopFrame); var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame; if (framesElapsed >= framesRemaining) { _playing = false; newFrame = _stopFrame; _stopFrame = NO_FRAME; } } updateFrame(newFrame, false, overDuration); for (var ii :int = 0; ii < this.numChildren; ++ii) { var child :DisplayObject = getChildAt(ii); if (child is Movie) { Movie(child).advanceTime(dt); } } } /** @private */ protected function extractFrame (position :Object) :int { if (position is int) return int(position); if (!(position is String)) throw new Error("Movie position must be an int frame or String label"); const label :String = String(position); for (var ii :int = 0; ii < _labels.length; ii++) { if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii; } throw new Error("No such label '" + label + "'"); } /** @private */ protected function updateFrame (newFrame :int, fromSkip :Boolean, overDuration :Boolean) :void { if (newFrame >= _frames) { throw new Error("Asked to go to frame " + newFrame + " past the last frame, " + (_frames - 1)); } if (_goingToFrame) { _pendingFrame = newFrame; return; } _goingToFrame = true; const differentFrame :Boolean = newFrame != _frame; const wrapped :Boolean = newFrame < _frame; if (differentFrame) { if (wrapped) { for each (var layer :Layer in _layers) { layer.changedKeyframe = true; layer.keyframeIdx = 0; } } for each (layer in _layers) layer.drawFrame(newFrame); } // Update the frame before firing, so if firing changes the frame, it sticks. const oldFrame :int = _frame; _frame = newFrame; if (fromSkip) { fireLabels(newFrame, newFrame); _playTime = newFrame/_frameRate; } else if (overDuration) { fireLabels(oldFrame + 1, _frames - 1); fireLabels(0, _frame); } else if (differentFrame) { if (wrapped) { fireLabels(oldFrame + 1, _frames - 1); fireLabels(0, _frame); } else fireLabels(oldFrame + 1, _frame); } _goingToFrame = false; if (_pendingFrame != NO_FRAME) { newFrame = _pendingFrame; _pendingFrame = NO_FRAME; updateFrame(newFrame, true, false); } } /** @private */ protected function fireLabels (startFrame :int, endFrame :int) :void { for (var ii :int = startFrame; ii <= endFrame; ii++) { if (_labels[ii] == null) continue; for each (var label :String in _labels[ii]) labelPassed.dispatch(label); } } /** @private */ protected var _goingToFrame :Boolean; /** @private */ protected var _pendingFrame :int = NO_FRAME; /** @private */ protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME; /** @private */ protected var _playing :Boolean = true; /** @private */ protected var _playTime :Number, _duration :Number; /** @private */ protected var _layers :Vector.<Layer>; /** @private */ protected var _frames :int; /** @private */ protected var _frameRate :Number; /** @private */ protected var _labels :Vector.<Vector.<String>>; private static const NO_FRAME :int = -1; } } import flump.display.Library; import flump.display.Movie; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import starling.display.DisplayObject; import starling.display.Sprite; class Layer { public var keyframeIdx :int ;// The index of the last keyframe drawn in drawFrame public var layerIdx :int;// This layer's index in the movie public var keyframes :Vector.<KeyframeMold>; // Only created if there are multiple items on this layer. If it does exist, the appropriate display is swapped in at keyframe changes. If it doesn't, the display is only added to the parent on layer creation public var displays :Vector.<DisplayObject>;// <SPDisplayObject*> public var movie :Movie; // The movie this layer belongs to // If the keyframe has changed since the last drawFrame public var changedKeyframe :Boolean; public function Layer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) { keyframes = src.keyframes; this.movie = movie; var lastItem :String; for (var ii :int = 0; ii < keyframes.length && lastItem == null; ii++) { lastItem = keyframes[ii].ref; } if (!flipbook && lastItem == null) movie.addChild(new Sprite());// Label only layer else { var multipleItems :Boolean = flipbook; for (ii = 0; ii < keyframes.length && !multipleItems; ii++) { multipleItems = keyframes[ii].ref != lastItem; } if (!multipleItems) movie.addChild(library.createDisplayObject(lastItem)); else { displays = new <DisplayObject>[]; for each (var kf :KeyframeMold in keyframes) { var display :DisplayObject = (kf.ref == null ? new Sprite() : library.createDisplayObject(kf.ref)); displays.push(display); display.name = src.name; } movie.addChild(displays[0]); } } layerIdx = movie.numChildren - 1; movie.getChildAt(layerIdx).name = src.name; } public function drawFrame (frame :int) :void { while (keyframeIdx < keyframes.length - 1 && keyframes[keyframeIdx + 1].index <= frame) { keyframeIdx++; changedKeyframe = true; } // We've got multiple items. Swap in the one for this kf if (changedKeyframe && displays != null) { movie.removeChildAt(layerIdx); movie.addChildAt(displays[keyframeIdx], layerIdx); } changedKeyframe = false; const kf :KeyframeMold = keyframes[keyframeIdx]; const layer :DisplayObject = movie.getChildAt(layerIdx); if (keyframeIdx == keyframes.length - 1 || kf.index == frame) { layer.x = kf.x; layer.y = kf.y; layer.scaleX = kf.scaleX; layer.scaleY = kf.scaleY; layer.skewX = kf.skewX; layer.skewY = kf.skewY; layer.alpha = kf.alpha; } else { var interped :Number = (frame - kf.index)/kf.duration; var ease :Number = kf.ease; if (ease != 0) { var t :Number; if (ease < 0) { // Ease in var inv :Number = 1 - interped; t = 1 - inv*inv; ease = -ease; } else { // Ease out t = interped*interped; } interped = ease*t + (1 - ease)*interped; } const nextKf :KeyframeMold = keyframes[keyframeIdx + 1]; layer.x = kf.x + (nextKf.x - kf.x) * interped; layer.y = kf.y + (nextKf.y - kf.y) * interped; layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped; layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped; layer.skewX = kf.skewX + (nextKf.skewX - kf.skewX) * interped; layer.skewY = kf.skewY + (nextKf.skewY - kf.skewY) * interped; layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped; } layer.pivotX = kf.pivotX; layer.pivotY = kf.pivotY; layer.visible = kf.visible; } }
// // Flump - Copyright 2012 Three Rings Design package flump.display { import flump.mold.MovieMold; import org.osflash.signals.Signal; import starling.animation.IAnimatable; import starling.display.DisplayObject; import starling.display.Sprite; import starling.events.Event; /** * A movie created from flump-exported data. It has children corresponding to the layers in the * movie in Flash, in the same order and with the same names. It fills in those children * initially with the image or movie of the symbol on that exported layer. After the initial * population, it only applies the keyframe-based transformations to the child at the index * corresponding to the layer. This means it's safe to swap in other DisplayObjects at those * positions to have them animated in place of the initial child. * * <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function * is otherwise called). When the movie is added to a juggler, it advances its playhead with the * frame ticks if isPlaying is true. It will automatically remove itself from its juggler when * removed from the stage.</p> * * @see Library and LibraryLoader to create instances of Movie. */ public class Movie extends Sprite implements IAnimatable { /** A label fired by all movies when entering their first frame. */ public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME"; /** A label fired by all movies when entering their last frame. */ public static const LAST_FRAME :String = "flump.movie.LAST_FRAME"; /** Fires the label string whenever it's passed in playing. */ public const labelPassed :Signal = new Signal(String); /** @private */ public function Movie (src :MovieMold, frameRate :Number, library :Library) { name = src.id; _labels = src.labels; _frameRate = frameRate; if (src.flipbook) { _layers = new Vector.<Layer>(1, true); _layers[0] = new Layer(this, src.layers[0], library, /*flipbook=*/true); _frames = src.layers[0].frames; } else { _layers = new Vector.<Layer>(src.layers.length, true); for (var ii :int = 0; ii < _layers.length; ii++) { _layers[ii] = new Layer(this, src.layers[ii], library, /*flipbook=*/false); _frames = Math.max(src.layers[ii].frames, _frames); } } _duration = _frames / _frameRate; updateFrame(0, /*fromSkip=*/true, /*overDuration=*/false); // When we're removed from the stage, remove ourselves from any juggler animating us. addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void { dispatchEventWith(Event.REMOVE_FROM_JUGGLER); }); } /** @return the frame being displayed. */ public function get frame () :int { return _frame; } /** @return the number of frames in the movie. */ public function get frames () :int { return _frames; } /** @return true if the movie is currently playing. */ public function get isPlaying () :Boolean { return _playing; } /** Starts playing if not already doing so, and continues to do so indefinitely. */ public function loop () :Movie { _playing = true; _stopFrame = NO_FRAME; return this; } /** * Moves to the given String label or int frame. Doesn't alter playing status or stop frame. * If there are labels at the given position, they're fired as part of the goto, even if the * current frame is equal to the destination. Labels between the current frame and the * destination frame are not fired. * * @param position the int frame or String label to goto. * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie */ public function goto (position :Object) :Movie { const frame :int = extractFrame(position); updateFrame(frame, /*fromSkip=*/true, /*overDuration=*/false); return this; } /** * Starts playing if not already doing so, and continues to do so to the last frame in the * movie. */ public function play () :Movie { return playTo(LAST_FRAME); } /** * Starts playing if not already doing so, and continues to do so to the given stop label or * frame. * * @param position to int frame or String label to stop at * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie. */ public function playTo (position :Object) :Movie { _stopFrame = extractFrame(position); _playing = true; return this; } /** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */ public function stop () :Movie { _playing = false; return this; } /** Advances the playhead by the give number of seconds. From IAnimatable. */ public function advanceTime (dt :Number) :void { if (!_playing) return; _playTime += dt; var actualPlaytime :Number = _playTime; if (_playTime >= _duration) _playTime = _playTime % _duration; // If _playTime is very close to _duration, rounding error can cause us to // land on lastFrame + 1. Protect against that. var newFrame :int = Math.min(int(_playTime * _frameRate), _frames - 1); const overDuration :Boolean = dt >= _duration; // If the update crosses or goes to the stopFrame, go to the stop frame, stop the movie and // clear it if (_stopFrame != NO_FRAME) { // how many frames remain to the stopframe? var framesRemaining :int = (_frame <= _stopFrame ? _stopFrame - _frame : _frames - _frame + _stopFrame); var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame; if (framesElapsed >= framesRemaining) { _playing = false; newFrame = _stopFrame; _stopFrame = NO_FRAME; } } updateFrame(newFrame, false, overDuration); for (var ii :int = 0; ii < this.numChildren; ++ii) { var child :DisplayObject = getChildAt(ii); if (child is Movie) { Movie(child).advanceTime(dt); } } } /** @private */ protected function extractFrame (position :Object) :int { if (position is int) return int(position); if (!(position is String)) throw new Error("Movie position must be an int frame or String label"); const label :String = String(position); for (var ii :int = 0; ii < _labels.length; ii++) { if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii; } throw new Error("No such label '" + label + "'"); } /** @private */ protected function updateFrame (newFrame :int, fromSkip :Boolean, overDuration :Boolean) :void { if (newFrame >= _frames) { throw new Error("Asked to go to frame " + newFrame + " past the last frame, " + (_frames - 1)); } if (_goingToFrame) { _pendingFrame = newFrame; return; } _goingToFrame = true; const differentFrame :Boolean = newFrame != _frame; const wrapped :Boolean = newFrame < _frame; if (differentFrame) { if (wrapped) { for each (var layer :Layer in _layers) { layer.changedKeyframe = true; layer.keyframeIdx = 0; } } for each (layer in _layers) layer.drawFrame(newFrame); } // Update the frame before firing, so if firing changes the frame, it sticks. const oldFrame :int = _frame; _frame = newFrame; if (fromSkip) { fireLabels(newFrame, newFrame); _playTime = newFrame/_frameRate; } else if (overDuration) { fireLabels(oldFrame + 1, _frames - 1); fireLabels(0, _frame); } else if (differentFrame) { if (wrapped) { fireLabels(oldFrame + 1, _frames - 1); fireLabels(0, _frame); } else fireLabels(oldFrame + 1, _frame); } _goingToFrame = false; if (_pendingFrame != NO_FRAME) { newFrame = _pendingFrame; _pendingFrame = NO_FRAME; updateFrame(newFrame, true, false); } } /** @private */ protected function fireLabels (startFrame :int, endFrame :int) :void { for (var ii :int = startFrame; ii <= endFrame; ii++) { if (_labels[ii] == null) continue; for each (var label :String in _labels[ii]) labelPassed.dispatch(label); } } /** @private */ protected var _goingToFrame :Boolean; /** @private */ protected var _pendingFrame :int = NO_FRAME; /** @private */ protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME; /** @private */ protected var _playing :Boolean = true; /** @private */ protected var _playTime :Number, _duration :Number; /** @private */ protected var _layers :Vector.<Layer>; /** @private */ protected var _frames :int; /** @private */ protected var _frameRate :Number; /** @private */ protected var _labels :Vector.<Vector.<String>>; private static const NO_FRAME :int = -1; } } import flump.display.Library; import flump.display.Movie; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import starling.display.DisplayObject; import starling.display.Sprite; class Layer { public var keyframeIdx :int ;// The index of the last keyframe drawn in drawFrame public var layerIdx :int;// This layer's index in the movie public var keyframes :Vector.<KeyframeMold>; // Only created if there are multiple items on this layer. If it does exist, the appropriate display is swapped in at keyframe changes. If it doesn't, the display is only added to the parent on layer creation public var displays :Vector.<DisplayObject>;// <SPDisplayObject*> public var movie :Movie; // The movie this layer belongs to // If the keyframe has changed since the last drawFrame public var changedKeyframe :Boolean; public function Layer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) { keyframes = src.keyframes; this.movie = movie; var lastItem :String; for (var ii :int = 0; ii < keyframes.length && lastItem == null; ii++) { lastItem = keyframes[ii].ref; } if (!flipbook && lastItem == null) movie.addChild(new Sprite());// Label only layer else { var multipleItems :Boolean = flipbook; for (ii = 0; ii < keyframes.length && !multipleItems; ii++) { multipleItems = keyframes[ii].ref != lastItem; } if (!multipleItems) movie.addChild(library.createDisplayObject(lastItem)); else { displays = new <DisplayObject>[]; for each (var kf :KeyframeMold in keyframes) { var display :DisplayObject = (kf.ref == null ? new Sprite() : library.createDisplayObject(kf.ref)); displays.push(display); display.name = src.name; } movie.addChild(displays[0]); } } layerIdx = movie.numChildren - 1; movie.getChildAt(layerIdx).name = src.name; } public function drawFrame (frame :int) :void { while (keyframeIdx < keyframes.length - 1 && keyframes[keyframeIdx + 1].index <= frame) { keyframeIdx++; changedKeyframe = true; } // We've got multiple items. Swap in the one for this kf if (changedKeyframe && displays != null) { movie.removeChildAt(layerIdx); movie.addChildAt(displays[keyframeIdx], layerIdx); } changedKeyframe = false; const kf :KeyframeMold = keyframes[keyframeIdx]; const layer :DisplayObject = movie.getChildAt(layerIdx); if (keyframeIdx == keyframes.length - 1 || kf.index == frame) { layer.x = kf.x; layer.y = kf.y; layer.scaleX = kf.scaleX; layer.scaleY = kf.scaleY; layer.skewX = kf.skewX; layer.skewY = kf.skewY; layer.alpha = kf.alpha; } else { var interped :Number = (frame - kf.index)/kf.duration; var ease :Number = kf.ease; if (ease != 0) { var t :Number; if (ease < 0) { // Ease in var inv :Number = 1 - interped; t = 1 - inv*inv; ease = -ease; } else { // Ease out t = interped*interped; } interped = ease*t + (1 - ease)*interped; } const nextKf :KeyframeMold = keyframes[keyframeIdx + 1]; layer.x = kf.x + (nextKf.x - kf.x) * interped; layer.y = kf.y + (nextKf.y - kf.y) * interped; layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped; layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped; layer.skewX = kf.skewX + (nextKf.skewX - kf.skewX) * interped; layer.skewY = kf.skewY + (nextKf.skewY - kf.skewY) * interped; layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped; } layer.pivotX = kf.pivotX; layer.pivotY = kf.pivotY; layer.visible = kf.visible; } }
Fix movies occasionally landing on lastFrame + 1
Fix movies occasionally landing on lastFrame + 1
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump
3be8caeccad8ce5338a043ac9db31f7d22cb3402
src/as/com/threerings/util/Enum.as
src/as/com/threerings/util/Enum.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.utils.Dictionary; /** * Base enum class for actionscript. Works pretty much like enums in Java, only you've got * to do one or two things. * * To use, you'll want to subclass and have something like the following: * * public final class Foo extends Enum * { * public static const ONE = new Foo("ONE"); * public static const TWO = new Foo("TWO"); * finishedEnumerating(Foo); * * // {at}private * public function Foo (name :String) * { * super(name); * } * * public static function valueOf (name :String) :Foo * { * return Enum.valueOf(Foo, name); * } * * public static function values () :Array * { * return Enum.values(Foo); * } * } * * Important notes: * - make your class final * - create a constructor that merely calls super * - declare your enum constants const, and with the same String as their name. * - call finishedEnumerating() at the end of your constants. * - your enum objects should be immutable * - implement a static valueOf() and values() methods for extra points, as above. */ public class Enum implements Hashable, Comparable { /** * Call this constructor in your enum subclass constructor. */ public function Enum (name :String) { const clazz :Class = ClassUtil.getClass(this); if (Boolean(_blocked[clazz])) { throw new Error("You may not just construct an enum!"); } else if (name == null) { throw new ArgumentError("null is invalid."); } var list :Array = _enums[clazz] as Array; if (list == null) { list = []; _enums[clazz] = list; } else { for each (var enum :Enum in list) { if (enum.name() === name) { throw new ArgumentError("Duplicate enum: " + name); } } } list.push(this); // now, actually construct _name = name; } /** * Get the name of this enum. */ public function name () :String { return _name; } /** * Get the ordinal of this enum. * Note that you should not use the ordinal in normal cases, as it may change if a new * enum is defined. Ordinals should only be used if you are writing a data structure * that generically handles enums in an efficient manner, and you are never persisting * anything where the ordinal can change. */ public function ordinal () :int { return (_enums[ClassUtil.getClass(this)] as Array).indexOf(this); } // from Hashable public function equals (other :Object) :Boolean { // enums are singleton return (other === this); } // from Hashable public function hashCode () :int { return ordinal(); } /** * Return the String representation of this enum. */ public function toString () :String { return _name; } // from Comparable public function compareTo (other :Object) :int { if (!ClassUtil.isSameClass(this, other)) { throw new ArgumentError("Not same class"); } return Integer.compare(this.ordinal(), Enum(other).ordinal()); } /** * Turn a String name into an Enum constant. */ public static function valueOf (clazz :Class, name :String) :Enum { for each (var enum :Enum in values(clazz)) { if (enum.name() === name) { return enum; } } throw new ArgumentError("No such enum [class=" + clazz + ", name=" + name + "]."); } /** * Get all the enums of the specified class, or null if it's not an enum. */ public static function values (clazz :Class) :Array { var arr :Array = _enums[clazz] as Array; if (arr == null) { throw new ArgumentError("Not an enum [class=" + clazz + "]."); } return arr.concat(); // return a copy, so that callers may not fuxor } /** * This should be called by your enum subclass after you've finished enumating the enum * constants. See the example in the class header documentation. */ protected static function finishedEnumerating (clazz :Class) :void { _blocked[clazz] = true; } /** The String name of this enum value. */ protected var _name :String; /** An array of enums for each enum class. */ private static const _enums :Dictionary = new Dictionary(true); /** Is further instantiation of enum constants for a class allowed? */ private static const _blocked :Dictionary = new Dictionary(true); finishedEnumerating(Enum); // do not allow any enums in this base class } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.utils.Dictionary; /** * Base enum class for actionscript. Works pretty much like enums in Java, only you've got * to do one or two things. * * To use, you'll want to subclass and have something like the following: * * public final class Foo extends Enum * { * public static const ONE = new Foo("ONE"); * public static const TWO = new Foo("TWO"); * finishedEnumerating(Foo); * * // {at}private * public function Foo (name :String) * { * super(name); * } * * public static function valueOf (name :String) :Foo * { * return Enum.valueOf(Foo, name); * } * * public static function values () :Array * { * return Enum.values(Foo); * } * } * * Important notes: * - make your class final * - create a constructor that calls super(name) * - declare your enum constants const, and with the same String as their name. * - call finishedEnumerating() at the end of your constants. * - your enum objects should be immutable * - implement a static valueOf() and values() methods for extra points, as above. */ public class Enum implements Hashable, Comparable { /** * Call this constructor in your enum subclass constructor. */ public function Enum (name :String) { const clazz :Class = ClassUtil.getClass(this); if (Boolean(_blocked[clazz])) { throw new Error("You may not just construct an enum!"); } else if (name == null) { throw new ArgumentError("null is invalid."); } var list :Array = _enums[clazz] as Array; if (list == null) { list = []; _enums[clazz] = list; } else { for each (var enum :Enum in list) { if (enum.name() === name) { throw new ArgumentError("Duplicate enum: " + name); } } } list.push(this); // now, actually construct _name = name; } /** * Get the name of this enum. */ public function name () :String { return _name; } /** * Get the ordinal of this enum. * Note that you should not use the ordinal in normal cases, as it may change if a new * enum is defined. Ordinals should only be used if you are writing a data structure * that generically handles enums in an efficient manner, and you are never persisting * anything where the ordinal can change. */ public function ordinal () :int { return (_enums[ClassUtil.getClass(this)] as Array).indexOf(this); } // from Hashable public function equals (other :Object) :Boolean { // enums are singleton return (other === this); } // from Hashable public function hashCode () :int { return ordinal(); } /** * Return the String representation of this enum. */ public function toString () :String { return _name; } // from Comparable public function compareTo (other :Object) :int { if (!ClassUtil.isSameClass(this, other)) { throw new ArgumentError("Not same class"); } return Integer.compare(this.ordinal(), Enum(other).ordinal()); } /** * Turn a String name into an Enum constant. */ public static function valueOf (clazz :Class, name :String) :Enum { for each (var enum :Enum in values(clazz)) { if (enum.name() === name) { return enum; } } throw new ArgumentError("No such enum [class=" + clazz + ", name=" + name + "]."); } /** * Get all the enums of the specified class, or null if it's not an enum. */ public static function values (clazz :Class) :Array { var arr :Array = _enums[clazz] as Array; if (arr == null) { throw new ArgumentError("Not an enum [class=" + clazz + "]."); } return arr.concat(); // return a copy, so that callers may not fuxor } /** * This should be called by your enum subclass after you've finished enumating the enum * constants. See the example in the class header documentation. */ protected static function finishedEnumerating (clazz :Class) :void { _blocked[clazz] = true; } /** The String name of this enum value. */ protected var _name :String; /** An array of enums for each enum class. */ private static const _enums :Dictionary = new Dictionary(true); /** Is further instantiation of enum constants for a class allowed? */ private static const _blocked :Dictionary = new Dictionary(true); finishedEnumerating(Enum); // do not allow any enums in this base class } }
Comment tweak.
Comment tweak. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5366 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
986edd94733da4417f1a7bc9f4e7b79788f7aefb
src/org/mangui/osmf/plugins/utils/ErrorManager.as
src/org/mangui/osmf/plugins/utils/ErrorManager.as
package org.mangui.osmf.plugins.utils { import org.mangui.hls.HLSError; import org.mangui.hls.HLSEvent; import org.osmf.events.MediaErrorCodes; public class ErrorManager { public static function getMediaErrorCode(event : HLSEvent) : int { var errorCode : int = MediaErrorCodes.NETSTREAM_PLAY_FAILED; if (event && event.error) { switch (event.error.code) { case HLSError.FRAGMENT_LOADING_ERROR: case HLSError.FRAGMENT_LOADING_CROSSDOMAIN_ERROR: case HLSError.KEY_LOADING_ERROR: case HLSError.KEY_LOADING_CROSSDOMAIN_ERROR: case HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR: case HLSError.MANIFEST_LOADING_IO_ERROR: errorCode = MediaErrorCodes.IO_ERROR; break; case org.mangui.hls.HLSError.FRAGMENT_PARSING_ERROR: case org.mangui.hls.HLSError.KEY_PARSING_ERROR: case org.mangui.hls.HLSError.MANIFEST_PARSING_ERROR: errorCode = MediaErrorCodes.NETSTREAM_FILE_STRUCTURE_INVALID; break; case org.mangui.hls.HLSError.TAG_APPENDING_ERROR: errorCode = MediaErrorCodes.ARGUMENT_ERROR; break; } } return errorCode; }; public static function getMediaErrorMessage(event : HLSEvent) : String { return (event && event.error) ? event.error.msg : "Unknown error"; }; }; }
Create ErrorManager util to get MediaErrorCode & MediaErrorMessage
Create ErrorManager util to get MediaErrorCode & MediaErrorMessage
ActionScript
mpl-2.0
hola/flashls,thdtjsdn/flashls,mangui/flashls,School-Improvement-Network/flashls,suuhas/flashls,clappr/flashls,vidible/vdb-flashls,aevange/flashls,stevemayhew/flashls,tedconf/flashls,tedconf/flashls,fixedmachine/flashls,codex-corp/flashls,Boxie5/flashls,stevemayhew/flashls,ryanhefner/flashls,loungelogic/flashls,JulianPena/flashls,Peer5/flashls,viktorot/flashls,stevemayhew/flashls,Peer5/flashls,Corey600/flashls,NicolasSiver/flashls,School-Improvement-Network/flashls,ryanhefner/flashls,Peer5/flashls,jlacivita/flashls,aevange/flashls,suuhas/flashls,dighan/flashls,hola/flashls,Corey600/flashls,School-Improvement-Network/flashls,codex-corp/flashls,neilrackett/flashls,fixedmachine/flashls,thdtjsdn/flashls,viktorot/flashls,Peer5/flashls,dighan/flashls,loungelogic/flashls,ryanhefner/flashls,Boxie5/flashls,suuhas/flashls,neilrackett/flashls,vidible/vdb-flashls,stevemayhew/flashls,aevange/flashls,ryanhefner/flashls,aevange/flashls,jlacivita/flashls,suuhas/flashls,clappr/flashls,NicolasSiver/flashls,JulianPena/flashls,viktorot/flashls,mangui/flashls
5bd39479e88181b633ff35aebda40577241aa884
test/acceptance/ecma3/Function/apply_001.as
test/acceptance/ecma3/Function/apply_001.as
/* -*- Mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var SECTION = "apply_001"; var VERSION = ""; startTest(); var TITLE = "Function.prototype.apply with very long argument lists"; writeHeaderToLog( SECTION + " "+ TITLE); var testcases = getTestCases(); test(); function getTestCases() { var array = new Array(); var initial = 1000; var limit = 10000000; var multiplier = 10; function makeArray(n) { var A = new Array; for ( var i=0 ; i < n ; i++ ) A[i] = i+1; return A; } function sum(...rest) { var n = 0; for ( var i=0 ; i < rest.length ; i++ ) n += rest[i]; return n; } for ( var i=initial ; i < limit ; i *= multiplier ) { status = 'Test apply(bigarray) #' + i; actual = sum.apply(null, makeArray(i)); expect = (i*(i+1))/2; array.push(new TestCase(SECTION, status, expect, actual)); } return array; }
Fix 551959 - Need huge test case for Function.apply (r=treilly, r=brbaker)
Fix 551959 - Need huge test case for Function.apply (r=treilly, r=brbaker)
ActionScript
mpl-2.0
pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux
6bf481b22e5d91b12a824c32ba74349d4579b0a8
src/main/org/shypl/common/util/UintComparator.as
src/main/org/shypl/common/util/UintComparator.as
package org.shypl.common.util { public class UintComparator extends SimpleComparator { private static var LOW_TO_HIGH:UintComparator; private static var HIGH_TO_LOW:UintComparator; public static function getInstance(reverse:Boolean = false):Comparator { if (reverse) { if (HIGH_TO_LOW === null) { HIGH_TO_LOW = new UintComparator(true); } return HIGH_TO_LOW; } if (LOW_TO_HIGH === null) { LOW_TO_HIGH = new UintComparator(false); } return LOW_TO_HIGH; } public function UintComparator(reverse:Boolean) { super(reverse); } override protected function isGreater(a:Object, b:Object):Boolean { return uint(a) > uint(b); } } }
Add UintComparator
Add UintComparator
ActionScript
apache-2.0
shypl/common-flash
e699e33107ad8764369b0ce8a07edfcb0dec3cfb
src/org/mangui/hls/HLSSettings.as
src/org/mangui/hls/HLSSettings.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls { import org.mangui.hls.constant.HLSSeekMode; import org.mangui.hls.constant.HLSMaxLevelCappingMode; public final class HLSSettings extends Object { /** * autoStartLoad * * if set to true, * start level playlist and first fragments will be loaded automatically, * after triggering of HlsEvent.MANIFEST_PARSED event * if set to false, * an explicit API call (hls.startLoad()) will be needed * to start quality level/fragment loading. * * Default is true */ public static var autoStartLoad : Boolean = true; /** * capLevelToStage * * Limit levels usable in auto-quality by the stage dimensions (width and height). * true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight). * Max level will be set depending on the maxLevelCappingMode option. * false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelToStage : Boolean = false; /** * maxLevelCappingMode * * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode * HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled) * HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled) * * Default is HLSMaxLevelCappingMode.DOWNSCALE */ public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE; // // // // // // ///////////////////////////////// // // org.mangui.hls.stream.HLSNetStream // // // // // // // ///////////////////////////////// /** * minBufferLength * * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling. * * Default is -1 = auto */ public static var minBufferLength : Number = -1; /** * minBufferLengthCapping * * Defines minimum buffer length capping value (max value) if minBufferLength is set to -1 * * Default is -1 = no capping */ public static var minBufferLengthCapping : Number = -1; /** * maxBufferLength * * Defines maximum buffer length in seconds. * (0 means infinite buffering) * * Default is 120 */ public static var maxBufferLength : Number = 120; /** * maxBackBufferLength * * Defines maximum back buffer length in seconds. * (0 means infinite back buffering) * * Default is 30 */ public static var maxBackBufferLength : Number = 30; /** * lowBufferLength * * Defines low buffer length in seconds. * When crossing down this threshold, HLS will switch to buffering state. * * Default is 3 */ public static var lowBufferLength : Number = 3; /** * mediaTimeUpdatePeriod * * time update period in ms * period at which HLSEvent.MEDIA_TIME will be triggered * Default is 100 ms */ public static var mediaTimePeriod : int = 100; /** * fpsDroppedMonitoringPeriod * * dropped FPS Monitor Period in ms * period at which nb dropped FPS will be checked * Default is 5000 ms */ public static var fpsDroppedMonitoringPeriod : int = 5000; /** * fpsDroppedMonitoringThreshold * * dropped FPS Threshold * every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS. * if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal * than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired * Default is 0.2 (20%) */ public static var fpsDroppedMonitoringThreshold : Number = 0.2; /** * capLevelonFPSDrop * * Limit levels usable in auto-quality when FPS drop is detected * i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a * true - enabled * false - disabled * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelonFPSDrop : Boolean = false; /** * smoothAutoSwitchonFPSDrop * * force a smooth level switch Limit when FPS drop is detected in auto-quality * i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch * to level 4 for next fragment * true - enabled * false - disabled * * Note: this setting is active only if capLevelonFPSDrop==true * * Default is true */ public static var smoothAutoSwitchonFPSDrop : Boolean = true; /** * switchDownOnLevelError * * if level loading fails, and if in auto mode, and we are not on lowest level * don't report Level loading error straight-away, try to switch down first * true - enabled * false - disabled * * Default is true */ public static var switchDownOnLevelError : Boolean = true; /** * seekMode * * Defines seek mode to one form available in HLSSeekMode class: * HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position * HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position) * * Default is HLSSeekMode.KEYFRAME_SEEK */ public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK; /** * keyLoadMaxRetry * * Max nb of retries for Key Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var keyLoadMaxRetry : int = 3; /** * keyLoadMaxRetryTimeout * * Maximum key retry timeout (in milliseconds) in case I/O errors are met. * Every fail on key request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var keyLoadMaxRetryTimeout : Number = 64000; /** * fragmentLoadMaxRetry * * Max number of retries for Fragment Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var fragmentLoadMaxRetry : int = 3; /** * fragmentLoadMaxRetryTimeout * * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached. * * Default is 4000 */ public static var fragmentLoadMaxRetryTimeout : Number = 4000; /** * fragmentLoadSkipAfterMaxRetry * * control behaviour in case fragment load still fails after max retry timeout * if set to true, fragment will be skipped and next one will be loaded. * If set to false, an I/O Error will be raised. * * Default is true. */ public static var fragmentLoadSkipAfterMaxRetry : Boolean = true; /** * flushLiveURLCache * * If set to true, live playlist will be flushed from URL cache before reloading * (this is to workaround some cache issues with some combination of Flash Player / IE version) * * Default is false */ public static var flushLiveURLCache : Boolean = false; /** * initialLiveManifestSize * * Number of segments needed to start playback of Live stream. * * Default is 1 */ public static var initialLiveManifestSize : uint = 1; /** * manifestLoadMaxRetry * * max nb of retries for Manifest Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var manifestLoadMaxRetry : int = 3; /** * manifestLoadMaxRetryTimeout * * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached. * * Default is 64000 */ public static var manifestLoadMaxRetryTimeout : Number = 64000; /** * manifestRedundantLoadmaxRetry * * max nb of looping over the redundant streams. * >0 means looping over the stream array 2 or more times * 0 means looping exactly once (no retries) - default behaviour * -1 means infinite retry */ public static var manifestRedundantLoadmaxRetry : int = 3; /** * startFromBitrate * * If greater than 0, specifies the preferred bitrate. * If -1, and startFromLevel is not specified, automatic start level selection will be used. * This parameter, if set, will take priority over startFromLevel. * * Default is -1 */ public static var startFromBitrate : Number = -1; /** * startFromLevel * * start level : * from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate) * * Default is -1 */ public static var startFromLevel : Number = -1; /** * autoStartMaxDuration * * max fragment loading duration in automatic start level selection mode (in ms) * -1 : max duration not capped * other : max duration is capped to avoid long playback starting time * * Default is -1 */ public static var autoStartMaxDuration : Number = -1; /** * seekFromLevel * * Seek level: * from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, keep previous level matching previous download bandwidth * * Default is -1 */ public static var seekFromLevel : Number = -1; /** * useHardwareVideoDecoder * * Use hardware video decoder: * it will set NetStream.useHardwareDecoder * refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder * * Default is true */ public static var useHardwareVideoDecoder : Boolean = true; /** * logInfo * * Defines whether INFO level log messages will will appear in the console * * Default is true */ public static var logInfo : Boolean = true; /** * logDebug * * Defines whether DEBUG level log messages will will appear in the console * * Default is false */ public static var logDebug : Boolean = false; /** * logDebug2 * * Defines whether DEBUG2 level log messages will will appear in the console * * Default is false */ public static var logDebug2 : Boolean = false; /** * logWarn * * Defines whether WARN level log messages will will appear in the console * * Default is true */ public static var logWarn : Boolean = true; /** * logError * * Defines whether ERROR level log messages will will appear in the console * * Default is true */ public static var logError : Boolean = true; } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls { import org.mangui.hls.constant.HLSSeekMode; import org.mangui.hls.constant.HLSMaxLevelCappingMode; public final class HLSSettings extends Object { /** * autoStartLoad * * if set to true, * start level playlist and first fragments will be loaded automatically, * after triggering of HlsEvent.MANIFEST_PARSED event * if set to false, * an explicit API call (hls.startLoad()) will be needed * to start quality level/fragment loading. * * Default is true */ public static var autoStartLoad : Boolean = true; /** * capLevelToStage * * Limit levels usable in auto-quality by the stage dimensions (width and height). * true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight). * Max level will be set depending on the maxLevelCappingMode option. * false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelToStage : Boolean = false; /** * maxLevelCappingMode * * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode * HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled) * HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled) * * Default is HLSMaxLevelCappingMode.DOWNSCALE */ public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE; // // // // // // ///////////////////////////////// // // org.mangui.hls.stream.HLSNetStream // // // // // // // ///////////////////////////////// /** * minBufferLength * * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling. * * Default is -1 = auto */ public static var minBufferLength : Number = -1; /** * minBufferLengthCapping * * Defines minimum buffer length capping value (max value) if minBufferLength is set to -1 * * Default is -1 = no capping */ public static var minBufferLengthCapping : Number = -1; /** * maxBufferLength * * Defines maximum buffer length in seconds. * (0 means infinite buffering) * * Default is 120 */ public static var maxBufferLength : Number = 120; /** * maxBackBufferLength * * Defines maximum back buffer length in seconds. * (0 means infinite back buffering) * * Default is 30 */ public static var maxBackBufferLength : Number = 30; /** * lowBufferLength * * Defines low buffer length in seconds. * When crossing down this threshold, HLS will switch to buffering state. * * Default is 3 */ public static var lowBufferLength : Number = 3; /** * mediaTimeUpdatePeriod * * time update period in ms * period at which HLSEvent.MEDIA_TIME will be triggered * Default is 100 ms */ public static var mediaTimePeriod : int = 100; /** * fpsDroppedMonitoringPeriod * * dropped FPS Monitor Period in ms * period at which nb dropped FPS will be checked * Default is 5000 ms */ public static var fpsDroppedMonitoringPeriod : int = 5000; /** * fpsDroppedMonitoringThreshold * * dropped FPS Threshold * every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS. * if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal * than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired * Default is 0.2 (20%) */ public static var fpsDroppedMonitoringThreshold : Number = 0.2; /** * capLevelonFPSDrop * * Limit levels usable in auto-quality when FPS drop is detected * i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a * true - enabled * false - disabled * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelonFPSDrop : Boolean = false; /** * smoothAutoSwitchonFPSDrop * * force a smooth level switch Limit when FPS drop is detected in auto-quality * i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch * to level 4 for next fragment * true - enabled * false - disabled * * Note: this setting is active only if capLevelonFPSDrop==true * * Default is true */ public static var smoothAutoSwitchonFPSDrop : Boolean = true; /** * switchDownOnLevelError * * if level loading fails, and if in auto mode, and we are not on lowest level * don't report Level loading error straight-away, try to switch down first * true - enabled * false - disabled * * Default is true */ public static var switchDownOnLevelError : Boolean = true; /** * seekMode * * Defines seek mode to one form available in HLSSeekMode class: * HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position * HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position) * * Default is HLSSeekMode.KEYFRAME_SEEK */ public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK; /** * keyLoadMaxRetry * * Max nb of retries for Key Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var keyLoadMaxRetry : int = 3; /** * keyLoadMaxRetryTimeout * * Maximum key retry timeout (in milliseconds) in case I/O errors are met. * Every fail on key request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var keyLoadMaxRetryTimeout : Number = 64000; /** * fragmentLoadMaxRetry * * Max number of retries for Fragment Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var fragmentLoadMaxRetry : int = 3; /** * fragmentLoadMaxRetryTimeout * * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached. * * Default is 4000 */ public static var fragmentLoadMaxRetryTimeout : Number = 4000; /** * fragmentLoadSkipAfterMaxRetry * * control behaviour in case fragment load still fails after max retry timeout * if set to true, fragment will be skipped and next one will be loaded. * If set to false, an I/O Error will be raised. * * Default is true. */ public static var fragmentLoadSkipAfterMaxRetry : Boolean = true; /** * maxSkippedFragments * * Maximum count of skipped fragments in a row before an I/O Error will be raised. * 0 - no skip (same as fragmentLoadSkipAfterMaxRetry = false) * -1 - no limit for skipping, skip till the end of the playlist * * Default is 5. */ public static var maxSkippedFragments : int = 5; /** * flushLiveURLCache * * If set to true, live playlist will be flushed from URL cache before reloading * (this is to workaround some cache issues with some combination of Flash Player / IE version) * * Default is false */ public static var flushLiveURLCache : Boolean = false; /** * initialLiveManifestSize * * Number of segments needed to start playback of Live stream. * * Default is 1 */ public static var initialLiveManifestSize : uint = 1; /** * manifestLoadMaxRetry * * max nb of retries for Manifest Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var manifestLoadMaxRetry : int = 3; /** * manifestLoadMaxRetryTimeout * * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached. * * Default is 64000 */ public static var manifestLoadMaxRetryTimeout : Number = 64000; /** * manifestRedundantLoadmaxRetry * * max nb of looping over the redundant streams. * >0 means looping over the stream array 2 or more times * 0 means looping exactly once (no retries) - default behaviour * -1 means infinite retry */ public static var manifestRedundantLoadmaxRetry : int = 3; /** * startFromBitrate * * If greater than 0, specifies the preferred bitrate. * If -1, and startFromLevel is not specified, automatic start level selection will be used. * This parameter, if set, will take priority over startFromLevel. * * Default is -1 */ public static var startFromBitrate : Number = -1; /** * startFromLevel * * start level : * from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate) * * Default is -1 */ public static var startFromLevel : Number = -1; /** * autoStartMaxDuration * * max fragment loading duration in automatic start level selection mode (in ms) * -1 : max duration not capped * other : max duration is capped to avoid long playback starting time * * Default is -1 */ public static var autoStartMaxDuration : Number = -1; /** * seekFromLevel * * Seek level: * from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, keep previous level matching previous download bandwidth * * Default is -1 */ public static var seekFromLevel : Number = -1; /** * useHardwareVideoDecoder * * Use hardware video decoder: * it will set NetStream.useHardwareDecoder * refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder * * Default is true */ public static var useHardwareVideoDecoder : Boolean = true; /** * logInfo * * Defines whether INFO level log messages will will appear in the console * * Default is true */ public static var logInfo : Boolean = true; /** * logDebug * * Defines whether DEBUG level log messages will will appear in the console * * Default is false */ public static var logDebug : Boolean = false; /** * logDebug2 * * Defines whether DEBUG2 level log messages will will appear in the console * * Default is false */ public static var logDebug2 : Boolean = false; /** * logWarn * * Defines whether WARN level log messages will will appear in the console * * Default is true */ public static var logWarn : Boolean = true; /** * logError * * Defines whether ERROR level log messages will will appear in the console * * Default is true */ public static var logError : Boolean = true; } }
Introduce maxSkippedFragments setting
Introduce maxSkippedFragments setting
ActionScript
mpl-2.0
jlacivita/flashls,NicolasSiver/flashls,fixedmachine/flashls,hola/flashls,neilrackett/flashls,fixedmachine/flashls,hola/flashls,vidible/vdb-flashls,clappr/flashls,NicolasSiver/flashls,jlacivita/flashls,clappr/flashls,tedconf/flashls,vidible/vdb-flashls,mangui/flashls,mangui/flashls,tedconf/flashls,neilrackett/flashls
37905ca39cb02c3de82fce0f8562fefdc7a83e19
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CallLaterBead.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CallLaterBead.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.display.DisplayObject; import flash.events.Event; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; /** * The CallLater bead implements ways for * a method to be called after other code has * finished running. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class CallLaterBead implements IBead { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function CallLaterBead() { super(); } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; } private var calls:Array; /** * Calls a function after some amount of time. * * CallLater works a bit differently than in * the Flex SDK. The Flex SDK version was * could use the Flash Player's RENDER event * to try to run code before the scren was * updated. Since there is no deferred rendering * in HTML/JS/CSS, this version of callLater * is almost always going to run after the * screen is updated. * * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function callLater(fn:Function, args:Array = null, thisArg:Object = null):void { DisplayObject(_strand).addEventListener(Event.ENTER_FRAME, enterFrameHandler); if (calls == null) calls = [ {thisArg: thisArg, fn: fn, args: args } ]; else calls.push({thisArg: thisArg, fn: fn, args: args }); } private function enterFrameHandler(event:Event):void { DisplayObject(_strand).removeEventListener(Event.ENTER_FRAME, enterFrameHandler); var list:Array = calls; var n:int = list.length; for (var i:int = 0; i < n; i++) { var call:Object = list.shift(); var fn:Function = call.fn; fn.apply(call.thisArg, call.args); } } } }
add a CallLaterBead
add a CallLaterBead
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
e459910d51eb1fc4f00b5de23563075e45ac8c1e
src/Library.as
src/Library.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package { import flash.display.Sprite; /** * The basic framework Library to be included in the SWC. * <p> * <b>Note:</b> This class is not a component, it is just * a shim that allow to declare the SWC manifest and associate an icon file. * </p> */ [ExcludeClass] [IconFile("gaforflash.png")] public class Library extends Sprite { public function Library() { } } }
add Library file to build the SWC, this file replace ALL the classes defined in com.google.analytics.components.*
add Library file to build the SWC, this file replace ALL the classes defined in com.google.analytics.components.*
ActionScript
apache-2.0
nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash
afe0ec129b581ac6d1fc693226c997ae23d30a23
frameworks/as/src/org/apache/flex/html/staticControls/beads/SolidBackgroundBead.as
frameworks/as/src/org/apache/flex/html/staticControls/beads/SolidBackgroundBead.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.staticControls.beads { import flash.display.Graphics; import flash.events.Event; import flash.events.IEventDispatcher; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.UIBase; public class SolidBackgroundBead implements IBead { public function SolidBackgroundBead() { } private var _strand:IStrand; public function get strand():IStrand { return _strand; } public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("heightChanged", changeHandler); IEventDispatcher(value).addEventListener("widthChanged", changeHandler); } private var _backgroundColor:uint; public function get backgroundColor():uint { return _backgroundColor; } public function set backgroundColor(value:uint):void { _backgroundColor = value; if (_strand) changeHandler(null); } private function changeHandler(event:Event):void { var host:UIBase = UIBase(_strand); var g:Graphics = host.graphics; var w:Number = host.width; var h:Number = host.height; g.clear(); g.beginFill(backgroundColor); g.drawRect(0, 0, w, h); g.endFill(); } } }
Add bead to draw solid background
Add bead to draw solid background
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
24dbe3a0f83607094cc3c81ccde89bffd88d3554
dolly-framework/src/main/actionscript/dolly/core/errors/CloningError.as
dolly-framework/src/main/actionscript/dolly/core/errors/CloningError.as
package dolly.core.errors { public class CloningError extends Error { public static const CLASS_IS_NOT_CLONEABLE_CODE:int = 1; public static const CLASS_IS_NOT_CLONEABLE_MESSAGE:String = "Class is not cloneable!"; public function CloningError(message:* = "", id:* = 0) { super(message, id); } } }
Create new error class: CloningError.
Create new error class: CloningError.
ActionScript
mit
Yarovoy/dolly
2b08e0cde92aea6d5ce28cecdd811600a6c7f003
src/flash/utils/ObjectInput.as
src/flash/utils/ObjectInput.as
/* * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flash.utils { [native(cls='ObjectInputClass')] internal class ObjectInput implements IDataInput { public native function get bytesAvailable(): uint; public native function get objectEncoding(): uint; public native function set objectEncoding(version: uint): void; public native function get endian(): String; public native function set endian(type: String): void; public native function readBytes(bytes: ByteArray, offset: uint = 0, length: uint = 0): void; public native function readBoolean(): Boolean; public native function readByte(): int; public native function readUnsignedByte(): uint; public native function readShort(): int; public native function readUnsignedShort(): uint; public native function readInt(): int; public native function readUnsignedInt(): uint; public native function readFloat(): Number; public native function readDouble(): Number; public native function readMultiByte(length: uint, charSet: String): String; public native function readUTF(): String; public native function readUTFBytes(length: uint): String; public native function readObject(): *; } }
Add missing builtin flash.utils.ObjectInput
Add missing builtin flash.utils.ObjectInput
ActionScript
apache-2.0
tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway
847c3cc47347f7c83290f163e8d86f69432a721b
tests/examplefiles/as3_test.as
tests/examplefiles/as3_test.as
import flash.events.MouseEvent; import com.example.programmingas3.playlist.PlayList; import com.example.programmingas3.playlist.Song; import com.example.programmingas3.playlist.SortProperty; // constants for the different "states" of the song form private static const ADD_SONG:uint = 1; private static const SONG_DETAIL:uint = 2; private var playList:PlayList = new PlayList(); private function initApp():void { // set the initial state of the song form, for adding a new song setFormState(ADD_SONG); // prepopulate the list with a few songs playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"])); playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"])); playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"])); playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"])); songList.dataProvider = playList.songList; } private function sortList(sortField:SortProperty):void { // Make all the sort type buttons enabled. // The active one will be grayed-out below sortByTitle.selected = false; sortByArtist.selected = false; sortByYear.selected = false; switch (sortField) { case SortProperty.TITLE: sortByTitle.selected = true; break; case SortProperty.ARTIST: sortByArtist.selected = true; break; case SortProperty.YEAR: sortByYear.selected = true; break; } playList.sortList(sortField); refreshList(); } private function refreshList():void { // remember which song was selected var selectedSong:Song = Song(songList.selectedItem); // re-assign the song list as the dataprovider to get the newly sorted list // and force the List control to refresh itself songList.dataProvider = playList.songList; // reset the song selection if (selectedSong != null) { songList.selectedItem = selectedSong; } } private function songSelectionChange():void { if (songList.selectedIndex != -1) { setFormState(SONG_DETAIL); } else { setFormState(ADD_SONG); } } private function addNewSong():void { // gather the values from the form and add the new song var title:String = newSongTitle.text; var artist:String = newSongArtist.text; var year:uint = newSongYear.value; var filename:String = newSongFilename.text; var genres:Array = newSongGenres.selectedItems; playList.addSong(new Song(title, artist, year, filename, genres)); refreshList(); // clear out the "add song" form fields setFormState(ADD_SONG); } private function songListLabel(item:Object):String { return item.toString(); } private function setFormState(state:uint):void { // set the form title and control state switch (state) { case ADD_SONG: formTitle.text = "Add New Song"; // show the submit button submitSongData.visible = true; showAddControlsBtn.visible = false; // clear the form fields newSongTitle.text = ""; newSongArtist.text = ""; newSongYear.value = (new Date()).fullYear; newSongFilename.text = ""; newSongGenres.selectedIndex = -1; // deselect the currently selected song (if any) songList.selectedIndex = -1; break; case SONG_DETAIL: formTitle.text = "Song Details"; // populate the form with the selected item's data var selectedSong:Song = Song(songList.selectedItem); newSongTitle.text = selectedSong.title; newSongArtist.text = selectedSong.artist; newSongYear.value = selectedSong.year; newSongFilename.text = selectedSong.filename; newSongGenres.selectedItems = selectedSong.genres; // hide the submit button submitSongData.visible = false; showAddControlsBtn.visible = true; break; } }
Add AS3 example.
Add AS3 example. --HG-- branch : trunk
ActionScript
bsd-2-clause
nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments,nex3/pygments
91ef8b82ab09fe1eef40a1b3ef4f5e8ce897980d
tests/examplefiles/as3_test.as
tests/examplefiles/as3_test.as
import flash.events.MouseEvent; import com.example.programmingas3.playlist.PlayList; import com.example.programmingas3.playlist.Song; import com.example.programmingas3.playlist.SortProperty; // constants for the different "states" of the song form private static const ADD_SONG:uint = 1; private static const SONG_DETAIL:uint = 2; private var playList:PlayList = new PlayList(); private function initApp():void { // set the initial state of the song form, for adding a new song setFormState(ADD_SONG); // prepopulate the list with a few songs playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"])); playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"])); playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"])); playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"])); songList.dataProvider = playList.songList; } private function sortList(sortField:SortProperty):void { // Make all the sort type buttons enabled. // The active one will be grayed-out below sortByTitle.selected = false; sortByArtist.selected = false; sortByYear.selected = false; switch (sortField) { case SortProperty.TITLE: sortByTitle.selected = true; break; case SortProperty.ARTIST: sortByArtist.selected = true; break; case SortProperty.YEAR: sortByYear.selected = true; break; } playList.sortList(sortField); refreshList(); } private function refreshList():void { // remember which song was selected var selectedSong:Song = Song(songList.selectedItem); // re-assign the song list as the dataprovider to get the newly sorted list // and force the List control to refresh itself songList.dataProvider = playList.songList; // reset the song selection if (selectedSong != null) { songList.selectedItem = selectedSong; } } private function songSelectionChange():void { if (songList.selectedIndex != -1) { setFormState(SONG_DETAIL); } else { setFormState(ADD_SONG); } } private function addNewSong():void { // gather the values from the form and add the new song var title:String = newSongTitle.text; var artist:String = newSongArtist.text; var year:uint = newSongYear.value; var filename:String = newSongFilename.text; var genres:Array = newSongGenres.selectedItems; playList.addSong(new Song(title, artist, year, filename, genres)); refreshList(); // clear out the "add song" form fields setFormState(ADD_SONG); } private function songListLabel(item:Object):String { return item.toString(); } private function setFormState(state:uint):void { // set the form title and control state switch (state) { case ADD_SONG: formTitle.text = "Add New Song"; // show the submit button submitSongData.visible = true; showAddControlsBtn.visible = false; // clear the form fields newSongTitle.text = ""; newSongArtist.text = ""; newSongYear.value = (new Date()).fullYear; newSongFilename.text = ""; newSongGenres.selectedIndex = -1; // deselect the currently selected song (if any) songList.selectedIndex = -1; break; case SONG_DETAIL: formTitle.text = "Song Details"; // populate the form with the selected item's data var selectedSong:Song = Song(songList.selectedItem); newSongTitle.text = selectedSong.title; newSongArtist.text = selectedSong.artist; newSongYear.value = selectedSong.year; newSongFilename.text = selectedSong.filename; newSongGenres.selectedItems = selectedSong.genres; // hide the submit button submitSongData.visible = false; showAddControlsBtn.visible = true; break; } }
Add AS3 example.
Add AS3 example.
ActionScript
bsd-2-clause
dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments
16c6924cab16d7c18b9f3aed2b245f6d4bdd9a9f
src/main/org/shypl/common/net/InetSocketAddress.as
src/main/org/shypl/common/net/InetSocketAddress.as
package org.shypl.common.net { public class InetSocketAddress { private var _host:String; private var _port:int; public function InetSocketAddress(host:String, port:int) { _host = host; _port = port; } public function get host():String { return _host; } public function get port():int { return _port; } public function toString():String { return _host + ":" + _port; } } }
Add InetSocketAddress
Add InetSocketAddress
ActionScript
apache-2.0
shypl/common-flash
1d13e464163d6480f3a0fdf40530b055131a740a
WeaveData/src/weave/data/DataSources/FREDDataSource.as
WeaveData/src/weave/data/DataSources/FREDDataSource.as
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.data.DataSources { import flash.net.URLRequest; import mx.charts.chartClasses.IColumn; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import weave.api.data.ColumnMetadata; import weave.api.data.DataType; import weave.api.data.IAttributeColumn; import weave.api.data.IColumnReference; import weave.api.data.IDataSource; import weave.api.data.IWeaveTreeNode; import weave.api.newDisposableChild; import weave.api.newLinkableChild; import weave.api.registerDisposableChild; import weave.api.registerLinkableChild; import weave.api.reportError; import weave.compiler.Compiler; import weave.compiler.StandardLib; import weave.core.LinkablePromise; import weave.core.LinkableString; import weave.data.AttributeColumns.ProxyColumn; import weave.data.hierarchy.ColumnTreeNode; import weave.primitives.Dictionary2D; import weave.services.JsonCache; import weave.services.addAsyncResponder; public class FREDDataSource extends AbstractDataSource { WeaveAPI.ClassRegistry.registerImplementation(IDataSource, FREDDataSource, "Federal Reserve Economic Data"); public function FREDDataSource() { } override protected function initialize():void { // recalculate all columns previously requested //refreshAllProxyColumns(); super.initialize(); } private const jsonCache:JsonCache = newLinkableChild(this, JsonCache); public const apiKey:LinkableString = registerLinkableChild(this, new LinkableString("fa99c080bdbd1d486a55e7cb6ab7acbb")); /** * @param method Examples: "category", "category/series" * @param params Example: {category_id: 125} */ private function getUrl(method:String, params:Object):String { params['api_key'] = apiKey.value; params['file_type'] = 'json'; var paramsStr:String = ''; for (var key:String in params) paramsStr += (paramsStr ? '&' : '?') + key + '=' + params[key]; return "http://api.stlouisfed.org/fred/" + method + paramsStr; } /** * @param method Examples: "category", "category/series" * @param params Example: {category_id: 125} */ private function getJson(method:String, params:Object):Object { return jsonCache.getJsonObject(getUrl(method, params)); } private var functionCache:Dictionary2D = new Dictionary2D(); public function createCategoryNode(data:Object = null, ..._):ColumnTreeNode { if (!data) { var name:String = WeaveAPI.globalHashMap.getName(this); data = {id: 0, name: name}; } var node:ColumnTreeNode = functionCache.get(createCategoryNode, data.id); if (!node) { node = new ColumnTreeNode({ source: this, data: data, label: data.name, isBranch: true, hasChildBranches: true, children: function(node:ColumnTreeNode):Array { return [].concat( getCategoryChildren(node), getCategorySeries(node) ); } }); functionCache.set(createCategoryNode, data.id, node); } return node; } private function getCategoryChildren(node:ColumnTreeNode):Array { var result:Object = getJson('category/children', {category_id: node.data.id}); if(!result.categories) return []; return result.categories.map(createCategoryNode); } private function getCategorySeries(node:ColumnTreeNode):Array { var result:Object = getJson('category/series', {category_id: node.data.id}); if(!result.seriess) return []; return result.seriess.map(createSeriesNode); } public function getObservationsCSV(series_id:String):CSVDataSource { var csv:CSVDataSource = functionCache.get(getObservationsCSV, series_id); if (!csv) { csv = newLinkableChild(this, CSVDataSource); functionCache.set(getObservationsCSV, series_id, csv); var request1:URLRequest = new URLRequest(getUrl('series', {series_id: series_id})); addAsyncResponder( WeaveAPI.URLRequestUtils.getURL(csv, request1), function(event:ResultEvent, csv:CSVDataSource):void { var data:Object = JsonCache.parseJSON(event.result.toString()); data = data.seriess[0]; var request2:URLRequest = new URLRequest(getUrl('series/observations', {series_id: series_id})); addAsyncResponder( WeaveAPI.URLRequestUtils.getURL(csv, request2), function(event:ResultEvent, csv:CSVDataSource):void { var result:Object = JsonCache.parseJSON(event.result.toString()); var columnOrder:Array = ['date', 'realtime_start', 'realtime_end', 'value']; var rows:Array = WeaveAPI.CSVParser.convertRecordsToRows(result.observations, columnOrder); csv.csvData.setSessionState(rows); var valueTitle:String = lang("{0} ({1})", data.title, data.units); var metadataArray:Array = [ {title: 'date', dataType: DataType.DATE, dateFormat: 'YYYY-MM-DD'}, {title: 'realtime_start', dataType: DataType.DATE, dateFormat: 'YYYY-MM-DD'}, {title: 'realtime_end', dataType: DataType.DATE, dateFormat: 'YYYY-MM-DD'}, {title: valueTitle, dataType: DataType.NUMBER}, ]; csv.metadata.setSessionState(metadataArray); }, handleFault, csv ); }, handleFault, csv ); } return csv; } private function handleFault(event:FaultEvent, token:Object = null):void { reportError(event); } public function createSeriesNode(data:Object, ..._):IWeaveTreeNode { var node:IWeaveTreeNode = functionCache.get(createSeriesNode, data.id); if (!node) { node = new ColumnTreeNode({ label: data.title, source: this, data: data, isBranch: true, hasChildBranches: false, children: function(node:ColumnTreeNode):Array { var csv:CSVDataSource = getObservationsCSV(data.id); var csvRoot:IWeaveTreeNode = csv.getHierarchyRoot(); node.source = csv; return csvRoot.getChildren().map(function(csvNode:IColumnReference, ..._):IWeaveTreeNode { var meta:Object = csvNode.getColumnMetadata(); meta[META_SERIES_ID] = data.id; meta[META_COLUMN_NAME] = meta[CSVDataSource.METADATA_COLUMN_NAME]; return generateHierarchyNode(meta); }); } }); functionCache.set(createSeriesNode, data.id, node); } return node; } override public function getHierarchyRoot():IWeaveTreeNode { if (!_rootNode) { var source:FREDDataSource = this; _rootNode = createCategoryNode(); } return _rootNode; } public static const META_SERIES_ID:String = 'FRED_series_id'; public static const META_COLUMN_NAME:String = 'FRED_column_name'; public static const META_ID_FIELDS:Array = [META_SERIES_ID, META_COLUMN_NAME]; override public function findHierarchyNode(metadata:Object):IWeaveTreeNode { return null; } override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode { if (!metadata) return null; return new ColumnTreeNode({ source: this, idFields: META_ID_FIELDS, columnMetadata: metadata }); } override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void { var series:String = proxyColumn.getMetadata(META_SERIES_ID); //var columnName:String = proxyColumn.getMetadata(META_COLUMN_NAME); var csv:CSVDataSource = getObservationsCSV(series); var csvColumn:IAttributeColumn = csv.getAttributeColumn(ColumnMetadata.getAllMetadata(proxyColumn)); proxyColumn.setInternalColumn(csvColumn); } } }
add FRED data source
add FRED data source
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
136f6ba704c30102f39d598506d1e7121c7d86c3
src/flash/utils/IExternalizable.as
src/flash/utils/IExternalizable.as
/* * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flash.utils { public interface IExternalizable { function writeExternal(output: IDataOutput): void; function readExternal(input: IDataInput): void; } }
Add missing builtin flash.utils.IExternalizable
Add missing builtin flash.utils.IExternalizable
ActionScript
apache-2.0
mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway
02693fd7c88c3a2b8782184d67872d75a0bba442
src/corsaair/server/spitfire/SimpleSocketServerSelect2.as
src/corsaair/server/spitfire/SimpleSocketServerSelect2.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package corsaair.server.spitfire { import C.errno.*; import C.arpa.inet.*; import C.netdb.*; import C.netinet.*; import C.sys.socket.*; import C.sys.select.*; import C.stdlib.*; import C.unistd.*; import flash.utils.ByteArray; /** * A simple socket server upgrade 2. * * Let's clean up the code and reorganise it into methods * to spearate responsibility. * */ public class SimpleSocketServerSelect2 { // the port users will be connecting to public const PORT:String = "3490"; // how many pending connections queue will hold public const BACKLOG:uint = 10; private var _address:Array; // list of addresses private var _info:addrinfo; // server selected address private var _run:Boolean; // run the server loop public var serverfd:int; // server socket descriptor public var selected:int; // selected socket descriptor public var connections:Array; // list of socket descriptor public function SimpleSocketServerSelect2() { super(); _address = []; _info = null; _run = true; serverfd = -1; selected = -1; connections = []; } /** * @private * * Use getaddrinfo() to obtain a list of IP addresses we can use * loop trough those addresses and bind to the first one we can * * Two possible outcome * * - we found an address and boudn to it * we set the _info object with the address * then we return the socket descriptor * * - we exhausted the list of addresses * without binding to any of them * then our _info object is not set * we return an unusable socket descriptor */ private function _getBindingSocket():int { var hints:addrinfo = new addrinfo(); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // indicates we want to bind var info:addrinfo; var eaierr:CEAIrror = new CEAIrror(); var addrlist:Array = getaddrinfo( null, PORT, hints, eaierr ); if( !addrlist ) { throw eaierr; } var sockfd:int; var option:int; var bound:int; var i:uint; var len:uint = addrlist.length; for( i = 0; i < len; i++ ) { info = addrlist[i]; sockfd = socket( info.ai_family, info.ai_socktype, info.ai_protocol ); if( sockfd == -1 ) { trace( "selectserver: socket" ) trace( new CError( "", errno ) ); continue; } option = setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, 1 ); if( option == -1 ) { trace( "setsockopt" ); trace( new CError( "", errno ) ); exit( 1 ); } bound = bind( sockfd, info.ai_addr ); if( bound == -1 ) { close( sockfd ); trace( "selectserver: bind" ); trace( new CError( "", errno ) ); continue; } // we save the selected addrinfo _info = info; break; } // we merge the addresses found into our list of address _address = _address.concat( addrlist ); // we return the socket descriptor return sockfd; } /** * @private * * Loop trough all the clients connections. * * Yes this is how we do multiplexing I/O * without really using select() * * All the secret is with isReadable() * from that point we know we can read on * the socket and this lead to 2 clear paths * * - the server * reading on the server socket means * accepting a new connection with accept() * * - the clients * reading on a client socket means * reading data from the client with recv() * * IMPORTANT: * both accept() and recv() are blocking * which means you can freeze your server loop * if something is misshandled or take too long * (this will be explained in the next example) */ private function _loopConnections():void { var i:uint; var len:uint = connections.length; for( i = 0; i < len; i++ ) { selected = connections[i]; if( isReadable( selected ) ) { if( selected == serverfd ) { _handleNewConnections(); } else { _handleClientData(); } } } } /** * @private * * Block on accept() * if accepted * - add the new socket descriptor to the connections * - send a welcome message to the client */ private function _handleNewConnections():void { // handle new connections var new_fd:int; // newly accept()ed socket descriptor var client_addr:sockaddr_in = new sockaddr_in(); new_fd = accept( serverfd, client_addr ); if( new_fd == -1 ) { trace( "accept" ); trace( new CError( "", errno ) ); } else { connections.push( new_fd ); var s:String = inet_ntop( client_addr.sin_family, client_addr ); trace( "selectserver: new connection from " + s + ", socket " + new_fd ); var msg_out:String = "Hello, world!\n"; var bytes_out:ByteArray = new ByteArray(); bytes_out.writeUTFBytes( msg_out ); bytes_out.position = 0; var sent:int = send( new_fd, bytes_out ); if( sent == -1 ) { trace( "send" ); trace( new CError( "", errno ) ); } else { trace( "sent " + sent + " bytes to the client " + new_fd ); } } } /** * @private * * Block on recv() * if receiving data * - write the data to the server log * - check for the "shutdown" command * * How do we know we are not receiving data ? * if you try to recv() on a disconected client * you will automatically recevie 0 which means * the client disconnected or hung up. * Or you will receive a negative integer * for signalling an error. * * In both case, we want to close the socket ot the client * and remove it from the connections list. */ private function _handleClientData():void { // handle data from a client var msg_in:String; var bytes_in:ByteArray = new ByteArray(); var received:int = recv( selected, bytes_in ); if( received <= 0 ) { // got error or connection closed by client if( received == 0 ) { // connection closed trace( "selectserver: socket " + selected + " hung up" ); } else { trace( "recv" ); trace( new CError( "", errno ) ); } close( selected ); // bye! // remove from master set _removeClient( selected ); } else { // we got some data from a client trace( "received " + received + " bytes from client " + selected ); bytes_in.position = 0; msg_in = bytes_in.readUTFBytes( bytes_in.length ); msg_in = msg_in.split( "\n" ).join( "" ); trace( selected + " : " + msg_in ); if( msg_in == "shutdown" ) { trace( "selectserver: received 'shutdown' command" ); _run = false; } } } /** * @private * * add a client to list of connections * so far a 'client' is only the integer of a socket descriptor * * a client can be as well the current server than a remobe client */ private function _addClient( sd:int ):void { connections.push( sd ); } /** * @private * * remove a client from the list of connections */ private function _removeClient( sd:int ):void { /* Note: protection from removing the server socket descriptor which would disconnect/crash all other clients */ if( sd == serverfd ) { return; } var i:uint; var len:uint = connections.length; var desc:int; for( i = 0; i < len; i++ ) { desc = connections[i]; if( desc == sd ) { connections.splice( i, 1 ); } } } /** * @private * * close the socket descriptor and remove it from the list of connections * we use that to clean after ourselves * but in most case if the server process were to crash * all the descriptor would be automatically closed as * they depend on this process. * * Alternatively you can also use this to disconnect all or parts of the clients. */ private function _closeAndRemoveAllClients( removeServer:Boolean = false ):void { var i:uint; var desc:int; for( i = 0; i < connections.length; i++ ) { desc = connections[i]; if( !removeServer && (desc == serverfd) ) { continue; } trace( "selectserver: terminate " + desc ); close( desc ); connections.splice( i, 1 ); i = 0; //rewind } } public function main():void { /* Note: find our IP address and bind thesocket to it in general the IP will be 0.0.0.0 which means listen on all interfaces */ serverfd = _getBindingSocket(); /* Note: Verify that we have selected an address if not it is a fatal error. eg. the loop trough the address info did not find an address */ if( _info == null ) { trace( "selectserver: failed to bind" ); exit( 1 ); } /* Note: The last part of the server setup is to listen() which means "I'm ready to receive data". If the server can not listen it is a fatal error. About BACKLOG see http://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html the backlog is here to limit the queue of incoming connections it will not handle multiple connections eg. that's the difference between queueing and multiplexing The backlog argument provides a hint to the implementation which the implementation shall use to limit the number of outstanding connections in the socket's listen queue. Implementations may impose a limit on backlog and silently reduce the specified value. Normally, a larger backlog argument value shall result in a larger or equal length of the listen queue. Implementations shall support values of backlog up to SOMAXCONN, defined in `C.sys.socket`. */ var listening:int = listen( serverfd, BACKLOG ); if( listening == -1 ) { trace( "listen" ); trace( new CError( "", errno ) ); exit( 1 ); } trace( "selectserver: waiting for connections..." ); // the server is always the first client to be added to the connections _addClient( serverfd ); trace( "selectserver: server on socket " + serverfd ); /* Note: main server loop Keep the server looping as long as run == true hopefully now the loop is easier to read :) */ while( _run ) { _loopConnections(); } trace( "selectserver: connections left [" + connections + "]" ); _closeAndRemoveAllClients(); trace( "shutting down server" ); shutdown( serverfd, SHUT_RDWR ); close( serverfd ); exit( 0 ); } } }
add updated select server, cleaner version
add updated select server, cleaner version git-svn-id: 44dac414ef660a76a1e627c7b7c0e36d248d62e4@20 c2cce57b-6cbb-4450-ba62-5fdab5196ef5
ActionScript
mpl-2.0
Corsaair/spitfire
e7bf51cfb89a12a7d718026032b58910d9fc755b
test/swfs/test_Template.as
test/swfs/test_Template.as
/* -*- Mode: java; indent-tabs-mode: nil -*- */ /* Compiled with: java -jar utils/asc.jar -import playerglobal.abc -swf Template,100,100,10 test/swfs/test_TemplateTest.as This template is for writing test SWFs using pure AS3. It allows for testing UI events, screen and program state using the Shumway test harness. */ package { import flash.display.Sprite; import flash.events.Event; public class TemplateTest extends Sprite { public var loader; public function TemplateTest() { var child = new TestObject(); addChild(child); addEventListener(Event.ENTER_FRAME, child.enterFrameHandler); } } } import flash.display.*; import flash.events.*; import flash.net.*; class TestObject extends Sprite { private var color: uint = 0xFFCC00; private var pos: uint = 10; private var size: uint = 80; /* In the constructor, install event listeners for testing events, and construct and add child objects. */ public function TestObject() { } private var frameCount = 0; /* In the enterFrameHandler, make API calls per frame to test both screen and program side-effects. */ function enterFrameHandler(event:Event):void { frameCount++; var target = event.target; var loader = target.loader; switch (frameCount) { case 1: (function () { /* Log test results in the standard format shown here to allow for easy linking with monitor programs. */ var result = true ? "PASS" : "FAIL"; trace(result + ": test::Template/method ()"); trace(result + ": test::Template/get name ()"); trace(result + ": test::Template/set name ()"); })(); break; default: /* Remove enterFrameHandler when done. */ parent.removeEventListener(Event.ENTER_FRAME, enterFrameHandler); break; } } }
Add template for writing SWF unit tests
Add template for writing SWF unit tests
ActionScript
apache-2.0
mozilla/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway
9a85e5b90a37c8c989cda04f69862b82f25ca924
RTMFPSocket.as
RTMFPSocket.as
/* The RTMFPSocket class provides a socket-like interface around RTMFP NetConnection and NetStream. Each RTMFPSocket contains one NetConnection and two NetStreams, one for reading and one for writing. To create a listening socket: var rs:RTMFPSocket = new RTMFPSocket(url, key); rs.addEventListener(Event.COMPLETE, function (e:Event):void { // rs.id is set and can be sent out of band to the client. }); rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, function (e:Event):void { // rs.peer_id is the ID of the connected client. }); rs.listen(); To connect to a listening socket: // Receive peer_id out of band. var rs:RTMFPSocket = new RTMFPSocket(url, key); rs.addEventListener(Event.CONNECT, function (e:Event):void { // rs.id and rs.peer_id are now set. }); */ package { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.net.NetConnection; import flash.net.NetStream; import flash.utils.ByteArray; public class RTMFPSocket extends EventDispatcher { public static const ACCEPT_EVENT:String = "accept"; public var connected:Boolean; private var nc:NetConnection; private var incoming:NetStream; private var outgoing:NetStream; /* Cache to hold the peer ID between when connect is called and the NetConnection exists. */ private var connect_peer_id:String; private var buffer:ByteArray; private var cirrus_url:String; private var cirrus_key:String; public function RTMFPSocket(cirrus_url:String, cirrus_key:String) { connected = false; buffer = new ByteArray(); this.cirrus_url = cirrus_url; this.cirrus_key = cirrus_key; nc = new NetConnection(); } public function get id():String { return nc.nearID; } public function get peer_id():String { return incoming.farID; } /* NetStatusEvents that aren't handled more specifically in listen_netstatus_event or connect_netstatus_event. */ private function generic_netstatus_event(e:NetStatusEvent):void { switch (e.info.code) { case "NetConnection.Connect.Closed": dispatchEvent(new Event(Event.CLOSE)); break; case "NetStream.Connect.Closed": connected = false; close(); break; default: var event:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR); event.text = e.info.code; dispatchEvent(event); break; } } private function listen_netstatus_event(e:NetStatusEvent):void { switch (e.info.code) { case "NetConnection.Connect.Success": outgoing = new NetStream(nc, NetStream.DIRECT_CONNECTIONS); outgoing.client = { onPeerConnect: listen_onpeerconnect }; outgoing.publish("server"); /* listen is complete, ready to accept. */ dispatchEvent(new Event(Event.COMPLETE)); break; case "NetStream.Connect.Success": break; default: return generic_netstatus_event(e); break; } } private function listen_onpeerconnect(peer:NetStream):Boolean { incoming = new NetStream(nc, peer.farID); incoming.client = { r: receive_data }; incoming.play("client"); connected = true; dispatchEvent(new Event(ACCEPT_EVENT)); return true; } private function connect_netstatus_event(e:NetStatusEvent):void { switch (e.info.code) { case "NetConnection.Connect.Success": outgoing = new NetStream(nc, NetStream.DIRECT_CONNECTIONS); outgoing.publish("client"); incoming = new NetStream(nc, connect_peer_id); incoming.client = { r: receive_data }; incoming.play("server"); break; case "NetStream.Connect.Success": connected = true; dispatchEvent(new Event(Event.CONNECT)); break; default: return generic_netstatus_event(e); break; } } /* Function called back when the other side does a send. */ private function receive_data(bytes:ByteArray):void { var event:ProgressEvent; event = new ProgressEvent(ProgressEvent.SOCKET_DATA); event.bytesLoaded = bytes.bytesAvailable; bytes.readBytes(buffer, buffer.length, bytes.bytesAvailable); if (bytes.bytesAvailable == 0) { /* Reclaim memory space. */ bytes.position = 0; bytes.length = 0; } dispatchEvent(event); } public function listen():void { nc.addEventListener(NetStatusEvent.NET_STATUS, listen_netstatus_event); nc.connect(cirrus_url, cirrus_key); } public function connect(peer_id:String):void { /* Store for later reading by connect_netstatus_event. */ this.connect_peer_id = peer_id; nc.addEventListener(NetStatusEvent.NET_STATUS, connect_netstatus_event); nc.connect(cirrus_url, cirrus_key); } public function close():void { outgoing.close(); incoming.close(); nc.close(); } public function readBytes(output:ByteArray, offset:uint = 0, length:uint = 0):void { buffer.readBytes(output, offset, length); } public function writeBytes(input:ByteArray, offset:uint = 0, length:uint = 0):void { var sendbuf:ByteArray; /* Read into a new buffer, in case offset and length do not completely span input. */ sendbuf = new ByteArray(); sendbuf.writeBytes(input, offset, length); /* Use a short method name because it's sent over the wire. */ outgoing.send("r", sendbuf); } } }
Add an RTMFPSocket class.
Add an RTMFPSocket class.
ActionScript
mit
infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy
2e35a2a12d08a9b3e1725aaff7ac57254b27b2c7
src/org/flintparticles/twoD/actions/TweenToCurrentPosition.as
src/org/flintparticles/twoD/actions/TweenToCurrentPosition.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.twoD.actions { import org.flintparticles.common.actions.ActionBase; import org.flintparticles.common.emitters.Emitter; import org.flintparticles.common.initializers.Initializer; import org.flintparticles.common.particles.Particle; import org.flintparticles.twoD.particles.Particle2D; import org.flintparticles.twoD.zones.Zone2D; import flash.geom.Point; [DefaultProperty("zone")] /** * The TweenToCurrentPosition action adjusts the particle's position between two * locations as it ages. The start location is a random point within the specified * zone, and the end location is the particle's position when it is created or added * to the emitter. The current position is relative to the particle's energy, * which changes as the particle ages in accordance with the energy easing * function used. This action should be used in conjunction with the Age action. */ public class TweenToCurrentPosition extends ActionBase implements Initializer { private var _zone : Zone2D; /** * The constructor creates a TweenToCurrentPosition action for use by an emitter. * To add a TweenToCurrentPosition to all particles created by an emitter, use the * emitter's addAction method. * * @see org.flintparticles.common.emitters.Emitter#addAction() * * @param zone The zone for the particle's position when its energy is 0. */ public function TweenToCurrentPosition( zone : Zone2D ) { _zone = zone; priority = -10; } /** * The zone for the particle's position when its energy is 0. */ public function get zone() : Zone2D { return _zone; } public function set zone( value : Zone2D ) : void { _zone = value; } /** * */ override public function addedToEmitter( emitter : Emitter ) : void { if ( !emitter.hasInitializer( this ) ) { emitter.addInitializer( this ); } } override public function removedFromEmitter( emitter : Emitter ) : void { emitter.removeInitializer( this ); } /** * */ public function initialize( emitter : Emitter, particle : Particle ) : void { var p : Particle2D = Particle2D( particle ); var pt : Point = _zone.getLocation(); var data : TweenToPositionData = new TweenToPositionData( pt.x, pt.y, p.x, p.y ); p.dictionary[this] = data; } /** * Calculates the current position of the particle based on it's energy. * * <p>This method is called by the emitter and need not be called by the * user.</p> * * @param emitter The Emitter that created the particle. * @param particle The particle to be updated. * @param time The duration of the frame - used for time based updates. * * @see org.flintparticles.common.actions.Action#update() */ override public function update( emitter : Emitter, particle : Particle, time : Number ) : void { var p : Particle2D = Particle2D( particle ); if ( !p.dictionary[this] ) { initialize( emitter, particle ); } var data : TweenToPositionData = p.dictionary[this]; p.x = data.endX + data.diffX * p.energy; p.y = data.endY + data.diffY * p.energy; } } } class TweenToPositionData { public var diffX : Number; public var diffY : Number; public var endX : Number; public var endY : Number; public function TweenToPositionData( startX : Number, startY : Number, endX : Number, endY : Number ) { this.diffX = startX - endX; this.diffY = startY - endY; this.endX = endX; this.endY = endY; } }
Add TweenToCurrentPosition 2d Action
Add TweenToCurrentPosition 2d Action
ActionScript
mit
richardlord/Flint
a496bc050554f457fccf9806987c813e7edea964
assets/scripts/character_states/walk_backward.as
assets/scripts/character_states/walk_backward.as
void enter(entity_impl& out owner) { owner.get_animation_component().blend_ani("walk_backward"); } void update(float delta_time, entity_impl& out owner) { } void leave(entity_impl& out owner) { }
add character state for backwards walking.
add character state for backwards walking.
ActionScript
mit
kasoki/project-zombye,kasoki/project-zombye,kasoki/project-zombye
797d1c721c95b35715a9a41c5d2df5115366296f
src/aerys/minko/render/resource/texture/TextureAtlas.as
src/aerys/minko/render/resource/texture/TextureAtlas.as
package aerys.minko.render.resource.texture { import aerys.minko.render.resource.texture.TextureResource; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.utils.Dictionary; public class TextureAtlas extends TextureResource { private var _nodes : Array = new Array(); private var _empty : Array = new Array(); private var _size : uint = 0; private var _atlasBitmapData : BitmapData = null; private var _bitmapDataToRectangle : Dictionary = new Dictionary(); public function TextureAtlas(size : uint = 2048, transparent : Boolean = true, backgroundColor : uint = 0x000000) { _size = size; _nodes[0] = new Rectangle(0, 0, _size, _size); _atlasBitmapData = new BitmapData(_size, _size, transparent, backgroundColor); setContentFromBitmapData(_atlasBitmapData, true); } public function get atlasBitmapData():BitmapData { return _atlasBitmapData; } public function get bitmapDataToRectangle():Dictionary { return _bitmapDataToRectangle; } public function addBitmapData(bitmapData : BitmapData) : Rectangle { var rectangle : Rectangle = getRectangle(bitmapData.width, bitmapData.height); if (rectangle == null) return null; _atlasBitmapData.copyPixels(bitmapData, bitmapData.rect, rectangle.topLeft); setContentFromBitmapData(_atlasBitmapData, true); _bitmapDataToRectangle[bitmapData] = rectangle.clone(); return _bitmapDataToRectangle[bitmapData]; } private function getRectangle(width : uint, height : uint, rootId : int = 0) : Rectangle { var node : Rectangle = _nodes[rootId]; var first : Rectangle = _nodes[int(rootId * 2 + 1)]; var second : Rectangle = _nodes[int(rootId * 2 + 2)]; if (!first && !second) { if (_empty[rootId] === false || width > node.width || height > node.height) return null; if (width == node.width && height == node.height) { _empty[rootId] = false; return node; } else { var dw : uint = node.width - width; var dh : uint = node.height - height; if (dw > dh) { first = new Rectangle(node.left, node.top, width, node.height); second = new Rectangle(node.left + width, node.top, node.width - width, node.height); } else { first = new Rectangle(node.left, node.top, node.width, height); second = new Rectangle(node.left, node.top + height, node.width, node.height - height); } _nodes[int(rootId * 2 + 1)] = first; _nodes[int(rootId * 2 + 2)] = second; return getRectangle(width, height, rootId * 2 + 1); } } if ((node = getRectangle(width, height, rootId * 2 + 1))) return node; return getRectangle(width, height, rootId * 2 + 2); } } }
Add TextureAtlas
Add TextureAtlas
ActionScript
mit
aerys/minko-as3
16ca28b9380765a310c05214d98e6bf846669ce0
src/corsaair/server/spitfire/SimpleSocketServerSelect3.as
src/corsaair/server/spitfire/SimpleSocketServerSelect3.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package corsaair.server.spitfire { import C.errno.*; import C.arpa.inet.*; import C.netdb.*; import C.netinet.*; import C.sys.socket.*; import C.sys.select.*; import C.stdlib.*; import C.unistd.*; import flash.utils.ByteArray; import flash.utils.Dictionary; /** * A simple socket server upgrade 3. * * Let's see special cases: * * - how to slow down your server loop ? * * - what happen when a client block * your server loop ? */ public class SimpleSocketServerSelect3 { // the port users will be connecting to public const PORT:String = "3490"; // how many pending connections queue will hold public const BACKLOG:uint = 10; private var _address:Array; // list of addresses private var _info:addrinfo; // server selected address private var _run:Boolean; // run the server loop public var serverfd:int; // server socket descriptor public var selected:int; // selected socket descriptor public var connections:Array; // list of socket descriptor /* Note: bascially a map of clients using thesocket descriptor as the key clients[ socket desc ] = { nickname: "test" } */ public var clients:Dictionary; // list of clients informations /* Note: allow to slow down the pace of the server loop time is expressed in milliseconds 0 - do not sleep 1000 - sleep 1 sec */ public var sleepTime:uint; public function SimpleSocketServerSelect3() { super(); _address = []; _info = null; _run = true; serverfd = -1; selected = -1; connections = []; clients = new Dictionary(); sleepTime = 0; // 0 means "do not sleep" } private function _getBindingSocket():int { var hints:addrinfo = new addrinfo(); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // indicates we want to bind var info:addrinfo; var eaierr:CEAIrror = new CEAIrror(); var addrlist:Array = getaddrinfo( null, PORT, hints, eaierr ); if( !addrlist ) { throw eaierr; } var sockfd:int; var option:int; var bound:int; var i:uint; var len:uint = addrlist.length; for( i = 0; i < len; i++ ) { info = addrlist[i]; sockfd = socket( info.ai_family, info.ai_socktype, info.ai_protocol ); if( sockfd == -1 ) { trace( "selectserver: socket" ) trace( new CError( "", errno ) ); continue; } option = setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, 1 ); if( option == -1 ) { trace( "setsockopt" ); trace( new CError( "", errno ) ); exit( 1 ); } bound = bind( sockfd, info.ai_addr ); if( bound == -1 ) { close( sockfd ); trace( "selectserver: bind" ); trace( new CError( "", errno ) ); continue; } // we save the selected addrinfo _info = info; break; } // we merge the addresses found into our list of address _address = _address.concat( addrlist ); // we return the socket descriptor return sockfd; } private function _loopConnections():void { var i:uint; var len:uint = connections.length; for( i = 0; i < len; i++ ) { selected = connections[i]; if( isReadable( selected ) ) { if( selected == serverfd ) { _handleNewConnections(); } else { _handleClientData(); } } } } private function _handleNewConnections():void { // handle new connections var new_fd:int; // newly accept()ed socket descriptor var client_addr:sockaddr_in = new sockaddr_in(); new_fd = accept( serverfd, client_addr ); if( new_fd == -1 ) { trace( "accept" ); trace( new CError( "", errno ) ); } else { _addClient( new_fd ); var s:String = inet_ntop( client_addr.sin_family, client_addr ); trace( "selectserver: new connection from " + s + ", socket " + new_fd ); var msg_out:String = "Hello, world!\n"; var bytes_out:ByteArray = new ByteArray(); bytes_out.writeUTFBytes( msg_out ); bytes_out.position = 0; var sent:int = send( new_fd, bytes_out ); if( sent == -1 ) { trace( "send" ); trace( new CError( "", errno ) ); } else { trace( "sent " + sent + " bytes to the client " + new_fd ); } registerNewArrival( new_fd ); } } private function _handleClientData():void { // handle data from a client var msg_in:String; var bytes_in:ByteArray = new ByteArray(); var received:int = recv( selected, bytes_in ); if( received <= 0 ) { // got error or connection closed by client if( received == 0 ) { // connection closed trace( "selectserver: socket " + selected + " hung up" ); } else { trace( "recv" ); trace( new CError( "", errno ) ); } close( selected ); // bye! // remove from master set _removeClient( selected ); } else { // we got some data from a client trace( "received " + received + " bytes from client " + selected ); bytes_in.position = 0; msg_in = bytes_in.readUTFBytes( bytes_in.length ); msg_in = msg_in.split( "\n" ).join( "" ); /* Note: If the nickname is not empty that means the client registered and so we use this nickname instead of the socket id */ if( clients[selected].nickname != "" ) { trace( clients[selected].nickname + " : " + msg_in ); } else { trace( selected + " : " + msg_in ); } if( msg_in == "shutdown" ) { trace( "selectserver: received 'shutdown' command" ); _run = false; } } } private function _addClient( sd:int, name:String = "" ):void { connections.push( sd ); clients[ sd ] = { nickname: name }; } private function _removeClient( sd:int ):void { /* Note: protection from removing the server socket descriptor which would disconnect/crash all other clients */ if( sd == serverfd ) { return; } var i:uint; var len:uint = connections.length; var desc:int; for( i = 0; i < len; i++ ) { desc = connections[i]; if( desc == sd ) { connections.splice( i, 1 ); delete clients[ sd ]; } } } private function _closeAndRemoveAllClients( removeServer:Boolean = false ):void { var i:uint; var desc:int; for( i = 0; i < connections.length; i++ ) { desc = connections[i]; if( !removeServer && (desc == serverfd) ) { continue; } if( clients[desc].nickname != "" ) { trace( "selectserver: terminate " + clients[desc].nickname + " (" + desc + ")" ); } else { trace( "selectserver: terminate " + desc ); } close( desc ); // close the socket connections.splice( i, 1 ); // remove the socket from the connections list delete clients[desc]; // delete the socket key for the clients data i = 0; //rewind } } /** * Register a new connected client. */ public function registerNewArrival( clientfd:int ):void { /* Note: For some reason we decided that each new socket clients had to register with a nickname - send a question - wait for the answer IMPORTANT: yes our server does support multiplexing meaning we can deal with multiple clients connections but here we want to illustrate a particular flaw each connection is blocking so even if we iterate trough each clients that means we need to wait for a client to be processed before being able to process the next client here, as long as the client does not register it will block ALL the other clients to either connect and register, send messages or commands, etc. */ var msg_welcome:String = "What is your nickname?\n"; var bytes_welcome:ByteArray = new ByteArray(); bytes_welcome.writeUTFBytes( msg_welcome ); bytes_welcome.position = 0; var welcome:int = send( clientfd, bytes_welcome ); if( welcome == -1 ) { trace( "selectserver: welcome sent" ); trace( new CError( "", errno ) ); close( clientfd ); _removeClient( clientfd ); return; } trace( "selectserver: wait for nickname ..." ); var bytes_answer:ByteArray = new ByteArray(); var nickname:String; var n:int; while( true ) { n = recv( clientfd, bytes_answer ); if( n <= 0 ) { // got error or connection closed by client if( n == 0 ) { // connection closed trace( "selectserver: socket " + clientfd + " hung up" ); } else { trace( "recv" ); trace( new CError( "", errno ) ); } close( clientfd ); _removeClient( clientfd ); break; } else { bytes_answer.position = 0; nickname = bytes_answer.readUTFBytes( n ); nickname = nickname.split( "\n" ).join( "" ); clients[ clientfd ].nickname = nickname; trace( "selectserver: socket " + clientfd + " registered as " + nickname ); break; } } } public function main():void { serverfd = _getBindingSocket(); if( _info == null ) { trace( "selectserver: failed to bind" ); exit( 1 ); } var listening:int = listen( serverfd, BACKLOG ); if( listening == -1 ) { trace( "listen" ); trace( new CError( "", errno ) ); exit( 1 ); } trace( "selectserver: waiting for connections..." ); // the server is always the first client to be added to the connections _addClient( serverfd, "server" ); trace( "selectserver: server on socket " + serverfd ); var frame:uint = 0; // main server loop while( _run ) { //trace( "selectserver: main loop" ); trace( "selectserver: main loop " + frame++ ); _loopConnections(); if( sleepTime > 0 ) { sleep( sleepTime ); } } trace( "selectserver: connections left [" + connections + "]" ); _closeAndRemoveAllClients(); trace( "shutting down server" ); shutdown( serverfd, SHUT_RDWR ); close( serverfd ); exit( 0 ); } } }
add example to show how to slow down the server and what happen when client block
add example to show how to slow down the server and what happen when client block git-svn-id: 44dac414ef660a76a1e627c7b7c0e36d248d62e4@27 c2cce57b-6cbb-4450-ba62-5fdab5196ef5
ActionScript
mpl-2.0
Corsaair/spitfire
f60200f415ca33fa75244336a00373f080ca4f20
src/aerys/minko/render/shader/compiler/ShaderCompilerError.as
src/aerys/minko/render/shader/compiler/ShaderCompilerError.as
package aerys.minko.render.shader.compiler { public final class ShaderCompilerError extends Error { public static const TOO_MANY_VERTEX_OPERATIONS : uint = 1 << 0; public static const TOO_MANY_VERTEX_CONSTANTS : uint = 1 << 1; public static const TOO_MANY_VERTEX_TEMPORARIES : uint = 1 << 2; public static const TOO_MANY_VERTEX_ATTRIBUTES : uint = 1 << 3; public static const TOO_MANY_VARYINGS : uint = 1 << 4; public static const TOO_MANY_FRAGMENT_OPERATIONS : uint = 1 << 5; public static const TOO_MANY_FRAGMENT_CONSTANTS : uint = 1 << 6; public static const TOO_MANY_FRAGMENT_TEMPORARIES : uint = 1 << 7; public static const TOO_MANY_FRAGMENT_SAMPLERS : uint = 1 << 8; public static const OUT_OF_REGISTERS : uint = TOO_MANY_VERTEX_CONSTANTS | TOO_MANY_VERTEX_TEMPORARIES | TOO_MANY_VERTEX_ATTRIBUTES | TOO_MANY_FRAGMENT_CONSTANTS | TOO_MANY_FRAGMENT_TEMPORARIES | TOO_MANY_FRAGMENT_SAMPLERS; public function ShaderCompilerError(id : uint = 0) { super(message, id); } } }
add missing ShaderCompilerError class
add missing ShaderCompilerError class
ActionScript
mit
aerys/minko-as3
9df8d3df36b85b173486dcb18e4868ff5c233783
src/avm2/tests/pilot/switch1.as
src/avm2/tests/pilot/switch1.as
var f = function() { switch (0) { case 0: trace('PASS'); break; } }; f(); trace('OK');
Add switch test for compiler
Add switch test for compiler
ActionScript
apache-2.0
mozilla/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway
8b3b0f298789e53685c8100f6eb0c9d6e21a8466
src/aerys/minko/scene/controller/mesh/VisibilityController.as
src/aerys/minko/scene/controller/mesh/VisibilityController.as
package aerys.minko.scene.controller.mesh { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.MeshVisibilityDataProvider; import aerys.minko.scene.node.Camera; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.bounding.FrustumCulling; import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; /** * The MeshVisibilityController watches the Mesh and the active Camera of a Scene * to determine whether the object is actually inside the view frustum or not. * * @author Jean-Marc Le Roux * */ public final class VisibilityController extends AbstractController { private static const STATE_UNDEFINED : uint = 0; private static const STATE_INSIDE : uint = 1; private static const STATE_OUTSIDE : uint = 2; private var _mesh : Mesh = null; private var _state : uint = 0; private var _visibilityData : MeshVisibilityDataProvider = new MeshVisibilityDataProvider(); public function get visible() : Boolean { return _visibilityData.visible; } public function set visible(value : Boolean) : void { _visibilityData.visible = value; } public function get frustumCulling() : uint { return _visibilityData.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibilityData.frustumCulling = value; } public function get insideFrustum() : Boolean { return _visibilityData.inFrustum; } public function VisibilityController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : VisibilityController, target : Mesh) : void { if (_mesh != null) throw new Error(); _mesh = target; target.addedToScene.add(meshAddedToSceneHandler); target.removedFromScene.add(meshRemovedFromSceneHandler); target.bindings.addProvider(_visibilityData); if (target.root is Scene) meshAddedToSceneHandler(target, target.root as Scene); } private function targetRemovedHandler(ctrl : VisibilityController, target : Mesh) : void { _mesh = null; target.addedToScene.remove(meshAddedToSceneHandler); target.removedFromScene.remove(meshRemovedFromSceneHandler); target.bindings.removeProvider(_visibilityData); if (target.root is Scene) meshRemovedFromSceneHandler(target, target.root as Scene); } private function meshAddedToSceneHandler(mesh : Mesh, scene : Scene) : void { scene.bindings.addCallback('worldToView', worldToViewChangedHandler); mesh.localToWorld.changed.add(meshLocalToWorldChangedHandler); } private function meshRemovedFromSceneHandler(mesh : Mesh, scene : Scene) : void { scene.bindings.removeCallback('worldToView', worldToViewChangedHandler); mesh.localToWorld.changed.remove(meshLocalToWorldChangedHandler); } private function worldToViewChangedHandler(bindings : DataBindings, propertyName : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { testCulling(); } private function meshLocalToWorldChangedHandler(transform : Matrix4x4) : void { testCulling(); } private function testCulling() : void { var culling : uint = _visibilityData.frustumCulling; /*if (culling != FrustumCulling.DISABLED && _mesh.geometry.boundingBox) { var camera : Camera = (_mesh.root as Scene).activeCamera; if (!camera) return ; culling = camera.cameraData.frustum.testBoundingVolume( _mesh.geometry, _mesh.localToWorld, culling ); var inside : Boolean = culling != Frustum.OUTSIDE; if (inside && _state != STATE_INSIDE) { _visibilityData.inFrustum = true; _state = STATE_INSIDE; } else if (!inside && _state != STATE_OUTSIDE) { _visibilityData.inFrustum = false; _state = STATE_OUTSIDE; } }*/ } override public function clone() : AbstractController { var clone : VisibilityController = new VisibilityController(); clone._visibilityData = _visibilityData.clone() as MeshVisibilityDataProvider; return clone; } } }
rename MeshVisibilityController into VisibilityController
rename MeshVisibilityController into VisibilityController
ActionScript
mit
aerys/minko-as3
479ea0c600c850d250a09fe2dd6d9df3e37db95a
Classes/Textbox.as
Classes/Textbox.as
package Classes { public class Textbox { public var contents:String; public function Textbox() { contents=""; } public function Textbox(text) { contents=text; } public setContents(text) { contents=text; } } }
Create a dummy textbox class for the sole purpose of writing the XML loader
Create a dummy textbox class for the sole purpose of writing the XML loader
ActionScript
agpl-3.0
mbjornas3/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
5432cfbb9e258458bb134eff8c6ab1c70f92d517
dolly-framework/src/test/resources/dolly/data/CopyableSubclass.as
dolly-framework/src/test/resources/dolly/data/CopyableSubclass.as
package dolly.data { [Copyable] public class CopyableSubclass extends CopyableClass { public static var staticProperty2:String = "Value of second-level static property."; private var _writableField2:String = "Value of second-level writable field."; public var property2:String = "Value of second-level public property."; public function CopyableSubclass() { super(); } public function get writableField2():String { return _writableField2; } public function set writableField2(value:String):void { _writableField2 = value; } public function get readOnlyField2():String { return "Value of second-level read-only field."; } } }
Create new data class for testing: CopyableSubclass.
Create new data class for testing: CopyableSubclass.
ActionScript
mit
Yarovoy/dolly
d7bb55ba3d8edd913cdb7053fae22c5043554ff5
dolly-framework/src/main/actionscript/dolly/core/metadata/MetadataName.as
dolly-framework/src/main/actionscript/dolly/core/metadata/MetadataName.as
package dolly.core.metadata { public class MetadataName { public static const CLONEABLE:String = "cloneable"; public static const COPYABLE:String = "copyable"; } }
Add Enum class MetadataName.
Add Enum class MetadataName.
ActionScript
mit
Yarovoy/dolly
362bc1e1ad7bc2c8ddbbef9a4fe4264fd5ded0f4
dolly-framework/src/test/actionscript/dolly/CopyingOfPropertyLevelCopyableCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CopyingOfPropertyLevelCopyableCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.PropertyLevelCopyableCloneableClass; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; use namespace dolly_internal; public class CopyingOfPropertyLevelCopyableCloneableClassTest { private var propertyLevelCopyableCloneableClass:PropertyLevelCopyableCloneableClass; private var propertyLevelCopyableCloneableClassType:Type; [Before] public function before():void { propertyLevelCopyableCloneableClass = new PropertyLevelCopyableCloneableClass(); propertyLevelCopyableCloneableClass.property1 = "property1 value"; propertyLevelCopyableCloneableClass.property2 = "property2 value"; propertyLevelCopyableCloneableClass.writableField1 = "writableField1 value"; propertyLevelCopyableCloneableClassType = Type.forInstance(propertyLevelCopyableCloneableClass); } [After] public function after():void { propertyLevelCopyableCloneableClass = null; propertyLevelCopyableCloneableClassType = null; } [Test] public function findingAllCopyableFieldsForType():void { const copyableFields:Vector.<Field> = Copier.findCopyableFieldsForType(propertyLevelCopyableCloneableClassType); assertNotNull(copyableFields); assertEquals(2, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); } [Test] public function copyingByCopier():void { const copyInstance:PropertyLevelCopyableCloneableClass = Copier.copy(propertyLevelCopyableCloneableClass); assertNotNull(copyInstance); assertNotNull(copyInstance.property1); assertEquals(copyInstance.property1, propertyLevelCopyableCloneableClass.property1); assertNotNull(copyInstance.property2); assertFalse(copyInstance.property2 == propertyLevelCopyableCloneableClass.property2); assertNotNull(copyInstance.writableField1); assertEquals(copyInstance.writableField1, propertyLevelCopyableCloneableClass.writableField1); } [Test] public function copyingByCopyFunction():void { const copyInstance:PropertyLevelCopyableCloneableClass = copy(propertyLevelCopyableCloneableClass); assertNotNull(copyInstance); assertNotNull(copyInstance.property1); assertEquals(copyInstance.property1, propertyLevelCopyableCloneableClass.property1); assertNotNull(copyInstance.property2); assertFalse(copyInstance.property2 == propertyLevelCopyableCloneableClass.property2); assertNotNull(copyInstance.writableField1); assertEquals(copyInstance.writableField1, propertyLevelCopyableCloneableClass.writableField1); } } }
Create new test class: CopyingOfPropertyLevelCopyableCloneableClassTest.
Create new test class: CopyingOfPropertyLevelCopyableCloneableClassTest.
ActionScript
mit
Yarovoy/dolly
004f5b35c05ee5b0e090a978439bae4f439b6fc4
dolly-framework/src/test/resources/dolly/data/ClassLevelCopyableSubclass.as
dolly-framework/src/test/resources/dolly/data/ClassLevelCopyableSubclass.as
package dolly.data { [Copyable] public class ClassLevelCopyableSubclass extends ClassLevelCopyable { private var _writableField2:String; public var property4:String; public var property5:String; public function ClassLevelCopyableSubclass() { } public function get writableField2():String { return _writableField2; } public function set writableField2(value:String):void { _writableField2 = value; } } }
Create data class for testing: ClassLevelCopyableSubclass.
Create data class for testing: ClassLevelCopyableSubclass.
ActionScript
mit
Yarovoy/dolly
18807ef09f1b5c98b74d48e000bd927854471f3d
src/com/pivotshare/hls/loader/FragmentStream.as
src/com/pivotshare/hls/loader/FragmentStream.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.pivotshare.hls.loader { import flash.display.DisplayObject; import flash.events.*; import flash.net.*; import flash.utils.ByteArray; import flash.utils.getTimer; import flash.utils.Timer; import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSLoadMetrics; import org.mangui.hls.HLS; import org.mangui.hls.model.Fragment; import org.mangui.hls.model.FragmentData; import org.mangui.hls.utils.AES; CONFIG::LOGGING { import org.mangui.hls.utils.Log; import org.mangui.hls.utils.Hex; } /** * HLS Fragment Streamer, which also handles decryption. * Tries to parallel URLStream design pattern, but is incomplete. * * See [Reading and writing a ByteArray](http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html) * * @class FragmentStream * @extends EventDispatcher * @author HGPA */ public class FragmentStream extends EventDispatcher { /* * DisplayObject needed by AES decrypter. */ private var _displayObject : DisplayObject; /* * Fragment being loaded. */ private var _fragment : Fragment; /* * URLStream used to download current Fragment. */ private var _fragmentURLStream : URLStream; /** * Create a FragmentStream. * * This constructor takes a reference to main DisplayObject, e.g. stage, * necessary for AES decryption control. * * TODO: It would be more appropriate to create a factory that itself * takes the DisplayObject (or a more flexible version of AES). * * @constructor * @param {DisplayObject} displayObject */ public function FragmentStream(displayObject : DisplayObject) : void { _displayObject = displayObject; }; /* * Return FragmentData of Fragment currently being downloaded. * Of immediate interest is the `bytes` field. * * @method getFragment * @return {Fragment} */ public function getFragment() : Fragment { return _fragment; } /* * Close the stream. * * @method close */ public function close() : void { if (_fragmentURLStream && _fragmentURLStream.connected) { _fragmentURLStream.close(); } if (_fragment) { if (_fragment.data.decryptAES) { _fragment.data.decryptAES.cancel(); _fragment.data.decryptAES = null; } // Explicitly release memory // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#clear() _fragment.data.bytes.clear(); _fragment.data.bytes = null; } } /** * Load a Fragment. * * This class/methods DOES NOT user reference of parameter. Instead it * clones the Fragment and manipulates this internally. * * @method load * @param {Fragment} fragment - Fragment with details (cloned) * @param {ByteArray} key - Encryption Key * @return {HLSLoadMetrics} */ public function load(fragment : Fragment, key : ByteArray) : HLSLoadMetrics { // Clone Fragment, with new initilizations of deep fields // Passing around references is what is causing problems. // FragmentData is initialized as part of construction _fragment = new Fragment( fragment.url, fragment.duration, fragment.level, fragment.seqnum, fragment.start_time, fragment.continuity, fragment.program_date, fragment.decrypt_url, fragment.decrypt_iv, // We need this reference fragment.byterange_start_offset, fragment.byterange_end_offset, new Vector.<String>() ) _fragmentURLStream = new URLStream(); // START (LOADING) METRICS // Event listener callbacks enclose _metrics var _metrics : HLSLoadMetrics = new HLSLoadMetrics(HLSLoaderTypes.FRAGMENT_MAIN); _metrics.level = _fragment.level; _metrics.id = _fragment.seqnum; _metrics.loading_request_time = getTimer(); // String used to identify fragment in debug messages CONFIG::LOGGING { var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]"; } // // See `onLoadProgress` first. // /* * Called when Fragment is processing which may inclue decryption. * * To access data, call `Fragment.getFragment`, which will include * all bytes loaded to this point, with FragmentData's ByteArray * having the expected position * * NOTE: This was `FragmentLoader._fragDecryptProgressHandler` before refactor. * * @method onProcess * @param {ByteArray} data - *Portion* of data that finished processing */ var onProcess : Function = function onProcess(data : ByteArray) : void { // Ensure byte array pointer starts at beginning data.position = 0; var bytes : ByteArray = _fragment.data.bytes; // Byte Range Business // TODO: Confirm this is still working if (_fragment.byterange_start_offset != -1) { _fragment.data.bytes.position = _fragment.data.bytes.length; _fragment.data.bytes.writeBytes(data); // if we have retrieved all the data, disconnect loader and notify fragment complete if (_fragment.data.bytes.length >= _fragment.byterange_end_offset) { if (_fragmentURLStream.connected) { _fragmentURLStream.close(); onProcessComplete(null); } } } else { // Append data to Fragment, but then reset position to mimic // expected pattern of URLStream var fragmentPosition : int = _fragment.data.bytes.position; _fragment.data.bytes.position = _fragment.data.bytes.length; _fragment.data.bytes.writeBytes(data); _fragment.data.bytes.position = fragmentPosition; } var progressEvent : ProgressEvent = new ProgressEvent( ProgressEvent.PROGRESS, false, false, _fragment.data.bytes.length, // bytesLoaded _fragment.data.bytesTotal // bytesTotal ); dispatchEvent(progressEvent); } /* * Called when Fragment has completed processing. * May or may not include decryption. * * NOTE: This was `FragmentLoader._fragDecryptCompleteHandler` * before refactor. * * @method onProcessComplete * @param {ByteArray} data - Portion of data finished processing */ var onProcessComplete : Function = function onProcessComplete() : void { // END DECRYPTION METRICS // garbage collect AES decrypter if (_fragment.data.decryptAES) { _metrics.decryption_end_time = getTimer(); var decrypt_duration : Number = _metrics.decryption_end_time - _metrics.decryption_begin_time; CONFIG::LOGGING { Log.debug("FragmentStream#onProcessComplete: Decrypted duration/length/speed:" + decrypt_duration + "/" + _fragment.data.bytesLoaded + "/" + Math.round((8000 * _fragment.data.bytesLoaded / decrypt_duration) / 1024) + " kb/s"); } _fragment.data.decryptAES = null; } var completeEvent : Event = new ProgressEvent(Event.COMPLETE); dispatchEvent(completeEvent); } /* * Called when URLStream has download a portion of the file fragment. * This event callback delegates to decrypter if necessary. * Eventually onProcess is called when the downloaded portion has * finished processing. * * NOTE: Was `_fragLoadCompleteHandler` before refactor * * @param {ProgressEvent} evt - Portion of data finished processing */ var onLoadProgress : Function = function onProgress(evt : ProgressEvent) : void { // First call of onProgress for this Fragment // Initilize fields in Fragment and FragmentData if (_fragment.data.bytes == null) { _fragment.data.bytes = new ByteArray(); _fragment.data.bytesLoaded = 0; _fragment.data.bytesTotal = evt.bytesTotal; _fragment.data.flushTags(); // NOTE: This may be wrong, as it is only called after data // has been loaded. _metrics.loading_begin_time = getTimer(); CONFIG::LOGGING { Log.debug("FragmentStream#onLoadProgress: Downloaded " + fragmentString + "'s first " + evt.bytesLoaded + " bytes of " + evt.bytesTotal + " Total"); } // decrypt data if needed if (_fragment.decrypt_url != null) { // START DECRYPTION METRICS _metrics.decryption_begin_time = getTimer(); CONFIG::LOGGING { Log.debug("FragmentStream#onLoadProgress: " + fragmentString + " needs to be decrypted"); } _fragment.data.decryptAES = new AES( _displayObject, key, _fragment.decrypt_iv, onProcess, onProcessComplete ); } else { _fragment.data.decryptAES = null; } } if (evt.bytesLoaded > _fragment.data.bytesLoaded && _fragmentURLStream.bytesAvailable > 0) { // prevent EOF error race condition // bytes from URLStream var data : ByteArray = new ByteArray(); _fragmentURLStream.readBytes(data); // Mark that bytes have been loaded, but do not store these // bytes yet _fragment.data.bytesLoaded += data.length; if (_fragment.data.decryptAES != null) { _fragment.data.decryptAES.append(data); } else { onProcess(data); } } } /* * Called when URLStream had completed downloading. * * @param {Event} evt - Portion of data finished processing */ var onLoadComplete : Function = function onLoadComplete(evt : Event) : void { // load complete, reset retry counter //_fragRetryCount = 0; //_fragRetryTimeout = 1000; if (_fragment.data.bytes == null) { CONFIG::LOGGING { Log.warn("FragmentStream#onLoadComplete: " + fragmentString + " size is null, invalidate it and load next one"); } //_levels[_hls.loadLevel].updateFragment(_fragCurrent.seqnum, false); //_loadingState = LOADING_IDLE; // TODO: Dispatch an error return; } CONFIG::LOGGING { Log.debug("FragmentStream#onLoadComplete: " + fragmentString + " has finished downloading, but may still be decrypting"); } // TODO: ??? //_fragSkipping = false; // END LOADING METRICS _metrics.loading_end_time = getTimer(); _metrics.size = _fragment.data.bytesLoaded; var _loading_duration : uint = _metrics.loading_end_time - _metrics.loading_request_time; CONFIG::LOGGING { Log.debug("FragmentStream#onLoadComplete: Loading duration/RTT/length/speed:" + _loading_duration + "/" + (_metrics.loading_begin_time - _metrics.loading_request_time) + "/" + _metrics.size + "/" + Math.round((8000 * _metrics.size / _loading_duration) / 1024) + " kb/s"); } if (_fragment.data.decryptAES) { _fragment.data.decryptAES.notifycomplete(); // Calls onProcessComplete by proxy } else { onProcessComplete(); } } /* * Called when URLStream has Errored. * @param {ErrorEvent} evt - Portion of data finished processing */ var onLoadError : Function = function onLoadError(evt : ErrorEvent) : void { CONFIG::LOGGING { Log.error("FragmentStream#onLoadError: " + evt.text); } // Forward error dispatchEvent(evt); } _fragmentURLStream.addEventListener(IOErrorEvent.IO_ERROR, onLoadError); _fragmentURLStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError); _fragmentURLStream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress); _fragmentURLStream.addEventListener(Event.COMPLETE, onLoadComplete); _fragmentURLStream.load(new URLRequest(fragment.url)); return _metrics; } } }
Add com.pivotshare.hls.loader.FragmentStream
[FragmentStream] Add com.pivotshare.hls.loader.FragmentStream
ActionScript
mpl-2.0
codex-corp/flashls,codex-corp/flashls
85e7fbaf9312b705d76d2d672a3843b57af56747
as3/com/netease/protobuf/ZigZag.as
as3/com/netease/protobuf/ZigZag.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved. // // [email protected] // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { public final class ZigZag { public static function encode32(n:int):int { return (n << 1) ^ (n >> 31) } public static function decode32(n:int):int { return (n >>> 1) ^ -(n & 1) } public static function encode64low(low:uint, high:int):uint { return (low << 1) ^ (high >> 31) } public static function encode64high(low:uint, high:int):int { return (low >>> 31) ^ (high << 1) ^ (high >> 31) } public static function decode64low(low:uint, high:int):uint { return (high << 31) ^ (low >>> 1) ^ -(low & 1) } public static function decode64high(low:uint, high:int):int { return (high >>> 1) ^ -(low & 1) } } }
添加遗漏的 ZigZag.as
添加遗漏的 ZigZag.as
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3